##// END OF EJS Templates
Merge with crew-stable.
Augie Fackler -
r17932:c8ffde27 merge default
parent child Browse files
Show More
@@ -1,2020 +1,2023 b''
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 subrepo, context, repair, graphmod, revset, phases, obsolete
14 14 import changelog
15 15 import lock as lockmod
16 16
17 17 def parsealiases(cmd):
18 18 return cmd.lstrip("^").split("|")
19 19
20 20 def findpossible(cmd, table, strict=False):
21 21 """
22 22 Return cmd -> (aliases, command table entry)
23 23 for each matching command.
24 24 Return debug commands (or their aliases) only if no normal command matches.
25 25 """
26 26 choice = {}
27 27 debugchoice = {}
28 28
29 29 if cmd in table:
30 30 # short-circuit exact matches, "log" alias beats "^log|history"
31 31 keys = [cmd]
32 32 else:
33 33 keys = table.keys()
34 34
35 35 for e in keys:
36 36 aliases = parsealiases(e)
37 37 found = None
38 38 if cmd in aliases:
39 39 found = cmd
40 40 elif not strict:
41 41 for a in aliases:
42 42 if a.startswith(cmd):
43 43 found = a
44 44 break
45 45 if found is not None:
46 46 if aliases[0].startswith("debug") or found.startswith("debug"):
47 47 debugchoice[found] = (aliases, table[e])
48 48 else:
49 49 choice[found] = (aliases, table[e])
50 50
51 51 if not choice and debugchoice:
52 52 choice = debugchoice
53 53
54 54 return choice
55 55
56 56 def findcmd(cmd, table, strict=True):
57 57 """Return (aliases, command table entry) for command string."""
58 58 choice = findpossible(cmd, table, strict)
59 59
60 60 if cmd in choice:
61 61 return choice[cmd]
62 62
63 63 if len(choice) > 1:
64 64 clist = choice.keys()
65 65 clist.sort()
66 66 raise error.AmbiguousCommand(cmd, clist)
67 67
68 68 if choice:
69 69 return choice.values()[0]
70 70
71 71 raise error.UnknownCommand(cmd)
72 72
73 73 def findrepo(p):
74 74 while not os.path.isdir(os.path.join(p, ".hg")):
75 75 oldp, p = p, os.path.dirname(p)
76 76 if p == oldp:
77 77 return None
78 78
79 79 return p
80 80
81 81 def bailifchanged(repo):
82 82 if repo.dirstate.p2() != nullid:
83 83 raise util.Abort(_('outstanding uncommitted merge'))
84 84 modified, added, removed, deleted = repo.status()[:4]
85 85 if modified or added or removed or deleted:
86 86 raise util.Abort(_("outstanding uncommitted changes"))
87 87 ctx = repo[None]
88 88 for s in ctx.substate:
89 89 if ctx.sub(s).dirty():
90 90 raise util.Abort(_("uncommitted changes in subrepo %s") % s)
91 91
92 92 def logmessage(ui, opts):
93 93 """ get the log message according to -m and -l option """
94 94 message = opts.get('message')
95 95 logfile = opts.get('logfile')
96 96
97 97 if message and logfile:
98 98 raise util.Abort(_('options --message and --logfile are mutually '
99 99 'exclusive'))
100 100 if not message and logfile:
101 101 try:
102 102 if logfile == '-':
103 103 message = ui.fin.read()
104 104 else:
105 105 message = '\n'.join(util.readfile(logfile).splitlines())
106 106 except IOError, inst:
107 107 raise util.Abort(_("can't read commit message '%s': %s") %
108 108 (logfile, inst.strerror))
109 109 return message
110 110
111 111 def loglimit(opts):
112 112 """get the log limit according to option -l/--limit"""
113 113 limit = opts.get('limit')
114 114 if limit:
115 115 try:
116 116 limit = int(limit)
117 117 except ValueError:
118 118 raise util.Abort(_('limit must be a positive integer'))
119 119 if limit <= 0:
120 120 raise util.Abort(_('limit must be positive'))
121 121 else:
122 122 limit = None
123 123 return limit
124 124
125 125 def makefilename(repo, pat, node, desc=None,
126 126 total=None, seqno=None, revwidth=None, pathname=None):
127 127 node_expander = {
128 128 'H': lambda: hex(node),
129 129 'R': lambda: str(repo.changelog.rev(node)),
130 130 'h': lambda: short(node),
131 131 'm': lambda: re.sub('[^\w]', '_', str(desc))
132 132 }
133 133 expander = {
134 134 '%': lambda: '%',
135 135 'b': lambda: os.path.basename(repo.root),
136 136 }
137 137
138 138 try:
139 139 if node:
140 140 expander.update(node_expander)
141 141 if node:
142 142 expander['r'] = (lambda:
143 143 str(repo.changelog.rev(node)).zfill(revwidth or 0))
144 144 if total is not None:
145 145 expander['N'] = lambda: str(total)
146 146 if seqno is not None:
147 147 expander['n'] = lambda: str(seqno)
148 148 if total is not None and seqno is not None:
149 149 expander['n'] = lambda: str(seqno).zfill(len(str(total)))
150 150 if pathname is not None:
151 151 expander['s'] = lambda: os.path.basename(pathname)
152 152 expander['d'] = lambda: os.path.dirname(pathname) or '.'
153 153 expander['p'] = lambda: pathname
154 154
155 155 newname = []
156 156 patlen = len(pat)
157 157 i = 0
158 158 while i < patlen:
159 159 c = pat[i]
160 160 if c == '%':
161 161 i += 1
162 162 c = pat[i]
163 163 c = expander[c]()
164 164 newname.append(c)
165 165 i += 1
166 166 return ''.join(newname)
167 167 except KeyError, inst:
168 168 raise util.Abort(_("invalid format spec '%%%s' in output filename") %
169 169 inst.args[0])
170 170
171 171 def makefileobj(repo, pat, node=None, desc=None, total=None,
172 172 seqno=None, revwidth=None, mode='wb', pathname=None):
173 173
174 174 writable = mode not in ('r', 'rb')
175 175
176 176 if not pat or pat == '-':
177 177 fp = writable and repo.ui.fout or repo.ui.fin
178 178 if util.safehasattr(fp, 'fileno'):
179 179 return os.fdopen(os.dup(fp.fileno()), mode)
180 180 else:
181 181 # if this fp can't be duped properly, return
182 182 # a dummy object that can be closed
183 183 class wrappedfileobj(object):
184 184 noop = lambda x: None
185 185 def __init__(self, f):
186 186 self.f = f
187 187 def __getattr__(self, attr):
188 188 if attr == 'close':
189 189 return self.noop
190 190 else:
191 191 return getattr(self.f, attr)
192 192
193 193 return wrappedfileobj(fp)
194 194 if util.safehasattr(pat, 'write') and writable:
195 195 return pat
196 196 if util.safehasattr(pat, 'read') and 'r' in mode:
197 197 return pat
198 198 return open(makefilename(repo, pat, node, desc, total, seqno, revwidth,
199 199 pathname),
200 200 mode)
201 201
202 202 def openrevlog(repo, cmd, file_, opts):
203 203 """opens the changelog, manifest, a filelog or a given revlog"""
204 204 cl = opts['changelog']
205 205 mf = opts['manifest']
206 206 msg = None
207 207 if cl and mf:
208 208 msg = _('cannot specify --changelog and --manifest at the same time')
209 209 elif cl or mf:
210 210 if file_:
211 211 msg = _('cannot specify filename with --changelog or --manifest')
212 212 elif not repo:
213 213 msg = _('cannot specify --changelog or --manifest '
214 214 'without a repository')
215 215 if msg:
216 216 raise util.Abort(msg)
217 217
218 218 r = None
219 219 if repo:
220 220 if cl:
221 221 r = repo.changelog
222 222 elif mf:
223 223 r = repo.manifest
224 224 elif file_:
225 225 filelog = repo.file(file_)
226 226 if len(filelog):
227 227 r = filelog
228 228 if not r:
229 229 if not file_:
230 230 raise error.CommandError(cmd, _('invalid arguments'))
231 231 if not os.path.isfile(file_):
232 232 raise util.Abort(_("revlog '%s' not found") % file_)
233 233 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False),
234 234 file_[:-2] + ".i")
235 235 return r
236 236
237 237 def copy(ui, repo, pats, opts, rename=False):
238 238 # called with the repo lock held
239 239 #
240 240 # hgsep => pathname that uses "/" to separate directories
241 241 # ossep => pathname that uses os.sep to separate directories
242 242 cwd = repo.getcwd()
243 243 targets = {}
244 244 after = opts.get("after")
245 245 dryrun = opts.get("dry_run")
246 246 wctx = repo[None]
247 247
248 248 def walkpat(pat):
249 249 srcs = []
250 250 badstates = after and '?' or '?r'
251 251 m = scmutil.match(repo[None], [pat], opts, globbed=True)
252 252 for abs in repo.walk(m):
253 253 state = repo.dirstate[abs]
254 254 rel = m.rel(abs)
255 255 exact = m.exact(abs)
256 256 if state in badstates:
257 257 if exact and state == '?':
258 258 ui.warn(_('%s: not copying - file is not managed\n') % rel)
259 259 if exact and state == 'r':
260 260 ui.warn(_('%s: not copying - file has been marked for'
261 261 ' remove\n') % rel)
262 262 continue
263 263 # abs: hgsep
264 264 # rel: ossep
265 265 srcs.append((abs, rel, exact))
266 266 return srcs
267 267
268 268 # abssrc: hgsep
269 269 # relsrc: ossep
270 270 # otarget: ossep
271 271 def copyfile(abssrc, relsrc, otarget, exact):
272 272 abstarget = scmutil.canonpath(repo.root, cwd, otarget)
273 273 if '/' in abstarget:
274 274 # We cannot normalize abstarget itself, this would prevent
275 275 # case only renames, like a => A.
276 276 abspath, absname = abstarget.rsplit('/', 1)
277 277 abstarget = repo.dirstate.normalize(abspath) + '/' + absname
278 278 reltarget = repo.pathto(abstarget, cwd)
279 279 target = repo.wjoin(abstarget)
280 280 src = repo.wjoin(abssrc)
281 281 state = repo.dirstate[abstarget]
282 282
283 283 scmutil.checkportable(ui, abstarget)
284 284
285 285 # check for collisions
286 286 prevsrc = targets.get(abstarget)
287 287 if prevsrc is not None:
288 288 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
289 289 (reltarget, repo.pathto(abssrc, cwd),
290 290 repo.pathto(prevsrc, cwd)))
291 291 return
292 292
293 293 # check for overwrites
294 294 exists = os.path.lexists(target)
295 295 samefile = False
296 296 if exists and abssrc != abstarget:
297 297 if (repo.dirstate.normalize(abssrc) ==
298 298 repo.dirstate.normalize(abstarget)):
299 299 if not rename:
300 300 ui.warn(_("%s: can't copy - same file\n") % reltarget)
301 301 return
302 302 exists = False
303 303 samefile = True
304 304
305 305 if not after and exists or after and state in 'mn':
306 306 if not opts['force']:
307 307 ui.warn(_('%s: not overwriting - file exists\n') %
308 308 reltarget)
309 309 return
310 310
311 311 if after:
312 312 if not exists:
313 313 if rename:
314 314 ui.warn(_('%s: not recording move - %s does not exist\n') %
315 315 (relsrc, reltarget))
316 316 else:
317 317 ui.warn(_('%s: not recording copy - %s does not exist\n') %
318 318 (relsrc, reltarget))
319 319 return
320 320 elif not dryrun:
321 321 try:
322 322 if exists:
323 323 os.unlink(target)
324 324 targetdir = os.path.dirname(target) or '.'
325 325 if not os.path.isdir(targetdir):
326 326 os.makedirs(targetdir)
327 327 if samefile:
328 328 tmp = target + "~hgrename"
329 329 os.rename(src, tmp)
330 330 os.rename(tmp, target)
331 331 else:
332 332 util.copyfile(src, target)
333 333 srcexists = True
334 334 except IOError, inst:
335 335 if inst.errno == errno.ENOENT:
336 336 ui.warn(_('%s: deleted in working copy\n') % relsrc)
337 337 srcexists = False
338 338 else:
339 339 ui.warn(_('%s: cannot copy - %s\n') %
340 340 (relsrc, inst.strerror))
341 341 return True # report a failure
342 342
343 343 if ui.verbose or not exact:
344 344 if rename:
345 345 ui.status(_('moving %s to %s\n') % (relsrc, reltarget))
346 346 else:
347 347 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
348 348
349 349 targets[abstarget] = abssrc
350 350
351 351 # fix up dirstate
352 352 scmutil.dirstatecopy(ui, repo, wctx, abssrc, abstarget,
353 353 dryrun=dryrun, cwd=cwd)
354 354 if rename and not dryrun:
355 355 if not after and srcexists and not samefile:
356 356 util.unlinkpath(repo.wjoin(abssrc))
357 357 wctx.forget([abssrc])
358 358
359 359 # pat: ossep
360 360 # dest ossep
361 361 # srcs: list of (hgsep, hgsep, ossep, bool)
362 362 # return: function that takes hgsep and returns ossep
363 363 def targetpathfn(pat, dest, srcs):
364 364 if os.path.isdir(pat):
365 365 abspfx = scmutil.canonpath(repo.root, cwd, pat)
366 366 abspfx = util.localpath(abspfx)
367 367 if destdirexists:
368 368 striplen = len(os.path.split(abspfx)[0])
369 369 else:
370 370 striplen = len(abspfx)
371 371 if striplen:
372 372 striplen += len(os.sep)
373 373 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
374 374 elif destdirexists:
375 375 res = lambda p: os.path.join(dest,
376 376 os.path.basename(util.localpath(p)))
377 377 else:
378 378 res = lambda p: dest
379 379 return res
380 380
381 381 # pat: ossep
382 382 # dest ossep
383 383 # srcs: list of (hgsep, hgsep, ossep, bool)
384 384 # return: function that takes hgsep and returns ossep
385 385 def targetpathafterfn(pat, dest, srcs):
386 386 if matchmod.patkind(pat):
387 387 # a mercurial pattern
388 388 res = lambda p: os.path.join(dest,
389 389 os.path.basename(util.localpath(p)))
390 390 else:
391 391 abspfx = scmutil.canonpath(repo.root, cwd, pat)
392 392 if len(abspfx) < len(srcs[0][0]):
393 393 # A directory. Either the target path contains the last
394 394 # component of the source path or it does not.
395 395 def evalpath(striplen):
396 396 score = 0
397 397 for s in srcs:
398 398 t = os.path.join(dest, util.localpath(s[0])[striplen:])
399 399 if os.path.lexists(t):
400 400 score += 1
401 401 return score
402 402
403 403 abspfx = util.localpath(abspfx)
404 404 striplen = len(abspfx)
405 405 if striplen:
406 406 striplen += len(os.sep)
407 407 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
408 408 score = evalpath(striplen)
409 409 striplen1 = len(os.path.split(abspfx)[0])
410 410 if striplen1:
411 411 striplen1 += len(os.sep)
412 412 if evalpath(striplen1) > score:
413 413 striplen = striplen1
414 414 res = lambda p: os.path.join(dest,
415 415 util.localpath(p)[striplen:])
416 416 else:
417 417 # a file
418 418 if destdirexists:
419 419 res = lambda p: os.path.join(dest,
420 420 os.path.basename(util.localpath(p)))
421 421 else:
422 422 res = lambda p: dest
423 423 return res
424 424
425 425
426 426 pats = scmutil.expandpats(pats)
427 427 if not pats:
428 428 raise util.Abort(_('no source or destination specified'))
429 429 if len(pats) == 1:
430 430 raise util.Abort(_('no destination specified'))
431 431 dest = pats.pop()
432 432 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
433 433 if not destdirexists:
434 434 if len(pats) > 1 or matchmod.patkind(pats[0]):
435 435 raise util.Abort(_('with multiple sources, destination must be an '
436 436 'existing directory'))
437 437 if util.endswithsep(dest):
438 438 raise util.Abort(_('destination %s is not a directory') % dest)
439 439
440 440 tfn = targetpathfn
441 441 if after:
442 442 tfn = targetpathafterfn
443 443 copylist = []
444 444 for pat in pats:
445 445 srcs = walkpat(pat)
446 446 if not srcs:
447 447 continue
448 448 copylist.append((tfn(pat, dest, srcs), srcs))
449 449 if not copylist:
450 450 raise util.Abort(_('no files to copy'))
451 451
452 452 errors = 0
453 453 for targetpath, srcs in copylist:
454 454 for abssrc, relsrc, exact in srcs:
455 455 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
456 456 errors += 1
457 457
458 458 if errors:
459 459 ui.warn(_('(consider using --after)\n'))
460 460
461 461 return errors != 0
462 462
463 463 def service(opts, parentfn=None, initfn=None, runfn=None, logfile=None,
464 464 runargs=None, appendpid=False):
465 465 '''Run a command as a service.'''
466 466
467 467 if opts['daemon'] and not opts['daemon_pipefds']:
468 468 # Signal child process startup with file removal
469 469 lockfd, lockpath = tempfile.mkstemp(prefix='hg-service-')
470 470 os.close(lockfd)
471 471 try:
472 472 if not runargs:
473 473 runargs = util.hgcmd() + sys.argv[1:]
474 474 runargs.append('--daemon-pipefds=%s' % lockpath)
475 475 # Don't pass --cwd to the child process, because we've already
476 476 # changed directory.
477 477 for i in xrange(1, len(runargs)):
478 478 if runargs[i].startswith('--cwd='):
479 479 del runargs[i]
480 480 break
481 481 elif runargs[i].startswith('--cwd'):
482 482 del runargs[i:i + 2]
483 483 break
484 484 def condfn():
485 485 return not os.path.exists(lockpath)
486 486 pid = util.rundetached(runargs, condfn)
487 487 if pid < 0:
488 488 raise util.Abort(_('child process failed to start'))
489 489 finally:
490 490 try:
491 491 os.unlink(lockpath)
492 492 except OSError, e:
493 493 if e.errno != errno.ENOENT:
494 494 raise
495 495 if parentfn:
496 496 return parentfn(pid)
497 497 else:
498 498 return
499 499
500 500 if initfn:
501 501 initfn()
502 502
503 503 if opts['pid_file']:
504 504 mode = appendpid and 'a' or 'w'
505 505 fp = open(opts['pid_file'], mode)
506 506 fp.write(str(os.getpid()) + '\n')
507 507 fp.close()
508 508
509 509 if opts['daemon_pipefds']:
510 510 lockpath = opts['daemon_pipefds']
511 511 try:
512 512 os.setsid()
513 513 except AttributeError:
514 514 pass
515 515 os.unlink(lockpath)
516 516 util.hidewindow()
517 517 sys.stdout.flush()
518 518 sys.stderr.flush()
519 519
520 520 nullfd = os.open(os.devnull, os.O_RDWR)
521 521 logfilefd = nullfd
522 522 if logfile:
523 523 logfilefd = os.open(logfile, os.O_RDWR | os.O_CREAT | os.O_APPEND)
524 524 os.dup2(nullfd, 0)
525 525 os.dup2(logfilefd, 1)
526 526 os.dup2(logfilefd, 2)
527 527 if nullfd not in (0, 1, 2):
528 528 os.close(nullfd)
529 529 if logfile and logfilefd not in (0, 1, 2):
530 530 os.close(logfilefd)
531 531
532 532 if runfn:
533 533 return runfn()
534 534
535 535 def export(repo, revs, template='hg-%h.patch', fp=None, switch_parent=False,
536 536 opts=None):
537 537 '''export changesets as hg patches.'''
538 538
539 539 total = len(revs)
540 540 revwidth = max([len(str(rev)) for rev in revs])
541 541
542 542 def single(rev, seqno, fp):
543 543 ctx = repo[rev]
544 544 node = ctx.node()
545 545 parents = [p.node() for p in ctx.parents() if p]
546 546 branch = ctx.branch()
547 547 if switch_parent:
548 548 parents.reverse()
549 549 prev = (parents and parents[0]) or nullid
550 550
551 551 shouldclose = False
552 552 if not fp and len(template) > 0:
553 553 desc_lines = ctx.description().rstrip().split('\n')
554 554 desc = desc_lines[0] #Commit always has a first line.
555 555 fp = makefileobj(repo, template, node, desc=desc, total=total,
556 556 seqno=seqno, revwidth=revwidth, mode='ab')
557 557 if fp != template:
558 558 shouldclose = True
559 559 if fp and fp != sys.stdout and util.safehasattr(fp, 'name'):
560 560 repo.ui.note("%s\n" % fp.name)
561 561
562 562 if not fp:
563 563 write = repo.ui.write
564 564 else:
565 565 def write(s, **kw):
566 566 fp.write(s)
567 567
568 568
569 569 write("# HG changeset patch\n")
570 570 write("# User %s\n" % ctx.user())
571 571 write("# Date %d %d\n" % ctx.date())
572 572 if branch and branch != 'default':
573 573 write("# Branch %s\n" % branch)
574 574 write("# Node ID %s\n" % hex(node))
575 575 write("# Parent %s\n" % hex(prev))
576 576 if len(parents) > 1:
577 577 write("# Parent %s\n" % hex(parents[1]))
578 578 write(ctx.description().rstrip())
579 579 write("\n\n")
580 580
581 581 for chunk, label in patch.diffui(repo, prev, node, opts=opts):
582 582 write(chunk, label=label)
583 583
584 584 if shouldclose:
585 585 fp.close()
586 586
587 587 for seqno, rev in enumerate(revs):
588 588 single(rev, seqno + 1, fp)
589 589
590 590 def diffordiffstat(ui, repo, diffopts, node1, node2, match,
591 591 changes=None, stat=False, fp=None, prefix='',
592 592 listsubrepos=False):
593 593 '''show diff or diffstat.'''
594 594 if fp is None:
595 595 write = ui.write
596 596 else:
597 597 def write(s, **kw):
598 598 fp.write(s)
599 599
600 600 if stat:
601 601 diffopts = diffopts.copy(context=0)
602 602 width = 80
603 603 if not ui.plain():
604 604 width = ui.termwidth()
605 605 chunks = patch.diff(repo, node1, node2, match, changes, diffopts,
606 606 prefix=prefix)
607 607 for chunk, label in patch.diffstatui(util.iterlines(chunks),
608 608 width=width,
609 609 git=diffopts.git):
610 610 write(chunk, label=label)
611 611 else:
612 612 for chunk, label in patch.diffui(repo, node1, node2, match,
613 613 changes, diffopts, prefix=prefix):
614 614 write(chunk, label=label)
615 615
616 616 if listsubrepos:
617 617 ctx1 = repo[node1]
618 618 ctx2 = repo[node2]
619 619 for subpath, sub in subrepo.itersubrepos(ctx1, ctx2):
620 620 tempnode2 = node2
621 621 try:
622 622 if node2 is not None:
623 623 tempnode2 = ctx2.substate[subpath][1]
624 624 except KeyError:
625 625 # A subrepo that existed in node1 was deleted between node1 and
626 626 # node2 (inclusive). Thus, ctx2's substate won't contain that
627 627 # subpath. The best we can do is to ignore it.
628 628 tempnode2 = None
629 629 submatch = matchmod.narrowmatcher(subpath, match)
630 630 sub.diff(diffopts, tempnode2, submatch, changes=changes,
631 631 stat=stat, fp=fp, prefix=prefix)
632 632
633 633 class changeset_printer(object):
634 634 '''show changeset information when templating not requested.'''
635 635
636 636 def __init__(self, ui, repo, patch, diffopts, buffered):
637 637 self.ui = ui
638 638 self.repo = repo
639 639 self.buffered = buffered
640 640 self.patch = patch
641 641 self.diffopts = diffopts
642 642 self.header = {}
643 643 self.hunk = {}
644 644 self.lastheader = None
645 645 self.footer = None
646 646
647 647 def flush(self, rev):
648 648 if rev in self.header:
649 649 h = self.header[rev]
650 650 if h != self.lastheader:
651 651 self.lastheader = h
652 652 self.ui.write(h)
653 653 del self.header[rev]
654 654 if rev in self.hunk:
655 655 self.ui.write(self.hunk[rev])
656 656 del self.hunk[rev]
657 657 return 1
658 658 return 0
659 659
660 660 def close(self):
661 661 if self.footer:
662 662 self.ui.write(self.footer)
663 663
664 664 def show(self, ctx, copies=None, matchfn=None, **props):
665 665 if self.buffered:
666 666 self.ui.pushbuffer()
667 667 self._show(ctx, copies, matchfn, props)
668 668 self.hunk[ctx.rev()] = self.ui.popbuffer(labeled=True)
669 669 else:
670 670 self._show(ctx, copies, matchfn, props)
671 671
672 672 def _show(self, ctx, copies, matchfn, props):
673 673 '''show a single changeset or file revision'''
674 674 changenode = ctx.node()
675 675 rev = ctx.rev()
676 676
677 677 if self.ui.quiet:
678 678 self.ui.write("%d:%s\n" % (rev, short(changenode)),
679 679 label='log.node')
680 680 return
681 681
682 682 log = self.repo.changelog
683 683 date = util.datestr(ctx.date())
684 684
685 685 hexfunc = self.ui.debugflag and hex or short
686 686
687 687 parents = [(p, hexfunc(log.node(p)))
688 688 for p in self._meaningful_parentrevs(log, rev)]
689 689
690 690 # i18n: column positioning for "hg log"
691 691 self.ui.write(_("changeset: %d:%s\n") % (rev, hexfunc(changenode)),
692 692 label='log.changeset changeset.%s' % ctx.phasestr())
693 693
694 694 branch = ctx.branch()
695 695 # don't show the default branch name
696 696 if branch != 'default':
697 697 # i18n: column positioning for "hg log"
698 698 self.ui.write(_("branch: %s\n") % branch,
699 699 label='log.branch')
700 700 for bookmark in self.repo.nodebookmarks(changenode):
701 701 # i18n: column positioning for "hg log"
702 702 self.ui.write(_("bookmark: %s\n") % bookmark,
703 703 label='log.bookmark')
704 704 for tag in self.repo.nodetags(changenode):
705 705 # i18n: column positioning for "hg log"
706 706 self.ui.write(_("tag: %s\n") % tag,
707 707 label='log.tag')
708 708 if self.ui.debugflag and ctx.phase():
709 709 # i18n: column positioning for "hg log"
710 710 self.ui.write(_("phase: %s\n") % _(ctx.phasestr()),
711 711 label='log.phase')
712 712 for parent in parents:
713 713 # i18n: column positioning for "hg log"
714 714 self.ui.write(_("parent: %d:%s\n") % parent,
715 715 label='log.parent changeset.%s' % ctx.phasestr())
716 716
717 717 if self.ui.debugflag:
718 718 mnode = ctx.manifestnode()
719 719 # i18n: column positioning for "hg log"
720 720 self.ui.write(_("manifest: %d:%s\n") %
721 721 (self.repo.manifest.rev(mnode), hex(mnode)),
722 722 label='ui.debug log.manifest')
723 723 # i18n: column positioning for "hg log"
724 724 self.ui.write(_("user: %s\n") % ctx.user(),
725 725 label='log.user')
726 726 # i18n: column positioning for "hg log"
727 727 self.ui.write(_("date: %s\n") % date,
728 728 label='log.date')
729 729
730 730 if self.ui.debugflag:
731 731 files = self.repo.status(log.parents(changenode)[0], changenode)[:3]
732 732 for key, value in zip([# i18n: column positioning for "hg log"
733 733 _("files:"),
734 734 # i18n: column positioning for "hg log"
735 735 _("files+:"),
736 736 # i18n: column positioning for "hg log"
737 737 _("files-:")], files):
738 738 if value:
739 739 self.ui.write("%-12s %s\n" % (key, " ".join(value)),
740 740 label='ui.debug log.files')
741 741 elif ctx.files() and self.ui.verbose:
742 742 # i18n: column positioning for "hg log"
743 743 self.ui.write(_("files: %s\n") % " ".join(ctx.files()),
744 744 label='ui.note log.files')
745 745 if copies and self.ui.verbose:
746 746 copies = ['%s (%s)' % c for c in copies]
747 747 # i18n: column positioning for "hg log"
748 748 self.ui.write(_("copies: %s\n") % ' '.join(copies),
749 749 label='ui.note log.copies')
750 750
751 751 extra = ctx.extra()
752 752 if extra and self.ui.debugflag:
753 753 for key, value in sorted(extra.items()):
754 754 # i18n: column positioning for "hg log"
755 755 self.ui.write(_("extra: %s=%s\n")
756 756 % (key, value.encode('string_escape')),
757 757 label='ui.debug log.extra')
758 758
759 759 description = ctx.description().strip()
760 760 if description:
761 761 if self.ui.verbose:
762 762 self.ui.write(_("description:\n"),
763 763 label='ui.note log.description')
764 764 self.ui.write(description,
765 765 label='ui.note log.description')
766 766 self.ui.write("\n\n")
767 767 else:
768 768 # i18n: column positioning for "hg log"
769 769 self.ui.write(_("summary: %s\n") %
770 770 description.splitlines()[0],
771 771 label='log.summary')
772 772 self.ui.write("\n")
773 773
774 774 self.showpatch(changenode, matchfn)
775 775
776 776 def showpatch(self, node, matchfn):
777 777 if not matchfn:
778 778 matchfn = self.patch
779 779 if matchfn:
780 780 stat = self.diffopts.get('stat')
781 781 diff = self.diffopts.get('patch')
782 782 diffopts = patch.diffopts(self.ui, self.diffopts)
783 783 prev = self.repo.changelog.parents(node)[0]
784 784 if stat:
785 785 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
786 786 match=matchfn, stat=True)
787 787 if diff:
788 788 if stat:
789 789 self.ui.write("\n")
790 790 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
791 791 match=matchfn, stat=False)
792 792 self.ui.write("\n")
793 793
794 794 def _meaningful_parentrevs(self, log, rev):
795 795 """Return list of meaningful (or all if debug) parentrevs for rev.
796 796
797 797 For merges (two non-nullrev revisions) both parents are meaningful.
798 798 Otherwise the first parent revision is considered meaningful if it
799 799 is not the preceding revision.
800 800 """
801 801 parents = log.parentrevs(rev)
802 802 if not self.ui.debugflag and parents[1] == nullrev:
803 803 if parents[0] >= rev - 1:
804 804 parents = []
805 805 else:
806 806 parents = [parents[0]]
807 807 return parents
808 808
809 809
810 810 class changeset_templater(changeset_printer):
811 811 '''format changeset information.'''
812 812
813 813 def __init__(self, ui, repo, patch, diffopts, mapfile, buffered):
814 814 changeset_printer.__init__(self, ui, repo, patch, diffopts, buffered)
815 815 formatnode = ui.debugflag and (lambda x: x) or (lambda x: x[:12])
816 816 defaulttempl = {
817 817 'parent': '{rev}:{node|formatnode} ',
818 818 'manifest': '{rev}:{node|formatnode}',
819 819 'file_copy': '{name} ({source})',
820 820 'extra': '{key}={value|stringescape}'
821 821 }
822 822 # filecopy is preserved for compatibility reasons
823 823 defaulttempl['filecopy'] = defaulttempl['file_copy']
824 824 self.t = templater.templater(mapfile, {'formatnode': formatnode},
825 825 cache=defaulttempl)
826 826 self.cache = {}
827 827
828 828 def use_template(self, t):
829 829 '''set template string to use'''
830 830 self.t.cache['changeset'] = t
831 831
832 832 def _meaningful_parentrevs(self, ctx):
833 833 """Return list of meaningful (or all if debug) parentrevs for rev.
834 834 """
835 835 parents = ctx.parents()
836 836 if len(parents) > 1:
837 837 return parents
838 838 if self.ui.debugflag:
839 839 return [parents[0], self.repo['null']]
840 840 if parents[0].rev() >= ctx.rev() - 1:
841 841 return []
842 842 return parents
843 843
844 844 def _show(self, ctx, copies, matchfn, props):
845 845 '''show a single changeset or file revision'''
846 846
847 847 showlist = templatekw.showlist
848 848
849 849 # showparents() behaviour depends on ui trace level which
850 850 # causes unexpected behaviours at templating level and makes
851 851 # it harder to extract it in a standalone function. Its
852 852 # behaviour cannot be changed so leave it here for now.
853 853 def showparents(**args):
854 854 ctx = args['ctx']
855 855 parents = [[('rev', p.rev()), ('node', p.hex())]
856 856 for p in self._meaningful_parentrevs(ctx)]
857 857 return showlist('parent', parents, **args)
858 858
859 859 props = props.copy()
860 860 props.update(templatekw.keywords)
861 861 props['parents'] = showparents
862 862 props['templ'] = self.t
863 863 props['ctx'] = ctx
864 864 props['repo'] = self.repo
865 865 props['revcache'] = {'copies': copies}
866 866 props['cache'] = self.cache
867 867
868 868 # find correct templates for current mode
869 869
870 870 tmplmodes = [
871 871 (True, None),
872 872 (self.ui.verbose, 'verbose'),
873 873 (self.ui.quiet, 'quiet'),
874 874 (self.ui.debugflag, 'debug'),
875 875 ]
876 876
877 877 types = {'header': '', 'footer':'', 'changeset': 'changeset'}
878 878 for mode, postfix in tmplmodes:
879 879 for type in types:
880 880 cur = postfix and ('%s_%s' % (type, postfix)) or type
881 881 if mode and cur in self.t:
882 882 types[type] = cur
883 883
884 884 try:
885 885
886 886 # write header
887 887 if types['header']:
888 888 h = templater.stringify(self.t(types['header'], **props))
889 889 if self.buffered:
890 890 self.header[ctx.rev()] = h
891 891 else:
892 892 if self.lastheader != h:
893 893 self.lastheader = h
894 894 self.ui.write(h)
895 895
896 896 # write changeset metadata, then patch if requested
897 897 key = types['changeset']
898 898 self.ui.write(templater.stringify(self.t(key, **props)))
899 899 self.showpatch(ctx.node(), matchfn)
900 900
901 901 if types['footer']:
902 902 if not self.footer:
903 903 self.footer = templater.stringify(self.t(types['footer'],
904 904 **props))
905 905
906 906 except KeyError, inst:
907 907 msg = _("%s: no key named '%s'")
908 908 raise util.Abort(msg % (self.t.mapfile, inst.args[0]))
909 909 except SyntaxError, inst:
910 910 raise util.Abort('%s: %s' % (self.t.mapfile, inst.args[0]))
911 911
912 912 def show_changeset(ui, repo, opts, buffered=False):
913 913 """show one changeset using template or regular display.
914 914
915 915 Display format will be the first non-empty hit of:
916 916 1. option 'template'
917 917 2. option 'style'
918 918 3. [ui] setting 'logtemplate'
919 919 4. [ui] setting 'style'
920 920 If all of these values are either the unset or the empty string,
921 921 regular display via changeset_printer() is done.
922 922 """
923 923 # options
924 924 patch = False
925 925 if opts.get('patch') or opts.get('stat'):
926 926 patch = scmutil.matchall(repo)
927 927
928 928 tmpl = opts.get('template')
929 929 style = None
930 930 if tmpl:
931 931 tmpl = templater.parsestring(tmpl, quoted=False)
932 932 else:
933 933 style = opts.get('style')
934 934
935 935 # ui settings
936 936 if not (tmpl or style):
937 937 tmpl = ui.config('ui', 'logtemplate')
938 938 if tmpl:
939 939 try:
940 940 tmpl = templater.parsestring(tmpl)
941 941 except SyntaxError:
942 942 tmpl = templater.parsestring(tmpl, quoted=False)
943 943 else:
944 944 style = util.expandpath(ui.config('ui', 'style', ''))
945 945
946 946 if not (tmpl or style):
947 947 return changeset_printer(ui, repo, patch, opts, buffered)
948 948
949 949 mapfile = None
950 950 if style and not tmpl:
951 951 mapfile = style
952 952 if not os.path.split(mapfile)[0]:
953 953 mapname = (templater.templatepath('map-cmdline.' + mapfile)
954 954 or templater.templatepath(mapfile))
955 955 if mapname:
956 956 mapfile = mapname
957 957
958 958 try:
959 959 t = changeset_templater(ui, repo, patch, opts, mapfile, buffered)
960 960 except SyntaxError, inst:
961 961 raise util.Abort(inst.args[0])
962 962 if tmpl:
963 963 t.use_template(tmpl)
964 964 return t
965 965
966 966 def finddate(ui, repo, date):
967 967 """Find the tipmost changeset that matches the given date spec"""
968 968
969 969 df = util.matchdate(date)
970 970 m = scmutil.matchall(repo)
971 971 results = {}
972 972
973 973 def prep(ctx, fns):
974 974 d = ctx.date()
975 975 if df(d[0]):
976 976 results[ctx.rev()] = d
977 977
978 978 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
979 979 rev = ctx.rev()
980 980 if rev in results:
981 981 ui.status(_("found revision %s from %s\n") %
982 982 (rev, util.datestr(results[rev])))
983 983 return str(rev)
984 984
985 985 raise util.Abort(_("revision matching date not found"))
986 986
987 987 def increasingwindows(start, end, windowsize=8, sizelimit=512):
988 988 if start < end:
989 989 while start < end:
990 990 yield start, min(windowsize, end - start)
991 991 start += windowsize
992 992 if windowsize < sizelimit:
993 993 windowsize *= 2
994 994 else:
995 995 while start > end:
996 996 yield start, min(windowsize, start - end - 1)
997 997 start -= windowsize
998 998 if windowsize < sizelimit:
999 999 windowsize *= 2
1000 1000
1001 1001 def walkchangerevs(repo, match, opts, prepare):
1002 1002 '''Iterate over files and the revs in which they changed.
1003 1003
1004 1004 Callers most commonly need to iterate backwards over the history
1005 1005 in which they are interested. Doing so has awful (quadratic-looking)
1006 1006 performance, so we use iterators in a "windowed" way.
1007 1007
1008 1008 We walk a window of revisions in the desired order. Within the
1009 1009 window, we first walk forwards to gather data, then in the desired
1010 1010 order (usually backwards) to display it.
1011 1011
1012 1012 This function returns an iterator yielding contexts. Before
1013 1013 yielding each context, the iterator will first call the prepare
1014 1014 function on each context in the window in forward order.'''
1015 1015
1016 1016 follow = opts.get('follow') or opts.get('follow_first')
1017 1017
1018 1018 if not len(repo):
1019 1019 return []
1020 1020 if opts.get('rev'):
1021 1021 revs = scmutil.revrange(repo, opts.get('rev'))
1022 1022 elif follow:
1023 1023 revs = repo.revs('reverse(:.)')
1024 1024 else:
1025 1025 revs = list(repo)
1026 1026 revs.reverse()
1027 1027 if not revs:
1028 1028 return []
1029 1029 wanted = set()
1030 1030 slowpath = match.anypats() or (match.files() and opts.get('removed'))
1031 1031 fncache = {}
1032 1032 change = repo.changectx
1033 1033
1034 1034 # First step is to fill wanted, the set of revisions that we want to yield.
1035 1035 # When it does not induce extra cost, we also fill fncache for revisions in
1036 1036 # wanted: a cache of filenames that were changed (ctx.files()) and that
1037 1037 # match the file filtering conditions.
1038 1038
1039 1039 if not slowpath and not match.files():
1040 1040 # No files, no patterns. Display all revs.
1041 1041 wanted = set(revs)
1042 1042 copies = []
1043 1043
1044 1044 if not slowpath and match.files():
1045 1045 # We only have to read through the filelog to find wanted revisions
1046 1046
1047 1047 minrev, maxrev = min(revs), max(revs)
1048 1048 def filerevgen(filelog, last):
1049 1049 """
1050 1050 Only files, no patterns. Check the history of each file.
1051 1051
1052 1052 Examines filelog entries within minrev, maxrev linkrev range
1053 1053 Returns an iterator yielding (linkrev, parentlinkrevs, copied)
1054 1054 tuples in backwards order
1055 1055 """
1056 1056 cl_count = len(repo)
1057 1057 revs = []
1058 1058 for j in xrange(0, last + 1):
1059 1059 linkrev = filelog.linkrev(j)
1060 1060 if linkrev < minrev:
1061 1061 continue
1062 1062 # only yield rev for which we have the changelog, it can
1063 1063 # happen while doing "hg log" during a pull or commit
1064 1064 if linkrev >= cl_count:
1065 1065 break
1066 1066
1067 1067 parentlinkrevs = []
1068 1068 for p in filelog.parentrevs(j):
1069 1069 if p != nullrev:
1070 1070 parentlinkrevs.append(filelog.linkrev(p))
1071 1071 n = filelog.node(j)
1072 1072 revs.append((linkrev, parentlinkrevs,
1073 1073 follow and filelog.renamed(n)))
1074 1074
1075 1075 return reversed(revs)
1076 1076 def iterfiles():
1077 1077 pctx = repo['.']
1078 1078 for filename in match.files():
1079 1079 if follow:
1080 1080 if filename not in pctx:
1081 1081 raise util.Abort(_('cannot follow file not in parent '
1082 1082 'revision: "%s"') % filename)
1083 1083 yield filename, pctx[filename].filenode()
1084 1084 else:
1085 1085 yield filename, None
1086 1086 for filename_node in copies:
1087 1087 yield filename_node
1088 1088 for file_, node in iterfiles():
1089 1089 filelog = repo.file(file_)
1090 1090 if not len(filelog):
1091 1091 if node is None:
1092 1092 # A zero count may be a directory or deleted file, so
1093 1093 # try to find matching entries on the slow path.
1094 1094 if follow:
1095 1095 raise util.Abort(
1096 1096 _('cannot follow nonexistent file: "%s"') % file_)
1097 1097 slowpath = True
1098 1098 break
1099 1099 else:
1100 1100 continue
1101 1101
1102 1102 if node is None:
1103 1103 last = len(filelog) - 1
1104 1104 else:
1105 1105 last = filelog.rev(node)
1106 1106
1107 1107
1108 1108 # keep track of all ancestors of the file
1109 1109 ancestors = set([filelog.linkrev(last)])
1110 1110
1111 1111 # iterate from latest to oldest revision
1112 1112 for rev, flparentlinkrevs, copied in filerevgen(filelog, last):
1113 1113 if not follow:
1114 1114 if rev > maxrev:
1115 1115 continue
1116 1116 else:
1117 1117 # Note that last might not be the first interesting
1118 1118 # rev to us:
1119 1119 # if the file has been changed after maxrev, we'll
1120 1120 # have linkrev(last) > maxrev, and we still need
1121 1121 # to explore the file graph
1122 1122 if rev not in ancestors:
1123 1123 continue
1124 1124 # XXX insert 1327 fix here
1125 1125 if flparentlinkrevs:
1126 1126 ancestors.update(flparentlinkrevs)
1127 1127
1128 1128 fncache.setdefault(rev, []).append(file_)
1129 1129 wanted.add(rev)
1130 1130 if copied:
1131 1131 copies.append(copied)
1132 1132
1133 1133 # We decided to fall back to the slowpath because at least one
1134 1134 # of the paths was not a file. Check to see if at least one of them
1135 1135 # existed in history, otherwise simply return
1136 1136 if slowpath:
1137 1137 for path in match.files():
1138 1138 if path == '.' or path in repo.store:
1139 1139 break
1140 1140 else:
1141 1141 return []
1142 1142
1143 1143 if slowpath:
1144 1144 # We have to read the changelog to match filenames against
1145 1145 # changed files
1146 1146
1147 1147 if follow:
1148 1148 raise util.Abort(_('can only follow copies/renames for explicit '
1149 1149 'filenames'))
1150 1150
1151 1151 # The slow path checks files modified in every changeset.
1152 1152 for i in sorted(revs):
1153 1153 ctx = change(i)
1154 1154 matches = filter(match, ctx.files())
1155 1155 if matches:
1156 1156 fncache[i] = matches
1157 1157 wanted.add(i)
1158 1158
1159 1159 class followfilter(object):
1160 1160 def __init__(self, onlyfirst=False):
1161 1161 self.startrev = nullrev
1162 1162 self.roots = set()
1163 1163 self.onlyfirst = onlyfirst
1164 1164
1165 1165 def match(self, rev):
1166 1166 def realparents(rev):
1167 1167 if self.onlyfirst:
1168 1168 return repo.changelog.parentrevs(rev)[0:1]
1169 1169 else:
1170 1170 return filter(lambda x: x != nullrev,
1171 1171 repo.changelog.parentrevs(rev))
1172 1172
1173 1173 if self.startrev == nullrev:
1174 1174 self.startrev = rev
1175 1175 return True
1176 1176
1177 1177 if rev > self.startrev:
1178 1178 # forward: all descendants
1179 1179 if not self.roots:
1180 1180 self.roots.add(self.startrev)
1181 1181 for parent in realparents(rev):
1182 1182 if parent in self.roots:
1183 1183 self.roots.add(rev)
1184 1184 return True
1185 1185 else:
1186 1186 # backwards: all parents
1187 1187 if not self.roots:
1188 1188 self.roots.update(realparents(self.startrev))
1189 1189 if rev in self.roots:
1190 1190 self.roots.remove(rev)
1191 1191 self.roots.update(realparents(rev))
1192 1192 return True
1193 1193
1194 1194 return False
1195 1195
1196 1196 # it might be worthwhile to do this in the iterator if the rev range
1197 1197 # is descending and the prune args are all within that range
1198 1198 for rev in opts.get('prune', ()):
1199 1199 rev = repo[rev].rev()
1200 1200 ff = followfilter()
1201 1201 stop = min(revs[0], revs[-1])
1202 1202 for x in xrange(rev, stop - 1, -1):
1203 1203 if ff.match(x):
1204 1204 wanted.discard(x)
1205 1205
1206 1206 # Now that wanted is correctly initialized, we can iterate over the
1207 1207 # revision range, yielding only revisions in wanted.
1208 1208 def iterate():
1209 1209 if follow and not match.files():
1210 1210 ff = followfilter(onlyfirst=opts.get('follow_first'))
1211 1211 def want(rev):
1212 1212 return ff.match(rev) and rev in wanted
1213 1213 else:
1214 1214 def want(rev):
1215 1215 return rev in wanted
1216 1216
1217 1217 for i, window in increasingwindows(0, len(revs)):
1218 1218 nrevs = [rev for rev in revs[i:i + window] if want(rev)]
1219 1219 for rev in sorted(nrevs):
1220 1220 fns = fncache.get(rev)
1221 1221 ctx = change(rev)
1222 1222 if not fns:
1223 1223 def fns_generator():
1224 1224 for f in ctx.files():
1225 1225 if match(f):
1226 1226 yield f
1227 1227 fns = fns_generator()
1228 1228 prepare(ctx, fns)
1229 1229 for rev in nrevs:
1230 1230 yield change(rev)
1231 1231 return iterate()
1232 1232
1233 1233 def _makegraphfilematcher(repo, pats, followfirst):
1234 1234 # When displaying a revision with --patch --follow FILE, we have
1235 1235 # to know which file of the revision must be diffed. With
1236 1236 # --follow, we want the names of the ancestors of FILE in the
1237 1237 # revision, stored in "fcache". "fcache" is populated by
1238 1238 # reproducing the graph traversal already done by --follow revset
1239 1239 # and relating linkrevs to file names (which is not "correct" but
1240 1240 # good enough).
1241 1241 fcache = {}
1242 1242 fcacheready = [False]
1243 1243 pctx = repo['.']
1244 1244 wctx = repo[None]
1245 1245
1246 1246 def populate():
1247 1247 for fn in pats:
1248 1248 for i in ((pctx[fn],), pctx[fn].ancestors(followfirst=followfirst)):
1249 1249 for c in i:
1250 1250 fcache.setdefault(c.linkrev(), set()).add(c.path())
1251 1251
1252 1252 def filematcher(rev):
1253 1253 if not fcacheready[0]:
1254 1254 # Lazy initialization
1255 1255 fcacheready[0] = True
1256 1256 populate()
1257 1257 return scmutil.match(wctx, fcache.get(rev, []), default='path')
1258 1258
1259 1259 return filematcher
1260 1260
1261 1261 def _makegraphlogrevset(repo, pats, opts, revs):
1262 1262 """Return (expr, filematcher) where expr is a revset string built
1263 1263 from log options and file patterns or None. If --stat or --patch
1264 1264 are not passed filematcher is None. Otherwise it is a callable
1265 1265 taking a revision number and returning a match objects filtering
1266 1266 the files to be detailed when displaying the revision.
1267 1267 """
1268 1268 opt2revset = {
1269 1269 'no_merges': ('not merge()', None),
1270 1270 'only_merges': ('merge()', None),
1271 1271 '_ancestors': ('ancestors(%(val)s)', None),
1272 1272 '_fancestors': ('_firstancestors(%(val)s)', None),
1273 1273 '_descendants': ('descendants(%(val)s)', None),
1274 1274 '_fdescendants': ('_firstdescendants(%(val)s)', None),
1275 1275 '_matchfiles': ('_matchfiles(%(val)s)', None),
1276 1276 'date': ('date(%(val)r)', None),
1277 1277 'branch': ('branch(%(val)r)', ' or '),
1278 1278 '_patslog': ('filelog(%(val)r)', ' or '),
1279 1279 '_patsfollow': ('follow(%(val)r)', ' or '),
1280 1280 '_patsfollowfirst': ('_followfirst(%(val)r)', ' or '),
1281 1281 'keyword': ('keyword(%(val)r)', ' or '),
1282 1282 'prune': ('not (%(val)r or ancestors(%(val)r))', ' and '),
1283 1283 'user': ('user(%(val)r)', ' or '),
1284 1284 }
1285 1285
1286 1286 opts = dict(opts)
1287 1287 # follow or not follow?
1288 1288 follow = opts.get('follow') or opts.get('follow_first')
1289 1289 followfirst = opts.get('follow_first') and 1 or 0
1290 1290 # --follow with FILE behaviour depends on revs...
1291 1291 startrev = revs[0]
1292 1292 followdescendants = (len(revs) > 1 and revs[0] < revs[1]) and 1 or 0
1293 1293
1294 1294 # branch and only_branch are really aliases and must be handled at
1295 1295 # the same time
1296 1296 opts['branch'] = opts.get('branch', []) + opts.get('only_branch', [])
1297 1297 opts['branch'] = [repo.lookupbranch(b) for b in opts['branch']]
1298 1298 # pats/include/exclude are passed to match.match() directly in
1299 1299 # _matchfiles() revset but walkchangerevs() builds its matcher with
1300 1300 # scmutil.match(). The difference is input pats are globbed on
1301 1301 # platforms without shell expansion (windows).
1302 1302 pctx = repo[None]
1303 1303 match, pats = scmutil.matchandpats(pctx, pats, opts)
1304 1304 slowpath = match.anypats() or (match.files() and opts.get('removed'))
1305 1305 if not slowpath:
1306 1306 for f in match.files():
1307 1307 if follow and f not in pctx:
1308 1308 raise util.Abort(_('cannot follow file not in parent '
1309 1309 'revision: "%s"') % f)
1310 1310 filelog = repo.file(f)
1311 1311 if not len(filelog):
1312 1312 # A zero count may be a directory or deleted file, so
1313 1313 # try to find matching entries on the slow path.
1314 1314 if follow:
1315 1315 raise util.Abort(
1316 1316 _('cannot follow nonexistent file: "%s"') % f)
1317 1317 slowpath = True
1318 1318
1319 1319 # We decided to fall back to the slowpath because at least one
1320 1320 # of the paths was not a file. Check to see if at least one of them
1321 1321 # existed in history - in that case, we'll continue down the
1322 1322 # slowpath; otherwise, we can turn off the slowpath
1323 1323 if slowpath:
1324 1324 for path in match.files():
1325 1325 if path == '.' or path in repo.store:
1326 1326 break
1327 1327 else:
1328 1328 slowpath = False
1329 1329
1330 1330 if slowpath:
1331 1331 # See walkchangerevs() slow path.
1332 1332 #
1333 1333 if follow:
1334 1334 raise util.Abort(_('can only follow copies/renames for explicit '
1335 1335 'filenames'))
1336 1336 # pats/include/exclude cannot be represented as separate
1337 1337 # revset expressions as their filtering logic applies at file
1338 1338 # level. For instance "-I a -X a" matches a revision touching
1339 1339 # "a" and "b" while "file(a) and not file(b)" does
1340 1340 # not. Besides, filesets are evaluated against the working
1341 1341 # directory.
1342 1342 matchargs = ['r:', 'd:relpath']
1343 1343 for p in pats:
1344 1344 matchargs.append('p:' + p)
1345 1345 for p in opts.get('include', []):
1346 1346 matchargs.append('i:' + p)
1347 1347 for p in opts.get('exclude', []):
1348 1348 matchargs.append('x:' + p)
1349 1349 matchargs = ','.join(('%r' % p) for p in matchargs)
1350 1350 opts['_matchfiles'] = matchargs
1351 1351 else:
1352 1352 if follow:
1353 1353 fpats = ('_patsfollow', '_patsfollowfirst')
1354 1354 fnopats = (('_ancestors', '_fancestors'),
1355 1355 ('_descendants', '_fdescendants'))
1356 1356 if pats:
1357 1357 # follow() revset interprets its file argument as a
1358 1358 # manifest entry, so use match.files(), not pats.
1359 1359 opts[fpats[followfirst]] = list(match.files())
1360 1360 else:
1361 1361 opts[fnopats[followdescendants][followfirst]] = str(startrev)
1362 1362 else:
1363 1363 opts['_patslog'] = list(pats)
1364 1364
1365 1365 filematcher = None
1366 1366 if opts.get('patch') or opts.get('stat'):
1367 1367 if follow:
1368 1368 filematcher = _makegraphfilematcher(repo, pats, followfirst)
1369 1369 else:
1370 1370 filematcher = lambda rev: match
1371 1371
1372 1372 expr = []
1373 1373 for op, val in opts.iteritems():
1374 1374 if not val:
1375 1375 continue
1376 1376 if op not in opt2revset:
1377 1377 continue
1378 1378 revop, andor = opt2revset[op]
1379 1379 if '%(val)' not in revop:
1380 1380 expr.append(revop)
1381 1381 else:
1382 1382 if not isinstance(val, list):
1383 1383 e = revop % {'val': val}
1384 1384 else:
1385 1385 e = '(' + andor.join((revop % {'val': v}) for v in val) + ')'
1386 1386 expr.append(e)
1387 1387
1388 1388 if expr:
1389 1389 expr = '(' + ' and '.join(expr) + ')'
1390 1390 else:
1391 1391 expr = None
1392 1392 return expr, filematcher
1393 1393
1394 1394 def getgraphlogrevs(repo, pats, opts):
1395 1395 """Return (revs, expr, filematcher) where revs is an iterable of
1396 1396 revision numbers, expr is a revset string built from log options
1397 1397 and file patterns or None, and used to filter 'revs'. If --stat or
1398 1398 --patch are not passed filematcher is None. Otherwise it is a
1399 1399 callable taking a revision number and returning a match objects
1400 1400 filtering the files to be detailed when displaying the revision.
1401 1401 """
1402 1402 def increasingrevs(repo, revs, matcher):
1403 1403 # The sorted input rev sequence is chopped in sub-sequences
1404 1404 # which are sorted in ascending order and passed to the
1405 1405 # matcher. The filtered revs are sorted again as they were in
1406 1406 # the original sub-sequence. This achieve several things:
1407 1407 #
1408 1408 # - getlogrevs() now returns a generator which behaviour is
1409 1409 # adapted to log need. First results come fast, last ones
1410 1410 # are batched for performances.
1411 1411 #
1412 1412 # - revset matchers often operate faster on revision in
1413 1413 # changelog order, because most filters deal with the
1414 1414 # changelog.
1415 1415 #
1416 1416 # - revset matchers can reorder revisions. "A or B" typically
1417 1417 # returns returns the revision matching A then the revision
1418 1418 # matching B. We want to hide this internal implementation
1419 1419 # detail from the caller, and sorting the filtered revision
1420 1420 # again achieves this.
1421 1421 for i, window in increasingwindows(0, len(revs), windowsize=1):
1422 1422 orevs = revs[i:i + window]
1423 1423 nrevs = set(matcher(repo, sorted(orevs)))
1424 1424 for rev in orevs:
1425 1425 if rev in nrevs:
1426 1426 yield rev
1427 1427
1428 1428 if not len(repo):
1429 1429 return iter([]), None, None
1430 1430 # Default --rev value depends on --follow but --follow behaviour
1431 1431 # depends on revisions resolved from --rev...
1432 1432 follow = opts.get('follow') or opts.get('follow_first')
1433 1433 if opts.get('rev'):
1434 1434 revs = scmutil.revrange(repo, opts['rev'])
1435 1435 else:
1436 1436 if follow and len(repo) > 0:
1437 1437 revs = repo.revs('reverse(:.)')
1438 1438 else:
1439 1439 revs = list(repo.changelog)
1440 1440 revs.reverse()
1441 1441 if not revs:
1442 1442 return iter([]), None, None
1443 1443 expr, filematcher = _makegraphlogrevset(repo, pats, opts, revs)
1444 1444 if expr:
1445 1445 matcher = revset.match(repo.ui, expr)
1446 1446 revs = increasingrevs(repo, revs, matcher)
1447 1447 if not opts.get('hidden'):
1448 1448 # --hidden is still experimental and not worth a dedicated revset
1449 1449 # yet. Fortunately, filtering revision number is fast.
1450 1450 revs = (r for r in revs if r not in repo.hiddenrevs)
1451 1451 else:
1452 1452 revs = iter(revs)
1453 1453 return revs, expr, filematcher
1454 1454
1455 1455 def displaygraph(ui, dag, displayer, showparents, edgefn, getrenamed=None,
1456 1456 filematcher=None):
1457 1457 seen, state = [], graphmod.asciistate()
1458 1458 for rev, type, ctx, parents in dag:
1459 1459 char = 'o'
1460 1460 if ctx.node() in showparents:
1461 1461 char = '@'
1462 1462 elif ctx.obsolete():
1463 1463 char = 'x'
1464 1464 copies = None
1465 1465 if getrenamed and ctx.rev():
1466 1466 copies = []
1467 1467 for fn in ctx.files():
1468 1468 rename = getrenamed(fn, ctx.rev())
1469 1469 if rename:
1470 1470 copies.append((fn, rename[0]))
1471 1471 revmatchfn = None
1472 1472 if filematcher is not None:
1473 1473 revmatchfn = filematcher(ctx.rev())
1474 1474 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
1475 1475 lines = displayer.hunk.pop(rev).split('\n')
1476 1476 if not lines[-1]:
1477 1477 del lines[-1]
1478 1478 displayer.flush(rev)
1479 1479 edges = edgefn(type, char, lines, seen, rev, parents)
1480 1480 for type, char, lines, coldata in edges:
1481 1481 graphmod.ascii(ui, state, type, char, lines, coldata)
1482 1482 displayer.close()
1483 1483
1484 1484 def graphlog(ui, repo, *pats, **opts):
1485 1485 # Parameters are identical to log command ones
1486 1486 revs, expr, filematcher = getgraphlogrevs(repo, pats, opts)
1487 1487 revs = sorted(revs, reverse=1)
1488 1488 limit = loglimit(opts)
1489 1489 if limit is not None:
1490 1490 revs = revs[:limit]
1491 1491 revdag = graphmod.dagwalker(repo, revs)
1492 1492
1493 1493 getrenamed = None
1494 1494 if opts.get('copies'):
1495 1495 endrev = None
1496 1496 if opts.get('rev'):
1497 1497 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
1498 1498 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
1499 1499 displayer = show_changeset(ui, repo, opts, buffered=True)
1500 1500 showparents = [ctx.node() for ctx in repo[None].parents()]
1501 1501 displaygraph(ui, revdag, displayer, showparents,
1502 1502 graphmod.asciiedges, getrenamed, filematcher)
1503 1503
1504 1504 def checkunsupportedgraphflags(pats, opts):
1505 1505 for op in ["newest_first"]:
1506 1506 if op in opts and opts[op]:
1507 1507 raise util.Abort(_("-G/--graph option is incompatible with --%s")
1508 1508 % op.replace("_", "-"))
1509 1509
1510 1510 def graphrevs(repo, nodes, opts):
1511 1511 limit = loglimit(opts)
1512 1512 nodes.reverse()
1513 1513 if limit is not None:
1514 1514 nodes = nodes[:limit]
1515 1515 return graphmod.nodes(repo, nodes)
1516 1516
1517 1517 def add(ui, repo, match, dryrun, listsubrepos, prefix, explicitonly):
1518 1518 join = lambda f: os.path.join(prefix, f)
1519 1519 bad = []
1520 1520 oldbad = match.bad
1521 1521 match.bad = lambda x, y: bad.append(x) or oldbad(x, y)
1522 1522 names = []
1523 1523 wctx = repo[None]
1524 1524 cca = None
1525 1525 abort, warn = scmutil.checkportabilityalert(ui)
1526 1526 if abort or warn:
1527 1527 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
1528 1528 for f in repo.walk(match):
1529 1529 exact = match.exact(f)
1530 1530 if exact or not explicitonly and f not in repo.dirstate:
1531 1531 if cca:
1532 1532 cca(f)
1533 1533 names.append(f)
1534 1534 if ui.verbose or not exact:
1535 1535 ui.status(_('adding %s\n') % match.rel(join(f)))
1536 1536
1537 1537 for subpath in wctx.substate:
1538 1538 sub = wctx.sub(subpath)
1539 1539 try:
1540 1540 submatch = matchmod.narrowmatcher(subpath, match)
1541 1541 if listsubrepos:
1542 1542 bad.extend(sub.add(ui, submatch, dryrun, listsubrepos, prefix,
1543 1543 False))
1544 1544 else:
1545 1545 bad.extend(sub.add(ui, submatch, dryrun, listsubrepos, prefix,
1546 1546 True))
1547 1547 except error.LookupError:
1548 1548 ui.status(_("skipping missing subrepository: %s\n")
1549 1549 % join(subpath))
1550 1550
1551 1551 if not dryrun:
1552 1552 rejected = wctx.add(names, prefix)
1553 1553 bad.extend(f for f in rejected if f in match.files())
1554 1554 return bad
1555 1555
1556 1556 def forget(ui, repo, match, prefix, explicitonly):
1557 1557 join = lambda f: os.path.join(prefix, f)
1558 1558 bad = []
1559 1559 oldbad = match.bad
1560 1560 match.bad = lambda x, y: bad.append(x) or oldbad(x, y)
1561 1561 wctx = repo[None]
1562 1562 forgot = []
1563 1563 s = repo.status(match=match, clean=True)
1564 1564 forget = sorted(s[0] + s[1] + s[3] + s[6])
1565 1565 if explicitonly:
1566 1566 forget = [f for f in forget if match.exact(f)]
1567 1567
1568 1568 for subpath in wctx.substate:
1569 1569 sub = wctx.sub(subpath)
1570 1570 try:
1571 1571 submatch = matchmod.narrowmatcher(subpath, match)
1572 1572 subbad, subforgot = sub.forget(ui, submatch, prefix)
1573 1573 bad.extend([subpath + '/' + f for f in subbad])
1574 1574 forgot.extend([subpath + '/' + f for f in subforgot])
1575 1575 except error.LookupError:
1576 1576 ui.status(_("skipping missing subrepository: %s\n")
1577 1577 % join(subpath))
1578 1578
1579 1579 if not explicitonly:
1580 1580 for f in match.files():
1581 1581 if f not in repo.dirstate and not os.path.isdir(match.rel(join(f))):
1582 1582 if f not in forgot:
1583 1583 if os.path.exists(match.rel(join(f))):
1584 1584 ui.warn(_('not removing %s: '
1585 1585 'file is already untracked\n')
1586 1586 % match.rel(join(f)))
1587 1587 bad.append(f)
1588 1588
1589 1589 for f in forget:
1590 1590 if ui.verbose or not match.exact(f):
1591 1591 ui.status(_('removing %s\n') % match.rel(join(f)))
1592 1592
1593 1593 rejected = wctx.forget(forget, prefix)
1594 1594 bad.extend(f for f in rejected if f in match.files())
1595 1595 forgot.extend(forget)
1596 1596 return bad, forgot
1597 1597
1598 1598 def duplicatecopies(repo, rev, p1):
1599 1599 "Reproduce copies found in the source revision in the dirstate for grafts"
1600 1600 for dst, src in copies.pathcopies(repo[p1], repo[rev]).iteritems():
1601 1601 repo.dirstate.copy(src, dst)
1602 1602
1603 1603 def commit(ui, repo, commitfunc, pats, opts):
1604 1604 '''commit the specified files or all outstanding changes'''
1605 1605 date = opts.get('date')
1606 1606 if date:
1607 1607 opts['date'] = util.parsedate(date)
1608 1608 message = logmessage(ui, opts)
1609 1609
1610 1610 # extract addremove carefully -- this function can be called from a command
1611 1611 # that doesn't support addremove
1612 1612 if opts.get('addremove'):
1613 1613 scmutil.addremove(repo, pats, opts)
1614 1614
1615 1615 return commitfunc(ui, repo, message,
1616 1616 scmutil.match(repo[None], pats, opts), opts)
1617 1617
1618 1618 def amend(ui, repo, commitfunc, old, extra, pats, opts):
1619 1619 ui.note(_('amending changeset %s\n') % old)
1620 1620 base = old.p1()
1621 1621
1622 1622 wlock = lock = None
1623 1623 try:
1624 1624 wlock = repo.wlock()
1625 1625 lock = repo.lock()
1626 1626 tr = repo.transaction('amend')
1627 1627 try:
1628 1628 # See if we got a message from -m or -l, if not, open the editor
1629 1629 # with the message of the changeset to amend
1630 1630 message = logmessage(ui, opts)
1631 1631 # ensure logfile does not conflict with later enforcement of the
1632 1632 # message. potential logfile content has been processed by
1633 1633 # `logmessage` anyway.
1634 1634 opts.pop('logfile')
1635 1635 # First, do a regular commit to record all changes in the working
1636 1636 # directory (if there are any)
1637 1637 ui.callhooks = False
1638 1638 try:
1639 1639 opts['message'] = 'temporary amend commit for %s' % old
1640 1640 node = commit(ui, repo, commitfunc, pats, opts)
1641 1641 finally:
1642 1642 ui.callhooks = True
1643 1643 ctx = repo[node]
1644 1644
1645 1645 # Participating changesets:
1646 1646 #
1647 1647 # node/ctx o - new (intermediate) commit that contains changes
1648 1648 # | from working dir to go into amending commit
1649 1649 # | (or a workingctx if there were no changes)
1650 1650 # |
1651 1651 # old o - changeset to amend
1652 1652 # |
1653 1653 # base o - parent of amending changeset
1654 1654
1655 1655 # Update extra dict from amended commit (e.g. to preserve graft
1656 1656 # source)
1657 1657 extra.update(old.extra())
1658 1658
1659 1659 # Also update it from the intermediate commit or from the wctx
1660 1660 extra.update(ctx.extra())
1661 1661
1662 1662 files = set(old.files())
1663 1663
1664 1664 # Second, we use either the commit we just did, or if there were no
1665 1665 # changes the parent of the working directory as the version of the
1666 1666 # files in the final amend commit
1667 1667 if node:
1668 1668 ui.note(_('copying changeset %s to %s\n') % (ctx, base))
1669 1669
1670 1670 user = ctx.user()
1671 1671 date = ctx.date()
1672 1672 # Recompute copies (avoid recording a -> b -> a)
1673 1673 copied = copies.pathcopies(base, ctx)
1674 1674
1675 1675 # Prune files which were reverted by the updates: if old
1676 1676 # introduced file X and our intermediate commit, node,
1677 1677 # renamed that file, then those two files are the same and
1678 1678 # we can discard X from our list of files. Likewise if X
1679 1679 # was deleted, it's no longer relevant
1680 1680 files.update(ctx.files())
1681 1681
1682 1682 def samefile(f):
1683 1683 if f in ctx.manifest():
1684 1684 a = ctx.filectx(f)
1685 1685 if f in base.manifest():
1686 1686 b = base.filectx(f)
1687 1687 return (not a.cmp(b)
1688 1688 and a.flags() == b.flags())
1689 1689 else:
1690 1690 return False
1691 1691 else:
1692 1692 return f not in base.manifest()
1693 1693 files = [f for f in files if not samefile(f)]
1694 1694
1695 1695 def filectxfn(repo, ctx_, path):
1696 1696 try:
1697 1697 fctx = ctx[path]
1698 1698 flags = fctx.flags()
1699 1699 mctx = context.memfilectx(fctx.path(), fctx.data(),
1700 1700 islink='l' in flags,
1701 1701 isexec='x' in flags,
1702 1702 copied=copied.get(path))
1703 1703 return mctx
1704 1704 except KeyError:
1705 1705 raise IOError
1706 1706 else:
1707 1707 ui.note(_('copying changeset %s to %s\n') % (old, base))
1708 1708
1709 1709 # Use version of files as in the old cset
1710 1710 def filectxfn(repo, ctx_, path):
1711 1711 try:
1712 1712 return old.filectx(path)
1713 1713 except KeyError:
1714 1714 raise IOError
1715 1715
1716 1716 user = opts.get('user') or old.user()
1717 1717 date = opts.get('date') or old.date()
1718 editmsg = False
1718 1719 if not message:
1720 editmsg = True
1719 1721 message = old.description()
1720 1722
1721 1723 pureextra = extra.copy()
1722 1724 extra['amend_source'] = old.hex()
1723 1725
1724 1726 new = context.memctx(repo,
1725 1727 parents=[base.node(), nullid],
1726 1728 text=message,
1727 1729 files=files,
1728 1730 filectxfn=filectxfn,
1729 1731 user=user,
1730 1732 date=date,
1731 1733 extra=extra)
1734 if editmsg:
1732 1735 new._text = commitforceeditor(repo, new, [])
1733 1736
1734 1737 newdesc = changelog.stripdesc(new.description())
1735 1738 if ((not node)
1736 1739 and newdesc == old.description()
1737 1740 and user == old.user()
1738 1741 and date == old.date()
1739 1742 and pureextra == old.extra()):
1740 1743 # nothing changed. continuing here would create a new node
1741 1744 # anyway because of the amend_source noise.
1742 1745 #
1743 1746 # This not what we expect from amend.
1744 1747 return old.node()
1745 1748
1746 1749 ph = repo.ui.config('phases', 'new-commit', phases.draft)
1747 1750 try:
1748 1751 repo.ui.setconfig('phases', 'new-commit', old.phase())
1749 1752 newid = repo.commitctx(new)
1750 1753 finally:
1751 1754 repo.ui.setconfig('phases', 'new-commit', ph)
1752 1755 if newid != old.node():
1753 1756 # Reroute the working copy parent to the new changeset
1754 1757 repo.setparents(newid, nullid)
1755 1758
1756 1759 # Move bookmarks from old parent to amend commit
1757 1760 bms = repo.nodebookmarks(old.node())
1758 1761 if bms:
1759 1762 marks = repo._bookmarks
1760 1763 for bm in bms:
1761 1764 marks[bm] = newid
1762 1765 marks.write()
1763 1766 #commit the whole amend process
1764 1767 if obsolete._enabled and newid != old.node():
1765 1768 # mark the new changeset as successor of the rewritten one
1766 1769 new = repo[newid]
1767 1770 obs = [(old, (new,))]
1768 1771 if node:
1769 1772 obs.append((ctx, ()))
1770 1773
1771 1774 obsolete.createmarkers(repo, obs)
1772 1775 tr.close()
1773 1776 finally:
1774 1777 tr.release()
1775 1778 if (not obsolete._enabled) and newid != old.node():
1776 1779 # Strip the intermediate commit (if there was one) and the amended
1777 1780 # commit
1778 1781 if node:
1779 1782 ui.note(_('stripping intermediate changeset %s\n') % ctx)
1780 1783 ui.note(_('stripping amended changeset %s\n') % old)
1781 1784 repair.strip(ui, repo, old.node(), topic='amend-backup')
1782 1785 finally:
1783 1786 lockmod.release(wlock, lock)
1784 1787 return newid
1785 1788
1786 1789 def commiteditor(repo, ctx, subs):
1787 1790 if ctx.description():
1788 1791 return ctx.description()
1789 1792 return commitforceeditor(repo, ctx, subs)
1790 1793
1791 1794 def commitforceeditor(repo, ctx, subs):
1792 1795 edittext = []
1793 1796 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
1794 1797 if ctx.description():
1795 1798 edittext.append(ctx.description())
1796 1799 edittext.append("")
1797 1800 edittext.append("") # Empty line between message and comments.
1798 1801 edittext.append(_("HG: Enter commit message."
1799 1802 " Lines beginning with 'HG:' are removed."))
1800 1803 edittext.append(_("HG: Leave message empty to abort commit."))
1801 1804 edittext.append("HG: --")
1802 1805 edittext.append(_("HG: user: %s") % ctx.user())
1803 1806 if ctx.p2():
1804 1807 edittext.append(_("HG: branch merge"))
1805 1808 if ctx.branch():
1806 1809 edittext.append(_("HG: branch '%s'") % ctx.branch())
1807 1810 edittext.extend([_("HG: subrepo %s") % s for s in subs])
1808 1811 edittext.extend([_("HG: added %s") % f for f in added])
1809 1812 edittext.extend([_("HG: changed %s") % f for f in modified])
1810 1813 edittext.extend([_("HG: removed %s") % f for f in removed])
1811 1814 if not added and not modified and not removed:
1812 1815 edittext.append(_("HG: no files changed"))
1813 1816 edittext.append("")
1814 1817 # run editor in the repository root
1815 1818 olddir = os.getcwd()
1816 1819 os.chdir(repo.root)
1817 1820 text = repo.ui.edit("\n".join(edittext), ctx.user())
1818 1821 text = re.sub("(?m)^HG:.*(\n|$)", "", text)
1819 1822 os.chdir(olddir)
1820 1823
1821 1824 if not text.strip():
1822 1825 raise util.Abort(_("empty commit message"))
1823 1826
1824 1827 return text
1825 1828
1826 1829 def revert(ui, repo, ctx, parents, *pats, **opts):
1827 1830 parent, p2 = parents
1828 1831 node = ctx.node()
1829 1832
1830 1833 mf = ctx.manifest()
1831 1834 if node == parent:
1832 1835 pmf = mf
1833 1836 else:
1834 1837 pmf = None
1835 1838
1836 1839 # need all matching names in dirstate and manifest of target rev,
1837 1840 # so have to walk both. do not print errors if files exist in one
1838 1841 # but not other.
1839 1842
1840 1843 names = {}
1841 1844
1842 1845 wlock = repo.wlock()
1843 1846 try:
1844 1847 # walk dirstate.
1845 1848
1846 1849 m = scmutil.match(repo[None], pats, opts)
1847 1850 m.bad = lambda x, y: False
1848 1851 for abs in repo.walk(m):
1849 1852 names[abs] = m.rel(abs), m.exact(abs)
1850 1853
1851 1854 # walk target manifest.
1852 1855
1853 1856 def badfn(path, msg):
1854 1857 if path in names:
1855 1858 return
1856 1859 if path in ctx.substate:
1857 1860 return
1858 1861 path_ = path + '/'
1859 1862 for f in names:
1860 1863 if f.startswith(path_):
1861 1864 return
1862 1865 ui.warn("%s: %s\n" % (m.rel(path), msg))
1863 1866
1864 1867 m = scmutil.match(ctx, pats, opts)
1865 1868 m.bad = badfn
1866 1869 for abs in ctx.walk(m):
1867 1870 if abs not in names:
1868 1871 names[abs] = m.rel(abs), m.exact(abs)
1869 1872
1870 1873 # get the list of subrepos that must be reverted
1871 1874 targetsubs = [s for s in ctx.substate if m(s)]
1872 1875 m = scmutil.matchfiles(repo, names)
1873 1876 changes = repo.status(match=m)[:4]
1874 1877 modified, added, removed, deleted = map(set, changes)
1875 1878
1876 1879 # if f is a rename, also revert the source
1877 1880 cwd = repo.getcwd()
1878 1881 for f in added:
1879 1882 src = repo.dirstate.copied(f)
1880 1883 if src and src not in names and repo.dirstate[src] == 'r':
1881 1884 removed.add(src)
1882 1885 names[src] = (repo.pathto(src, cwd), True)
1883 1886
1884 1887 def removeforget(abs):
1885 1888 if repo.dirstate[abs] == 'a':
1886 1889 return _('forgetting %s\n')
1887 1890 return _('removing %s\n')
1888 1891
1889 1892 revert = ([], _('reverting %s\n'))
1890 1893 add = ([], _('adding %s\n'))
1891 1894 remove = ([], removeforget)
1892 1895 undelete = ([], _('undeleting %s\n'))
1893 1896
1894 1897 disptable = (
1895 1898 # dispatch table:
1896 1899 # file state
1897 1900 # action if in target manifest
1898 1901 # action if not in target manifest
1899 1902 # make backup if in target manifest
1900 1903 # make backup if not in target manifest
1901 1904 (modified, revert, remove, True, True),
1902 1905 (added, revert, remove, True, False),
1903 1906 (removed, undelete, None, False, False),
1904 1907 (deleted, revert, remove, False, False),
1905 1908 )
1906 1909
1907 1910 for abs, (rel, exact) in sorted(names.items()):
1908 1911 mfentry = mf.get(abs)
1909 1912 target = repo.wjoin(abs)
1910 1913 def handle(xlist, dobackup):
1911 1914 xlist[0].append(abs)
1912 1915 if (dobackup and not opts.get('no_backup') and
1913 1916 os.path.lexists(target)):
1914 1917 bakname = "%s.orig" % rel
1915 1918 ui.note(_('saving current version of %s as %s\n') %
1916 1919 (rel, bakname))
1917 1920 if not opts.get('dry_run'):
1918 1921 util.rename(target, bakname)
1919 1922 if ui.verbose or not exact:
1920 1923 msg = xlist[1]
1921 1924 if not isinstance(msg, basestring):
1922 1925 msg = msg(abs)
1923 1926 ui.status(msg % rel)
1924 1927 for table, hitlist, misslist, backuphit, backupmiss in disptable:
1925 1928 if abs not in table:
1926 1929 continue
1927 1930 # file has changed in dirstate
1928 1931 if mfentry:
1929 1932 handle(hitlist, backuphit)
1930 1933 elif misslist is not None:
1931 1934 handle(misslist, backupmiss)
1932 1935 break
1933 1936 else:
1934 1937 if abs not in repo.dirstate:
1935 1938 if mfentry:
1936 1939 handle(add, True)
1937 1940 elif exact:
1938 1941 ui.warn(_('file not managed: %s\n') % rel)
1939 1942 continue
1940 1943 # file has not changed in dirstate
1941 1944 if node == parent:
1942 1945 if exact:
1943 1946 ui.warn(_('no changes needed to %s\n') % rel)
1944 1947 continue
1945 1948 if pmf is None:
1946 1949 # only need parent manifest in this unlikely case,
1947 1950 # so do not read by default
1948 1951 pmf = repo[parent].manifest()
1949 1952 if abs in pmf and mfentry:
1950 1953 # if version of file is same in parent and target
1951 1954 # manifests, do nothing
1952 1955 if (pmf[abs] != mfentry or
1953 1956 pmf.flags(abs) != mf.flags(abs)):
1954 1957 handle(revert, False)
1955 1958 else:
1956 1959 handle(remove, False)
1957 1960
1958 1961 if not opts.get('dry_run'):
1959 1962 def checkout(f):
1960 1963 fc = ctx[f]
1961 1964 repo.wwrite(f, fc.data(), fc.flags())
1962 1965
1963 1966 audit_path = scmutil.pathauditor(repo.root)
1964 1967 for f in remove[0]:
1965 1968 if repo.dirstate[f] == 'a':
1966 1969 repo.dirstate.drop(f)
1967 1970 continue
1968 1971 audit_path(f)
1969 1972 try:
1970 1973 util.unlinkpath(repo.wjoin(f))
1971 1974 except OSError:
1972 1975 pass
1973 1976 repo.dirstate.remove(f)
1974 1977
1975 1978 normal = None
1976 1979 if node == parent:
1977 1980 # We're reverting to our parent. If possible, we'd like status
1978 1981 # to report the file as clean. We have to use normallookup for
1979 1982 # merges to avoid losing information about merged/dirty files.
1980 1983 if p2 != nullid:
1981 1984 normal = repo.dirstate.normallookup
1982 1985 else:
1983 1986 normal = repo.dirstate.normal
1984 1987 for f in revert[0]:
1985 1988 checkout(f)
1986 1989 if normal:
1987 1990 normal(f)
1988 1991
1989 1992 for f in add[0]:
1990 1993 checkout(f)
1991 1994 repo.dirstate.add(f)
1992 1995
1993 1996 normal = repo.dirstate.normallookup
1994 1997 if node == parent and p2 == nullid:
1995 1998 normal = repo.dirstate.normal
1996 1999 for f in undelete[0]:
1997 2000 checkout(f)
1998 2001 normal(f)
1999 2002
2000 2003 if targetsubs:
2001 2004 # Revert the subrepos on the revert list
2002 2005 for sub in targetsubs:
2003 2006 ctx.sub(sub).revert(ui, ctx.substate[sub], *pats, **opts)
2004 2007 finally:
2005 2008 wlock.release()
2006 2009
2007 2010 def command(table):
2008 2011 '''returns a function object bound to table which can be used as
2009 2012 a decorator for populating table as a command table'''
2010 2013
2011 2014 def cmd(name, options, synopsis=None):
2012 2015 def decorator(func):
2013 2016 if synopsis:
2014 2017 table[name] = func, options[:], synopsis
2015 2018 else:
2016 2019 table[name] = func, options[:]
2017 2020 return func
2018 2021 return decorator
2019 2022
2020 2023 return cmd
@@ -1,458 +1,460 b''
1 1 $ hg init
2 2
3 3 Setup:
4 4
5 5 $ echo a >> a
6 6 $ hg ci -Am 'base'
7 7 adding a
8 8
9 9 Refuse to amend public csets:
10 10
11 11 $ hg phase -r . -p
12 12 $ hg ci --amend
13 13 abort: cannot amend public changesets
14 14 [255]
15 15 $ hg phase -r . -f -d
16 16
17 17 $ echo a >> a
18 18 $ hg ci -Am 'base1'
19 19
20 20 Nothing to amend:
21 21
22 22 $ hg ci --amend
23 23 nothing changed
24 24 [1]
25 25
26 26 $ cat >> $HGRCPATH <<EOF
27 27 > [hooks]
28 28 > pretxncommit.foo = sh -c "echo \\"pretxncommit \$HG_NODE\\"; hg id -r \$HG_NODE"
29 29 > EOF
30 30
31 31 Amending changeset with changes in working dir:
32 (and check that --message does not trigger an editor)
32 33
33 34 $ echo a >> a
34 $ hg ci --amend -m 'amend base1'
35 $ HGEDITOR="\"sh\" \"`pwd`/editor.sh\"" hg commit --amend -m 'amend base1'
35 36 pretxncommit 43f1ba15f28a50abf0aae529cf8a16bfced7b149
36 37 43f1ba15f28a tip
37 38 saved backup bundle to $TESTTMP/.hg/strip-backup/489edb5b847d-amend-backup.hg (glob)
38 39 $ echo 'pretxncommit.foo = ' >> $HGRCPATH
39 40 $ hg diff -c .
40 41 diff -r ad120869acf0 -r 43f1ba15f28a a
41 42 --- a/a Thu Jan 01 00:00:00 1970 +0000
42 43 +++ b/a Thu Jan 01 00:00:00 1970 +0000
43 44 @@ -1,1 +1,3 @@
44 45 a
45 46 +a
46 47 +a
47 48 $ hg log
48 49 changeset: 1:43f1ba15f28a
49 50 tag: tip
50 51 user: test
51 52 date: Thu Jan 01 00:00:00 1970 +0000
52 53 summary: amend base1
53 54
54 55 changeset: 0:ad120869acf0
55 56 user: test
56 57 date: Thu Jan 01 00:00:00 1970 +0000
57 58 summary: base
58 59
59 60
60 61 Add new file:
61 62
62 63 $ echo b > b
63 64 $ hg ci --amend -Am 'amend base1 new file'
64 65 adding b
65 66 saved backup bundle to $TESTTMP/.hg/strip-backup/43f1ba15f28a-amend-backup.hg (glob)
66 67
67 68 Remove file that was added in amended commit:
68 69 (and test logfile option)
70 (and test that logfile option do not trigger an editor)
69 71
70 72 $ hg rm b
71 73 $ echo 'amend base1 remove new file' > ../logfile
72 $ hg ci --amend -l ../logfile
74 $ HGEDITOR="\"sh\" \"`pwd`/editor.sh\"" hg ci --amend --logfile ../logfile
73 75 saved backup bundle to $TESTTMP/.hg/strip-backup/b8e3cb2b3882-amend-backup.hg (glob)
74 76
75 77 $ hg cat b
76 78 b: no such file in rev 74609c7f506e
77 79 [1]
78 80
79 81 No changes, just a different message:
80 82
81 83 $ hg ci -v --amend -m 'no changes, new message'
82 84 amending changeset 74609c7f506e
83 85 copying changeset 74609c7f506e to ad120869acf0
84 86 a
85 87 stripping amended changeset 74609c7f506e
86 88 1 changesets found
87 89 saved backup bundle to $TESTTMP/.hg/strip-backup/74609c7f506e-amend-backup.hg (glob)
88 90 1 changesets found
89 91 adding branch
90 92 adding changesets
91 93 adding manifests
92 94 adding file changes
93 95 added 1 changesets with 1 changes to 1 files
94 96 committed changeset 1:1cd866679df8
95 97 $ hg diff -c .
96 98 diff -r ad120869acf0 -r 1cd866679df8 a
97 99 --- a/a Thu Jan 01 00:00:00 1970 +0000
98 100 +++ b/a Thu Jan 01 00:00:00 1970 +0000
99 101 @@ -1,1 +1,3 @@
100 102 a
101 103 +a
102 104 +a
103 105 $ hg log
104 106 changeset: 1:1cd866679df8
105 107 tag: tip
106 108 user: test
107 109 date: Thu Jan 01 00:00:00 1970 +0000
108 110 summary: no changes, new message
109 111
110 112 changeset: 0:ad120869acf0
111 113 user: test
112 114 date: Thu Jan 01 00:00:00 1970 +0000
113 115 summary: base
114 116
115 117
116 118 Disable default date on commit so when -d isn't given, the old date is preserved:
117 119
118 120 $ echo '[defaults]' >> $HGRCPATH
119 121 $ echo 'commit=' >> $HGRCPATH
120 122
121 123 Test -u/-d:
122 124
123 125 $ hg ci --amend -u foo -d '1 0'
124 126 saved backup bundle to $TESTTMP/.hg/strip-backup/1cd866679df8-amend-backup.hg (glob)
125 127 $ echo a >> a
126 128 $ hg ci --amend -u foo -d '1 0'
127 129 saved backup bundle to $TESTTMP/.hg/strip-backup/780e6f23e03d-amend-backup.hg (glob)
128 130 $ hg log -r .
129 131 changeset: 1:5f357c7560ab
130 132 tag: tip
131 133 user: foo
132 134 date: Thu Jan 01 00:00:01 1970 +0000
133 135 summary: no changes, new message
134 136
135 137
136 138 Open editor with old commit message if a message isn't given otherwise:
137 139
138 140 $ cat > editor.sh << '__EOF__'
139 141 > #!/bin/sh
140 142 > cat $1
141 143 > echo "another precious commit message" > "$1"
142 144 > __EOF__
143 145 $ HGEDITOR="\"sh\" \"`pwd`/editor.sh\"" hg commit --amend -v
144 146 amending changeset 5f357c7560ab
145 147 copying changeset 5f357c7560ab to ad120869acf0
146 148 no changes, new message
147 149
148 150
149 151 HG: Enter commit message. Lines beginning with 'HG:' are removed.
150 152 HG: Leave message empty to abort commit.
151 153 HG: --
152 154 HG: user: foo
153 155 HG: branch 'default'
154 156 HG: changed a
155 157 a
156 158 stripping amended changeset 5f357c7560ab
157 159 1 changesets found
158 160 saved backup bundle to $TESTTMP/.hg/strip-backup/5f357c7560ab-amend-backup.hg (glob)
159 161 1 changesets found
160 162 adding branch
161 163 adding changesets
162 164 adding manifests
163 165 adding file changes
164 166 added 1 changesets with 1 changes to 1 files
165 167 committed changeset 1:7ab3bf440b54
166 168
167 169 Same, but with changes in working dir (different code path):
168 170
169 171 $ echo a >> a
170 172 $ HGEDITOR="\"sh\" \"`pwd`/editor.sh\"" hg commit --amend -v
171 173 amending changeset 7ab3bf440b54
172 174 a
173 175 copying changeset a0ea9b1a4c8c to ad120869acf0
174 176 another precious commit message
175 177
176 178
177 179 HG: Enter commit message. Lines beginning with 'HG:' are removed.
178 180 HG: Leave message empty to abort commit.
179 181 HG: --
180 182 HG: user: foo
181 183 HG: branch 'default'
182 184 HG: changed a
183 185 a
184 186 stripping intermediate changeset a0ea9b1a4c8c
185 187 stripping amended changeset 7ab3bf440b54
186 188 2 changesets found
187 189 saved backup bundle to $TESTTMP/.hg/strip-backup/7ab3bf440b54-amend-backup.hg (glob)
188 190 1 changesets found
189 191 adding branch
190 192 adding changesets
191 193 adding manifests
192 194 adding file changes
193 195 added 1 changesets with 1 changes to 1 files
194 196 committed changeset 1:ea22a388757c
195 197
196 198 $ rm editor.sh
197 199 $ hg log -r .
198 200 changeset: 1:ea22a388757c
199 201 tag: tip
200 202 user: foo
201 203 date: Thu Jan 01 00:00:01 1970 +0000
202 204 summary: another precious commit message
203 205
204 206
205 207 Moving bookmarks, preserve active bookmark:
206 208
207 209 $ hg book book1
208 210 $ hg book book2
209 211 $ hg ci --amend -m 'move bookmarks'
210 212 saved backup bundle to $TESTTMP/.hg/strip-backup/ea22a388757c-amend-backup.hg (glob)
211 213 $ hg book
212 214 book1 1:6cec5aa930e2
213 215 * book2 1:6cec5aa930e2
214 216 $ echo a >> a
215 217 $ hg ci --amend -m 'move bookmarks'
216 218 saved backup bundle to $TESTTMP/.hg/strip-backup/6cec5aa930e2-amend-backup.hg (glob)
217 219 $ hg book
218 220 book1 1:48bb6e53a15f
219 221 * book2 1:48bb6e53a15f
220 222
221 223 $ echo '[defaults]' >> $HGRCPATH
222 224 $ echo "commit=-d '0 0'" >> $HGRCPATH
223 225
224 226 Moving branches:
225 227
226 228 $ hg branch foo
227 229 marked working directory as branch foo
228 230 (branches are permanent and global, did you want a bookmark?)
229 231 $ echo a >> a
230 232 $ hg ci -m 'branch foo'
231 233 $ hg branch default -f
232 234 marked working directory as branch default
233 235 (branches are permanent and global, did you want a bookmark?)
234 236 $ hg ci --amend -m 'back to default'
235 237 saved backup bundle to $TESTTMP/.hg/strip-backup/8ac881fbf49d-amend-backup.hg (glob)
236 238 $ hg branches
237 239 default 2:ce12b0b57d46
238 240
239 241 Close branch:
240 242
241 243 $ hg up -q 0
242 244 $ echo b >> b
243 245 $ hg branch foo
244 246 marked working directory as branch foo
245 247 (branches are permanent and global, did you want a bookmark?)
246 248 $ hg ci -Am 'fork'
247 249 adding b
248 250 $ echo b >> b
249 251 $ hg ci -mb
250 252 $ hg ci --amend --close-branch -m 'closing branch foo'
251 253 saved backup bundle to $TESTTMP/.hg/strip-backup/c962248fa264-amend-backup.hg (glob)
252 254
253 255 Same thing, different code path:
254 256
255 257 $ echo b >> b
256 258 $ hg ci -m 'reopen branch'
257 259 reopening closed branch head 4
258 260 $ echo b >> b
259 261 $ hg ci --amend --close-branch
260 262 saved backup bundle to $TESTTMP/.hg/strip-backup/027371728205-amend-backup.hg (glob)
261 263 $ hg branches
262 264 default 2:ce12b0b57d46
263 265
264 266 Refuse to amend merges:
265 267
266 268 $ hg up -q default
267 269 $ hg merge foo
268 270 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
269 271 (branch merge, don't forget to commit)
270 272 $ hg ci --amend
271 273 abort: cannot amend while merging
272 274 [255]
273 275 $ hg ci -m 'merge'
274 276 $ hg ci --amend
275 277 abort: cannot amend merge changesets
276 278 [255]
277 279
278 280 Follow copies/renames:
279 281
280 282 $ hg mv b c
281 283 $ hg ci -m 'b -> c'
282 284 $ hg mv c d
283 285 $ hg ci --amend -m 'b -> d'
284 286 saved backup bundle to $TESTTMP/.hg/strip-backup/b8c6eac7f12e-amend-backup.hg (glob)
285 287 $ hg st --rev '.^' --copies d
286 288 A d
287 289 b
288 290 $ hg cp d e
289 291 $ hg ci -m 'e = d'
290 292 $ hg cp e f
291 293 $ hg ci --amend -m 'f = d'
292 294 saved backup bundle to $TESTTMP/.hg/strip-backup/7f9761d65613-amend-backup.hg (glob)
293 295 $ hg st --rev '.^' --copies f
294 296 A f
295 297 d
296 298
297 299 $ mv f f.orig
298 300 $ hg rm -A f
299 301 $ hg ci -m removef
300 302 $ hg cp a f
301 303 $ mv f.orig f
302 304 $ hg ci --amend -m replacef
303 305 saved backup bundle to $TESTTMP/.hg/strip-backup/9e8c5f7e3d95-amend-backup.hg (glob)
304 306 $ hg st --change . --copies
305 307 $ hg log -r . --template "{file_copies}\n"
306 308
307 309
308 310 Move added file (issue3410):
309 311
310 312 $ echo g >> g
311 313 $ hg ci -Am g
312 314 adding g
313 315 $ hg mv g h
314 316 $ hg ci --amend
315 317 saved backup bundle to $TESTTMP/.hg/strip-backup/24aa8eacce2b-amend-backup.hg (glob)
316 318 $ hg st --change . --copies h
317 319 A h
318 320 $ hg log -r . --template "{file_copies}\n"
319 321
320 322
321 323 Can't rollback an amend:
322 324
323 325 $ hg rollback
324 326 no rollback information available
325 327 [1]
326 328
327 329 Preserve extra dict (issue3430):
328 330
329 331 $ hg branch a
330 332 marked working directory as branch a
331 333 (branches are permanent and global, did you want a bookmark?)
332 334 $ echo a >> a
333 335 $ hg ci -ma
334 336 $ hg ci --amend -m "a'"
335 337 saved backup bundle to $TESTTMP/.hg/strip-backup/3837aa2a2fdb-amend-backup.hg (glob)
336 338 $ hg log -r . --template "{branch}\n"
337 339 a
338 340 $ hg ci --amend -m "a''"
339 341 saved backup bundle to $TESTTMP/.hg/strip-backup/c05c06be7514-amend-backup.hg (glob)
340 342 $ hg log -r . --template "{branch}\n"
341 343 a
342 344
343 345 Also preserve other entries in the dict that are in the old commit,
344 346 first graft something so there's an additional entry:
345 347
346 348 $ hg up 0 -q
347 349 $ echo z > z
348 350 $ hg ci -Am 'fork'
349 351 adding z
350 352 created new head
351 353 $ hg up 11
352 354 5 files updated, 0 files merged, 1 files removed, 0 files unresolved
353 355 $ hg graft 12
354 356 grafting revision 12
355 357 $ hg ci --amend -m 'graft amend'
356 358 saved backup bundle to $TESTTMP/.hg/strip-backup/bd010aea3f39-amend-backup.hg (glob)
357 359 $ hg log -r . --debug | grep extra
358 360 extra: amend_source=bd010aea3f39f3fb2a2f884b9ccb0471cd77398e
359 361 extra: branch=a
360 362 extra: source=2647734878ef0236dda712fae9c1651cf694ea8a
361 363
362 364 Preserve phase
363 365
364 366 $ hg phase '.^::.'
365 367 11: draft
366 368 13: draft
367 369 $ hg phase --secret --force .
368 370 $ hg phase '.^::.'
369 371 11: draft
370 372 13: secret
371 373 $ hg commit --amend -m 'amend for phase' -q
372 374 $ hg phase '.^::.'
373 375 11: draft
374 376 13: secret
375 377
376 378 Test amend with obsolete
377 379 ---------------------------
378 380
379 381 Enable obsolete
380 382
381 383 $ cat > ${TESTTMP}/obs.py << EOF
382 384 > import mercurial.obsolete
383 385 > mercurial.obsolete._enabled = True
384 386 > EOF
385 387 $ echo '[extensions]' >> $HGRCPATH
386 388 $ echo "obs=${TESTTMP}/obs.py" >> $HGRCPATH
387 389
388 390
389 391 Amend with no files changes
390 392
391 393 $ hg id -n
392 394 13
393 395 $ hg ci --amend -m 'babar'
394 396 $ hg id -n
395 397 14
396 398 $ hg log -Gl 3 --style=compact
397 399 @ 14[tip]:11 b650e6ee8614 1970-01-01 00:00 +0000 test
398 400 | babar
399 401 |
400 402 | o 12:0 2647734878ef 1970-01-01 00:00 +0000 test
401 403 | | fork
402 404 | |
403 405 o | 11 3334b7925910 1970-01-01 00:00 +0000 test
404 406 | | a''
405 407 | |
406 408 $ hg log -Gl 4 --hidden --style=compact
407 409 @ 14[tip]:11 b650e6ee8614 1970-01-01 00:00 +0000 test
408 410 | babar
409 411 |
410 412 | x 13:11 68ff8ff97044 1970-01-01 00:00 +0000 test
411 413 |/ amend for phase
412 414 |
413 415 | o 12:0 2647734878ef 1970-01-01 00:00 +0000 test
414 416 | | fork
415 417 | |
416 418 o | 11 3334b7925910 1970-01-01 00:00 +0000 test
417 419 | | a''
418 420 | |
419 421
420 422 Amend with files changes
421 423
422 424 (note: the extra commit over 15 is a temporary junk I would be happy to get
423 425 ride of)
424 426
425 427 $ echo 'babar' >> a
426 428 $ hg commit --amend
427 429 $ hg log -Gl 6 --hidden --style=compact
428 430 @ 16[tip]:11 9f9e9bccf56c 1970-01-01 00:00 +0000 test
429 431 | babar
430 432 |
431 433 | x 15 90fef497c56f 1970-01-01 00:00 +0000 test
432 434 | | temporary amend commit for b650e6ee8614
433 435 | |
434 436 | x 14:11 b650e6ee8614 1970-01-01 00:00 +0000 test
435 437 |/ babar
436 438 |
437 439 | x 13:11 68ff8ff97044 1970-01-01 00:00 +0000 test
438 440 |/ amend for phase
439 441 |
440 442 | o 12:0 2647734878ef 1970-01-01 00:00 +0000 test
441 443 | | fork
442 444 | |
443 445 o | 11 3334b7925910 1970-01-01 00:00 +0000 test
444 446 | | a''
445 447 | |
446 448
447 449
448 450 Test that amend does not make it easy to create obsoletescence cycle
449 451 ---------------------------------------------------------------------
450 452
451 453
452 454 $ hg id -r 14
453 455 b650e6ee8614 (a)
454 456 $ hg revert -ar 14
455 457 reverting a
456 458 $ hg commit --amend
457 459 $ hg id
458 460 b99e5df575f7 (a) tip
General Comments 0
You need to be logged in to leave comments. Login now