##// END OF EJS Templates
commit: pass 'editform' argument to 'cmdutil.getcommiteditor'...
FUJIWARA Katsunori -
r22010:41e969cb default
parent child Browse files
Show More
@@ -1,2635 +1,2636
1 1 # cmdutil.py - help for command processing in mercurial
2 2 #
3 3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 from node import hex, nullid, nullrev, short
9 9 from i18n import _
10 10 import os, sys, errno, re, tempfile
11 11 import util, scmutil, templater, patch, error, templatekw, revlog, copies
12 12 import match as matchmod
13 13 import context, repair, graphmod, revset, phases, obsolete, pathutil
14 14 import changelog
15 15 import bookmarks
16 16 import lock as lockmod
17 17
18 18 def parsealiases(cmd):
19 19 return cmd.lstrip("^").split("|")
20 20
21 21 def findpossible(cmd, table, strict=False):
22 22 """
23 23 Return cmd -> (aliases, command table entry)
24 24 for each matching command.
25 25 Return debug commands (or their aliases) only if no normal command matches.
26 26 """
27 27 choice = {}
28 28 debugchoice = {}
29 29
30 30 if cmd in table:
31 31 # short-circuit exact matches, "log" alias beats "^log|history"
32 32 keys = [cmd]
33 33 else:
34 34 keys = table.keys()
35 35
36 36 for e in keys:
37 37 aliases = parsealiases(e)
38 38 found = None
39 39 if cmd in aliases:
40 40 found = cmd
41 41 elif not strict:
42 42 for a in aliases:
43 43 if a.startswith(cmd):
44 44 found = a
45 45 break
46 46 if found is not None:
47 47 if aliases[0].startswith("debug") or found.startswith("debug"):
48 48 debugchoice[found] = (aliases, table[e])
49 49 else:
50 50 choice[found] = (aliases, table[e])
51 51
52 52 if not choice and debugchoice:
53 53 choice = debugchoice
54 54
55 55 return choice
56 56
57 57 def findcmd(cmd, table, strict=True):
58 58 """Return (aliases, command table entry) for command string."""
59 59 choice = findpossible(cmd, table, strict)
60 60
61 61 if cmd in choice:
62 62 return choice[cmd]
63 63
64 64 if len(choice) > 1:
65 65 clist = choice.keys()
66 66 clist.sort()
67 67 raise error.AmbiguousCommand(cmd, clist)
68 68
69 69 if choice:
70 70 return choice.values()[0]
71 71
72 72 raise error.UnknownCommand(cmd)
73 73
74 74 def findrepo(p):
75 75 while not os.path.isdir(os.path.join(p, ".hg")):
76 76 oldp, p = p, os.path.dirname(p)
77 77 if p == oldp:
78 78 return None
79 79
80 80 return p
81 81
82 82 def bailifchanged(repo):
83 83 if repo.dirstate.p2() != nullid:
84 84 raise util.Abort(_('outstanding uncommitted merge'))
85 85 modified, added, removed, deleted = repo.status()[:4]
86 86 if modified or added or removed or deleted:
87 87 raise util.Abort(_('uncommitted changes'))
88 88 ctx = repo[None]
89 89 for s in sorted(ctx.substate):
90 90 if ctx.sub(s).dirty():
91 91 raise util.Abort(_("uncommitted changes in subrepo %s") % s)
92 92
93 93 def logmessage(ui, opts):
94 94 """ get the log message according to -m and -l option """
95 95 message = opts.get('message')
96 96 logfile = opts.get('logfile')
97 97
98 98 if message and logfile:
99 99 raise util.Abort(_('options --message and --logfile are mutually '
100 100 'exclusive'))
101 101 if not message and logfile:
102 102 try:
103 103 if logfile == '-':
104 104 message = ui.fin.read()
105 105 else:
106 106 message = '\n'.join(util.readfile(logfile).splitlines())
107 107 except IOError, inst:
108 108 raise util.Abort(_("can't read commit message '%s': %s") %
109 109 (logfile, inst.strerror))
110 110 return message
111 111
112 112 def getcommiteditor(edit=False, finishdesc=None, extramsg=None,
113 113 editform='', **opts):
114 114 """get appropriate commit message editor according to '--edit' option
115 115
116 116 'finishdesc' is a function to be called with edited commit message
117 117 (= 'description' of the new changeset) just after editing, but
118 118 before checking empty-ness. It should return actual text to be
119 119 stored into history. This allows to change description before
120 120 storing.
121 121
122 122 'extramsg' is a extra message to be shown in the editor instead of
123 123 'Leave message empty to abort commit' line. 'HG: ' prefix and EOL
124 124 is automatically added.
125 125
126 126 'editform' is a dot-separated list of names, to distinguish
127 127 the purpose of commit text editing.
128 128
129 129 'getcommiteditor' returns 'commitforceeditor' regardless of
130 130 'edit', if one of 'finishdesc' or 'extramsg' is specified, because
131 131 they are specific for usage in MQ.
132 132 """
133 133 if edit or finishdesc or extramsg:
134 134 return lambda r, c, s: commitforceeditor(r, c, s,
135 135 finishdesc=finishdesc,
136 136 extramsg=extramsg,
137 137 editform=editform)
138 138 elif editform:
139 139 return lambda r, c, s: commiteditor(r, c, s, editform=editform)
140 140 else:
141 141 return commiteditor
142 142
143 143 def loglimit(opts):
144 144 """get the log limit according to option -l/--limit"""
145 145 limit = opts.get('limit')
146 146 if limit:
147 147 try:
148 148 limit = int(limit)
149 149 except ValueError:
150 150 raise util.Abort(_('limit must be a positive integer'))
151 151 if limit <= 0:
152 152 raise util.Abort(_('limit must be positive'))
153 153 else:
154 154 limit = None
155 155 return limit
156 156
157 157 def makefilename(repo, pat, node, desc=None,
158 158 total=None, seqno=None, revwidth=None, pathname=None):
159 159 node_expander = {
160 160 'H': lambda: hex(node),
161 161 'R': lambda: str(repo.changelog.rev(node)),
162 162 'h': lambda: short(node),
163 163 'm': lambda: re.sub('[^\w]', '_', str(desc))
164 164 }
165 165 expander = {
166 166 '%': lambda: '%',
167 167 'b': lambda: os.path.basename(repo.root),
168 168 }
169 169
170 170 try:
171 171 if node:
172 172 expander.update(node_expander)
173 173 if node:
174 174 expander['r'] = (lambda:
175 175 str(repo.changelog.rev(node)).zfill(revwidth or 0))
176 176 if total is not None:
177 177 expander['N'] = lambda: str(total)
178 178 if seqno is not None:
179 179 expander['n'] = lambda: str(seqno)
180 180 if total is not None and seqno is not None:
181 181 expander['n'] = lambda: str(seqno).zfill(len(str(total)))
182 182 if pathname is not None:
183 183 expander['s'] = lambda: os.path.basename(pathname)
184 184 expander['d'] = lambda: os.path.dirname(pathname) or '.'
185 185 expander['p'] = lambda: pathname
186 186
187 187 newname = []
188 188 patlen = len(pat)
189 189 i = 0
190 190 while i < patlen:
191 191 c = pat[i]
192 192 if c == '%':
193 193 i += 1
194 194 c = pat[i]
195 195 c = expander[c]()
196 196 newname.append(c)
197 197 i += 1
198 198 return ''.join(newname)
199 199 except KeyError, inst:
200 200 raise util.Abort(_("invalid format spec '%%%s' in output filename") %
201 201 inst.args[0])
202 202
203 203 def makefileobj(repo, pat, node=None, desc=None, total=None,
204 204 seqno=None, revwidth=None, mode='wb', modemap=None,
205 205 pathname=None):
206 206
207 207 writable = mode not in ('r', 'rb')
208 208
209 209 if not pat or pat == '-':
210 210 fp = writable and repo.ui.fout or repo.ui.fin
211 211 if util.safehasattr(fp, 'fileno'):
212 212 return os.fdopen(os.dup(fp.fileno()), mode)
213 213 else:
214 214 # if this fp can't be duped properly, return
215 215 # a dummy object that can be closed
216 216 class wrappedfileobj(object):
217 217 noop = lambda x: None
218 218 def __init__(self, f):
219 219 self.f = f
220 220 def __getattr__(self, attr):
221 221 if attr == 'close':
222 222 return self.noop
223 223 else:
224 224 return getattr(self.f, attr)
225 225
226 226 return wrappedfileobj(fp)
227 227 if util.safehasattr(pat, 'write') and writable:
228 228 return pat
229 229 if util.safehasattr(pat, 'read') and 'r' in mode:
230 230 return pat
231 231 fn = makefilename(repo, pat, node, desc, total, seqno, revwidth, pathname)
232 232 if modemap is not None:
233 233 mode = modemap.get(fn, mode)
234 234 if mode == 'wb':
235 235 modemap[fn] = 'ab'
236 236 return open(fn, mode)
237 237
238 238 def openrevlog(repo, cmd, file_, opts):
239 239 """opens the changelog, manifest, a filelog or a given revlog"""
240 240 cl = opts['changelog']
241 241 mf = opts['manifest']
242 242 msg = None
243 243 if cl and mf:
244 244 msg = _('cannot specify --changelog and --manifest at the same time')
245 245 elif cl or mf:
246 246 if file_:
247 247 msg = _('cannot specify filename with --changelog or --manifest')
248 248 elif not repo:
249 249 msg = _('cannot specify --changelog or --manifest '
250 250 'without a repository')
251 251 if msg:
252 252 raise util.Abort(msg)
253 253
254 254 r = None
255 255 if repo:
256 256 if cl:
257 257 r = repo.unfiltered().changelog
258 258 elif mf:
259 259 r = repo.manifest
260 260 elif file_:
261 261 filelog = repo.file(file_)
262 262 if len(filelog):
263 263 r = filelog
264 264 if not r:
265 265 if not file_:
266 266 raise error.CommandError(cmd, _('invalid arguments'))
267 267 if not os.path.isfile(file_):
268 268 raise util.Abort(_("revlog '%s' not found") % file_)
269 269 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False),
270 270 file_[:-2] + ".i")
271 271 return r
272 272
273 273 def copy(ui, repo, pats, opts, rename=False):
274 274 # called with the repo lock held
275 275 #
276 276 # hgsep => pathname that uses "/" to separate directories
277 277 # ossep => pathname that uses os.sep to separate directories
278 278 cwd = repo.getcwd()
279 279 targets = {}
280 280 after = opts.get("after")
281 281 dryrun = opts.get("dry_run")
282 282 wctx = repo[None]
283 283
284 284 def walkpat(pat):
285 285 srcs = []
286 286 badstates = after and '?' or '?r'
287 287 m = scmutil.match(repo[None], [pat], opts, globbed=True)
288 288 for abs in repo.walk(m):
289 289 state = repo.dirstate[abs]
290 290 rel = m.rel(abs)
291 291 exact = m.exact(abs)
292 292 if state in badstates:
293 293 if exact and state == '?':
294 294 ui.warn(_('%s: not copying - file is not managed\n') % rel)
295 295 if exact and state == 'r':
296 296 ui.warn(_('%s: not copying - file has been marked for'
297 297 ' remove\n') % rel)
298 298 continue
299 299 # abs: hgsep
300 300 # rel: ossep
301 301 srcs.append((abs, rel, exact))
302 302 return srcs
303 303
304 304 # abssrc: hgsep
305 305 # relsrc: ossep
306 306 # otarget: ossep
307 307 def copyfile(abssrc, relsrc, otarget, exact):
308 308 abstarget = pathutil.canonpath(repo.root, cwd, otarget)
309 309 if '/' in abstarget:
310 310 # We cannot normalize abstarget itself, this would prevent
311 311 # case only renames, like a => A.
312 312 abspath, absname = abstarget.rsplit('/', 1)
313 313 abstarget = repo.dirstate.normalize(abspath) + '/' + absname
314 314 reltarget = repo.pathto(abstarget, cwd)
315 315 target = repo.wjoin(abstarget)
316 316 src = repo.wjoin(abssrc)
317 317 state = repo.dirstate[abstarget]
318 318
319 319 scmutil.checkportable(ui, abstarget)
320 320
321 321 # check for collisions
322 322 prevsrc = targets.get(abstarget)
323 323 if prevsrc is not None:
324 324 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
325 325 (reltarget, repo.pathto(abssrc, cwd),
326 326 repo.pathto(prevsrc, cwd)))
327 327 return
328 328
329 329 # check for overwrites
330 330 exists = os.path.lexists(target)
331 331 samefile = False
332 332 if exists and abssrc != abstarget:
333 333 if (repo.dirstate.normalize(abssrc) ==
334 334 repo.dirstate.normalize(abstarget)):
335 335 if not rename:
336 336 ui.warn(_("%s: can't copy - same file\n") % reltarget)
337 337 return
338 338 exists = False
339 339 samefile = True
340 340
341 341 if not after and exists or after and state in 'mn':
342 342 if not opts['force']:
343 343 ui.warn(_('%s: not overwriting - file exists\n') %
344 344 reltarget)
345 345 return
346 346
347 347 if after:
348 348 if not exists:
349 349 if rename:
350 350 ui.warn(_('%s: not recording move - %s does not exist\n') %
351 351 (relsrc, reltarget))
352 352 else:
353 353 ui.warn(_('%s: not recording copy - %s does not exist\n') %
354 354 (relsrc, reltarget))
355 355 return
356 356 elif not dryrun:
357 357 try:
358 358 if exists:
359 359 os.unlink(target)
360 360 targetdir = os.path.dirname(target) or '.'
361 361 if not os.path.isdir(targetdir):
362 362 os.makedirs(targetdir)
363 363 if samefile:
364 364 tmp = target + "~hgrename"
365 365 os.rename(src, tmp)
366 366 os.rename(tmp, target)
367 367 else:
368 368 util.copyfile(src, target)
369 369 srcexists = True
370 370 except IOError, inst:
371 371 if inst.errno == errno.ENOENT:
372 372 ui.warn(_('%s: deleted in working copy\n') % relsrc)
373 373 srcexists = False
374 374 else:
375 375 ui.warn(_('%s: cannot copy - %s\n') %
376 376 (relsrc, inst.strerror))
377 377 return True # report a failure
378 378
379 379 if ui.verbose or not exact:
380 380 if rename:
381 381 ui.status(_('moving %s to %s\n') % (relsrc, reltarget))
382 382 else:
383 383 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
384 384
385 385 targets[abstarget] = abssrc
386 386
387 387 # fix up dirstate
388 388 scmutil.dirstatecopy(ui, repo, wctx, abssrc, abstarget,
389 389 dryrun=dryrun, cwd=cwd)
390 390 if rename and not dryrun:
391 391 if not after and srcexists and not samefile:
392 392 util.unlinkpath(repo.wjoin(abssrc))
393 393 wctx.forget([abssrc])
394 394
395 395 # pat: ossep
396 396 # dest ossep
397 397 # srcs: list of (hgsep, hgsep, ossep, bool)
398 398 # return: function that takes hgsep and returns ossep
399 399 def targetpathfn(pat, dest, srcs):
400 400 if os.path.isdir(pat):
401 401 abspfx = pathutil.canonpath(repo.root, cwd, pat)
402 402 abspfx = util.localpath(abspfx)
403 403 if destdirexists:
404 404 striplen = len(os.path.split(abspfx)[0])
405 405 else:
406 406 striplen = len(abspfx)
407 407 if striplen:
408 408 striplen += len(os.sep)
409 409 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
410 410 elif destdirexists:
411 411 res = lambda p: os.path.join(dest,
412 412 os.path.basename(util.localpath(p)))
413 413 else:
414 414 res = lambda p: dest
415 415 return res
416 416
417 417 # pat: ossep
418 418 # dest ossep
419 419 # srcs: list of (hgsep, hgsep, ossep, bool)
420 420 # return: function that takes hgsep and returns ossep
421 421 def targetpathafterfn(pat, dest, srcs):
422 422 if matchmod.patkind(pat):
423 423 # a mercurial pattern
424 424 res = lambda p: os.path.join(dest,
425 425 os.path.basename(util.localpath(p)))
426 426 else:
427 427 abspfx = pathutil.canonpath(repo.root, cwd, pat)
428 428 if len(abspfx) < len(srcs[0][0]):
429 429 # A directory. Either the target path contains the last
430 430 # component of the source path or it does not.
431 431 def evalpath(striplen):
432 432 score = 0
433 433 for s in srcs:
434 434 t = os.path.join(dest, util.localpath(s[0])[striplen:])
435 435 if os.path.lexists(t):
436 436 score += 1
437 437 return score
438 438
439 439 abspfx = util.localpath(abspfx)
440 440 striplen = len(abspfx)
441 441 if striplen:
442 442 striplen += len(os.sep)
443 443 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
444 444 score = evalpath(striplen)
445 445 striplen1 = len(os.path.split(abspfx)[0])
446 446 if striplen1:
447 447 striplen1 += len(os.sep)
448 448 if evalpath(striplen1) > score:
449 449 striplen = striplen1
450 450 res = lambda p: os.path.join(dest,
451 451 util.localpath(p)[striplen:])
452 452 else:
453 453 # a file
454 454 if destdirexists:
455 455 res = lambda p: os.path.join(dest,
456 456 os.path.basename(util.localpath(p)))
457 457 else:
458 458 res = lambda p: dest
459 459 return res
460 460
461 461
462 462 pats = scmutil.expandpats(pats)
463 463 if not pats:
464 464 raise util.Abort(_('no source or destination specified'))
465 465 if len(pats) == 1:
466 466 raise util.Abort(_('no destination specified'))
467 467 dest = pats.pop()
468 468 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
469 469 if not destdirexists:
470 470 if len(pats) > 1 or matchmod.patkind(pats[0]):
471 471 raise util.Abort(_('with multiple sources, destination must be an '
472 472 'existing directory'))
473 473 if util.endswithsep(dest):
474 474 raise util.Abort(_('destination %s is not a directory') % dest)
475 475
476 476 tfn = targetpathfn
477 477 if after:
478 478 tfn = targetpathafterfn
479 479 copylist = []
480 480 for pat in pats:
481 481 srcs = walkpat(pat)
482 482 if not srcs:
483 483 continue
484 484 copylist.append((tfn(pat, dest, srcs), srcs))
485 485 if not copylist:
486 486 raise util.Abort(_('no files to copy'))
487 487
488 488 errors = 0
489 489 for targetpath, srcs in copylist:
490 490 for abssrc, relsrc, exact in srcs:
491 491 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
492 492 errors += 1
493 493
494 494 if errors:
495 495 ui.warn(_('(consider using --after)\n'))
496 496
497 497 return errors != 0
498 498
499 499 def service(opts, parentfn=None, initfn=None, runfn=None, logfile=None,
500 500 runargs=None, appendpid=False):
501 501 '''Run a command as a service.'''
502 502
503 503 def writepid(pid):
504 504 if opts['pid_file']:
505 505 mode = appendpid and 'a' or 'w'
506 506 fp = open(opts['pid_file'], mode)
507 507 fp.write(str(pid) + '\n')
508 508 fp.close()
509 509
510 510 if opts['daemon'] and not opts['daemon_pipefds']:
511 511 # Signal child process startup with file removal
512 512 lockfd, lockpath = tempfile.mkstemp(prefix='hg-service-')
513 513 os.close(lockfd)
514 514 try:
515 515 if not runargs:
516 516 runargs = util.hgcmd() + sys.argv[1:]
517 517 runargs.append('--daemon-pipefds=%s' % lockpath)
518 518 # Don't pass --cwd to the child process, because we've already
519 519 # changed directory.
520 520 for i in xrange(1, len(runargs)):
521 521 if runargs[i].startswith('--cwd='):
522 522 del runargs[i]
523 523 break
524 524 elif runargs[i].startswith('--cwd'):
525 525 del runargs[i:i + 2]
526 526 break
527 527 def condfn():
528 528 return not os.path.exists(lockpath)
529 529 pid = util.rundetached(runargs, condfn)
530 530 if pid < 0:
531 531 raise util.Abort(_('child process failed to start'))
532 532 writepid(pid)
533 533 finally:
534 534 try:
535 535 os.unlink(lockpath)
536 536 except OSError, e:
537 537 if e.errno != errno.ENOENT:
538 538 raise
539 539 if parentfn:
540 540 return parentfn(pid)
541 541 else:
542 542 return
543 543
544 544 if initfn:
545 545 initfn()
546 546
547 547 if not opts['daemon']:
548 548 writepid(os.getpid())
549 549
550 550 if opts['daemon_pipefds']:
551 551 lockpath = opts['daemon_pipefds']
552 552 try:
553 553 os.setsid()
554 554 except AttributeError:
555 555 pass
556 556 os.unlink(lockpath)
557 557 util.hidewindow()
558 558 sys.stdout.flush()
559 559 sys.stderr.flush()
560 560
561 561 nullfd = os.open(os.devnull, os.O_RDWR)
562 562 logfilefd = nullfd
563 563 if logfile:
564 564 logfilefd = os.open(logfile, os.O_RDWR | os.O_CREAT | os.O_APPEND)
565 565 os.dup2(nullfd, 0)
566 566 os.dup2(logfilefd, 1)
567 567 os.dup2(logfilefd, 2)
568 568 if nullfd not in (0, 1, 2):
569 569 os.close(nullfd)
570 570 if logfile and logfilefd not in (0, 1, 2):
571 571 os.close(logfilefd)
572 572
573 573 if runfn:
574 574 return runfn()
575 575
576 576 def tryimportone(ui, repo, hunk, parents, opts, msgs, updatefunc):
577 577 """Utility function used by commands.import to import a single patch
578 578
579 579 This function is explicitly defined here to help the evolve extension to
580 580 wrap this part of the import logic.
581 581
582 582 The API is currently a bit ugly because it a simple code translation from
583 583 the import command. Feel free to make it better.
584 584
585 585 :hunk: a patch (as a binary string)
586 586 :parents: nodes that will be parent of the created commit
587 587 :opts: the full dict of option passed to the import command
588 588 :msgs: list to save commit message to.
589 589 (used in case we need to save it when failing)
590 590 :updatefunc: a function that update a repo to a given node
591 591 updatefunc(<repo>, <node>)
592 592 """
593 593 tmpname, message, user, date, branch, nodeid, p1, p2 = \
594 594 patch.extract(ui, hunk)
595 595
596 596 editor = getcommiteditor(**opts)
597 597 update = not opts.get('bypass')
598 598 strip = opts["strip"]
599 599 sim = float(opts.get('similarity') or 0)
600 600 if not tmpname:
601 601 return (None, None, False)
602 602 msg = _('applied to working directory')
603 603
604 604 rejects = False
605 605
606 606 try:
607 607 cmdline_message = logmessage(ui, opts)
608 608 if cmdline_message:
609 609 # pickup the cmdline msg
610 610 message = cmdline_message
611 611 elif message:
612 612 # pickup the patch msg
613 613 message = message.strip()
614 614 else:
615 615 # launch the editor
616 616 message = None
617 617 ui.debug('message:\n%s\n' % message)
618 618
619 619 if len(parents) == 1:
620 620 parents.append(repo[nullid])
621 621 if opts.get('exact'):
622 622 if not nodeid or not p1:
623 623 raise util.Abort(_('not a Mercurial patch'))
624 624 p1 = repo[p1]
625 625 p2 = repo[p2 or nullid]
626 626 elif p2:
627 627 try:
628 628 p1 = repo[p1]
629 629 p2 = repo[p2]
630 630 # Without any options, consider p2 only if the
631 631 # patch is being applied on top of the recorded
632 632 # first parent.
633 633 if p1 != parents[0]:
634 634 p1 = parents[0]
635 635 p2 = repo[nullid]
636 636 except error.RepoError:
637 637 p1, p2 = parents
638 638 else:
639 639 p1, p2 = parents
640 640
641 641 n = None
642 642 if update:
643 643 if p1 != parents[0]:
644 644 updatefunc(repo, p1.node())
645 645 if p2 != parents[1]:
646 646 repo.setparents(p1.node(), p2.node())
647 647
648 648 if opts.get('exact') or opts.get('import_branch'):
649 649 repo.dirstate.setbranch(branch or 'default')
650 650
651 651 partial = opts.get('partial', False)
652 652 files = set()
653 653 try:
654 654 patch.patch(ui, repo, tmpname, strip=strip, files=files,
655 655 eolmode=None, similarity=sim / 100.0)
656 656 except patch.PatchError, e:
657 657 if not partial:
658 658 raise util.Abort(str(e))
659 659 if partial:
660 660 rejects = True
661 661
662 662 files = list(files)
663 663 if opts.get('no_commit'):
664 664 if message:
665 665 msgs.append(message)
666 666 else:
667 667 if opts.get('exact') or p2:
668 668 # If you got here, you either use --force and know what
669 669 # you are doing or used --exact or a merge patch while
670 670 # being updated to its first parent.
671 671 m = None
672 672 else:
673 673 m = scmutil.matchfiles(repo, files or [])
674 674 n = repo.commit(message, opts.get('user') or user,
675 675 opts.get('date') or date, match=m,
676 676 editor=editor, force=partial)
677 677 else:
678 678 if opts.get('exact') or opts.get('import_branch'):
679 679 branch = branch or 'default'
680 680 else:
681 681 branch = p1.branch()
682 682 store = patch.filestore()
683 683 try:
684 684 files = set()
685 685 try:
686 686 patch.patchrepo(ui, repo, p1, store, tmpname, strip,
687 687 files, eolmode=None)
688 688 except patch.PatchError, e:
689 689 raise util.Abort(str(e))
690 690 memctx = context.makememctx(repo, (p1.node(), p2.node()),
691 691 message,
692 692 opts.get('user') or user,
693 693 opts.get('date') or date,
694 694 branch, files, store,
695 695 editor=getcommiteditor())
696 696 n = memctx.commit()
697 697 finally:
698 698 store.close()
699 699 if opts.get('exact') and hex(n) != nodeid:
700 700 raise util.Abort(_('patch is damaged or loses information'))
701 701 if n:
702 702 # i18n: refers to a short changeset id
703 703 msg = _('created %s') % short(n)
704 704 return (msg, n, rejects)
705 705 finally:
706 706 os.unlink(tmpname)
707 707
708 708 def export(repo, revs, template='hg-%h.patch', fp=None, switch_parent=False,
709 709 opts=None):
710 710 '''export changesets as hg patches.'''
711 711
712 712 total = len(revs)
713 713 revwidth = max([len(str(rev)) for rev in revs])
714 714 filemode = {}
715 715
716 716 def single(rev, seqno, fp):
717 717 ctx = repo[rev]
718 718 node = ctx.node()
719 719 parents = [p.node() for p in ctx.parents() if p]
720 720 branch = ctx.branch()
721 721 if switch_parent:
722 722 parents.reverse()
723 723 prev = (parents and parents[0]) or nullid
724 724
725 725 shouldclose = False
726 726 if not fp and len(template) > 0:
727 727 desc_lines = ctx.description().rstrip().split('\n')
728 728 desc = desc_lines[0] #Commit always has a first line.
729 729 fp = makefileobj(repo, template, node, desc=desc, total=total,
730 730 seqno=seqno, revwidth=revwidth, mode='wb',
731 731 modemap=filemode)
732 732 if fp != template:
733 733 shouldclose = True
734 734 if fp and fp != sys.stdout and util.safehasattr(fp, 'name'):
735 735 repo.ui.note("%s\n" % fp.name)
736 736
737 737 if not fp:
738 738 write = repo.ui.write
739 739 else:
740 740 def write(s, **kw):
741 741 fp.write(s)
742 742
743 743
744 744 write("# HG changeset patch\n")
745 745 write("# User %s\n" % ctx.user())
746 746 write("# Date %d %d\n" % ctx.date())
747 747 write("# %s\n" % util.datestr(ctx.date()))
748 748 if branch and branch != 'default':
749 749 write("# Branch %s\n" % branch)
750 750 write("# Node ID %s\n" % hex(node))
751 751 write("# Parent %s\n" % hex(prev))
752 752 if len(parents) > 1:
753 753 write("# Parent %s\n" % hex(parents[1]))
754 754 write(ctx.description().rstrip())
755 755 write("\n\n")
756 756
757 757 for chunk, label in patch.diffui(repo, prev, node, opts=opts):
758 758 write(chunk, label=label)
759 759
760 760 if shouldclose:
761 761 fp.close()
762 762
763 763 for seqno, rev in enumerate(revs):
764 764 single(rev, seqno + 1, fp)
765 765
766 766 def diffordiffstat(ui, repo, diffopts, node1, node2, match,
767 767 changes=None, stat=False, fp=None, prefix='',
768 768 listsubrepos=False):
769 769 '''show diff or diffstat.'''
770 770 if fp is None:
771 771 write = ui.write
772 772 else:
773 773 def write(s, **kw):
774 774 fp.write(s)
775 775
776 776 if stat:
777 777 diffopts = diffopts.copy(context=0)
778 778 width = 80
779 779 if not ui.plain():
780 780 width = ui.termwidth()
781 781 chunks = patch.diff(repo, node1, node2, match, changes, diffopts,
782 782 prefix=prefix)
783 783 for chunk, label in patch.diffstatui(util.iterlines(chunks),
784 784 width=width,
785 785 git=diffopts.git):
786 786 write(chunk, label=label)
787 787 else:
788 788 for chunk, label in patch.diffui(repo, node1, node2, match,
789 789 changes, diffopts, prefix=prefix):
790 790 write(chunk, label=label)
791 791
792 792 if listsubrepos:
793 793 ctx1 = repo[node1]
794 794 ctx2 = repo[node2]
795 795 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
796 796 tempnode2 = node2
797 797 try:
798 798 if node2 is not None:
799 799 tempnode2 = ctx2.substate[subpath][1]
800 800 except KeyError:
801 801 # A subrepo that existed in node1 was deleted between node1 and
802 802 # node2 (inclusive). Thus, ctx2's substate won't contain that
803 803 # subpath. The best we can do is to ignore it.
804 804 tempnode2 = None
805 805 submatch = matchmod.narrowmatcher(subpath, match)
806 806 sub.diff(ui, diffopts, tempnode2, submatch, changes=changes,
807 807 stat=stat, fp=fp, prefix=prefix)
808 808
809 809 class changeset_printer(object):
810 810 '''show changeset information when templating not requested.'''
811 811
812 812 def __init__(self, ui, repo, patch, diffopts, buffered):
813 813 self.ui = ui
814 814 self.repo = repo
815 815 self.buffered = buffered
816 816 self.patch = patch
817 817 self.diffopts = diffopts
818 818 self.header = {}
819 819 self.hunk = {}
820 820 self.lastheader = None
821 821 self.footer = None
822 822
823 823 def flush(self, rev):
824 824 if rev in self.header:
825 825 h = self.header[rev]
826 826 if h != self.lastheader:
827 827 self.lastheader = h
828 828 self.ui.write(h)
829 829 del self.header[rev]
830 830 if rev in self.hunk:
831 831 self.ui.write(self.hunk[rev])
832 832 del self.hunk[rev]
833 833 return 1
834 834 return 0
835 835
836 836 def close(self):
837 837 if self.footer:
838 838 self.ui.write(self.footer)
839 839
840 840 def show(self, ctx, copies=None, matchfn=None, **props):
841 841 if self.buffered:
842 842 self.ui.pushbuffer()
843 843 self._show(ctx, copies, matchfn, props)
844 844 self.hunk[ctx.rev()] = self.ui.popbuffer(labeled=True)
845 845 else:
846 846 self._show(ctx, copies, matchfn, props)
847 847
848 848 def _show(self, ctx, copies, matchfn, props):
849 849 '''show a single changeset or file revision'''
850 850 changenode = ctx.node()
851 851 rev = ctx.rev()
852 852
853 853 if self.ui.quiet:
854 854 self.ui.write("%d:%s\n" % (rev, short(changenode)),
855 855 label='log.node')
856 856 return
857 857
858 858 log = self.repo.changelog
859 859 date = util.datestr(ctx.date())
860 860
861 861 hexfunc = self.ui.debugflag and hex or short
862 862
863 863 parents = [(p, hexfunc(log.node(p)))
864 864 for p in self._meaningful_parentrevs(log, rev)]
865 865
866 866 # i18n: column positioning for "hg log"
867 867 self.ui.write(_("changeset: %d:%s\n") % (rev, hexfunc(changenode)),
868 868 label='log.changeset changeset.%s' % ctx.phasestr())
869 869
870 870 branch = ctx.branch()
871 871 # don't show the default branch name
872 872 if branch != 'default':
873 873 # i18n: column positioning for "hg log"
874 874 self.ui.write(_("branch: %s\n") % branch,
875 875 label='log.branch')
876 876 for bookmark in self.repo.nodebookmarks(changenode):
877 877 # i18n: column positioning for "hg log"
878 878 self.ui.write(_("bookmark: %s\n") % bookmark,
879 879 label='log.bookmark')
880 880 for tag in self.repo.nodetags(changenode):
881 881 # i18n: column positioning for "hg log"
882 882 self.ui.write(_("tag: %s\n") % tag,
883 883 label='log.tag')
884 884 if self.ui.debugflag and ctx.phase():
885 885 # i18n: column positioning for "hg log"
886 886 self.ui.write(_("phase: %s\n") % _(ctx.phasestr()),
887 887 label='log.phase')
888 888 for parent in parents:
889 889 # i18n: column positioning for "hg log"
890 890 self.ui.write(_("parent: %d:%s\n") % parent,
891 891 label='log.parent changeset.%s' % ctx.phasestr())
892 892
893 893 if self.ui.debugflag:
894 894 mnode = ctx.manifestnode()
895 895 # i18n: column positioning for "hg log"
896 896 self.ui.write(_("manifest: %d:%s\n") %
897 897 (self.repo.manifest.rev(mnode), hex(mnode)),
898 898 label='ui.debug log.manifest')
899 899 # i18n: column positioning for "hg log"
900 900 self.ui.write(_("user: %s\n") % ctx.user(),
901 901 label='log.user')
902 902 # i18n: column positioning for "hg log"
903 903 self.ui.write(_("date: %s\n") % date,
904 904 label='log.date')
905 905
906 906 if self.ui.debugflag:
907 907 files = self.repo.status(log.parents(changenode)[0], changenode)[:3]
908 908 for key, value in zip([# i18n: column positioning for "hg log"
909 909 _("files:"),
910 910 # i18n: column positioning for "hg log"
911 911 _("files+:"),
912 912 # i18n: column positioning for "hg log"
913 913 _("files-:")], files):
914 914 if value:
915 915 self.ui.write("%-12s %s\n" % (key, " ".join(value)),
916 916 label='ui.debug log.files')
917 917 elif ctx.files() and self.ui.verbose:
918 918 # i18n: column positioning for "hg log"
919 919 self.ui.write(_("files: %s\n") % " ".join(ctx.files()),
920 920 label='ui.note log.files')
921 921 if copies and self.ui.verbose:
922 922 copies = ['%s (%s)' % c for c in copies]
923 923 # i18n: column positioning for "hg log"
924 924 self.ui.write(_("copies: %s\n") % ' '.join(copies),
925 925 label='ui.note log.copies')
926 926
927 927 extra = ctx.extra()
928 928 if extra and self.ui.debugflag:
929 929 for key, value in sorted(extra.items()):
930 930 # i18n: column positioning for "hg log"
931 931 self.ui.write(_("extra: %s=%s\n")
932 932 % (key, value.encode('string_escape')),
933 933 label='ui.debug log.extra')
934 934
935 935 description = ctx.description().strip()
936 936 if description:
937 937 if self.ui.verbose:
938 938 self.ui.write(_("description:\n"),
939 939 label='ui.note log.description')
940 940 self.ui.write(description,
941 941 label='ui.note log.description')
942 942 self.ui.write("\n\n")
943 943 else:
944 944 # i18n: column positioning for "hg log"
945 945 self.ui.write(_("summary: %s\n") %
946 946 description.splitlines()[0],
947 947 label='log.summary')
948 948 self.ui.write("\n")
949 949
950 950 self.showpatch(changenode, matchfn)
951 951
952 952 def showpatch(self, node, matchfn):
953 953 if not matchfn:
954 954 matchfn = self.patch
955 955 if matchfn:
956 956 stat = self.diffopts.get('stat')
957 957 diff = self.diffopts.get('patch')
958 958 diffopts = patch.diffopts(self.ui, self.diffopts)
959 959 prev = self.repo.changelog.parents(node)[0]
960 960 if stat:
961 961 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
962 962 match=matchfn, stat=True)
963 963 if diff:
964 964 if stat:
965 965 self.ui.write("\n")
966 966 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
967 967 match=matchfn, stat=False)
968 968 self.ui.write("\n")
969 969
970 970 def _meaningful_parentrevs(self, log, rev):
971 971 """Return list of meaningful (or all if debug) parentrevs for rev.
972 972
973 973 For merges (two non-nullrev revisions) both parents are meaningful.
974 974 Otherwise the first parent revision is considered meaningful if it
975 975 is not the preceding revision.
976 976 """
977 977 parents = log.parentrevs(rev)
978 978 if not self.ui.debugflag and parents[1] == nullrev:
979 979 if parents[0] >= rev - 1:
980 980 parents = []
981 981 else:
982 982 parents = [parents[0]]
983 983 return parents
984 984
985 985
986 986 class changeset_templater(changeset_printer):
987 987 '''format changeset information.'''
988 988
989 989 def __init__(self, ui, repo, patch, diffopts, tmpl, mapfile, buffered):
990 990 changeset_printer.__init__(self, ui, repo, patch, diffopts, buffered)
991 991 formatnode = ui.debugflag and (lambda x: x) or (lambda x: x[:12])
992 992 defaulttempl = {
993 993 'parent': '{rev}:{node|formatnode} ',
994 994 'manifest': '{rev}:{node|formatnode}',
995 995 'file_copy': '{name} ({source})',
996 996 'extra': '{key}={value|stringescape}'
997 997 }
998 998 # filecopy is preserved for compatibility reasons
999 999 defaulttempl['filecopy'] = defaulttempl['file_copy']
1000 1000 self.t = templater.templater(mapfile, {'formatnode': formatnode},
1001 1001 cache=defaulttempl)
1002 1002 if tmpl:
1003 1003 self.t.cache['changeset'] = tmpl
1004 1004
1005 1005 self.cache = {}
1006 1006
1007 1007 def _meaningful_parentrevs(self, ctx):
1008 1008 """Return list of meaningful (or all if debug) parentrevs for rev.
1009 1009 """
1010 1010 parents = ctx.parents()
1011 1011 if len(parents) > 1:
1012 1012 return parents
1013 1013 if self.ui.debugflag:
1014 1014 return [parents[0], self.repo['null']]
1015 1015 if parents[0].rev() >= ctx.rev() - 1:
1016 1016 return []
1017 1017 return parents
1018 1018
1019 1019 def _show(self, ctx, copies, matchfn, props):
1020 1020 '''show a single changeset or file revision'''
1021 1021
1022 1022 showlist = templatekw.showlist
1023 1023
1024 1024 # showparents() behaviour depends on ui trace level which
1025 1025 # causes unexpected behaviours at templating level and makes
1026 1026 # it harder to extract it in a standalone function. Its
1027 1027 # behaviour cannot be changed so leave it here for now.
1028 1028 def showparents(**args):
1029 1029 ctx = args['ctx']
1030 1030 parents = [[('rev', p.rev()), ('node', p.hex())]
1031 1031 for p in self._meaningful_parentrevs(ctx)]
1032 1032 return showlist('parent', parents, **args)
1033 1033
1034 1034 props = props.copy()
1035 1035 props.update(templatekw.keywords)
1036 1036 props['parents'] = showparents
1037 1037 props['templ'] = self.t
1038 1038 props['ctx'] = ctx
1039 1039 props['repo'] = self.repo
1040 1040 props['revcache'] = {'copies': copies}
1041 1041 props['cache'] = self.cache
1042 1042
1043 1043 # find correct templates for current mode
1044 1044
1045 1045 tmplmodes = [
1046 1046 (True, None),
1047 1047 (self.ui.verbose, 'verbose'),
1048 1048 (self.ui.quiet, 'quiet'),
1049 1049 (self.ui.debugflag, 'debug'),
1050 1050 ]
1051 1051
1052 1052 types = {'header': '', 'footer':'', 'changeset': 'changeset'}
1053 1053 for mode, postfix in tmplmodes:
1054 1054 for type in types:
1055 1055 cur = postfix and ('%s_%s' % (type, postfix)) or type
1056 1056 if mode and cur in self.t:
1057 1057 types[type] = cur
1058 1058
1059 1059 try:
1060 1060
1061 1061 # write header
1062 1062 if types['header']:
1063 1063 h = templater.stringify(self.t(types['header'], **props))
1064 1064 if self.buffered:
1065 1065 self.header[ctx.rev()] = h
1066 1066 else:
1067 1067 if self.lastheader != h:
1068 1068 self.lastheader = h
1069 1069 self.ui.write(h)
1070 1070
1071 1071 # write changeset metadata, then patch if requested
1072 1072 key = types['changeset']
1073 1073 self.ui.write(templater.stringify(self.t(key, **props)))
1074 1074 self.showpatch(ctx.node(), matchfn)
1075 1075
1076 1076 if types['footer']:
1077 1077 if not self.footer:
1078 1078 self.footer = templater.stringify(self.t(types['footer'],
1079 1079 **props))
1080 1080
1081 1081 except KeyError, inst:
1082 1082 msg = _("%s: no key named '%s'")
1083 1083 raise util.Abort(msg % (self.t.mapfile, inst.args[0]))
1084 1084 except SyntaxError, inst:
1085 1085 raise util.Abort('%s: %s' % (self.t.mapfile, inst.args[0]))
1086 1086
1087 1087 def gettemplate(ui, tmpl, style):
1088 1088 """
1089 1089 Find the template matching the given template spec or style.
1090 1090 """
1091 1091
1092 1092 # ui settings
1093 1093 if not tmpl and not style:
1094 1094 tmpl = ui.config('ui', 'logtemplate')
1095 1095 if tmpl:
1096 1096 try:
1097 1097 tmpl = templater.parsestring(tmpl)
1098 1098 except SyntaxError:
1099 1099 tmpl = templater.parsestring(tmpl, quoted=False)
1100 1100 return tmpl, None
1101 1101 else:
1102 1102 style = util.expandpath(ui.config('ui', 'style', ''))
1103 1103
1104 1104 if style:
1105 1105 mapfile = style
1106 1106 if not os.path.split(mapfile)[0]:
1107 1107 mapname = (templater.templatepath('map-cmdline.' + mapfile)
1108 1108 or templater.templatepath(mapfile))
1109 1109 if mapname:
1110 1110 mapfile = mapname
1111 1111 return None, mapfile
1112 1112
1113 1113 if not tmpl:
1114 1114 return None, None
1115 1115
1116 1116 # looks like a literal template?
1117 1117 if '{' in tmpl:
1118 1118 return tmpl, None
1119 1119
1120 1120 # perhaps a stock style?
1121 1121 if not os.path.split(tmpl)[0]:
1122 1122 mapname = (templater.templatepath('map-cmdline.' + tmpl)
1123 1123 or templater.templatepath(tmpl))
1124 1124 if mapname and os.path.isfile(mapname):
1125 1125 return None, mapname
1126 1126
1127 1127 # perhaps it's a reference to [templates]
1128 1128 t = ui.config('templates', tmpl)
1129 1129 if t:
1130 1130 try:
1131 1131 tmpl = templater.parsestring(t)
1132 1132 except SyntaxError:
1133 1133 tmpl = templater.parsestring(t, quoted=False)
1134 1134 return tmpl, None
1135 1135
1136 1136 if tmpl == 'list':
1137 1137 ui.write(_("available styles: %s\n") % templater.stylelist())
1138 1138 raise util.Abort(_("specify a template"))
1139 1139
1140 1140 # perhaps it's a path to a map or a template
1141 1141 if ('/' in tmpl or '\\' in tmpl) and os.path.isfile(tmpl):
1142 1142 # is it a mapfile for a style?
1143 1143 if os.path.basename(tmpl).startswith("map-"):
1144 1144 return None, os.path.realpath(tmpl)
1145 1145 tmpl = open(tmpl).read()
1146 1146 return tmpl, None
1147 1147
1148 1148 # constant string?
1149 1149 return tmpl, None
1150 1150
1151 1151 def show_changeset(ui, repo, opts, buffered=False):
1152 1152 """show one changeset using template or regular display.
1153 1153
1154 1154 Display format will be the first non-empty hit of:
1155 1155 1. option 'template'
1156 1156 2. option 'style'
1157 1157 3. [ui] setting 'logtemplate'
1158 1158 4. [ui] setting 'style'
1159 1159 If all of these values are either the unset or the empty string,
1160 1160 regular display via changeset_printer() is done.
1161 1161 """
1162 1162 # options
1163 1163 patch = None
1164 1164 if opts.get('patch') or opts.get('stat'):
1165 1165 patch = scmutil.matchall(repo)
1166 1166
1167 1167 tmpl, mapfile = gettemplate(ui, opts.get('template'), opts.get('style'))
1168 1168
1169 1169 if not tmpl and not mapfile:
1170 1170 return changeset_printer(ui, repo, patch, opts, buffered)
1171 1171
1172 1172 try:
1173 1173 t = changeset_templater(ui, repo, patch, opts, tmpl, mapfile, buffered)
1174 1174 except SyntaxError, inst:
1175 1175 raise util.Abort(inst.args[0])
1176 1176 return t
1177 1177
1178 1178 def showmarker(ui, marker):
1179 1179 """utility function to display obsolescence marker in a readable way
1180 1180
1181 1181 To be used by debug function."""
1182 1182 ui.write(hex(marker.precnode()))
1183 1183 for repl in marker.succnodes():
1184 1184 ui.write(' ')
1185 1185 ui.write(hex(repl))
1186 1186 ui.write(' %X ' % marker._data[2])
1187 1187 ui.write('{%s}' % (', '.join('%r: %r' % t for t in
1188 1188 sorted(marker.metadata().items()))))
1189 1189 ui.write('\n')
1190 1190
1191 1191 def finddate(ui, repo, date):
1192 1192 """Find the tipmost changeset that matches the given date spec"""
1193 1193
1194 1194 df = util.matchdate(date)
1195 1195 m = scmutil.matchall(repo)
1196 1196 results = {}
1197 1197
1198 1198 def prep(ctx, fns):
1199 1199 d = ctx.date()
1200 1200 if df(d[0]):
1201 1201 results[ctx.rev()] = d
1202 1202
1203 1203 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
1204 1204 rev = ctx.rev()
1205 1205 if rev in results:
1206 1206 ui.status(_("found revision %s from %s\n") %
1207 1207 (rev, util.datestr(results[rev])))
1208 1208 return str(rev)
1209 1209
1210 1210 raise util.Abort(_("revision matching date not found"))
1211 1211
1212 1212 def increasingwindows(windowsize=8, sizelimit=512):
1213 1213 while True:
1214 1214 yield windowsize
1215 1215 if windowsize < sizelimit:
1216 1216 windowsize *= 2
1217 1217
1218 1218 class FileWalkError(Exception):
1219 1219 pass
1220 1220
1221 1221 def walkfilerevs(repo, match, follow, revs, fncache):
1222 1222 '''Walks the file history for the matched files.
1223 1223
1224 1224 Returns the changeset revs that are involved in the file history.
1225 1225
1226 1226 Throws FileWalkError if the file history can't be walked using
1227 1227 filelogs alone.
1228 1228 '''
1229 1229 wanted = set()
1230 1230 copies = []
1231 1231 minrev, maxrev = min(revs), max(revs)
1232 1232 def filerevgen(filelog, last):
1233 1233 """
1234 1234 Only files, no patterns. Check the history of each file.
1235 1235
1236 1236 Examines filelog entries within minrev, maxrev linkrev range
1237 1237 Returns an iterator yielding (linkrev, parentlinkrevs, copied)
1238 1238 tuples in backwards order
1239 1239 """
1240 1240 cl_count = len(repo)
1241 1241 revs = []
1242 1242 for j in xrange(0, last + 1):
1243 1243 linkrev = filelog.linkrev(j)
1244 1244 if linkrev < minrev:
1245 1245 continue
1246 1246 # only yield rev for which we have the changelog, it can
1247 1247 # happen while doing "hg log" during a pull or commit
1248 1248 if linkrev >= cl_count:
1249 1249 break
1250 1250
1251 1251 parentlinkrevs = []
1252 1252 for p in filelog.parentrevs(j):
1253 1253 if p != nullrev:
1254 1254 parentlinkrevs.append(filelog.linkrev(p))
1255 1255 n = filelog.node(j)
1256 1256 revs.append((linkrev, parentlinkrevs,
1257 1257 follow and filelog.renamed(n)))
1258 1258
1259 1259 return reversed(revs)
1260 1260 def iterfiles():
1261 1261 pctx = repo['.']
1262 1262 for filename in match.files():
1263 1263 if follow:
1264 1264 if filename not in pctx:
1265 1265 raise util.Abort(_('cannot follow file not in parent '
1266 1266 'revision: "%s"') % filename)
1267 1267 yield filename, pctx[filename].filenode()
1268 1268 else:
1269 1269 yield filename, None
1270 1270 for filename_node in copies:
1271 1271 yield filename_node
1272 1272
1273 1273 for file_, node in iterfiles():
1274 1274 filelog = repo.file(file_)
1275 1275 if not len(filelog):
1276 1276 if node is None:
1277 1277 # A zero count may be a directory or deleted file, so
1278 1278 # try to find matching entries on the slow path.
1279 1279 if follow:
1280 1280 raise util.Abort(
1281 1281 _('cannot follow nonexistent file: "%s"') % file_)
1282 1282 raise FileWalkError("Cannot walk via filelog")
1283 1283 else:
1284 1284 continue
1285 1285
1286 1286 if node is None:
1287 1287 last = len(filelog) - 1
1288 1288 else:
1289 1289 last = filelog.rev(node)
1290 1290
1291 1291
1292 1292 # keep track of all ancestors of the file
1293 1293 ancestors = set([filelog.linkrev(last)])
1294 1294
1295 1295 # iterate from latest to oldest revision
1296 1296 for rev, flparentlinkrevs, copied in filerevgen(filelog, last):
1297 1297 if not follow:
1298 1298 if rev > maxrev:
1299 1299 continue
1300 1300 else:
1301 1301 # Note that last might not be the first interesting
1302 1302 # rev to us:
1303 1303 # if the file has been changed after maxrev, we'll
1304 1304 # have linkrev(last) > maxrev, and we still need
1305 1305 # to explore the file graph
1306 1306 if rev not in ancestors:
1307 1307 continue
1308 1308 # XXX insert 1327 fix here
1309 1309 if flparentlinkrevs:
1310 1310 ancestors.update(flparentlinkrevs)
1311 1311
1312 1312 fncache.setdefault(rev, []).append(file_)
1313 1313 wanted.add(rev)
1314 1314 if copied:
1315 1315 copies.append(copied)
1316 1316
1317 1317 return wanted
1318 1318
1319 1319 def walkchangerevs(repo, match, opts, prepare):
1320 1320 '''Iterate over files and the revs in which they changed.
1321 1321
1322 1322 Callers most commonly need to iterate backwards over the history
1323 1323 in which they are interested. Doing so has awful (quadratic-looking)
1324 1324 performance, so we use iterators in a "windowed" way.
1325 1325
1326 1326 We walk a window of revisions in the desired order. Within the
1327 1327 window, we first walk forwards to gather data, then in the desired
1328 1328 order (usually backwards) to display it.
1329 1329
1330 1330 This function returns an iterator yielding contexts. Before
1331 1331 yielding each context, the iterator will first call the prepare
1332 1332 function on each context in the window in forward order.'''
1333 1333
1334 1334 follow = opts.get('follow') or opts.get('follow_first')
1335 1335
1336 1336 if opts.get('rev'):
1337 1337 revs = scmutil.revrange(repo, opts.get('rev'))
1338 1338 elif follow:
1339 1339 revs = repo.revs('reverse(:.)')
1340 1340 else:
1341 1341 revs = revset.spanset(repo)
1342 1342 revs.reverse()
1343 1343 if not revs:
1344 1344 return []
1345 1345 wanted = set()
1346 1346 slowpath = match.anypats() or (match.files() and opts.get('removed'))
1347 1347 fncache = {}
1348 1348 change = repo.changectx
1349 1349
1350 1350 # First step is to fill wanted, the set of revisions that we want to yield.
1351 1351 # When it does not induce extra cost, we also fill fncache for revisions in
1352 1352 # wanted: a cache of filenames that were changed (ctx.files()) and that
1353 1353 # match the file filtering conditions.
1354 1354
1355 1355 if not slowpath and not match.files():
1356 1356 # No files, no patterns. Display all revs.
1357 1357 wanted = revs
1358 1358
1359 1359 if not slowpath and match.files():
1360 1360 # We only have to read through the filelog to find wanted revisions
1361 1361
1362 1362 try:
1363 1363 wanted = walkfilerevs(repo, match, follow, revs, fncache)
1364 1364 except FileWalkError:
1365 1365 slowpath = True
1366 1366
1367 1367 # We decided to fall back to the slowpath because at least one
1368 1368 # of the paths was not a file. Check to see if at least one of them
1369 1369 # existed in history, otherwise simply return
1370 1370 for path in match.files():
1371 1371 if path == '.' or path in repo.store:
1372 1372 break
1373 1373 else:
1374 1374 return []
1375 1375
1376 1376 if slowpath:
1377 1377 # We have to read the changelog to match filenames against
1378 1378 # changed files
1379 1379
1380 1380 if follow:
1381 1381 raise util.Abort(_('can only follow copies/renames for explicit '
1382 1382 'filenames'))
1383 1383
1384 1384 # The slow path checks files modified in every changeset.
1385 1385 # This is really slow on large repos, so compute the set lazily.
1386 1386 class lazywantedset(object):
1387 1387 def __init__(self):
1388 1388 self.set = set()
1389 1389 self.revs = set(revs)
1390 1390
1391 1391 # No need to worry about locality here because it will be accessed
1392 1392 # in the same order as the increasing window below.
1393 1393 def __contains__(self, value):
1394 1394 if value in self.set:
1395 1395 return True
1396 1396 elif not value in self.revs:
1397 1397 return False
1398 1398 else:
1399 1399 self.revs.discard(value)
1400 1400 ctx = change(value)
1401 1401 matches = filter(match, ctx.files())
1402 1402 if matches:
1403 1403 fncache[value] = matches
1404 1404 self.set.add(value)
1405 1405 return True
1406 1406 return False
1407 1407
1408 1408 def discard(self, value):
1409 1409 self.revs.discard(value)
1410 1410 self.set.discard(value)
1411 1411
1412 1412 wanted = lazywantedset()
1413 1413
1414 1414 class followfilter(object):
1415 1415 def __init__(self, onlyfirst=False):
1416 1416 self.startrev = nullrev
1417 1417 self.roots = set()
1418 1418 self.onlyfirst = onlyfirst
1419 1419
1420 1420 def match(self, rev):
1421 1421 def realparents(rev):
1422 1422 if self.onlyfirst:
1423 1423 return repo.changelog.parentrevs(rev)[0:1]
1424 1424 else:
1425 1425 return filter(lambda x: x != nullrev,
1426 1426 repo.changelog.parentrevs(rev))
1427 1427
1428 1428 if self.startrev == nullrev:
1429 1429 self.startrev = rev
1430 1430 return True
1431 1431
1432 1432 if rev > self.startrev:
1433 1433 # forward: all descendants
1434 1434 if not self.roots:
1435 1435 self.roots.add(self.startrev)
1436 1436 for parent in realparents(rev):
1437 1437 if parent in self.roots:
1438 1438 self.roots.add(rev)
1439 1439 return True
1440 1440 else:
1441 1441 # backwards: all parents
1442 1442 if not self.roots:
1443 1443 self.roots.update(realparents(self.startrev))
1444 1444 if rev in self.roots:
1445 1445 self.roots.remove(rev)
1446 1446 self.roots.update(realparents(rev))
1447 1447 return True
1448 1448
1449 1449 return False
1450 1450
1451 1451 # it might be worthwhile to do this in the iterator if the rev range
1452 1452 # is descending and the prune args are all within that range
1453 1453 for rev in opts.get('prune', ()):
1454 1454 rev = repo[rev].rev()
1455 1455 ff = followfilter()
1456 1456 stop = min(revs[0], revs[-1])
1457 1457 for x in xrange(rev, stop - 1, -1):
1458 1458 if ff.match(x):
1459 1459 wanted = wanted - [x]
1460 1460
1461 1461 # Now that wanted is correctly initialized, we can iterate over the
1462 1462 # revision range, yielding only revisions in wanted.
1463 1463 def iterate():
1464 1464 if follow and not match.files():
1465 1465 ff = followfilter(onlyfirst=opts.get('follow_first'))
1466 1466 def want(rev):
1467 1467 return ff.match(rev) and rev in wanted
1468 1468 else:
1469 1469 def want(rev):
1470 1470 return rev in wanted
1471 1471
1472 1472 it = iter(revs)
1473 1473 stopiteration = False
1474 1474 for windowsize in increasingwindows():
1475 1475 nrevs = []
1476 1476 for i in xrange(windowsize):
1477 1477 try:
1478 1478 rev = it.next()
1479 1479 if want(rev):
1480 1480 nrevs.append(rev)
1481 1481 except (StopIteration):
1482 1482 stopiteration = True
1483 1483 break
1484 1484 for rev in sorted(nrevs):
1485 1485 fns = fncache.get(rev)
1486 1486 ctx = change(rev)
1487 1487 if not fns:
1488 1488 def fns_generator():
1489 1489 for f in ctx.files():
1490 1490 if match(f):
1491 1491 yield f
1492 1492 fns = fns_generator()
1493 1493 prepare(ctx, fns)
1494 1494 for rev in nrevs:
1495 1495 yield change(rev)
1496 1496
1497 1497 if stopiteration:
1498 1498 break
1499 1499
1500 1500 return iterate()
1501 1501
1502 1502 def _makelogfilematcher(repo, files, followfirst):
1503 1503 # When displaying a revision with --patch --follow FILE, we have
1504 1504 # to know which file of the revision must be diffed. With
1505 1505 # --follow, we want the names of the ancestors of FILE in the
1506 1506 # revision, stored in "fcache". "fcache" is populated by
1507 1507 # reproducing the graph traversal already done by --follow revset
1508 1508 # and relating linkrevs to file names (which is not "correct" but
1509 1509 # good enough).
1510 1510 fcache = {}
1511 1511 fcacheready = [False]
1512 1512 pctx = repo['.']
1513 1513
1514 1514 def populate():
1515 1515 for fn in files:
1516 1516 for i in ((pctx[fn],), pctx[fn].ancestors(followfirst=followfirst)):
1517 1517 for c in i:
1518 1518 fcache.setdefault(c.linkrev(), set()).add(c.path())
1519 1519
1520 1520 def filematcher(rev):
1521 1521 if not fcacheready[0]:
1522 1522 # Lazy initialization
1523 1523 fcacheready[0] = True
1524 1524 populate()
1525 1525 return scmutil.matchfiles(repo, fcache.get(rev, []))
1526 1526
1527 1527 return filematcher
1528 1528
1529 1529 def _makelogrevset(repo, pats, opts, revs):
1530 1530 """Return (expr, filematcher) where expr is a revset string built
1531 1531 from log options and file patterns or None. If --stat or --patch
1532 1532 are not passed filematcher is None. Otherwise it is a callable
1533 1533 taking a revision number and returning a match objects filtering
1534 1534 the files to be detailed when displaying the revision.
1535 1535 """
1536 1536 opt2revset = {
1537 1537 'no_merges': ('not merge()', None),
1538 1538 'only_merges': ('merge()', None),
1539 1539 '_ancestors': ('ancestors(%(val)s)', None),
1540 1540 '_fancestors': ('_firstancestors(%(val)s)', None),
1541 1541 '_descendants': ('descendants(%(val)s)', None),
1542 1542 '_fdescendants': ('_firstdescendants(%(val)s)', None),
1543 1543 '_matchfiles': ('_matchfiles(%(val)s)', None),
1544 1544 'date': ('date(%(val)r)', None),
1545 1545 'branch': ('branch(%(val)r)', ' or '),
1546 1546 '_patslog': ('filelog(%(val)r)', ' or '),
1547 1547 '_patsfollow': ('follow(%(val)r)', ' or '),
1548 1548 '_patsfollowfirst': ('_followfirst(%(val)r)', ' or '),
1549 1549 'keyword': ('keyword(%(val)r)', ' or '),
1550 1550 'prune': ('not (%(val)r or ancestors(%(val)r))', ' and '),
1551 1551 'user': ('user(%(val)r)', ' or '),
1552 1552 }
1553 1553
1554 1554 opts = dict(opts)
1555 1555 # follow or not follow?
1556 1556 follow = opts.get('follow') or opts.get('follow_first')
1557 1557 followfirst = opts.get('follow_first') and 1 or 0
1558 1558 # --follow with FILE behaviour depends on revs...
1559 1559 it = iter(revs)
1560 1560 startrev = it.next()
1561 1561 try:
1562 1562 followdescendants = startrev < it.next()
1563 1563 except (StopIteration):
1564 1564 followdescendants = False
1565 1565
1566 1566 # branch and only_branch are really aliases and must be handled at
1567 1567 # the same time
1568 1568 opts['branch'] = opts.get('branch', []) + opts.get('only_branch', [])
1569 1569 opts['branch'] = [repo.lookupbranch(b) for b in opts['branch']]
1570 1570 # pats/include/exclude are passed to match.match() directly in
1571 1571 # _matchfiles() revset but walkchangerevs() builds its matcher with
1572 1572 # scmutil.match(). The difference is input pats are globbed on
1573 1573 # platforms without shell expansion (windows).
1574 1574 pctx = repo[None]
1575 1575 match, pats = scmutil.matchandpats(pctx, pats, opts)
1576 1576 slowpath = match.anypats() or (match.files() and opts.get('removed'))
1577 1577 if not slowpath:
1578 1578 for f in match.files():
1579 1579 if follow and f not in pctx:
1580 1580 # If the file exists, it may be a directory, so let it
1581 1581 # take the slow path.
1582 1582 if os.path.exists(repo.wjoin(f)):
1583 1583 slowpath = True
1584 1584 continue
1585 1585 else:
1586 1586 raise util.Abort(_('cannot follow file not in parent '
1587 1587 'revision: "%s"') % f)
1588 1588 filelog = repo.file(f)
1589 1589 if not filelog:
1590 1590 # A zero count may be a directory or deleted file, so
1591 1591 # try to find matching entries on the slow path.
1592 1592 if follow:
1593 1593 raise util.Abort(
1594 1594 _('cannot follow nonexistent file: "%s"') % f)
1595 1595 slowpath = True
1596 1596
1597 1597 # We decided to fall back to the slowpath because at least one
1598 1598 # of the paths was not a file. Check to see if at least one of them
1599 1599 # existed in history - in that case, we'll continue down the
1600 1600 # slowpath; otherwise, we can turn off the slowpath
1601 1601 if slowpath:
1602 1602 for path in match.files():
1603 1603 if path == '.' or path in repo.store:
1604 1604 break
1605 1605 else:
1606 1606 slowpath = False
1607 1607
1608 1608 if slowpath:
1609 1609 # See walkchangerevs() slow path.
1610 1610 #
1611 1611 # pats/include/exclude cannot be represented as separate
1612 1612 # revset expressions as their filtering logic applies at file
1613 1613 # level. For instance "-I a -X a" matches a revision touching
1614 1614 # "a" and "b" while "file(a) and not file(b)" does
1615 1615 # not. Besides, filesets are evaluated against the working
1616 1616 # directory.
1617 1617 matchargs = ['r:', 'd:relpath']
1618 1618 for p in pats:
1619 1619 matchargs.append('p:' + p)
1620 1620 for p in opts.get('include', []):
1621 1621 matchargs.append('i:' + p)
1622 1622 for p in opts.get('exclude', []):
1623 1623 matchargs.append('x:' + p)
1624 1624 matchargs = ','.join(('%r' % p) for p in matchargs)
1625 1625 opts['_matchfiles'] = matchargs
1626 1626 else:
1627 1627 if follow:
1628 1628 fpats = ('_patsfollow', '_patsfollowfirst')
1629 1629 fnopats = (('_ancestors', '_fancestors'),
1630 1630 ('_descendants', '_fdescendants'))
1631 1631 if pats:
1632 1632 # follow() revset interprets its file argument as a
1633 1633 # manifest entry, so use match.files(), not pats.
1634 1634 opts[fpats[followfirst]] = list(match.files())
1635 1635 else:
1636 1636 opts[fnopats[followdescendants][followfirst]] = str(startrev)
1637 1637 else:
1638 1638 opts['_patslog'] = list(pats)
1639 1639
1640 1640 filematcher = None
1641 1641 if opts.get('patch') or opts.get('stat'):
1642 1642 # When following files, track renames via a special matcher.
1643 1643 # If we're forced to take the slowpath it means we're following
1644 1644 # at least one pattern/directory, so don't bother with rename tracking.
1645 1645 if follow and not match.always() and not slowpath:
1646 1646 # _makelogfilematcher expects its files argument to be relative to
1647 1647 # the repo root, so use match.files(), not pats.
1648 1648 filematcher = _makelogfilematcher(repo, match.files(), followfirst)
1649 1649 else:
1650 1650 filematcher = lambda rev: match
1651 1651
1652 1652 expr = []
1653 1653 for op, val in opts.iteritems():
1654 1654 if not val:
1655 1655 continue
1656 1656 if op not in opt2revset:
1657 1657 continue
1658 1658 revop, andor = opt2revset[op]
1659 1659 if '%(val)' not in revop:
1660 1660 expr.append(revop)
1661 1661 else:
1662 1662 if not isinstance(val, list):
1663 1663 e = revop % {'val': val}
1664 1664 else:
1665 1665 e = '(' + andor.join((revop % {'val': v}) for v in val) + ')'
1666 1666 expr.append(e)
1667 1667
1668 1668 if expr:
1669 1669 expr = '(' + ' and '.join(expr) + ')'
1670 1670 else:
1671 1671 expr = None
1672 1672 return expr, filematcher
1673 1673
1674 1674 def getgraphlogrevs(repo, pats, opts):
1675 1675 """Return (revs, expr, filematcher) where revs is an iterable of
1676 1676 revision numbers, expr is a revset string built from log options
1677 1677 and file patterns or None, and used to filter 'revs'. If --stat or
1678 1678 --patch are not passed filematcher is None. Otherwise it is a
1679 1679 callable taking a revision number and returning a match objects
1680 1680 filtering the files to be detailed when displaying the revision.
1681 1681 """
1682 1682 if not len(repo):
1683 1683 return [], None, None
1684 1684 limit = loglimit(opts)
1685 1685 # Default --rev value depends on --follow but --follow behaviour
1686 1686 # depends on revisions resolved from --rev...
1687 1687 follow = opts.get('follow') or opts.get('follow_first')
1688 1688 possiblyunsorted = False # whether revs might need sorting
1689 1689 if opts.get('rev'):
1690 1690 revs = scmutil.revrange(repo, opts['rev'])
1691 1691 # Don't sort here because _makelogrevset might depend on the
1692 1692 # order of revs
1693 1693 possiblyunsorted = True
1694 1694 else:
1695 1695 if follow and len(repo) > 0:
1696 1696 revs = repo.revs('reverse(:.)')
1697 1697 else:
1698 1698 revs = revset.spanset(repo)
1699 1699 revs.reverse()
1700 1700 if not revs:
1701 1701 return revset.baseset(), None, None
1702 1702 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
1703 1703 if possiblyunsorted:
1704 1704 revs.sort(reverse=True)
1705 1705 if expr:
1706 1706 # Revset matchers often operate faster on revisions in changelog
1707 1707 # order, because most filters deal with the changelog.
1708 1708 revs.reverse()
1709 1709 matcher = revset.match(repo.ui, expr)
1710 1710 # Revset matches can reorder revisions. "A or B" typically returns
1711 1711 # returns the revision matching A then the revision matching B. Sort
1712 1712 # again to fix that.
1713 1713 revs = matcher(repo, revs)
1714 1714 revs.sort(reverse=True)
1715 1715 if limit is not None:
1716 1716 limitedrevs = revset.baseset()
1717 1717 for idx, rev in enumerate(revs):
1718 1718 if idx >= limit:
1719 1719 break
1720 1720 limitedrevs.append(rev)
1721 1721 revs = limitedrevs
1722 1722
1723 1723 return revs, expr, filematcher
1724 1724
1725 1725 def getlogrevs(repo, pats, opts):
1726 1726 """Return (revs, expr, filematcher) where revs is an iterable of
1727 1727 revision numbers, expr is a revset string built from log options
1728 1728 and file patterns or None, and used to filter 'revs'. If --stat or
1729 1729 --patch are not passed filematcher is None. Otherwise it is a
1730 1730 callable taking a revision number and returning a match objects
1731 1731 filtering the files to be detailed when displaying the revision.
1732 1732 """
1733 1733 limit = loglimit(opts)
1734 1734 # Default --rev value depends on --follow but --follow behaviour
1735 1735 # depends on revisions resolved from --rev...
1736 1736 follow = opts.get('follow') or opts.get('follow_first')
1737 1737 if opts.get('rev'):
1738 1738 revs = scmutil.revrange(repo, opts['rev'])
1739 1739 elif follow:
1740 1740 revs = repo.revs('reverse(:.)')
1741 1741 else:
1742 1742 revs = revset.spanset(repo)
1743 1743 revs.reverse()
1744 1744 if not revs:
1745 1745 return revset.baseset([]), None, None
1746 1746 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
1747 1747 if expr:
1748 1748 # Revset matchers often operate faster on revisions in changelog
1749 1749 # order, because most filters deal with the changelog.
1750 1750 if not opts.get('rev'):
1751 1751 revs.reverse()
1752 1752 matcher = revset.match(repo.ui, expr)
1753 1753 # Revset matches can reorder revisions. "A or B" typically returns
1754 1754 # returns the revision matching A then the revision matching B. Sort
1755 1755 # again to fix that.
1756 1756 revs = matcher(repo, revs)
1757 1757 if not opts.get('rev'):
1758 1758 revs.sort(reverse=True)
1759 1759 if limit is not None:
1760 1760 count = 0
1761 1761 limitedrevs = revset.baseset([])
1762 1762 it = iter(revs)
1763 1763 while count < limit:
1764 1764 try:
1765 1765 limitedrevs.append(it.next())
1766 1766 except (StopIteration):
1767 1767 break
1768 1768 count += 1
1769 1769 revs = limitedrevs
1770 1770
1771 1771 return revs, expr, filematcher
1772 1772
1773 1773 def displaygraph(ui, dag, displayer, showparents, edgefn, getrenamed=None,
1774 1774 filematcher=None):
1775 1775 seen, state = [], graphmod.asciistate()
1776 1776 for rev, type, ctx, parents in dag:
1777 1777 char = 'o'
1778 1778 if ctx.node() in showparents:
1779 1779 char = '@'
1780 1780 elif ctx.obsolete():
1781 1781 char = 'x'
1782 1782 copies = None
1783 1783 if getrenamed and ctx.rev():
1784 1784 copies = []
1785 1785 for fn in ctx.files():
1786 1786 rename = getrenamed(fn, ctx.rev())
1787 1787 if rename:
1788 1788 copies.append((fn, rename[0]))
1789 1789 revmatchfn = None
1790 1790 if filematcher is not None:
1791 1791 revmatchfn = filematcher(ctx.rev())
1792 1792 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
1793 1793 lines = displayer.hunk.pop(rev).split('\n')
1794 1794 if not lines[-1]:
1795 1795 del lines[-1]
1796 1796 displayer.flush(rev)
1797 1797 edges = edgefn(type, char, lines, seen, rev, parents)
1798 1798 for type, char, lines, coldata in edges:
1799 1799 graphmod.ascii(ui, state, type, char, lines, coldata)
1800 1800 displayer.close()
1801 1801
1802 1802 def graphlog(ui, repo, *pats, **opts):
1803 1803 # Parameters are identical to log command ones
1804 1804 revs, expr, filematcher = getgraphlogrevs(repo, pats, opts)
1805 1805 revdag = graphmod.dagwalker(repo, revs)
1806 1806
1807 1807 getrenamed = None
1808 1808 if opts.get('copies'):
1809 1809 endrev = None
1810 1810 if opts.get('rev'):
1811 1811 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
1812 1812 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
1813 1813 displayer = show_changeset(ui, repo, opts, buffered=True)
1814 1814 showparents = [ctx.node() for ctx in repo[None].parents()]
1815 1815 displaygraph(ui, revdag, displayer, showparents,
1816 1816 graphmod.asciiedges, getrenamed, filematcher)
1817 1817
1818 1818 def checkunsupportedgraphflags(pats, opts):
1819 1819 for op in ["newest_first"]:
1820 1820 if op in opts and opts[op]:
1821 1821 raise util.Abort(_("-G/--graph option is incompatible with --%s")
1822 1822 % op.replace("_", "-"))
1823 1823
1824 1824 def graphrevs(repo, nodes, opts):
1825 1825 limit = loglimit(opts)
1826 1826 nodes.reverse()
1827 1827 if limit is not None:
1828 1828 nodes = nodes[:limit]
1829 1829 return graphmod.nodes(repo, nodes)
1830 1830
1831 1831 def add(ui, repo, match, dryrun, listsubrepos, prefix, explicitonly):
1832 1832 join = lambda f: os.path.join(prefix, f)
1833 1833 bad = []
1834 1834 oldbad = match.bad
1835 1835 match.bad = lambda x, y: bad.append(x) or oldbad(x, y)
1836 1836 names = []
1837 1837 wctx = repo[None]
1838 1838 cca = None
1839 1839 abort, warn = scmutil.checkportabilityalert(ui)
1840 1840 if abort or warn:
1841 1841 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
1842 1842 for f in repo.walk(match):
1843 1843 exact = match.exact(f)
1844 1844 if exact or not explicitonly and f not in repo.dirstate:
1845 1845 if cca:
1846 1846 cca(f)
1847 1847 names.append(f)
1848 1848 if ui.verbose or not exact:
1849 1849 ui.status(_('adding %s\n') % match.rel(join(f)))
1850 1850
1851 1851 for subpath in sorted(wctx.substate):
1852 1852 sub = wctx.sub(subpath)
1853 1853 try:
1854 1854 submatch = matchmod.narrowmatcher(subpath, match)
1855 1855 if listsubrepos:
1856 1856 bad.extend(sub.add(ui, submatch, dryrun, listsubrepos, prefix,
1857 1857 False))
1858 1858 else:
1859 1859 bad.extend(sub.add(ui, submatch, dryrun, listsubrepos, prefix,
1860 1860 True))
1861 1861 except error.LookupError:
1862 1862 ui.status(_("skipping missing subrepository: %s\n")
1863 1863 % join(subpath))
1864 1864
1865 1865 if not dryrun:
1866 1866 rejected = wctx.add(names, prefix)
1867 1867 bad.extend(f for f in rejected if f in match.files())
1868 1868 return bad
1869 1869
1870 1870 def forget(ui, repo, match, prefix, explicitonly):
1871 1871 join = lambda f: os.path.join(prefix, f)
1872 1872 bad = []
1873 1873 oldbad = match.bad
1874 1874 match.bad = lambda x, y: bad.append(x) or oldbad(x, y)
1875 1875 wctx = repo[None]
1876 1876 forgot = []
1877 1877 s = repo.status(match=match, clean=True)
1878 1878 forget = sorted(s[0] + s[1] + s[3] + s[6])
1879 1879 if explicitonly:
1880 1880 forget = [f for f in forget if match.exact(f)]
1881 1881
1882 1882 for subpath in sorted(wctx.substate):
1883 1883 sub = wctx.sub(subpath)
1884 1884 try:
1885 1885 submatch = matchmod.narrowmatcher(subpath, match)
1886 1886 subbad, subforgot = sub.forget(ui, submatch, prefix)
1887 1887 bad.extend([subpath + '/' + f for f in subbad])
1888 1888 forgot.extend([subpath + '/' + f for f in subforgot])
1889 1889 except error.LookupError:
1890 1890 ui.status(_("skipping missing subrepository: %s\n")
1891 1891 % join(subpath))
1892 1892
1893 1893 if not explicitonly:
1894 1894 for f in match.files():
1895 1895 if f not in repo.dirstate and not os.path.isdir(match.rel(join(f))):
1896 1896 if f not in forgot:
1897 1897 if os.path.exists(match.rel(join(f))):
1898 1898 ui.warn(_('not removing %s: '
1899 1899 'file is already untracked\n')
1900 1900 % match.rel(join(f)))
1901 1901 bad.append(f)
1902 1902
1903 1903 for f in forget:
1904 1904 if ui.verbose or not match.exact(f):
1905 1905 ui.status(_('removing %s\n') % match.rel(join(f)))
1906 1906
1907 1907 rejected = wctx.forget(forget, prefix)
1908 1908 bad.extend(f for f in rejected if f in match.files())
1909 1909 forgot.extend(forget)
1910 1910 return bad, forgot
1911 1911
1912 1912 def cat(ui, repo, ctx, matcher, prefix, **opts):
1913 1913 err = 1
1914 1914
1915 1915 def write(path):
1916 1916 fp = makefileobj(repo, opts.get('output'), ctx.node(),
1917 1917 pathname=os.path.join(prefix, path))
1918 1918 data = ctx[path].data()
1919 1919 if opts.get('decode'):
1920 1920 data = repo.wwritedata(path, data)
1921 1921 fp.write(data)
1922 1922 fp.close()
1923 1923
1924 1924 # Automation often uses hg cat on single files, so special case it
1925 1925 # for performance to avoid the cost of parsing the manifest.
1926 1926 if len(matcher.files()) == 1 and not matcher.anypats():
1927 1927 file = matcher.files()[0]
1928 1928 mf = repo.manifest
1929 1929 mfnode = ctx._changeset[0]
1930 1930 if mf.find(mfnode, file)[0]:
1931 1931 write(file)
1932 1932 return 0
1933 1933
1934 1934 # Don't warn about "missing" files that are really in subrepos
1935 1935 bad = matcher.bad
1936 1936
1937 1937 def badfn(path, msg):
1938 1938 for subpath in ctx.substate:
1939 1939 if path.startswith(subpath):
1940 1940 return
1941 1941 bad(path, msg)
1942 1942
1943 1943 matcher.bad = badfn
1944 1944
1945 1945 for abs in ctx.walk(matcher):
1946 1946 write(abs)
1947 1947 err = 0
1948 1948
1949 1949 matcher.bad = bad
1950 1950
1951 1951 for subpath in sorted(ctx.substate):
1952 1952 sub = ctx.sub(subpath)
1953 1953 try:
1954 1954 submatch = matchmod.narrowmatcher(subpath, matcher)
1955 1955
1956 1956 if not sub.cat(ui, submatch, os.path.join(prefix, sub._path),
1957 1957 **opts):
1958 1958 err = 0
1959 1959 except error.RepoLookupError:
1960 1960 ui.status(_("skipping missing subrepository: %s\n")
1961 1961 % os.path.join(prefix, subpath))
1962 1962
1963 1963 return err
1964 1964
1965 1965 def duplicatecopies(repo, rev, fromrev, skiprev=None):
1966 1966 '''reproduce copies from fromrev to rev in the dirstate
1967 1967
1968 1968 If skiprev is specified, it's a revision that should be used to
1969 1969 filter copy records. Any copies that occur between fromrev and
1970 1970 skiprev will not be duplicated, even if they appear in the set of
1971 1971 copies between fromrev and rev.
1972 1972 '''
1973 1973 exclude = {}
1974 1974 if skiprev is not None:
1975 1975 exclude = copies.pathcopies(repo[fromrev], repo[skiprev])
1976 1976 for dst, src in copies.pathcopies(repo[fromrev], repo[rev]).iteritems():
1977 1977 # copies.pathcopies returns backward renames, so dst might not
1978 1978 # actually be in the dirstate
1979 1979 if dst in exclude:
1980 1980 continue
1981 1981 if repo.dirstate[dst] in "nma":
1982 1982 repo.dirstate.copy(src, dst)
1983 1983
1984 1984 def commit(ui, repo, commitfunc, pats, opts):
1985 1985 '''commit the specified files or all outstanding changes'''
1986 1986 date = opts.get('date')
1987 1987 if date:
1988 1988 opts['date'] = util.parsedate(date)
1989 1989 message = logmessage(ui, opts)
1990 1990
1991 1991 # extract addremove carefully -- this function can be called from a command
1992 1992 # that doesn't support addremove
1993 1993 if opts.get('addremove'):
1994 1994 scmutil.addremove(repo, pats, opts)
1995 1995
1996 1996 return commitfunc(ui, repo, message,
1997 1997 scmutil.match(repo[None], pats, opts), opts)
1998 1998
1999 1999 def amend(ui, repo, commitfunc, old, extra, pats, opts):
2000 2000 ui.note(_('amending changeset %s\n') % old)
2001 2001 base = old.p1()
2002 2002
2003 2003 wlock = lock = newid = None
2004 2004 try:
2005 2005 wlock = repo.wlock()
2006 2006 lock = repo.lock()
2007 2007 tr = repo.transaction('amend')
2008 2008 try:
2009 2009 # See if we got a message from -m or -l, if not, open the editor
2010 2010 # with the message of the changeset to amend
2011 2011 message = logmessage(ui, opts)
2012 2012 # ensure logfile does not conflict with later enforcement of the
2013 2013 # message. potential logfile content has been processed by
2014 2014 # `logmessage` anyway.
2015 2015 opts.pop('logfile')
2016 2016 # First, do a regular commit to record all changes in the working
2017 2017 # directory (if there are any)
2018 2018 ui.callhooks = False
2019 2019 currentbookmark = repo._bookmarkcurrent
2020 2020 try:
2021 2021 repo._bookmarkcurrent = None
2022 2022 opts['message'] = 'temporary amend commit for %s' % old
2023 2023 node = commit(ui, repo, commitfunc, pats, opts)
2024 2024 finally:
2025 2025 repo._bookmarkcurrent = currentbookmark
2026 2026 ui.callhooks = True
2027 2027 ctx = repo[node]
2028 2028
2029 2029 # Participating changesets:
2030 2030 #
2031 2031 # node/ctx o - new (intermediate) commit that contains changes
2032 2032 # | from working dir to go into amending commit
2033 2033 # | (or a workingctx if there were no changes)
2034 2034 # |
2035 2035 # old o - changeset to amend
2036 2036 # |
2037 2037 # base o - parent of amending changeset
2038 2038
2039 2039 # Update extra dict from amended commit (e.g. to preserve graft
2040 2040 # source)
2041 2041 extra.update(old.extra())
2042 2042
2043 2043 # Also update it from the intermediate commit or from the wctx
2044 2044 extra.update(ctx.extra())
2045 2045
2046 2046 if len(old.parents()) > 1:
2047 2047 # ctx.files() isn't reliable for merges, so fall back to the
2048 2048 # slower repo.status() method
2049 2049 files = set([fn for st in repo.status(base, old)[:3]
2050 2050 for fn in st])
2051 2051 else:
2052 2052 files = set(old.files())
2053 2053
2054 2054 # Second, we use either the commit we just did, or if there were no
2055 2055 # changes the parent of the working directory as the version of the
2056 2056 # files in the final amend commit
2057 2057 if node:
2058 2058 ui.note(_('copying changeset %s to %s\n') % (ctx, base))
2059 2059
2060 2060 user = ctx.user()
2061 2061 date = ctx.date()
2062 2062 # Recompute copies (avoid recording a -> b -> a)
2063 2063 copied = copies.pathcopies(base, ctx)
2064 2064
2065 2065 # Prune files which were reverted by the updates: if old
2066 2066 # introduced file X and our intermediate commit, node,
2067 2067 # renamed that file, then those two files are the same and
2068 2068 # we can discard X from our list of files. Likewise if X
2069 2069 # was deleted, it's no longer relevant
2070 2070 files.update(ctx.files())
2071 2071
2072 2072 def samefile(f):
2073 2073 if f in ctx.manifest():
2074 2074 a = ctx.filectx(f)
2075 2075 if f in base.manifest():
2076 2076 b = base.filectx(f)
2077 2077 return (not a.cmp(b)
2078 2078 and a.flags() == b.flags())
2079 2079 else:
2080 2080 return False
2081 2081 else:
2082 2082 return f not in base.manifest()
2083 2083 files = [f for f in files if not samefile(f)]
2084 2084
2085 2085 def filectxfn(repo, ctx_, path):
2086 2086 try:
2087 2087 fctx = ctx[path]
2088 2088 flags = fctx.flags()
2089 2089 mctx = context.memfilectx(repo,
2090 2090 fctx.path(), fctx.data(),
2091 2091 islink='l' in flags,
2092 2092 isexec='x' in flags,
2093 2093 copied=copied.get(path))
2094 2094 return mctx
2095 2095 except KeyError:
2096 2096 raise IOError
2097 2097 else:
2098 2098 ui.note(_('copying changeset %s to %s\n') % (old, base))
2099 2099
2100 2100 # Use version of files as in the old cset
2101 2101 def filectxfn(repo, ctx_, path):
2102 2102 try:
2103 2103 return old.filectx(path)
2104 2104 except KeyError:
2105 2105 raise IOError
2106 2106
2107 2107 user = opts.get('user') or old.user()
2108 2108 date = opts.get('date') or old.date()
2109 editor = getcommiteditor(**opts)
2109 editform = 'commit.amend'
2110 editor = getcommiteditor(editform=editform, **opts)
2110 2111 if not message:
2111 editor = getcommiteditor(edit=True)
2112 editor = getcommiteditor(edit=True, editform=editform)
2112 2113 message = old.description()
2113 2114
2114 2115 pureextra = extra.copy()
2115 2116 extra['amend_source'] = old.hex()
2116 2117
2117 2118 new = context.memctx(repo,
2118 2119 parents=[base.node(), old.p2().node()],
2119 2120 text=message,
2120 2121 files=files,
2121 2122 filectxfn=filectxfn,
2122 2123 user=user,
2123 2124 date=date,
2124 2125 extra=extra,
2125 2126 editor=editor)
2126 2127
2127 2128 newdesc = changelog.stripdesc(new.description())
2128 2129 if ((not node)
2129 2130 and newdesc == old.description()
2130 2131 and user == old.user()
2131 2132 and date == old.date()
2132 2133 and pureextra == old.extra()):
2133 2134 # nothing changed. continuing here would create a new node
2134 2135 # anyway because of the amend_source noise.
2135 2136 #
2136 2137 # This not what we expect from amend.
2137 2138 return old.node()
2138 2139
2139 2140 ph = repo.ui.config('phases', 'new-commit', phases.draft)
2140 2141 try:
2141 2142 if opts.get('secret'):
2142 2143 commitphase = 'secret'
2143 2144 else:
2144 2145 commitphase = old.phase()
2145 2146 repo.ui.setconfig('phases', 'new-commit', commitphase, 'amend')
2146 2147 newid = repo.commitctx(new)
2147 2148 finally:
2148 2149 repo.ui.setconfig('phases', 'new-commit', ph, 'amend')
2149 2150 if newid != old.node():
2150 2151 # Reroute the working copy parent to the new changeset
2151 2152 repo.setparents(newid, nullid)
2152 2153
2153 2154 # Move bookmarks from old parent to amend commit
2154 2155 bms = repo.nodebookmarks(old.node())
2155 2156 if bms:
2156 2157 marks = repo._bookmarks
2157 2158 for bm in bms:
2158 2159 marks[bm] = newid
2159 2160 marks.write()
2160 2161 #commit the whole amend process
2161 2162 if obsolete._enabled and newid != old.node():
2162 2163 # mark the new changeset as successor of the rewritten one
2163 2164 new = repo[newid]
2164 2165 obs = [(old, (new,))]
2165 2166 if node:
2166 2167 obs.append((ctx, ()))
2167 2168
2168 2169 obsolete.createmarkers(repo, obs)
2169 2170 tr.close()
2170 2171 finally:
2171 2172 tr.release()
2172 2173 if (not obsolete._enabled) and newid != old.node():
2173 2174 # Strip the intermediate commit (if there was one) and the amended
2174 2175 # commit
2175 2176 if node:
2176 2177 ui.note(_('stripping intermediate changeset %s\n') % ctx)
2177 2178 ui.note(_('stripping amended changeset %s\n') % old)
2178 2179 repair.strip(ui, repo, old.node(), topic='amend-backup')
2179 2180 finally:
2180 2181 if newid is None:
2181 2182 repo.dirstate.invalidate()
2182 2183 lockmod.release(lock, wlock)
2183 2184 return newid
2184 2185
2185 2186 def commiteditor(repo, ctx, subs, editform=''):
2186 2187 if ctx.description():
2187 2188 return ctx.description()
2188 2189 return commitforceeditor(repo, ctx, subs, editform=editform)
2189 2190
2190 2191 def commitforceeditor(repo, ctx, subs, finishdesc=None, extramsg=None,
2191 2192 editform=''):
2192 2193 if not extramsg:
2193 2194 extramsg = _("Leave message empty to abort commit.")
2194 2195 tmpl = repo.ui.config('committemplate', 'changeset', '').strip()
2195 2196 if tmpl:
2196 2197 committext = buildcommittemplate(repo, ctx, subs, extramsg, tmpl)
2197 2198 else:
2198 2199 committext = buildcommittext(repo, ctx, subs, extramsg)
2199 2200
2200 2201 # run editor in the repository root
2201 2202 olddir = os.getcwd()
2202 2203 os.chdir(repo.root)
2203 2204 text = repo.ui.edit(committext, ctx.user(), ctx.extra())
2204 2205 text = re.sub("(?m)^HG:.*(\n|$)", "", text)
2205 2206 os.chdir(olddir)
2206 2207
2207 2208 if finishdesc:
2208 2209 text = finishdesc(text)
2209 2210 if not text.strip():
2210 2211 raise util.Abort(_("empty commit message"))
2211 2212
2212 2213 return text
2213 2214
2214 2215 def buildcommittemplate(repo, ctx, subs, extramsg, tmpl):
2215 2216 ui = repo.ui
2216 2217 tmpl, mapfile = gettemplate(ui, tmpl, None)
2217 2218
2218 2219 try:
2219 2220 t = changeset_templater(ui, repo, None, {}, tmpl, mapfile, False)
2220 2221 except SyntaxError, inst:
2221 2222 raise util.Abort(inst.args[0])
2222 2223
2223 2224 if not extramsg:
2224 2225 extramsg = '' # ensure that extramsg is string
2225 2226
2226 2227 ui.pushbuffer()
2227 2228 t.show(ctx, extramsg=extramsg)
2228 2229 return ui.popbuffer()
2229 2230
2230 2231 def buildcommittext(repo, ctx, subs, extramsg):
2231 2232 edittext = []
2232 2233 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
2233 2234 if ctx.description():
2234 2235 edittext.append(ctx.description())
2235 2236 edittext.append("")
2236 2237 edittext.append("") # Empty line between message and comments.
2237 2238 edittext.append(_("HG: Enter commit message."
2238 2239 " Lines beginning with 'HG:' are removed."))
2239 2240 edittext.append("HG: %s" % extramsg)
2240 2241 edittext.append("HG: --")
2241 2242 edittext.append(_("HG: user: %s") % ctx.user())
2242 2243 if ctx.p2():
2243 2244 edittext.append(_("HG: branch merge"))
2244 2245 if ctx.branch():
2245 2246 edittext.append(_("HG: branch '%s'") % ctx.branch())
2246 2247 if bookmarks.iscurrent(repo):
2247 2248 edittext.append(_("HG: bookmark '%s'") % repo._bookmarkcurrent)
2248 2249 edittext.extend([_("HG: subrepo %s") % s for s in subs])
2249 2250 edittext.extend([_("HG: added %s") % f for f in added])
2250 2251 edittext.extend([_("HG: changed %s") % f for f in modified])
2251 2252 edittext.extend([_("HG: removed %s") % f for f in removed])
2252 2253 if not added and not modified and not removed:
2253 2254 edittext.append(_("HG: no files changed"))
2254 2255 edittext.append("")
2255 2256
2256 2257 return "\n".join(edittext)
2257 2258
2258 2259 def commitstatus(repo, node, branch, bheads=None, opts={}):
2259 2260 ctx = repo[node]
2260 2261 parents = ctx.parents()
2261 2262
2262 2263 if (not opts.get('amend') and bheads and node not in bheads and not
2263 2264 [x for x in parents if x.node() in bheads and x.branch() == branch]):
2264 2265 repo.ui.status(_('created new head\n'))
2265 2266 # The message is not printed for initial roots. For the other
2266 2267 # changesets, it is printed in the following situations:
2267 2268 #
2268 2269 # Par column: for the 2 parents with ...
2269 2270 # N: null or no parent
2270 2271 # B: parent is on another named branch
2271 2272 # C: parent is a regular non head changeset
2272 2273 # H: parent was a branch head of the current branch
2273 2274 # Msg column: whether we print "created new head" message
2274 2275 # In the following, it is assumed that there already exists some
2275 2276 # initial branch heads of the current branch, otherwise nothing is
2276 2277 # printed anyway.
2277 2278 #
2278 2279 # Par Msg Comment
2279 2280 # N N y additional topo root
2280 2281 #
2281 2282 # B N y additional branch root
2282 2283 # C N y additional topo head
2283 2284 # H N n usual case
2284 2285 #
2285 2286 # B B y weird additional branch root
2286 2287 # C B y branch merge
2287 2288 # H B n merge with named branch
2288 2289 #
2289 2290 # C C y additional head from merge
2290 2291 # C H n merge with a head
2291 2292 #
2292 2293 # H H n head merge: head count decreases
2293 2294
2294 2295 if not opts.get('close_branch'):
2295 2296 for r in parents:
2296 2297 if r.closesbranch() and r.branch() == branch:
2297 2298 repo.ui.status(_('reopening closed branch head %d\n') % r)
2298 2299
2299 2300 if repo.ui.debugflag:
2300 2301 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
2301 2302 elif repo.ui.verbose:
2302 2303 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
2303 2304
2304 2305 def revert(ui, repo, ctx, parents, *pats, **opts):
2305 2306 parent, p2 = parents
2306 2307 node = ctx.node()
2307 2308
2308 2309 mf = ctx.manifest()
2309 2310 if node == p2:
2310 2311 parent = p2
2311 2312 if node == parent:
2312 2313 pmf = mf
2313 2314 else:
2314 2315 pmf = None
2315 2316
2316 2317 # need all matching names in dirstate and manifest of target rev,
2317 2318 # so have to walk both. do not print errors if files exist in one
2318 2319 # but not other.
2319 2320
2320 2321 # `names` is a mapping for all elements in working copy and target revision
2321 2322 # The mapping is in the form:
2322 2323 # <asb path in repo> -> (<path from CWD>, <exactly specified by matcher?>)
2323 2324 names = {}
2324 2325
2325 2326 wlock = repo.wlock()
2326 2327 try:
2327 2328 ## filling of the `names` mapping
2328 2329 # walk dirstate to fill `names`
2329 2330
2330 2331 m = scmutil.match(repo[None], pats, opts)
2331 2332 m.bad = lambda x, y: False
2332 2333 for abs in repo.walk(m):
2333 2334 names[abs] = m.rel(abs), m.exact(abs)
2334 2335
2335 2336 # walk target manifest to fill `names`
2336 2337
2337 2338 def badfn(path, msg):
2338 2339 if path in names:
2339 2340 return
2340 2341 if path in ctx.substate:
2341 2342 return
2342 2343 path_ = path + '/'
2343 2344 for f in names:
2344 2345 if f.startswith(path_):
2345 2346 return
2346 2347 ui.warn("%s: %s\n" % (m.rel(path), msg))
2347 2348
2348 2349 m = scmutil.match(ctx, pats, opts)
2349 2350 m.bad = badfn
2350 2351 for abs in ctx.walk(m):
2351 2352 if abs not in names:
2352 2353 names[abs] = m.rel(abs), m.exact(abs)
2353 2354
2354 2355 # get the list of subrepos that must be reverted
2355 2356 targetsubs = sorted(s for s in ctx.substate if m(s))
2356 2357
2357 2358 # Find status of all file in `names`. (Against working directory parent)
2358 2359 m = scmutil.matchfiles(repo, names)
2359 2360 changes = repo.status(node1=parent, match=m)[:4]
2360 2361 modified, added, removed, deleted = map(set, changes)
2361 2362
2362 2363 # if f is a rename, update `names` to also revert the source
2363 2364 cwd = repo.getcwd()
2364 2365 for f in added:
2365 2366 src = repo.dirstate.copied(f)
2366 2367 if src and src not in names and repo.dirstate[src] == 'r':
2367 2368 removed.add(src)
2368 2369 names[src] = (repo.pathto(src, cwd), True)
2369 2370
2370 2371 ## computation of the action to performs on `names` content.
2371 2372
2372 2373 def removeforget(abs):
2373 2374 if repo.dirstate[abs] == 'a':
2374 2375 return _('forgetting %s\n')
2375 2376 return _('removing %s\n')
2376 2377
2377 2378 # action to be actually performed by revert
2378 2379 # (<list of file>, message>) tuple
2379 2380 actions = {'revert': ([], _('reverting %s\n')),
2380 2381 'add': ([], _('adding %s\n')),
2381 2382 'remove': ([], removeforget),
2382 2383 'undelete': ([], _('undeleting %s\n'))}
2383 2384
2384 2385 disptable = (
2385 2386 # dispatch table:
2386 2387 # file state
2387 2388 # action if in target manifest
2388 2389 # action if not in target manifest
2389 2390 # make backup if in target manifest
2390 2391 # make backup if not in target manifest
2391 2392 (modified, (actions['revert'], True),
2392 2393 (actions['remove'], True)),
2393 2394 (added, (actions['revert'], True),
2394 2395 (actions['remove'], False)),
2395 2396 (removed, (actions['undelete'], True),
2396 2397 (None, False)),
2397 2398 (deleted, (actions['revert'], False),
2398 2399 (actions['remove'], False)),
2399 2400 )
2400 2401
2401 2402 for abs, (rel, exact) in sorted(names.items()):
2402 2403 # hash on file in target manifest (or None if missing from target)
2403 2404 mfentry = mf.get(abs)
2404 2405 # target file to be touch on disk (relative to cwd)
2405 2406 target = repo.wjoin(abs)
2406 2407 def handle(xlist, dobackup):
2407 2408 xlist[0].append(abs)
2408 2409 if (dobackup and not opts.get('no_backup') and
2409 2410 os.path.lexists(target) and
2410 2411 abs in ctx and repo[None][abs].cmp(ctx[abs])):
2411 2412 bakname = "%s.orig" % rel
2412 2413 ui.note(_('saving current version of %s as %s\n') %
2413 2414 (rel, bakname))
2414 2415 if not opts.get('dry_run'):
2415 2416 util.rename(target, bakname)
2416 2417 if ui.verbose or not exact:
2417 2418 msg = xlist[1]
2418 2419 if not isinstance(msg, basestring):
2419 2420 msg = msg(abs)
2420 2421 ui.status(msg % rel)
2421 2422 # search the entry in the dispatch table.
2422 2423 # if the file is in any of this sets, it was touched in the working
2423 2424 # directory parent and we are sure it needs to be reverted.
2424 2425 for table, hit, miss in disptable:
2425 2426 if abs not in table:
2426 2427 continue
2427 2428 # file has changed in dirstate
2428 2429 if mfentry:
2429 2430 handle(*hit)
2430 2431 elif miss[0] is not None:
2431 2432 handle(*miss)
2432 2433 break
2433 2434 else:
2434 2435 # Not touched in current dirstate.
2435 2436
2436 2437 # file is unknown in parent, restore older version or ignore.
2437 2438 if abs not in repo.dirstate:
2438 2439 if mfentry:
2439 2440 handle(actions['add'], True)
2440 2441 elif exact:
2441 2442 ui.warn(_('file not managed: %s\n') % rel)
2442 2443 continue
2443 2444
2444 2445 # parent is target, no changes mean no changes
2445 2446 if node == parent:
2446 2447 if exact:
2447 2448 ui.warn(_('no changes needed to %s\n') % rel)
2448 2449 continue
2449 2450 # no change in dirstate but parent and target may differ
2450 2451 if pmf is None:
2451 2452 # only need parent manifest in this unlikely case,
2452 2453 # so do not read by default
2453 2454 pmf = repo[parent].manifest()
2454 2455 if abs in pmf and mfentry:
2455 2456 # if version of file is same in parent and target
2456 2457 # manifests, do nothing
2457 2458 if (pmf[abs] != mfentry or
2458 2459 pmf.flags(abs) != mf.flags(abs)):
2459 2460 handle(actions['revert'], False)
2460 2461 else:
2461 2462 handle(actions['remove'], False)
2462 2463
2463 2464 if not opts.get('dry_run'):
2464 2465 _performrevert(repo, parents, ctx, actions)
2465 2466
2466 2467 if targetsubs:
2467 2468 # Revert the subrepos on the revert list
2468 2469 for sub in targetsubs:
2469 2470 ctx.sub(sub).revert(ui, ctx.substate[sub], *pats, **opts)
2470 2471 finally:
2471 2472 wlock.release()
2472 2473
2473 2474 def _performrevert(repo, parents, ctx, actions):
2474 2475 """function that actually perform all the actions computed for revert
2475 2476
2476 2477 This is an independent function to let extension to plug in and react to
2477 2478 the imminent revert.
2478 2479
2479 2480 Make sure you have the working directory locked when calling this function.
2480 2481 """
2481 2482 parent, p2 = parents
2482 2483 node = ctx.node()
2483 2484 def checkout(f):
2484 2485 fc = ctx[f]
2485 2486 repo.wwrite(f, fc.data(), fc.flags())
2486 2487
2487 2488 audit_path = pathutil.pathauditor(repo.root)
2488 2489 for f in actions['remove'][0]:
2489 2490 if repo.dirstate[f] == 'a':
2490 2491 repo.dirstate.drop(f)
2491 2492 continue
2492 2493 audit_path(f)
2493 2494 try:
2494 2495 util.unlinkpath(repo.wjoin(f))
2495 2496 except OSError:
2496 2497 pass
2497 2498 repo.dirstate.remove(f)
2498 2499
2499 2500 normal = None
2500 2501 if node == parent:
2501 2502 # We're reverting to our parent. If possible, we'd like status
2502 2503 # to report the file as clean. We have to use normallookup for
2503 2504 # merges to avoid losing information about merged/dirty files.
2504 2505 if p2 != nullid:
2505 2506 normal = repo.dirstate.normallookup
2506 2507 else:
2507 2508 normal = repo.dirstate.normal
2508 2509 for f in actions['revert'][0]:
2509 2510 checkout(f)
2510 2511 if normal:
2511 2512 normal(f)
2512 2513
2513 2514 for f in actions['add'][0]:
2514 2515 checkout(f)
2515 2516 repo.dirstate.add(f)
2516 2517
2517 2518 normal = repo.dirstate.normallookup
2518 2519 if node == parent and p2 == nullid:
2519 2520 normal = repo.dirstate.normal
2520 2521 for f in actions['undelete'][0]:
2521 2522 checkout(f)
2522 2523 normal(f)
2523 2524
2524 2525 copied = copies.pathcopies(repo[parent], ctx)
2525 2526
2526 2527 for f in actions['add'][0] + actions['undelete'][0] + actions['revert'][0]:
2527 2528 if f in copied:
2528 2529 repo.dirstate.copy(copied[f], f)
2529 2530
2530 2531 def command(table):
2531 2532 """Returns a function object to be used as a decorator for making commands.
2532 2533
2533 2534 This function receives a command table as its argument. The table should
2534 2535 be a dict.
2535 2536
2536 2537 The returned function can be used as a decorator for adding commands
2537 2538 to that command table. This function accepts multiple arguments to define
2538 2539 a command.
2539 2540
2540 2541 The first argument is the command name.
2541 2542
2542 2543 The options argument is an iterable of tuples defining command arguments.
2543 2544 See ``mercurial.fancyopts.fancyopts()`` for the format of each tuple.
2544 2545
2545 2546 The synopsis argument defines a short, one line summary of how to use the
2546 2547 command. This shows up in the help output.
2547 2548
2548 2549 The norepo argument defines whether the command does not require a
2549 2550 local repository. Most commands operate against a repository, thus the
2550 2551 default is False.
2551 2552
2552 2553 The optionalrepo argument defines whether the command optionally requires
2553 2554 a local repository.
2554 2555
2555 2556 The inferrepo argument defines whether to try to find a repository from the
2556 2557 command line arguments. If True, arguments will be examined for potential
2557 2558 repository locations. See ``findrepo()``. If a repository is found, it
2558 2559 will be used.
2559 2560 """
2560 2561 def cmd(name, options=(), synopsis=None, norepo=False, optionalrepo=False,
2561 2562 inferrepo=False):
2562 2563 def decorator(func):
2563 2564 if synopsis:
2564 2565 table[name] = func, list(options), synopsis
2565 2566 else:
2566 2567 table[name] = func, list(options)
2567 2568
2568 2569 if norepo:
2569 2570 # Avoid import cycle.
2570 2571 import commands
2571 2572 commands.norepo += ' %s' % ' '.join(parsealiases(name))
2572 2573
2573 2574 if optionalrepo:
2574 2575 import commands
2575 2576 commands.optionalrepo += ' %s' % ' '.join(parsealiases(name))
2576 2577
2577 2578 if inferrepo:
2578 2579 import commands
2579 2580 commands.inferrepo += ' %s' % ' '.join(parsealiases(name))
2580 2581
2581 2582 return func
2582 2583 return decorator
2583 2584
2584 2585 return cmd
2585 2586
2586 2587 # a list of (ui, repo, otherpeer, opts, missing) functions called by
2587 2588 # commands.outgoing. "missing" is "missing" of the result of
2588 2589 # "findcommonoutgoing()"
2589 2590 outgoinghooks = util.hooks()
2590 2591
2591 2592 # a list of (ui, repo) functions called by commands.summary
2592 2593 summaryhooks = util.hooks()
2593 2594
2594 2595 # a list of (ui, repo, opts, changes) functions called by commands.summary.
2595 2596 #
2596 2597 # functions should return tuple of booleans below, if 'changes' is None:
2597 2598 # (whether-incomings-are-needed, whether-outgoings-are-needed)
2598 2599 #
2599 2600 # otherwise, 'changes' is a tuple of tuples below:
2600 2601 # - (sourceurl, sourcebranch, sourcepeer, incoming)
2601 2602 # - (desturl, destbranch, destpeer, outgoing)
2602 2603 summaryremotehooks = util.hooks()
2603 2604
2604 2605 # A list of state files kept by multistep operations like graft.
2605 2606 # Since graft cannot be aborted, it is considered 'clearable' by update.
2606 2607 # note: bisect is intentionally excluded
2607 2608 # (state file, clearable, allowcommit, error, hint)
2608 2609 unfinishedstates = [
2609 2610 ('graftstate', True, False, _('graft in progress'),
2610 2611 _("use 'hg graft --continue' or 'hg update' to abort")),
2611 2612 ('updatestate', True, False, _('last update was interrupted'),
2612 2613 _("use 'hg update' to get a consistent checkout"))
2613 2614 ]
2614 2615
2615 2616 def checkunfinished(repo, commit=False):
2616 2617 '''Look for an unfinished multistep operation, like graft, and abort
2617 2618 if found. It's probably good to check this right before
2618 2619 bailifchanged().
2619 2620 '''
2620 2621 for f, clearable, allowcommit, msg, hint in unfinishedstates:
2621 2622 if commit and allowcommit:
2622 2623 continue
2623 2624 if repo.vfs.exists(f):
2624 2625 raise util.Abort(msg, hint=hint)
2625 2626
2626 2627 def clearunfinished(repo):
2627 2628 '''Check for unfinished operations (as above), and clear the ones
2628 2629 that are clearable.
2629 2630 '''
2630 2631 for f, clearable, allowcommit, msg, hint in unfinishedstates:
2631 2632 if not clearable and repo.vfs.exists(f):
2632 2633 raise util.Abort(msg, hint=hint)
2633 2634 for f, clearable, allowcommit, msg, hint in unfinishedstates:
2634 2635 if clearable and repo.vfs.exists(f):
2635 2636 util.unlink(repo.join(f))
@@ -1,6056 +1,6058
1 1 # commands.py - command processing for mercurial
2 2 #
3 3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 from node import hex, bin, nullid, nullrev, short
9 9 from lock import release
10 10 from i18n import _
11 11 import os, re, difflib, time, tempfile, errno, shlex
12 12 import sys
13 13 import hg, scmutil, util, revlog, copies, error, bookmarks
14 14 import patch, help, encoding, templatekw, discovery
15 15 import archival, changegroup, cmdutil, hbisect
16 16 import sshserver, hgweb, commandserver
17 17 import extensions
18 18 from hgweb import server as hgweb_server
19 19 import merge as mergemod
20 20 import minirst, revset, fileset
21 21 import dagparser, context, simplemerge, graphmod
22 22 import random
23 23 import setdiscovery, treediscovery, dagutil, pvec, localrepo
24 24 import phases, obsolete, exchange
25 25
26 26 table = {}
27 27
28 28 command = cmdutil.command(table)
29 29
30 30 # Space delimited list of commands that don't require local repositories.
31 31 # This should be populated by passing norepo=True into the @command decorator.
32 32 norepo = ''
33 33 # Space delimited list of commands that optionally require local repositories.
34 34 # This should be populated by passing optionalrepo=True into the @command
35 35 # decorator.
36 36 optionalrepo = ''
37 37 # Space delimited list of commands that will examine arguments looking for
38 38 # a repository. This should be populated by passing inferrepo=True into the
39 39 # @command decorator.
40 40 inferrepo = ''
41 41
42 42 # common command options
43 43
44 44 globalopts = [
45 45 ('R', 'repository', '',
46 46 _('repository root directory or name of overlay bundle file'),
47 47 _('REPO')),
48 48 ('', 'cwd', '',
49 49 _('change working directory'), _('DIR')),
50 50 ('y', 'noninteractive', None,
51 51 _('do not prompt, automatically pick the first choice for all prompts')),
52 52 ('q', 'quiet', None, _('suppress output')),
53 53 ('v', 'verbose', None, _('enable additional output')),
54 54 ('', 'config', [],
55 55 _('set/override config option (use \'section.name=value\')'),
56 56 _('CONFIG')),
57 57 ('', 'debug', None, _('enable debugging output')),
58 58 ('', 'debugger', None, _('start debugger')),
59 59 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
60 60 _('ENCODE')),
61 61 ('', 'encodingmode', encoding.encodingmode,
62 62 _('set the charset encoding mode'), _('MODE')),
63 63 ('', 'traceback', None, _('always print a traceback on exception')),
64 64 ('', 'time', None, _('time how long the command takes')),
65 65 ('', 'profile', None, _('print command execution profile')),
66 66 ('', 'version', None, _('output version information and exit')),
67 67 ('h', 'help', None, _('display help and exit')),
68 68 ('', 'hidden', False, _('consider hidden changesets')),
69 69 ]
70 70
71 71 dryrunopts = [('n', 'dry-run', None,
72 72 _('do not perform actions, just print output'))]
73 73
74 74 remoteopts = [
75 75 ('e', 'ssh', '',
76 76 _('specify ssh command to use'), _('CMD')),
77 77 ('', 'remotecmd', '',
78 78 _('specify hg command to run on the remote side'), _('CMD')),
79 79 ('', 'insecure', None,
80 80 _('do not verify server certificate (ignoring web.cacerts config)')),
81 81 ]
82 82
83 83 walkopts = [
84 84 ('I', 'include', [],
85 85 _('include names matching the given patterns'), _('PATTERN')),
86 86 ('X', 'exclude', [],
87 87 _('exclude names matching the given patterns'), _('PATTERN')),
88 88 ]
89 89
90 90 commitopts = [
91 91 ('m', 'message', '',
92 92 _('use text as commit message'), _('TEXT')),
93 93 ('l', 'logfile', '',
94 94 _('read commit message from file'), _('FILE')),
95 95 ]
96 96
97 97 commitopts2 = [
98 98 ('d', 'date', '',
99 99 _('record the specified date as commit date'), _('DATE')),
100 100 ('u', 'user', '',
101 101 _('record the specified user as committer'), _('USER')),
102 102 ]
103 103
104 104 templateopts = [
105 105 ('', 'style', '',
106 106 _('display using template map file (DEPRECATED)'), _('STYLE')),
107 107 ('T', 'template', '',
108 108 _('display with template'), _('TEMPLATE')),
109 109 ]
110 110
111 111 logopts = [
112 112 ('p', 'patch', None, _('show patch')),
113 113 ('g', 'git', None, _('use git extended diff format')),
114 114 ('l', 'limit', '',
115 115 _('limit number of changes displayed'), _('NUM')),
116 116 ('M', 'no-merges', None, _('do not show merges')),
117 117 ('', 'stat', None, _('output diffstat-style summary of changes')),
118 118 ('G', 'graph', None, _("show the revision DAG")),
119 119 ] + templateopts
120 120
121 121 diffopts = [
122 122 ('a', 'text', None, _('treat all files as text')),
123 123 ('g', 'git', None, _('use git extended diff format')),
124 124 ('', 'nodates', None, _('omit dates from diff headers'))
125 125 ]
126 126
127 127 diffwsopts = [
128 128 ('w', 'ignore-all-space', None,
129 129 _('ignore white space when comparing lines')),
130 130 ('b', 'ignore-space-change', None,
131 131 _('ignore changes in the amount of white space')),
132 132 ('B', 'ignore-blank-lines', None,
133 133 _('ignore changes whose lines are all blank')),
134 134 ]
135 135
136 136 diffopts2 = [
137 137 ('p', 'show-function', None, _('show which function each change is in')),
138 138 ('', 'reverse', None, _('produce a diff that undoes the changes')),
139 139 ] + diffwsopts + [
140 140 ('U', 'unified', '',
141 141 _('number of lines of context to show'), _('NUM')),
142 142 ('', 'stat', None, _('output diffstat-style summary of changes')),
143 143 ]
144 144
145 145 mergetoolopts = [
146 146 ('t', 'tool', '', _('specify merge tool')),
147 147 ]
148 148
149 149 similarityopts = [
150 150 ('s', 'similarity', '',
151 151 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
152 152 ]
153 153
154 154 subrepoopts = [
155 155 ('S', 'subrepos', None,
156 156 _('recurse into subrepositories'))
157 157 ]
158 158
159 159 # Commands start here, listed alphabetically
160 160
161 161 @command('^add',
162 162 walkopts + subrepoopts + dryrunopts,
163 163 _('[OPTION]... [FILE]...'),
164 164 inferrepo=True)
165 165 def add(ui, repo, *pats, **opts):
166 166 """add the specified files on the next commit
167 167
168 168 Schedule files to be version controlled and added to the
169 169 repository.
170 170
171 171 The files will be added to the repository at the next commit. To
172 172 undo an add before that, see :hg:`forget`.
173 173
174 174 If no names are given, add all files to the repository.
175 175
176 176 .. container:: verbose
177 177
178 178 An example showing how new (unknown) files are added
179 179 automatically by :hg:`add`::
180 180
181 181 $ ls
182 182 foo.c
183 183 $ hg status
184 184 ? foo.c
185 185 $ hg add
186 186 adding foo.c
187 187 $ hg status
188 188 A foo.c
189 189
190 190 Returns 0 if all files are successfully added.
191 191 """
192 192
193 193 m = scmutil.match(repo[None], pats, opts)
194 194 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
195 195 opts.get('subrepos'), prefix="", explicitonly=False)
196 196 return rejected and 1 or 0
197 197
198 198 @command('addremove',
199 199 similarityopts + walkopts + dryrunopts,
200 200 _('[OPTION]... [FILE]...'),
201 201 inferrepo=True)
202 202 def addremove(ui, repo, *pats, **opts):
203 203 """add all new files, delete all missing files
204 204
205 205 Add all new files and remove all missing files from the
206 206 repository.
207 207
208 208 New files are ignored if they match any of the patterns in
209 209 ``.hgignore``. As with add, these changes take effect at the next
210 210 commit.
211 211
212 212 Use the -s/--similarity option to detect renamed files. This
213 213 option takes a percentage between 0 (disabled) and 100 (files must
214 214 be identical) as its parameter. With a parameter greater than 0,
215 215 this compares every removed file with every added file and records
216 216 those similar enough as renames. Detecting renamed files this way
217 217 can be expensive. After using this option, :hg:`status -C` can be
218 218 used to check which files were identified as moved or renamed. If
219 219 not specified, -s/--similarity defaults to 100 and only renames of
220 220 identical files are detected.
221 221
222 222 Returns 0 if all files are successfully added.
223 223 """
224 224 try:
225 225 sim = float(opts.get('similarity') or 100)
226 226 except ValueError:
227 227 raise util.Abort(_('similarity must be a number'))
228 228 if sim < 0 or sim > 100:
229 229 raise util.Abort(_('similarity must be between 0 and 100'))
230 230 return scmutil.addremove(repo, pats, opts, similarity=sim / 100.0)
231 231
232 232 @command('^annotate|blame',
233 233 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
234 234 ('', 'follow', None,
235 235 _('follow copies/renames and list the filename (DEPRECATED)')),
236 236 ('', 'no-follow', None, _("don't follow copies and renames")),
237 237 ('a', 'text', None, _('treat all files as text')),
238 238 ('u', 'user', None, _('list the author (long with -v)')),
239 239 ('f', 'file', None, _('list the filename')),
240 240 ('d', 'date', None, _('list the date (short with -q)')),
241 241 ('n', 'number', None, _('list the revision number (default)')),
242 242 ('c', 'changeset', None, _('list the changeset')),
243 243 ('l', 'line-number', None, _('show line number at the first appearance'))
244 244 ] + diffwsopts + walkopts,
245 245 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
246 246 inferrepo=True)
247 247 def annotate(ui, repo, *pats, **opts):
248 248 """show changeset information by line for each file
249 249
250 250 List changes in files, showing the revision id responsible for
251 251 each line
252 252
253 253 This command is useful for discovering when a change was made and
254 254 by whom.
255 255
256 256 Without the -a/--text option, annotate will avoid processing files
257 257 it detects as binary. With -a, annotate will annotate the file
258 258 anyway, although the results will probably be neither useful
259 259 nor desirable.
260 260
261 261 Returns 0 on success.
262 262 """
263 263 if opts.get('follow'):
264 264 # --follow is deprecated and now just an alias for -f/--file
265 265 # to mimic the behavior of Mercurial before version 1.5
266 266 opts['file'] = True
267 267
268 268 datefunc = ui.quiet and util.shortdate or util.datestr
269 269 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
270 270
271 271 if not pats:
272 272 raise util.Abort(_('at least one filename or pattern is required'))
273 273
274 274 hexfn = ui.debugflag and hex or short
275 275
276 276 opmap = [('user', ' ', lambda x: ui.shortuser(x[0].user())),
277 277 ('number', ' ', lambda x: str(x[0].rev())),
278 278 ('changeset', ' ', lambda x: hexfn(x[0].node())),
279 279 ('date', ' ', getdate),
280 280 ('file', ' ', lambda x: x[0].path()),
281 281 ('line_number', ':', lambda x: str(x[1])),
282 282 ]
283 283
284 284 if (not opts.get('user') and not opts.get('changeset')
285 285 and not opts.get('date') and not opts.get('file')):
286 286 opts['number'] = True
287 287
288 288 linenumber = opts.get('line_number') is not None
289 289 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
290 290 raise util.Abort(_('at least one of -n/-c is required for -l'))
291 291
292 292 funcmap = [(func, sep) for op, sep, func in opmap if opts.get(op)]
293 293 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
294 294
295 295 def bad(x, y):
296 296 raise util.Abort("%s: %s" % (x, y))
297 297
298 298 ctx = scmutil.revsingle(repo, opts.get('rev'))
299 299 m = scmutil.match(ctx, pats, opts)
300 300 m.bad = bad
301 301 follow = not opts.get('no_follow')
302 302 diffopts = patch.diffopts(ui, opts, section='annotate')
303 303 for abs in ctx.walk(m):
304 304 fctx = ctx[abs]
305 305 if not opts.get('text') and util.binary(fctx.data()):
306 306 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
307 307 continue
308 308
309 309 lines = fctx.annotate(follow=follow, linenumber=linenumber,
310 310 diffopts=diffopts)
311 311 pieces = []
312 312
313 313 for f, sep in funcmap:
314 314 l = [f(n) for n, dummy in lines]
315 315 if l:
316 316 sized = [(x, encoding.colwidth(x)) for x in l]
317 317 ml = max([w for x, w in sized])
318 318 pieces.append(["%s%s%s" % (sep, ' ' * (ml - w), x)
319 319 for x, w in sized])
320 320
321 321 if pieces:
322 322 for p, l in zip(zip(*pieces), lines):
323 323 ui.write("%s: %s" % ("".join(p), l[1]))
324 324
325 325 if lines and not lines[-1][1].endswith('\n'):
326 326 ui.write('\n')
327 327
328 328 @command('archive',
329 329 [('', 'no-decode', None, _('do not pass files through decoders')),
330 330 ('p', 'prefix', '', _('directory prefix for files in archive'),
331 331 _('PREFIX')),
332 332 ('r', 'rev', '', _('revision to distribute'), _('REV')),
333 333 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
334 334 ] + subrepoopts + walkopts,
335 335 _('[OPTION]... DEST'))
336 336 def archive(ui, repo, dest, **opts):
337 337 '''create an unversioned archive of a repository revision
338 338
339 339 By default, the revision used is the parent of the working
340 340 directory; use -r/--rev to specify a different revision.
341 341
342 342 The archive type is automatically detected based on file
343 343 extension (or override using -t/--type).
344 344
345 345 .. container:: verbose
346 346
347 347 Examples:
348 348
349 349 - create a zip file containing the 1.0 release::
350 350
351 351 hg archive -r 1.0 project-1.0.zip
352 352
353 353 - create a tarball excluding .hg files::
354 354
355 355 hg archive project.tar.gz -X ".hg*"
356 356
357 357 Valid types are:
358 358
359 359 :``files``: a directory full of files (default)
360 360 :``tar``: tar archive, uncompressed
361 361 :``tbz2``: tar archive, compressed using bzip2
362 362 :``tgz``: tar archive, compressed using gzip
363 363 :``uzip``: zip archive, uncompressed
364 364 :``zip``: zip archive, compressed using deflate
365 365
366 366 The exact name of the destination archive or directory is given
367 367 using a format string; see :hg:`help export` for details.
368 368
369 369 Each member added to an archive file has a directory prefix
370 370 prepended. Use -p/--prefix to specify a format string for the
371 371 prefix. The default is the basename of the archive, with suffixes
372 372 removed.
373 373
374 374 Returns 0 on success.
375 375 '''
376 376
377 377 ctx = scmutil.revsingle(repo, opts.get('rev'))
378 378 if not ctx:
379 379 raise util.Abort(_('no working directory: please specify a revision'))
380 380 node = ctx.node()
381 381 dest = cmdutil.makefilename(repo, dest, node)
382 382 if os.path.realpath(dest) == repo.root:
383 383 raise util.Abort(_('repository root cannot be destination'))
384 384
385 385 kind = opts.get('type') or archival.guesskind(dest) or 'files'
386 386 prefix = opts.get('prefix')
387 387
388 388 if dest == '-':
389 389 if kind == 'files':
390 390 raise util.Abort(_('cannot archive plain files to stdout'))
391 391 dest = cmdutil.makefileobj(repo, dest)
392 392 if not prefix:
393 393 prefix = os.path.basename(repo.root) + '-%h'
394 394
395 395 prefix = cmdutil.makefilename(repo, prefix, node)
396 396 matchfn = scmutil.match(ctx, [], opts)
397 397 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
398 398 matchfn, prefix, subrepos=opts.get('subrepos'))
399 399
400 400 @command('backout',
401 401 [('', 'merge', None, _('merge with old dirstate parent after backout')),
402 402 ('', 'parent', '',
403 403 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
404 404 ('r', 'rev', '', _('revision to backout'), _('REV')),
405 405 ('e', 'edit', False, _('invoke editor on commit messages')),
406 406 ] + mergetoolopts + walkopts + commitopts + commitopts2,
407 407 _('[OPTION]... [-r] REV'))
408 408 def backout(ui, repo, node=None, rev=None, **opts):
409 409 '''reverse effect of earlier changeset
410 410
411 411 Prepare a new changeset with the effect of REV undone in the
412 412 current working directory.
413 413
414 414 If REV is the parent of the working directory, then this new changeset
415 415 is committed automatically. Otherwise, hg needs to merge the
416 416 changes and the merged result is left uncommitted.
417 417
418 418 .. note::
419 419
420 420 backout cannot be used to fix either an unwanted or
421 421 incorrect merge.
422 422
423 423 .. container:: verbose
424 424
425 425 By default, the pending changeset will have one parent,
426 426 maintaining a linear history. With --merge, the pending
427 427 changeset will instead have two parents: the old parent of the
428 428 working directory and a new child of REV that simply undoes REV.
429 429
430 430 Before version 1.7, the behavior without --merge was equivalent
431 431 to specifying --merge followed by :hg:`update --clean .` to
432 432 cancel the merge and leave the child of REV as a head to be
433 433 merged separately.
434 434
435 435 See :hg:`help dates` for a list of formats valid for -d/--date.
436 436
437 437 Returns 0 on success, 1 if nothing to backout or there are unresolved
438 438 files.
439 439 '''
440 440 if rev and node:
441 441 raise util.Abort(_("please specify just one revision"))
442 442
443 443 if not rev:
444 444 rev = node
445 445
446 446 if not rev:
447 447 raise util.Abort(_("please specify a revision to backout"))
448 448
449 449 date = opts.get('date')
450 450 if date:
451 451 opts['date'] = util.parsedate(date)
452 452
453 453 cmdutil.checkunfinished(repo)
454 454 cmdutil.bailifchanged(repo)
455 455 node = scmutil.revsingle(repo, rev).node()
456 456
457 457 op1, op2 = repo.dirstate.parents()
458 458 if node not in repo.changelog.commonancestorsheads(op1, node):
459 459 raise util.Abort(_('cannot backout change that is not an ancestor'))
460 460
461 461 p1, p2 = repo.changelog.parents(node)
462 462 if p1 == nullid:
463 463 raise util.Abort(_('cannot backout a change with no parents'))
464 464 if p2 != nullid:
465 465 if not opts.get('parent'):
466 466 raise util.Abort(_('cannot backout a merge changeset'))
467 467 p = repo.lookup(opts['parent'])
468 468 if p not in (p1, p2):
469 469 raise util.Abort(_('%s is not a parent of %s') %
470 470 (short(p), short(node)))
471 471 parent = p
472 472 else:
473 473 if opts.get('parent'):
474 474 raise util.Abort(_('cannot use --parent on non-merge changeset'))
475 475 parent = p1
476 476
477 477 # the backout should appear on the same branch
478 478 wlock = repo.wlock()
479 479 try:
480 480 branch = repo.dirstate.branch()
481 481 bheads = repo.branchheads(branch)
482 482 rctx = scmutil.revsingle(repo, hex(parent))
483 483 if not opts.get('merge') and op1 != node:
484 484 try:
485 485 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
486 486 'backout')
487 487 stats = mergemod.update(repo, parent, True, True, False,
488 488 node, False)
489 489 repo.setparents(op1, op2)
490 490 hg._showstats(repo, stats)
491 491 if stats[3]:
492 492 repo.ui.status(_("use 'hg resolve' to retry unresolved "
493 493 "file merges\n"))
494 494 else:
495 495 msg = _("changeset %s backed out, "
496 496 "don't forget to commit.\n")
497 497 ui.status(msg % short(node))
498 498 return stats[3] > 0
499 499 finally:
500 500 ui.setconfig('ui', 'forcemerge', '', '')
501 501 else:
502 502 hg.clean(repo, node, show_stats=False)
503 503 repo.dirstate.setbranch(branch)
504 504 cmdutil.revert(ui, repo, rctx, repo.dirstate.parents())
505 505
506 506
507 507 def commitfunc(ui, repo, message, match, opts):
508 508 editform = 'backout'
509 509 e = cmdutil.getcommiteditor(editform=editform, **opts)
510 510 if not message:
511 511 # we don't translate commit messages
512 512 message = "Backed out changeset %s" % short(node)
513 513 e = cmdutil.getcommiteditor(edit=True, editform=editform)
514 514 return repo.commit(message, opts.get('user'), opts.get('date'),
515 515 match, editor=e)
516 516 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
517 517 if not newnode:
518 518 ui.status(_("nothing changed\n"))
519 519 return 1
520 520 cmdutil.commitstatus(repo, newnode, branch, bheads)
521 521
522 522 def nice(node):
523 523 return '%d:%s' % (repo.changelog.rev(node), short(node))
524 524 ui.status(_('changeset %s backs out changeset %s\n') %
525 525 (nice(repo.changelog.tip()), nice(node)))
526 526 if opts.get('merge') and op1 != node:
527 527 hg.clean(repo, op1, show_stats=False)
528 528 ui.status(_('merging with changeset %s\n')
529 529 % nice(repo.changelog.tip()))
530 530 try:
531 531 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
532 532 'backout')
533 533 return hg.merge(repo, hex(repo.changelog.tip()))
534 534 finally:
535 535 ui.setconfig('ui', 'forcemerge', '', '')
536 536 finally:
537 537 wlock.release()
538 538 return 0
539 539
540 540 @command('bisect',
541 541 [('r', 'reset', False, _('reset bisect state')),
542 542 ('g', 'good', False, _('mark changeset good')),
543 543 ('b', 'bad', False, _('mark changeset bad')),
544 544 ('s', 'skip', False, _('skip testing changeset')),
545 545 ('e', 'extend', False, _('extend the bisect range')),
546 546 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
547 547 ('U', 'noupdate', False, _('do not update to target'))],
548 548 _("[-gbsr] [-U] [-c CMD] [REV]"))
549 549 def bisect(ui, repo, rev=None, extra=None, command=None,
550 550 reset=None, good=None, bad=None, skip=None, extend=None,
551 551 noupdate=None):
552 552 """subdivision search of changesets
553 553
554 554 This command helps to find changesets which introduce problems. To
555 555 use, mark the earliest changeset you know exhibits the problem as
556 556 bad, then mark the latest changeset which is free from the problem
557 557 as good. Bisect will update your working directory to a revision
558 558 for testing (unless the -U/--noupdate option is specified). Once
559 559 you have performed tests, mark the working directory as good or
560 560 bad, and bisect will either update to another candidate changeset
561 561 or announce that it has found the bad revision.
562 562
563 563 As a shortcut, you can also use the revision argument to mark a
564 564 revision as good or bad without checking it out first.
565 565
566 566 If you supply a command, it will be used for automatic bisection.
567 567 The environment variable HG_NODE will contain the ID of the
568 568 changeset being tested. The exit status of the command will be
569 569 used to mark revisions as good or bad: status 0 means good, 125
570 570 means to skip the revision, 127 (command not found) will abort the
571 571 bisection, and any other non-zero exit status means the revision
572 572 is bad.
573 573
574 574 .. container:: verbose
575 575
576 576 Some examples:
577 577
578 578 - start a bisection with known bad revision 34, and good revision 12::
579 579
580 580 hg bisect --bad 34
581 581 hg bisect --good 12
582 582
583 583 - advance the current bisection by marking current revision as good or
584 584 bad::
585 585
586 586 hg bisect --good
587 587 hg bisect --bad
588 588
589 589 - mark the current revision, or a known revision, to be skipped (e.g. if
590 590 that revision is not usable because of another issue)::
591 591
592 592 hg bisect --skip
593 593 hg bisect --skip 23
594 594
595 595 - skip all revisions that do not touch directories ``foo`` or ``bar``::
596 596
597 597 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
598 598
599 599 - forget the current bisection::
600 600
601 601 hg bisect --reset
602 602
603 603 - use 'make && make tests' to automatically find the first broken
604 604 revision::
605 605
606 606 hg bisect --reset
607 607 hg bisect --bad 34
608 608 hg bisect --good 12
609 609 hg bisect --command "make && make tests"
610 610
611 611 - see all changesets whose states are already known in the current
612 612 bisection::
613 613
614 614 hg log -r "bisect(pruned)"
615 615
616 616 - see the changeset currently being bisected (especially useful
617 617 if running with -U/--noupdate)::
618 618
619 619 hg log -r "bisect(current)"
620 620
621 621 - see all changesets that took part in the current bisection::
622 622
623 623 hg log -r "bisect(range)"
624 624
625 625 - you can even get a nice graph::
626 626
627 627 hg log --graph -r "bisect(range)"
628 628
629 629 See :hg:`help revsets` for more about the `bisect()` keyword.
630 630
631 631 Returns 0 on success.
632 632 """
633 633 def extendbisectrange(nodes, good):
634 634 # bisect is incomplete when it ends on a merge node and
635 635 # one of the parent was not checked.
636 636 parents = repo[nodes[0]].parents()
637 637 if len(parents) > 1:
638 638 side = good and state['bad'] or state['good']
639 639 num = len(set(i.node() for i in parents) & set(side))
640 640 if num == 1:
641 641 return parents[0].ancestor(parents[1])
642 642 return None
643 643
644 644 def print_result(nodes, good):
645 645 displayer = cmdutil.show_changeset(ui, repo, {})
646 646 if len(nodes) == 1:
647 647 # narrowed it down to a single revision
648 648 if good:
649 649 ui.write(_("The first good revision is:\n"))
650 650 else:
651 651 ui.write(_("The first bad revision is:\n"))
652 652 displayer.show(repo[nodes[0]])
653 653 extendnode = extendbisectrange(nodes, good)
654 654 if extendnode is not None:
655 655 ui.write(_('Not all ancestors of this changeset have been'
656 656 ' checked.\nUse bisect --extend to continue the '
657 657 'bisection from\nthe common ancestor, %s.\n')
658 658 % extendnode)
659 659 else:
660 660 # multiple possible revisions
661 661 if good:
662 662 ui.write(_("Due to skipped revisions, the first "
663 663 "good revision could be any of:\n"))
664 664 else:
665 665 ui.write(_("Due to skipped revisions, the first "
666 666 "bad revision could be any of:\n"))
667 667 for n in nodes:
668 668 displayer.show(repo[n])
669 669 displayer.close()
670 670
671 671 def check_state(state, interactive=True):
672 672 if not state['good'] or not state['bad']:
673 673 if (good or bad or skip or reset) and interactive:
674 674 return
675 675 if not state['good']:
676 676 raise util.Abort(_('cannot bisect (no known good revisions)'))
677 677 else:
678 678 raise util.Abort(_('cannot bisect (no known bad revisions)'))
679 679 return True
680 680
681 681 # backward compatibility
682 682 if rev in "good bad reset init".split():
683 683 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
684 684 cmd, rev, extra = rev, extra, None
685 685 if cmd == "good":
686 686 good = True
687 687 elif cmd == "bad":
688 688 bad = True
689 689 else:
690 690 reset = True
691 691 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
692 692 raise util.Abort(_('incompatible arguments'))
693 693
694 694 cmdutil.checkunfinished(repo)
695 695
696 696 if reset:
697 697 p = repo.join("bisect.state")
698 698 if os.path.exists(p):
699 699 os.unlink(p)
700 700 return
701 701
702 702 state = hbisect.load_state(repo)
703 703
704 704 if command:
705 705 changesets = 1
706 706 if noupdate:
707 707 try:
708 708 node = state['current'][0]
709 709 except LookupError:
710 710 raise util.Abort(_('current bisect revision is unknown - '
711 711 'start a new bisect to fix'))
712 712 else:
713 713 node, p2 = repo.dirstate.parents()
714 714 if p2 != nullid:
715 715 raise util.Abort(_('current bisect revision is a merge'))
716 716 try:
717 717 while changesets:
718 718 # update state
719 719 state['current'] = [node]
720 720 hbisect.save_state(repo, state)
721 721 status = util.system(command,
722 722 environ={'HG_NODE': hex(node)},
723 723 out=ui.fout)
724 724 if status == 125:
725 725 transition = "skip"
726 726 elif status == 0:
727 727 transition = "good"
728 728 # status < 0 means process was killed
729 729 elif status == 127:
730 730 raise util.Abort(_("failed to execute %s") % command)
731 731 elif status < 0:
732 732 raise util.Abort(_("%s killed") % command)
733 733 else:
734 734 transition = "bad"
735 735 ctx = scmutil.revsingle(repo, rev, node)
736 736 rev = None # clear for future iterations
737 737 state[transition].append(ctx.node())
738 738 ui.status(_('changeset %d:%s: %s\n') % (ctx, ctx, transition))
739 739 check_state(state, interactive=False)
740 740 # bisect
741 741 nodes, changesets, bgood = hbisect.bisect(repo.changelog, state)
742 742 # update to next check
743 743 node = nodes[0]
744 744 if not noupdate:
745 745 cmdutil.bailifchanged(repo)
746 746 hg.clean(repo, node, show_stats=False)
747 747 finally:
748 748 state['current'] = [node]
749 749 hbisect.save_state(repo, state)
750 750 print_result(nodes, bgood)
751 751 return
752 752
753 753 # update state
754 754
755 755 if rev:
756 756 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
757 757 else:
758 758 nodes = [repo.lookup('.')]
759 759
760 760 if good or bad or skip:
761 761 if good:
762 762 state['good'] += nodes
763 763 elif bad:
764 764 state['bad'] += nodes
765 765 elif skip:
766 766 state['skip'] += nodes
767 767 hbisect.save_state(repo, state)
768 768
769 769 if not check_state(state):
770 770 return
771 771
772 772 # actually bisect
773 773 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
774 774 if extend:
775 775 if not changesets:
776 776 extendnode = extendbisectrange(nodes, good)
777 777 if extendnode is not None:
778 778 ui.write(_("Extending search to changeset %d:%s\n")
779 779 % (extendnode.rev(), extendnode))
780 780 state['current'] = [extendnode.node()]
781 781 hbisect.save_state(repo, state)
782 782 if noupdate:
783 783 return
784 784 cmdutil.bailifchanged(repo)
785 785 return hg.clean(repo, extendnode.node())
786 786 raise util.Abort(_("nothing to extend"))
787 787
788 788 if changesets == 0:
789 789 print_result(nodes, good)
790 790 else:
791 791 assert len(nodes) == 1 # only a single node can be tested next
792 792 node = nodes[0]
793 793 # compute the approximate number of remaining tests
794 794 tests, size = 0, 2
795 795 while size <= changesets:
796 796 tests, size = tests + 1, size * 2
797 797 rev = repo.changelog.rev(node)
798 798 ui.write(_("Testing changeset %d:%s "
799 799 "(%d changesets remaining, ~%d tests)\n")
800 800 % (rev, short(node), changesets, tests))
801 801 state['current'] = [node]
802 802 hbisect.save_state(repo, state)
803 803 if not noupdate:
804 804 cmdutil.bailifchanged(repo)
805 805 return hg.clean(repo, node)
806 806
807 807 @command('bookmarks|bookmark',
808 808 [('f', 'force', False, _('force')),
809 809 ('r', 'rev', '', _('revision'), _('REV')),
810 810 ('d', 'delete', False, _('delete a given bookmark')),
811 811 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
812 812 ('i', 'inactive', False, _('mark a bookmark inactive'))],
813 813 _('hg bookmarks [OPTIONS]... [NAME]...'))
814 814 def bookmark(ui, repo, *names, **opts):
815 815 '''create a new bookmark or list existing bookmarks
816 816
817 817 Bookmarks are labels on changesets to help track lines of development.
818 818 Bookmarks are unversioned and can be moved, renamed and deleted.
819 819 Deleting or moving a bookmark has no effect on the associated changesets.
820 820
821 821 Creating or updating to a bookmark causes it to be marked as 'active'.
822 822 Active bookmarks are indicated with a '*'.
823 823 When a commit is made, an active bookmark will advance to the new commit.
824 824 A plain :hg:`update` will also advance an active bookmark, if possible.
825 825 Updating away from a bookmark will cause it to be deactivated.
826 826
827 827 Bookmarks can be pushed and pulled between repositories (see
828 828 :hg:`help push` and :hg:`help pull`). If a shared bookmark has
829 829 diverged, a new 'divergent bookmark' of the form 'name@path' will
830 830 be created. Using :hg:'merge' will resolve the divergence.
831 831
832 832 A bookmark named '@' has the special property that :hg:`clone` will
833 833 check it out by default if it exists.
834 834
835 835 .. container:: verbose
836 836
837 837 Examples:
838 838
839 839 - create an active bookmark for a new line of development::
840 840
841 841 hg book new-feature
842 842
843 843 - create an inactive bookmark as a place marker::
844 844
845 845 hg book -i reviewed
846 846
847 847 - create an inactive bookmark on another changeset::
848 848
849 849 hg book -r .^ tested
850 850
851 851 - move the '@' bookmark from another branch::
852 852
853 853 hg book -f @
854 854 '''
855 855 force = opts.get('force')
856 856 rev = opts.get('rev')
857 857 delete = opts.get('delete')
858 858 rename = opts.get('rename')
859 859 inactive = opts.get('inactive')
860 860
861 861 def checkformat(mark):
862 862 mark = mark.strip()
863 863 if not mark:
864 864 raise util.Abort(_("bookmark names cannot consist entirely of "
865 865 "whitespace"))
866 866 scmutil.checknewlabel(repo, mark, 'bookmark')
867 867 return mark
868 868
869 869 def checkconflict(repo, mark, cur, force=False, target=None):
870 870 if mark in marks and not force:
871 871 if target:
872 872 if marks[mark] == target and target == cur:
873 873 # re-activating a bookmark
874 874 return
875 875 anc = repo.changelog.ancestors([repo[target].rev()])
876 876 bmctx = repo[marks[mark]]
877 877 divs = [repo[b].node() for b in marks
878 878 if b.split('@', 1)[0] == mark.split('@', 1)[0]]
879 879
880 880 # allow resolving a single divergent bookmark even if moving
881 881 # the bookmark across branches when a revision is specified
882 882 # that contains a divergent bookmark
883 883 if bmctx.rev() not in anc and target in divs:
884 884 bookmarks.deletedivergent(repo, [target], mark)
885 885 return
886 886
887 887 deletefrom = [b for b in divs
888 888 if repo[b].rev() in anc or b == target]
889 889 bookmarks.deletedivergent(repo, deletefrom, mark)
890 890 if bookmarks.validdest(repo, bmctx, repo[target]):
891 891 ui.status(_("moving bookmark '%s' forward from %s\n") %
892 892 (mark, short(bmctx.node())))
893 893 return
894 894 raise util.Abort(_("bookmark '%s' already exists "
895 895 "(use -f to force)") % mark)
896 896 if ((mark in repo.branchmap() or mark == repo.dirstate.branch())
897 897 and not force):
898 898 raise util.Abort(
899 899 _("a bookmark cannot have the name of an existing branch"))
900 900
901 901 if delete and rename:
902 902 raise util.Abort(_("--delete and --rename are incompatible"))
903 903 if delete and rev:
904 904 raise util.Abort(_("--rev is incompatible with --delete"))
905 905 if rename and rev:
906 906 raise util.Abort(_("--rev is incompatible with --rename"))
907 907 if not names and (delete or rev):
908 908 raise util.Abort(_("bookmark name required"))
909 909
910 910 if delete or rename or names or inactive:
911 911 wlock = repo.wlock()
912 912 try:
913 913 cur = repo.changectx('.').node()
914 914 marks = repo._bookmarks
915 915 if delete:
916 916 for mark in names:
917 917 if mark not in marks:
918 918 raise util.Abort(_("bookmark '%s' does not exist") %
919 919 mark)
920 920 if mark == repo._bookmarkcurrent:
921 921 bookmarks.unsetcurrent(repo)
922 922 del marks[mark]
923 923 marks.write()
924 924
925 925 elif rename:
926 926 if not names:
927 927 raise util.Abort(_("new bookmark name required"))
928 928 elif len(names) > 1:
929 929 raise util.Abort(_("only one new bookmark name allowed"))
930 930 mark = checkformat(names[0])
931 931 if rename not in marks:
932 932 raise util.Abort(_("bookmark '%s' does not exist") % rename)
933 933 checkconflict(repo, mark, cur, force)
934 934 marks[mark] = marks[rename]
935 935 if repo._bookmarkcurrent == rename and not inactive:
936 936 bookmarks.setcurrent(repo, mark)
937 937 del marks[rename]
938 938 marks.write()
939 939
940 940 elif names:
941 941 newact = None
942 942 for mark in names:
943 943 mark = checkformat(mark)
944 944 if newact is None:
945 945 newact = mark
946 946 if inactive and mark == repo._bookmarkcurrent:
947 947 bookmarks.unsetcurrent(repo)
948 948 return
949 949 tgt = cur
950 950 if rev:
951 951 tgt = scmutil.revsingle(repo, rev).node()
952 952 checkconflict(repo, mark, cur, force, tgt)
953 953 marks[mark] = tgt
954 954 if not inactive and cur == marks[newact] and not rev:
955 955 bookmarks.setcurrent(repo, newact)
956 956 elif cur != tgt and newact == repo._bookmarkcurrent:
957 957 bookmarks.unsetcurrent(repo)
958 958 marks.write()
959 959
960 960 elif inactive:
961 961 if len(marks) == 0:
962 962 ui.status(_("no bookmarks set\n"))
963 963 elif not repo._bookmarkcurrent:
964 964 ui.status(_("no active bookmark\n"))
965 965 else:
966 966 bookmarks.unsetcurrent(repo)
967 967 finally:
968 968 wlock.release()
969 969 else: # show bookmarks
970 970 hexfn = ui.debugflag and hex or short
971 971 marks = repo._bookmarks
972 972 if len(marks) == 0:
973 973 ui.status(_("no bookmarks set\n"))
974 974 else:
975 975 for bmark, n in sorted(marks.iteritems()):
976 976 current = repo._bookmarkcurrent
977 977 if bmark == current:
978 978 prefix, label = '*', 'bookmarks.current'
979 979 else:
980 980 prefix, label = ' ', ''
981 981
982 982 if ui.quiet:
983 983 ui.write("%s\n" % bmark, label=label)
984 984 else:
985 985 pad = " " * (25 - encoding.colwidth(bmark))
986 986 ui.write(" %s %s%s %d:%s\n" % (
987 987 prefix, bmark, pad, repo.changelog.rev(n), hexfn(n)),
988 988 label=label)
989 989
990 990 @command('branch',
991 991 [('f', 'force', None,
992 992 _('set branch name even if it shadows an existing branch')),
993 993 ('C', 'clean', None, _('reset branch name to parent branch name'))],
994 994 _('[-fC] [NAME]'))
995 995 def branch(ui, repo, label=None, **opts):
996 996 """set or show the current branch name
997 997
998 998 .. note::
999 999
1000 1000 Branch names are permanent and global. Use :hg:`bookmark` to create a
1001 1001 light-weight bookmark instead. See :hg:`help glossary` for more
1002 1002 information about named branches and bookmarks.
1003 1003
1004 1004 With no argument, show the current branch name. With one argument,
1005 1005 set the working directory branch name (the branch will not exist
1006 1006 in the repository until the next commit). Standard practice
1007 1007 recommends that primary development take place on the 'default'
1008 1008 branch.
1009 1009
1010 1010 Unless -f/--force is specified, branch will not let you set a
1011 1011 branch name that already exists, even if it's inactive.
1012 1012
1013 1013 Use -C/--clean to reset the working directory branch to that of
1014 1014 the parent of the working directory, negating a previous branch
1015 1015 change.
1016 1016
1017 1017 Use the command :hg:`update` to switch to an existing branch. Use
1018 1018 :hg:`commit --close-branch` to mark this branch as closed.
1019 1019
1020 1020 Returns 0 on success.
1021 1021 """
1022 1022 if label:
1023 1023 label = label.strip()
1024 1024
1025 1025 if not opts.get('clean') and not label:
1026 1026 ui.write("%s\n" % repo.dirstate.branch())
1027 1027 return
1028 1028
1029 1029 wlock = repo.wlock()
1030 1030 try:
1031 1031 if opts.get('clean'):
1032 1032 label = repo[None].p1().branch()
1033 1033 repo.dirstate.setbranch(label)
1034 1034 ui.status(_('reset working directory to branch %s\n') % label)
1035 1035 elif label:
1036 1036 if not opts.get('force') and label in repo.branchmap():
1037 1037 if label not in [p.branch() for p in repo.parents()]:
1038 1038 raise util.Abort(_('a branch of the same name already'
1039 1039 ' exists'),
1040 1040 # i18n: "it" refers to an existing branch
1041 1041 hint=_("use 'hg update' to switch to it"))
1042 1042 scmutil.checknewlabel(repo, label, 'branch')
1043 1043 repo.dirstate.setbranch(label)
1044 1044 ui.status(_('marked working directory as branch %s\n') % label)
1045 1045 ui.status(_('(branches are permanent and global, '
1046 1046 'did you want a bookmark?)\n'))
1047 1047 finally:
1048 1048 wlock.release()
1049 1049
1050 1050 @command('branches',
1051 1051 [('a', 'active', False, _('show only branches that have unmerged heads')),
1052 1052 ('c', 'closed', False, _('show normal and closed branches'))],
1053 1053 _('[-ac]'))
1054 1054 def branches(ui, repo, active=False, closed=False):
1055 1055 """list repository named branches
1056 1056
1057 1057 List the repository's named branches, indicating which ones are
1058 1058 inactive. If -c/--closed is specified, also list branches which have
1059 1059 been marked closed (see :hg:`commit --close-branch`).
1060 1060
1061 1061 If -a/--active is specified, only show active branches. A branch
1062 1062 is considered active if it contains repository heads.
1063 1063
1064 1064 Use the command :hg:`update` to switch to an existing branch.
1065 1065
1066 1066 Returns 0.
1067 1067 """
1068 1068
1069 1069 hexfunc = ui.debugflag and hex or short
1070 1070
1071 1071 allheads = set(repo.heads())
1072 1072 branches = []
1073 1073 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1074 1074 isactive = not isclosed and bool(set(heads) & allheads)
1075 1075 branches.append((tag, repo[tip], isactive, not isclosed))
1076 1076 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]),
1077 1077 reverse=True)
1078 1078
1079 1079 for tag, ctx, isactive, isopen in branches:
1080 1080 if (not active) or isactive:
1081 1081 if isactive:
1082 1082 label = 'branches.active'
1083 1083 notice = ''
1084 1084 elif not isopen:
1085 1085 if not closed:
1086 1086 continue
1087 1087 label = 'branches.closed'
1088 1088 notice = _(' (closed)')
1089 1089 else:
1090 1090 label = 'branches.inactive'
1091 1091 notice = _(' (inactive)')
1092 1092 if tag == repo.dirstate.branch():
1093 1093 label = 'branches.current'
1094 1094 rev = str(ctx.rev()).rjust(31 - encoding.colwidth(tag))
1095 1095 rev = ui.label('%s:%s' % (rev, hexfunc(ctx.node())),
1096 1096 'log.changeset changeset.%s' % ctx.phasestr())
1097 1097 labeledtag = ui.label(tag, label)
1098 1098 if ui.quiet:
1099 1099 ui.write("%s\n" % labeledtag)
1100 1100 else:
1101 1101 ui.write("%s %s%s\n" % (labeledtag, rev, notice))
1102 1102
1103 1103 @command('bundle',
1104 1104 [('f', 'force', None, _('run even when the destination is unrelated')),
1105 1105 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1106 1106 _('REV')),
1107 1107 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1108 1108 _('BRANCH')),
1109 1109 ('', 'base', [],
1110 1110 _('a base changeset assumed to be available at the destination'),
1111 1111 _('REV')),
1112 1112 ('a', 'all', None, _('bundle all changesets in the repository')),
1113 1113 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1114 1114 ] + remoteopts,
1115 1115 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
1116 1116 def bundle(ui, repo, fname, dest=None, **opts):
1117 1117 """create a changegroup file
1118 1118
1119 1119 Generate a compressed changegroup file collecting changesets not
1120 1120 known to be in another repository.
1121 1121
1122 1122 If you omit the destination repository, then hg assumes the
1123 1123 destination will have all the nodes you specify with --base
1124 1124 parameters. To create a bundle containing all changesets, use
1125 1125 -a/--all (or --base null).
1126 1126
1127 1127 You can change compression method with the -t/--type option.
1128 1128 The available compression methods are: none, bzip2, and
1129 1129 gzip (by default, bundles are compressed using bzip2).
1130 1130
1131 1131 The bundle file can then be transferred using conventional means
1132 1132 and applied to another repository with the unbundle or pull
1133 1133 command. This is useful when direct push and pull are not
1134 1134 available or when exporting an entire repository is undesirable.
1135 1135
1136 1136 Applying bundles preserves all changeset contents including
1137 1137 permissions, copy/rename information, and revision history.
1138 1138
1139 1139 Returns 0 on success, 1 if no changes found.
1140 1140 """
1141 1141 revs = None
1142 1142 if 'rev' in opts:
1143 1143 revs = scmutil.revrange(repo, opts['rev'])
1144 1144
1145 1145 bundletype = opts.get('type', 'bzip2').lower()
1146 1146 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1147 1147 bundletype = btypes.get(bundletype)
1148 1148 if bundletype not in changegroup.bundletypes:
1149 1149 raise util.Abort(_('unknown bundle type specified with --type'))
1150 1150
1151 1151 if opts.get('all'):
1152 1152 base = ['null']
1153 1153 else:
1154 1154 base = scmutil.revrange(repo, opts.get('base'))
1155 1155 # TODO: get desired bundlecaps from command line.
1156 1156 bundlecaps = None
1157 1157 if base:
1158 1158 if dest:
1159 1159 raise util.Abort(_("--base is incompatible with specifying "
1160 1160 "a destination"))
1161 1161 common = [repo.lookup(rev) for rev in base]
1162 1162 heads = revs and map(repo.lookup, revs) or revs
1163 1163 cg = changegroup.getbundle(repo, 'bundle', heads=heads, common=common,
1164 1164 bundlecaps=bundlecaps)
1165 1165 outgoing = None
1166 1166 else:
1167 1167 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1168 1168 dest, branches = hg.parseurl(dest, opts.get('branch'))
1169 1169 other = hg.peer(repo, opts, dest)
1170 1170 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1171 1171 heads = revs and map(repo.lookup, revs) or revs
1172 1172 outgoing = discovery.findcommonoutgoing(repo, other,
1173 1173 onlyheads=heads,
1174 1174 force=opts.get('force'),
1175 1175 portable=True)
1176 1176 cg = changegroup.getlocalbundle(repo, 'bundle', outgoing, bundlecaps)
1177 1177 if not cg:
1178 1178 scmutil.nochangesfound(ui, repo, outgoing and outgoing.excluded)
1179 1179 return 1
1180 1180
1181 1181 changegroup.writebundle(cg, fname, bundletype)
1182 1182
1183 1183 @command('cat',
1184 1184 [('o', 'output', '',
1185 1185 _('print output to file with formatted name'), _('FORMAT')),
1186 1186 ('r', 'rev', '', _('print the given revision'), _('REV')),
1187 1187 ('', 'decode', None, _('apply any matching decode filter')),
1188 1188 ] + walkopts,
1189 1189 _('[OPTION]... FILE...'),
1190 1190 inferrepo=True)
1191 1191 def cat(ui, repo, file1, *pats, **opts):
1192 1192 """output the current or given revision of files
1193 1193
1194 1194 Print the specified files as they were at the given revision. If
1195 1195 no revision is given, the parent of the working directory is used.
1196 1196
1197 1197 Output may be to a file, in which case the name of the file is
1198 1198 given using a format string. The formatting rules as follows:
1199 1199
1200 1200 :``%%``: literal "%" character
1201 1201 :``%s``: basename of file being printed
1202 1202 :``%d``: dirname of file being printed, or '.' if in repository root
1203 1203 :``%p``: root-relative path name of file being printed
1204 1204 :``%H``: changeset hash (40 hexadecimal digits)
1205 1205 :``%R``: changeset revision number
1206 1206 :``%h``: short-form changeset hash (12 hexadecimal digits)
1207 1207 :``%r``: zero-padded changeset revision number
1208 1208 :``%b``: basename of the exporting repository
1209 1209
1210 1210 Returns 0 on success.
1211 1211 """
1212 1212 ctx = scmutil.revsingle(repo, opts.get('rev'))
1213 1213 m = scmutil.match(ctx, (file1,) + pats, opts)
1214 1214
1215 1215 return cmdutil.cat(ui, repo, ctx, m, '', **opts)
1216 1216
1217 1217 @command('^clone',
1218 1218 [('U', 'noupdate', None,
1219 1219 _('the clone will include an empty working copy (only a repository)')),
1220 1220 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
1221 1221 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1222 1222 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1223 1223 ('', 'pull', None, _('use pull protocol to copy metadata')),
1224 1224 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1225 1225 ] + remoteopts,
1226 1226 _('[OPTION]... SOURCE [DEST]'),
1227 1227 norepo=True)
1228 1228 def clone(ui, source, dest=None, **opts):
1229 1229 """make a copy of an existing repository
1230 1230
1231 1231 Create a copy of an existing repository in a new directory.
1232 1232
1233 1233 If no destination directory name is specified, it defaults to the
1234 1234 basename of the source.
1235 1235
1236 1236 The location of the source is added to the new repository's
1237 1237 ``.hg/hgrc`` file, as the default to be used for future pulls.
1238 1238
1239 1239 Only local paths and ``ssh://`` URLs are supported as
1240 1240 destinations. For ``ssh://`` destinations, no working directory or
1241 1241 ``.hg/hgrc`` will be created on the remote side.
1242 1242
1243 1243 To pull only a subset of changesets, specify one or more revisions
1244 1244 identifiers with -r/--rev or branches with -b/--branch. The
1245 1245 resulting clone will contain only the specified changesets and
1246 1246 their ancestors. These options (or 'clone src#rev dest') imply
1247 1247 --pull, even for local source repositories. Note that specifying a
1248 1248 tag will include the tagged changeset but not the changeset
1249 1249 containing the tag.
1250 1250
1251 1251 If the source repository has a bookmark called '@' set, that
1252 1252 revision will be checked out in the new repository by default.
1253 1253
1254 1254 To check out a particular version, use -u/--update, or
1255 1255 -U/--noupdate to create a clone with no working directory.
1256 1256
1257 1257 .. container:: verbose
1258 1258
1259 1259 For efficiency, hardlinks are used for cloning whenever the
1260 1260 source and destination are on the same filesystem (note this
1261 1261 applies only to the repository data, not to the working
1262 1262 directory). Some filesystems, such as AFS, implement hardlinking
1263 1263 incorrectly, but do not report errors. In these cases, use the
1264 1264 --pull option to avoid hardlinking.
1265 1265
1266 1266 In some cases, you can clone repositories and the working
1267 1267 directory using full hardlinks with ::
1268 1268
1269 1269 $ cp -al REPO REPOCLONE
1270 1270
1271 1271 This is the fastest way to clone, but it is not always safe. The
1272 1272 operation is not atomic (making sure REPO is not modified during
1273 1273 the operation is up to you) and you have to make sure your
1274 1274 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1275 1275 so). Also, this is not compatible with certain extensions that
1276 1276 place their metadata under the .hg directory, such as mq.
1277 1277
1278 1278 Mercurial will update the working directory to the first applicable
1279 1279 revision from this list:
1280 1280
1281 1281 a) null if -U or the source repository has no changesets
1282 1282 b) if -u . and the source repository is local, the first parent of
1283 1283 the source repository's working directory
1284 1284 c) the changeset specified with -u (if a branch name, this means the
1285 1285 latest head of that branch)
1286 1286 d) the changeset specified with -r
1287 1287 e) the tipmost head specified with -b
1288 1288 f) the tipmost head specified with the url#branch source syntax
1289 1289 g) the revision marked with the '@' bookmark, if present
1290 1290 h) the tipmost head of the default branch
1291 1291 i) tip
1292 1292
1293 1293 Examples:
1294 1294
1295 1295 - clone a remote repository to a new directory named hg/::
1296 1296
1297 1297 hg clone http://selenic.com/hg
1298 1298
1299 1299 - create a lightweight local clone::
1300 1300
1301 1301 hg clone project/ project-feature/
1302 1302
1303 1303 - clone from an absolute path on an ssh server (note double-slash)::
1304 1304
1305 1305 hg clone ssh://user@server//home/projects/alpha/
1306 1306
1307 1307 - do a high-speed clone over a LAN while checking out a
1308 1308 specified version::
1309 1309
1310 1310 hg clone --uncompressed http://server/repo -u 1.5
1311 1311
1312 1312 - create a repository without changesets after a particular revision::
1313 1313
1314 1314 hg clone -r 04e544 experimental/ good/
1315 1315
1316 1316 - clone (and track) a particular named branch::
1317 1317
1318 1318 hg clone http://selenic.com/hg#stable
1319 1319
1320 1320 See :hg:`help urls` for details on specifying URLs.
1321 1321
1322 1322 Returns 0 on success.
1323 1323 """
1324 1324 if opts.get('noupdate') and opts.get('updaterev'):
1325 1325 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1326 1326
1327 1327 r = hg.clone(ui, opts, source, dest,
1328 1328 pull=opts.get('pull'),
1329 1329 stream=opts.get('uncompressed'),
1330 1330 rev=opts.get('rev'),
1331 1331 update=opts.get('updaterev') or not opts.get('noupdate'),
1332 1332 branch=opts.get('branch'))
1333 1333
1334 1334 return r is None
1335 1335
1336 1336 @command('^commit|ci',
1337 1337 [('A', 'addremove', None,
1338 1338 _('mark new/missing files as added/removed before committing')),
1339 1339 ('', 'close-branch', None,
1340 1340 _('mark a branch as closed, hiding it from the branch list')),
1341 1341 ('', 'amend', None, _('amend the parent of the working dir')),
1342 1342 ('s', 'secret', None, _('use the secret phase for committing')),
1343 1343 ('e', 'edit', None, _('invoke editor on commit messages')),
1344 1344 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1345 1345 _('[OPTION]... [FILE]...'),
1346 1346 inferrepo=True)
1347 1347 def commit(ui, repo, *pats, **opts):
1348 1348 """commit the specified files or all outstanding changes
1349 1349
1350 1350 Commit changes to the given files into the repository. Unlike a
1351 1351 centralized SCM, this operation is a local operation. See
1352 1352 :hg:`push` for a way to actively distribute your changes.
1353 1353
1354 1354 If a list of files is omitted, all changes reported by :hg:`status`
1355 1355 will be committed.
1356 1356
1357 1357 If you are committing the result of a merge, do not provide any
1358 1358 filenames or -I/-X filters.
1359 1359
1360 1360 If no commit message is specified, Mercurial starts your
1361 1361 configured editor where you can enter a message. In case your
1362 1362 commit fails, you will find a backup of your message in
1363 1363 ``.hg/last-message.txt``.
1364 1364
1365 1365 The --amend flag can be used to amend the parent of the
1366 1366 working directory with a new commit that contains the changes
1367 1367 in the parent in addition to those currently reported by :hg:`status`,
1368 1368 if there are any. The old commit is stored in a backup bundle in
1369 1369 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1370 1370 on how to restore it).
1371 1371
1372 1372 Message, user and date are taken from the amended commit unless
1373 1373 specified. When a message isn't specified on the command line,
1374 1374 the editor will open with the message of the amended commit.
1375 1375
1376 1376 It is not possible to amend public changesets (see :hg:`help phases`)
1377 1377 or changesets that have children.
1378 1378
1379 1379 See :hg:`help dates` for a list of formats valid for -d/--date.
1380 1380
1381 1381 Returns 0 on success, 1 if nothing changed.
1382 1382 """
1383 1383 if opts.get('subrepos'):
1384 1384 if opts.get('amend'):
1385 1385 raise util.Abort(_('cannot amend with --subrepos'))
1386 1386 # Let --subrepos on the command line override config setting.
1387 1387 ui.setconfig('ui', 'commitsubrepos', True, 'commit')
1388 1388
1389 1389 # Save this for restoring it later
1390 1390 oldcommitphase = ui.config('phases', 'new-commit')
1391 1391
1392 1392 cmdutil.checkunfinished(repo, commit=True)
1393 1393
1394 1394 branch = repo[None].branch()
1395 1395 bheads = repo.branchheads(branch)
1396 1396
1397 1397 extra = {}
1398 1398 if opts.get('close_branch'):
1399 1399 extra['close'] = 1
1400 1400
1401 1401 if not bheads:
1402 1402 raise util.Abort(_('can only close branch heads'))
1403 1403 elif opts.get('amend'):
1404 1404 if repo.parents()[0].p1().branch() != branch and \
1405 1405 repo.parents()[0].p2().branch() != branch:
1406 1406 raise util.Abort(_('can only close branch heads'))
1407 1407
1408 1408 if opts.get('amend'):
1409 1409 if ui.configbool('ui', 'commitsubrepos'):
1410 1410 raise util.Abort(_('cannot amend with ui.commitsubrepos enabled'))
1411 1411
1412 1412 old = repo['.']
1413 1413 if old.phase() == phases.public:
1414 1414 raise util.Abort(_('cannot amend public changesets'))
1415 1415 if len(repo[None].parents()) > 1:
1416 1416 raise util.Abort(_('cannot amend while merging'))
1417 1417 if (not obsolete._enabled) and old.children():
1418 1418 raise util.Abort(_('cannot amend changeset with children'))
1419 1419
1420 1420 # commitfunc is used only for temporary amend commit by cmdutil.amend
1421 1421 def commitfunc(ui, repo, message, match, opts):
1422 1422 return repo.commit(message,
1423 1423 opts.get('user') or old.user(),
1424 1424 opts.get('date') or old.date(),
1425 1425 match,
1426 1426 extra=extra)
1427 1427
1428 1428 current = repo._bookmarkcurrent
1429 1429 marks = old.bookmarks()
1430 1430 node = cmdutil.amend(ui, repo, commitfunc, old, extra, pats, opts)
1431 1431 if node == old.node():
1432 1432 ui.status(_("nothing changed\n"))
1433 1433 return 1
1434 1434 elif marks:
1435 1435 ui.debug('moving bookmarks %r from %s to %s\n' %
1436 1436 (marks, old.hex(), hex(node)))
1437 1437 newmarks = repo._bookmarks
1438 1438 for bm in marks:
1439 1439 newmarks[bm] = node
1440 1440 if bm == current:
1441 1441 bookmarks.setcurrent(repo, bm)
1442 1442 newmarks.write()
1443 1443 else:
1444 1444 def commitfunc(ui, repo, message, match, opts):
1445 1445 try:
1446 1446 if opts.get('secret'):
1447 1447 ui.setconfig('phases', 'new-commit', 'secret', 'commit')
1448 1448 # Propagate to subrepos
1449 1449 repo.baseui.setconfig('phases', 'new-commit', 'secret',
1450 1450 'commit')
1451 1451
1452 editform = 'commit.normal'
1453 editor = cmdutil.getcommiteditor(editform=editform, **opts)
1452 1454 return repo.commit(message, opts.get('user'), opts.get('date'),
1453 1455 match,
1454 editor=cmdutil.getcommiteditor(**opts),
1456 editor=editor,
1455 1457 extra=extra)
1456 1458 finally:
1457 1459 ui.setconfig('phases', 'new-commit', oldcommitphase, 'commit')
1458 1460 repo.baseui.setconfig('phases', 'new-commit', oldcommitphase,
1459 1461 'commit')
1460 1462
1461 1463
1462 1464 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1463 1465
1464 1466 if not node:
1465 1467 stat = repo.status(match=scmutil.match(repo[None], pats, opts))
1466 1468 if stat[3]:
1467 1469 ui.status(_("nothing changed (%d missing files, see "
1468 1470 "'hg status')\n") % len(stat[3]))
1469 1471 else:
1470 1472 ui.status(_("nothing changed\n"))
1471 1473 return 1
1472 1474
1473 1475 cmdutil.commitstatus(repo, node, branch, bheads, opts)
1474 1476
1475 1477 @command('config|showconfig|debugconfig',
1476 1478 [('u', 'untrusted', None, _('show untrusted configuration options')),
1477 1479 ('e', 'edit', None, _('edit user config')),
1478 1480 ('l', 'local', None, _('edit repository config')),
1479 1481 ('g', 'global', None, _('edit global config'))],
1480 1482 _('[-u] [NAME]...'),
1481 1483 optionalrepo=True)
1482 1484 def config(ui, repo, *values, **opts):
1483 1485 """show combined config settings from all hgrc files
1484 1486
1485 1487 With no arguments, print names and values of all config items.
1486 1488
1487 1489 With one argument of the form section.name, print just the value
1488 1490 of that config item.
1489 1491
1490 1492 With multiple arguments, print names and values of all config
1491 1493 items with matching section names.
1492 1494
1493 1495 With --edit, start an editor on the user-level config file. With
1494 1496 --global, edit the system-wide config file. With --local, edit the
1495 1497 repository-level config file.
1496 1498
1497 1499 With --debug, the source (filename and line number) is printed
1498 1500 for each config item.
1499 1501
1500 1502 See :hg:`help config` for more information about config files.
1501 1503
1502 1504 Returns 0 on success.
1503 1505
1504 1506 """
1505 1507
1506 1508 if opts.get('edit') or opts.get('local') or opts.get('global'):
1507 1509 if opts.get('local') and opts.get('global'):
1508 1510 raise util.Abort(_("can't use --local and --global together"))
1509 1511
1510 1512 if opts.get('local'):
1511 1513 if not repo:
1512 1514 raise util.Abort(_("can't use --local outside a repository"))
1513 1515 paths = [repo.join('hgrc')]
1514 1516 elif opts.get('global'):
1515 1517 paths = scmutil.systemrcpath()
1516 1518 else:
1517 1519 paths = scmutil.userrcpath()
1518 1520
1519 1521 for f in paths:
1520 1522 if os.path.exists(f):
1521 1523 break
1522 1524 else:
1523 1525 f = paths[0]
1524 1526 fp = open(f, "w")
1525 1527 fp.write(
1526 1528 '# example config (see "hg help config" for more info)\n'
1527 1529 '\n'
1528 1530 '[ui]\n'
1529 1531 '# name and email, e.g.\n'
1530 1532 '# username = Jane Doe <jdoe@example.com>\n'
1531 1533 'username =\n'
1532 1534 '\n'
1533 1535 '[extensions]\n'
1534 1536 '# uncomment these lines to enable some popular extensions\n'
1535 1537 '# (see "hg help extensions" for more info)\n'
1536 1538 '# pager =\n'
1537 1539 '# progress =\n'
1538 1540 '# color =\n')
1539 1541 fp.close()
1540 1542
1541 1543 editor = ui.geteditor()
1542 1544 util.system("%s \"%s\"" % (editor, f),
1543 1545 onerr=util.Abort, errprefix=_("edit failed"),
1544 1546 out=ui.fout)
1545 1547 return
1546 1548
1547 1549 for f in scmutil.rcpath():
1548 1550 ui.debug('read config from: %s\n' % f)
1549 1551 untrusted = bool(opts.get('untrusted'))
1550 1552 if values:
1551 1553 sections = [v for v in values if '.' not in v]
1552 1554 items = [v for v in values if '.' in v]
1553 1555 if len(items) > 1 or items and sections:
1554 1556 raise util.Abort(_('only one config item permitted'))
1555 1557 for section, name, value in ui.walkconfig(untrusted=untrusted):
1556 1558 value = str(value).replace('\n', '\\n')
1557 1559 sectname = section + '.' + name
1558 1560 if values:
1559 1561 for v in values:
1560 1562 if v == section:
1561 1563 ui.debug('%s: ' %
1562 1564 ui.configsource(section, name, untrusted))
1563 1565 ui.write('%s=%s\n' % (sectname, value))
1564 1566 elif v == sectname:
1565 1567 ui.debug('%s: ' %
1566 1568 ui.configsource(section, name, untrusted))
1567 1569 ui.write(value, '\n')
1568 1570 else:
1569 1571 ui.debug('%s: ' %
1570 1572 ui.configsource(section, name, untrusted))
1571 1573 ui.write('%s=%s\n' % (sectname, value))
1572 1574
1573 1575 @command('copy|cp',
1574 1576 [('A', 'after', None, _('record a copy that has already occurred')),
1575 1577 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1576 1578 ] + walkopts + dryrunopts,
1577 1579 _('[OPTION]... [SOURCE]... DEST'))
1578 1580 def copy(ui, repo, *pats, **opts):
1579 1581 """mark files as copied for the next commit
1580 1582
1581 1583 Mark dest as having copies of source files. If dest is a
1582 1584 directory, copies are put in that directory. If dest is a file,
1583 1585 the source must be a single file.
1584 1586
1585 1587 By default, this command copies the contents of files as they
1586 1588 exist in the working directory. If invoked with -A/--after, the
1587 1589 operation is recorded, but no copying is performed.
1588 1590
1589 1591 This command takes effect with the next commit. To undo a copy
1590 1592 before that, see :hg:`revert`.
1591 1593
1592 1594 Returns 0 on success, 1 if errors are encountered.
1593 1595 """
1594 1596 wlock = repo.wlock(False)
1595 1597 try:
1596 1598 return cmdutil.copy(ui, repo, pats, opts)
1597 1599 finally:
1598 1600 wlock.release()
1599 1601
1600 1602 @command('debugancestor', [], _('[INDEX] REV1 REV2'), optionalrepo=True)
1601 1603 def debugancestor(ui, repo, *args):
1602 1604 """find the ancestor revision of two revisions in a given index"""
1603 1605 if len(args) == 3:
1604 1606 index, rev1, rev2 = args
1605 1607 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1606 1608 lookup = r.lookup
1607 1609 elif len(args) == 2:
1608 1610 if not repo:
1609 1611 raise util.Abort(_("there is no Mercurial repository here "
1610 1612 "(.hg not found)"))
1611 1613 rev1, rev2 = args
1612 1614 r = repo.changelog
1613 1615 lookup = repo.lookup
1614 1616 else:
1615 1617 raise util.Abort(_('either two or three arguments required'))
1616 1618 a = r.ancestor(lookup(rev1), lookup(rev2))
1617 1619 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1618 1620
1619 1621 @command('debugbuilddag',
1620 1622 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1621 1623 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1622 1624 ('n', 'new-file', None, _('add new file at each rev'))],
1623 1625 _('[OPTION]... [TEXT]'))
1624 1626 def debugbuilddag(ui, repo, text=None,
1625 1627 mergeable_file=False,
1626 1628 overwritten_file=False,
1627 1629 new_file=False):
1628 1630 """builds a repo with a given DAG from scratch in the current empty repo
1629 1631
1630 1632 The description of the DAG is read from stdin if not given on the
1631 1633 command line.
1632 1634
1633 1635 Elements:
1634 1636
1635 1637 - "+n" is a linear run of n nodes based on the current default parent
1636 1638 - "." is a single node based on the current default parent
1637 1639 - "$" resets the default parent to null (implied at the start);
1638 1640 otherwise the default parent is always the last node created
1639 1641 - "<p" sets the default parent to the backref p
1640 1642 - "*p" is a fork at parent p, which is a backref
1641 1643 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1642 1644 - "/p2" is a merge of the preceding node and p2
1643 1645 - ":tag" defines a local tag for the preceding node
1644 1646 - "@branch" sets the named branch for subsequent nodes
1645 1647 - "#...\\n" is a comment up to the end of the line
1646 1648
1647 1649 Whitespace between the above elements is ignored.
1648 1650
1649 1651 A backref is either
1650 1652
1651 1653 - a number n, which references the node curr-n, where curr is the current
1652 1654 node, or
1653 1655 - the name of a local tag you placed earlier using ":tag", or
1654 1656 - empty to denote the default parent.
1655 1657
1656 1658 All string valued-elements are either strictly alphanumeric, or must
1657 1659 be enclosed in double quotes ("..."), with "\\" as escape character.
1658 1660 """
1659 1661
1660 1662 if text is None:
1661 1663 ui.status(_("reading DAG from stdin\n"))
1662 1664 text = ui.fin.read()
1663 1665
1664 1666 cl = repo.changelog
1665 1667 if len(cl) > 0:
1666 1668 raise util.Abort(_('repository is not empty'))
1667 1669
1668 1670 # determine number of revs in DAG
1669 1671 total = 0
1670 1672 for type, data in dagparser.parsedag(text):
1671 1673 if type == 'n':
1672 1674 total += 1
1673 1675
1674 1676 if mergeable_file:
1675 1677 linesperrev = 2
1676 1678 # make a file with k lines per rev
1677 1679 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1678 1680 initialmergedlines.append("")
1679 1681
1680 1682 tags = []
1681 1683
1682 1684 lock = tr = None
1683 1685 try:
1684 1686 lock = repo.lock()
1685 1687 tr = repo.transaction("builddag")
1686 1688
1687 1689 at = -1
1688 1690 atbranch = 'default'
1689 1691 nodeids = []
1690 1692 id = 0
1691 1693 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1692 1694 for type, data in dagparser.parsedag(text):
1693 1695 if type == 'n':
1694 1696 ui.note(('node %s\n' % str(data)))
1695 1697 id, ps = data
1696 1698
1697 1699 files = []
1698 1700 fctxs = {}
1699 1701
1700 1702 p2 = None
1701 1703 if mergeable_file:
1702 1704 fn = "mf"
1703 1705 p1 = repo[ps[0]]
1704 1706 if len(ps) > 1:
1705 1707 p2 = repo[ps[1]]
1706 1708 pa = p1.ancestor(p2)
1707 1709 base, local, other = [x[fn].data() for x in (pa, p1,
1708 1710 p2)]
1709 1711 m3 = simplemerge.Merge3Text(base, local, other)
1710 1712 ml = [l.strip() for l in m3.merge_lines()]
1711 1713 ml.append("")
1712 1714 elif at > 0:
1713 1715 ml = p1[fn].data().split("\n")
1714 1716 else:
1715 1717 ml = initialmergedlines
1716 1718 ml[id * linesperrev] += " r%i" % id
1717 1719 mergedtext = "\n".join(ml)
1718 1720 files.append(fn)
1719 1721 fctxs[fn] = context.memfilectx(repo, fn, mergedtext)
1720 1722
1721 1723 if overwritten_file:
1722 1724 fn = "of"
1723 1725 files.append(fn)
1724 1726 fctxs[fn] = context.memfilectx(repo, fn, "r%i\n" % id)
1725 1727
1726 1728 if new_file:
1727 1729 fn = "nf%i" % id
1728 1730 files.append(fn)
1729 1731 fctxs[fn] = context.memfilectx(repo, fn, "r%i\n" % id)
1730 1732 if len(ps) > 1:
1731 1733 if not p2:
1732 1734 p2 = repo[ps[1]]
1733 1735 for fn in p2:
1734 1736 if fn.startswith("nf"):
1735 1737 files.append(fn)
1736 1738 fctxs[fn] = p2[fn]
1737 1739
1738 1740 def fctxfn(repo, cx, path):
1739 1741 return fctxs.get(path)
1740 1742
1741 1743 if len(ps) == 0 or ps[0] < 0:
1742 1744 pars = [None, None]
1743 1745 elif len(ps) == 1:
1744 1746 pars = [nodeids[ps[0]], None]
1745 1747 else:
1746 1748 pars = [nodeids[p] for p in ps]
1747 1749 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1748 1750 date=(id, 0),
1749 1751 user="debugbuilddag",
1750 1752 extra={'branch': atbranch})
1751 1753 nodeid = repo.commitctx(cx)
1752 1754 nodeids.append(nodeid)
1753 1755 at = id
1754 1756 elif type == 'l':
1755 1757 id, name = data
1756 1758 ui.note(('tag %s\n' % name))
1757 1759 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1758 1760 elif type == 'a':
1759 1761 ui.note(('branch %s\n' % data))
1760 1762 atbranch = data
1761 1763 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1762 1764 tr.close()
1763 1765
1764 1766 if tags:
1765 1767 repo.opener.write("localtags", "".join(tags))
1766 1768 finally:
1767 1769 ui.progress(_('building'), None)
1768 1770 release(tr, lock)
1769 1771
1770 1772 @command('debugbundle',
1771 1773 [('a', 'all', None, _('show all details'))],
1772 1774 _('FILE'),
1773 1775 norepo=True)
1774 1776 def debugbundle(ui, bundlepath, all=None, **opts):
1775 1777 """lists the contents of a bundle"""
1776 1778 f = hg.openpath(ui, bundlepath)
1777 1779 try:
1778 1780 gen = exchange.readbundle(ui, f, bundlepath)
1779 1781 if all:
1780 1782 ui.write(("format: id, p1, p2, cset, delta base, len(delta)\n"))
1781 1783
1782 1784 def showchunks(named):
1783 1785 ui.write("\n%s\n" % named)
1784 1786 chain = None
1785 1787 while True:
1786 1788 chunkdata = gen.deltachunk(chain)
1787 1789 if not chunkdata:
1788 1790 break
1789 1791 node = chunkdata['node']
1790 1792 p1 = chunkdata['p1']
1791 1793 p2 = chunkdata['p2']
1792 1794 cs = chunkdata['cs']
1793 1795 deltabase = chunkdata['deltabase']
1794 1796 delta = chunkdata['delta']
1795 1797 ui.write("%s %s %s %s %s %s\n" %
1796 1798 (hex(node), hex(p1), hex(p2),
1797 1799 hex(cs), hex(deltabase), len(delta)))
1798 1800 chain = node
1799 1801
1800 1802 chunkdata = gen.changelogheader()
1801 1803 showchunks("changelog")
1802 1804 chunkdata = gen.manifestheader()
1803 1805 showchunks("manifest")
1804 1806 while True:
1805 1807 chunkdata = gen.filelogheader()
1806 1808 if not chunkdata:
1807 1809 break
1808 1810 fname = chunkdata['filename']
1809 1811 showchunks(fname)
1810 1812 else:
1811 1813 chunkdata = gen.changelogheader()
1812 1814 chain = None
1813 1815 while True:
1814 1816 chunkdata = gen.deltachunk(chain)
1815 1817 if not chunkdata:
1816 1818 break
1817 1819 node = chunkdata['node']
1818 1820 ui.write("%s\n" % hex(node))
1819 1821 chain = node
1820 1822 finally:
1821 1823 f.close()
1822 1824
1823 1825 @command('debugcheckstate', [], '')
1824 1826 def debugcheckstate(ui, repo):
1825 1827 """validate the correctness of the current dirstate"""
1826 1828 parent1, parent2 = repo.dirstate.parents()
1827 1829 m1 = repo[parent1].manifest()
1828 1830 m2 = repo[parent2].manifest()
1829 1831 errors = 0
1830 1832 for f in repo.dirstate:
1831 1833 state = repo.dirstate[f]
1832 1834 if state in "nr" and f not in m1:
1833 1835 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1834 1836 errors += 1
1835 1837 if state in "a" and f in m1:
1836 1838 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1837 1839 errors += 1
1838 1840 if state in "m" and f not in m1 and f not in m2:
1839 1841 ui.warn(_("%s in state %s, but not in either manifest\n") %
1840 1842 (f, state))
1841 1843 errors += 1
1842 1844 for f in m1:
1843 1845 state = repo.dirstate[f]
1844 1846 if state not in "nrm":
1845 1847 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1846 1848 errors += 1
1847 1849 if errors:
1848 1850 error = _(".hg/dirstate inconsistent with current parent's manifest")
1849 1851 raise util.Abort(error)
1850 1852
1851 1853 @command('debugcommands', [], _('[COMMAND]'), norepo=True)
1852 1854 def debugcommands(ui, cmd='', *args):
1853 1855 """list all available commands and options"""
1854 1856 for cmd, vals in sorted(table.iteritems()):
1855 1857 cmd = cmd.split('|')[0].strip('^')
1856 1858 opts = ', '.join([i[1] for i in vals[1]])
1857 1859 ui.write('%s: %s\n' % (cmd, opts))
1858 1860
1859 1861 @command('debugcomplete',
1860 1862 [('o', 'options', None, _('show the command options'))],
1861 1863 _('[-o] CMD'),
1862 1864 norepo=True)
1863 1865 def debugcomplete(ui, cmd='', **opts):
1864 1866 """returns the completion list associated with the given command"""
1865 1867
1866 1868 if opts.get('options'):
1867 1869 options = []
1868 1870 otables = [globalopts]
1869 1871 if cmd:
1870 1872 aliases, entry = cmdutil.findcmd(cmd, table, False)
1871 1873 otables.append(entry[1])
1872 1874 for t in otables:
1873 1875 for o in t:
1874 1876 if "(DEPRECATED)" in o[3]:
1875 1877 continue
1876 1878 if o[0]:
1877 1879 options.append('-%s' % o[0])
1878 1880 options.append('--%s' % o[1])
1879 1881 ui.write("%s\n" % "\n".join(options))
1880 1882 return
1881 1883
1882 1884 cmdlist = cmdutil.findpossible(cmd, table)
1883 1885 if ui.verbose:
1884 1886 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1885 1887 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1886 1888
1887 1889 @command('debugdag',
1888 1890 [('t', 'tags', None, _('use tags as labels')),
1889 1891 ('b', 'branches', None, _('annotate with branch names')),
1890 1892 ('', 'dots', None, _('use dots for runs')),
1891 1893 ('s', 'spaces', None, _('separate elements by spaces'))],
1892 1894 _('[OPTION]... [FILE [REV]...]'),
1893 1895 optionalrepo=True)
1894 1896 def debugdag(ui, repo, file_=None, *revs, **opts):
1895 1897 """format the changelog or an index DAG as a concise textual description
1896 1898
1897 1899 If you pass a revlog index, the revlog's DAG is emitted. If you list
1898 1900 revision numbers, they get labeled in the output as rN.
1899 1901
1900 1902 Otherwise, the changelog DAG of the current repo is emitted.
1901 1903 """
1902 1904 spaces = opts.get('spaces')
1903 1905 dots = opts.get('dots')
1904 1906 if file_:
1905 1907 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1906 1908 revs = set((int(r) for r in revs))
1907 1909 def events():
1908 1910 for r in rlog:
1909 1911 yield 'n', (r, list(set(p for p in rlog.parentrevs(r)
1910 1912 if p != -1)))
1911 1913 if r in revs:
1912 1914 yield 'l', (r, "r%i" % r)
1913 1915 elif repo:
1914 1916 cl = repo.changelog
1915 1917 tags = opts.get('tags')
1916 1918 branches = opts.get('branches')
1917 1919 if tags:
1918 1920 labels = {}
1919 1921 for l, n in repo.tags().items():
1920 1922 labels.setdefault(cl.rev(n), []).append(l)
1921 1923 def events():
1922 1924 b = "default"
1923 1925 for r in cl:
1924 1926 if branches:
1925 1927 newb = cl.read(cl.node(r))[5]['branch']
1926 1928 if newb != b:
1927 1929 yield 'a', newb
1928 1930 b = newb
1929 1931 yield 'n', (r, list(set(p for p in cl.parentrevs(r)
1930 1932 if p != -1)))
1931 1933 if tags:
1932 1934 ls = labels.get(r)
1933 1935 if ls:
1934 1936 for l in ls:
1935 1937 yield 'l', (r, l)
1936 1938 else:
1937 1939 raise util.Abort(_('need repo for changelog dag'))
1938 1940
1939 1941 for line in dagparser.dagtextlines(events(),
1940 1942 addspaces=spaces,
1941 1943 wraplabels=True,
1942 1944 wrapannotations=True,
1943 1945 wrapnonlinear=dots,
1944 1946 usedots=dots,
1945 1947 maxlinewidth=70):
1946 1948 ui.write(line)
1947 1949 ui.write("\n")
1948 1950
1949 1951 @command('debugdata',
1950 1952 [('c', 'changelog', False, _('open changelog')),
1951 1953 ('m', 'manifest', False, _('open manifest'))],
1952 1954 _('-c|-m|FILE REV'))
1953 1955 def debugdata(ui, repo, file_, rev=None, **opts):
1954 1956 """dump the contents of a data file revision"""
1955 1957 if opts.get('changelog') or opts.get('manifest'):
1956 1958 file_, rev = None, file_
1957 1959 elif rev is None:
1958 1960 raise error.CommandError('debugdata', _('invalid arguments'))
1959 1961 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1960 1962 try:
1961 1963 ui.write(r.revision(r.lookup(rev)))
1962 1964 except KeyError:
1963 1965 raise util.Abort(_('invalid revision identifier %s') % rev)
1964 1966
1965 1967 @command('debugdate',
1966 1968 [('e', 'extended', None, _('try extended date formats'))],
1967 1969 _('[-e] DATE [RANGE]'),
1968 1970 norepo=True, optionalrepo=True)
1969 1971 def debugdate(ui, date, range=None, **opts):
1970 1972 """parse and display a date"""
1971 1973 if opts["extended"]:
1972 1974 d = util.parsedate(date, util.extendeddateformats)
1973 1975 else:
1974 1976 d = util.parsedate(date)
1975 1977 ui.write(("internal: %s %s\n") % d)
1976 1978 ui.write(("standard: %s\n") % util.datestr(d))
1977 1979 if range:
1978 1980 m = util.matchdate(range)
1979 1981 ui.write(("match: %s\n") % m(d[0]))
1980 1982
1981 1983 @command('debugdiscovery',
1982 1984 [('', 'old', None, _('use old-style discovery')),
1983 1985 ('', 'nonheads', None,
1984 1986 _('use old-style discovery with non-heads included')),
1985 1987 ] + remoteopts,
1986 1988 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1987 1989 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1988 1990 """runs the changeset discovery protocol in isolation"""
1989 1991 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl),
1990 1992 opts.get('branch'))
1991 1993 remote = hg.peer(repo, opts, remoteurl)
1992 1994 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1993 1995
1994 1996 # make sure tests are repeatable
1995 1997 random.seed(12323)
1996 1998
1997 1999 def doit(localheads, remoteheads, remote=remote):
1998 2000 if opts.get('old'):
1999 2001 if localheads:
2000 2002 raise util.Abort('cannot use localheads with old style '
2001 2003 'discovery')
2002 2004 if not util.safehasattr(remote, 'branches'):
2003 2005 # enable in-client legacy support
2004 2006 remote = localrepo.locallegacypeer(remote.local())
2005 2007 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
2006 2008 force=True)
2007 2009 common = set(common)
2008 2010 if not opts.get('nonheads'):
2009 2011 ui.write(("unpruned common: %s\n") %
2010 2012 " ".join(sorted(short(n) for n in common)))
2011 2013 dag = dagutil.revlogdag(repo.changelog)
2012 2014 all = dag.ancestorset(dag.internalizeall(common))
2013 2015 common = dag.externalizeall(dag.headsetofconnecteds(all))
2014 2016 else:
2015 2017 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
2016 2018 common = set(common)
2017 2019 rheads = set(hds)
2018 2020 lheads = set(repo.heads())
2019 2021 ui.write(("common heads: %s\n") %
2020 2022 " ".join(sorted(short(n) for n in common)))
2021 2023 if lheads <= common:
2022 2024 ui.write(("local is subset\n"))
2023 2025 elif rheads <= common:
2024 2026 ui.write(("remote is subset\n"))
2025 2027
2026 2028 serverlogs = opts.get('serverlog')
2027 2029 if serverlogs:
2028 2030 for filename in serverlogs:
2029 2031 logfile = open(filename, 'r')
2030 2032 try:
2031 2033 line = logfile.readline()
2032 2034 while line:
2033 2035 parts = line.strip().split(';')
2034 2036 op = parts[1]
2035 2037 if op == 'cg':
2036 2038 pass
2037 2039 elif op == 'cgss':
2038 2040 doit(parts[2].split(' '), parts[3].split(' '))
2039 2041 elif op == 'unb':
2040 2042 doit(parts[3].split(' '), parts[2].split(' '))
2041 2043 line = logfile.readline()
2042 2044 finally:
2043 2045 logfile.close()
2044 2046
2045 2047 else:
2046 2048 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
2047 2049 opts.get('remote_head'))
2048 2050 localrevs = opts.get('local_head')
2049 2051 doit(localrevs, remoterevs)
2050 2052
2051 2053 @command('debugfileset',
2052 2054 [('r', 'rev', '', _('apply the filespec on this revision'), _('REV'))],
2053 2055 _('[-r REV] FILESPEC'))
2054 2056 def debugfileset(ui, repo, expr, **opts):
2055 2057 '''parse and apply a fileset specification'''
2056 2058 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
2057 2059 if ui.verbose:
2058 2060 tree = fileset.parse(expr)[0]
2059 2061 ui.note(tree, "\n")
2060 2062
2061 2063 for f in ctx.getfileset(expr):
2062 2064 ui.write("%s\n" % f)
2063 2065
2064 2066 @command('debugfsinfo', [], _('[PATH]'), norepo=True)
2065 2067 def debugfsinfo(ui, path="."):
2066 2068 """show information detected about current filesystem"""
2067 2069 util.writefile('.debugfsinfo', '')
2068 2070 ui.write(('exec: %s\n') % (util.checkexec(path) and 'yes' or 'no'))
2069 2071 ui.write(('symlink: %s\n') % (util.checklink(path) and 'yes' or 'no'))
2070 2072 ui.write(('hardlink: %s\n') % (util.checknlink(path) and 'yes' or 'no'))
2071 2073 ui.write(('case-sensitive: %s\n') % (util.checkcase('.debugfsinfo')
2072 2074 and 'yes' or 'no'))
2073 2075 os.unlink('.debugfsinfo')
2074 2076
2075 2077 @command('debuggetbundle',
2076 2078 [('H', 'head', [], _('id of head node'), _('ID')),
2077 2079 ('C', 'common', [], _('id of common node'), _('ID')),
2078 2080 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
2079 2081 _('REPO FILE [-H|-C ID]...'),
2080 2082 norepo=True)
2081 2083 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
2082 2084 """retrieves a bundle from a repo
2083 2085
2084 2086 Every ID must be a full-length hex node id string. Saves the bundle to the
2085 2087 given file.
2086 2088 """
2087 2089 repo = hg.peer(ui, opts, repopath)
2088 2090 if not repo.capable('getbundle'):
2089 2091 raise util.Abort("getbundle() not supported by target repository")
2090 2092 args = {}
2091 2093 if common:
2092 2094 args['common'] = [bin(s) for s in common]
2093 2095 if head:
2094 2096 args['heads'] = [bin(s) for s in head]
2095 2097 # TODO: get desired bundlecaps from command line.
2096 2098 args['bundlecaps'] = None
2097 2099 bundle = repo.getbundle('debug', **args)
2098 2100
2099 2101 bundletype = opts.get('type', 'bzip2').lower()
2100 2102 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
2101 2103 bundletype = btypes.get(bundletype)
2102 2104 if bundletype not in changegroup.bundletypes:
2103 2105 raise util.Abort(_('unknown bundle type specified with --type'))
2104 2106 changegroup.writebundle(bundle, bundlepath, bundletype)
2105 2107
2106 2108 @command('debugignore', [], '')
2107 2109 def debugignore(ui, repo, *values, **opts):
2108 2110 """display the combined ignore pattern"""
2109 2111 ignore = repo.dirstate._ignore
2110 2112 includepat = getattr(ignore, 'includepat', None)
2111 2113 if includepat is not None:
2112 2114 ui.write("%s\n" % includepat)
2113 2115 else:
2114 2116 raise util.Abort(_("no ignore patterns found"))
2115 2117
2116 2118 @command('debugindex',
2117 2119 [('c', 'changelog', False, _('open changelog')),
2118 2120 ('m', 'manifest', False, _('open manifest')),
2119 2121 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
2120 2122 _('[-f FORMAT] -c|-m|FILE'),
2121 2123 optionalrepo=True)
2122 2124 def debugindex(ui, repo, file_=None, **opts):
2123 2125 """dump the contents of an index file"""
2124 2126 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
2125 2127 format = opts.get('format', 0)
2126 2128 if format not in (0, 1):
2127 2129 raise util.Abort(_("unknown format %d") % format)
2128 2130
2129 2131 generaldelta = r.version & revlog.REVLOGGENERALDELTA
2130 2132 if generaldelta:
2131 2133 basehdr = ' delta'
2132 2134 else:
2133 2135 basehdr = ' base'
2134 2136
2135 2137 if format == 0:
2136 2138 ui.write(" rev offset length " + basehdr + " linkrev"
2137 2139 " nodeid p1 p2\n")
2138 2140 elif format == 1:
2139 2141 ui.write(" rev flag offset length"
2140 2142 " size " + basehdr + " link p1 p2"
2141 2143 " nodeid\n")
2142 2144
2143 2145 for i in r:
2144 2146 node = r.node(i)
2145 2147 if generaldelta:
2146 2148 base = r.deltaparent(i)
2147 2149 else:
2148 2150 base = r.chainbase(i)
2149 2151 if format == 0:
2150 2152 try:
2151 2153 pp = r.parents(node)
2152 2154 except Exception:
2153 2155 pp = [nullid, nullid]
2154 2156 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
2155 2157 i, r.start(i), r.length(i), base, r.linkrev(i),
2156 2158 short(node), short(pp[0]), short(pp[1])))
2157 2159 elif format == 1:
2158 2160 pr = r.parentrevs(i)
2159 2161 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
2160 2162 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
2161 2163 base, r.linkrev(i), pr[0], pr[1], short(node)))
2162 2164
2163 2165 @command('debugindexdot', [], _('FILE'), optionalrepo=True)
2164 2166 def debugindexdot(ui, repo, file_):
2165 2167 """dump an index DAG as a graphviz dot file"""
2166 2168 r = None
2167 2169 if repo:
2168 2170 filelog = repo.file(file_)
2169 2171 if len(filelog):
2170 2172 r = filelog
2171 2173 if not r:
2172 2174 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
2173 2175 ui.write(("digraph G {\n"))
2174 2176 for i in r:
2175 2177 node = r.node(i)
2176 2178 pp = r.parents(node)
2177 2179 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
2178 2180 if pp[1] != nullid:
2179 2181 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
2180 2182 ui.write("}\n")
2181 2183
2182 2184 @command('debuginstall', [], '', norepo=True)
2183 2185 def debuginstall(ui):
2184 2186 '''test Mercurial installation
2185 2187
2186 2188 Returns 0 on success.
2187 2189 '''
2188 2190
2189 2191 def writetemp(contents):
2190 2192 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
2191 2193 f = os.fdopen(fd, "wb")
2192 2194 f.write(contents)
2193 2195 f.close()
2194 2196 return name
2195 2197
2196 2198 problems = 0
2197 2199
2198 2200 # encoding
2199 2201 ui.status(_("checking encoding (%s)...\n") % encoding.encoding)
2200 2202 try:
2201 2203 encoding.fromlocal("test")
2202 2204 except util.Abort, inst:
2203 2205 ui.write(" %s\n" % inst)
2204 2206 ui.write(_(" (check that your locale is properly set)\n"))
2205 2207 problems += 1
2206 2208
2207 2209 # Python
2208 2210 ui.status(_("checking Python executable (%s)\n") % sys.executable)
2209 2211 ui.status(_("checking Python version (%s)\n")
2210 2212 % ("%s.%s.%s" % sys.version_info[:3]))
2211 2213 ui.status(_("checking Python lib (%s)...\n")
2212 2214 % os.path.dirname(os.__file__))
2213 2215
2214 2216 # compiled modules
2215 2217 ui.status(_("checking installed modules (%s)...\n")
2216 2218 % os.path.dirname(__file__))
2217 2219 try:
2218 2220 import bdiff, mpatch, base85, osutil
2219 2221 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
2220 2222 except Exception, inst:
2221 2223 ui.write(" %s\n" % inst)
2222 2224 ui.write(_(" One or more extensions could not be found"))
2223 2225 ui.write(_(" (check that you compiled the extensions)\n"))
2224 2226 problems += 1
2225 2227
2226 2228 # templates
2227 2229 import templater
2228 2230 p = templater.templatepath()
2229 2231 ui.status(_("checking templates (%s)...\n") % ' '.join(p))
2230 2232 if p:
2231 2233 m = templater.templatepath("map-cmdline.default")
2232 2234 if m:
2233 2235 # template found, check if it is working
2234 2236 try:
2235 2237 templater.templater(m)
2236 2238 except Exception, inst:
2237 2239 ui.write(" %s\n" % inst)
2238 2240 p = None
2239 2241 else:
2240 2242 ui.write(_(" template 'default' not found\n"))
2241 2243 p = None
2242 2244 else:
2243 2245 ui.write(_(" no template directories found\n"))
2244 2246 if not p:
2245 2247 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
2246 2248 problems += 1
2247 2249
2248 2250 # editor
2249 2251 ui.status(_("checking commit editor...\n"))
2250 2252 editor = ui.geteditor()
2251 2253 cmdpath = util.findexe(shlex.split(editor)[0])
2252 2254 if not cmdpath:
2253 2255 if editor == 'vi':
2254 2256 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
2255 2257 ui.write(_(" (specify a commit editor in your configuration"
2256 2258 " file)\n"))
2257 2259 else:
2258 2260 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
2259 2261 ui.write(_(" (specify a commit editor in your configuration"
2260 2262 " file)\n"))
2261 2263 problems += 1
2262 2264
2263 2265 # check username
2264 2266 ui.status(_("checking username...\n"))
2265 2267 try:
2266 2268 ui.username()
2267 2269 except util.Abort, e:
2268 2270 ui.write(" %s\n" % e)
2269 2271 ui.write(_(" (specify a username in your configuration file)\n"))
2270 2272 problems += 1
2271 2273
2272 2274 if not problems:
2273 2275 ui.status(_("no problems detected\n"))
2274 2276 else:
2275 2277 ui.write(_("%s problems detected,"
2276 2278 " please check your install!\n") % problems)
2277 2279
2278 2280 return problems
2279 2281
2280 2282 @command('debugknown', [], _('REPO ID...'), norepo=True)
2281 2283 def debugknown(ui, repopath, *ids, **opts):
2282 2284 """test whether node ids are known to a repo
2283 2285
2284 2286 Every ID must be a full-length hex node id string. Returns a list of 0s
2285 2287 and 1s indicating unknown/known.
2286 2288 """
2287 2289 repo = hg.peer(ui, opts, repopath)
2288 2290 if not repo.capable('known'):
2289 2291 raise util.Abort("known() not supported by target repository")
2290 2292 flags = repo.known([bin(s) for s in ids])
2291 2293 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
2292 2294
2293 2295 @command('debuglabelcomplete', [], _('LABEL...'))
2294 2296 def debuglabelcomplete(ui, repo, *args):
2295 2297 '''complete "labels" - tags, open branch names, bookmark names'''
2296 2298
2297 2299 labels = set()
2298 2300 labels.update(t[0] for t in repo.tagslist())
2299 2301 labels.update(repo._bookmarks.keys())
2300 2302 labels.update(tag for (tag, heads, tip, closed)
2301 2303 in repo.branchmap().iterbranches() if not closed)
2302 2304 completions = set()
2303 2305 if not args:
2304 2306 args = ['']
2305 2307 for a in args:
2306 2308 completions.update(l for l in labels if l.startswith(a))
2307 2309 ui.write('\n'.join(sorted(completions)))
2308 2310 ui.write('\n')
2309 2311
2310 2312 @command('debugobsolete',
2311 2313 [('', 'flags', 0, _('markers flag')),
2312 2314 ] + commitopts2,
2313 2315 _('[OBSOLETED [REPLACEMENT] [REPL... ]'))
2314 2316 def debugobsolete(ui, repo, precursor=None, *successors, **opts):
2315 2317 """create arbitrary obsolete marker
2316 2318
2317 2319 With no arguments, displays the list of obsolescence markers."""
2318 2320
2319 2321 def parsenodeid(s):
2320 2322 try:
2321 2323 # We do not use revsingle/revrange functions here to accept
2322 2324 # arbitrary node identifiers, possibly not present in the
2323 2325 # local repository.
2324 2326 n = bin(s)
2325 2327 if len(n) != len(nullid):
2326 2328 raise TypeError()
2327 2329 return n
2328 2330 except TypeError:
2329 2331 raise util.Abort('changeset references must be full hexadecimal '
2330 2332 'node identifiers')
2331 2333
2332 2334 if precursor is not None:
2333 2335 metadata = {}
2334 2336 if 'date' in opts:
2335 2337 metadata['date'] = opts['date']
2336 2338 metadata['user'] = opts['user'] or ui.username()
2337 2339 succs = tuple(parsenodeid(succ) for succ in successors)
2338 2340 l = repo.lock()
2339 2341 try:
2340 2342 tr = repo.transaction('debugobsolete')
2341 2343 try:
2342 2344 repo.obsstore.create(tr, parsenodeid(precursor), succs,
2343 2345 opts['flags'], metadata)
2344 2346 tr.close()
2345 2347 finally:
2346 2348 tr.release()
2347 2349 finally:
2348 2350 l.release()
2349 2351 else:
2350 2352 for m in obsolete.allmarkers(repo):
2351 2353 cmdutil.showmarker(ui, m)
2352 2354
2353 2355 @command('debugpathcomplete',
2354 2356 [('f', 'full', None, _('complete an entire path')),
2355 2357 ('n', 'normal', None, _('show only normal files')),
2356 2358 ('a', 'added', None, _('show only added files')),
2357 2359 ('r', 'removed', None, _('show only removed files'))],
2358 2360 _('FILESPEC...'))
2359 2361 def debugpathcomplete(ui, repo, *specs, **opts):
2360 2362 '''complete part or all of a tracked path
2361 2363
2362 2364 This command supports shells that offer path name completion. It
2363 2365 currently completes only files already known to the dirstate.
2364 2366
2365 2367 Completion extends only to the next path segment unless
2366 2368 --full is specified, in which case entire paths are used.'''
2367 2369
2368 2370 def complete(path, acceptable):
2369 2371 dirstate = repo.dirstate
2370 2372 spec = os.path.normpath(os.path.join(os.getcwd(), path))
2371 2373 rootdir = repo.root + os.sep
2372 2374 if spec != repo.root and not spec.startswith(rootdir):
2373 2375 return [], []
2374 2376 if os.path.isdir(spec):
2375 2377 spec += '/'
2376 2378 spec = spec[len(rootdir):]
2377 2379 fixpaths = os.sep != '/'
2378 2380 if fixpaths:
2379 2381 spec = spec.replace(os.sep, '/')
2380 2382 speclen = len(spec)
2381 2383 fullpaths = opts['full']
2382 2384 files, dirs = set(), set()
2383 2385 adddir, addfile = dirs.add, files.add
2384 2386 for f, st in dirstate.iteritems():
2385 2387 if f.startswith(spec) and st[0] in acceptable:
2386 2388 if fixpaths:
2387 2389 f = f.replace('/', os.sep)
2388 2390 if fullpaths:
2389 2391 addfile(f)
2390 2392 continue
2391 2393 s = f.find(os.sep, speclen)
2392 2394 if s >= 0:
2393 2395 adddir(f[:s])
2394 2396 else:
2395 2397 addfile(f)
2396 2398 return files, dirs
2397 2399
2398 2400 acceptable = ''
2399 2401 if opts['normal']:
2400 2402 acceptable += 'nm'
2401 2403 if opts['added']:
2402 2404 acceptable += 'a'
2403 2405 if opts['removed']:
2404 2406 acceptable += 'r'
2405 2407 cwd = repo.getcwd()
2406 2408 if not specs:
2407 2409 specs = ['.']
2408 2410
2409 2411 files, dirs = set(), set()
2410 2412 for spec in specs:
2411 2413 f, d = complete(spec, acceptable or 'nmar')
2412 2414 files.update(f)
2413 2415 dirs.update(d)
2414 2416 files.update(dirs)
2415 2417 ui.write('\n'.join(repo.pathto(p, cwd) for p in sorted(files)))
2416 2418 ui.write('\n')
2417 2419
2418 2420 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'), norepo=True)
2419 2421 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
2420 2422 '''access the pushkey key/value protocol
2421 2423
2422 2424 With two args, list the keys in the given namespace.
2423 2425
2424 2426 With five args, set a key to new if it currently is set to old.
2425 2427 Reports success or failure.
2426 2428 '''
2427 2429
2428 2430 target = hg.peer(ui, {}, repopath)
2429 2431 if keyinfo:
2430 2432 key, old, new = keyinfo
2431 2433 r = target.pushkey(namespace, key, old, new)
2432 2434 ui.status(str(r) + '\n')
2433 2435 return not r
2434 2436 else:
2435 2437 for k, v in sorted(target.listkeys(namespace).iteritems()):
2436 2438 ui.write("%s\t%s\n" % (k.encode('string-escape'),
2437 2439 v.encode('string-escape')))
2438 2440
2439 2441 @command('debugpvec', [], _('A B'))
2440 2442 def debugpvec(ui, repo, a, b=None):
2441 2443 ca = scmutil.revsingle(repo, a)
2442 2444 cb = scmutil.revsingle(repo, b)
2443 2445 pa = pvec.ctxpvec(ca)
2444 2446 pb = pvec.ctxpvec(cb)
2445 2447 if pa == pb:
2446 2448 rel = "="
2447 2449 elif pa > pb:
2448 2450 rel = ">"
2449 2451 elif pa < pb:
2450 2452 rel = "<"
2451 2453 elif pa | pb:
2452 2454 rel = "|"
2453 2455 ui.write(_("a: %s\n") % pa)
2454 2456 ui.write(_("b: %s\n") % pb)
2455 2457 ui.write(_("depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
2456 2458 ui.write(_("delta: %d hdist: %d distance: %d relation: %s\n") %
2457 2459 (abs(pa._depth - pb._depth), pvec._hamming(pa._vec, pb._vec),
2458 2460 pa.distance(pb), rel))
2459 2461
2460 2462 @command('debugrebuilddirstate|debugrebuildstate',
2461 2463 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
2462 2464 _('[-r REV]'))
2463 2465 def debugrebuilddirstate(ui, repo, rev):
2464 2466 """rebuild the dirstate as it would look like for the given revision
2465 2467
2466 2468 If no revision is specified the first current parent will be used.
2467 2469
2468 2470 The dirstate will be set to the files of the given revision.
2469 2471 The actual working directory content or existing dirstate
2470 2472 information such as adds or removes is not considered.
2471 2473
2472 2474 One use of this command is to make the next :hg:`status` invocation
2473 2475 check the actual file content.
2474 2476 """
2475 2477 ctx = scmutil.revsingle(repo, rev)
2476 2478 wlock = repo.wlock()
2477 2479 try:
2478 2480 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
2479 2481 finally:
2480 2482 wlock.release()
2481 2483
2482 2484 @command('debugrename',
2483 2485 [('r', 'rev', '', _('revision to debug'), _('REV'))],
2484 2486 _('[-r REV] FILE'))
2485 2487 def debugrename(ui, repo, file1, *pats, **opts):
2486 2488 """dump rename information"""
2487 2489
2488 2490 ctx = scmutil.revsingle(repo, opts.get('rev'))
2489 2491 m = scmutil.match(ctx, (file1,) + pats, opts)
2490 2492 for abs in ctx.walk(m):
2491 2493 fctx = ctx[abs]
2492 2494 o = fctx.filelog().renamed(fctx.filenode())
2493 2495 rel = m.rel(abs)
2494 2496 if o:
2495 2497 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
2496 2498 else:
2497 2499 ui.write(_("%s not renamed\n") % rel)
2498 2500
2499 2501 @command('debugrevlog',
2500 2502 [('c', 'changelog', False, _('open changelog')),
2501 2503 ('m', 'manifest', False, _('open manifest')),
2502 2504 ('d', 'dump', False, _('dump index data'))],
2503 2505 _('-c|-m|FILE'),
2504 2506 optionalrepo=True)
2505 2507 def debugrevlog(ui, repo, file_=None, **opts):
2506 2508 """show data and statistics about a revlog"""
2507 2509 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
2508 2510
2509 2511 if opts.get("dump"):
2510 2512 numrevs = len(r)
2511 2513 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
2512 2514 " rawsize totalsize compression heads\n")
2513 2515 ts = 0
2514 2516 heads = set()
2515 2517 for rev in xrange(numrevs):
2516 2518 dbase = r.deltaparent(rev)
2517 2519 if dbase == -1:
2518 2520 dbase = rev
2519 2521 cbase = r.chainbase(rev)
2520 2522 p1, p2 = r.parentrevs(rev)
2521 2523 rs = r.rawsize(rev)
2522 2524 ts = ts + rs
2523 2525 heads -= set(r.parentrevs(rev))
2524 2526 heads.add(rev)
2525 2527 ui.write("%5d %5d %5d %5d %5d %10d %4d %4d %4d %7d %9d %11d %5d\n" %
2526 2528 (rev, p1, p2, r.start(rev), r.end(rev),
2527 2529 r.start(dbase), r.start(cbase),
2528 2530 r.start(p1), r.start(p2),
2529 2531 rs, ts, ts / r.end(rev), len(heads)))
2530 2532 return 0
2531 2533
2532 2534 v = r.version
2533 2535 format = v & 0xFFFF
2534 2536 flags = []
2535 2537 gdelta = False
2536 2538 if v & revlog.REVLOGNGINLINEDATA:
2537 2539 flags.append('inline')
2538 2540 if v & revlog.REVLOGGENERALDELTA:
2539 2541 gdelta = True
2540 2542 flags.append('generaldelta')
2541 2543 if not flags:
2542 2544 flags = ['(none)']
2543 2545
2544 2546 nummerges = 0
2545 2547 numfull = 0
2546 2548 numprev = 0
2547 2549 nump1 = 0
2548 2550 nump2 = 0
2549 2551 numother = 0
2550 2552 nump1prev = 0
2551 2553 nump2prev = 0
2552 2554 chainlengths = []
2553 2555
2554 2556 datasize = [None, 0, 0L]
2555 2557 fullsize = [None, 0, 0L]
2556 2558 deltasize = [None, 0, 0L]
2557 2559
2558 2560 def addsize(size, l):
2559 2561 if l[0] is None or size < l[0]:
2560 2562 l[0] = size
2561 2563 if size > l[1]:
2562 2564 l[1] = size
2563 2565 l[2] += size
2564 2566
2565 2567 numrevs = len(r)
2566 2568 for rev in xrange(numrevs):
2567 2569 p1, p2 = r.parentrevs(rev)
2568 2570 delta = r.deltaparent(rev)
2569 2571 if format > 0:
2570 2572 addsize(r.rawsize(rev), datasize)
2571 2573 if p2 != nullrev:
2572 2574 nummerges += 1
2573 2575 size = r.length(rev)
2574 2576 if delta == nullrev:
2575 2577 chainlengths.append(0)
2576 2578 numfull += 1
2577 2579 addsize(size, fullsize)
2578 2580 else:
2579 2581 chainlengths.append(chainlengths[delta] + 1)
2580 2582 addsize(size, deltasize)
2581 2583 if delta == rev - 1:
2582 2584 numprev += 1
2583 2585 if delta == p1:
2584 2586 nump1prev += 1
2585 2587 elif delta == p2:
2586 2588 nump2prev += 1
2587 2589 elif delta == p1:
2588 2590 nump1 += 1
2589 2591 elif delta == p2:
2590 2592 nump2 += 1
2591 2593 elif delta != nullrev:
2592 2594 numother += 1
2593 2595
2594 2596 # Adjust size min value for empty cases
2595 2597 for size in (datasize, fullsize, deltasize):
2596 2598 if size[0] is None:
2597 2599 size[0] = 0
2598 2600
2599 2601 numdeltas = numrevs - numfull
2600 2602 numoprev = numprev - nump1prev - nump2prev
2601 2603 totalrawsize = datasize[2]
2602 2604 datasize[2] /= numrevs
2603 2605 fulltotal = fullsize[2]
2604 2606 fullsize[2] /= numfull
2605 2607 deltatotal = deltasize[2]
2606 2608 if numrevs - numfull > 0:
2607 2609 deltasize[2] /= numrevs - numfull
2608 2610 totalsize = fulltotal + deltatotal
2609 2611 avgchainlen = sum(chainlengths) / numrevs
2610 2612 compratio = totalrawsize / totalsize
2611 2613
2612 2614 basedfmtstr = '%%%dd\n'
2613 2615 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
2614 2616
2615 2617 def dfmtstr(max):
2616 2618 return basedfmtstr % len(str(max))
2617 2619 def pcfmtstr(max, padding=0):
2618 2620 return basepcfmtstr % (len(str(max)), ' ' * padding)
2619 2621
2620 2622 def pcfmt(value, total):
2621 2623 return (value, 100 * float(value) / total)
2622 2624
2623 2625 ui.write(('format : %d\n') % format)
2624 2626 ui.write(('flags : %s\n') % ', '.join(flags))
2625 2627
2626 2628 ui.write('\n')
2627 2629 fmt = pcfmtstr(totalsize)
2628 2630 fmt2 = dfmtstr(totalsize)
2629 2631 ui.write(('revisions : ') + fmt2 % numrevs)
2630 2632 ui.write((' merges : ') + fmt % pcfmt(nummerges, numrevs))
2631 2633 ui.write((' normal : ') + fmt % pcfmt(numrevs - nummerges, numrevs))
2632 2634 ui.write(('revisions : ') + fmt2 % numrevs)
2633 2635 ui.write((' full : ') + fmt % pcfmt(numfull, numrevs))
2634 2636 ui.write((' deltas : ') + fmt % pcfmt(numdeltas, numrevs))
2635 2637 ui.write(('revision size : ') + fmt2 % totalsize)
2636 2638 ui.write((' full : ') + fmt % pcfmt(fulltotal, totalsize))
2637 2639 ui.write((' deltas : ') + fmt % pcfmt(deltatotal, totalsize))
2638 2640
2639 2641 ui.write('\n')
2640 2642 fmt = dfmtstr(max(avgchainlen, compratio))
2641 2643 ui.write(('avg chain length : ') + fmt % avgchainlen)
2642 2644 ui.write(('compression ratio : ') + fmt % compratio)
2643 2645
2644 2646 if format > 0:
2645 2647 ui.write('\n')
2646 2648 ui.write(('uncompressed data size (min/max/avg) : %d / %d / %d\n')
2647 2649 % tuple(datasize))
2648 2650 ui.write(('full revision size (min/max/avg) : %d / %d / %d\n')
2649 2651 % tuple(fullsize))
2650 2652 ui.write(('delta size (min/max/avg) : %d / %d / %d\n')
2651 2653 % tuple(deltasize))
2652 2654
2653 2655 if numdeltas > 0:
2654 2656 ui.write('\n')
2655 2657 fmt = pcfmtstr(numdeltas)
2656 2658 fmt2 = pcfmtstr(numdeltas, 4)
2657 2659 ui.write(('deltas against prev : ') + fmt % pcfmt(numprev, numdeltas))
2658 2660 if numprev > 0:
2659 2661 ui.write((' where prev = p1 : ') + fmt2 % pcfmt(nump1prev,
2660 2662 numprev))
2661 2663 ui.write((' where prev = p2 : ') + fmt2 % pcfmt(nump2prev,
2662 2664 numprev))
2663 2665 ui.write((' other : ') + fmt2 % pcfmt(numoprev,
2664 2666 numprev))
2665 2667 if gdelta:
2666 2668 ui.write(('deltas against p1 : ')
2667 2669 + fmt % pcfmt(nump1, numdeltas))
2668 2670 ui.write(('deltas against p2 : ')
2669 2671 + fmt % pcfmt(nump2, numdeltas))
2670 2672 ui.write(('deltas against other : ') + fmt % pcfmt(numother,
2671 2673 numdeltas))
2672 2674
2673 2675 @command('debugrevspec',
2674 2676 [('', 'optimize', None, _('print parsed tree after optimizing'))],
2675 2677 ('REVSPEC'))
2676 2678 def debugrevspec(ui, repo, expr, **opts):
2677 2679 """parse and apply a revision specification
2678 2680
2679 2681 Use --verbose to print the parsed tree before and after aliases
2680 2682 expansion.
2681 2683 """
2682 2684 if ui.verbose:
2683 2685 tree = revset.parse(expr)[0]
2684 2686 ui.note(revset.prettyformat(tree), "\n")
2685 2687 newtree = revset.findaliases(ui, tree)
2686 2688 if newtree != tree:
2687 2689 ui.note(revset.prettyformat(newtree), "\n")
2688 2690 if opts["optimize"]:
2689 2691 weight, optimizedtree = revset.optimize(newtree, True)
2690 2692 ui.note("* optimized:\n", revset.prettyformat(optimizedtree), "\n")
2691 2693 func = revset.match(ui, expr)
2692 2694 for c in func(repo, revset.spanset(repo)):
2693 2695 ui.write("%s\n" % c)
2694 2696
2695 2697 @command('debugsetparents', [], _('REV1 [REV2]'))
2696 2698 def debugsetparents(ui, repo, rev1, rev2=None):
2697 2699 """manually set the parents of the current working directory
2698 2700
2699 2701 This is useful for writing repository conversion tools, but should
2700 2702 be used with care.
2701 2703
2702 2704 Returns 0 on success.
2703 2705 """
2704 2706
2705 2707 r1 = scmutil.revsingle(repo, rev1).node()
2706 2708 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2707 2709
2708 2710 wlock = repo.wlock()
2709 2711 try:
2710 2712 repo.setparents(r1, r2)
2711 2713 finally:
2712 2714 wlock.release()
2713 2715
2714 2716 @command('debugdirstate|debugstate',
2715 2717 [('', 'nodates', None, _('do not display the saved mtime')),
2716 2718 ('', 'datesort', None, _('sort by saved mtime'))],
2717 2719 _('[OPTION]...'))
2718 2720 def debugstate(ui, repo, nodates=None, datesort=None):
2719 2721 """show the contents of the current dirstate"""
2720 2722 timestr = ""
2721 2723 showdate = not nodates
2722 2724 if datesort:
2723 2725 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2724 2726 else:
2725 2727 keyfunc = None # sort by filename
2726 2728 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2727 2729 if showdate:
2728 2730 if ent[3] == -1:
2729 2731 # Pad or slice to locale representation
2730 2732 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2731 2733 time.localtime(0)))
2732 2734 timestr = 'unset'
2733 2735 timestr = (timestr[:locale_len] +
2734 2736 ' ' * (locale_len - len(timestr)))
2735 2737 else:
2736 2738 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2737 2739 time.localtime(ent[3]))
2738 2740 if ent[1] & 020000:
2739 2741 mode = 'lnk'
2740 2742 else:
2741 2743 mode = '%3o' % (ent[1] & 0777 & ~util.umask)
2742 2744 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2743 2745 for f in repo.dirstate.copies():
2744 2746 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2745 2747
2746 2748 @command('debugsub',
2747 2749 [('r', 'rev', '',
2748 2750 _('revision to check'), _('REV'))],
2749 2751 _('[-r REV] [REV]'))
2750 2752 def debugsub(ui, repo, rev=None):
2751 2753 ctx = scmutil.revsingle(repo, rev, None)
2752 2754 for k, v in sorted(ctx.substate.items()):
2753 2755 ui.write(('path %s\n') % k)
2754 2756 ui.write((' source %s\n') % v[0])
2755 2757 ui.write((' revision %s\n') % v[1])
2756 2758
2757 2759 @command('debugsuccessorssets',
2758 2760 [],
2759 2761 _('[REV]'))
2760 2762 def debugsuccessorssets(ui, repo, *revs):
2761 2763 """show set of successors for revision
2762 2764
2763 2765 A successors set of changeset A is a consistent group of revisions that
2764 2766 succeed A. It contains non-obsolete changesets only.
2765 2767
2766 2768 In most cases a changeset A has a single successors set containing a single
2767 2769 successor (changeset A replaced by A').
2768 2770
2769 2771 A changeset that is made obsolete with no successors are called "pruned".
2770 2772 Such changesets have no successors sets at all.
2771 2773
2772 2774 A changeset that has been "split" will have a successors set containing
2773 2775 more than one successor.
2774 2776
2775 2777 A changeset that has been rewritten in multiple different ways is called
2776 2778 "divergent". Such changesets have multiple successor sets (each of which
2777 2779 may also be split, i.e. have multiple successors).
2778 2780
2779 2781 Results are displayed as follows::
2780 2782
2781 2783 <rev1>
2782 2784 <successors-1A>
2783 2785 <rev2>
2784 2786 <successors-2A>
2785 2787 <successors-2B1> <successors-2B2> <successors-2B3>
2786 2788
2787 2789 Here rev2 has two possible (i.e. divergent) successors sets. The first
2788 2790 holds one element, whereas the second holds three (i.e. the changeset has
2789 2791 been split).
2790 2792 """
2791 2793 # passed to successorssets caching computation from one call to another
2792 2794 cache = {}
2793 2795 ctx2str = str
2794 2796 node2str = short
2795 2797 if ui.debug():
2796 2798 def ctx2str(ctx):
2797 2799 return ctx.hex()
2798 2800 node2str = hex
2799 2801 for rev in scmutil.revrange(repo, revs):
2800 2802 ctx = repo[rev]
2801 2803 ui.write('%s\n'% ctx2str(ctx))
2802 2804 for succsset in obsolete.successorssets(repo, ctx.node(), cache):
2803 2805 if succsset:
2804 2806 ui.write(' ')
2805 2807 ui.write(node2str(succsset[0]))
2806 2808 for node in succsset[1:]:
2807 2809 ui.write(' ')
2808 2810 ui.write(node2str(node))
2809 2811 ui.write('\n')
2810 2812
2811 2813 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'), inferrepo=True)
2812 2814 def debugwalk(ui, repo, *pats, **opts):
2813 2815 """show how files match on given patterns"""
2814 2816 m = scmutil.match(repo[None], pats, opts)
2815 2817 items = list(repo.walk(m))
2816 2818 if not items:
2817 2819 return
2818 2820 f = lambda fn: fn
2819 2821 if ui.configbool('ui', 'slash') and os.sep != '/':
2820 2822 f = lambda fn: util.normpath(fn)
2821 2823 fmt = 'f %%-%ds %%-%ds %%s' % (
2822 2824 max([len(abs) for abs in items]),
2823 2825 max([len(m.rel(abs)) for abs in items]))
2824 2826 for abs in items:
2825 2827 line = fmt % (abs, f(m.rel(abs)), m.exact(abs) and 'exact' or '')
2826 2828 ui.write("%s\n" % line.rstrip())
2827 2829
2828 2830 @command('debugwireargs',
2829 2831 [('', 'three', '', 'three'),
2830 2832 ('', 'four', '', 'four'),
2831 2833 ('', 'five', '', 'five'),
2832 2834 ] + remoteopts,
2833 2835 _('REPO [OPTIONS]... [ONE [TWO]]'),
2834 2836 norepo=True)
2835 2837 def debugwireargs(ui, repopath, *vals, **opts):
2836 2838 repo = hg.peer(ui, opts, repopath)
2837 2839 for opt in remoteopts:
2838 2840 del opts[opt[1]]
2839 2841 args = {}
2840 2842 for k, v in opts.iteritems():
2841 2843 if v:
2842 2844 args[k] = v
2843 2845 # run twice to check that we don't mess up the stream for the next command
2844 2846 res1 = repo.debugwireargs(*vals, **args)
2845 2847 res2 = repo.debugwireargs(*vals, **args)
2846 2848 ui.write("%s\n" % res1)
2847 2849 if res1 != res2:
2848 2850 ui.warn("%s\n" % res2)
2849 2851
2850 2852 @command('^diff',
2851 2853 [('r', 'rev', [], _('revision'), _('REV')),
2852 2854 ('c', 'change', '', _('change made by revision'), _('REV'))
2853 2855 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2854 2856 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'),
2855 2857 inferrepo=True)
2856 2858 def diff(ui, repo, *pats, **opts):
2857 2859 """diff repository (or selected files)
2858 2860
2859 2861 Show differences between revisions for the specified files.
2860 2862
2861 2863 Differences between files are shown using the unified diff format.
2862 2864
2863 2865 .. note::
2864 2866
2865 2867 diff may generate unexpected results for merges, as it will
2866 2868 default to comparing against the working directory's first
2867 2869 parent changeset if no revisions are specified.
2868 2870
2869 2871 When two revision arguments are given, then changes are shown
2870 2872 between those revisions. If only one revision is specified then
2871 2873 that revision is compared to the working directory, and, when no
2872 2874 revisions are specified, the working directory files are compared
2873 2875 to its parent.
2874 2876
2875 2877 Alternatively you can specify -c/--change with a revision to see
2876 2878 the changes in that changeset relative to its first parent.
2877 2879
2878 2880 Without the -a/--text option, diff will avoid generating diffs of
2879 2881 files it detects as binary. With -a, diff will generate a diff
2880 2882 anyway, probably with undesirable results.
2881 2883
2882 2884 Use the -g/--git option to generate diffs in the git extended diff
2883 2885 format. For more information, read :hg:`help diffs`.
2884 2886
2885 2887 .. container:: verbose
2886 2888
2887 2889 Examples:
2888 2890
2889 2891 - compare a file in the current working directory to its parent::
2890 2892
2891 2893 hg diff foo.c
2892 2894
2893 2895 - compare two historical versions of a directory, with rename info::
2894 2896
2895 2897 hg diff --git -r 1.0:1.2 lib/
2896 2898
2897 2899 - get change stats relative to the last change on some date::
2898 2900
2899 2901 hg diff --stat -r "date('may 2')"
2900 2902
2901 2903 - diff all newly-added files that contain a keyword::
2902 2904
2903 2905 hg diff "set:added() and grep(GNU)"
2904 2906
2905 2907 - compare a revision and its parents::
2906 2908
2907 2909 hg diff -c 9353 # compare against first parent
2908 2910 hg diff -r 9353^:9353 # same using revset syntax
2909 2911 hg diff -r 9353^2:9353 # compare against the second parent
2910 2912
2911 2913 Returns 0 on success.
2912 2914 """
2913 2915
2914 2916 revs = opts.get('rev')
2915 2917 change = opts.get('change')
2916 2918 stat = opts.get('stat')
2917 2919 reverse = opts.get('reverse')
2918 2920
2919 2921 if revs and change:
2920 2922 msg = _('cannot specify --rev and --change at the same time')
2921 2923 raise util.Abort(msg)
2922 2924 elif change:
2923 2925 node2 = scmutil.revsingle(repo, change, None).node()
2924 2926 node1 = repo[node2].p1().node()
2925 2927 else:
2926 2928 node1, node2 = scmutil.revpair(repo, revs)
2927 2929
2928 2930 if reverse:
2929 2931 node1, node2 = node2, node1
2930 2932
2931 2933 diffopts = patch.diffopts(ui, opts)
2932 2934 m = scmutil.match(repo[node2], pats, opts)
2933 2935 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2934 2936 listsubrepos=opts.get('subrepos'))
2935 2937
2936 2938 @command('^export',
2937 2939 [('o', 'output', '',
2938 2940 _('print output to file with formatted name'), _('FORMAT')),
2939 2941 ('', 'switch-parent', None, _('diff against the second parent')),
2940 2942 ('r', 'rev', [], _('revisions to export'), _('REV')),
2941 2943 ] + diffopts,
2942 2944 _('[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'))
2943 2945 def export(ui, repo, *changesets, **opts):
2944 2946 """dump the header and diffs for one or more changesets
2945 2947
2946 2948 Print the changeset header and diffs for one or more revisions.
2947 2949 If no revision is given, the parent of the working directory is used.
2948 2950
2949 2951 The information shown in the changeset header is: author, date,
2950 2952 branch name (if non-default), changeset hash, parent(s) and commit
2951 2953 comment.
2952 2954
2953 2955 .. note::
2954 2956
2955 2957 export may generate unexpected diff output for merge
2956 2958 changesets, as it will compare the merge changeset against its
2957 2959 first parent only.
2958 2960
2959 2961 Output may be to a file, in which case the name of the file is
2960 2962 given using a format string. The formatting rules are as follows:
2961 2963
2962 2964 :``%%``: literal "%" character
2963 2965 :``%H``: changeset hash (40 hexadecimal digits)
2964 2966 :``%N``: number of patches being generated
2965 2967 :``%R``: changeset revision number
2966 2968 :``%b``: basename of the exporting repository
2967 2969 :``%h``: short-form changeset hash (12 hexadecimal digits)
2968 2970 :``%m``: first line of the commit message (only alphanumeric characters)
2969 2971 :``%n``: zero-padded sequence number, starting at 1
2970 2972 :``%r``: zero-padded changeset revision number
2971 2973
2972 2974 Without the -a/--text option, export will avoid generating diffs
2973 2975 of files it detects as binary. With -a, export will generate a
2974 2976 diff anyway, probably with undesirable results.
2975 2977
2976 2978 Use the -g/--git option to generate diffs in the git extended diff
2977 2979 format. See :hg:`help diffs` for more information.
2978 2980
2979 2981 With the --switch-parent option, the diff will be against the
2980 2982 second parent. It can be useful to review a merge.
2981 2983
2982 2984 .. container:: verbose
2983 2985
2984 2986 Examples:
2985 2987
2986 2988 - use export and import to transplant a bugfix to the current
2987 2989 branch::
2988 2990
2989 2991 hg export -r 9353 | hg import -
2990 2992
2991 2993 - export all the changesets between two revisions to a file with
2992 2994 rename information::
2993 2995
2994 2996 hg export --git -r 123:150 > changes.txt
2995 2997
2996 2998 - split outgoing changes into a series of patches with
2997 2999 descriptive names::
2998 3000
2999 3001 hg export -r "outgoing()" -o "%n-%m.patch"
3000 3002
3001 3003 Returns 0 on success.
3002 3004 """
3003 3005 changesets += tuple(opts.get('rev', []))
3004 3006 if not changesets:
3005 3007 changesets = ['.']
3006 3008 revs = scmutil.revrange(repo, changesets)
3007 3009 if not revs:
3008 3010 raise util.Abort(_("export requires at least one changeset"))
3009 3011 if len(revs) > 1:
3010 3012 ui.note(_('exporting patches:\n'))
3011 3013 else:
3012 3014 ui.note(_('exporting patch:\n'))
3013 3015 cmdutil.export(repo, revs, template=opts.get('output'),
3014 3016 switch_parent=opts.get('switch_parent'),
3015 3017 opts=patch.diffopts(ui, opts))
3016 3018
3017 3019 @command('^forget', walkopts, _('[OPTION]... FILE...'), inferrepo=True)
3018 3020 def forget(ui, repo, *pats, **opts):
3019 3021 """forget the specified files on the next commit
3020 3022
3021 3023 Mark the specified files so they will no longer be tracked
3022 3024 after the next commit.
3023 3025
3024 3026 This only removes files from the current branch, not from the
3025 3027 entire project history, and it does not delete them from the
3026 3028 working directory.
3027 3029
3028 3030 To undo a forget before the next commit, see :hg:`add`.
3029 3031
3030 3032 .. container:: verbose
3031 3033
3032 3034 Examples:
3033 3035
3034 3036 - forget newly-added binary files::
3035 3037
3036 3038 hg forget "set:added() and binary()"
3037 3039
3038 3040 - forget files that would be excluded by .hgignore::
3039 3041
3040 3042 hg forget "set:hgignore()"
3041 3043
3042 3044 Returns 0 on success.
3043 3045 """
3044 3046
3045 3047 if not pats:
3046 3048 raise util.Abort(_('no files specified'))
3047 3049
3048 3050 m = scmutil.match(repo[None], pats, opts)
3049 3051 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
3050 3052 return rejected and 1 or 0
3051 3053
3052 3054 @command(
3053 3055 'graft',
3054 3056 [('r', 'rev', [], _('revisions to graft'), _('REV')),
3055 3057 ('c', 'continue', False, _('resume interrupted graft')),
3056 3058 ('e', 'edit', False, _('invoke editor on commit messages')),
3057 3059 ('', 'log', None, _('append graft info to log message')),
3058 3060 ('f', 'force', False, _('force graft')),
3059 3061 ('D', 'currentdate', False,
3060 3062 _('record the current date as commit date')),
3061 3063 ('U', 'currentuser', False,
3062 3064 _('record the current user as committer'), _('DATE'))]
3063 3065 + commitopts2 + mergetoolopts + dryrunopts,
3064 3066 _('[OPTION]... [-r] REV...'))
3065 3067 def graft(ui, repo, *revs, **opts):
3066 3068 '''copy changes from other branches onto the current branch
3067 3069
3068 3070 This command uses Mercurial's merge logic to copy individual
3069 3071 changes from other branches without merging branches in the
3070 3072 history graph. This is sometimes known as 'backporting' or
3071 3073 'cherry-picking'. By default, graft will copy user, date, and
3072 3074 description from the source changesets.
3073 3075
3074 3076 Changesets that are ancestors of the current revision, that have
3075 3077 already been grafted, or that are merges will be skipped.
3076 3078
3077 3079 If --log is specified, log messages will have a comment appended
3078 3080 of the form::
3079 3081
3080 3082 (grafted from CHANGESETHASH)
3081 3083
3082 3084 If --force is specified, revisions will be grafted even if they
3083 3085 are already ancestors of or have been grafted to the destination.
3084 3086 This is useful when the revisions have since been backed out.
3085 3087
3086 3088 If a graft merge results in conflicts, the graft process is
3087 3089 interrupted so that the current merge can be manually resolved.
3088 3090 Once all conflicts are addressed, the graft process can be
3089 3091 continued with the -c/--continue option.
3090 3092
3091 3093 .. note::
3092 3094
3093 3095 The -c/--continue option does not reapply earlier options, except
3094 3096 for --force.
3095 3097
3096 3098 .. container:: verbose
3097 3099
3098 3100 Examples:
3099 3101
3100 3102 - copy a single change to the stable branch and edit its description::
3101 3103
3102 3104 hg update stable
3103 3105 hg graft --edit 9393
3104 3106
3105 3107 - graft a range of changesets with one exception, updating dates::
3106 3108
3107 3109 hg graft -D "2085::2093 and not 2091"
3108 3110
3109 3111 - continue a graft after resolving conflicts::
3110 3112
3111 3113 hg graft -c
3112 3114
3113 3115 - show the source of a grafted changeset::
3114 3116
3115 3117 hg log --debug -r .
3116 3118
3117 3119 See :hg:`help revisions` and :hg:`help revsets` for more about
3118 3120 specifying revisions.
3119 3121
3120 3122 Returns 0 on successful completion.
3121 3123 '''
3122 3124
3123 3125 revs = list(revs)
3124 3126 revs.extend(opts['rev'])
3125 3127
3126 3128 if not opts.get('user') and opts.get('currentuser'):
3127 3129 opts['user'] = ui.username()
3128 3130 if not opts.get('date') and opts.get('currentdate'):
3129 3131 opts['date'] = "%d %d" % util.makedate()
3130 3132
3131 3133 editor = cmdutil.getcommiteditor(editform='graft', **opts)
3132 3134
3133 3135 cont = False
3134 3136 if opts['continue']:
3135 3137 cont = True
3136 3138 if revs:
3137 3139 raise util.Abort(_("can't specify --continue and revisions"))
3138 3140 # read in unfinished revisions
3139 3141 try:
3140 3142 nodes = repo.opener.read('graftstate').splitlines()
3141 3143 revs = [repo[node].rev() for node in nodes]
3142 3144 except IOError, inst:
3143 3145 if inst.errno != errno.ENOENT:
3144 3146 raise
3145 3147 raise util.Abort(_("no graft state found, can't continue"))
3146 3148 else:
3147 3149 cmdutil.checkunfinished(repo)
3148 3150 cmdutil.bailifchanged(repo)
3149 3151 if not revs:
3150 3152 raise util.Abort(_('no revisions specified'))
3151 3153 revs = scmutil.revrange(repo, revs)
3152 3154
3153 3155 # check for merges
3154 3156 for rev in repo.revs('%ld and merge()', revs):
3155 3157 ui.warn(_('skipping ungraftable merge revision %s\n') % rev)
3156 3158 revs.remove(rev)
3157 3159 if not revs:
3158 3160 return -1
3159 3161
3160 3162 # Don't check in the --continue case, in effect retaining --force across
3161 3163 # --continues. That's because without --force, any revisions we decided to
3162 3164 # skip would have been filtered out here, so they wouldn't have made their
3163 3165 # way to the graftstate. With --force, any revisions we would have otherwise
3164 3166 # skipped would not have been filtered out, and if they hadn't been applied
3165 3167 # already, they'd have been in the graftstate.
3166 3168 if not (cont or opts.get('force')):
3167 3169 # check for ancestors of dest branch
3168 3170 crev = repo['.'].rev()
3169 3171 ancestors = repo.changelog.ancestors([crev], inclusive=True)
3170 3172 # Cannot use x.remove(y) on smart set, this has to be a list.
3171 3173 # XXX make this lazy in the future
3172 3174 revs = list(revs)
3173 3175 # don't mutate while iterating, create a copy
3174 3176 for rev in list(revs):
3175 3177 if rev in ancestors:
3176 3178 ui.warn(_('skipping ancestor revision %s\n') % rev)
3177 3179 # XXX remove on list is slow
3178 3180 revs.remove(rev)
3179 3181 if not revs:
3180 3182 return -1
3181 3183
3182 3184 # analyze revs for earlier grafts
3183 3185 ids = {}
3184 3186 for ctx in repo.set("%ld", revs):
3185 3187 ids[ctx.hex()] = ctx.rev()
3186 3188 n = ctx.extra().get('source')
3187 3189 if n:
3188 3190 ids[n] = ctx.rev()
3189 3191
3190 3192 # check ancestors for earlier grafts
3191 3193 ui.debug('scanning for duplicate grafts\n')
3192 3194
3193 3195 for rev in repo.changelog.findmissingrevs(revs, [crev]):
3194 3196 ctx = repo[rev]
3195 3197 n = ctx.extra().get('source')
3196 3198 if n in ids:
3197 3199 r = repo[n].rev()
3198 3200 if r in revs:
3199 3201 ui.warn(_('skipping revision %s (already grafted to %s)\n')
3200 3202 % (r, rev))
3201 3203 revs.remove(r)
3202 3204 elif ids[n] in revs:
3203 3205 ui.warn(_('skipping already grafted revision %s '
3204 3206 '(%s also has origin %d)\n') % (ids[n], rev, r))
3205 3207 revs.remove(ids[n])
3206 3208 elif ctx.hex() in ids:
3207 3209 r = ids[ctx.hex()]
3208 3210 ui.warn(_('skipping already grafted revision %s '
3209 3211 '(was grafted from %d)\n') % (r, rev))
3210 3212 revs.remove(r)
3211 3213 if not revs:
3212 3214 return -1
3213 3215
3214 3216 wlock = repo.wlock()
3215 3217 try:
3216 3218 current = repo['.']
3217 3219 for pos, ctx in enumerate(repo.set("%ld", revs)):
3218 3220
3219 3221 ui.status(_('grafting revision %s\n') % ctx.rev())
3220 3222 if opts.get('dry_run'):
3221 3223 continue
3222 3224
3223 3225 source = ctx.extra().get('source')
3224 3226 if not source:
3225 3227 source = ctx.hex()
3226 3228 extra = {'source': source}
3227 3229 user = ctx.user()
3228 3230 if opts.get('user'):
3229 3231 user = opts['user']
3230 3232 date = ctx.date()
3231 3233 if opts.get('date'):
3232 3234 date = opts['date']
3233 3235 message = ctx.description()
3234 3236 if opts.get('log'):
3235 3237 message += '\n(grafted from %s)' % ctx.hex()
3236 3238
3237 3239 # we don't merge the first commit when continuing
3238 3240 if not cont:
3239 3241 # perform the graft merge with p1(rev) as 'ancestor'
3240 3242 try:
3241 3243 # ui.forcemerge is an internal variable, do not document
3242 3244 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
3243 3245 'graft')
3244 3246 stats = mergemod.update(repo, ctx.node(), True, True, False,
3245 3247 ctx.p1().node(),
3246 3248 labels=['local', 'graft'])
3247 3249 finally:
3248 3250 repo.ui.setconfig('ui', 'forcemerge', '', 'graft')
3249 3251 # report any conflicts
3250 3252 if stats and stats[3] > 0:
3251 3253 # write out state for --continue
3252 3254 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
3253 3255 repo.opener.write('graftstate', ''.join(nodelines))
3254 3256 raise util.Abort(
3255 3257 _("unresolved conflicts, can't continue"),
3256 3258 hint=_('use hg resolve and hg graft --continue'))
3257 3259 else:
3258 3260 cont = False
3259 3261
3260 3262 # drop the second merge parent
3261 3263 repo.setparents(current.node(), nullid)
3262 3264 repo.dirstate.write()
3263 3265 # fix up dirstate for copies and renames
3264 3266 cmdutil.duplicatecopies(repo, ctx.rev(), ctx.p1().rev())
3265 3267
3266 3268 # commit
3267 3269 node = repo.commit(text=message, user=user,
3268 3270 date=date, extra=extra, editor=editor)
3269 3271 if node is None:
3270 3272 ui.status(_('graft for revision %s is empty\n') % ctx.rev())
3271 3273 else:
3272 3274 current = repo[node]
3273 3275 finally:
3274 3276 wlock.release()
3275 3277
3276 3278 # remove state when we complete successfully
3277 3279 if not opts.get('dry_run'):
3278 3280 util.unlinkpath(repo.join('graftstate'), ignoremissing=True)
3279 3281
3280 3282 return 0
3281 3283
3282 3284 @command('grep',
3283 3285 [('0', 'print0', None, _('end fields with NUL')),
3284 3286 ('', 'all', None, _('print all revisions that match')),
3285 3287 ('a', 'text', None, _('treat all files as text')),
3286 3288 ('f', 'follow', None,
3287 3289 _('follow changeset history,'
3288 3290 ' or file history across copies and renames')),
3289 3291 ('i', 'ignore-case', None, _('ignore case when matching')),
3290 3292 ('l', 'files-with-matches', None,
3291 3293 _('print only filenames and revisions that match')),
3292 3294 ('n', 'line-number', None, _('print matching line numbers')),
3293 3295 ('r', 'rev', [],
3294 3296 _('only search files changed within revision range'), _('REV')),
3295 3297 ('u', 'user', None, _('list the author (long with -v)')),
3296 3298 ('d', 'date', None, _('list the date (short with -q)')),
3297 3299 ] + walkopts,
3298 3300 _('[OPTION]... PATTERN [FILE]...'),
3299 3301 inferrepo=True)
3300 3302 def grep(ui, repo, pattern, *pats, **opts):
3301 3303 """search for a pattern in specified files and revisions
3302 3304
3303 3305 Search revisions of files for a regular expression.
3304 3306
3305 3307 This command behaves differently than Unix grep. It only accepts
3306 3308 Python/Perl regexps. It searches repository history, not the
3307 3309 working directory. It always prints the revision number in which a
3308 3310 match appears.
3309 3311
3310 3312 By default, grep only prints output for the first revision of a
3311 3313 file in which it finds a match. To get it to print every revision
3312 3314 that contains a change in match status ("-" for a match that
3313 3315 becomes a non-match, or "+" for a non-match that becomes a match),
3314 3316 use the --all flag.
3315 3317
3316 3318 Returns 0 if a match is found, 1 otherwise.
3317 3319 """
3318 3320 reflags = re.M
3319 3321 if opts.get('ignore_case'):
3320 3322 reflags |= re.I
3321 3323 try:
3322 3324 regexp = util.re.compile(pattern, reflags)
3323 3325 except re.error, inst:
3324 3326 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
3325 3327 return 1
3326 3328 sep, eol = ':', '\n'
3327 3329 if opts.get('print0'):
3328 3330 sep = eol = '\0'
3329 3331
3330 3332 getfile = util.lrucachefunc(repo.file)
3331 3333
3332 3334 def matchlines(body):
3333 3335 begin = 0
3334 3336 linenum = 0
3335 3337 while begin < len(body):
3336 3338 match = regexp.search(body, begin)
3337 3339 if not match:
3338 3340 break
3339 3341 mstart, mend = match.span()
3340 3342 linenum += body.count('\n', begin, mstart) + 1
3341 3343 lstart = body.rfind('\n', begin, mstart) + 1 or begin
3342 3344 begin = body.find('\n', mend) + 1 or len(body) + 1
3343 3345 lend = begin - 1
3344 3346 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
3345 3347
3346 3348 class linestate(object):
3347 3349 def __init__(self, line, linenum, colstart, colend):
3348 3350 self.line = line
3349 3351 self.linenum = linenum
3350 3352 self.colstart = colstart
3351 3353 self.colend = colend
3352 3354
3353 3355 def __hash__(self):
3354 3356 return hash((self.linenum, self.line))
3355 3357
3356 3358 def __eq__(self, other):
3357 3359 return self.line == other.line
3358 3360
3359 3361 def __iter__(self):
3360 3362 yield (self.line[:self.colstart], '')
3361 3363 yield (self.line[self.colstart:self.colend], 'grep.match')
3362 3364 rest = self.line[self.colend:]
3363 3365 while rest != '':
3364 3366 match = regexp.search(rest)
3365 3367 if not match:
3366 3368 yield (rest, '')
3367 3369 break
3368 3370 mstart, mend = match.span()
3369 3371 yield (rest[:mstart], '')
3370 3372 yield (rest[mstart:mend], 'grep.match')
3371 3373 rest = rest[mend:]
3372 3374
3373 3375 matches = {}
3374 3376 copies = {}
3375 3377 def grepbody(fn, rev, body):
3376 3378 matches[rev].setdefault(fn, [])
3377 3379 m = matches[rev][fn]
3378 3380 for lnum, cstart, cend, line in matchlines(body):
3379 3381 s = linestate(line, lnum, cstart, cend)
3380 3382 m.append(s)
3381 3383
3382 3384 def difflinestates(a, b):
3383 3385 sm = difflib.SequenceMatcher(None, a, b)
3384 3386 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
3385 3387 if tag == 'insert':
3386 3388 for i in xrange(blo, bhi):
3387 3389 yield ('+', b[i])
3388 3390 elif tag == 'delete':
3389 3391 for i in xrange(alo, ahi):
3390 3392 yield ('-', a[i])
3391 3393 elif tag == 'replace':
3392 3394 for i in xrange(alo, ahi):
3393 3395 yield ('-', a[i])
3394 3396 for i in xrange(blo, bhi):
3395 3397 yield ('+', b[i])
3396 3398
3397 3399 def display(fn, ctx, pstates, states):
3398 3400 rev = ctx.rev()
3399 3401 datefunc = ui.quiet and util.shortdate or util.datestr
3400 3402 found = False
3401 3403 @util.cachefunc
3402 3404 def binary():
3403 3405 flog = getfile(fn)
3404 3406 return util.binary(flog.read(ctx.filenode(fn)))
3405 3407
3406 3408 if opts.get('all'):
3407 3409 iter = difflinestates(pstates, states)
3408 3410 else:
3409 3411 iter = [('', l) for l in states]
3410 3412 for change, l in iter:
3411 3413 cols = [(fn, 'grep.filename'), (str(rev), 'grep.rev')]
3412 3414
3413 3415 if opts.get('line_number'):
3414 3416 cols.append((str(l.linenum), 'grep.linenumber'))
3415 3417 if opts.get('all'):
3416 3418 cols.append((change, 'grep.change'))
3417 3419 if opts.get('user'):
3418 3420 cols.append((ui.shortuser(ctx.user()), 'grep.user'))
3419 3421 if opts.get('date'):
3420 3422 cols.append((datefunc(ctx.date()), 'grep.date'))
3421 3423 for col, label in cols[:-1]:
3422 3424 ui.write(col, label=label)
3423 3425 ui.write(sep, label='grep.sep')
3424 3426 ui.write(cols[-1][0], label=cols[-1][1])
3425 3427 if not opts.get('files_with_matches'):
3426 3428 ui.write(sep, label='grep.sep')
3427 3429 if not opts.get('text') and binary():
3428 3430 ui.write(" Binary file matches")
3429 3431 else:
3430 3432 for s, label in l:
3431 3433 ui.write(s, label=label)
3432 3434 ui.write(eol)
3433 3435 found = True
3434 3436 if opts.get('files_with_matches'):
3435 3437 break
3436 3438 return found
3437 3439
3438 3440 skip = {}
3439 3441 revfiles = {}
3440 3442 matchfn = scmutil.match(repo[None], pats, opts)
3441 3443 found = False
3442 3444 follow = opts.get('follow')
3443 3445
3444 3446 def prep(ctx, fns):
3445 3447 rev = ctx.rev()
3446 3448 pctx = ctx.p1()
3447 3449 parent = pctx.rev()
3448 3450 matches.setdefault(rev, {})
3449 3451 matches.setdefault(parent, {})
3450 3452 files = revfiles.setdefault(rev, [])
3451 3453 for fn in fns:
3452 3454 flog = getfile(fn)
3453 3455 try:
3454 3456 fnode = ctx.filenode(fn)
3455 3457 except error.LookupError:
3456 3458 continue
3457 3459
3458 3460 copied = flog.renamed(fnode)
3459 3461 copy = follow and copied and copied[0]
3460 3462 if copy:
3461 3463 copies.setdefault(rev, {})[fn] = copy
3462 3464 if fn in skip:
3463 3465 if copy:
3464 3466 skip[copy] = True
3465 3467 continue
3466 3468 files.append(fn)
3467 3469
3468 3470 if fn not in matches[rev]:
3469 3471 grepbody(fn, rev, flog.read(fnode))
3470 3472
3471 3473 pfn = copy or fn
3472 3474 if pfn not in matches[parent]:
3473 3475 try:
3474 3476 fnode = pctx.filenode(pfn)
3475 3477 grepbody(pfn, parent, flog.read(fnode))
3476 3478 except error.LookupError:
3477 3479 pass
3478 3480
3479 3481 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3480 3482 rev = ctx.rev()
3481 3483 parent = ctx.p1().rev()
3482 3484 for fn in sorted(revfiles.get(rev, [])):
3483 3485 states = matches[rev][fn]
3484 3486 copy = copies.get(rev, {}).get(fn)
3485 3487 if fn in skip:
3486 3488 if copy:
3487 3489 skip[copy] = True
3488 3490 continue
3489 3491 pstates = matches.get(parent, {}).get(copy or fn, [])
3490 3492 if pstates or states:
3491 3493 r = display(fn, ctx, pstates, states)
3492 3494 found = found or r
3493 3495 if r and not opts.get('all'):
3494 3496 skip[fn] = True
3495 3497 if copy:
3496 3498 skip[copy] = True
3497 3499 del matches[rev]
3498 3500 del revfiles[rev]
3499 3501
3500 3502 return not found
3501 3503
3502 3504 @command('heads',
3503 3505 [('r', 'rev', '',
3504 3506 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
3505 3507 ('t', 'topo', False, _('show topological heads only')),
3506 3508 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
3507 3509 ('c', 'closed', False, _('show normal and closed branch heads')),
3508 3510 ] + templateopts,
3509 3511 _('[-ct] [-r STARTREV] [REV]...'))
3510 3512 def heads(ui, repo, *branchrevs, **opts):
3511 3513 """show branch heads
3512 3514
3513 3515 With no arguments, show all open branch heads in the repository.
3514 3516 Branch heads are changesets that have no descendants on the
3515 3517 same branch. They are where development generally takes place and
3516 3518 are the usual targets for update and merge operations.
3517 3519
3518 3520 If one or more REVs are given, only open branch heads on the
3519 3521 branches associated with the specified changesets are shown. This
3520 3522 means that you can use :hg:`heads .` to see the heads on the
3521 3523 currently checked-out branch.
3522 3524
3523 3525 If -c/--closed is specified, also show branch heads marked closed
3524 3526 (see :hg:`commit --close-branch`).
3525 3527
3526 3528 If STARTREV is specified, only those heads that are descendants of
3527 3529 STARTREV will be displayed.
3528 3530
3529 3531 If -t/--topo is specified, named branch mechanics will be ignored and only
3530 3532 topological heads (changesets with no children) will be shown.
3531 3533
3532 3534 Returns 0 if matching heads are found, 1 if not.
3533 3535 """
3534 3536
3535 3537 start = None
3536 3538 if 'rev' in opts:
3537 3539 start = scmutil.revsingle(repo, opts['rev'], None).node()
3538 3540
3539 3541 if opts.get('topo'):
3540 3542 heads = [repo[h] for h in repo.heads(start)]
3541 3543 else:
3542 3544 heads = []
3543 3545 for branch in repo.branchmap():
3544 3546 heads += repo.branchheads(branch, start, opts.get('closed'))
3545 3547 heads = [repo[h] for h in heads]
3546 3548
3547 3549 if branchrevs:
3548 3550 branches = set(repo[br].branch() for br in branchrevs)
3549 3551 heads = [h for h in heads if h.branch() in branches]
3550 3552
3551 3553 if opts.get('active') and branchrevs:
3552 3554 dagheads = repo.heads(start)
3553 3555 heads = [h for h in heads if h.node() in dagheads]
3554 3556
3555 3557 if branchrevs:
3556 3558 haveheads = set(h.branch() for h in heads)
3557 3559 if branches - haveheads:
3558 3560 headless = ', '.join(b for b in branches - haveheads)
3559 3561 msg = _('no open branch heads found on branches %s')
3560 3562 if opts.get('rev'):
3561 3563 msg += _(' (started at %s)') % opts['rev']
3562 3564 ui.warn((msg + '\n') % headless)
3563 3565
3564 3566 if not heads:
3565 3567 return 1
3566 3568
3567 3569 heads = sorted(heads, key=lambda x: -x.rev())
3568 3570 displayer = cmdutil.show_changeset(ui, repo, opts)
3569 3571 for ctx in heads:
3570 3572 displayer.show(ctx)
3571 3573 displayer.close()
3572 3574
3573 3575 @command('help',
3574 3576 [('e', 'extension', None, _('show only help for extensions')),
3575 3577 ('c', 'command', None, _('show only help for commands')),
3576 3578 ('k', 'keyword', '', _('show topics matching keyword')),
3577 3579 ],
3578 3580 _('[-ec] [TOPIC]'),
3579 3581 norepo=True)
3580 3582 def help_(ui, name=None, **opts):
3581 3583 """show help for a given topic or a help overview
3582 3584
3583 3585 With no arguments, print a list of commands with short help messages.
3584 3586
3585 3587 Given a topic, extension, or command name, print help for that
3586 3588 topic.
3587 3589
3588 3590 Returns 0 if successful.
3589 3591 """
3590 3592
3591 3593 textwidth = min(ui.termwidth(), 80) - 2
3592 3594
3593 3595 keep = ui.verbose and ['verbose'] or []
3594 3596 text = help.help_(ui, name, **opts)
3595 3597
3596 3598 formatted, pruned = minirst.format(text, textwidth, keep=keep)
3597 3599 if 'verbose' in pruned:
3598 3600 keep.append('omitted')
3599 3601 else:
3600 3602 keep.append('notomitted')
3601 3603 formatted, pruned = minirst.format(text, textwidth, keep=keep)
3602 3604 ui.write(formatted)
3603 3605
3604 3606
3605 3607 @command('identify|id',
3606 3608 [('r', 'rev', '',
3607 3609 _('identify the specified revision'), _('REV')),
3608 3610 ('n', 'num', None, _('show local revision number')),
3609 3611 ('i', 'id', None, _('show global revision id')),
3610 3612 ('b', 'branch', None, _('show branch')),
3611 3613 ('t', 'tags', None, _('show tags')),
3612 3614 ('B', 'bookmarks', None, _('show bookmarks')),
3613 3615 ] + remoteopts,
3614 3616 _('[-nibtB] [-r REV] [SOURCE]'),
3615 3617 optionalrepo=True)
3616 3618 def identify(ui, repo, source=None, rev=None,
3617 3619 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
3618 3620 """identify the working copy or specified revision
3619 3621
3620 3622 Print a summary identifying the repository state at REV using one or
3621 3623 two parent hash identifiers, followed by a "+" if the working
3622 3624 directory has uncommitted changes, the branch name (if not default),
3623 3625 a list of tags, and a list of bookmarks.
3624 3626
3625 3627 When REV is not given, print a summary of the current state of the
3626 3628 repository.
3627 3629
3628 3630 Specifying a path to a repository root or Mercurial bundle will
3629 3631 cause lookup to operate on that repository/bundle.
3630 3632
3631 3633 .. container:: verbose
3632 3634
3633 3635 Examples:
3634 3636
3635 3637 - generate a build identifier for the working directory::
3636 3638
3637 3639 hg id --id > build-id.dat
3638 3640
3639 3641 - find the revision corresponding to a tag::
3640 3642
3641 3643 hg id -n -r 1.3
3642 3644
3643 3645 - check the most recent revision of a remote repository::
3644 3646
3645 3647 hg id -r tip http://selenic.com/hg/
3646 3648
3647 3649 Returns 0 if successful.
3648 3650 """
3649 3651
3650 3652 if not repo and not source:
3651 3653 raise util.Abort(_("there is no Mercurial repository here "
3652 3654 "(.hg not found)"))
3653 3655
3654 3656 hexfunc = ui.debugflag and hex or short
3655 3657 default = not (num or id or branch or tags or bookmarks)
3656 3658 output = []
3657 3659 revs = []
3658 3660
3659 3661 if source:
3660 3662 source, branches = hg.parseurl(ui.expandpath(source))
3661 3663 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
3662 3664 repo = peer.local()
3663 3665 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
3664 3666
3665 3667 if not repo:
3666 3668 if num or branch or tags:
3667 3669 raise util.Abort(
3668 3670 _("can't query remote revision number, branch, or tags"))
3669 3671 if not rev and revs:
3670 3672 rev = revs[0]
3671 3673 if not rev:
3672 3674 rev = "tip"
3673 3675
3674 3676 remoterev = peer.lookup(rev)
3675 3677 if default or id:
3676 3678 output = [hexfunc(remoterev)]
3677 3679
3678 3680 def getbms():
3679 3681 bms = []
3680 3682
3681 3683 if 'bookmarks' in peer.listkeys('namespaces'):
3682 3684 hexremoterev = hex(remoterev)
3683 3685 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
3684 3686 if bmr == hexremoterev]
3685 3687
3686 3688 return sorted(bms)
3687 3689
3688 3690 if bookmarks:
3689 3691 output.extend(getbms())
3690 3692 elif default and not ui.quiet:
3691 3693 # multiple bookmarks for a single parent separated by '/'
3692 3694 bm = '/'.join(getbms())
3693 3695 if bm:
3694 3696 output.append(bm)
3695 3697 else:
3696 3698 if not rev:
3697 3699 ctx = repo[None]
3698 3700 parents = ctx.parents()
3699 3701 changed = ""
3700 3702 if default or id or num:
3701 3703 if (util.any(repo.status())
3702 3704 or util.any(ctx.sub(s).dirty() for s in ctx.substate)):
3703 3705 changed = '+'
3704 3706 if default or id:
3705 3707 output = ["%s%s" %
3706 3708 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
3707 3709 if num:
3708 3710 output.append("%s%s" %
3709 3711 ('+'.join([str(p.rev()) for p in parents]), changed))
3710 3712 else:
3711 3713 ctx = scmutil.revsingle(repo, rev)
3712 3714 if default or id:
3713 3715 output = [hexfunc(ctx.node())]
3714 3716 if num:
3715 3717 output.append(str(ctx.rev()))
3716 3718
3717 3719 if default and not ui.quiet:
3718 3720 b = ctx.branch()
3719 3721 if b != 'default':
3720 3722 output.append("(%s)" % b)
3721 3723
3722 3724 # multiple tags for a single parent separated by '/'
3723 3725 t = '/'.join(ctx.tags())
3724 3726 if t:
3725 3727 output.append(t)
3726 3728
3727 3729 # multiple bookmarks for a single parent separated by '/'
3728 3730 bm = '/'.join(ctx.bookmarks())
3729 3731 if bm:
3730 3732 output.append(bm)
3731 3733 else:
3732 3734 if branch:
3733 3735 output.append(ctx.branch())
3734 3736
3735 3737 if tags:
3736 3738 output.extend(ctx.tags())
3737 3739
3738 3740 if bookmarks:
3739 3741 output.extend(ctx.bookmarks())
3740 3742
3741 3743 ui.write("%s\n" % ' '.join(output))
3742 3744
3743 3745 @command('import|patch',
3744 3746 [('p', 'strip', 1,
3745 3747 _('directory strip option for patch. This has the same '
3746 3748 'meaning as the corresponding patch option'), _('NUM')),
3747 3749 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
3748 3750 ('e', 'edit', False, _('invoke editor on commit messages')),
3749 3751 ('f', 'force', None,
3750 3752 _('skip check for outstanding uncommitted changes (DEPRECATED)')),
3751 3753 ('', 'no-commit', None,
3752 3754 _("don't commit, just update the working directory")),
3753 3755 ('', 'bypass', None,
3754 3756 _("apply patch without touching the working directory")),
3755 3757 ('', 'partial', None,
3756 3758 _('commit even if some hunks fail')),
3757 3759 ('', 'exact', None,
3758 3760 _('apply patch to the nodes from which it was generated')),
3759 3761 ('', 'import-branch', None,
3760 3762 _('use any branch information in patch (implied by --exact)'))] +
3761 3763 commitopts + commitopts2 + similarityopts,
3762 3764 _('[OPTION]... PATCH...'))
3763 3765 def import_(ui, repo, patch1=None, *patches, **opts):
3764 3766 """import an ordered set of patches
3765 3767
3766 3768 Import a list of patches and commit them individually (unless
3767 3769 --no-commit is specified).
3768 3770
3769 3771 Because import first applies changes to the working directory,
3770 3772 import will abort if there are outstanding changes.
3771 3773
3772 3774 You can import a patch straight from a mail message. Even patches
3773 3775 as attachments work (to use the body part, it must have type
3774 3776 text/plain or text/x-patch). From and Subject headers of email
3775 3777 message are used as default committer and commit message. All
3776 3778 text/plain body parts before first diff are added to commit
3777 3779 message.
3778 3780
3779 3781 If the imported patch was generated by :hg:`export`, user and
3780 3782 description from patch override values from message headers and
3781 3783 body. Values given on command line with -m/--message and -u/--user
3782 3784 override these.
3783 3785
3784 3786 If --exact is specified, import will set the working directory to
3785 3787 the parent of each patch before applying it, and will abort if the
3786 3788 resulting changeset has a different ID than the one recorded in
3787 3789 the patch. This may happen due to character set problems or other
3788 3790 deficiencies in the text patch format.
3789 3791
3790 3792 Use --bypass to apply and commit patches directly to the
3791 3793 repository, not touching the working directory. Without --exact,
3792 3794 patches will be applied on top of the working directory parent
3793 3795 revision.
3794 3796
3795 3797 With -s/--similarity, hg will attempt to discover renames and
3796 3798 copies in the patch in the same way as :hg:`addremove`.
3797 3799
3798 3800 Use --partial to ensure a changeset will be created from the patch
3799 3801 even if some hunks fail to apply. Hunks that fail to apply will be
3800 3802 written to a <target-file>.rej file. Conflicts can then be resolved
3801 3803 by hand before :hg:`commit --amend` is run to update the created
3802 3804 changeset. This flag exists to let people import patches that
3803 3805 partially apply without losing the associated metadata (author,
3804 3806 date, description, ...). Note that when none of the hunk applies
3805 3807 cleanly, :hg:`import --partial` will create an empty changeset,
3806 3808 importing only the patch metadata.
3807 3809
3808 3810 To read a patch from standard input, use "-" as the patch name. If
3809 3811 a URL is specified, the patch will be downloaded from it.
3810 3812 See :hg:`help dates` for a list of formats valid for -d/--date.
3811 3813
3812 3814 .. container:: verbose
3813 3815
3814 3816 Examples:
3815 3817
3816 3818 - import a traditional patch from a website and detect renames::
3817 3819
3818 3820 hg import -s 80 http://example.com/bugfix.patch
3819 3821
3820 3822 - import a changeset from an hgweb server::
3821 3823
3822 3824 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
3823 3825
3824 3826 - import all the patches in an Unix-style mbox::
3825 3827
3826 3828 hg import incoming-patches.mbox
3827 3829
3828 3830 - attempt to exactly restore an exported changeset (not always
3829 3831 possible)::
3830 3832
3831 3833 hg import --exact proposed-fix.patch
3832 3834
3833 3835 Returns 0 on success, 1 on partial success (see --partial).
3834 3836 """
3835 3837
3836 3838 if not patch1:
3837 3839 raise util.Abort(_('need at least one patch to import'))
3838 3840
3839 3841 patches = (patch1,) + patches
3840 3842
3841 3843 date = opts.get('date')
3842 3844 if date:
3843 3845 opts['date'] = util.parsedate(date)
3844 3846
3845 3847 update = not opts.get('bypass')
3846 3848 if not update and opts.get('no_commit'):
3847 3849 raise util.Abort(_('cannot use --no-commit with --bypass'))
3848 3850 try:
3849 3851 sim = float(opts.get('similarity') or 0)
3850 3852 except ValueError:
3851 3853 raise util.Abort(_('similarity must be a number'))
3852 3854 if sim < 0 or sim > 100:
3853 3855 raise util.Abort(_('similarity must be between 0 and 100'))
3854 3856 if sim and not update:
3855 3857 raise util.Abort(_('cannot use --similarity with --bypass'))
3856 3858
3857 3859 if update:
3858 3860 cmdutil.checkunfinished(repo)
3859 3861 if (opts.get('exact') or not opts.get('force')) and update:
3860 3862 cmdutil.bailifchanged(repo)
3861 3863
3862 3864 base = opts["base"]
3863 3865 wlock = lock = tr = None
3864 3866 msgs = []
3865 3867 ret = 0
3866 3868
3867 3869
3868 3870 try:
3869 3871 try:
3870 3872 wlock = repo.wlock()
3871 3873 if not opts.get('no_commit'):
3872 3874 lock = repo.lock()
3873 3875 tr = repo.transaction('import')
3874 3876 parents = repo.parents()
3875 3877 for patchurl in patches:
3876 3878 if patchurl == '-':
3877 3879 ui.status(_('applying patch from stdin\n'))
3878 3880 patchfile = ui.fin
3879 3881 patchurl = 'stdin' # for error message
3880 3882 else:
3881 3883 patchurl = os.path.join(base, patchurl)
3882 3884 ui.status(_('applying %s\n') % patchurl)
3883 3885 patchfile = hg.openpath(ui, patchurl)
3884 3886
3885 3887 haspatch = False
3886 3888 for hunk in patch.split(patchfile):
3887 3889 (msg, node, rej) = cmdutil.tryimportone(ui, repo, hunk,
3888 3890 parents, opts,
3889 3891 msgs, hg.clean)
3890 3892 if msg:
3891 3893 haspatch = True
3892 3894 ui.note(msg + '\n')
3893 3895 if update or opts.get('exact'):
3894 3896 parents = repo.parents()
3895 3897 else:
3896 3898 parents = [repo[node]]
3897 3899 if rej:
3898 3900 ui.write_err(_("patch applied partially\n"))
3899 3901 ui.write_err(_("(fix the .rej files and run "
3900 3902 "`hg commit --amend`)\n"))
3901 3903 ret = 1
3902 3904 break
3903 3905
3904 3906 if not haspatch:
3905 3907 raise util.Abort(_('%s: no diffs found') % patchurl)
3906 3908
3907 3909 if tr:
3908 3910 tr.close()
3909 3911 if msgs:
3910 3912 repo.savecommitmessage('\n* * *\n'.join(msgs))
3911 3913 return ret
3912 3914 except: # re-raises
3913 3915 # wlock.release() indirectly calls dirstate.write(): since
3914 3916 # we're crashing, we do not want to change the working dir
3915 3917 # parent after all, so make sure it writes nothing
3916 3918 repo.dirstate.invalidate()
3917 3919 raise
3918 3920 finally:
3919 3921 if tr:
3920 3922 tr.release()
3921 3923 release(lock, wlock)
3922 3924
3923 3925 @command('incoming|in',
3924 3926 [('f', 'force', None,
3925 3927 _('run even if remote repository is unrelated')),
3926 3928 ('n', 'newest-first', None, _('show newest record first')),
3927 3929 ('', 'bundle', '',
3928 3930 _('file to store the bundles into'), _('FILE')),
3929 3931 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3930 3932 ('B', 'bookmarks', False, _("compare bookmarks")),
3931 3933 ('b', 'branch', [],
3932 3934 _('a specific branch you would like to pull'), _('BRANCH')),
3933 3935 ] + logopts + remoteopts + subrepoopts,
3934 3936 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3935 3937 def incoming(ui, repo, source="default", **opts):
3936 3938 """show new changesets found in source
3937 3939
3938 3940 Show new changesets found in the specified path/URL or the default
3939 3941 pull location. These are the changesets that would have been pulled
3940 3942 if a pull at the time you issued this command.
3941 3943
3942 3944 For remote repository, using --bundle avoids downloading the
3943 3945 changesets twice if the incoming is followed by a pull.
3944 3946
3945 3947 See pull for valid source format details.
3946 3948
3947 3949 .. container:: verbose
3948 3950
3949 3951 Examples:
3950 3952
3951 3953 - show incoming changes with patches and full description::
3952 3954
3953 3955 hg incoming -vp
3954 3956
3955 3957 - show incoming changes excluding merges, store a bundle::
3956 3958
3957 3959 hg in -vpM --bundle incoming.hg
3958 3960 hg pull incoming.hg
3959 3961
3960 3962 - briefly list changes inside a bundle::
3961 3963
3962 3964 hg in changes.hg -T "{desc|firstline}\\n"
3963 3965
3964 3966 Returns 0 if there are incoming changes, 1 otherwise.
3965 3967 """
3966 3968 if opts.get('graph'):
3967 3969 cmdutil.checkunsupportedgraphflags([], opts)
3968 3970 def display(other, chlist, displayer):
3969 3971 revdag = cmdutil.graphrevs(other, chlist, opts)
3970 3972 showparents = [ctx.node() for ctx in repo[None].parents()]
3971 3973 cmdutil.displaygraph(ui, revdag, displayer, showparents,
3972 3974 graphmod.asciiedges)
3973 3975
3974 3976 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
3975 3977 return 0
3976 3978
3977 3979 if opts.get('bundle') and opts.get('subrepos'):
3978 3980 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3979 3981
3980 3982 if opts.get('bookmarks'):
3981 3983 source, branches = hg.parseurl(ui.expandpath(source),
3982 3984 opts.get('branch'))
3983 3985 other = hg.peer(repo, opts, source)
3984 3986 if 'bookmarks' not in other.listkeys('namespaces'):
3985 3987 ui.warn(_("remote doesn't support bookmarks\n"))
3986 3988 return 0
3987 3989 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3988 3990 return bookmarks.diff(ui, repo, other)
3989 3991
3990 3992 repo._subtoppath = ui.expandpath(source)
3991 3993 try:
3992 3994 return hg.incoming(ui, repo, source, opts)
3993 3995 finally:
3994 3996 del repo._subtoppath
3995 3997
3996 3998
3997 3999 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'),
3998 4000 norepo=True)
3999 4001 def init(ui, dest=".", **opts):
4000 4002 """create a new repository in the given directory
4001 4003
4002 4004 Initialize a new repository in the given directory. If the given
4003 4005 directory does not exist, it will be created.
4004 4006
4005 4007 If no directory is given, the current directory is used.
4006 4008
4007 4009 It is possible to specify an ``ssh://`` URL as the destination.
4008 4010 See :hg:`help urls` for more information.
4009 4011
4010 4012 Returns 0 on success.
4011 4013 """
4012 4014 hg.peer(ui, opts, ui.expandpath(dest), create=True)
4013 4015
4014 4016 @command('locate',
4015 4017 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
4016 4018 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4017 4019 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
4018 4020 ] + walkopts,
4019 4021 _('[OPTION]... [PATTERN]...'))
4020 4022 def locate(ui, repo, *pats, **opts):
4021 4023 """locate files matching specific patterns
4022 4024
4023 4025 Print files under Mercurial control in the working directory whose
4024 4026 names match the given patterns.
4025 4027
4026 4028 By default, this command searches all directories in the working
4027 4029 directory. To search just the current directory and its
4028 4030 subdirectories, use "--include .".
4029 4031
4030 4032 If no patterns are given to match, this command prints the names
4031 4033 of all files under Mercurial control in the working directory.
4032 4034
4033 4035 If you want to feed the output of this command into the "xargs"
4034 4036 command, use the -0 option to both this command and "xargs". This
4035 4037 will avoid the problem of "xargs" treating single filenames that
4036 4038 contain whitespace as multiple filenames.
4037 4039
4038 4040 Returns 0 if a match is found, 1 otherwise.
4039 4041 """
4040 4042 end = opts.get('print0') and '\0' or '\n'
4041 4043 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
4042 4044
4043 4045 ret = 1
4044 4046 ctx = repo[rev]
4045 4047 m = scmutil.match(ctx, pats, opts, default='relglob')
4046 4048 m.bad = lambda x, y: False
4047 4049
4048 4050 for abs in ctx.matches(m):
4049 4051 if opts.get('fullpath'):
4050 4052 ui.write(repo.wjoin(abs), end)
4051 4053 else:
4052 4054 ui.write(((pats and m.rel(abs)) or abs), end)
4053 4055 ret = 0
4054 4056
4055 4057 return ret
4056 4058
4057 4059 @command('^log|history',
4058 4060 [('f', 'follow', None,
4059 4061 _('follow changeset history, or file history across copies and renames')),
4060 4062 ('', 'follow-first', None,
4061 4063 _('only follow the first parent of merge changesets (DEPRECATED)')),
4062 4064 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
4063 4065 ('C', 'copies', None, _('show copied files')),
4064 4066 ('k', 'keyword', [],
4065 4067 _('do case-insensitive search for a given text'), _('TEXT')),
4066 4068 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
4067 4069 ('', 'removed', None, _('include revisions where files were removed')),
4068 4070 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
4069 4071 ('u', 'user', [], _('revisions committed by user'), _('USER')),
4070 4072 ('', 'only-branch', [],
4071 4073 _('show only changesets within the given named branch (DEPRECATED)'),
4072 4074 _('BRANCH')),
4073 4075 ('b', 'branch', [],
4074 4076 _('show changesets within the given named branch'), _('BRANCH')),
4075 4077 ('P', 'prune', [],
4076 4078 _('do not display revision or any of its ancestors'), _('REV')),
4077 4079 ] + logopts + walkopts,
4078 4080 _('[OPTION]... [FILE]'),
4079 4081 inferrepo=True)
4080 4082 def log(ui, repo, *pats, **opts):
4081 4083 """show revision history of entire repository or files
4082 4084
4083 4085 Print the revision history of the specified files or the entire
4084 4086 project.
4085 4087
4086 4088 If no revision range is specified, the default is ``tip:0`` unless
4087 4089 --follow is set, in which case the working directory parent is
4088 4090 used as the starting revision.
4089 4091
4090 4092 File history is shown without following rename or copy history of
4091 4093 files. Use -f/--follow with a filename to follow history across
4092 4094 renames and copies. --follow without a filename will only show
4093 4095 ancestors or descendants of the starting revision.
4094 4096
4095 4097 By default this command prints revision number and changeset id,
4096 4098 tags, non-trivial parents, user, date and time, and a summary for
4097 4099 each commit. When the -v/--verbose switch is used, the list of
4098 4100 changed files and full commit message are shown.
4099 4101
4100 4102 With --graph the revisions are shown as an ASCII art DAG with the most
4101 4103 recent changeset at the top.
4102 4104 'o' is a changeset, '@' is a working directory parent, 'x' is obsolete,
4103 4105 and '+' represents a fork where the changeset from the lines below is a
4104 4106 parent of the 'o' merge on the same line.
4105 4107
4106 4108 .. note::
4107 4109
4108 4110 log -p/--patch may generate unexpected diff output for merge
4109 4111 changesets, as it will only compare the merge changeset against
4110 4112 its first parent. Also, only files different from BOTH parents
4111 4113 will appear in files:.
4112 4114
4113 4115 .. note::
4114 4116
4115 4117 for performance reasons, log FILE may omit duplicate changes
4116 4118 made on branches and will not show deletions. To see all
4117 4119 changes including duplicates and deletions, use the --removed
4118 4120 switch.
4119 4121
4120 4122 .. container:: verbose
4121 4123
4122 4124 Some examples:
4123 4125
4124 4126 - changesets with full descriptions and file lists::
4125 4127
4126 4128 hg log -v
4127 4129
4128 4130 - changesets ancestral to the working directory::
4129 4131
4130 4132 hg log -f
4131 4133
4132 4134 - last 10 commits on the current branch::
4133 4135
4134 4136 hg log -l 10 -b .
4135 4137
4136 4138 - changesets showing all modifications of a file, including removals::
4137 4139
4138 4140 hg log --removed file.c
4139 4141
4140 4142 - all changesets that touch a directory, with diffs, excluding merges::
4141 4143
4142 4144 hg log -Mp lib/
4143 4145
4144 4146 - all revision numbers that match a keyword::
4145 4147
4146 4148 hg log -k bug --template "{rev}\\n"
4147 4149
4148 4150 - list available log templates::
4149 4151
4150 4152 hg log -T list
4151 4153
4152 4154 - check if a given changeset is included is a tagged release::
4153 4155
4154 4156 hg log -r "a21ccf and ancestor(1.9)"
4155 4157
4156 4158 - find all changesets by some user in a date range::
4157 4159
4158 4160 hg log -k alice -d "may 2008 to jul 2008"
4159 4161
4160 4162 - summary of all changesets after the last tag::
4161 4163
4162 4164 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
4163 4165
4164 4166 See :hg:`help dates` for a list of formats valid for -d/--date.
4165 4167
4166 4168 See :hg:`help revisions` and :hg:`help revsets` for more about
4167 4169 specifying revisions.
4168 4170
4169 4171 See :hg:`help templates` for more about pre-packaged styles and
4170 4172 specifying custom templates.
4171 4173
4172 4174 Returns 0 on success.
4173 4175 """
4174 4176 if opts.get('graph'):
4175 4177 return cmdutil.graphlog(ui, repo, *pats, **opts)
4176 4178
4177 4179 revs, expr, filematcher = cmdutil.getlogrevs(repo, pats, opts)
4178 4180 limit = cmdutil.loglimit(opts)
4179 4181 count = 0
4180 4182
4181 4183 getrenamed = None
4182 4184 if opts.get('copies'):
4183 4185 endrev = None
4184 4186 if opts.get('rev'):
4185 4187 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
4186 4188 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
4187 4189
4188 4190 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
4189 4191 for rev in revs:
4190 4192 if count == limit:
4191 4193 break
4192 4194 ctx = repo[rev]
4193 4195 copies = None
4194 4196 if getrenamed is not None and rev:
4195 4197 copies = []
4196 4198 for fn in ctx.files():
4197 4199 rename = getrenamed(fn, rev)
4198 4200 if rename:
4199 4201 copies.append((fn, rename[0]))
4200 4202 revmatchfn = filematcher and filematcher(ctx.rev()) or None
4201 4203 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
4202 4204 if displayer.flush(rev):
4203 4205 count += 1
4204 4206
4205 4207 displayer.close()
4206 4208
4207 4209 @command('manifest',
4208 4210 [('r', 'rev', '', _('revision to display'), _('REV')),
4209 4211 ('', 'all', False, _("list files from all revisions"))],
4210 4212 _('[-r REV]'))
4211 4213 def manifest(ui, repo, node=None, rev=None, **opts):
4212 4214 """output the current or given revision of the project manifest
4213 4215
4214 4216 Print a list of version controlled files for the given revision.
4215 4217 If no revision is given, the first parent of the working directory
4216 4218 is used, or the null revision if no revision is checked out.
4217 4219
4218 4220 With -v, print file permissions, symlink and executable bits.
4219 4221 With --debug, print file revision hashes.
4220 4222
4221 4223 If option --all is specified, the list of all files from all revisions
4222 4224 is printed. This includes deleted and renamed files.
4223 4225
4224 4226 Returns 0 on success.
4225 4227 """
4226 4228
4227 4229 fm = ui.formatter('manifest', opts)
4228 4230
4229 4231 if opts.get('all'):
4230 4232 if rev or node:
4231 4233 raise util.Abort(_("can't specify a revision with --all"))
4232 4234
4233 4235 res = []
4234 4236 prefix = "data/"
4235 4237 suffix = ".i"
4236 4238 plen = len(prefix)
4237 4239 slen = len(suffix)
4238 4240 lock = repo.lock()
4239 4241 try:
4240 4242 for fn, b, size in repo.store.datafiles():
4241 4243 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
4242 4244 res.append(fn[plen:-slen])
4243 4245 finally:
4244 4246 lock.release()
4245 4247 for f in res:
4246 4248 fm.startitem()
4247 4249 fm.write("path", '%s\n', f)
4248 4250 fm.end()
4249 4251 return
4250 4252
4251 4253 if rev and node:
4252 4254 raise util.Abort(_("please specify just one revision"))
4253 4255
4254 4256 if not node:
4255 4257 node = rev
4256 4258
4257 4259 char = {'l': '@', 'x': '*', '': ''}
4258 4260 mode = {'l': '644', 'x': '755', '': '644'}
4259 4261 ctx = scmutil.revsingle(repo, node)
4260 4262 mf = ctx.manifest()
4261 4263 for f in ctx:
4262 4264 fm.startitem()
4263 4265 fl = ctx[f].flags()
4264 4266 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
4265 4267 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
4266 4268 fm.write('path', '%s\n', f)
4267 4269 fm.end()
4268 4270
4269 4271 @command('^merge',
4270 4272 [('f', 'force', None,
4271 4273 _('force a merge including outstanding changes (DEPRECATED)')),
4272 4274 ('r', 'rev', '', _('revision to merge'), _('REV')),
4273 4275 ('P', 'preview', None,
4274 4276 _('review revisions to merge (no merge is performed)'))
4275 4277 ] + mergetoolopts,
4276 4278 _('[-P] [-f] [[-r] REV]'))
4277 4279 def merge(ui, repo, node=None, **opts):
4278 4280 """merge working directory with another revision
4279 4281
4280 4282 The current working directory is updated with all changes made in
4281 4283 the requested revision since the last common predecessor revision.
4282 4284
4283 4285 Files that changed between either parent are marked as changed for
4284 4286 the next commit and a commit must be performed before any further
4285 4287 updates to the repository are allowed. The next commit will have
4286 4288 two parents.
4287 4289
4288 4290 ``--tool`` can be used to specify the merge tool used for file
4289 4291 merges. It overrides the HGMERGE environment variable and your
4290 4292 configuration files. See :hg:`help merge-tools` for options.
4291 4293
4292 4294 If no revision is specified, the working directory's parent is a
4293 4295 head revision, and the current branch contains exactly one other
4294 4296 head, the other head is merged with by default. Otherwise, an
4295 4297 explicit revision with which to merge with must be provided.
4296 4298
4297 4299 :hg:`resolve` must be used to resolve unresolved files.
4298 4300
4299 4301 To undo an uncommitted merge, use :hg:`update --clean .` which
4300 4302 will check out a clean copy of the original merge parent, losing
4301 4303 all changes.
4302 4304
4303 4305 Returns 0 on success, 1 if there are unresolved files.
4304 4306 """
4305 4307
4306 4308 if opts.get('rev') and node:
4307 4309 raise util.Abort(_("please specify just one revision"))
4308 4310 if not node:
4309 4311 node = opts.get('rev')
4310 4312
4311 4313 if node:
4312 4314 node = scmutil.revsingle(repo, node).node()
4313 4315
4314 4316 if not node and repo._bookmarkcurrent:
4315 4317 bmheads = repo.bookmarkheads(repo._bookmarkcurrent)
4316 4318 curhead = repo[repo._bookmarkcurrent].node()
4317 4319 if len(bmheads) == 2:
4318 4320 if curhead == bmheads[0]:
4319 4321 node = bmheads[1]
4320 4322 else:
4321 4323 node = bmheads[0]
4322 4324 elif len(bmheads) > 2:
4323 4325 raise util.Abort(_("multiple matching bookmarks to merge - "
4324 4326 "please merge with an explicit rev or bookmark"),
4325 4327 hint=_("run 'hg heads' to see all heads"))
4326 4328 elif len(bmheads) <= 1:
4327 4329 raise util.Abort(_("no matching bookmark to merge - "
4328 4330 "please merge with an explicit rev or bookmark"),
4329 4331 hint=_("run 'hg heads' to see all heads"))
4330 4332
4331 4333 if not node and not repo._bookmarkcurrent:
4332 4334 branch = repo[None].branch()
4333 4335 bheads = repo.branchheads(branch)
4334 4336 nbhs = [bh for bh in bheads if not repo[bh].bookmarks()]
4335 4337
4336 4338 if len(nbhs) > 2:
4337 4339 raise util.Abort(_("branch '%s' has %d heads - "
4338 4340 "please merge with an explicit rev")
4339 4341 % (branch, len(bheads)),
4340 4342 hint=_("run 'hg heads .' to see heads"))
4341 4343
4342 4344 parent = repo.dirstate.p1()
4343 4345 if len(nbhs) <= 1:
4344 4346 if len(bheads) > 1:
4345 4347 raise util.Abort(_("heads are bookmarked - "
4346 4348 "please merge with an explicit rev"),
4347 4349 hint=_("run 'hg heads' to see all heads"))
4348 4350 if len(repo.heads()) > 1:
4349 4351 raise util.Abort(_("branch '%s' has one head - "
4350 4352 "please merge with an explicit rev")
4351 4353 % branch,
4352 4354 hint=_("run 'hg heads' to see all heads"))
4353 4355 msg, hint = _('nothing to merge'), None
4354 4356 if parent != repo.lookup(branch):
4355 4357 hint = _("use 'hg update' instead")
4356 4358 raise util.Abort(msg, hint=hint)
4357 4359
4358 4360 if parent not in bheads:
4359 4361 raise util.Abort(_('working directory not at a head revision'),
4360 4362 hint=_("use 'hg update' or merge with an "
4361 4363 "explicit revision"))
4362 4364 if parent == nbhs[0]:
4363 4365 node = nbhs[-1]
4364 4366 else:
4365 4367 node = nbhs[0]
4366 4368
4367 4369 if opts.get('preview'):
4368 4370 # find nodes that are ancestors of p2 but not of p1
4369 4371 p1 = repo.lookup('.')
4370 4372 p2 = repo.lookup(node)
4371 4373 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4372 4374
4373 4375 displayer = cmdutil.show_changeset(ui, repo, opts)
4374 4376 for node in nodes:
4375 4377 displayer.show(repo[node])
4376 4378 displayer.close()
4377 4379 return 0
4378 4380
4379 4381 try:
4380 4382 # ui.forcemerge is an internal variable, do not document
4381 4383 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''), 'merge')
4382 4384 return hg.merge(repo, node, force=opts.get('force'))
4383 4385 finally:
4384 4386 ui.setconfig('ui', 'forcemerge', '', 'merge')
4385 4387
4386 4388 @command('outgoing|out',
4387 4389 [('f', 'force', None, _('run even when the destination is unrelated')),
4388 4390 ('r', 'rev', [],
4389 4391 _('a changeset intended to be included in the destination'), _('REV')),
4390 4392 ('n', 'newest-first', None, _('show newest record first')),
4391 4393 ('B', 'bookmarks', False, _('compare bookmarks')),
4392 4394 ('b', 'branch', [], _('a specific branch you would like to push'),
4393 4395 _('BRANCH')),
4394 4396 ] + logopts + remoteopts + subrepoopts,
4395 4397 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
4396 4398 def outgoing(ui, repo, dest=None, **opts):
4397 4399 """show changesets not found in the destination
4398 4400
4399 4401 Show changesets not found in the specified destination repository
4400 4402 or the default push location. These are the changesets that would
4401 4403 be pushed if a push was requested.
4402 4404
4403 4405 See pull for details of valid destination formats.
4404 4406
4405 4407 Returns 0 if there are outgoing changes, 1 otherwise.
4406 4408 """
4407 4409 if opts.get('graph'):
4408 4410 cmdutil.checkunsupportedgraphflags([], opts)
4409 4411 o, other = hg._outgoing(ui, repo, dest, opts)
4410 4412 if not o:
4411 4413 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4412 4414 return
4413 4415
4414 4416 revdag = cmdutil.graphrevs(repo, o, opts)
4415 4417 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
4416 4418 showparents = [ctx.node() for ctx in repo[None].parents()]
4417 4419 cmdutil.displaygraph(ui, revdag, displayer, showparents,
4418 4420 graphmod.asciiedges)
4419 4421 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4420 4422 return 0
4421 4423
4422 4424 if opts.get('bookmarks'):
4423 4425 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4424 4426 dest, branches = hg.parseurl(dest, opts.get('branch'))
4425 4427 other = hg.peer(repo, opts, dest)
4426 4428 if 'bookmarks' not in other.listkeys('namespaces'):
4427 4429 ui.warn(_("remote doesn't support bookmarks\n"))
4428 4430 return 0
4429 4431 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
4430 4432 return bookmarks.diff(ui, other, repo)
4431 4433
4432 4434 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
4433 4435 try:
4434 4436 return hg.outgoing(ui, repo, dest, opts)
4435 4437 finally:
4436 4438 del repo._subtoppath
4437 4439
4438 4440 @command('parents',
4439 4441 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
4440 4442 ] + templateopts,
4441 4443 _('[-r REV] [FILE]'),
4442 4444 inferrepo=True)
4443 4445 def parents(ui, repo, file_=None, **opts):
4444 4446 """show the parents of the working directory or revision
4445 4447
4446 4448 Print the working directory's parent revisions. If a revision is
4447 4449 given via -r/--rev, the parent of that revision will be printed.
4448 4450 If a file argument is given, the revision in which the file was
4449 4451 last changed (before the working directory revision or the
4450 4452 argument to --rev if given) is printed.
4451 4453
4452 4454 Returns 0 on success.
4453 4455 """
4454 4456
4455 4457 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
4456 4458
4457 4459 if file_:
4458 4460 m = scmutil.match(ctx, (file_,), opts)
4459 4461 if m.anypats() or len(m.files()) != 1:
4460 4462 raise util.Abort(_('can only specify an explicit filename'))
4461 4463 file_ = m.files()[0]
4462 4464 filenodes = []
4463 4465 for cp in ctx.parents():
4464 4466 if not cp:
4465 4467 continue
4466 4468 try:
4467 4469 filenodes.append(cp.filenode(file_))
4468 4470 except error.LookupError:
4469 4471 pass
4470 4472 if not filenodes:
4471 4473 raise util.Abort(_("'%s' not found in manifest!") % file_)
4472 4474 p = []
4473 4475 for fn in filenodes:
4474 4476 fctx = repo.filectx(file_, fileid=fn)
4475 4477 p.append(fctx.node())
4476 4478 else:
4477 4479 p = [cp.node() for cp in ctx.parents()]
4478 4480
4479 4481 displayer = cmdutil.show_changeset(ui, repo, opts)
4480 4482 for n in p:
4481 4483 if n != nullid:
4482 4484 displayer.show(repo[n])
4483 4485 displayer.close()
4484 4486
4485 4487 @command('paths', [], _('[NAME]'), optionalrepo=True)
4486 4488 def paths(ui, repo, search=None):
4487 4489 """show aliases for remote repositories
4488 4490
4489 4491 Show definition of symbolic path name NAME. If no name is given,
4490 4492 show definition of all available names.
4491 4493
4492 4494 Option -q/--quiet suppresses all output when searching for NAME
4493 4495 and shows only the path names when listing all definitions.
4494 4496
4495 4497 Path names are defined in the [paths] section of your
4496 4498 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
4497 4499 repository, ``.hg/hgrc`` is used, too.
4498 4500
4499 4501 The path names ``default`` and ``default-push`` have a special
4500 4502 meaning. When performing a push or pull operation, they are used
4501 4503 as fallbacks if no location is specified on the command-line.
4502 4504 When ``default-push`` is set, it will be used for push and
4503 4505 ``default`` will be used for pull; otherwise ``default`` is used
4504 4506 as the fallback for both. When cloning a repository, the clone
4505 4507 source is written as ``default`` in ``.hg/hgrc``. Note that
4506 4508 ``default`` and ``default-push`` apply to all inbound (e.g.
4507 4509 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
4508 4510 :hg:`bundle`) operations.
4509 4511
4510 4512 See :hg:`help urls` for more information.
4511 4513
4512 4514 Returns 0 on success.
4513 4515 """
4514 4516 if search:
4515 4517 for name, path in ui.configitems("paths"):
4516 4518 if name == search:
4517 4519 ui.status("%s\n" % util.hidepassword(path))
4518 4520 return
4519 4521 if not ui.quiet:
4520 4522 ui.warn(_("not found!\n"))
4521 4523 return 1
4522 4524 else:
4523 4525 for name, path in ui.configitems("paths"):
4524 4526 if ui.quiet:
4525 4527 ui.write("%s\n" % name)
4526 4528 else:
4527 4529 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
4528 4530
4529 4531 @command('phase',
4530 4532 [('p', 'public', False, _('set changeset phase to public')),
4531 4533 ('d', 'draft', False, _('set changeset phase to draft')),
4532 4534 ('s', 'secret', False, _('set changeset phase to secret')),
4533 4535 ('f', 'force', False, _('allow to move boundary backward')),
4534 4536 ('r', 'rev', [], _('target revision'), _('REV')),
4535 4537 ],
4536 4538 _('[-p|-d|-s] [-f] [-r] REV...'))
4537 4539 def phase(ui, repo, *revs, **opts):
4538 4540 """set or show the current phase name
4539 4541
4540 4542 With no argument, show the phase name of specified revisions.
4541 4543
4542 4544 With one of -p/--public, -d/--draft or -s/--secret, change the
4543 4545 phase value of the specified revisions.
4544 4546
4545 4547 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
4546 4548 lower phase to an higher phase. Phases are ordered as follows::
4547 4549
4548 4550 public < draft < secret
4549 4551
4550 4552 Returns 0 on success, 1 if no phases were changed or some could not
4551 4553 be changed.
4552 4554 """
4553 4555 # search for a unique phase argument
4554 4556 targetphase = None
4555 4557 for idx, name in enumerate(phases.phasenames):
4556 4558 if opts[name]:
4557 4559 if targetphase is not None:
4558 4560 raise util.Abort(_('only one phase can be specified'))
4559 4561 targetphase = idx
4560 4562
4561 4563 # look for specified revision
4562 4564 revs = list(revs)
4563 4565 revs.extend(opts['rev'])
4564 4566 if not revs:
4565 4567 raise util.Abort(_('no revisions specified'))
4566 4568
4567 4569 revs = scmutil.revrange(repo, revs)
4568 4570
4569 4571 lock = None
4570 4572 ret = 0
4571 4573 if targetphase is None:
4572 4574 # display
4573 4575 for r in revs:
4574 4576 ctx = repo[r]
4575 4577 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
4576 4578 else:
4577 4579 lock = repo.lock()
4578 4580 try:
4579 4581 # set phase
4580 4582 if not revs:
4581 4583 raise util.Abort(_('empty revision set'))
4582 4584 nodes = [repo[r].node() for r in revs]
4583 4585 olddata = repo._phasecache.getphaserevs(repo)[:]
4584 4586 phases.advanceboundary(repo, targetphase, nodes)
4585 4587 if opts['force']:
4586 4588 phases.retractboundary(repo, targetphase, nodes)
4587 4589 finally:
4588 4590 lock.release()
4589 4591 # moving revision from public to draft may hide them
4590 4592 # We have to check result on an unfiltered repository
4591 4593 unfi = repo.unfiltered()
4592 4594 newdata = repo._phasecache.getphaserevs(unfi)
4593 4595 changes = sum(o != newdata[i] for i, o in enumerate(olddata))
4594 4596 cl = unfi.changelog
4595 4597 rejected = [n for n in nodes
4596 4598 if newdata[cl.rev(n)] < targetphase]
4597 4599 if rejected:
4598 4600 ui.warn(_('cannot move %i changesets to a higher '
4599 4601 'phase, use --force\n') % len(rejected))
4600 4602 ret = 1
4601 4603 if changes:
4602 4604 msg = _('phase changed for %i changesets\n') % changes
4603 4605 if ret:
4604 4606 ui.status(msg)
4605 4607 else:
4606 4608 ui.note(msg)
4607 4609 else:
4608 4610 ui.warn(_('no phases changed\n'))
4609 4611 ret = 1
4610 4612 return ret
4611 4613
4612 4614 def postincoming(ui, repo, modheads, optupdate, checkout):
4613 4615 if modheads == 0:
4614 4616 return
4615 4617 if optupdate:
4616 4618 checkout, movemarkfrom = bookmarks.calculateupdate(ui, repo, checkout)
4617 4619 try:
4618 4620 ret = hg.update(repo, checkout)
4619 4621 except util.Abort, inst:
4620 4622 ui.warn(_("not updating: %s\n") % str(inst))
4621 4623 if inst.hint:
4622 4624 ui.warn(_("(%s)\n") % inst.hint)
4623 4625 return 0
4624 4626 if not ret and not checkout:
4625 4627 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
4626 4628 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
4627 4629 return ret
4628 4630 if modheads > 1:
4629 4631 currentbranchheads = len(repo.branchheads())
4630 4632 if currentbranchheads == modheads:
4631 4633 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
4632 4634 elif currentbranchheads > 1:
4633 4635 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
4634 4636 "merge)\n"))
4635 4637 else:
4636 4638 ui.status(_("(run 'hg heads' to see heads)\n"))
4637 4639 else:
4638 4640 ui.status(_("(run 'hg update' to get a working copy)\n"))
4639 4641
4640 4642 @command('^pull',
4641 4643 [('u', 'update', None,
4642 4644 _('update to new branch head if changesets were pulled')),
4643 4645 ('f', 'force', None, _('run even when remote repository is unrelated')),
4644 4646 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4645 4647 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
4646 4648 ('b', 'branch', [], _('a specific branch you would like to pull'),
4647 4649 _('BRANCH')),
4648 4650 ] + remoteopts,
4649 4651 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
4650 4652 def pull(ui, repo, source="default", **opts):
4651 4653 """pull changes from the specified source
4652 4654
4653 4655 Pull changes from a remote repository to a local one.
4654 4656
4655 4657 This finds all changes from the repository at the specified path
4656 4658 or URL and adds them to a local repository (the current one unless
4657 4659 -R is specified). By default, this does not update the copy of the
4658 4660 project in the working directory.
4659 4661
4660 4662 Use :hg:`incoming` if you want to see what would have been added
4661 4663 by a pull at the time you issued this command. If you then decide
4662 4664 to add those changes to the repository, you should use :hg:`pull
4663 4665 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4664 4666
4665 4667 If SOURCE is omitted, the 'default' path will be used.
4666 4668 See :hg:`help urls` for more information.
4667 4669
4668 4670 Returns 0 on success, 1 if an update had unresolved files.
4669 4671 """
4670 4672 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4671 4673 other = hg.peer(repo, opts, source)
4672 4674 try:
4673 4675 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4674 4676 revs, checkout = hg.addbranchrevs(repo, other, branches,
4675 4677 opts.get('rev'))
4676 4678
4677 4679 remotebookmarks = other.listkeys('bookmarks')
4678 4680
4679 4681 if opts.get('bookmark'):
4680 4682 if not revs:
4681 4683 revs = []
4682 4684 for b in opts['bookmark']:
4683 4685 if b not in remotebookmarks:
4684 4686 raise util.Abort(_('remote bookmark %s not found!') % b)
4685 4687 revs.append(remotebookmarks[b])
4686 4688
4687 4689 if revs:
4688 4690 try:
4689 4691 revs = [other.lookup(rev) for rev in revs]
4690 4692 except error.CapabilityError:
4691 4693 err = _("other repository doesn't support revision lookup, "
4692 4694 "so a rev cannot be specified.")
4693 4695 raise util.Abort(err)
4694 4696
4695 4697 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
4696 4698 bookmarks.updatefromremote(ui, repo, remotebookmarks, source)
4697 4699 if checkout:
4698 4700 checkout = str(repo.changelog.rev(other.lookup(checkout)))
4699 4701 repo._subtoppath = source
4700 4702 try:
4701 4703 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
4702 4704
4703 4705 finally:
4704 4706 del repo._subtoppath
4705 4707
4706 4708 # update specified bookmarks
4707 4709 if opts.get('bookmark'):
4708 4710 marks = repo._bookmarks
4709 4711 for b in opts['bookmark']:
4710 4712 # explicit pull overrides local bookmark if any
4711 4713 ui.status(_("importing bookmark %s\n") % b)
4712 4714 marks[b] = repo[remotebookmarks[b]].node()
4713 4715 marks.write()
4714 4716 finally:
4715 4717 other.close()
4716 4718 return ret
4717 4719
4718 4720 @command('^push',
4719 4721 [('f', 'force', None, _('force push')),
4720 4722 ('r', 'rev', [],
4721 4723 _('a changeset intended to be included in the destination'),
4722 4724 _('REV')),
4723 4725 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4724 4726 ('b', 'branch', [],
4725 4727 _('a specific branch you would like to push'), _('BRANCH')),
4726 4728 ('', 'new-branch', False, _('allow pushing a new branch')),
4727 4729 ] + remoteopts,
4728 4730 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4729 4731 def push(ui, repo, dest=None, **opts):
4730 4732 """push changes to the specified destination
4731 4733
4732 4734 Push changesets from the local repository to the specified
4733 4735 destination.
4734 4736
4735 4737 This operation is symmetrical to pull: it is identical to a pull
4736 4738 in the destination repository from the current one.
4737 4739
4738 4740 By default, push will not allow creation of new heads at the
4739 4741 destination, since multiple heads would make it unclear which head
4740 4742 to use. In this situation, it is recommended to pull and merge
4741 4743 before pushing.
4742 4744
4743 4745 Use --new-branch if you want to allow push to create a new named
4744 4746 branch that is not present at the destination. This allows you to
4745 4747 only create a new branch without forcing other changes.
4746 4748
4747 4749 .. note::
4748 4750
4749 4751 Extra care should be taken with the -f/--force option,
4750 4752 which will push all new heads on all branches, an action which will
4751 4753 almost always cause confusion for collaborators.
4752 4754
4753 4755 If -r/--rev is used, the specified revision and all its ancestors
4754 4756 will be pushed to the remote repository.
4755 4757
4756 4758 If -B/--bookmark is used, the specified bookmarked revision, its
4757 4759 ancestors, and the bookmark will be pushed to the remote
4758 4760 repository.
4759 4761
4760 4762 Please see :hg:`help urls` for important details about ``ssh://``
4761 4763 URLs. If DESTINATION is omitted, a default path will be used.
4762 4764
4763 4765 Returns 0 if push was successful, 1 if nothing to push.
4764 4766 """
4765 4767
4766 4768 if opts.get('bookmark'):
4767 4769 ui.setconfig('bookmarks', 'pushing', opts['bookmark'], 'push')
4768 4770 for b in opts['bookmark']:
4769 4771 # translate -B options to -r so changesets get pushed
4770 4772 if b in repo._bookmarks:
4771 4773 opts.setdefault('rev', []).append(b)
4772 4774 else:
4773 4775 # if we try to push a deleted bookmark, translate it to null
4774 4776 # this lets simultaneous -r, -b options continue working
4775 4777 opts.setdefault('rev', []).append("null")
4776 4778
4777 4779 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4778 4780 dest, branches = hg.parseurl(dest, opts.get('branch'))
4779 4781 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4780 4782 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4781 4783 try:
4782 4784 other = hg.peer(repo, opts, dest)
4783 4785 except error.RepoError:
4784 4786 if dest == "default-push":
4785 4787 raise util.Abort(_("default repository not configured!"),
4786 4788 hint=_('see the "path" section in "hg help config"'))
4787 4789 else:
4788 4790 raise
4789 4791
4790 4792 if revs:
4791 4793 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
4792 4794
4793 4795 repo._subtoppath = dest
4794 4796 try:
4795 4797 # push subrepos depth-first for coherent ordering
4796 4798 c = repo['']
4797 4799 subs = c.substate # only repos that are committed
4798 4800 for s in sorted(subs):
4799 4801 result = c.sub(s).push(opts)
4800 4802 if result == 0:
4801 4803 return not result
4802 4804 finally:
4803 4805 del repo._subtoppath
4804 4806 result = repo.push(other, opts.get('force'), revs=revs,
4805 4807 newbranch=opts.get('new_branch'))
4806 4808
4807 4809 result = not result
4808 4810
4809 4811 if opts.get('bookmark'):
4810 4812 bresult = bookmarks.pushtoremote(ui, repo, other, opts['bookmark'])
4811 4813 if bresult == 2:
4812 4814 return 2
4813 4815 if not result and bresult:
4814 4816 result = 2
4815 4817
4816 4818 return result
4817 4819
4818 4820 @command('recover', [])
4819 4821 def recover(ui, repo):
4820 4822 """roll back an interrupted transaction
4821 4823
4822 4824 Recover from an interrupted commit or pull.
4823 4825
4824 4826 This command tries to fix the repository status after an
4825 4827 interrupted operation. It should only be necessary when Mercurial
4826 4828 suggests it.
4827 4829
4828 4830 Returns 0 if successful, 1 if nothing to recover or verify fails.
4829 4831 """
4830 4832 if repo.recover():
4831 4833 return hg.verify(repo)
4832 4834 return 1
4833 4835
4834 4836 @command('^remove|rm',
4835 4837 [('A', 'after', None, _('record delete for missing files')),
4836 4838 ('f', 'force', None,
4837 4839 _('remove (and delete) file even if added or modified')),
4838 4840 ] + walkopts,
4839 4841 _('[OPTION]... FILE...'),
4840 4842 inferrepo=True)
4841 4843 def remove(ui, repo, *pats, **opts):
4842 4844 """remove the specified files on the next commit
4843 4845
4844 4846 Schedule the indicated files for removal from the current branch.
4845 4847
4846 4848 This command schedules the files to be removed at the next commit.
4847 4849 To undo a remove before that, see :hg:`revert`. To undo added
4848 4850 files, see :hg:`forget`.
4849 4851
4850 4852 .. container:: verbose
4851 4853
4852 4854 -A/--after can be used to remove only files that have already
4853 4855 been deleted, -f/--force can be used to force deletion, and -Af
4854 4856 can be used to remove files from the next revision without
4855 4857 deleting them from the working directory.
4856 4858
4857 4859 The following table details the behavior of remove for different
4858 4860 file states (columns) and option combinations (rows). The file
4859 4861 states are Added [A], Clean [C], Modified [M] and Missing [!]
4860 4862 (as reported by :hg:`status`). The actions are Warn, Remove
4861 4863 (from branch) and Delete (from disk):
4862 4864
4863 4865 ========= == == == ==
4864 4866 opt/state A C M !
4865 4867 ========= == == == ==
4866 4868 none W RD W R
4867 4869 -f R RD RD R
4868 4870 -A W W W R
4869 4871 -Af R R R R
4870 4872 ========= == == == ==
4871 4873
4872 4874 Note that remove never deletes files in Added [A] state from the
4873 4875 working directory, not even if option --force is specified.
4874 4876
4875 4877 Returns 0 on success, 1 if any warnings encountered.
4876 4878 """
4877 4879
4878 4880 ret = 0
4879 4881 after, force = opts.get('after'), opts.get('force')
4880 4882 if not pats and not after:
4881 4883 raise util.Abort(_('no files specified'))
4882 4884
4883 4885 m = scmutil.match(repo[None], pats, opts)
4884 4886 s = repo.status(match=m, clean=True)
4885 4887 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
4886 4888
4887 4889 # warn about failure to delete explicit files/dirs
4888 4890 wctx = repo[None]
4889 4891 for f in m.files():
4890 4892 if f in repo.dirstate or f in wctx.dirs():
4891 4893 continue
4892 4894 if os.path.exists(m.rel(f)):
4893 4895 if os.path.isdir(m.rel(f)):
4894 4896 ui.warn(_('not removing %s: no tracked files\n') % m.rel(f))
4895 4897 else:
4896 4898 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
4897 4899 # missing files will generate a warning elsewhere
4898 4900 ret = 1
4899 4901
4900 4902 if force:
4901 4903 list = modified + deleted + clean + added
4902 4904 elif after:
4903 4905 list = deleted
4904 4906 for f in modified + added + clean:
4905 4907 ui.warn(_('not removing %s: file still exists\n') % m.rel(f))
4906 4908 ret = 1
4907 4909 else:
4908 4910 list = deleted + clean
4909 4911 for f in modified:
4910 4912 ui.warn(_('not removing %s: file is modified (use -f'
4911 4913 ' to force removal)\n') % m.rel(f))
4912 4914 ret = 1
4913 4915 for f in added:
4914 4916 ui.warn(_('not removing %s: file has been marked for add'
4915 4917 ' (use forget to undo)\n') % m.rel(f))
4916 4918 ret = 1
4917 4919
4918 4920 for f in sorted(list):
4919 4921 if ui.verbose or not m.exact(f):
4920 4922 ui.status(_('removing %s\n') % m.rel(f))
4921 4923
4922 4924 wlock = repo.wlock()
4923 4925 try:
4924 4926 if not after:
4925 4927 for f in list:
4926 4928 if f in added:
4927 4929 continue # we never unlink added files on remove
4928 4930 util.unlinkpath(repo.wjoin(f), ignoremissing=True)
4929 4931 repo[None].forget(list)
4930 4932 finally:
4931 4933 wlock.release()
4932 4934
4933 4935 return ret
4934 4936
4935 4937 @command('rename|move|mv',
4936 4938 [('A', 'after', None, _('record a rename that has already occurred')),
4937 4939 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4938 4940 ] + walkopts + dryrunopts,
4939 4941 _('[OPTION]... SOURCE... DEST'))
4940 4942 def rename(ui, repo, *pats, **opts):
4941 4943 """rename files; equivalent of copy + remove
4942 4944
4943 4945 Mark dest as copies of sources; mark sources for deletion. If dest
4944 4946 is a directory, copies are put in that directory. If dest is a
4945 4947 file, there can only be one source.
4946 4948
4947 4949 By default, this command copies the contents of files as they
4948 4950 exist in the working directory. If invoked with -A/--after, the
4949 4951 operation is recorded, but no copying is performed.
4950 4952
4951 4953 This command takes effect at the next commit. To undo a rename
4952 4954 before that, see :hg:`revert`.
4953 4955
4954 4956 Returns 0 on success, 1 if errors are encountered.
4955 4957 """
4956 4958 wlock = repo.wlock(False)
4957 4959 try:
4958 4960 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4959 4961 finally:
4960 4962 wlock.release()
4961 4963
4962 4964 @command('resolve',
4963 4965 [('a', 'all', None, _('select all unresolved files')),
4964 4966 ('l', 'list', None, _('list state of files needing merge')),
4965 4967 ('m', 'mark', None, _('mark files as resolved')),
4966 4968 ('u', 'unmark', None, _('mark files as unresolved')),
4967 4969 ('n', 'no-status', None, _('hide status prefix'))]
4968 4970 + mergetoolopts + walkopts,
4969 4971 _('[OPTION]... [FILE]...'),
4970 4972 inferrepo=True)
4971 4973 def resolve(ui, repo, *pats, **opts):
4972 4974 """redo merges or set/view the merge status of files
4973 4975
4974 4976 Merges with unresolved conflicts are often the result of
4975 4977 non-interactive merging using the ``internal:merge`` configuration
4976 4978 setting, or a command-line merge tool like ``diff3``. The resolve
4977 4979 command is used to manage the files involved in a merge, after
4978 4980 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4979 4981 working directory must have two parents). See :hg:`help
4980 4982 merge-tools` for information on configuring merge tools.
4981 4983
4982 4984 The resolve command can be used in the following ways:
4983 4985
4984 4986 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4985 4987 files, discarding any previous merge attempts. Re-merging is not
4986 4988 performed for files already marked as resolved. Use ``--all/-a``
4987 4989 to select all unresolved files. ``--tool`` can be used to specify
4988 4990 the merge tool used for the given files. It overrides the HGMERGE
4989 4991 environment variable and your configuration files. Previous file
4990 4992 contents are saved with a ``.orig`` suffix.
4991 4993
4992 4994 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4993 4995 (e.g. after having manually fixed-up the files). The default is
4994 4996 to mark all unresolved files.
4995 4997
4996 4998 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4997 4999 default is to mark all resolved files.
4998 5000
4999 5001 - :hg:`resolve -l`: list files which had or still have conflicts.
5000 5002 In the printed list, ``U`` = unresolved and ``R`` = resolved.
5001 5003
5002 5004 Note that Mercurial will not let you commit files with unresolved
5003 5005 merge conflicts. You must use :hg:`resolve -m ...` before you can
5004 5006 commit after a conflicting merge.
5005 5007
5006 5008 Returns 0 on success, 1 if any files fail a resolve attempt.
5007 5009 """
5008 5010
5009 5011 all, mark, unmark, show, nostatus = \
5010 5012 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
5011 5013
5012 5014 if (show and (mark or unmark)) or (mark and unmark):
5013 5015 raise util.Abort(_("too many options specified"))
5014 5016 if pats and all:
5015 5017 raise util.Abort(_("can't specify --all and patterns"))
5016 5018 if not (all or pats or show or mark or unmark):
5017 5019 raise util.Abort(_('no files or directories specified'),
5018 5020 hint=('use --all to remerge all files'))
5019 5021
5020 5022 wlock = repo.wlock()
5021 5023 try:
5022 5024 ms = mergemod.mergestate(repo)
5023 5025
5024 5026 if not ms.active() and not show:
5025 5027 raise util.Abort(
5026 5028 _('resolve command not applicable when not merging'))
5027 5029
5028 5030 m = scmutil.match(repo[None], pats, opts)
5029 5031 ret = 0
5030 5032 didwork = False
5031 5033
5032 5034 for f in ms:
5033 5035 if not m(f):
5034 5036 continue
5035 5037
5036 5038 didwork = True
5037 5039
5038 5040 if show:
5039 5041 if nostatus:
5040 5042 ui.write("%s\n" % f)
5041 5043 else:
5042 5044 ui.write("%s %s\n" % (ms[f].upper(), f),
5043 5045 label='resolve.' +
5044 5046 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
5045 5047 elif mark:
5046 5048 ms.mark(f, "r")
5047 5049 elif unmark:
5048 5050 ms.mark(f, "u")
5049 5051 else:
5050 5052 wctx = repo[None]
5051 5053
5052 5054 # backup pre-resolve (merge uses .orig for its own purposes)
5053 5055 a = repo.wjoin(f)
5054 5056 util.copyfile(a, a + ".resolve")
5055 5057
5056 5058 try:
5057 5059 # resolve file
5058 5060 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
5059 5061 'resolve')
5060 5062 if ms.resolve(f, wctx):
5061 5063 ret = 1
5062 5064 finally:
5063 5065 ui.setconfig('ui', 'forcemerge', '', 'resolve')
5064 5066 ms.commit()
5065 5067
5066 5068 # replace filemerge's .orig file with our resolve file
5067 5069 util.rename(a + ".resolve", a + ".orig")
5068 5070
5069 5071 ms.commit()
5070 5072
5071 5073 if not didwork and pats:
5072 5074 ui.warn(_("arguments do not match paths that need resolving\n"))
5073 5075
5074 5076 finally:
5075 5077 wlock.release()
5076 5078
5077 5079 # Nudge users into finishing an unfinished operation. We don't print
5078 5080 # this with the list/show operation because we want list/show to remain
5079 5081 # machine readable.
5080 5082 if not list(ms.unresolved()) and not show:
5081 5083 ui.status(_('(no more unresolved files)\n'))
5082 5084
5083 5085 return ret
5084 5086
5085 5087 @command('revert',
5086 5088 [('a', 'all', None, _('revert all changes when no arguments given')),
5087 5089 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5088 5090 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
5089 5091 ('C', 'no-backup', None, _('do not save backup copies of files')),
5090 5092 ] + walkopts + dryrunopts,
5091 5093 _('[OPTION]... [-r REV] [NAME]...'))
5092 5094 def revert(ui, repo, *pats, **opts):
5093 5095 """restore files to their checkout state
5094 5096
5095 5097 .. note::
5096 5098
5097 5099 To check out earlier revisions, you should use :hg:`update REV`.
5098 5100 To cancel an uncommitted merge (and lose your changes),
5099 5101 use :hg:`update --clean .`.
5100 5102
5101 5103 With no revision specified, revert the specified files or directories
5102 5104 to the contents they had in the parent of the working directory.
5103 5105 This restores the contents of files to an unmodified
5104 5106 state and unschedules adds, removes, copies, and renames. If the
5105 5107 working directory has two parents, you must explicitly specify a
5106 5108 revision.
5107 5109
5108 5110 Using the -r/--rev or -d/--date options, revert the given files or
5109 5111 directories to their states as of a specific revision. Because
5110 5112 revert does not change the working directory parents, this will
5111 5113 cause these files to appear modified. This can be helpful to "back
5112 5114 out" some or all of an earlier change. See :hg:`backout` for a
5113 5115 related method.
5114 5116
5115 5117 Modified files are saved with a .orig suffix before reverting.
5116 5118 To disable these backups, use --no-backup.
5117 5119
5118 5120 See :hg:`help dates` for a list of formats valid for -d/--date.
5119 5121
5120 5122 Returns 0 on success.
5121 5123 """
5122 5124
5123 5125 if opts.get("date"):
5124 5126 if opts.get("rev"):
5125 5127 raise util.Abort(_("you can't specify a revision and a date"))
5126 5128 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
5127 5129
5128 5130 parent, p2 = repo.dirstate.parents()
5129 5131 if not opts.get('rev') and p2 != nullid:
5130 5132 # revert after merge is a trap for new users (issue2915)
5131 5133 raise util.Abort(_('uncommitted merge with no revision specified'),
5132 5134 hint=_('use "hg update" or see "hg help revert"'))
5133 5135
5134 5136 ctx = scmutil.revsingle(repo, opts.get('rev'))
5135 5137
5136 5138 if not pats and not opts.get('all'):
5137 5139 msg = _("no files or directories specified")
5138 5140 if p2 != nullid:
5139 5141 hint = _("uncommitted merge, use --all to discard all changes,"
5140 5142 " or 'hg update -C .' to abort the merge")
5141 5143 raise util.Abort(msg, hint=hint)
5142 5144 dirty = util.any(repo.status())
5143 5145 node = ctx.node()
5144 5146 if node != parent:
5145 5147 if dirty:
5146 5148 hint = _("uncommitted changes, use --all to discard all"
5147 5149 " changes, or 'hg update %s' to update") % ctx.rev()
5148 5150 else:
5149 5151 hint = _("use --all to revert all files,"
5150 5152 " or 'hg update %s' to update") % ctx.rev()
5151 5153 elif dirty:
5152 5154 hint = _("uncommitted changes, use --all to discard all changes")
5153 5155 else:
5154 5156 hint = _("use --all to revert all files")
5155 5157 raise util.Abort(msg, hint=hint)
5156 5158
5157 5159 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
5158 5160
5159 5161 @command('rollback', dryrunopts +
5160 5162 [('f', 'force', False, _('ignore safety measures'))])
5161 5163 def rollback(ui, repo, **opts):
5162 5164 """roll back the last transaction (DANGEROUS) (DEPRECATED)
5163 5165
5164 5166 Please use :hg:`commit --amend` instead of rollback to correct
5165 5167 mistakes in the last commit.
5166 5168
5167 5169 This command should be used with care. There is only one level of
5168 5170 rollback, and there is no way to undo a rollback. It will also
5169 5171 restore the dirstate at the time of the last transaction, losing
5170 5172 any dirstate changes since that time. This command does not alter
5171 5173 the working directory.
5172 5174
5173 5175 Transactions are used to encapsulate the effects of all commands
5174 5176 that create new changesets or propagate existing changesets into a
5175 5177 repository.
5176 5178
5177 5179 .. container:: verbose
5178 5180
5179 5181 For example, the following commands are transactional, and their
5180 5182 effects can be rolled back:
5181 5183
5182 5184 - commit
5183 5185 - import
5184 5186 - pull
5185 5187 - push (with this repository as the destination)
5186 5188 - unbundle
5187 5189
5188 5190 To avoid permanent data loss, rollback will refuse to rollback a
5189 5191 commit transaction if it isn't checked out. Use --force to
5190 5192 override this protection.
5191 5193
5192 5194 This command is not intended for use on public repositories. Once
5193 5195 changes are visible for pull by other users, rolling a transaction
5194 5196 back locally is ineffective (someone else may already have pulled
5195 5197 the changes). Furthermore, a race is possible with readers of the
5196 5198 repository; for example an in-progress pull from the repository
5197 5199 may fail if a rollback is performed.
5198 5200
5199 5201 Returns 0 on success, 1 if no rollback data is available.
5200 5202 """
5201 5203 return repo.rollback(dryrun=opts.get('dry_run'),
5202 5204 force=opts.get('force'))
5203 5205
5204 5206 @command('root', [])
5205 5207 def root(ui, repo):
5206 5208 """print the root (top) of the current working directory
5207 5209
5208 5210 Print the root directory of the current repository.
5209 5211
5210 5212 Returns 0 on success.
5211 5213 """
5212 5214 ui.write(repo.root + "\n")
5213 5215
5214 5216 @command('^serve',
5215 5217 [('A', 'accesslog', '', _('name of access log file to write to'),
5216 5218 _('FILE')),
5217 5219 ('d', 'daemon', None, _('run server in background')),
5218 5220 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
5219 5221 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
5220 5222 # use string type, then we can check if something was passed
5221 5223 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
5222 5224 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
5223 5225 _('ADDR')),
5224 5226 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
5225 5227 _('PREFIX')),
5226 5228 ('n', 'name', '',
5227 5229 _('name to show in web pages (default: working directory)'), _('NAME')),
5228 5230 ('', 'web-conf', '',
5229 5231 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
5230 5232 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
5231 5233 _('FILE')),
5232 5234 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
5233 5235 ('', 'stdio', None, _('for remote clients')),
5234 5236 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
5235 5237 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
5236 5238 ('', 'style', '', _('template style to use'), _('STYLE')),
5237 5239 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
5238 5240 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
5239 5241 _('[OPTION]...'),
5240 5242 optionalrepo=True)
5241 5243 def serve(ui, repo, **opts):
5242 5244 """start stand-alone webserver
5243 5245
5244 5246 Start a local HTTP repository browser and pull server. You can use
5245 5247 this for ad-hoc sharing and browsing of repositories. It is
5246 5248 recommended to use a real web server to serve a repository for
5247 5249 longer periods of time.
5248 5250
5249 5251 Please note that the server does not implement access control.
5250 5252 This means that, by default, anybody can read from the server and
5251 5253 nobody can write to it by default. Set the ``web.allow_push``
5252 5254 option to ``*`` to allow everybody to push to the server. You
5253 5255 should use a real web server if you need to authenticate users.
5254 5256
5255 5257 By default, the server logs accesses to stdout and errors to
5256 5258 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
5257 5259 files.
5258 5260
5259 5261 To have the server choose a free port number to listen on, specify
5260 5262 a port number of 0; in this case, the server will print the port
5261 5263 number it uses.
5262 5264
5263 5265 Returns 0 on success.
5264 5266 """
5265 5267
5266 5268 if opts["stdio"] and opts["cmdserver"]:
5267 5269 raise util.Abort(_("cannot use --stdio with --cmdserver"))
5268 5270
5269 5271 if opts["stdio"]:
5270 5272 if repo is None:
5271 5273 raise error.RepoError(_("there is no Mercurial repository here"
5272 5274 " (.hg not found)"))
5273 5275 s = sshserver.sshserver(ui, repo)
5274 5276 s.serve_forever()
5275 5277
5276 5278 if opts["cmdserver"]:
5277 5279 s = commandserver.server(ui, repo, opts["cmdserver"])
5278 5280 return s.serve()
5279 5281
5280 5282 # this way we can check if something was given in the command-line
5281 5283 if opts.get('port'):
5282 5284 opts['port'] = util.getport(opts.get('port'))
5283 5285
5284 5286 baseui = repo and repo.baseui or ui
5285 5287 optlist = ("name templates style address port prefix ipv6"
5286 5288 " accesslog errorlog certificate encoding")
5287 5289 for o in optlist.split():
5288 5290 val = opts.get(o, '')
5289 5291 if val in (None, ''): # should check against default options instead
5290 5292 continue
5291 5293 baseui.setconfig("web", o, val, 'serve')
5292 5294 if repo and repo.ui != baseui:
5293 5295 repo.ui.setconfig("web", o, val, 'serve')
5294 5296
5295 5297 o = opts.get('web_conf') or opts.get('webdir_conf')
5296 5298 if not o:
5297 5299 if not repo:
5298 5300 raise error.RepoError(_("there is no Mercurial repository"
5299 5301 " here (.hg not found)"))
5300 5302 o = repo
5301 5303
5302 5304 app = hgweb.hgweb(o, baseui=baseui)
5303 5305 service = httpservice(ui, app, opts)
5304 5306 cmdutil.service(opts, initfn=service.init, runfn=service.run)
5305 5307
5306 5308 class httpservice(object):
5307 5309 def __init__(self, ui, app, opts):
5308 5310 self.ui = ui
5309 5311 self.app = app
5310 5312 self.opts = opts
5311 5313
5312 5314 def init(self):
5313 5315 util.setsignalhandler()
5314 5316 self.httpd = hgweb_server.create_server(self.ui, self.app)
5315 5317
5316 5318 if self.opts['port'] and not self.ui.verbose:
5317 5319 return
5318 5320
5319 5321 if self.httpd.prefix:
5320 5322 prefix = self.httpd.prefix.strip('/') + '/'
5321 5323 else:
5322 5324 prefix = ''
5323 5325
5324 5326 port = ':%d' % self.httpd.port
5325 5327 if port == ':80':
5326 5328 port = ''
5327 5329
5328 5330 bindaddr = self.httpd.addr
5329 5331 if bindaddr == '0.0.0.0':
5330 5332 bindaddr = '*'
5331 5333 elif ':' in bindaddr: # IPv6
5332 5334 bindaddr = '[%s]' % bindaddr
5333 5335
5334 5336 fqaddr = self.httpd.fqaddr
5335 5337 if ':' in fqaddr:
5336 5338 fqaddr = '[%s]' % fqaddr
5337 5339 if self.opts['port']:
5338 5340 write = self.ui.status
5339 5341 else:
5340 5342 write = self.ui.write
5341 5343 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
5342 5344 (fqaddr, port, prefix, bindaddr, self.httpd.port))
5343 5345 self.ui.flush() # avoid buffering of status message
5344 5346
5345 5347 def run(self):
5346 5348 self.httpd.serve_forever()
5347 5349
5348 5350
5349 5351 @command('^status|st',
5350 5352 [('A', 'all', None, _('show status of all files')),
5351 5353 ('m', 'modified', None, _('show only modified files')),
5352 5354 ('a', 'added', None, _('show only added files')),
5353 5355 ('r', 'removed', None, _('show only removed files')),
5354 5356 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
5355 5357 ('c', 'clean', None, _('show only files without changes')),
5356 5358 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
5357 5359 ('i', 'ignored', None, _('show only ignored files')),
5358 5360 ('n', 'no-status', None, _('hide status prefix')),
5359 5361 ('C', 'copies', None, _('show source of copied files')),
5360 5362 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
5361 5363 ('', 'rev', [], _('show difference from revision'), _('REV')),
5362 5364 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
5363 5365 ] + walkopts + subrepoopts,
5364 5366 _('[OPTION]... [FILE]...'),
5365 5367 inferrepo=True)
5366 5368 def status(ui, repo, *pats, **opts):
5367 5369 """show changed files in the working directory
5368 5370
5369 5371 Show status of files in the repository. If names are given, only
5370 5372 files that match are shown. Files that are clean or ignored or
5371 5373 the source of a copy/move operation, are not listed unless
5372 5374 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
5373 5375 Unless options described with "show only ..." are given, the
5374 5376 options -mardu are used.
5375 5377
5376 5378 Option -q/--quiet hides untracked (unknown and ignored) files
5377 5379 unless explicitly requested with -u/--unknown or -i/--ignored.
5378 5380
5379 5381 .. note::
5380 5382
5381 5383 status may appear to disagree with diff if permissions have
5382 5384 changed or a merge has occurred. The standard diff format does
5383 5385 not report permission changes and diff only reports changes
5384 5386 relative to one merge parent.
5385 5387
5386 5388 If one revision is given, it is used as the base revision.
5387 5389 If two revisions are given, the differences between them are
5388 5390 shown. The --change option can also be used as a shortcut to list
5389 5391 the changed files of a revision from its first parent.
5390 5392
5391 5393 The codes used to show the status of files are::
5392 5394
5393 5395 M = modified
5394 5396 A = added
5395 5397 R = removed
5396 5398 C = clean
5397 5399 ! = missing (deleted by non-hg command, but still tracked)
5398 5400 ? = not tracked
5399 5401 I = ignored
5400 5402 = origin of the previous file (with --copies)
5401 5403
5402 5404 .. container:: verbose
5403 5405
5404 5406 Examples:
5405 5407
5406 5408 - show changes in the working directory relative to a
5407 5409 changeset::
5408 5410
5409 5411 hg status --rev 9353
5410 5412
5411 5413 - show all changes including copies in an existing changeset::
5412 5414
5413 5415 hg status --copies --change 9353
5414 5416
5415 5417 - get a NUL separated list of added files, suitable for xargs::
5416 5418
5417 5419 hg status -an0
5418 5420
5419 5421 Returns 0 on success.
5420 5422 """
5421 5423
5422 5424 revs = opts.get('rev')
5423 5425 change = opts.get('change')
5424 5426
5425 5427 if revs and change:
5426 5428 msg = _('cannot specify --rev and --change at the same time')
5427 5429 raise util.Abort(msg)
5428 5430 elif change:
5429 5431 node2 = scmutil.revsingle(repo, change, None).node()
5430 5432 node1 = repo[node2].p1().node()
5431 5433 else:
5432 5434 node1, node2 = scmutil.revpair(repo, revs)
5433 5435
5434 5436 cwd = (pats and repo.getcwd()) or ''
5435 5437 end = opts.get('print0') and '\0' or '\n'
5436 5438 copy = {}
5437 5439 states = 'modified added removed deleted unknown ignored clean'.split()
5438 5440 show = [k for k in states if opts.get(k)]
5439 5441 if opts.get('all'):
5440 5442 show += ui.quiet and (states[:4] + ['clean']) or states
5441 5443 if not show:
5442 5444 show = ui.quiet and states[:4] or states[:5]
5443 5445
5444 5446 stat = repo.status(node1, node2, scmutil.match(repo[node2], pats, opts),
5445 5447 'ignored' in show, 'clean' in show, 'unknown' in show,
5446 5448 opts.get('subrepos'))
5447 5449 changestates = zip(states, 'MAR!?IC', stat)
5448 5450
5449 5451 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
5450 5452 copy = copies.pathcopies(repo[node1], repo[node2])
5451 5453
5452 5454 fm = ui.formatter('status', opts)
5453 5455 fmt = '%s' + end
5454 5456 showchar = not opts.get('no_status')
5455 5457
5456 5458 for state, char, files in changestates:
5457 5459 if state in show:
5458 5460 label = 'status.' + state
5459 5461 for f in files:
5460 5462 fm.startitem()
5461 5463 fm.condwrite(showchar, 'status', '%s ', char, label=label)
5462 5464 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
5463 5465 if f in copy:
5464 5466 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
5465 5467 label='status.copied')
5466 5468 fm.end()
5467 5469
5468 5470 @command('^summary|sum',
5469 5471 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
5470 5472 def summary(ui, repo, **opts):
5471 5473 """summarize working directory state
5472 5474
5473 5475 This generates a brief summary of the working directory state,
5474 5476 including parents, branch, commit status, and available updates.
5475 5477
5476 5478 With the --remote option, this will check the default paths for
5477 5479 incoming and outgoing changes. This can be time-consuming.
5478 5480
5479 5481 Returns 0 on success.
5480 5482 """
5481 5483
5482 5484 ctx = repo[None]
5483 5485 parents = ctx.parents()
5484 5486 pnode = parents[0].node()
5485 5487 marks = []
5486 5488
5487 5489 for p in parents:
5488 5490 # label with log.changeset (instead of log.parent) since this
5489 5491 # shows a working directory parent *changeset*:
5490 5492 # i18n: column positioning for "hg summary"
5491 5493 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
5492 5494 label='log.changeset changeset.%s' % p.phasestr())
5493 5495 ui.write(' '.join(p.tags()), label='log.tag')
5494 5496 if p.bookmarks():
5495 5497 marks.extend(p.bookmarks())
5496 5498 if p.rev() == -1:
5497 5499 if not len(repo):
5498 5500 ui.write(_(' (empty repository)'))
5499 5501 else:
5500 5502 ui.write(_(' (no revision checked out)'))
5501 5503 ui.write('\n')
5502 5504 if p.description():
5503 5505 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5504 5506 label='log.summary')
5505 5507
5506 5508 branch = ctx.branch()
5507 5509 bheads = repo.branchheads(branch)
5508 5510 # i18n: column positioning for "hg summary"
5509 5511 m = _('branch: %s\n') % branch
5510 5512 if branch != 'default':
5511 5513 ui.write(m, label='log.branch')
5512 5514 else:
5513 5515 ui.status(m, label='log.branch')
5514 5516
5515 5517 if marks:
5516 5518 current = repo._bookmarkcurrent
5517 5519 # i18n: column positioning for "hg summary"
5518 5520 ui.write(_('bookmarks:'), label='log.bookmark')
5519 5521 if current is not None:
5520 5522 if current in marks:
5521 5523 ui.write(' *' + current, label='bookmarks.current')
5522 5524 marks.remove(current)
5523 5525 else:
5524 5526 ui.write(' [%s]' % current, label='bookmarks.current')
5525 5527 for m in marks:
5526 5528 ui.write(' ' + m, label='log.bookmark')
5527 5529 ui.write('\n', label='log.bookmark')
5528 5530
5529 5531 st = list(repo.status(unknown=True))[:6]
5530 5532
5531 5533 c = repo.dirstate.copies()
5532 5534 copied, renamed = [], []
5533 5535 for d, s in c.iteritems():
5534 5536 if s in st[2]:
5535 5537 st[2].remove(s)
5536 5538 renamed.append(d)
5537 5539 else:
5538 5540 copied.append(d)
5539 5541 if d in st[1]:
5540 5542 st[1].remove(d)
5541 5543 st.insert(3, renamed)
5542 5544 st.insert(4, copied)
5543 5545
5544 5546 ms = mergemod.mergestate(repo)
5545 5547 st.append([f for f in ms if ms[f] == 'u'])
5546 5548
5547 5549 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5548 5550 st.append(subs)
5549 5551
5550 5552 labels = [ui.label(_('%d modified'), 'status.modified'),
5551 5553 ui.label(_('%d added'), 'status.added'),
5552 5554 ui.label(_('%d removed'), 'status.removed'),
5553 5555 ui.label(_('%d renamed'), 'status.copied'),
5554 5556 ui.label(_('%d copied'), 'status.copied'),
5555 5557 ui.label(_('%d deleted'), 'status.deleted'),
5556 5558 ui.label(_('%d unknown'), 'status.unknown'),
5557 5559 ui.label(_('%d ignored'), 'status.ignored'),
5558 5560 ui.label(_('%d unresolved'), 'resolve.unresolved'),
5559 5561 ui.label(_('%d subrepos'), 'status.modified')]
5560 5562 t = []
5561 5563 for s, l in zip(st, labels):
5562 5564 if s:
5563 5565 t.append(l % len(s))
5564 5566
5565 5567 t = ', '.join(t)
5566 5568 cleanworkdir = False
5567 5569
5568 5570 if repo.vfs.exists('updatestate'):
5569 5571 t += _(' (interrupted update)')
5570 5572 elif len(parents) > 1:
5571 5573 t += _(' (merge)')
5572 5574 elif branch != parents[0].branch():
5573 5575 t += _(' (new branch)')
5574 5576 elif (parents[0].closesbranch() and
5575 5577 pnode in repo.branchheads(branch, closed=True)):
5576 5578 t += _(' (head closed)')
5577 5579 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
5578 5580 t += _(' (clean)')
5579 5581 cleanworkdir = True
5580 5582 elif pnode not in bheads:
5581 5583 t += _(' (new branch head)')
5582 5584
5583 5585 if cleanworkdir:
5584 5586 # i18n: column positioning for "hg summary"
5585 5587 ui.status(_('commit: %s\n') % t.strip())
5586 5588 else:
5587 5589 # i18n: column positioning for "hg summary"
5588 5590 ui.write(_('commit: %s\n') % t.strip())
5589 5591
5590 5592 # all ancestors of branch heads - all ancestors of parent = new csets
5591 5593 new = len(repo.changelog.findmissing([ctx.node() for ctx in parents],
5592 5594 bheads))
5593 5595
5594 5596 if new == 0:
5595 5597 # i18n: column positioning for "hg summary"
5596 5598 ui.status(_('update: (current)\n'))
5597 5599 elif pnode not in bheads:
5598 5600 # i18n: column positioning for "hg summary"
5599 5601 ui.write(_('update: %d new changesets (update)\n') % new)
5600 5602 else:
5601 5603 # i18n: column positioning for "hg summary"
5602 5604 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5603 5605 (new, len(bheads)))
5604 5606
5605 5607 cmdutil.summaryhooks(ui, repo)
5606 5608
5607 5609 if opts.get('remote'):
5608 5610 needsincoming, needsoutgoing = True, True
5609 5611 else:
5610 5612 needsincoming, needsoutgoing = False, False
5611 5613 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
5612 5614 if i:
5613 5615 needsincoming = True
5614 5616 if o:
5615 5617 needsoutgoing = True
5616 5618 if not needsincoming and not needsoutgoing:
5617 5619 return
5618 5620
5619 5621 def getincoming():
5620 5622 source, branches = hg.parseurl(ui.expandpath('default'))
5621 5623 sbranch = branches[0]
5622 5624 try:
5623 5625 other = hg.peer(repo, {}, source)
5624 5626 except error.RepoError:
5625 5627 if opts.get('remote'):
5626 5628 raise
5627 5629 return source, sbranch, None, None, None
5628 5630 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
5629 5631 if revs:
5630 5632 revs = [other.lookup(rev) for rev in revs]
5631 5633 ui.debug('comparing with %s\n' % util.hidepassword(source))
5632 5634 repo.ui.pushbuffer()
5633 5635 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
5634 5636 repo.ui.popbuffer()
5635 5637 return source, sbranch, other, commoninc, commoninc[1]
5636 5638
5637 5639 if needsincoming:
5638 5640 source, sbranch, sother, commoninc, incoming = getincoming()
5639 5641 else:
5640 5642 source = sbranch = sother = commoninc = incoming = None
5641 5643
5642 5644 def getoutgoing():
5643 5645 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5644 5646 dbranch = branches[0]
5645 5647 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5646 5648 if source != dest:
5647 5649 try:
5648 5650 dother = hg.peer(repo, {}, dest)
5649 5651 except error.RepoError:
5650 5652 if opts.get('remote'):
5651 5653 raise
5652 5654 return dest, dbranch, None, None
5653 5655 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5654 5656 elif sother is None:
5655 5657 # there is no explicit destination peer, but source one is invalid
5656 5658 return dest, dbranch, None, None
5657 5659 else:
5658 5660 dother = sother
5659 5661 if (source != dest or (sbranch is not None and sbranch != dbranch)):
5660 5662 common = None
5661 5663 else:
5662 5664 common = commoninc
5663 5665 if revs:
5664 5666 revs = [repo.lookup(rev) for rev in revs]
5665 5667 repo.ui.pushbuffer()
5666 5668 outgoing = discovery.findcommonoutgoing(repo, dother, onlyheads=revs,
5667 5669 commoninc=common)
5668 5670 repo.ui.popbuffer()
5669 5671 return dest, dbranch, dother, outgoing
5670 5672
5671 5673 if needsoutgoing:
5672 5674 dest, dbranch, dother, outgoing = getoutgoing()
5673 5675 else:
5674 5676 dest = dbranch = dother = outgoing = None
5675 5677
5676 5678 if opts.get('remote'):
5677 5679 t = []
5678 5680 if incoming:
5679 5681 t.append(_('1 or more incoming'))
5680 5682 o = outgoing.missing
5681 5683 if o:
5682 5684 t.append(_('%d outgoing') % len(o))
5683 5685 other = dother or sother
5684 5686 if 'bookmarks' in other.listkeys('namespaces'):
5685 5687 lmarks = repo.listkeys('bookmarks')
5686 5688 rmarks = other.listkeys('bookmarks')
5687 5689 diff = set(rmarks) - set(lmarks)
5688 5690 if len(diff) > 0:
5689 5691 t.append(_('%d incoming bookmarks') % len(diff))
5690 5692 diff = set(lmarks) - set(rmarks)
5691 5693 if len(diff) > 0:
5692 5694 t.append(_('%d outgoing bookmarks') % len(diff))
5693 5695
5694 5696 if t:
5695 5697 # i18n: column positioning for "hg summary"
5696 5698 ui.write(_('remote: %s\n') % (', '.join(t)))
5697 5699 else:
5698 5700 # i18n: column positioning for "hg summary"
5699 5701 ui.status(_('remote: (synced)\n'))
5700 5702
5701 5703 cmdutil.summaryremotehooks(ui, repo, opts,
5702 5704 ((source, sbranch, sother, commoninc),
5703 5705 (dest, dbranch, dother, outgoing)))
5704 5706
5705 5707 @command('tag',
5706 5708 [('f', 'force', None, _('force tag')),
5707 5709 ('l', 'local', None, _('make the tag local')),
5708 5710 ('r', 'rev', '', _('revision to tag'), _('REV')),
5709 5711 ('', 'remove', None, _('remove a tag')),
5710 5712 # -l/--local is already there, commitopts cannot be used
5711 5713 ('e', 'edit', None, _('invoke editor on commit messages')),
5712 5714 ('m', 'message', '', _('use text as commit message'), _('TEXT')),
5713 5715 ] + commitopts2,
5714 5716 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5715 5717 def tag(ui, repo, name1, *names, **opts):
5716 5718 """add one or more tags for the current or given revision
5717 5719
5718 5720 Name a particular revision using <name>.
5719 5721
5720 5722 Tags are used to name particular revisions of the repository and are
5721 5723 very useful to compare different revisions, to go back to significant
5722 5724 earlier versions or to mark branch points as releases, etc. Changing
5723 5725 an existing tag is normally disallowed; use -f/--force to override.
5724 5726
5725 5727 If no revision is given, the parent of the working directory is
5726 5728 used.
5727 5729
5728 5730 To facilitate version control, distribution, and merging of tags,
5729 5731 they are stored as a file named ".hgtags" which is managed similarly
5730 5732 to other project files and can be hand-edited if necessary. This
5731 5733 also means that tagging creates a new commit. The file
5732 5734 ".hg/localtags" is used for local tags (not shared among
5733 5735 repositories).
5734 5736
5735 5737 Tag commits are usually made at the head of a branch. If the parent
5736 5738 of the working directory is not a branch head, :hg:`tag` aborts; use
5737 5739 -f/--force to force the tag commit to be based on a non-head
5738 5740 changeset.
5739 5741
5740 5742 See :hg:`help dates` for a list of formats valid for -d/--date.
5741 5743
5742 5744 Since tag names have priority over branch names during revision
5743 5745 lookup, using an existing branch name as a tag name is discouraged.
5744 5746
5745 5747 Returns 0 on success.
5746 5748 """
5747 5749 wlock = lock = None
5748 5750 try:
5749 5751 wlock = repo.wlock()
5750 5752 lock = repo.lock()
5751 5753 rev_ = "."
5752 5754 names = [t.strip() for t in (name1,) + names]
5753 5755 if len(names) != len(set(names)):
5754 5756 raise util.Abort(_('tag names must be unique'))
5755 5757 for n in names:
5756 5758 scmutil.checknewlabel(repo, n, 'tag')
5757 5759 if not n:
5758 5760 raise util.Abort(_('tag names cannot consist entirely of '
5759 5761 'whitespace'))
5760 5762 if opts.get('rev') and opts.get('remove'):
5761 5763 raise util.Abort(_("--rev and --remove are incompatible"))
5762 5764 if opts.get('rev'):
5763 5765 rev_ = opts['rev']
5764 5766 message = opts.get('message')
5765 5767 if opts.get('remove'):
5766 5768 expectedtype = opts.get('local') and 'local' or 'global'
5767 5769 for n in names:
5768 5770 if not repo.tagtype(n):
5769 5771 raise util.Abort(_("tag '%s' does not exist") % n)
5770 5772 if repo.tagtype(n) != expectedtype:
5771 5773 if expectedtype == 'global':
5772 5774 raise util.Abort(_("tag '%s' is not a global tag") % n)
5773 5775 else:
5774 5776 raise util.Abort(_("tag '%s' is not a local tag") % n)
5775 5777 rev_ = nullid
5776 5778 if not message:
5777 5779 # we don't translate commit messages
5778 5780 message = 'Removed tag %s' % ', '.join(names)
5779 5781 elif not opts.get('force'):
5780 5782 for n in names:
5781 5783 if n in repo.tags():
5782 5784 raise util.Abort(_("tag '%s' already exists "
5783 5785 "(use -f to force)") % n)
5784 5786 if not opts.get('local'):
5785 5787 p1, p2 = repo.dirstate.parents()
5786 5788 if p2 != nullid:
5787 5789 raise util.Abort(_('uncommitted merge'))
5788 5790 bheads = repo.branchheads()
5789 5791 if not opts.get('force') and bheads and p1 not in bheads:
5790 5792 raise util.Abort(_('not at a branch head (use -f to force)'))
5791 5793 r = scmutil.revsingle(repo, rev_).node()
5792 5794
5793 5795 if not message:
5794 5796 # we don't translate commit messages
5795 5797 message = ('Added tag %s for changeset %s' %
5796 5798 (', '.join(names), short(r)))
5797 5799
5798 5800 date = opts.get('date')
5799 5801 if date:
5800 5802 date = util.parsedate(date)
5801 5803
5802 5804 if opts.get('remove'):
5803 5805 editform = 'tag.remove'
5804 5806 else:
5805 5807 editform = 'tag.add'
5806 5808 editor = cmdutil.getcommiteditor(editform=editform, **opts)
5807 5809
5808 5810 # don't allow tagging the null rev
5809 5811 if (not opts.get('remove') and
5810 5812 scmutil.revsingle(repo, rev_).rev() == nullrev):
5811 5813 raise util.Abort(_("cannot tag null revision"))
5812 5814
5813 5815 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date,
5814 5816 editor=editor)
5815 5817 finally:
5816 5818 release(lock, wlock)
5817 5819
5818 5820 @command('tags', [], '')
5819 5821 def tags(ui, repo, **opts):
5820 5822 """list repository tags
5821 5823
5822 5824 This lists both regular and local tags. When the -v/--verbose
5823 5825 switch is used, a third column "local" is printed for local tags.
5824 5826
5825 5827 Returns 0 on success.
5826 5828 """
5827 5829
5828 5830 fm = ui.formatter('tags', opts)
5829 5831 hexfunc = ui.debugflag and hex or short
5830 5832 tagtype = ""
5831 5833
5832 5834 for t, n in reversed(repo.tagslist()):
5833 5835 hn = hexfunc(n)
5834 5836 label = 'tags.normal'
5835 5837 tagtype = ''
5836 5838 if repo.tagtype(t) == 'local':
5837 5839 label = 'tags.local'
5838 5840 tagtype = 'local'
5839 5841
5840 5842 fm.startitem()
5841 5843 fm.write('tag', '%s', t, label=label)
5842 5844 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
5843 5845 fm.condwrite(not ui.quiet, 'rev id', fmt,
5844 5846 repo.changelog.rev(n), hn, label=label)
5845 5847 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
5846 5848 tagtype, label=label)
5847 5849 fm.plain('\n')
5848 5850 fm.end()
5849 5851
5850 5852 @command('tip',
5851 5853 [('p', 'patch', None, _('show patch')),
5852 5854 ('g', 'git', None, _('use git extended diff format')),
5853 5855 ] + templateopts,
5854 5856 _('[-p] [-g]'))
5855 5857 def tip(ui, repo, **opts):
5856 5858 """show the tip revision (DEPRECATED)
5857 5859
5858 5860 The tip revision (usually just called the tip) is the changeset
5859 5861 most recently added to the repository (and therefore the most
5860 5862 recently changed head).
5861 5863
5862 5864 If you have just made a commit, that commit will be the tip. If
5863 5865 you have just pulled changes from another repository, the tip of
5864 5866 that repository becomes the current tip. The "tip" tag is special
5865 5867 and cannot be renamed or assigned to a different changeset.
5866 5868
5867 5869 This command is deprecated, please use :hg:`heads` instead.
5868 5870
5869 5871 Returns 0 on success.
5870 5872 """
5871 5873 displayer = cmdutil.show_changeset(ui, repo, opts)
5872 5874 displayer.show(repo['tip'])
5873 5875 displayer.close()
5874 5876
5875 5877 @command('unbundle',
5876 5878 [('u', 'update', None,
5877 5879 _('update to new branch head if changesets were unbundled'))],
5878 5880 _('[-u] FILE...'))
5879 5881 def unbundle(ui, repo, fname1, *fnames, **opts):
5880 5882 """apply one or more changegroup files
5881 5883
5882 5884 Apply one or more compressed changegroup files generated by the
5883 5885 bundle command.
5884 5886
5885 5887 Returns 0 on success, 1 if an update has unresolved files.
5886 5888 """
5887 5889 fnames = (fname1,) + fnames
5888 5890
5889 5891 lock = repo.lock()
5890 5892 wc = repo['.']
5891 5893 try:
5892 5894 for fname in fnames:
5893 5895 f = hg.openpath(ui, fname)
5894 5896 gen = exchange.readbundle(ui, f, fname)
5895 5897 modheads = changegroup.addchangegroup(repo, gen, 'unbundle',
5896 5898 'bundle:' + fname)
5897 5899 finally:
5898 5900 lock.release()
5899 5901 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
5900 5902 return postincoming(ui, repo, modheads, opts.get('update'), None)
5901 5903
5902 5904 @command('^update|up|checkout|co',
5903 5905 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5904 5906 ('c', 'check', None,
5905 5907 _('update across branches if no uncommitted changes')),
5906 5908 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5907 5909 ('r', 'rev', '', _('revision'), _('REV'))
5908 5910 ] + mergetoolopts,
5909 5911 _('[-c] [-C] [-d DATE] [[-r] REV]'))
5910 5912 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False,
5911 5913 tool=None):
5912 5914 """update working directory (or switch revisions)
5913 5915
5914 5916 Update the repository's working directory to the specified
5915 5917 changeset. If no changeset is specified, update to the tip of the
5916 5918 current named branch and move the current bookmark (see :hg:`help
5917 5919 bookmarks`).
5918 5920
5919 5921 Update sets the working directory's parent revision to the specified
5920 5922 changeset (see :hg:`help parents`).
5921 5923
5922 5924 If the changeset is not a descendant or ancestor of the working
5923 5925 directory's parent, the update is aborted. With the -c/--check
5924 5926 option, the working directory is checked for uncommitted changes; if
5925 5927 none are found, the working directory is updated to the specified
5926 5928 changeset.
5927 5929
5928 5930 .. container:: verbose
5929 5931
5930 5932 The following rules apply when the working directory contains
5931 5933 uncommitted changes:
5932 5934
5933 5935 1. If neither -c/--check nor -C/--clean is specified, and if
5934 5936 the requested changeset is an ancestor or descendant of
5935 5937 the working directory's parent, the uncommitted changes
5936 5938 are merged into the requested changeset and the merged
5937 5939 result is left uncommitted. If the requested changeset is
5938 5940 not an ancestor or descendant (that is, it is on another
5939 5941 branch), the update is aborted and the uncommitted changes
5940 5942 are preserved.
5941 5943
5942 5944 2. With the -c/--check option, the update is aborted and the
5943 5945 uncommitted changes are preserved.
5944 5946
5945 5947 3. With the -C/--clean option, uncommitted changes are discarded and
5946 5948 the working directory is updated to the requested changeset.
5947 5949
5948 5950 To cancel an uncommitted merge (and lose your changes), use
5949 5951 :hg:`update --clean .`.
5950 5952
5951 5953 Use null as the changeset to remove the working directory (like
5952 5954 :hg:`clone -U`).
5953 5955
5954 5956 If you want to revert just one file to an older revision, use
5955 5957 :hg:`revert [-r REV] NAME`.
5956 5958
5957 5959 See :hg:`help dates` for a list of formats valid for -d/--date.
5958 5960
5959 5961 Returns 0 on success, 1 if there are unresolved files.
5960 5962 """
5961 5963 if rev and node:
5962 5964 raise util.Abort(_("please specify just one revision"))
5963 5965
5964 5966 if rev is None or rev == '':
5965 5967 rev = node
5966 5968
5967 5969 cmdutil.clearunfinished(repo)
5968 5970
5969 5971 # with no argument, we also move the current bookmark, if any
5970 5972 rev, movemarkfrom = bookmarks.calculateupdate(ui, repo, rev)
5971 5973
5972 5974 # if we defined a bookmark, we have to remember the original bookmark name
5973 5975 brev = rev
5974 5976 rev = scmutil.revsingle(repo, rev, rev).rev()
5975 5977
5976 5978 if check and clean:
5977 5979 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5978 5980
5979 5981 if date:
5980 5982 if rev is not None:
5981 5983 raise util.Abort(_("you can't specify a revision and a date"))
5982 5984 rev = cmdutil.finddate(ui, repo, date)
5983 5985
5984 5986 if check:
5985 5987 c = repo[None]
5986 5988 if c.dirty(merge=False, branch=False, missing=True):
5987 5989 raise util.Abort(_("uncommitted changes"))
5988 5990 if rev is None:
5989 5991 rev = repo[repo[None].branch()].rev()
5990 5992 mergemod._checkunknown(repo, repo[None], repo[rev])
5991 5993
5992 5994 repo.ui.setconfig('ui', 'forcemerge', tool, 'update')
5993 5995
5994 5996 if clean:
5995 5997 ret = hg.clean(repo, rev)
5996 5998 else:
5997 5999 ret = hg.update(repo, rev)
5998 6000
5999 6001 if not ret and movemarkfrom:
6000 6002 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
6001 6003 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
6002 6004 elif brev in repo._bookmarks:
6003 6005 bookmarks.setcurrent(repo, brev)
6004 6006 ui.status(_("(activating bookmark %s)\n") % brev)
6005 6007 elif brev:
6006 6008 if repo._bookmarkcurrent:
6007 6009 ui.status(_("(leaving bookmark %s)\n") %
6008 6010 repo._bookmarkcurrent)
6009 6011 bookmarks.unsetcurrent(repo)
6010 6012
6011 6013 return ret
6012 6014
6013 6015 @command('verify', [])
6014 6016 def verify(ui, repo):
6015 6017 """verify the integrity of the repository
6016 6018
6017 6019 Verify the integrity of the current repository.
6018 6020
6019 6021 This will perform an extensive check of the repository's
6020 6022 integrity, validating the hashes and checksums of each entry in
6021 6023 the changelog, manifest, and tracked files, as well as the
6022 6024 integrity of their crosslinks and indices.
6023 6025
6024 6026 Please see http://mercurial.selenic.com/wiki/RepositoryCorruption
6025 6027 for more information about recovery from corruption of the
6026 6028 repository.
6027 6029
6028 6030 Returns 0 on success, 1 if errors are encountered.
6029 6031 """
6030 6032 return hg.verify(repo)
6031 6033
6032 6034 @command('version', [], norepo=True)
6033 6035 def version_(ui):
6034 6036 """output version and copyright information"""
6035 6037 ui.write(_("Mercurial Distributed SCM (version %s)\n")
6036 6038 % util.version())
6037 6039 ui.status(_(
6038 6040 "(see http://mercurial.selenic.com for more information)\n"
6039 6041 "\nCopyright (C) 2005-2014 Matt Mackall and others\n"
6040 6042 "This is free software; see the source for copying conditions. "
6041 6043 "There is NO\nwarranty; "
6042 6044 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
6043 6045 ))
6044 6046
6045 6047 ui.note(_("\nEnabled extensions:\n\n"))
6046 6048 if ui.verbose:
6047 6049 # format names and versions into columns
6048 6050 names = []
6049 6051 vers = []
6050 6052 for name, module in extensions.extensions():
6051 6053 names.append(name)
6052 6054 vers.append(extensions.moduleversion(module))
6053 6055 if names:
6054 6056 maxnamelen = max(len(n) for n in names)
6055 6057 for i, name in enumerate(names):
6056 6058 ui.write(" %-*s %s\n" % (maxnamelen, name, vers[i]))
General Comments 0
You need to be logged in to leave comments. Login now