##// END OF EJS Templates
graphlog: move comment and flag denoting revs might be unsorted...
Yuya Nishihara -
r24060:eb1c9700 default
parent child Browse files
Show More
@@ -1,2975 +1,2973 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 context, repair, graphmod, revset, phases, obsolete, pathutil
14 14 import changelog
15 15 import bookmarks
16 16 import encoding
17 17 import lock as lockmod
18 18
19 19 def parsealiases(cmd):
20 20 return cmd.lstrip("^").split("|")
21 21
22 22 def findpossible(cmd, table, strict=False):
23 23 """
24 24 Return cmd -> (aliases, command table entry)
25 25 for each matching command.
26 26 Return debug commands (or their aliases) only if no normal command matches.
27 27 """
28 28 choice = {}
29 29 debugchoice = {}
30 30
31 31 if cmd in table:
32 32 # short-circuit exact matches, "log" alias beats "^log|history"
33 33 keys = [cmd]
34 34 else:
35 35 keys = table.keys()
36 36
37 37 for e in keys:
38 38 aliases = parsealiases(e)
39 39 found = None
40 40 if cmd in aliases:
41 41 found = cmd
42 42 elif not strict:
43 43 for a in aliases:
44 44 if a.startswith(cmd):
45 45 found = a
46 46 break
47 47 if found is not None:
48 48 if aliases[0].startswith("debug") or found.startswith("debug"):
49 49 debugchoice[found] = (aliases, table[e])
50 50 else:
51 51 choice[found] = (aliases, table[e])
52 52
53 53 if not choice and debugchoice:
54 54 choice = debugchoice
55 55
56 56 return choice
57 57
58 58 def findcmd(cmd, table, strict=True):
59 59 """Return (aliases, command table entry) for command string."""
60 60 choice = findpossible(cmd, table, strict)
61 61
62 62 if cmd in choice:
63 63 return choice[cmd]
64 64
65 65 if len(choice) > 1:
66 66 clist = choice.keys()
67 67 clist.sort()
68 68 raise error.AmbiguousCommand(cmd, clist)
69 69
70 70 if choice:
71 71 return choice.values()[0]
72 72
73 73 raise error.UnknownCommand(cmd)
74 74
75 75 def findrepo(p):
76 76 while not os.path.isdir(os.path.join(p, ".hg")):
77 77 oldp, p = p, os.path.dirname(p)
78 78 if p == oldp:
79 79 return None
80 80
81 81 return p
82 82
83 83 def bailifchanged(repo):
84 84 if repo.dirstate.p2() != nullid:
85 85 raise util.Abort(_('outstanding uncommitted merge'))
86 86 modified, added, removed, deleted = repo.status()[:4]
87 87 if modified or added or removed or deleted:
88 88 raise util.Abort(_('uncommitted changes'))
89 89 ctx = repo[None]
90 90 for s in sorted(ctx.substate):
91 91 if ctx.sub(s).dirty():
92 92 raise util.Abort(_("uncommitted changes in subrepo %s") % s)
93 93
94 94 def logmessage(ui, opts):
95 95 """ get the log message according to -m and -l option """
96 96 message = opts.get('message')
97 97 logfile = opts.get('logfile')
98 98
99 99 if message and logfile:
100 100 raise util.Abort(_('options --message and --logfile are mutually '
101 101 'exclusive'))
102 102 if not message and logfile:
103 103 try:
104 104 if logfile == '-':
105 105 message = ui.fin.read()
106 106 else:
107 107 message = '\n'.join(util.readfile(logfile).splitlines())
108 108 except IOError, inst:
109 109 raise util.Abort(_("can't read commit message '%s': %s") %
110 110 (logfile, inst.strerror))
111 111 return message
112 112
113 113 def mergeeditform(ctxorbool, baseform):
114 114 """build appropriate editform from ctxorbool and baseform
115 115
116 116 'ctxorbool' is one of a ctx to be committed, or a bool whether
117 117 merging is committed.
118 118
119 119 This returns editform 'baseform' with '.merge' if merging is
120 120 committed, or one with '.normal' suffix otherwise.
121 121 """
122 122 if isinstance(ctxorbool, bool):
123 123 if ctxorbool:
124 124 return baseform + ".merge"
125 125 elif 1 < len(ctxorbool.parents()):
126 126 return baseform + ".merge"
127 127
128 128 return baseform + ".normal"
129 129
130 130 def getcommiteditor(edit=False, finishdesc=None, extramsg=None,
131 131 editform='', **opts):
132 132 """get appropriate commit message editor according to '--edit' option
133 133
134 134 'finishdesc' is a function to be called with edited commit message
135 135 (= 'description' of the new changeset) just after editing, but
136 136 before checking empty-ness. It should return actual text to be
137 137 stored into history. This allows to change description before
138 138 storing.
139 139
140 140 'extramsg' is a extra message to be shown in the editor instead of
141 141 'Leave message empty to abort commit' line. 'HG: ' prefix and EOL
142 142 is automatically added.
143 143
144 144 'editform' is a dot-separated list of names, to distinguish
145 145 the purpose of commit text editing.
146 146
147 147 'getcommiteditor' returns 'commitforceeditor' regardless of
148 148 'edit', if one of 'finishdesc' or 'extramsg' is specified, because
149 149 they are specific for usage in MQ.
150 150 """
151 151 if edit or finishdesc or extramsg:
152 152 return lambda r, c, s: commitforceeditor(r, c, s,
153 153 finishdesc=finishdesc,
154 154 extramsg=extramsg,
155 155 editform=editform)
156 156 elif editform:
157 157 return lambda r, c, s: commiteditor(r, c, s, editform=editform)
158 158 else:
159 159 return commiteditor
160 160
161 161 def loglimit(opts):
162 162 """get the log limit according to option -l/--limit"""
163 163 limit = opts.get('limit')
164 164 if limit:
165 165 try:
166 166 limit = int(limit)
167 167 except ValueError:
168 168 raise util.Abort(_('limit must be a positive integer'))
169 169 if limit <= 0:
170 170 raise util.Abort(_('limit must be positive'))
171 171 else:
172 172 limit = None
173 173 return limit
174 174
175 175 def makefilename(repo, pat, node, desc=None,
176 176 total=None, seqno=None, revwidth=None, pathname=None):
177 177 node_expander = {
178 178 'H': lambda: hex(node),
179 179 'R': lambda: str(repo.changelog.rev(node)),
180 180 'h': lambda: short(node),
181 181 'm': lambda: re.sub('[^\w]', '_', str(desc))
182 182 }
183 183 expander = {
184 184 '%': lambda: '%',
185 185 'b': lambda: os.path.basename(repo.root),
186 186 }
187 187
188 188 try:
189 189 if node:
190 190 expander.update(node_expander)
191 191 if node:
192 192 expander['r'] = (lambda:
193 193 str(repo.changelog.rev(node)).zfill(revwidth or 0))
194 194 if total is not None:
195 195 expander['N'] = lambda: str(total)
196 196 if seqno is not None:
197 197 expander['n'] = lambda: str(seqno)
198 198 if total is not None and seqno is not None:
199 199 expander['n'] = lambda: str(seqno).zfill(len(str(total)))
200 200 if pathname is not None:
201 201 expander['s'] = lambda: os.path.basename(pathname)
202 202 expander['d'] = lambda: os.path.dirname(pathname) or '.'
203 203 expander['p'] = lambda: pathname
204 204
205 205 newname = []
206 206 patlen = len(pat)
207 207 i = 0
208 208 while i < patlen:
209 209 c = pat[i]
210 210 if c == '%':
211 211 i += 1
212 212 c = pat[i]
213 213 c = expander[c]()
214 214 newname.append(c)
215 215 i += 1
216 216 return ''.join(newname)
217 217 except KeyError, inst:
218 218 raise util.Abort(_("invalid format spec '%%%s' in output filename") %
219 219 inst.args[0])
220 220
221 221 def makefileobj(repo, pat, node=None, desc=None, total=None,
222 222 seqno=None, revwidth=None, mode='wb', modemap=None,
223 223 pathname=None):
224 224
225 225 writable = mode not in ('r', 'rb')
226 226
227 227 if not pat or pat == '-':
228 228 fp = writable and repo.ui.fout or repo.ui.fin
229 229 if util.safehasattr(fp, 'fileno'):
230 230 return os.fdopen(os.dup(fp.fileno()), mode)
231 231 else:
232 232 # if this fp can't be duped properly, return
233 233 # a dummy object that can be closed
234 234 class wrappedfileobj(object):
235 235 noop = lambda x: None
236 236 def __init__(self, f):
237 237 self.f = f
238 238 def __getattr__(self, attr):
239 239 if attr == 'close':
240 240 return self.noop
241 241 else:
242 242 return getattr(self.f, attr)
243 243
244 244 return wrappedfileobj(fp)
245 245 if util.safehasattr(pat, 'write') and writable:
246 246 return pat
247 247 if util.safehasattr(pat, 'read') and 'r' in mode:
248 248 return pat
249 249 fn = makefilename(repo, pat, node, desc, total, seqno, revwidth, pathname)
250 250 if modemap is not None:
251 251 mode = modemap.get(fn, mode)
252 252 if mode == 'wb':
253 253 modemap[fn] = 'ab'
254 254 return open(fn, mode)
255 255
256 256 def openrevlog(repo, cmd, file_, opts):
257 257 """opens the changelog, manifest, a filelog or a given revlog"""
258 258 cl = opts['changelog']
259 259 mf = opts['manifest']
260 260 msg = None
261 261 if cl and mf:
262 262 msg = _('cannot specify --changelog and --manifest at the same time')
263 263 elif cl or mf:
264 264 if file_:
265 265 msg = _('cannot specify filename with --changelog or --manifest')
266 266 elif not repo:
267 267 msg = _('cannot specify --changelog or --manifest '
268 268 'without a repository')
269 269 if msg:
270 270 raise util.Abort(msg)
271 271
272 272 r = None
273 273 if repo:
274 274 if cl:
275 275 r = repo.unfiltered().changelog
276 276 elif mf:
277 277 r = repo.manifest
278 278 elif file_:
279 279 filelog = repo.file(file_)
280 280 if len(filelog):
281 281 r = filelog
282 282 if not r:
283 283 if not file_:
284 284 raise error.CommandError(cmd, _('invalid arguments'))
285 285 if not os.path.isfile(file_):
286 286 raise util.Abort(_("revlog '%s' not found") % file_)
287 287 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False),
288 288 file_[:-2] + ".i")
289 289 return r
290 290
291 291 def copy(ui, repo, pats, opts, rename=False):
292 292 # called with the repo lock held
293 293 #
294 294 # hgsep => pathname that uses "/" to separate directories
295 295 # ossep => pathname that uses os.sep to separate directories
296 296 cwd = repo.getcwd()
297 297 targets = {}
298 298 after = opts.get("after")
299 299 dryrun = opts.get("dry_run")
300 300 wctx = repo[None]
301 301
302 302 def walkpat(pat):
303 303 srcs = []
304 304 badstates = after and '?' or '?r'
305 305 m = scmutil.match(repo[None], [pat], opts, globbed=True)
306 306 for abs in repo.walk(m):
307 307 state = repo.dirstate[abs]
308 308 rel = m.rel(abs)
309 309 exact = m.exact(abs)
310 310 if state in badstates:
311 311 if exact and state == '?':
312 312 ui.warn(_('%s: not copying - file is not managed\n') % rel)
313 313 if exact and state == 'r':
314 314 ui.warn(_('%s: not copying - file has been marked for'
315 315 ' remove\n') % rel)
316 316 continue
317 317 # abs: hgsep
318 318 # rel: ossep
319 319 srcs.append((abs, rel, exact))
320 320 return srcs
321 321
322 322 # abssrc: hgsep
323 323 # relsrc: ossep
324 324 # otarget: ossep
325 325 def copyfile(abssrc, relsrc, otarget, exact):
326 326 abstarget = pathutil.canonpath(repo.root, cwd, otarget)
327 327 if '/' in abstarget:
328 328 # We cannot normalize abstarget itself, this would prevent
329 329 # case only renames, like a => A.
330 330 abspath, absname = abstarget.rsplit('/', 1)
331 331 abstarget = repo.dirstate.normalize(abspath) + '/' + absname
332 332 reltarget = repo.pathto(abstarget, cwd)
333 333 target = repo.wjoin(abstarget)
334 334 src = repo.wjoin(abssrc)
335 335 state = repo.dirstate[abstarget]
336 336
337 337 scmutil.checkportable(ui, abstarget)
338 338
339 339 # check for collisions
340 340 prevsrc = targets.get(abstarget)
341 341 if prevsrc is not None:
342 342 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
343 343 (reltarget, repo.pathto(abssrc, cwd),
344 344 repo.pathto(prevsrc, cwd)))
345 345 return
346 346
347 347 # check for overwrites
348 348 exists = os.path.lexists(target)
349 349 samefile = False
350 350 if exists and abssrc != abstarget:
351 351 if (repo.dirstate.normalize(abssrc) ==
352 352 repo.dirstate.normalize(abstarget)):
353 353 if not rename:
354 354 ui.warn(_("%s: can't copy - same file\n") % reltarget)
355 355 return
356 356 exists = False
357 357 samefile = True
358 358
359 359 if not after and exists or after and state in 'mn':
360 360 if not opts['force']:
361 361 ui.warn(_('%s: not overwriting - file exists\n') %
362 362 reltarget)
363 363 return
364 364
365 365 if after:
366 366 if not exists:
367 367 if rename:
368 368 ui.warn(_('%s: not recording move - %s does not exist\n') %
369 369 (relsrc, reltarget))
370 370 else:
371 371 ui.warn(_('%s: not recording copy - %s does not exist\n') %
372 372 (relsrc, reltarget))
373 373 return
374 374 elif not dryrun:
375 375 try:
376 376 if exists:
377 377 os.unlink(target)
378 378 targetdir = os.path.dirname(target) or '.'
379 379 if not os.path.isdir(targetdir):
380 380 os.makedirs(targetdir)
381 381 if samefile:
382 382 tmp = target + "~hgrename"
383 383 os.rename(src, tmp)
384 384 os.rename(tmp, target)
385 385 else:
386 386 util.copyfile(src, target)
387 387 srcexists = True
388 388 except IOError, inst:
389 389 if inst.errno == errno.ENOENT:
390 390 ui.warn(_('%s: deleted in working copy\n') % relsrc)
391 391 srcexists = False
392 392 else:
393 393 ui.warn(_('%s: cannot copy - %s\n') %
394 394 (relsrc, inst.strerror))
395 395 return True # report a failure
396 396
397 397 if ui.verbose or not exact:
398 398 if rename:
399 399 ui.status(_('moving %s to %s\n') % (relsrc, reltarget))
400 400 else:
401 401 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
402 402
403 403 targets[abstarget] = abssrc
404 404
405 405 # fix up dirstate
406 406 scmutil.dirstatecopy(ui, repo, wctx, abssrc, abstarget,
407 407 dryrun=dryrun, cwd=cwd)
408 408 if rename and not dryrun:
409 409 if not after and srcexists and not samefile:
410 410 util.unlinkpath(repo.wjoin(abssrc))
411 411 wctx.forget([abssrc])
412 412
413 413 # pat: ossep
414 414 # dest ossep
415 415 # srcs: list of (hgsep, hgsep, ossep, bool)
416 416 # return: function that takes hgsep and returns ossep
417 417 def targetpathfn(pat, dest, srcs):
418 418 if os.path.isdir(pat):
419 419 abspfx = pathutil.canonpath(repo.root, cwd, pat)
420 420 abspfx = util.localpath(abspfx)
421 421 if destdirexists:
422 422 striplen = len(os.path.split(abspfx)[0])
423 423 else:
424 424 striplen = len(abspfx)
425 425 if striplen:
426 426 striplen += len(os.sep)
427 427 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
428 428 elif destdirexists:
429 429 res = lambda p: os.path.join(dest,
430 430 os.path.basename(util.localpath(p)))
431 431 else:
432 432 res = lambda p: dest
433 433 return res
434 434
435 435 # pat: ossep
436 436 # dest ossep
437 437 # srcs: list of (hgsep, hgsep, ossep, bool)
438 438 # return: function that takes hgsep and returns ossep
439 439 def targetpathafterfn(pat, dest, srcs):
440 440 if matchmod.patkind(pat):
441 441 # a mercurial pattern
442 442 res = lambda p: os.path.join(dest,
443 443 os.path.basename(util.localpath(p)))
444 444 else:
445 445 abspfx = pathutil.canonpath(repo.root, cwd, pat)
446 446 if len(abspfx) < len(srcs[0][0]):
447 447 # A directory. Either the target path contains the last
448 448 # component of the source path or it does not.
449 449 def evalpath(striplen):
450 450 score = 0
451 451 for s in srcs:
452 452 t = os.path.join(dest, util.localpath(s[0])[striplen:])
453 453 if os.path.lexists(t):
454 454 score += 1
455 455 return score
456 456
457 457 abspfx = util.localpath(abspfx)
458 458 striplen = len(abspfx)
459 459 if striplen:
460 460 striplen += len(os.sep)
461 461 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
462 462 score = evalpath(striplen)
463 463 striplen1 = len(os.path.split(abspfx)[0])
464 464 if striplen1:
465 465 striplen1 += len(os.sep)
466 466 if evalpath(striplen1) > score:
467 467 striplen = striplen1
468 468 res = lambda p: os.path.join(dest,
469 469 util.localpath(p)[striplen:])
470 470 else:
471 471 # a file
472 472 if destdirexists:
473 473 res = lambda p: os.path.join(dest,
474 474 os.path.basename(util.localpath(p)))
475 475 else:
476 476 res = lambda p: dest
477 477 return res
478 478
479 479
480 480 pats = scmutil.expandpats(pats)
481 481 if not pats:
482 482 raise util.Abort(_('no source or destination specified'))
483 483 if len(pats) == 1:
484 484 raise util.Abort(_('no destination specified'))
485 485 dest = pats.pop()
486 486 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
487 487 if not destdirexists:
488 488 if len(pats) > 1 or matchmod.patkind(pats[0]):
489 489 raise util.Abort(_('with multiple sources, destination must be an '
490 490 'existing directory'))
491 491 if util.endswithsep(dest):
492 492 raise util.Abort(_('destination %s is not a directory') % dest)
493 493
494 494 tfn = targetpathfn
495 495 if after:
496 496 tfn = targetpathafterfn
497 497 copylist = []
498 498 for pat in pats:
499 499 srcs = walkpat(pat)
500 500 if not srcs:
501 501 continue
502 502 copylist.append((tfn(pat, dest, srcs), srcs))
503 503 if not copylist:
504 504 raise util.Abort(_('no files to copy'))
505 505
506 506 errors = 0
507 507 for targetpath, srcs in copylist:
508 508 for abssrc, relsrc, exact in srcs:
509 509 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
510 510 errors += 1
511 511
512 512 if errors:
513 513 ui.warn(_('(consider using --after)\n'))
514 514
515 515 return errors != 0
516 516
517 517 def service(opts, parentfn=None, initfn=None, runfn=None, logfile=None,
518 518 runargs=None, appendpid=False):
519 519 '''Run a command as a service.'''
520 520
521 521 def writepid(pid):
522 522 if opts['pid_file']:
523 523 mode = appendpid and 'a' or 'w'
524 524 fp = open(opts['pid_file'], mode)
525 525 fp.write(str(pid) + '\n')
526 526 fp.close()
527 527
528 528 if opts['daemon'] and not opts['daemon_pipefds']:
529 529 # Signal child process startup with file removal
530 530 lockfd, lockpath = tempfile.mkstemp(prefix='hg-service-')
531 531 os.close(lockfd)
532 532 try:
533 533 if not runargs:
534 534 runargs = util.hgcmd() + sys.argv[1:]
535 535 runargs.append('--daemon-pipefds=%s' % lockpath)
536 536 # Don't pass --cwd to the child process, because we've already
537 537 # changed directory.
538 538 for i in xrange(1, len(runargs)):
539 539 if runargs[i].startswith('--cwd='):
540 540 del runargs[i]
541 541 break
542 542 elif runargs[i].startswith('--cwd'):
543 543 del runargs[i:i + 2]
544 544 break
545 545 def condfn():
546 546 return not os.path.exists(lockpath)
547 547 pid = util.rundetached(runargs, condfn)
548 548 if pid < 0:
549 549 raise util.Abort(_('child process failed to start'))
550 550 writepid(pid)
551 551 finally:
552 552 try:
553 553 os.unlink(lockpath)
554 554 except OSError, e:
555 555 if e.errno != errno.ENOENT:
556 556 raise
557 557 if parentfn:
558 558 return parentfn(pid)
559 559 else:
560 560 return
561 561
562 562 if initfn:
563 563 initfn()
564 564
565 565 if not opts['daemon']:
566 566 writepid(os.getpid())
567 567
568 568 if opts['daemon_pipefds']:
569 569 lockpath = opts['daemon_pipefds']
570 570 try:
571 571 os.setsid()
572 572 except AttributeError:
573 573 pass
574 574 os.unlink(lockpath)
575 575 util.hidewindow()
576 576 sys.stdout.flush()
577 577 sys.stderr.flush()
578 578
579 579 nullfd = os.open(os.devnull, os.O_RDWR)
580 580 logfilefd = nullfd
581 581 if logfile:
582 582 logfilefd = os.open(logfile, os.O_RDWR | os.O_CREAT | os.O_APPEND)
583 583 os.dup2(nullfd, 0)
584 584 os.dup2(logfilefd, 1)
585 585 os.dup2(logfilefd, 2)
586 586 if nullfd not in (0, 1, 2):
587 587 os.close(nullfd)
588 588 if logfile and logfilefd not in (0, 1, 2):
589 589 os.close(logfilefd)
590 590
591 591 if runfn:
592 592 return runfn()
593 593
594 594 def tryimportone(ui, repo, hunk, parents, opts, msgs, updatefunc):
595 595 """Utility function used by commands.import to import a single patch
596 596
597 597 This function is explicitly defined here to help the evolve extension to
598 598 wrap this part of the import logic.
599 599
600 600 The API is currently a bit ugly because it a simple code translation from
601 601 the import command. Feel free to make it better.
602 602
603 603 :hunk: a patch (as a binary string)
604 604 :parents: nodes that will be parent of the created commit
605 605 :opts: the full dict of option passed to the import command
606 606 :msgs: list to save commit message to.
607 607 (used in case we need to save it when failing)
608 608 :updatefunc: a function that update a repo to a given node
609 609 updatefunc(<repo>, <node>)
610 610 """
611 611 tmpname, message, user, date, branch, nodeid, p1, p2 = \
612 612 patch.extract(ui, hunk)
613 613
614 614 update = not opts.get('bypass')
615 615 strip = opts["strip"]
616 616 sim = float(opts.get('similarity') or 0)
617 617 if not tmpname:
618 618 return (None, None, False)
619 619 msg = _('applied to working directory')
620 620
621 621 rejects = False
622 622
623 623 try:
624 624 cmdline_message = logmessage(ui, opts)
625 625 if cmdline_message:
626 626 # pickup the cmdline msg
627 627 message = cmdline_message
628 628 elif message:
629 629 # pickup the patch msg
630 630 message = message.strip()
631 631 else:
632 632 # launch the editor
633 633 message = None
634 634 ui.debug('message:\n%s\n' % message)
635 635
636 636 if len(parents) == 1:
637 637 parents.append(repo[nullid])
638 638 if opts.get('exact'):
639 639 if not nodeid or not p1:
640 640 raise util.Abort(_('not a Mercurial patch'))
641 641 p1 = repo[p1]
642 642 p2 = repo[p2 or nullid]
643 643 elif p2:
644 644 try:
645 645 p1 = repo[p1]
646 646 p2 = repo[p2]
647 647 # Without any options, consider p2 only if the
648 648 # patch is being applied on top of the recorded
649 649 # first parent.
650 650 if p1 != parents[0]:
651 651 p1 = parents[0]
652 652 p2 = repo[nullid]
653 653 except error.RepoError:
654 654 p1, p2 = parents
655 655 if p2.node() == nullid:
656 656 ui.warn(_("warning: import the patch as a normal revision\n"
657 657 "(use --exact to import the patch as a merge)\n"))
658 658 else:
659 659 p1, p2 = parents
660 660
661 661 n = None
662 662 if update:
663 663 repo.dirstate.beginparentchange()
664 664 if p1 != parents[0]:
665 665 updatefunc(repo, p1.node())
666 666 if p2 != parents[1]:
667 667 repo.setparents(p1.node(), p2.node())
668 668
669 669 if opts.get('exact') or opts.get('import_branch'):
670 670 repo.dirstate.setbranch(branch or 'default')
671 671
672 672 partial = opts.get('partial', False)
673 673 files = set()
674 674 try:
675 675 patch.patch(ui, repo, tmpname, strip=strip, files=files,
676 676 eolmode=None, similarity=sim / 100.0)
677 677 except patch.PatchError, e:
678 678 if not partial:
679 679 raise util.Abort(str(e))
680 680 if partial:
681 681 rejects = True
682 682
683 683 files = list(files)
684 684 if opts.get('no_commit'):
685 685 if message:
686 686 msgs.append(message)
687 687 else:
688 688 if opts.get('exact') or p2:
689 689 # If you got here, you either use --force and know what
690 690 # you are doing or used --exact or a merge patch while
691 691 # being updated to its first parent.
692 692 m = None
693 693 else:
694 694 m = scmutil.matchfiles(repo, files or [])
695 695 editform = mergeeditform(repo[None], 'import.normal')
696 696 if opts.get('exact'):
697 697 editor = None
698 698 else:
699 699 editor = getcommiteditor(editform=editform, **opts)
700 700 n = repo.commit(message, opts.get('user') or user,
701 701 opts.get('date') or date, match=m,
702 702 editor=editor, force=partial)
703 703 repo.dirstate.endparentchange()
704 704 else:
705 705 if opts.get('exact') or opts.get('import_branch'):
706 706 branch = branch or 'default'
707 707 else:
708 708 branch = p1.branch()
709 709 store = patch.filestore()
710 710 try:
711 711 files = set()
712 712 try:
713 713 patch.patchrepo(ui, repo, p1, store, tmpname, strip,
714 714 files, eolmode=None)
715 715 except patch.PatchError, e:
716 716 raise util.Abort(str(e))
717 717 if opts.get('exact'):
718 718 editor = None
719 719 else:
720 720 editor = getcommiteditor(editform='import.bypass')
721 721 memctx = context.makememctx(repo, (p1.node(), p2.node()),
722 722 message,
723 723 opts.get('user') or user,
724 724 opts.get('date') or date,
725 725 branch, files, store,
726 726 editor=editor)
727 727 n = memctx.commit()
728 728 finally:
729 729 store.close()
730 730 if opts.get('exact') and opts.get('no_commit'):
731 731 # --exact with --no-commit is still useful in that it does merge
732 732 # and branch bits
733 733 ui.warn(_("warning: can't check exact import with --no-commit\n"))
734 734 elif opts.get('exact') and hex(n) != nodeid:
735 735 raise util.Abort(_('patch is damaged or loses information'))
736 736 if n:
737 737 # i18n: refers to a short changeset id
738 738 msg = _('created %s') % short(n)
739 739 return (msg, n, rejects)
740 740 finally:
741 741 os.unlink(tmpname)
742 742
743 743 def export(repo, revs, template='hg-%h.patch', fp=None, switch_parent=False,
744 744 opts=None):
745 745 '''export changesets as hg patches.'''
746 746
747 747 total = len(revs)
748 748 revwidth = max([len(str(rev)) for rev in revs])
749 749 filemode = {}
750 750
751 751 def single(rev, seqno, fp):
752 752 ctx = repo[rev]
753 753 node = ctx.node()
754 754 parents = [p.node() for p in ctx.parents() if p]
755 755 branch = ctx.branch()
756 756 if switch_parent:
757 757 parents.reverse()
758 758 prev = (parents and parents[0]) or nullid
759 759
760 760 shouldclose = False
761 761 if not fp and len(template) > 0:
762 762 desc_lines = ctx.description().rstrip().split('\n')
763 763 desc = desc_lines[0] #Commit always has a first line.
764 764 fp = makefileobj(repo, template, node, desc=desc, total=total,
765 765 seqno=seqno, revwidth=revwidth, mode='wb',
766 766 modemap=filemode)
767 767 if fp != template:
768 768 shouldclose = True
769 769 if fp and fp != sys.stdout and util.safehasattr(fp, 'name'):
770 770 repo.ui.note("%s\n" % fp.name)
771 771
772 772 if not fp:
773 773 write = repo.ui.write
774 774 else:
775 775 def write(s, **kw):
776 776 fp.write(s)
777 777
778 778
779 779 write("# HG changeset patch\n")
780 780 write("# User %s\n" % ctx.user())
781 781 write("# Date %d %d\n" % ctx.date())
782 782 write("# %s\n" % util.datestr(ctx.date()))
783 783 if branch and branch != 'default':
784 784 write("# Branch %s\n" % branch)
785 785 write("# Node ID %s\n" % hex(node))
786 786 write("# Parent %s\n" % hex(prev))
787 787 if len(parents) > 1:
788 788 write("# Parent %s\n" % hex(parents[1]))
789 789 write(ctx.description().rstrip())
790 790 write("\n\n")
791 791
792 792 for chunk, label in patch.diffui(repo, prev, node, opts=opts):
793 793 write(chunk, label=label)
794 794
795 795 if shouldclose:
796 796 fp.close()
797 797
798 798 for seqno, rev in enumerate(revs):
799 799 single(rev, seqno + 1, fp)
800 800
801 801 def diffordiffstat(ui, repo, diffopts, node1, node2, match,
802 802 changes=None, stat=False, fp=None, prefix='',
803 803 listsubrepos=False):
804 804 '''show diff or diffstat.'''
805 805 if fp is None:
806 806 write = ui.write
807 807 else:
808 808 def write(s, **kw):
809 809 fp.write(s)
810 810
811 811 if stat:
812 812 diffopts = diffopts.copy(context=0)
813 813 width = 80
814 814 if not ui.plain():
815 815 width = ui.termwidth()
816 816 chunks = patch.diff(repo, node1, node2, match, changes, diffopts,
817 817 prefix=prefix)
818 818 for chunk, label in patch.diffstatui(util.iterlines(chunks),
819 819 width=width,
820 820 git=diffopts.git):
821 821 write(chunk, label=label)
822 822 else:
823 823 for chunk, label in patch.diffui(repo, node1, node2, match,
824 824 changes, diffopts, prefix=prefix):
825 825 write(chunk, label=label)
826 826
827 827 if listsubrepos:
828 828 ctx1 = repo[node1]
829 829 ctx2 = repo[node2]
830 830 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
831 831 tempnode2 = node2
832 832 try:
833 833 if node2 is not None:
834 834 tempnode2 = ctx2.substate[subpath][1]
835 835 except KeyError:
836 836 # A subrepo that existed in node1 was deleted between node1 and
837 837 # node2 (inclusive). Thus, ctx2's substate won't contain that
838 838 # subpath. The best we can do is to ignore it.
839 839 tempnode2 = None
840 840 submatch = matchmod.narrowmatcher(subpath, match)
841 841 sub.diff(ui, diffopts, tempnode2, submatch, changes=changes,
842 842 stat=stat, fp=fp, prefix=prefix)
843 843
844 844 class changeset_printer(object):
845 845 '''show changeset information when templating not requested.'''
846 846
847 847 def __init__(self, ui, repo, matchfn, diffopts, buffered):
848 848 self.ui = ui
849 849 self.repo = repo
850 850 self.buffered = buffered
851 851 self.matchfn = matchfn
852 852 self.diffopts = diffopts
853 853 self.header = {}
854 854 self.hunk = {}
855 855 self.lastheader = None
856 856 self.footer = None
857 857
858 858 def flush(self, rev):
859 859 if rev in self.header:
860 860 h = self.header[rev]
861 861 if h != self.lastheader:
862 862 self.lastheader = h
863 863 self.ui.write(h)
864 864 del self.header[rev]
865 865 if rev in self.hunk:
866 866 self.ui.write(self.hunk[rev])
867 867 del self.hunk[rev]
868 868 return 1
869 869 return 0
870 870
871 871 def close(self):
872 872 if self.footer:
873 873 self.ui.write(self.footer)
874 874
875 875 def show(self, ctx, copies=None, matchfn=None, **props):
876 876 if self.buffered:
877 877 self.ui.pushbuffer()
878 878 self._show(ctx, copies, matchfn, props)
879 879 self.hunk[ctx.rev()] = self.ui.popbuffer(labeled=True)
880 880 else:
881 881 self._show(ctx, copies, matchfn, props)
882 882
883 883 def _show(self, ctx, copies, matchfn, props):
884 884 '''show a single changeset or file revision'''
885 885 changenode = ctx.node()
886 886 rev = ctx.rev()
887 887
888 888 if self.ui.quiet:
889 889 self.ui.write("%d:%s\n" % (rev, short(changenode)),
890 890 label='log.node')
891 891 return
892 892
893 893 log = self.repo.changelog
894 894 date = util.datestr(ctx.date())
895 895
896 896 hexfunc = self.ui.debugflag and hex or short
897 897
898 898 parents = [(p, hexfunc(log.node(p)))
899 899 for p in self._meaningful_parentrevs(log, rev)]
900 900
901 901 # i18n: column positioning for "hg log"
902 902 self.ui.write(_("changeset: %d:%s\n") % (rev, hexfunc(changenode)),
903 903 label='log.changeset changeset.%s' % ctx.phasestr())
904 904
905 905 # branches are shown first before any other names due to backwards
906 906 # compatibility
907 907 branch = ctx.branch()
908 908 # don't show the default branch name
909 909 if branch != 'default':
910 910 # i18n: column positioning for "hg log"
911 911 self.ui.write(_("branch: %s\n") % branch,
912 912 label='log.branch')
913 913
914 914 for name, ns in self.repo.names.iteritems():
915 915 # branches has special logic already handled above, so here we just
916 916 # skip it
917 917 if name == 'branches':
918 918 continue
919 919 # we will use the templatename as the color name since those two
920 920 # should be the same
921 921 for name in ns.names(self.repo, changenode):
922 922 self.ui.write(ns.logfmt % name,
923 923 label='log.%s' % ns.colorname)
924 924 if self.ui.debugflag:
925 925 # i18n: column positioning for "hg log"
926 926 self.ui.write(_("phase: %s\n") % _(ctx.phasestr()),
927 927 label='log.phase')
928 928 for parent in parents:
929 929 label = 'log.parent changeset.%s' % self.repo[parent[0]].phasestr()
930 930 # i18n: column positioning for "hg log"
931 931 self.ui.write(_("parent: %d:%s\n") % parent,
932 932 label=label)
933 933
934 934 if self.ui.debugflag:
935 935 mnode = ctx.manifestnode()
936 936 # i18n: column positioning for "hg log"
937 937 self.ui.write(_("manifest: %d:%s\n") %
938 938 (self.repo.manifest.rev(mnode), hex(mnode)),
939 939 label='ui.debug log.manifest')
940 940 # i18n: column positioning for "hg log"
941 941 self.ui.write(_("user: %s\n") % ctx.user(),
942 942 label='log.user')
943 943 # i18n: column positioning for "hg log"
944 944 self.ui.write(_("date: %s\n") % date,
945 945 label='log.date')
946 946
947 947 if self.ui.debugflag:
948 948 files = self.repo.status(log.parents(changenode)[0], changenode)[:3]
949 949 for key, value in zip([# i18n: column positioning for "hg log"
950 950 _("files:"),
951 951 # i18n: column positioning for "hg log"
952 952 _("files+:"),
953 953 # i18n: column positioning for "hg log"
954 954 _("files-:")], files):
955 955 if value:
956 956 self.ui.write("%-12s %s\n" % (key, " ".join(value)),
957 957 label='ui.debug log.files')
958 958 elif ctx.files() and self.ui.verbose:
959 959 # i18n: column positioning for "hg log"
960 960 self.ui.write(_("files: %s\n") % " ".join(ctx.files()),
961 961 label='ui.note log.files')
962 962 if copies and self.ui.verbose:
963 963 copies = ['%s (%s)' % c for c in copies]
964 964 # i18n: column positioning for "hg log"
965 965 self.ui.write(_("copies: %s\n") % ' '.join(copies),
966 966 label='ui.note log.copies')
967 967
968 968 extra = ctx.extra()
969 969 if extra and self.ui.debugflag:
970 970 for key, value in sorted(extra.items()):
971 971 # i18n: column positioning for "hg log"
972 972 self.ui.write(_("extra: %s=%s\n")
973 973 % (key, value.encode('string_escape')),
974 974 label='ui.debug log.extra')
975 975
976 976 description = ctx.description().strip()
977 977 if description:
978 978 if self.ui.verbose:
979 979 self.ui.write(_("description:\n"),
980 980 label='ui.note log.description')
981 981 self.ui.write(description,
982 982 label='ui.note log.description')
983 983 self.ui.write("\n\n")
984 984 else:
985 985 # i18n: column positioning for "hg log"
986 986 self.ui.write(_("summary: %s\n") %
987 987 description.splitlines()[0],
988 988 label='log.summary')
989 989 self.ui.write("\n")
990 990
991 991 self.showpatch(changenode, matchfn)
992 992
993 993 def showpatch(self, node, matchfn):
994 994 if not matchfn:
995 995 matchfn = self.matchfn
996 996 if matchfn:
997 997 stat = self.diffopts.get('stat')
998 998 diff = self.diffopts.get('patch')
999 999 diffopts = patch.diffallopts(self.ui, self.diffopts)
1000 1000 prev = self.repo.changelog.parents(node)[0]
1001 1001 if stat:
1002 1002 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1003 1003 match=matchfn, stat=True)
1004 1004 if diff:
1005 1005 if stat:
1006 1006 self.ui.write("\n")
1007 1007 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1008 1008 match=matchfn, stat=False)
1009 1009 self.ui.write("\n")
1010 1010
1011 1011 def _meaningful_parentrevs(self, log, rev):
1012 1012 """Return list of meaningful (or all if debug) parentrevs for rev.
1013 1013
1014 1014 For merges (two non-nullrev revisions) both parents are meaningful.
1015 1015 Otherwise the first parent revision is considered meaningful if it
1016 1016 is not the preceding revision.
1017 1017 """
1018 1018 parents = log.parentrevs(rev)
1019 1019 if not self.ui.debugflag and parents[1] == nullrev:
1020 1020 if parents[0] >= rev - 1:
1021 1021 parents = []
1022 1022 else:
1023 1023 parents = [parents[0]]
1024 1024 return parents
1025 1025
1026 1026 class jsonchangeset(changeset_printer):
1027 1027 '''format changeset information.'''
1028 1028
1029 1029 def __init__(self, ui, repo, matchfn, diffopts, buffered):
1030 1030 changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered)
1031 1031 self.cache = {}
1032 1032 self._first = True
1033 1033
1034 1034 def close(self):
1035 1035 if not self._first:
1036 1036 self.ui.write("\n]\n")
1037 1037 else:
1038 1038 self.ui.write("[]\n")
1039 1039
1040 1040 def _show(self, ctx, copies, matchfn, props):
1041 1041 '''show a single changeset or file revision'''
1042 1042 hexnode = hex(ctx.node())
1043 1043 rev = ctx.rev()
1044 1044 j = encoding.jsonescape
1045 1045
1046 1046 if self._first:
1047 1047 self.ui.write("[\n {")
1048 1048 self._first = False
1049 1049 else:
1050 1050 self.ui.write(",\n {")
1051 1051
1052 1052 if self.ui.quiet:
1053 1053 self.ui.write('\n "rev": %d' % rev)
1054 1054 self.ui.write(',\n "node": "%s"' % hexnode)
1055 1055 self.ui.write('\n }')
1056 1056 return
1057 1057
1058 1058 self.ui.write('\n "rev": %d' % rev)
1059 1059 self.ui.write(',\n "node": "%s"' % hexnode)
1060 1060 self.ui.write(',\n "branch": "%s"' % j(ctx.branch()))
1061 1061 self.ui.write(',\n "phase": "%s"' % ctx.phasestr())
1062 1062 self.ui.write(',\n "user": "%s"' % j(ctx.user()))
1063 1063 self.ui.write(',\n "date": [%d, %d]' % ctx.date())
1064 1064 self.ui.write(',\n "desc": "%s"' % j(ctx.description()))
1065 1065
1066 1066 self.ui.write(',\n "bookmarks": [%s]' %
1067 1067 ", ".join('"%s"' % j(b) for b in ctx.bookmarks()))
1068 1068 self.ui.write(',\n "tags": [%s]' %
1069 1069 ", ".join('"%s"' % j(t) for t in ctx.tags()))
1070 1070 self.ui.write(',\n "parents": [%s]' %
1071 1071 ", ".join('"%s"' % c.hex() for c in ctx.parents()))
1072 1072
1073 1073 if self.ui.debugflag:
1074 1074 self.ui.write(',\n "manifest": "%s"' % hex(ctx.manifestnode()))
1075 1075
1076 1076 self.ui.write(',\n "extra": {%s}' %
1077 1077 ", ".join('"%s": "%s"' % (j(k), j(v))
1078 1078 for k, v in ctx.extra().items()))
1079 1079
1080 1080 files = ctx.p1().status(ctx)
1081 1081 self.ui.write(',\n "modified": [%s]' %
1082 1082 ", ".join('"%s"' % j(f) for f in files[0]))
1083 1083 self.ui.write(',\n "added": [%s]' %
1084 1084 ", ".join('"%s"' % j(f) for f in files[1]))
1085 1085 self.ui.write(',\n "removed": [%s]' %
1086 1086 ", ".join('"%s"' % j(f) for f in files[2]))
1087 1087
1088 1088 elif self.ui.verbose:
1089 1089 self.ui.write(',\n "files": [%s]' %
1090 1090 ", ".join('"%s"' % j(f) for f in ctx.files()))
1091 1091
1092 1092 if copies:
1093 1093 self.ui.write(',\n "copies": {%s}' %
1094 1094 ", ".join('"%s": "%s"' % (j(k), j(v))
1095 1095 for k, v in copies))
1096 1096
1097 1097 matchfn = self.matchfn
1098 1098 if matchfn:
1099 1099 stat = self.diffopts.get('stat')
1100 1100 diff = self.diffopts.get('patch')
1101 1101 diffopts = patch.difffeatureopts(self.ui, self.diffopts, git=True)
1102 1102 node, prev = ctx.node(), ctx.p1().node()
1103 1103 if stat:
1104 1104 self.ui.pushbuffer()
1105 1105 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1106 1106 match=matchfn, stat=True)
1107 1107 self.ui.write(',\n "diffstat": "%s"' % j(self.ui.popbuffer()))
1108 1108 if diff:
1109 1109 self.ui.pushbuffer()
1110 1110 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1111 1111 match=matchfn, stat=False)
1112 1112 self.ui.write(',\n "diff": "%s"' % j(self.ui.popbuffer()))
1113 1113
1114 1114 self.ui.write("\n }")
1115 1115
1116 1116 class changeset_templater(changeset_printer):
1117 1117 '''format changeset information.'''
1118 1118
1119 1119 def __init__(self, ui, repo, matchfn, diffopts, tmpl, mapfile, buffered):
1120 1120 changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered)
1121 1121 formatnode = ui.debugflag and (lambda x: x) or (lambda x: x[:12])
1122 1122 defaulttempl = {
1123 1123 'parent': '{rev}:{node|formatnode} ',
1124 1124 'manifest': '{rev}:{node|formatnode}',
1125 1125 'file_copy': '{name} ({source})',
1126 1126 'extra': '{key}={value|stringescape}'
1127 1127 }
1128 1128 # filecopy is preserved for compatibility reasons
1129 1129 defaulttempl['filecopy'] = defaulttempl['file_copy']
1130 1130 self.t = templater.templater(mapfile, {'formatnode': formatnode},
1131 1131 cache=defaulttempl)
1132 1132 if tmpl:
1133 1133 self.t.cache['changeset'] = tmpl
1134 1134
1135 1135 self.cache = {}
1136 1136
1137 1137 def _meaningful_parentrevs(self, ctx):
1138 1138 """Return list of meaningful (or all if debug) parentrevs for rev.
1139 1139 """
1140 1140 parents = ctx.parents()
1141 1141 if len(parents) > 1:
1142 1142 return parents
1143 1143 if self.ui.debugflag:
1144 1144 return [parents[0], self.repo['null']]
1145 1145 if parents[0].rev() >= ctx.rev() - 1:
1146 1146 return []
1147 1147 return parents
1148 1148
1149 1149 def _show(self, ctx, copies, matchfn, props):
1150 1150 '''show a single changeset or file revision'''
1151 1151
1152 1152 showlist = templatekw.showlist
1153 1153
1154 1154 # showparents() behaviour depends on ui trace level which
1155 1155 # causes unexpected behaviours at templating level and makes
1156 1156 # it harder to extract it in a standalone function. Its
1157 1157 # behaviour cannot be changed so leave it here for now.
1158 1158 def showparents(**args):
1159 1159 ctx = args['ctx']
1160 1160 parents = [[('rev', p.rev()),
1161 1161 ('node', p.hex()),
1162 1162 ('phase', p.phasestr())]
1163 1163 for p in self._meaningful_parentrevs(ctx)]
1164 1164 return showlist('parent', parents, **args)
1165 1165
1166 1166 props = props.copy()
1167 1167 props.update(templatekw.keywords)
1168 1168 props['parents'] = showparents
1169 1169 props['templ'] = self.t
1170 1170 props['ctx'] = ctx
1171 1171 props['repo'] = self.repo
1172 1172 props['revcache'] = {'copies': copies}
1173 1173 props['cache'] = self.cache
1174 1174
1175 1175 # find correct templates for current mode
1176 1176
1177 1177 tmplmodes = [
1178 1178 (True, None),
1179 1179 (self.ui.verbose, 'verbose'),
1180 1180 (self.ui.quiet, 'quiet'),
1181 1181 (self.ui.debugflag, 'debug'),
1182 1182 ]
1183 1183
1184 1184 types = {'header': '', 'footer':'', 'changeset': 'changeset'}
1185 1185 for mode, postfix in tmplmodes:
1186 1186 for type in types:
1187 1187 cur = postfix and ('%s_%s' % (type, postfix)) or type
1188 1188 if mode and cur in self.t:
1189 1189 types[type] = cur
1190 1190
1191 1191 try:
1192 1192
1193 1193 # write header
1194 1194 if types['header']:
1195 1195 h = templater.stringify(self.t(types['header'], **props))
1196 1196 if self.buffered:
1197 1197 self.header[ctx.rev()] = h
1198 1198 else:
1199 1199 if self.lastheader != h:
1200 1200 self.lastheader = h
1201 1201 self.ui.write(h)
1202 1202
1203 1203 # write changeset metadata, then patch if requested
1204 1204 key = types['changeset']
1205 1205 self.ui.write(templater.stringify(self.t(key, **props)))
1206 1206 self.showpatch(ctx.node(), matchfn)
1207 1207
1208 1208 if types['footer']:
1209 1209 if not self.footer:
1210 1210 self.footer = templater.stringify(self.t(types['footer'],
1211 1211 **props))
1212 1212
1213 1213 except KeyError, inst:
1214 1214 msg = _("%s: no key named '%s'")
1215 1215 raise util.Abort(msg % (self.t.mapfile, inst.args[0]))
1216 1216 except SyntaxError, inst:
1217 1217 raise util.Abort('%s: %s' % (self.t.mapfile, inst.args[0]))
1218 1218
1219 1219 def gettemplate(ui, tmpl, style):
1220 1220 """
1221 1221 Find the template matching the given template spec or style.
1222 1222 """
1223 1223
1224 1224 # ui settings
1225 1225 if not tmpl and not style: # template are stronger than style
1226 1226 tmpl = ui.config('ui', 'logtemplate')
1227 1227 if tmpl:
1228 1228 try:
1229 1229 tmpl = templater.parsestring(tmpl)
1230 1230 except SyntaxError:
1231 1231 tmpl = templater.parsestring(tmpl, quoted=False)
1232 1232 return tmpl, None
1233 1233 else:
1234 1234 style = util.expandpath(ui.config('ui', 'style', ''))
1235 1235
1236 1236 if not tmpl and style:
1237 1237 mapfile = style
1238 1238 if not os.path.split(mapfile)[0]:
1239 1239 mapname = (templater.templatepath('map-cmdline.' + mapfile)
1240 1240 or templater.templatepath(mapfile))
1241 1241 if mapname:
1242 1242 mapfile = mapname
1243 1243 return None, mapfile
1244 1244
1245 1245 if not tmpl:
1246 1246 return None, None
1247 1247
1248 1248 # looks like a literal template?
1249 1249 if '{' in tmpl:
1250 1250 return tmpl, None
1251 1251
1252 1252 # perhaps a stock style?
1253 1253 if not os.path.split(tmpl)[0]:
1254 1254 mapname = (templater.templatepath('map-cmdline.' + tmpl)
1255 1255 or templater.templatepath(tmpl))
1256 1256 if mapname and os.path.isfile(mapname):
1257 1257 return None, mapname
1258 1258
1259 1259 # perhaps it's a reference to [templates]
1260 1260 t = ui.config('templates', tmpl)
1261 1261 if t:
1262 1262 try:
1263 1263 tmpl = templater.parsestring(t)
1264 1264 except SyntaxError:
1265 1265 tmpl = templater.parsestring(t, quoted=False)
1266 1266 return tmpl, None
1267 1267
1268 1268 if tmpl == 'list':
1269 1269 ui.write(_("available styles: %s\n") % templater.stylelist())
1270 1270 raise util.Abort(_("specify a template"))
1271 1271
1272 1272 # perhaps it's a path to a map or a template
1273 1273 if ('/' in tmpl or '\\' in tmpl) and os.path.isfile(tmpl):
1274 1274 # is it a mapfile for a style?
1275 1275 if os.path.basename(tmpl).startswith("map-"):
1276 1276 return None, os.path.realpath(tmpl)
1277 1277 tmpl = open(tmpl).read()
1278 1278 return tmpl, None
1279 1279
1280 1280 # constant string?
1281 1281 return tmpl, None
1282 1282
1283 1283 def show_changeset(ui, repo, opts, buffered=False):
1284 1284 """show one changeset using template or regular display.
1285 1285
1286 1286 Display format will be the first non-empty hit of:
1287 1287 1. option 'template'
1288 1288 2. option 'style'
1289 1289 3. [ui] setting 'logtemplate'
1290 1290 4. [ui] setting 'style'
1291 1291 If all of these values are either the unset or the empty string,
1292 1292 regular display via changeset_printer() is done.
1293 1293 """
1294 1294 # options
1295 1295 matchfn = None
1296 1296 if opts.get('patch') or opts.get('stat'):
1297 1297 matchfn = scmutil.matchall(repo)
1298 1298
1299 1299 if opts.get('template') == 'json':
1300 1300 return jsonchangeset(ui, repo, matchfn, opts, buffered)
1301 1301
1302 1302 tmpl, mapfile = gettemplate(ui, opts.get('template'), opts.get('style'))
1303 1303
1304 1304 if not tmpl and not mapfile:
1305 1305 return changeset_printer(ui, repo, matchfn, opts, buffered)
1306 1306
1307 1307 try:
1308 1308 t = changeset_templater(ui, repo, matchfn, opts, tmpl, mapfile,
1309 1309 buffered)
1310 1310 except SyntaxError, inst:
1311 1311 raise util.Abort(inst.args[0])
1312 1312 return t
1313 1313
1314 1314 def showmarker(ui, marker):
1315 1315 """utility function to display obsolescence marker in a readable way
1316 1316
1317 1317 To be used by debug function."""
1318 1318 ui.write(hex(marker.precnode()))
1319 1319 for repl in marker.succnodes():
1320 1320 ui.write(' ')
1321 1321 ui.write(hex(repl))
1322 1322 ui.write(' %X ' % marker.flags())
1323 1323 parents = marker.parentnodes()
1324 1324 if parents is not None:
1325 1325 ui.write('{%s} ' % ', '.join(hex(p) for p in parents))
1326 1326 ui.write('(%s) ' % util.datestr(marker.date()))
1327 1327 ui.write('{%s}' % (', '.join('%r: %r' % t for t in
1328 1328 sorted(marker.metadata().items())
1329 1329 if t[0] != 'date')))
1330 1330 ui.write('\n')
1331 1331
1332 1332 def finddate(ui, repo, date):
1333 1333 """Find the tipmost changeset that matches the given date spec"""
1334 1334
1335 1335 df = util.matchdate(date)
1336 1336 m = scmutil.matchall(repo)
1337 1337 results = {}
1338 1338
1339 1339 def prep(ctx, fns):
1340 1340 d = ctx.date()
1341 1341 if df(d[0]):
1342 1342 results[ctx.rev()] = d
1343 1343
1344 1344 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
1345 1345 rev = ctx.rev()
1346 1346 if rev in results:
1347 1347 ui.status(_("found revision %s from %s\n") %
1348 1348 (rev, util.datestr(results[rev])))
1349 1349 return str(rev)
1350 1350
1351 1351 raise util.Abort(_("revision matching date not found"))
1352 1352
1353 1353 def increasingwindows(windowsize=8, sizelimit=512):
1354 1354 while True:
1355 1355 yield windowsize
1356 1356 if windowsize < sizelimit:
1357 1357 windowsize *= 2
1358 1358
1359 1359 class FileWalkError(Exception):
1360 1360 pass
1361 1361
1362 1362 def walkfilerevs(repo, match, follow, revs, fncache):
1363 1363 '''Walks the file history for the matched files.
1364 1364
1365 1365 Returns the changeset revs that are involved in the file history.
1366 1366
1367 1367 Throws FileWalkError if the file history can't be walked using
1368 1368 filelogs alone.
1369 1369 '''
1370 1370 wanted = set()
1371 1371 copies = []
1372 1372 minrev, maxrev = min(revs), max(revs)
1373 1373 def filerevgen(filelog, last):
1374 1374 """
1375 1375 Only files, no patterns. Check the history of each file.
1376 1376
1377 1377 Examines filelog entries within minrev, maxrev linkrev range
1378 1378 Returns an iterator yielding (linkrev, parentlinkrevs, copied)
1379 1379 tuples in backwards order
1380 1380 """
1381 1381 cl_count = len(repo)
1382 1382 revs = []
1383 1383 for j in xrange(0, last + 1):
1384 1384 linkrev = filelog.linkrev(j)
1385 1385 if linkrev < minrev:
1386 1386 continue
1387 1387 # only yield rev for which we have the changelog, it can
1388 1388 # happen while doing "hg log" during a pull or commit
1389 1389 if linkrev >= cl_count:
1390 1390 break
1391 1391
1392 1392 parentlinkrevs = []
1393 1393 for p in filelog.parentrevs(j):
1394 1394 if p != nullrev:
1395 1395 parentlinkrevs.append(filelog.linkrev(p))
1396 1396 n = filelog.node(j)
1397 1397 revs.append((linkrev, parentlinkrevs,
1398 1398 follow and filelog.renamed(n)))
1399 1399
1400 1400 return reversed(revs)
1401 1401 def iterfiles():
1402 1402 pctx = repo['.']
1403 1403 for filename in match.files():
1404 1404 if follow:
1405 1405 if filename not in pctx:
1406 1406 raise util.Abort(_('cannot follow file not in parent '
1407 1407 'revision: "%s"') % filename)
1408 1408 yield filename, pctx[filename].filenode()
1409 1409 else:
1410 1410 yield filename, None
1411 1411 for filename_node in copies:
1412 1412 yield filename_node
1413 1413
1414 1414 for file_, node in iterfiles():
1415 1415 filelog = repo.file(file_)
1416 1416 if not len(filelog):
1417 1417 if node is None:
1418 1418 # A zero count may be a directory or deleted file, so
1419 1419 # try to find matching entries on the slow path.
1420 1420 if follow:
1421 1421 raise util.Abort(
1422 1422 _('cannot follow nonexistent file: "%s"') % file_)
1423 1423 raise FileWalkError("Cannot walk via filelog")
1424 1424 else:
1425 1425 continue
1426 1426
1427 1427 if node is None:
1428 1428 last = len(filelog) - 1
1429 1429 else:
1430 1430 last = filelog.rev(node)
1431 1431
1432 1432
1433 1433 # keep track of all ancestors of the file
1434 1434 ancestors = set([filelog.linkrev(last)])
1435 1435
1436 1436 # iterate from latest to oldest revision
1437 1437 for rev, flparentlinkrevs, copied in filerevgen(filelog, last):
1438 1438 if not follow:
1439 1439 if rev > maxrev:
1440 1440 continue
1441 1441 else:
1442 1442 # Note that last might not be the first interesting
1443 1443 # rev to us:
1444 1444 # if the file has been changed after maxrev, we'll
1445 1445 # have linkrev(last) > maxrev, and we still need
1446 1446 # to explore the file graph
1447 1447 if rev not in ancestors:
1448 1448 continue
1449 1449 # XXX insert 1327 fix here
1450 1450 if flparentlinkrevs:
1451 1451 ancestors.update(flparentlinkrevs)
1452 1452
1453 1453 fncache.setdefault(rev, []).append(file_)
1454 1454 wanted.add(rev)
1455 1455 if copied:
1456 1456 copies.append(copied)
1457 1457
1458 1458 return wanted
1459 1459
1460 1460 def walkchangerevs(repo, match, opts, prepare):
1461 1461 '''Iterate over files and the revs in which they changed.
1462 1462
1463 1463 Callers most commonly need to iterate backwards over the history
1464 1464 in which they are interested. Doing so has awful (quadratic-looking)
1465 1465 performance, so we use iterators in a "windowed" way.
1466 1466
1467 1467 We walk a window of revisions in the desired order. Within the
1468 1468 window, we first walk forwards to gather data, then in the desired
1469 1469 order (usually backwards) to display it.
1470 1470
1471 1471 This function returns an iterator yielding contexts. Before
1472 1472 yielding each context, the iterator will first call the prepare
1473 1473 function on each context in the window in forward order.'''
1474 1474
1475 1475 follow = opts.get('follow') or opts.get('follow_first')
1476 1476
1477 1477 if opts.get('rev'):
1478 1478 revs = scmutil.revrange(repo, opts.get('rev'))
1479 1479 elif follow:
1480 1480 revs = repo.revs('reverse(:.)')
1481 1481 else:
1482 1482 revs = revset.spanset(repo)
1483 1483 revs.reverse()
1484 1484 if not revs:
1485 1485 return []
1486 1486 wanted = set()
1487 1487 slowpath = match.anypats() or (match.files() and opts.get('removed'))
1488 1488 fncache = {}
1489 1489 change = repo.changectx
1490 1490
1491 1491 # First step is to fill wanted, the set of revisions that we want to yield.
1492 1492 # When it does not induce extra cost, we also fill fncache for revisions in
1493 1493 # wanted: a cache of filenames that were changed (ctx.files()) and that
1494 1494 # match the file filtering conditions.
1495 1495
1496 1496 if not slowpath and not match.files():
1497 1497 # No files, no patterns. Display all revs.
1498 1498 wanted = revs
1499 1499
1500 1500 if not slowpath and match.files():
1501 1501 # We only have to read through the filelog to find wanted revisions
1502 1502
1503 1503 try:
1504 1504 wanted = walkfilerevs(repo, match, follow, revs, fncache)
1505 1505 except FileWalkError:
1506 1506 slowpath = True
1507 1507
1508 1508 # We decided to fall back to the slowpath because at least one
1509 1509 # of the paths was not a file. Check to see if at least one of them
1510 1510 # existed in history, otherwise simply return
1511 1511 for path in match.files():
1512 1512 if path == '.' or path in repo.store:
1513 1513 break
1514 1514 else:
1515 1515 return []
1516 1516
1517 1517 if slowpath:
1518 1518 # We have to read the changelog to match filenames against
1519 1519 # changed files
1520 1520
1521 1521 if follow:
1522 1522 raise util.Abort(_('can only follow copies/renames for explicit '
1523 1523 'filenames'))
1524 1524
1525 1525 # The slow path checks files modified in every changeset.
1526 1526 # This is really slow on large repos, so compute the set lazily.
1527 1527 class lazywantedset(object):
1528 1528 def __init__(self):
1529 1529 self.set = set()
1530 1530 self.revs = set(revs)
1531 1531
1532 1532 # No need to worry about locality here because it will be accessed
1533 1533 # in the same order as the increasing window below.
1534 1534 def __contains__(self, value):
1535 1535 if value in self.set:
1536 1536 return True
1537 1537 elif not value in self.revs:
1538 1538 return False
1539 1539 else:
1540 1540 self.revs.discard(value)
1541 1541 ctx = change(value)
1542 1542 matches = filter(match, ctx.files())
1543 1543 if matches:
1544 1544 fncache[value] = matches
1545 1545 self.set.add(value)
1546 1546 return True
1547 1547 return False
1548 1548
1549 1549 def discard(self, value):
1550 1550 self.revs.discard(value)
1551 1551 self.set.discard(value)
1552 1552
1553 1553 wanted = lazywantedset()
1554 1554
1555 1555 class followfilter(object):
1556 1556 def __init__(self, onlyfirst=False):
1557 1557 self.startrev = nullrev
1558 1558 self.roots = set()
1559 1559 self.onlyfirst = onlyfirst
1560 1560
1561 1561 def match(self, rev):
1562 1562 def realparents(rev):
1563 1563 if self.onlyfirst:
1564 1564 return repo.changelog.parentrevs(rev)[0:1]
1565 1565 else:
1566 1566 return filter(lambda x: x != nullrev,
1567 1567 repo.changelog.parentrevs(rev))
1568 1568
1569 1569 if self.startrev == nullrev:
1570 1570 self.startrev = rev
1571 1571 return True
1572 1572
1573 1573 if rev > self.startrev:
1574 1574 # forward: all descendants
1575 1575 if not self.roots:
1576 1576 self.roots.add(self.startrev)
1577 1577 for parent in realparents(rev):
1578 1578 if parent in self.roots:
1579 1579 self.roots.add(rev)
1580 1580 return True
1581 1581 else:
1582 1582 # backwards: all parents
1583 1583 if not self.roots:
1584 1584 self.roots.update(realparents(self.startrev))
1585 1585 if rev in self.roots:
1586 1586 self.roots.remove(rev)
1587 1587 self.roots.update(realparents(rev))
1588 1588 return True
1589 1589
1590 1590 return False
1591 1591
1592 1592 # it might be worthwhile to do this in the iterator if the rev range
1593 1593 # is descending and the prune args are all within that range
1594 1594 for rev in opts.get('prune', ()):
1595 1595 rev = repo[rev].rev()
1596 1596 ff = followfilter()
1597 1597 stop = min(revs[0], revs[-1])
1598 1598 for x in xrange(rev, stop - 1, -1):
1599 1599 if ff.match(x):
1600 1600 wanted = wanted - [x]
1601 1601
1602 1602 # Now that wanted is correctly initialized, we can iterate over the
1603 1603 # revision range, yielding only revisions in wanted.
1604 1604 def iterate():
1605 1605 if follow and not match.files():
1606 1606 ff = followfilter(onlyfirst=opts.get('follow_first'))
1607 1607 def want(rev):
1608 1608 return ff.match(rev) and rev in wanted
1609 1609 else:
1610 1610 def want(rev):
1611 1611 return rev in wanted
1612 1612
1613 1613 it = iter(revs)
1614 1614 stopiteration = False
1615 1615 for windowsize in increasingwindows():
1616 1616 nrevs = []
1617 1617 for i in xrange(windowsize):
1618 1618 try:
1619 1619 rev = it.next()
1620 1620 if want(rev):
1621 1621 nrevs.append(rev)
1622 1622 except (StopIteration):
1623 1623 stopiteration = True
1624 1624 break
1625 1625 for rev in sorted(nrevs):
1626 1626 fns = fncache.get(rev)
1627 1627 ctx = change(rev)
1628 1628 if not fns:
1629 1629 def fns_generator():
1630 1630 for f in ctx.files():
1631 1631 if match(f):
1632 1632 yield f
1633 1633 fns = fns_generator()
1634 1634 prepare(ctx, fns)
1635 1635 for rev in nrevs:
1636 1636 yield change(rev)
1637 1637
1638 1638 if stopiteration:
1639 1639 break
1640 1640
1641 1641 return iterate()
1642 1642
1643 1643 def _makefollowlogfilematcher(repo, files, followfirst):
1644 1644 # When displaying a revision with --patch --follow FILE, we have
1645 1645 # to know which file of the revision must be diffed. With
1646 1646 # --follow, we want the names of the ancestors of FILE in the
1647 1647 # revision, stored in "fcache". "fcache" is populated by
1648 1648 # reproducing the graph traversal already done by --follow revset
1649 1649 # and relating linkrevs to file names (which is not "correct" but
1650 1650 # good enough).
1651 1651 fcache = {}
1652 1652 fcacheready = [False]
1653 1653 pctx = repo['.']
1654 1654
1655 1655 def populate():
1656 1656 for fn in files:
1657 1657 for i in ((pctx[fn],), pctx[fn].ancestors(followfirst=followfirst)):
1658 1658 for c in i:
1659 1659 fcache.setdefault(c.linkrev(), set()).add(c.path())
1660 1660
1661 1661 def filematcher(rev):
1662 1662 if not fcacheready[0]:
1663 1663 # Lazy initialization
1664 1664 fcacheready[0] = True
1665 1665 populate()
1666 1666 return scmutil.matchfiles(repo, fcache.get(rev, []))
1667 1667
1668 1668 return filematcher
1669 1669
1670 1670 def _makenofollowlogfilematcher(repo, pats, opts):
1671 1671 '''hook for extensions to override the filematcher for non-follow cases'''
1672 1672 return None
1673 1673
1674 1674 def _makelogrevset(repo, pats, opts, revs):
1675 1675 """Return (expr, filematcher) where expr is a revset string built
1676 1676 from log options and file patterns or None. If --stat or --patch
1677 1677 are not passed filematcher is None. Otherwise it is a callable
1678 1678 taking a revision number and returning a match objects filtering
1679 1679 the files to be detailed when displaying the revision.
1680 1680 """
1681 1681 opt2revset = {
1682 1682 'no_merges': ('not merge()', None),
1683 1683 'only_merges': ('merge()', None),
1684 1684 '_ancestors': ('ancestors(%(val)s)', None),
1685 1685 '_fancestors': ('_firstancestors(%(val)s)', None),
1686 1686 '_descendants': ('descendants(%(val)s)', None),
1687 1687 '_fdescendants': ('_firstdescendants(%(val)s)', None),
1688 1688 '_matchfiles': ('_matchfiles(%(val)s)', None),
1689 1689 'date': ('date(%(val)r)', None),
1690 1690 'branch': ('branch(%(val)r)', ' or '),
1691 1691 '_patslog': ('filelog(%(val)r)', ' or '),
1692 1692 '_patsfollow': ('follow(%(val)r)', ' or '),
1693 1693 '_patsfollowfirst': ('_followfirst(%(val)r)', ' or '),
1694 1694 'keyword': ('keyword(%(val)r)', ' or '),
1695 1695 'prune': ('not (%(val)r or ancestors(%(val)r))', ' and '),
1696 1696 'user': ('user(%(val)r)', ' or '),
1697 1697 }
1698 1698
1699 1699 opts = dict(opts)
1700 1700 # follow or not follow?
1701 1701 follow = opts.get('follow') or opts.get('follow_first')
1702 1702 followfirst = opts.get('follow_first') and 1 or 0
1703 1703 # --follow with FILE behaviour depends on revs...
1704 1704 it = iter(revs)
1705 1705 startrev = it.next()
1706 1706 try:
1707 1707 followdescendants = startrev < it.next()
1708 1708 except (StopIteration):
1709 1709 followdescendants = False
1710 1710
1711 1711 # branch and only_branch are really aliases and must be handled at
1712 1712 # the same time
1713 1713 opts['branch'] = opts.get('branch', []) + opts.get('only_branch', [])
1714 1714 opts['branch'] = [repo.lookupbranch(b) for b in opts['branch']]
1715 1715 # pats/include/exclude are passed to match.match() directly in
1716 1716 # _matchfiles() revset but walkchangerevs() builds its matcher with
1717 1717 # scmutil.match(). The difference is input pats are globbed on
1718 1718 # platforms without shell expansion (windows).
1719 1719 pctx = repo[None]
1720 1720 match, pats = scmutil.matchandpats(pctx, pats, opts)
1721 1721 slowpath = match.anypats() or (match.files() and opts.get('removed'))
1722 1722 if not slowpath:
1723 1723 for f in match.files():
1724 1724 if follow and f not in pctx:
1725 1725 # If the file exists, it may be a directory, so let it
1726 1726 # take the slow path.
1727 1727 if os.path.exists(repo.wjoin(f)):
1728 1728 slowpath = True
1729 1729 continue
1730 1730 else:
1731 1731 raise util.Abort(_('cannot follow file not in parent '
1732 1732 'revision: "%s"') % f)
1733 1733 filelog = repo.file(f)
1734 1734 if not filelog:
1735 1735 # A zero count may be a directory or deleted file, so
1736 1736 # try to find matching entries on the slow path.
1737 1737 if follow:
1738 1738 raise util.Abort(
1739 1739 _('cannot follow nonexistent file: "%s"') % f)
1740 1740 slowpath = True
1741 1741
1742 1742 # We decided to fall back to the slowpath because at least one
1743 1743 # of the paths was not a file. Check to see if at least one of them
1744 1744 # existed in history - in that case, we'll continue down the
1745 1745 # slowpath; otherwise, we can turn off the slowpath
1746 1746 if slowpath:
1747 1747 for path in match.files():
1748 1748 if path == '.' or path in repo.store:
1749 1749 break
1750 1750 else:
1751 1751 slowpath = False
1752 1752
1753 1753 fpats = ('_patsfollow', '_patsfollowfirst')
1754 1754 fnopats = (('_ancestors', '_fancestors'),
1755 1755 ('_descendants', '_fdescendants'))
1756 1756 if slowpath:
1757 1757 # See walkchangerevs() slow path.
1758 1758 #
1759 1759 # pats/include/exclude cannot be represented as separate
1760 1760 # revset expressions as their filtering logic applies at file
1761 1761 # level. For instance "-I a -X a" matches a revision touching
1762 1762 # "a" and "b" while "file(a) and not file(b)" does
1763 1763 # not. Besides, filesets are evaluated against the working
1764 1764 # directory.
1765 1765 matchargs = ['r:', 'd:relpath']
1766 1766 for p in pats:
1767 1767 matchargs.append('p:' + p)
1768 1768 for p in opts.get('include', []):
1769 1769 matchargs.append('i:' + p)
1770 1770 for p in opts.get('exclude', []):
1771 1771 matchargs.append('x:' + p)
1772 1772 matchargs = ','.join(('%r' % p) for p in matchargs)
1773 1773 opts['_matchfiles'] = matchargs
1774 1774 if follow:
1775 1775 opts[fnopats[0][followfirst]] = '.'
1776 1776 else:
1777 1777 if follow:
1778 1778 if pats:
1779 1779 # follow() revset interprets its file argument as a
1780 1780 # manifest entry, so use match.files(), not pats.
1781 1781 opts[fpats[followfirst]] = list(match.files())
1782 1782 else:
1783 1783 op = fnopats[followdescendants][followfirst]
1784 1784 opts[op] = 'rev(%d)' % startrev
1785 1785 else:
1786 1786 opts['_patslog'] = list(pats)
1787 1787
1788 1788 filematcher = None
1789 1789 if opts.get('patch') or opts.get('stat'):
1790 1790 # When following files, track renames via a special matcher.
1791 1791 # If we're forced to take the slowpath it means we're following
1792 1792 # at least one pattern/directory, so don't bother with rename tracking.
1793 1793 if follow and not match.always() and not slowpath:
1794 1794 # _makefollowlogfilematcher expects its files argument to be
1795 1795 # relative to the repo root, so use match.files(), not pats.
1796 1796 filematcher = _makefollowlogfilematcher(repo, match.files(),
1797 1797 followfirst)
1798 1798 else:
1799 1799 filematcher = _makenofollowlogfilematcher(repo, pats, opts)
1800 1800 if filematcher is None:
1801 1801 filematcher = lambda rev: match
1802 1802
1803 1803 expr = []
1804 1804 for op, val in sorted(opts.iteritems()):
1805 1805 if not val:
1806 1806 continue
1807 1807 if op not in opt2revset:
1808 1808 continue
1809 1809 revop, andor = opt2revset[op]
1810 1810 if '%(val)' not in revop:
1811 1811 expr.append(revop)
1812 1812 else:
1813 1813 if not isinstance(val, list):
1814 1814 e = revop % {'val': val}
1815 1815 else:
1816 1816 e = '(' + andor.join((revop % {'val': v}) for v in val) + ')'
1817 1817 expr.append(e)
1818 1818
1819 1819 if expr:
1820 1820 expr = '(' + ' and '.join(expr) + ')'
1821 1821 else:
1822 1822 expr = None
1823 1823 return expr, filematcher
1824 1824
1825 1825 def getgraphlogrevs(repo, pats, opts):
1826 1826 """Return (revs, expr, filematcher) where revs is an iterable of
1827 1827 revision numbers, expr is a revset string built from log options
1828 1828 and file patterns or None, and used to filter 'revs'. If --stat or
1829 1829 --patch are not passed filematcher is None. Otherwise it is a
1830 1830 callable taking a revision number and returning a match objects
1831 1831 filtering the files to be detailed when displaying the revision.
1832 1832 """
1833 1833 limit = loglimit(opts)
1834 1834 # Default --rev value depends on --follow but --follow behaviour
1835 1835 # depends on revisions resolved from --rev...
1836 1836 follow = opts.get('follow') or opts.get('follow_first')
1837 possiblyunsorted = False # whether revs might need sorting
1838 1837 if opts.get('rev'):
1839 1838 revs = scmutil.revrange(repo, opts['rev'])
1840 # Don't sort here because _makelogrevset might depend on the
1841 # order of revs
1842 possiblyunsorted = True
1843 1839 else:
1844 1840 if follow and len(repo) > 0:
1845 1841 revs = repo.revs('reverse(:.)')
1846 1842 else:
1847 1843 revs = revset.spanset(repo)
1848 1844 revs.reverse()
1849 1845 if not revs:
1850 1846 return revset.baseset(), None, None
1851 1847 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
1852 if possiblyunsorted:
1848 if opts.get('rev'):
1849 # User-specified revs might be unsorted, but don't sort before
1850 # _makelogrevset because it might depend on the order of revs
1853 1851 revs.sort(reverse=True)
1854 1852 if expr:
1855 1853 # Revset matchers often operate faster on revisions in changelog
1856 1854 # order, because most filters deal with the changelog.
1857 1855 revs.reverse()
1858 1856 matcher = revset.match(repo.ui, expr)
1859 1857 # Revset matches can reorder revisions. "A or B" typically returns
1860 1858 # returns the revision matching A then the revision matching B. Sort
1861 1859 # again to fix that.
1862 1860 revs = matcher(repo, revs)
1863 1861 revs.sort(reverse=True)
1864 1862 if limit is not None:
1865 1863 limitedrevs = []
1866 1864 for idx, rev in enumerate(revs):
1867 1865 if idx >= limit:
1868 1866 break
1869 1867 limitedrevs.append(rev)
1870 1868 revs = revset.baseset(limitedrevs)
1871 1869
1872 1870 return revs, expr, filematcher
1873 1871
1874 1872 def getlogrevs(repo, pats, opts):
1875 1873 """Return (revs, expr, filematcher) where revs is an iterable of
1876 1874 revision numbers, expr is a revset string built from log options
1877 1875 and file patterns or None, and used to filter 'revs'. If --stat or
1878 1876 --patch are not passed filematcher is None. Otherwise it is a
1879 1877 callable taking a revision number and returning a match objects
1880 1878 filtering the files to be detailed when displaying the revision.
1881 1879 """
1882 1880 limit = loglimit(opts)
1883 1881 # Default --rev value depends on --follow but --follow behaviour
1884 1882 # depends on revisions resolved from --rev...
1885 1883 follow = opts.get('follow') or opts.get('follow_first')
1886 1884 if opts.get('rev'):
1887 1885 revs = scmutil.revrange(repo, opts['rev'])
1888 1886 elif follow:
1889 1887 revs = repo.revs('reverse(:.)')
1890 1888 else:
1891 1889 revs = revset.spanset(repo)
1892 1890 revs.reverse()
1893 1891 if not revs:
1894 1892 return revset.baseset([]), None, None
1895 1893 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
1896 1894 if expr:
1897 1895 # Revset matchers often operate faster on revisions in changelog
1898 1896 # order, because most filters deal with the changelog.
1899 1897 if not opts.get('rev'):
1900 1898 revs.reverse()
1901 1899 matcher = revset.match(repo.ui, expr)
1902 1900 # Revset matches can reorder revisions. "A or B" typically returns
1903 1901 # returns the revision matching A then the revision matching B. Sort
1904 1902 # again to fix that.
1905 1903 revs = matcher(repo, revs)
1906 1904 if not opts.get('rev'):
1907 1905 revs.sort(reverse=True)
1908 1906 if limit is not None:
1909 1907 count = 0
1910 1908 limitedrevs = []
1911 1909 it = iter(revs)
1912 1910 while count < limit:
1913 1911 try:
1914 1912 limitedrevs.append(it.next())
1915 1913 except (StopIteration):
1916 1914 break
1917 1915 count += 1
1918 1916 revs = revset.baseset(limitedrevs)
1919 1917
1920 1918 return revs, expr, filematcher
1921 1919
1922 1920 def displaygraph(ui, dag, displayer, showparents, edgefn, getrenamed=None,
1923 1921 filematcher=None):
1924 1922 seen, state = [], graphmod.asciistate()
1925 1923 for rev, type, ctx, parents in dag:
1926 1924 char = 'o'
1927 1925 if ctx.node() in showparents:
1928 1926 char = '@'
1929 1927 elif ctx.obsolete():
1930 1928 char = 'x'
1931 1929 copies = None
1932 1930 if getrenamed and ctx.rev():
1933 1931 copies = []
1934 1932 for fn in ctx.files():
1935 1933 rename = getrenamed(fn, ctx.rev())
1936 1934 if rename:
1937 1935 copies.append((fn, rename[0]))
1938 1936 revmatchfn = None
1939 1937 if filematcher is not None:
1940 1938 revmatchfn = filematcher(ctx.rev())
1941 1939 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
1942 1940 lines = displayer.hunk.pop(rev).split('\n')
1943 1941 if not lines[-1]:
1944 1942 del lines[-1]
1945 1943 displayer.flush(rev)
1946 1944 edges = edgefn(type, char, lines, seen, rev, parents)
1947 1945 for type, char, lines, coldata in edges:
1948 1946 graphmod.ascii(ui, state, type, char, lines, coldata)
1949 1947 displayer.close()
1950 1948
1951 1949 def graphlog(ui, repo, *pats, **opts):
1952 1950 # Parameters are identical to log command ones
1953 1951 revs, expr, filematcher = getgraphlogrevs(repo, pats, opts)
1954 1952 revdag = graphmod.dagwalker(repo, revs)
1955 1953
1956 1954 getrenamed = None
1957 1955 if opts.get('copies'):
1958 1956 endrev = None
1959 1957 if opts.get('rev'):
1960 1958 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
1961 1959 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
1962 1960 displayer = show_changeset(ui, repo, opts, buffered=True)
1963 1961 showparents = [ctx.node() for ctx in repo[None].parents()]
1964 1962 displaygraph(ui, revdag, displayer, showparents,
1965 1963 graphmod.asciiedges, getrenamed, filematcher)
1966 1964
1967 1965 def checkunsupportedgraphflags(pats, opts):
1968 1966 for op in ["newest_first"]:
1969 1967 if op in opts and opts[op]:
1970 1968 raise util.Abort(_("-G/--graph option is incompatible with --%s")
1971 1969 % op.replace("_", "-"))
1972 1970
1973 1971 def graphrevs(repo, nodes, opts):
1974 1972 limit = loglimit(opts)
1975 1973 nodes.reverse()
1976 1974 if limit is not None:
1977 1975 nodes = nodes[:limit]
1978 1976 return graphmod.nodes(repo, nodes)
1979 1977
1980 1978 def add(ui, repo, match, prefix, explicitonly, **opts):
1981 1979 join = lambda f: os.path.join(prefix, f)
1982 1980 bad = []
1983 1981 oldbad = match.bad
1984 1982 match.bad = lambda x, y: bad.append(x) or oldbad(x, y)
1985 1983 names = []
1986 1984 wctx = repo[None]
1987 1985 cca = None
1988 1986 abort, warn = scmutil.checkportabilityalert(ui)
1989 1987 if abort or warn:
1990 1988 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
1991 1989 for f in wctx.walk(match):
1992 1990 exact = match.exact(f)
1993 1991 if exact or not explicitonly and f not in wctx and repo.wvfs.lexists(f):
1994 1992 if cca:
1995 1993 cca(f)
1996 1994 names.append(f)
1997 1995 if ui.verbose or not exact:
1998 1996 ui.status(_('adding %s\n') % match.rel(f))
1999 1997
2000 1998 for subpath in sorted(wctx.substate):
2001 1999 sub = wctx.sub(subpath)
2002 2000 try:
2003 2001 submatch = matchmod.narrowmatcher(subpath, match)
2004 2002 if opts.get('subrepos'):
2005 2003 bad.extend(sub.add(ui, submatch, prefix, False, **opts))
2006 2004 else:
2007 2005 bad.extend(sub.add(ui, submatch, prefix, True, **opts))
2008 2006 except error.LookupError:
2009 2007 ui.status(_("skipping missing subrepository: %s\n")
2010 2008 % join(subpath))
2011 2009
2012 2010 if not opts.get('dry_run'):
2013 2011 rejected = wctx.add(names, prefix)
2014 2012 bad.extend(f for f in rejected if f in match.files())
2015 2013 return bad
2016 2014
2017 2015 def forget(ui, repo, match, prefix, explicitonly):
2018 2016 join = lambda f: os.path.join(prefix, f)
2019 2017 bad = []
2020 2018 oldbad = match.bad
2021 2019 match.bad = lambda x, y: bad.append(x) or oldbad(x, y)
2022 2020 wctx = repo[None]
2023 2021 forgot = []
2024 2022 s = repo.status(match=match, clean=True)
2025 2023 forget = sorted(s[0] + s[1] + s[3] + s[6])
2026 2024 if explicitonly:
2027 2025 forget = [f for f in forget if match.exact(f)]
2028 2026
2029 2027 for subpath in sorted(wctx.substate):
2030 2028 sub = wctx.sub(subpath)
2031 2029 try:
2032 2030 submatch = matchmod.narrowmatcher(subpath, match)
2033 2031 subbad, subforgot = sub.forget(submatch, prefix)
2034 2032 bad.extend([subpath + '/' + f for f in subbad])
2035 2033 forgot.extend([subpath + '/' + f for f in subforgot])
2036 2034 except error.LookupError:
2037 2035 ui.status(_("skipping missing subrepository: %s\n")
2038 2036 % join(subpath))
2039 2037
2040 2038 if not explicitonly:
2041 2039 for f in match.files():
2042 2040 if f not in repo.dirstate and not repo.wvfs.isdir(f):
2043 2041 if f not in forgot:
2044 2042 if repo.wvfs.exists(f):
2045 2043 ui.warn(_('not removing %s: '
2046 2044 'file is already untracked\n')
2047 2045 % match.rel(f))
2048 2046 bad.append(f)
2049 2047
2050 2048 for f in forget:
2051 2049 if ui.verbose or not match.exact(f):
2052 2050 ui.status(_('removing %s\n') % match.rel(f))
2053 2051
2054 2052 rejected = wctx.forget(forget, prefix)
2055 2053 bad.extend(f for f in rejected if f in match.files())
2056 2054 forgot.extend(f for f in forget if f not in rejected)
2057 2055 return bad, forgot
2058 2056
2059 2057 def remove(ui, repo, m, prefix, after, force, subrepos):
2060 2058 join = lambda f: os.path.join(prefix, f)
2061 2059 ret = 0
2062 2060 s = repo.status(match=m, clean=True)
2063 2061 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
2064 2062
2065 2063 wctx = repo[None]
2066 2064
2067 2065 for subpath in sorted(wctx.substate):
2068 2066 def matchessubrepo(matcher, subpath):
2069 2067 if matcher.exact(subpath):
2070 2068 return True
2071 2069 for f in matcher.files():
2072 2070 if f.startswith(subpath):
2073 2071 return True
2074 2072 return False
2075 2073
2076 2074 if subrepos or matchessubrepo(m, subpath):
2077 2075 sub = wctx.sub(subpath)
2078 2076 try:
2079 2077 submatch = matchmod.narrowmatcher(subpath, m)
2080 2078 if sub.removefiles(submatch, prefix, after, force, subrepos):
2081 2079 ret = 1
2082 2080 except error.LookupError:
2083 2081 ui.status(_("skipping missing subrepository: %s\n")
2084 2082 % join(subpath))
2085 2083
2086 2084 # warn about failure to delete explicit files/dirs
2087 2085 for f in m.files():
2088 2086 def insubrepo():
2089 2087 for subpath in wctx.substate:
2090 2088 if f.startswith(subpath):
2091 2089 return True
2092 2090 return False
2093 2091
2094 2092 if f in repo.dirstate or f in wctx.dirs() or f == '.' or insubrepo():
2095 2093 continue
2096 2094
2097 2095 if repo.wvfs.exists(f):
2098 2096 if repo.wvfs.isdir(f):
2099 2097 ui.warn(_('not removing %s: no tracked files\n')
2100 2098 % m.rel(f))
2101 2099 else:
2102 2100 ui.warn(_('not removing %s: file is untracked\n')
2103 2101 % m.rel(f))
2104 2102 # missing files will generate a warning elsewhere
2105 2103 ret = 1
2106 2104
2107 2105 if force:
2108 2106 list = modified + deleted + clean + added
2109 2107 elif after:
2110 2108 list = deleted
2111 2109 for f in modified + added + clean:
2112 2110 ui.warn(_('not removing %s: file still exists\n') % m.rel(f))
2113 2111 ret = 1
2114 2112 else:
2115 2113 list = deleted + clean
2116 2114 for f in modified:
2117 2115 ui.warn(_('not removing %s: file is modified (use -f'
2118 2116 ' to force removal)\n') % m.rel(f))
2119 2117 ret = 1
2120 2118 for f in added:
2121 2119 ui.warn(_('not removing %s: file has been marked for add'
2122 2120 ' (use forget to undo)\n') % m.rel(f))
2123 2121 ret = 1
2124 2122
2125 2123 for f in sorted(list):
2126 2124 if ui.verbose or not m.exact(f):
2127 2125 ui.status(_('removing %s\n') % m.rel(f))
2128 2126
2129 2127 wlock = repo.wlock()
2130 2128 try:
2131 2129 if not after:
2132 2130 for f in list:
2133 2131 if f in added:
2134 2132 continue # we never unlink added files on remove
2135 2133 util.unlinkpath(repo.wjoin(f), ignoremissing=True)
2136 2134 repo[None].forget(list)
2137 2135 finally:
2138 2136 wlock.release()
2139 2137
2140 2138 return ret
2141 2139
2142 2140 def cat(ui, repo, ctx, matcher, prefix, **opts):
2143 2141 err = 1
2144 2142
2145 2143 def write(path):
2146 2144 fp = makefileobj(repo, opts.get('output'), ctx.node(),
2147 2145 pathname=os.path.join(prefix, path))
2148 2146 data = ctx[path].data()
2149 2147 if opts.get('decode'):
2150 2148 data = repo.wwritedata(path, data)
2151 2149 fp.write(data)
2152 2150 fp.close()
2153 2151
2154 2152 # Automation often uses hg cat on single files, so special case it
2155 2153 # for performance to avoid the cost of parsing the manifest.
2156 2154 if len(matcher.files()) == 1 and not matcher.anypats():
2157 2155 file = matcher.files()[0]
2158 2156 mf = repo.manifest
2159 2157 mfnode = ctx._changeset[0]
2160 2158 if mf.find(mfnode, file)[0]:
2161 2159 write(file)
2162 2160 return 0
2163 2161
2164 2162 # Don't warn about "missing" files that are really in subrepos
2165 2163 bad = matcher.bad
2166 2164
2167 2165 def badfn(path, msg):
2168 2166 for subpath in ctx.substate:
2169 2167 if path.startswith(subpath):
2170 2168 return
2171 2169 bad(path, msg)
2172 2170
2173 2171 matcher.bad = badfn
2174 2172
2175 2173 for abs in ctx.walk(matcher):
2176 2174 write(abs)
2177 2175 err = 0
2178 2176
2179 2177 matcher.bad = bad
2180 2178
2181 2179 for subpath in sorted(ctx.substate):
2182 2180 sub = ctx.sub(subpath)
2183 2181 try:
2184 2182 submatch = matchmod.narrowmatcher(subpath, matcher)
2185 2183
2186 2184 if not sub.cat(submatch, os.path.join(prefix, sub._path),
2187 2185 **opts):
2188 2186 err = 0
2189 2187 except error.RepoLookupError:
2190 2188 ui.status(_("skipping missing subrepository: %s\n")
2191 2189 % os.path.join(prefix, subpath))
2192 2190
2193 2191 return err
2194 2192
2195 2193 def commit(ui, repo, commitfunc, pats, opts):
2196 2194 '''commit the specified files or all outstanding changes'''
2197 2195 date = opts.get('date')
2198 2196 if date:
2199 2197 opts['date'] = util.parsedate(date)
2200 2198 message = logmessage(ui, opts)
2201 2199 matcher = scmutil.match(repo[None], pats, opts)
2202 2200
2203 2201 # extract addremove carefully -- this function can be called from a command
2204 2202 # that doesn't support addremove
2205 2203 if opts.get('addremove'):
2206 2204 if scmutil.addremove(repo, matcher, "", opts) != 0:
2207 2205 raise util.Abort(
2208 2206 _("failed to mark all new/missing files as added/removed"))
2209 2207
2210 2208 return commitfunc(ui, repo, message, matcher, opts)
2211 2209
2212 2210 def amend(ui, repo, commitfunc, old, extra, pats, opts):
2213 2211 # amend will reuse the existing user if not specified, but the obsolete
2214 2212 # marker creation requires that the current user's name is specified.
2215 2213 if obsolete._enabled:
2216 2214 ui.username() # raise exception if username not set
2217 2215
2218 2216 ui.note(_('amending changeset %s\n') % old)
2219 2217 base = old.p1()
2220 2218
2221 2219 wlock = lock = newid = None
2222 2220 try:
2223 2221 wlock = repo.wlock()
2224 2222 lock = repo.lock()
2225 2223 tr = repo.transaction('amend')
2226 2224 try:
2227 2225 # See if we got a message from -m or -l, if not, open the editor
2228 2226 # with the message of the changeset to amend
2229 2227 message = logmessage(ui, opts)
2230 2228 # ensure logfile does not conflict with later enforcement of the
2231 2229 # message. potential logfile content has been processed by
2232 2230 # `logmessage` anyway.
2233 2231 opts.pop('logfile')
2234 2232 # First, do a regular commit to record all changes in the working
2235 2233 # directory (if there are any)
2236 2234 ui.callhooks = False
2237 2235 currentbookmark = repo._bookmarkcurrent
2238 2236 try:
2239 2237 repo._bookmarkcurrent = None
2240 2238 opts['message'] = 'temporary amend commit for %s' % old
2241 2239 node = commit(ui, repo, commitfunc, pats, opts)
2242 2240 finally:
2243 2241 repo._bookmarkcurrent = currentbookmark
2244 2242 ui.callhooks = True
2245 2243 ctx = repo[node]
2246 2244
2247 2245 # Participating changesets:
2248 2246 #
2249 2247 # node/ctx o - new (intermediate) commit that contains changes
2250 2248 # | from working dir to go into amending commit
2251 2249 # | (or a workingctx if there were no changes)
2252 2250 # |
2253 2251 # old o - changeset to amend
2254 2252 # |
2255 2253 # base o - parent of amending changeset
2256 2254
2257 2255 # Update extra dict from amended commit (e.g. to preserve graft
2258 2256 # source)
2259 2257 extra.update(old.extra())
2260 2258
2261 2259 # Also update it from the intermediate commit or from the wctx
2262 2260 extra.update(ctx.extra())
2263 2261
2264 2262 if len(old.parents()) > 1:
2265 2263 # ctx.files() isn't reliable for merges, so fall back to the
2266 2264 # slower repo.status() method
2267 2265 files = set([fn for st in repo.status(base, old)[:3]
2268 2266 for fn in st])
2269 2267 else:
2270 2268 files = set(old.files())
2271 2269
2272 2270 # Second, we use either the commit we just did, or if there were no
2273 2271 # changes the parent of the working directory as the version of the
2274 2272 # files in the final amend commit
2275 2273 if node:
2276 2274 ui.note(_('copying changeset %s to %s\n') % (ctx, base))
2277 2275
2278 2276 user = ctx.user()
2279 2277 date = ctx.date()
2280 2278 # Recompute copies (avoid recording a -> b -> a)
2281 2279 copied = copies.pathcopies(base, ctx)
2282 2280
2283 2281 # Prune files which were reverted by the updates: if old
2284 2282 # introduced file X and our intermediate commit, node,
2285 2283 # renamed that file, then those two files are the same and
2286 2284 # we can discard X from our list of files. Likewise if X
2287 2285 # was deleted, it's no longer relevant
2288 2286 files.update(ctx.files())
2289 2287
2290 2288 def samefile(f):
2291 2289 if f in ctx.manifest():
2292 2290 a = ctx.filectx(f)
2293 2291 if f in base.manifest():
2294 2292 b = base.filectx(f)
2295 2293 return (not a.cmp(b)
2296 2294 and a.flags() == b.flags())
2297 2295 else:
2298 2296 return False
2299 2297 else:
2300 2298 return f not in base.manifest()
2301 2299 files = [f for f in files if not samefile(f)]
2302 2300
2303 2301 def filectxfn(repo, ctx_, path):
2304 2302 try:
2305 2303 fctx = ctx[path]
2306 2304 flags = fctx.flags()
2307 2305 mctx = context.memfilectx(repo,
2308 2306 fctx.path(), fctx.data(),
2309 2307 islink='l' in flags,
2310 2308 isexec='x' in flags,
2311 2309 copied=copied.get(path))
2312 2310 return mctx
2313 2311 except KeyError:
2314 2312 return None
2315 2313 else:
2316 2314 ui.note(_('copying changeset %s to %s\n') % (old, base))
2317 2315
2318 2316 # Use version of files as in the old cset
2319 2317 def filectxfn(repo, ctx_, path):
2320 2318 try:
2321 2319 return old.filectx(path)
2322 2320 except KeyError:
2323 2321 return None
2324 2322
2325 2323 user = opts.get('user') or old.user()
2326 2324 date = opts.get('date') or old.date()
2327 2325 editform = mergeeditform(old, 'commit.amend')
2328 2326 editor = getcommiteditor(editform=editform, **opts)
2329 2327 if not message:
2330 2328 editor = getcommiteditor(edit=True, editform=editform)
2331 2329 message = old.description()
2332 2330
2333 2331 pureextra = extra.copy()
2334 2332 extra['amend_source'] = old.hex()
2335 2333
2336 2334 new = context.memctx(repo,
2337 2335 parents=[base.node(), old.p2().node()],
2338 2336 text=message,
2339 2337 files=files,
2340 2338 filectxfn=filectxfn,
2341 2339 user=user,
2342 2340 date=date,
2343 2341 extra=extra,
2344 2342 editor=editor)
2345 2343
2346 2344 newdesc = changelog.stripdesc(new.description())
2347 2345 if ((not node)
2348 2346 and newdesc == old.description()
2349 2347 and user == old.user()
2350 2348 and date == old.date()
2351 2349 and pureextra == old.extra()):
2352 2350 # nothing changed. continuing here would create a new node
2353 2351 # anyway because of the amend_source noise.
2354 2352 #
2355 2353 # This not what we expect from amend.
2356 2354 return old.node()
2357 2355
2358 2356 ph = repo.ui.config('phases', 'new-commit', phases.draft)
2359 2357 try:
2360 2358 if opts.get('secret'):
2361 2359 commitphase = 'secret'
2362 2360 else:
2363 2361 commitphase = old.phase()
2364 2362 repo.ui.setconfig('phases', 'new-commit', commitphase, 'amend')
2365 2363 newid = repo.commitctx(new)
2366 2364 finally:
2367 2365 repo.ui.setconfig('phases', 'new-commit', ph, 'amend')
2368 2366 if newid != old.node():
2369 2367 # Reroute the working copy parent to the new changeset
2370 2368 repo.setparents(newid, nullid)
2371 2369
2372 2370 # Move bookmarks from old parent to amend commit
2373 2371 bms = repo.nodebookmarks(old.node())
2374 2372 if bms:
2375 2373 marks = repo._bookmarks
2376 2374 for bm in bms:
2377 2375 marks[bm] = newid
2378 2376 marks.write()
2379 2377 #commit the whole amend process
2380 2378 createmarkers = obsolete.isenabled(repo, obsolete.createmarkersopt)
2381 2379 if createmarkers and newid != old.node():
2382 2380 # mark the new changeset as successor of the rewritten one
2383 2381 new = repo[newid]
2384 2382 obs = [(old, (new,))]
2385 2383 if node:
2386 2384 obs.append((ctx, ()))
2387 2385
2388 2386 obsolete.createmarkers(repo, obs)
2389 2387 tr.close()
2390 2388 finally:
2391 2389 tr.release()
2392 2390 if not createmarkers and newid != old.node():
2393 2391 # Strip the intermediate commit (if there was one) and the amended
2394 2392 # commit
2395 2393 if node:
2396 2394 ui.note(_('stripping intermediate changeset %s\n') % ctx)
2397 2395 ui.note(_('stripping amended changeset %s\n') % old)
2398 2396 repair.strip(ui, repo, old.node(), topic='amend-backup')
2399 2397 finally:
2400 2398 if newid is None:
2401 2399 repo.dirstate.invalidate()
2402 2400 lockmod.release(lock, wlock)
2403 2401 return newid
2404 2402
2405 2403 def commiteditor(repo, ctx, subs, editform=''):
2406 2404 if ctx.description():
2407 2405 return ctx.description()
2408 2406 return commitforceeditor(repo, ctx, subs, editform=editform)
2409 2407
2410 2408 def commitforceeditor(repo, ctx, subs, finishdesc=None, extramsg=None,
2411 2409 editform=''):
2412 2410 if not extramsg:
2413 2411 extramsg = _("Leave message empty to abort commit.")
2414 2412
2415 2413 forms = [e for e in editform.split('.') if e]
2416 2414 forms.insert(0, 'changeset')
2417 2415 while forms:
2418 2416 tmpl = repo.ui.config('committemplate', '.'.join(forms))
2419 2417 if tmpl:
2420 2418 committext = buildcommittemplate(repo, ctx, subs, extramsg, tmpl)
2421 2419 break
2422 2420 forms.pop()
2423 2421 else:
2424 2422 committext = buildcommittext(repo, ctx, subs, extramsg)
2425 2423
2426 2424 # run editor in the repository root
2427 2425 olddir = os.getcwd()
2428 2426 os.chdir(repo.root)
2429 2427 text = repo.ui.edit(committext, ctx.user(), ctx.extra(), editform=editform)
2430 2428 text = re.sub("(?m)^HG:.*(\n|$)", "", text)
2431 2429 os.chdir(olddir)
2432 2430
2433 2431 if finishdesc:
2434 2432 text = finishdesc(text)
2435 2433 if not text.strip():
2436 2434 raise util.Abort(_("empty commit message"))
2437 2435
2438 2436 return text
2439 2437
2440 2438 def buildcommittemplate(repo, ctx, subs, extramsg, tmpl):
2441 2439 ui = repo.ui
2442 2440 tmpl, mapfile = gettemplate(ui, tmpl, None)
2443 2441
2444 2442 try:
2445 2443 t = changeset_templater(ui, repo, None, {}, tmpl, mapfile, False)
2446 2444 except SyntaxError, inst:
2447 2445 raise util.Abort(inst.args[0])
2448 2446
2449 2447 for k, v in repo.ui.configitems('committemplate'):
2450 2448 if k != 'changeset':
2451 2449 t.t.cache[k] = v
2452 2450
2453 2451 if not extramsg:
2454 2452 extramsg = '' # ensure that extramsg is string
2455 2453
2456 2454 ui.pushbuffer()
2457 2455 t.show(ctx, extramsg=extramsg)
2458 2456 return ui.popbuffer()
2459 2457
2460 2458 def buildcommittext(repo, ctx, subs, extramsg):
2461 2459 edittext = []
2462 2460 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
2463 2461 if ctx.description():
2464 2462 edittext.append(ctx.description())
2465 2463 edittext.append("")
2466 2464 edittext.append("") # Empty line between message and comments.
2467 2465 edittext.append(_("HG: Enter commit message."
2468 2466 " Lines beginning with 'HG:' are removed."))
2469 2467 edittext.append("HG: %s" % extramsg)
2470 2468 edittext.append("HG: --")
2471 2469 edittext.append(_("HG: user: %s") % ctx.user())
2472 2470 if ctx.p2():
2473 2471 edittext.append(_("HG: branch merge"))
2474 2472 if ctx.branch():
2475 2473 edittext.append(_("HG: branch '%s'") % ctx.branch())
2476 2474 if bookmarks.iscurrent(repo):
2477 2475 edittext.append(_("HG: bookmark '%s'") % repo._bookmarkcurrent)
2478 2476 edittext.extend([_("HG: subrepo %s") % s for s in subs])
2479 2477 edittext.extend([_("HG: added %s") % f for f in added])
2480 2478 edittext.extend([_("HG: changed %s") % f for f in modified])
2481 2479 edittext.extend([_("HG: removed %s") % f for f in removed])
2482 2480 if not added and not modified and not removed:
2483 2481 edittext.append(_("HG: no files changed"))
2484 2482 edittext.append("")
2485 2483
2486 2484 return "\n".join(edittext)
2487 2485
2488 2486 def commitstatus(repo, node, branch, bheads=None, opts={}):
2489 2487 ctx = repo[node]
2490 2488 parents = ctx.parents()
2491 2489
2492 2490 if (not opts.get('amend') and bheads and node not in bheads and not
2493 2491 [x for x in parents if x.node() in bheads and x.branch() == branch]):
2494 2492 repo.ui.status(_('created new head\n'))
2495 2493 # The message is not printed for initial roots. For the other
2496 2494 # changesets, it is printed in the following situations:
2497 2495 #
2498 2496 # Par column: for the 2 parents with ...
2499 2497 # N: null or no parent
2500 2498 # B: parent is on another named branch
2501 2499 # C: parent is a regular non head changeset
2502 2500 # H: parent was a branch head of the current branch
2503 2501 # Msg column: whether we print "created new head" message
2504 2502 # In the following, it is assumed that there already exists some
2505 2503 # initial branch heads of the current branch, otherwise nothing is
2506 2504 # printed anyway.
2507 2505 #
2508 2506 # Par Msg Comment
2509 2507 # N N y additional topo root
2510 2508 #
2511 2509 # B N y additional branch root
2512 2510 # C N y additional topo head
2513 2511 # H N n usual case
2514 2512 #
2515 2513 # B B y weird additional branch root
2516 2514 # C B y branch merge
2517 2515 # H B n merge with named branch
2518 2516 #
2519 2517 # C C y additional head from merge
2520 2518 # C H n merge with a head
2521 2519 #
2522 2520 # H H n head merge: head count decreases
2523 2521
2524 2522 if not opts.get('close_branch'):
2525 2523 for r in parents:
2526 2524 if r.closesbranch() and r.branch() == branch:
2527 2525 repo.ui.status(_('reopening closed branch head %d\n') % r)
2528 2526
2529 2527 if repo.ui.debugflag:
2530 2528 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
2531 2529 elif repo.ui.verbose:
2532 2530 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
2533 2531
2534 2532 def revert(ui, repo, ctx, parents, *pats, **opts):
2535 2533 parent, p2 = parents
2536 2534 node = ctx.node()
2537 2535
2538 2536 mf = ctx.manifest()
2539 2537 if node == p2:
2540 2538 parent = p2
2541 2539 if node == parent:
2542 2540 pmf = mf
2543 2541 else:
2544 2542 pmf = None
2545 2543
2546 2544 # need all matching names in dirstate and manifest of target rev,
2547 2545 # so have to walk both. do not print errors if files exist in one
2548 2546 # but not other.
2549 2547
2550 2548 # `names` is a mapping for all elements in working copy and target revision
2551 2549 # The mapping is in the form:
2552 2550 # <asb path in repo> -> (<path from CWD>, <exactly specified by matcher?>)
2553 2551 names = {}
2554 2552
2555 2553 wlock = repo.wlock()
2556 2554 try:
2557 2555 ## filling of the `names` mapping
2558 2556 # walk dirstate to fill `names`
2559 2557
2560 2558 m = scmutil.match(repo[None], pats, opts)
2561 2559 if not m.always() or node != parent:
2562 2560 m.bad = lambda x, y: False
2563 2561 for abs in repo.walk(m):
2564 2562 names[abs] = m.rel(abs), m.exact(abs)
2565 2563
2566 2564 # walk target manifest to fill `names`
2567 2565
2568 2566 def badfn(path, msg):
2569 2567 if path in names:
2570 2568 return
2571 2569 if path in ctx.substate:
2572 2570 return
2573 2571 path_ = path + '/'
2574 2572 for f in names:
2575 2573 if f.startswith(path_):
2576 2574 return
2577 2575 ui.warn("%s: %s\n" % (m.rel(path), msg))
2578 2576
2579 2577 m = scmutil.match(ctx, pats, opts)
2580 2578 m.bad = badfn
2581 2579 for abs in ctx.walk(m):
2582 2580 if abs not in names:
2583 2581 names[abs] = m.rel(abs), m.exact(abs)
2584 2582
2585 2583 # Find status of all file in `names`.
2586 2584 m = scmutil.matchfiles(repo, names)
2587 2585
2588 2586 changes = repo.status(node1=node, match=m,
2589 2587 unknown=True, ignored=True, clean=True)
2590 2588 else:
2591 2589 changes = repo.status(match=m)
2592 2590 for kind in changes:
2593 2591 for abs in kind:
2594 2592 names[abs] = m.rel(abs), m.exact(abs)
2595 2593
2596 2594 m = scmutil.matchfiles(repo, names)
2597 2595
2598 2596 modified = set(changes.modified)
2599 2597 added = set(changes.added)
2600 2598 removed = set(changes.removed)
2601 2599 _deleted = set(changes.deleted)
2602 2600 unknown = set(changes.unknown)
2603 2601 unknown.update(changes.ignored)
2604 2602 clean = set(changes.clean)
2605 2603 modadded = set()
2606 2604
2607 2605 # split between files known in target manifest and the others
2608 2606 smf = set(mf)
2609 2607
2610 2608 # determine the exact nature of the deleted changesets
2611 2609 deladded = _deleted - smf
2612 2610 deleted = _deleted - deladded
2613 2611
2614 2612 # We need to account for the state of file in the dirstate.
2615 2613 #
2616 2614 # Even, when we revert against something else than parent. This will
2617 2615 # slightly alter the behavior of revert (doing back up or not, delete
2618 2616 # or just forget etc).
2619 2617 if parent == node:
2620 2618 dsmodified = modified
2621 2619 dsadded = added
2622 2620 dsremoved = removed
2623 2621 # store all local modifications, useful later for rename detection
2624 2622 localchanges = dsmodified | dsadded
2625 2623 modified, added, removed = set(), set(), set()
2626 2624 else:
2627 2625 changes = repo.status(node1=parent, match=m)
2628 2626 dsmodified = set(changes.modified)
2629 2627 dsadded = set(changes.added)
2630 2628 dsremoved = set(changes.removed)
2631 2629 # store all local modifications, useful later for rename detection
2632 2630 localchanges = dsmodified | dsadded
2633 2631
2634 2632 # only take into account for removes between wc and target
2635 2633 clean |= dsremoved - removed
2636 2634 dsremoved &= removed
2637 2635 # distinct between dirstate remove and other
2638 2636 removed -= dsremoved
2639 2637
2640 2638 modadded = added & dsmodified
2641 2639 added -= modadded
2642 2640
2643 2641 # tell newly modified apart.
2644 2642 dsmodified &= modified
2645 2643 dsmodified |= modified & dsadded # dirstate added may needs backup
2646 2644 modified -= dsmodified
2647 2645
2648 2646 # We need to wait for some post-processing to update this set
2649 2647 # before making the distinction. The dirstate will be used for
2650 2648 # that purpose.
2651 2649 dsadded = added
2652 2650
2653 2651 # in case of merge, files that are actually added can be reported as
2654 2652 # modified, we need to post process the result
2655 2653 if p2 != nullid:
2656 2654 if pmf is None:
2657 2655 # only need parent manifest in the merge case,
2658 2656 # so do not read by default
2659 2657 pmf = repo[parent].manifest()
2660 2658 mergeadd = dsmodified - set(pmf)
2661 2659 dsadded |= mergeadd
2662 2660 dsmodified -= mergeadd
2663 2661
2664 2662 # if f is a rename, update `names` to also revert the source
2665 2663 cwd = repo.getcwd()
2666 2664 for f in localchanges:
2667 2665 src = repo.dirstate.copied(f)
2668 2666 # XXX should we check for rename down to target node?
2669 2667 if src and src not in names and repo.dirstate[src] == 'r':
2670 2668 dsremoved.add(src)
2671 2669 names[src] = (repo.pathto(src, cwd), True)
2672 2670
2673 2671 # distinguish between file to forget and the other
2674 2672 added = set()
2675 2673 for abs in dsadded:
2676 2674 if repo.dirstate[abs] != 'a':
2677 2675 added.add(abs)
2678 2676 dsadded -= added
2679 2677
2680 2678 for abs in deladded:
2681 2679 if repo.dirstate[abs] == 'a':
2682 2680 dsadded.add(abs)
2683 2681 deladded -= dsadded
2684 2682
2685 2683 # For files marked as removed, we check if an unknown file is present at
2686 2684 # the same path. If a such file exists it may need to be backed up.
2687 2685 # Making the distinction at this stage helps have simpler backup
2688 2686 # logic.
2689 2687 removunk = set()
2690 2688 for abs in removed:
2691 2689 target = repo.wjoin(abs)
2692 2690 if os.path.lexists(target):
2693 2691 removunk.add(abs)
2694 2692 removed -= removunk
2695 2693
2696 2694 dsremovunk = set()
2697 2695 for abs in dsremoved:
2698 2696 target = repo.wjoin(abs)
2699 2697 if os.path.lexists(target):
2700 2698 dsremovunk.add(abs)
2701 2699 dsremoved -= dsremovunk
2702 2700
2703 2701 # action to be actually performed by revert
2704 2702 # (<list of file>, message>) tuple
2705 2703 actions = {'revert': ([], _('reverting %s\n')),
2706 2704 'add': ([], _('adding %s\n')),
2707 2705 'remove': ([], _('removing %s\n')),
2708 2706 'drop': ([], _('removing %s\n')),
2709 2707 'forget': ([], _('forgetting %s\n')),
2710 2708 'undelete': ([], _('undeleting %s\n')),
2711 2709 'noop': (None, _('no changes needed to %s\n')),
2712 2710 'unknown': (None, _('file not managed: %s\n')),
2713 2711 }
2714 2712
2715 2713 # "constant" that convey the backup strategy.
2716 2714 # All set to `discard` if `no-backup` is set do avoid checking
2717 2715 # no_backup lower in the code.
2718 2716 # These values are ordered for comparison purposes
2719 2717 backup = 2 # unconditionally do backup
2720 2718 check = 1 # check if the existing file differs from target
2721 2719 discard = 0 # never do backup
2722 2720 if opts.get('no_backup'):
2723 2721 backup = check = discard
2724 2722
2725 2723 backupanddel = actions['remove']
2726 2724 if not opts.get('no_backup'):
2727 2725 backupanddel = actions['drop']
2728 2726
2729 2727 disptable = (
2730 2728 # dispatch table:
2731 2729 # file state
2732 2730 # action
2733 2731 # make backup
2734 2732
2735 2733 ## Sets that results that will change file on disk
2736 2734 # Modified compared to target, no local change
2737 2735 (modified, actions['revert'], discard),
2738 2736 # Modified compared to target, but local file is deleted
2739 2737 (deleted, actions['revert'], discard),
2740 2738 # Modified compared to target, local change
2741 2739 (dsmodified, actions['revert'], backup),
2742 2740 # Added since target
2743 2741 (added, actions['remove'], discard),
2744 2742 # Added in working directory
2745 2743 (dsadded, actions['forget'], discard),
2746 2744 # Added since target, have local modification
2747 2745 (modadded, backupanddel, backup),
2748 2746 # Added since target but file is missing in working directory
2749 2747 (deladded, actions['drop'], discard),
2750 2748 # Removed since target, before working copy parent
2751 2749 (removed, actions['add'], discard),
2752 2750 # Same as `removed` but an unknown file exists at the same path
2753 2751 (removunk, actions['add'], check),
2754 2752 # Removed since targe, marked as such in working copy parent
2755 2753 (dsremoved, actions['undelete'], discard),
2756 2754 # Same as `dsremoved` but an unknown file exists at the same path
2757 2755 (dsremovunk, actions['undelete'], check),
2758 2756 ## the following sets does not result in any file changes
2759 2757 # File with no modification
2760 2758 (clean, actions['noop'], discard),
2761 2759 # Existing file, not tracked anywhere
2762 2760 (unknown, actions['unknown'], discard),
2763 2761 )
2764 2762
2765 2763 wctx = repo[None]
2766 2764 for abs, (rel, exact) in sorted(names.items()):
2767 2765 # target file to be touch on disk (relative to cwd)
2768 2766 target = repo.wjoin(abs)
2769 2767 # search the entry in the dispatch table.
2770 2768 # if the file is in any of these sets, it was touched in the working
2771 2769 # directory parent and we are sure it needs to be reverted.
2772 2770 for table, (xlist, msg), dobackup in disptable:
2773 2771 if abs not in table:
2774 2772 continue
2775 2773 if xlist is not None:
2776 2774 xlist.append(abs)
2777 2775 if dobackup and (backup <= dobackup
2778 2776 or wctx[abs].cmp(ctx[abs])):
2779 2777 bakname = "%s.orig" % rel
2780 2778 ui.note(_('saving current version of %s as %s\n') %
2781 2779 (rel, bakname))
2782 2780 if not opts.get('dry_run'):
2783 2781 util.rename(target, bakname)
2784 2782 if ui.verbose or not exact:
2785 2783 if not isinstance(msg, basestring):
2786 2784 msg = msg(abs)
2787 2785 ui.status(msg % rel)
2788 2786 elif exact:
2789 2787 ui.warn(msg % rel)
2790 2788 break
2791 2789
2792 2790
2793 2791 if not opts.get('dry_run'):
2794 2792 needdata = ('revert', 'add', 'undelete')
2795 2793 _revertprefetch(repo, ctx, *[actions[name][0] for name in needdata])
2796 2794
2797 2795 _performrevert(repo, parents, ctx, actions)
2798 2796
2799 2797 # get the list of subrepos that must be reverted
2800 2798 subrepomatch = scmutil.match(ctx, pats, opts)
2801 2799 targetsubs = sorted(s for s in ctx.substate if subrepomatch(s))
2802 2800
2803 2801 if targetsubs:
2804 2802 # Revert the subrepos on the revert list
2805 2803 for sub in targetsubs:
2806 2804 ctx.sub(sub).revert(ctx.substate[sub], *pats, **opts)
2807 2805 finally:
2808 2806 wlock.release()
2809 2807
2810 2808 def _revertprefetch(repo, ctx, *files):
2811 2809 """Let extension changing the storage layer prefetch content"""
2812 2810 pass
2813 2811
2814 2812 def _performrevert(repo, parents, ctx, actions):
2815 2813 """function that actually perform all the actions computed for revert
2816 2814
2817 2815 This is an independent function to let extension to plug in and react to
2818 2816 the imminent revert.
2819 2817
2820 2818 Make sure you have the working directory locked when calling this function.
2821 2819 """
2822 2820 parent, p2 = parents
2823 2821 node = ctx.node()
2824 2822 def checkout(f):
2825 2823 fc = ctx[f]
2826 2824 repo.wwrite(f, fc.data(), fc.flags())
2827 2825
2828 2826 audit_path = pathutil.pathauditor(repo.root)
2829 2827 for f in actions['forget'][0]:
2830 2828 repo.dirstate.drop(f)
2831 2829 for f in actions['remove'][0]:
2832 2830 audit_path(f)
2833 2831 util.unlinkpath(repo.wjoin(f))
2834 2832 repo.dirstate.remove(f)
2835 2833 for f in actions['drop'][0]:
2836 2834 audit_path(f)
2837 2835 repo.dirstate.remove(f)
2838 2836
2839 2837 normal = None
2840 2838 if node == parent:
2841 2839 # We're reverting to our parent. If possible, we'd like status
2842 2840 # to report the file as clean. We have to use normallookup for
2843 2841 # merges to avoid losing information about merged/dirty files.
2844 2842 if p2 != nullid:
2845 2843 normal = repo.dirstate.normallookup
2846 2844 else:
2847 2845 normal = repo.dirstate.normal
2848 2846 for f in actions['revert'][0]:
2849 2847 checkout(f)
2850 2848 if normal:
2851 2849 normal(f)
2852 2850
2853 2851 for f in actions['add'][0]:
2854 2852 checkout(f)
2855 2853 repo.dirstate.add(f)
2856 2854
2857 2855 normal = repo.dirstate.normallookup
2858 2856 if node == parent and p2 == nullid:
2859 2857 normal = repo.dirstate.normal
2860 2858 for f in actions['undelete'][0]:
2861 2859 checkout(f)
2862 2860 normal(f)
2863 2861
2864 2862 copied = copies.pathcopies(repo[parent], ctx)
2865 2863
2866 2864 for f in actions['add'][0] + actions['undelete'][0] + actions['revert'][0]:
2867 2865 if f in copied:
2868 2866 repo.dirstate.copy(copied[f], f)
2869 2867
2870 2868 def command(table):
2871 2869 """Returns a function object to be used as a decorator for making commands.
2872 2870
2873 2871 This function receives a command table as its argument. The table should
2874 2872 be a dict.
2875 2873
2876 2874 The returned function can be used as a decorator for adding commands
2877 2875 to that command table. This function accepts multiple arguments to define
2878 2876 a command.
2879 2877
2880 2878 The first argument is the command name.
2881 2879
2882 2880 The options argument is an iterable of tuples defining command arguments.
2883 2881 See ``mercurial.fancyopts.fancyopts()`` for the format of each tuple.
2884 2882
2885 2883 The synopsis argument defines a short, one line summary of how to use the
2886 2884 command. This shows up in the help output.
2887 2885
2888 2886 The norepo argument defines whether the command does not require a
2889 2887 local repository. Most commands operate against a repository, thus the
2890 2888 default is False.
2891 2889
2892 2890 The optionalrepo argument defines whether the command optionally requires
2893 2891 a local repository.
2894 2892
2895 2893 The inferrepo argument defines whether to try to find a repository from the
2896 2894 command line arguments. If True, arguments will be examined for potential
2897 2895 repository locations. See ``findrepo()``. If a repository is found, it
2898 2896 will be used.
2899 2897 """
2900 2898 def cmd(name, options=(), synopsis=None, norepo=False, optionalrepo=False,
2901 2899 inferrepo=False):
2902 2900 def decorator(func):
2903 2901 if synopsis:
2904 2902 table[name] = func, list(options), synopsis
2905 2903 else:
2906 2904 table[name] = func, list(options)
2907 2905
2908 2906 if norepo:
2909 2907 # Avoid import cycle.
2910 2908 import commands
2911 2909 commands.norepo += ' %s' % ' '.join(parsealiases(name))
2912 2910
2913 2911 if optionalrepo:
2914 2912 import commands
2915 2913 commands.optionalrepo += ' %s' % ' '.join(parsealiases(name))
2916 2914
2917 2915 if inferrepo:
2918 2916 import commands
2919 2917 commands.inferrepo += ' %s' % ' '.join(parsealiases(name))
2920 2918
2921 2919 return func
2922 2920 return decorator
2923 2921
2924 2922 return cmd
2925 2923
2926 2924 # a list of (ui, repo, otherpeer, opts, missing) functions called by
2927 2925 # commands.outgoing. "missing" is "missing" of the result of
2928 2926 # "findcommonoutgoing()"
2929 2927 outgoinghooks = util.hooks()
2930 2928
2931 2929 # a list of (ui, repo) functions called by commands.summary
2932 2930 summaryhooks = util.hooks()
2933 2931
2934 2932 # a list of (ui, repo, opts, changes) functions called by commands.summary.
2935 2933 #
2936 2934 # functions should return tuple of booleans below, if 'changes' is None:
2937 2935 # (whether-incomings-are-needed, whether-outgoings-are-needed)
2938 2936 #
2939 2937 # otherwise, 'changes' is a tuple of tuples below:
2940 2938 # - (sourceurl, sourcebranch, sourcepeer, incoming)
2941 2939 # - (desturl, destbranch, destpeer, outgoing)
2942 2940 summaryremotehooks = util.hooks()
2943 2941
2944 2942 # A list of state files kept by multistep operations like graft.
2945 2943 # Since graft cannot be aborted, it is considered 'clearable' by update.
2946 2944 # note: bisect is intentionally excluded
2947 2945 # (state file, clearable, allowcommit, error, hint)
2948 2946 unfinishedstates = [
2949 2947 ('graftstate', True, False, _('graft in progress'),
2950 2948 _("use 'hg graft --continue' or 'hg update' to abort")),
2951 2949 ('updatestate', True, False, _('last update was interrupted'),
2952 2950 _("use 'hg update' to get a consistent checkout"))
2953 2951 ]
2954 2952
2955 2953 def checkunfinished(repo, commit=False):
2956 2954 '''Look for an unfinished multistep operation, like graft, and abort
2957 2955 if found. It's probably good to check this right before
2958 2956 bailifchanged().
2959 2957 '''
2960 2958 for f, clearable, allowcommit, msg, hint in unfinishedstates:
2961 2959 if commit and allowcommit:
2962 2960 continue
2963 2961 if repo.vfs.exists(f):
2964 2962 raise util.Abort(msg, hint=hint)
2965 2963
2966 2964 def clearunfinished(repo):
2967 2965 '''Check for unfinished operations (as above), and clear the ones
2968 2966 that are clearable.
2969 2967 '''
2970 2968 for f, clearable, allowcommit, msg, hint in unfinishedstates:
2971 2969 if not clearable and repo.vfs.exists(f):
2972 2970 raise util.Abort(msg, hint=hint)
2973 2971 for f, clearable, allowcommit, msg, hint in unfinishedstates:
2974 2972 if clearable and repo.vfs.exists(f):
2975 2973 util.unlink(repo.join(f))
General Comments 0
You need to be logged in to leave comments. Login now