##// END OF EJS Templates
commands: add revset support to most commands
Matt Mackall -
r12925:6eab8f0d default
parent child Browse files
Show More
@@ -1,1365 +1,1370 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, glob, tempfile
11 11 import util, templater, patch, error, encoding, templatekw
12 12 import match as matchmod
13 13 import similar, revset, subrepo
14 14
15 15 revrangesep = ':'
16 16
17 17 def parsealiases(cmd):
18 18 return cmd.lstrip("^").split("|")
19 19
20 20 def findpossible(cmd, table, strict=False):
21 21 """
22 22 Return cmd -> (aliases, command table entry)
23 23 for each matching command.
24 24 Return debug commands (or their aliases) only if no normal command matches.
25 25 """
26 26 choice = {}
27 27 debugchoice = {}
28 28 for e in table.keys():
29 29 aliases = parsealiases(e)
30 30 found = None
31 31 if cmd in aliases:
32 32 found = cmd
33 33 elif not strict:
34 34 for a in aliases:
35 35 if a.startswith(cmd):
36 36 found = a
37 37 break
38 38 if found is not None:
39 39 if aliases[0].startswith("debug") or found.startswith("debug"):
40 40 debugchoice[found] = (aliases, table[e])
41 41 else:
42 42 choice[found] = (aliases, table[e])
43 43
44 44 if not choice and debugchoice:
45 45 choice = debugchoice
46 46
47 47 return choice
48 48
49 49 def findcmd(cmd, table, strict=True):
50 50 """Return (aliases, command table entry) for command string."""
51 51 choice = findpossible(cmd, table, strict)
52 52
53 53 if cmd in choice:
54 54 return choice[cmd]
55 55
56 56 if len(choice) > 1:
57 57 clist = choice.keys()
58 58 clist.sort()
59 59 raise error.AmbiguousCommand(cmd, clist)
60 60
61 61 if choice:
62 62 return choice.values()[0]
63 63
64 64 raise error.UnknownCommand(cmd)
65 65
66 66 def findrepo(p):
67 67 while not os.path.isdir(os.path.join(p, ".hg")):
68 68 oldp, p = p, os.path.dirname(p)
69 69 if p == oldp:
70 70 return None
71 71
72 72 return p
73 73
74 74 def bail_if_changed(repo):
75 75 if repo.dirstate.parents()[1] != nullid:
76 76 raise util.Abort(_('outstanding uncommitted merge'))
77 77 modified, added, removed, deleted = repo.status()[:4]
78 78 if modified or added or removed or deleted:
79 79 raise util.Abort(_("outstanding uncommitted changes"))
80 80
81 81 def logmessage(opts):
82 82 """ get the log message according to -m and -l option """
83 83 message = opts.get('message')
84 84 logfile = opts.get('logfile')
85 85
86 86 if message and logfile:
87 87 raise util.Abort(_('options --message and --logfile are mutually '
88 88 'exclusive'))
89 89 if not message and logfile:
90 90 try:
91 91 if logfile == '-':
92 92 message = sys.stdin.read()
93 93 else:
94 94 message = open(logfile).read()
95 95 except IOError, inst:
96 96 raise util.Abort(_("can't read commit message '%s': %s") %
97 97 (logfile, inst.strerror))
98 98 return message
99 99
100 100 def loglimit(opts):
101 101 """get the log limit according to option -l/--limit"""
102 102 limit = opts.get('limit')
103 103 if limit:
104 104 try:
105 105 limit = int(limit)
106 106 except ValueError:
107 107 raise util.Abort(_('limit must be a positive integer'))
108 108 if limit <= 0:
109 109 raise util.Abort(_('limit must be positive'))
110 110 else:
111 111 limit = None
112 112 return limit
113 113
114 114 def revsingle(repo, revspec, default='.'):
115 115 if not revspec:
116 116 return repo[default]
117 117
118 118 l = revrange(repo, [revspec])
119 119 if len(l) < 1:
120 120 raise util.Abort(_('empty revision set'))
121 121 return repo[l[-1]]
122 122
123 123 def revpair(repo, revs):
124 124 if not revs:
125 125 return repo.dirstate.parents()[0], None
126 126
127 127 l = revrange(repo, revs)
128 128
129 129 if len(l) == 0:
130 130 return repo.dirstate.parents()[0], None
131 131
132 132 if len(l) == 1:
133 133 return repo.lookup(l[0]), None
134 134
135 135 return repo.lookup(l[0]), repo.lookup(l[-1])
136 136
137 137 def revrange(repo, revs):
138 138 """Yield revision as strings from a list of revision specifications."""
139 139
140 140 def revfix(repo, val, defval):
141 141 if not val and val != 0 and defval is not None:
142 142 return defval
143 143 return repo.changelog.rev(repo.lookup(val))
144 144
145 145 seen, l = set(), []
146 146 for spec in revs:
147 147 # attempt to parse old-style ranges first to deal with
148 148 # things like old-tag which contain query metacharacters
149 149 try:
150 if isinstance(spec, int):
151 seen.add(spec)
152 l.append(spec)
153 continue
154
150 155 if revrangesep in spec:
151 156 start, end = spec.split(revrangesep, 1)
152 157 start = revfix(repo, start, 0)
153 158 end = revfix(repo, end, len(repo) - 1)
154 159 step = start > end and -1 or 1
155 160 for rev in xrange(start, end + step, step):
156 161 if rev in seen:
157 162 continue
158 163 seen.add(rev)
159 164 l.append(rev)
160 165 continue
161 166 elif spec and spec in repo: # single unquoted rev
162 167 rev = revfix(repo, spec, None)
163 168 if rev in seen:
164 169 continue
165 170 seen.add(rev)
166 171 l.append(rev)
167 172 continue
168 173 except error.RepoLookupError:
169 174 pass
170 175
171 176 # fall through to new-style queries if old-style fails
172 177 m = revset.match(spec)
173 178 for r in m(repo, range(len(repo))):
174 179 if r not in seen:
175 180 l.append(r)
176 181 seen.update(l)
177 182
178 183 return l
179 184
180 185 def make_filename(repo, pat, node,
181 186 total=None, seqno=None, revwidth=None, pathname=None):
182 187 node_expander = {
183 188 'H': lambda: hex(node),
184 189 'R': lambda: str(repo.changelog.rev(node)),
185 190 'h': lambda: short(node),
186 191 }
187 192 expander = {
188 193 '%': lambda: '%',
189 194 'b': lambda: os.path.basename(repo.root),
190 195 }
191 196
192 197 try:
193 198 if node:
194 199 expander.update(node_expander)
195 200 if node:
196 201 expander['r'] = (lambda:
197 202 str(repo.changelog.rev(node)).zfill(revwidth or 0))
198 203 if total is not None:
199 204 expander['N'] = lambda: str(total)
200 205 if seqno is not None:
201 206 expander['n'] = lambda: str(seqno)
202 207 if total is not None and seqno is not None:
203 208 expander['n'] = lambda: str(seqno).zfill(len(str(total)))
204 209 if pathname is not None:
205 210 expander['s'] = lambda: os.path.basename(pathname)
206 211 expander['d'] = lambda: os.path.dirname(pathname) or '.'
207 212 expander['p'] = lambda: pathname
208 213
209 214 newname = []
210 215 patlen = len(pat)
211 216 i = 0
212 217 while i < patlen:
213 218 c = pat[i]
214 219 if c == '%':
215 220 i += 1
216 221 c = pat[i]
217 222 c = expander[c]()
218 223 newname.append(c)
219 224 i += 1
220 225 return ''.join(newname)
221 226 except KeyError, inst:
222 227 raise util.Abort(_("invalid format spec '%%%s' in output filename") %
223 228 inst.args[0])
224 229
225 230 def make_file(repo, pat, node=None,
226 231 total=None, seqno=None, revwidth=None, mode='wb', pathname=None):
227 232
228 233 writable = 'w' in mode or 'a' in mode
229 234
230 235 if not pat or pat == '-':
231 236 return writable and sys.stdout or sys.stdin
232 237 if hasattr(pat, 'write') and writable:
233 238 return pat
234 239 if hasattr(pat, 'read') and 'r' in mode:
235 240 return pat
236 241 return open(make_filename(repo, pat, node, total, seqno, revwidth,
237 242 pathname),
238 243 mode)
239 244
240 245 def expandpats(pats):
241 246 if not util.expandglobs:
242 247 return list(pats)
243 248 ret = []
244 249 for p in pats:
245 250 kind, name = matchmod._patsplit(p, None)
246 251 if kind is None:
247 252 try:
248 253 globbed = glob.glob(name)
249 254 except re.error:
250 255 globbed = [name]
251 256 if globbed:
252 257 ret.extend(globbed)
253 258 continue
254 259 ret.append(p)
255 260 return ret
256 261
257 262 def match(repo, pats=[], opts={}, globbed=False, default='relpath'):
258 263 if not globbed and default == 'relpath':
259 264 pats = expandpats(pats or [])
260 265 m = matchmod.match(repo.root, repo.getcwd(), pats,
261 266 opts.get('include'), opts.get('exclude'), default,
262 267 auditor=repo.auditor)
263 268 def badfn(f, msg):
264 269 repo.ui.warn("%s: %s\n" % (m.rel(f), msg))
265 270 m.bad = badfn
266 271 return m
267 272
268 273 def matchall(repo):
269 274 return matchmod.always(repo.root, repo.getcwd())
270 275
271 276 def matchfiles(repo, files):
272 277 return matchmod.exact(repo.root, repo.getcwd(), files)
273 278
274 279 def addremove(repo, pats=[], opts={}, dry_run=None, similarity=None):
275 280 if dry_run is None:
276 281 dry_run = opts.get('dry_run')
277 282 if similarity is None:
278 283 similarity = float(opts.get('similarity') or 0)
279 284 # we'd use status here, except handling of symlinks and ignore is tricky
280 285 added, unknown, deleted, removed = [], [], [], []
281 286 audit_path = util.path_auditor(repo.root)
282 287 m = match(repo, pats, opts)
283 288 for abs in repo.walk(m):
284 289 target = repo.wjoin(abs)
285 290 good = True
286 291 try:
287 292 audit_path(abs)
288 293 except:
289 294 good = False
290 295 rel = m.rel(abs)
291 296 exact = m.exact(abs)
292 297 if good and abs not in repo.dirstate:
293 298 unknown.append(abs)
294 299 if repo.ui.verbose or not exact:
295 300 repo.ui.status(_('adding %s\n') % ((pats and rel) or abs))
296 301 elif repo.dirstate[abs] != 'r' and (not good or not os.path.lexists(target)
297 302 or (os.path.isdir(target) and not os.path.islink(target))):
298 303 deleted.append(abs)
299 304 if repo.ui.verbose or not exact:
300 305 repo.ui.status(_('removing %s\n') % ((pats and rel) or abs))
301 306 # for finding renames
302 307 elif repo.dirstate[abs] == 'r':
303 308 removed.append(abs)
304 309 elif repo.dirstate[abs] == 'a':
305 310 added.append(abs)
306 311 copies = {}
307 312 if similarity > 0:
308 313 for old, new, score in similar.findrenames(repo,
309 314 added + unknown, removed + deleted, similarity):
310 315 if repo.ui.verbose or not m.exact(old) or not m.exact(new):
311 316 repo.ui.status(_('recording removal of %s as rename to %s '
312 317 '(%d%% similar)\n') %
313 318 (m.rel(old), m.rel(new), score * 100))
314 319 copies[new] = old
315 320
316 321 if not dry_run:
317 322 wctx = repo[None]
318 323 wlock = repo.wlock()
319 324 try:
320 325 wctx.remove(deleted)
321 326 wctx.add(unknown)
322 327 for new, old in copies.iteritems():
323 328 wctx.copy(old, new)
324 329 finally:
325 330 wlock.release()
326 331
327 332 def updatedir(ui, repo, patches, similarity=0):
328 333 '''Update dirstate after patch application according to metadata'''
329 334 if not patches:
330 335 return
331 336 copies = []
332 337 removes = set()
333 338 cfiles = patches.keys()
334 339 cwd = repo.getcwd()
335 340 if cwd:
336 341 cfiles = [util.pathto(repo.root, cwd, f) for f in patches.keys()]
337 342 for f in patches:
338 343 gp = patches[f]
339 344 if not gp:
340 345 continue
341 346 if gp.op == 'RENAME':
342 347 copies.append((gp.oldpath, gp.path))
343 348 removes.add(gp.oldpath)
344 349 elif gp.op == 'COPY':
345 350 copies.append((gp.oldpath, gp.path))
346 351 elif gp.op == 'DELETE':
347 352 removes.add(gp.path)
348 353
349 354 wctx = repo[None]
350 355 for src, dst in copies:
351 356 dirstatecopy(ui, repo, wctx, src, dst, cwd=cwd)
352 357 if (not similarity) and removes:
353 358 wctx.remove(sorted(removes), True)
354 359
355 360 for f in patches:
356 361 gp = patches[f]
357 362 if gp and gp.mode:
358 363 islink, isexec = gp.mode
359 364 dst = repo.wjoin(gp.path)
360 365 # patch won't create empty files
361 366 if gp.op == 'ADD' and not os.path.lexists(dst):
362 367 flags = (isexec and 'x' or '') + (islink and 'l' or '')
363 368 repo.wwrite(gp.path, '', flags)
364 369 util.set_flags(dst, islink, isexec)
365 370 addremove(repo, cfiles, similarity=similarity)
366 371 files = patches.keys()
367 372 files.extend([r for r in removes if r not in files])
368 373 return sorted(files)
369 374
370 375 def dirstatecopy(ui, repo, wctx, src, dst, dryrun=False, cwd=None):
371 376 """Update the dirstate to reflect the intent of copying src to dst. For
372 377 different reasons it might not end with dst being marked as copied from src.
373 378 """
374 379 origsrc = repo.dirstate.copied(src) or src
375 380 if dst == origsrc: # copying back a copy?
376 381 if repo.dirstate[dst] not in 'mn' and not dryrun:
377 382 repo.dirstate.normallookup(dst)
378 383 else:
379 384 if repo.dirstate[origsrc] == 'a' and origsrc == src:
380 385 if not ui.quiet:
381 386 ui.warn(_("%s has not been committed yet, so no copy "
382 387 "data will be stored for %s.\n")
383 388 % (repo.pathto(origsrc, cwd), repo.pathto(dst, cwd)))
384 389 if repo.dirstate[dst] in '?r' and not dryrun:
385 390 wctx.add([dst])
386 391 elif not dryrun:
387 392 wctx.copy(origsrc, dst)
388 393
389 394 def copy(ui, repo, pats, opts, rename=False):
390 395 # called with the repo lock held
391 396 #
392 397 # hgsep => pathname that uses "/" to separate directories
393 398 # ossep => pathname that uses os.sep to separate directories
394 399 cwd = repo.getcwd()
395 400 targets = {}
396 401 after = opts.get("after")
397 402 dryrun = opts.get("dry_run")
398 403 wctx = repo[None]
399 404
400 405 def walkpat(pat):
401 406 srcs = []
402 407 badstates = after and '?' or '?r'
403 408 m = match(repo, [pat], opts, globbed=True)
404 409 for abs in repo.walk(m):
405 410 state = repo.dirstate[abs]
406 411 rel = m.rel(abs)
407 412 exact = m.exact(abs)
408 413 if state in badstates:
409 414 if exact and state == '?':
410 415 ui.warn(_('%s: not copying - file is not managed\n') % rel)
411 416 if exact and state == 'r':
412 417 ui.warn(_('%s: not copying - file has been marked for'
413 418 ' remove\n') % rel)
414 419 continue
415 420 # abs: hgsep
416 421 # rel: ossep
417 422 srcs.append((abs, rel, exact))
418 423 return srcs
419 424
420 425 # abssrc: hgsep
421 426 # relsrc: ossep
422 427 # otarget: ossep
423 428 def copyfile(abssrc, relsrc, otarget, exact):
424 429 abstarget = util.canonpath(repo.root, cwd, otarget)
425 430 reltarget = repo.pathto(abstarget, cwd)
426 431 target = repo.wjoin(abstarget)
427 432 src = repo.wjoin(abssrc)
428 433 state = repo.dirstate[abstarget]
429 434
430 435 # check for collisions
431 436 prevsrc = targets.get(abstarget)
432 437 if prevsrc is not None:
433 438 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
434 439 (reltarget, repo.pathto(abssrc, cwd),
435 440 repo.pathto(prevsrc, cwd)))
436 441 return
437 442
438 443 # check for overwrites
439 444 exists = os.path.lexists(target)
440 445 if not after and exists or after and state in 'mn':
441 446 if not opts['force']:
442 447 ui.warn(_('%s: not overwriting - file exists\n') %
443 448 reltarget)
444 449 return
445 450
446 451 if after:
447 452 if not exists:
448 453 if rename:
449 454 ui.warn(_('%s: not recording move - %s does not exist\n') %
450 455 (relsrc, reltarget))
451 456 else:
452 457 ui.warn(_('%s: not recording copy - %s does not exist\n') %
453 458 (relsrc, reltarget))
454 459 return
455 460 elif not dryrun:
456 461 try:
457 462 if exists:
458 463 os.unlink(target)
459 464 targetdir = os.path.dirname(target) or '.'
460 465 if not os.path.isdir(targetdir):
461 466 os.makedirs(targetdir)
462 467 util.copyfile(src, target)
463 468 except IOError, inst:
464 469 if inst.errno == errno.ENOENT:
465 470 ui.warn(_('%s: deleted in working copy\n') % relsrc)
466 471 else:
467 472 ui.warn(_('%s: cannot copy - %s\n') %
468 473 (relsrc, inst.strerror))
469 474 return True # report a failure
470 475
471 476 if ui.verbose or not exact:
472 477 if rename:
473 478 ui.status(_('moving %s to %s\n') % (relsrc, reltarget))
474 479 else:
475 480 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
476 481
477 482 targets[abstarget] = abssrc
478 483
479 484 # fix up dirstate
480 485 dirstatecopy(ui, repo, wctx, abssrc, abstarget, dryrun=dryrun, cwd=cwd)
481 486 if rename and not dryrun:
482 487 wctx.remove([abssrc], not after)
483 488
484 489 # pat: ossep
485 490 # dest ossep
486 491 # srcs: list of (hgsep, hgsep, ossep, bool)
487 492 # return: function that takes hgsep and returns ossep
488 493 def targetpathfn(pat, dest, srcs):
489 494 if os.path.isdir(pat):
490 495 abspfx = util.canonpath(repo.root, cwd, pat)
491 496 abspfx = util.localpath(abspfx)
492 497 if destdirexists:
493 498 striplen = len(os.path.split(abspfx)[0])
494 499 else:
495 500 striplen = len(abspfx)
496 501 if striplen:
497 502 striplen += len(os.sep)
498 503 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
499 504 elif destdirexists:
500 505 res = lambda p: os.path.join(dest,
501 506 os.path.basename(util.localpath(p)))
502 507 else:
503 508 res = lambda p: dest
504 509 return res
505 510
506 511 # pat: ossep
507 512 # dest ossep
508 513 # srcs: list of (hgsep, hgsep, ossep, bool)
509 514 # return: function that takes hgsep and returns ossep
510 515 def targetpathafterfn(pat, dest, srcs):
511 516 if matchmod.patkind(pat):
512 517 # a mercurial pattern
513 518 res = lambda p: os.path.join(dest,
514 519 os.path.basename(util.localpath(p)))
515 520 else:
516 521 abspfx = util.canonpath(repo.root, cwd, pat)
517 522 if len(abspfx) < len(srcs[0][0]):
518 523 # A directory. Either the target path contains the last
519 524 # component of the source path or it does not.
520 525 def evalpath(striplen):
521 526 score = 0
522 527 for s in srcs:
523 528 t = os.path.join(dest, util.localpath(s[0])[striplen:])
524 529 if os.path.lexists(t):
525 530 score += 1
526 531 return score
527 532
528 533 abspfx = util.localpath(abspfx)
529 534 striplen = len(abspfx)
530 535 if striplen:
531 536 striplen += len(os.sep)
532 537 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
533 538 score = evalpath(striplen)
534 539 striplen1 = len(os.path.split(abspfx)[0])
535 540 if striplen1:
536 541 striplen1 += len(os.sep)
537 542 if evalpath(striplen1) > score:
538 543 striplen = striplen1
539 544 res = lambda p: os.path.join(dest,
540 545 util.localpath(p)[striplen:])
541 546 else:
542 547 # a file
543 548 if destdirexists:
544 549 res = lambda p: os.path.join(dest,
545 550 os.path.basename(util.localpath(p)))
546 551 else:
547 552 res = lambda p: dest
548 553 return res
549 554
550 555
551 556 pats = expandpats(pats)
552 557 if not pats:
553 558 raise util.Abort(_('no source or destination specified'))
554 559 if len(pats) == 1:
555 560 raise util.Abort(_('no destination specified'))
556 561 dest = pats.pop()
557 562 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
558 563 if not destdirexists:
559 564 if len(pats) > 1 or matchmod.patkind(pats[0]):
560 565 raise util.Abort(_('with multiple sources, destination must be an '
561 566 'existing directory'))
562 567 if util.endswithsep(dest):
563 568 raise util.Abort(_('destination %s is not a directory') % dest)
564 569
565 570 tfn = targetpathfn
566 571 if after:
567 572 tfn = targetpathafterfn
568 573 copylist = []
569 574 for pat in pats:
570 575 srcs = walkpat(pat)
571 576 if not srcs:
572 577 continue
573 578 copylist.append((tfn(pat, dest, srcs), srcs))
574 579 if not copylist:
575 580 raise util.Abort(_('no files to copy'))
576 581
577 582 errors = 0
578 583 for targetpath, srcs in copylist:
579 584 for abssrc, relsrc, exact in srcs:
580 585 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
581 586 errors += 1
582 587
583 588 if errors:
584 589 ui.warn(_('(consider using --after)\n'))
585 590
586 591 return errors != 0
587 592
588 593 def service(opts, parentfn=None, initfn=None, runfn=None, logfile=None,
589 594 runargs=None, appendpid=False):
590 595 '''Run a command as a service.'''
591 596
592 597 if opts['daemon'] and not opts['daemon_pipefds']:
593 598 # Signal child process startup with file removal
594 599 lockfd, lockpath = tempfile.mkstemp(prefix='hg-service-')
595 600 os.close(lockfd)
596 601 try:
597 602 if not runargs:
598 603 runargs = util.hgcmd() + sys.argv[1:]
599 604 runargs.append('--daemon-pipefds=%s' % lockpath)
600 605 # Don't pass --cwd to the child process, because we've already
601 606 # changed directory.
602 607 for i in xrange(1, len(runargs)):
603 608 if runargs[i].startswith('--cwd='):
604 609 del runargs[i]
605 610 break
606 611 elif runargs[i].startswith('--cwd'):
607 612 del runargs[i:i + 2]
608 613 break
609 614 def condfn():
610 615 return not os.path.exists(lockpath)
611 616 pid = util.rundetached(runargs, condfn)
612 617 if pid < 0:
613 618 raise util.Abort(_('child process failed to start'))
614 619 finally:
615 620 try:
616 621 os.unlink(lockpath)
617 622 except OSError, e:
618 623 if e.errno != errno.ENOENT:
619 624 raise
620 625 if parentfn:
621 626 return parentfn(pid)
622 627 else:
623 628 return
624 629
625 630 if initfn:
626 631 initfn()
627 632
628 633 if opts['pid_file']:
629 634 mode = appendpid and 'a' or 'w'
630 635 fp = open(opts['pid_file'], mode)
631 636 fp.write(str(os.getpid()) + '\n')
632 637 fp.close()
633 638
634 639 if opts['daemon_pipefds']:
635 640 lockpath = opts['daemon_pipefds']
636 641 try:
637 642 os.setsid()
638 643 except AttributeError:
639 644 pass
640 645 os.unlink(lockpath)
641 646 util.hidewindow()
642 647 sys.stdout.flush()
643 648 sys.stderr.flush()
644 649
645 650 nullfd = os.open(util.nulldev, os.O_RDWR)
646 651 logfilefd = nullfd
647 652 if logfile:
648 653 logfilefd = os.open(logfile, os.O_RDWR | os.O_CREAT | os.O_APPEND)
649 654 os.dup2(nullfd, 0)
650 655 os.dup2(logfilefd, 1)
651 656 os.dup2(logfilefd, 2)
652 657 if nullfd not in (0, 1, 2):
653 658 os.close(nullfd)
654 659 if logfile and logfilefd not in (0, 1, 2):
655 660 os.close(logfilefd)
656 661
657 662 if runfn:
658 663 return runfn()
659 664
660 665 def export(repo, revs, template='hg-%h.patch', fp=None, switch_parent=False,
661 666 opts=None):
662 667 '''export changesets as hg patches.'''
663 668
664 669 total = len(revs)
665 670 revwidth = max([len(str(rev)) for rev in revs])
666 671
667 672 def single(rev, seqno, fp):
668 673 ctx = repo[rev]
669 674 node = ctx.node()
670 675 parents = [p.node() for p in ctx.parents() if p]
671 676 branch = ctx.branch()
672 677 if switch_parent:
673 678 parents.reverse()
674 679 prev = (parents and parents[0]) or nullid
675 680
676 681 if not fp:
677 682 fp = make_file(repo, template, node, total=total, seqno=seqno,
678 683 revwidth=revwidth, mode='ab')
679 684 if fp != sys.stdout and hasattr(fp, 'name'):
680 685 repo.ui.note("%s\n" % fp.name)
681 686
682 687 fp.write("# HG changeset patch\n")
683 688 fp.write("# User %s\n" % ctx.user())
684 689 fp.write("# Date %d %d\n" % ctx.date())
685 690 if branch and branch != 'default':
686 691 fp.write("# Branch %s\n" % branch)
687 692 fp.write("# Node ID %s\n" % hex(node))
688 693 fp.write("# Parent %s\n" % hex(prev))
689 694 if len(parents) > 1:
690 695 fp.write("# Parent %s\n" % hex(parents[1]))
691 696 fp.write(ctx.description().rstrip())
692 697 fp.write("\n\n")
693 698
694 699 for chunk in patch.diff(repo, prev, node, opts=opts):
695 700 fp.write(chunk)
696 701
697 702 for seqno, rev in enumerate(revs):
698 703 single(rev, seqno + 1, fp)
699 704
700 705 def diffordiffstat(ui, repo, diffopts, node1, node2, match,
701 706 changes=None, stat=False, fp=None, prefix='',
702 707 listsubrepos=False):
703 708 '''show diff or diffstat.'''
704 709 if fp is None:
705 710 write = ui.write
706 711 else:
707 712 def write(s, **kw):
708 713 fp.write(s)
709 714
710 715 if stat:
711 716 diffopts = diffopts.copy(context=0)
712 717 width = 80
713 718 if not ui.plain():
714 719 width = ui.termwidth()
715 720 chunks = patch.diff(repo, node1, node2, match, changes, diffopts,
716 721 prefix=prefix)
717 722 for chunk, label in patch.diffstatui(util.iterlines(chunks),
718 723 width=width,
719 724 git=diffopts.git):
720 725 write(chunk, label=label)
721 726 else:
722 727 for chunk, label in patch.diffui(repo, node1, node2, match,
723 728 changes, diffopts, prefix=prefix):
724 729 write(chunk, label=label)
725 730
726 731 if listsubrepos:
727 732 ctx1 = repo[node1]
728 733 ctx2 = repo[node2]
729 734 for subpath, sub in subrepo.itersubrepos(ctx1, ctx2):
730 735 if node2 is not None:
731 736 node2 = ctx2.substate[subpath][1]
732 737 submatch = matchmod.narrowmatcher(subpath, match)
733 738 sub.diff(diffopts, node2, submatch, changes=changes,
734 739 stat=stat, fp=fp, prefix=prefix)
735 740
736 741 class changeset_printer(object):
737 742 '''show changeset information when templating not requested.'''
738 743
739 744 def __init__(self, ui, repo, patch, diffopts, buffered):
740 745 self.ui = ui
741 746 self.repo = repo
742 747 self.buffered = buffered
743 748 self.patch = patch
744 749 self.diffopts = diffopts
745 750 self.header = {}
746 751 self.hunk = {}
747 752 self.lastheader = None
748 753 self.footer = None
749 754
750 755 def flush(self, rev):
751 756 if rev in self.header:
752 757 h = self.header[rev]
753 758 if h != self.lastheader:
754 759 self.lastheader = h
755 760 self.ui.write(h)
756 761 del self.header[rev]
757 762 if rev in self.hunk:
758 763 self.ui.write(self.hunk[rev])
759 764 del self.hunk[rev]
760 765 return 1
761 766 return 0
762 767
763 768 def close(self):
764 769 if self.footer:
765 770 self.ui.write(self.footer)
766 771
767 772 def show(self, ctx, copies=None, matchfn=None, **props):
768 773 if self.buffered:
769 774 self.ui.pushbuffer()
770 775 self._show(ctx, copies, matchfn, props)
771 776 self.hunk[ctx.rev()] = self.ui.popbuffer(labeled=True)
772 777 else:
773 778 self._show(ctx, copies, matchfn, props)
774 779
775 780 def _show(self, ctx, copies, matchfn, props):
776 781 '''show a single changeset or file revision'''
777 782 changenode = ctx.node()
778 783 rev = ctx.rev()
779 784
780 785 if self.ui.quiet:
781 786 self.ui.write("%d:%s\n" % (rev, short(changenode)),
782 787 label='log.node')
783 788 return
784 789
785 790 log = self.repo.changelog
786 791 date = util.datestr(ctx.date())
787 792
788 793 hexfunc = self.ui.debugflag and hex or short
789 794
790 795 parents = [(p, hexfunc(log.node(p)))
791 796 for p in self._meaningful_parentrevs(log, rev)]
792 797
793 798 self.ui.write(_("changeset: %d:%s\n") % (rev, hexfunc(changenode)),
794 799 label='log.changeset')
795 800
796 801 branch = ctx.branch()
797 802 # don't show the default branch name
798 803 if branch != 'default':
799 804 branch = encoding.tolocal(branch)
800 805 self.ui.write(_("branch: %s\n") % branch,
801 806 label='log.branch')
802 807 for tag in self.repo.nodetags(changenode):
803 808 self.ui.write(_("tag: %s\n") % tag,
804 809 label='log.tag')
805 810 for parent in parents:
806 811 self.ui.write(_("parent: %d:%s\n") % parent,
807 812 label='log.parent')
808 813
809 814 if self.ui.debugflag:
810 815 mnode = ctx.manifestnode()
811 816 self.ui.write(_("manifest: %d:%s\n") %
812 817 (self.repo.manifest.rev(mnode), hex(mnode)),
813 818 label='ui.debug log.manifest')
814 819 self.ui.write(_("user: %s\n") % ctx.user(),
815 820 label='log.user')
816 821 self.ui.write(_("date: %s\n") % date,
817 822 label='log.date')
818 823
819 824 if self.ui.debugflag:
820 825 files = self.repo.status(log.parents(changenode)[0], changenode)[:3]
821 826 for key, value in zip([_("files:"), _("files+:"), _("files-:")],
822 827 files):
823 828 if value:
824 829 self.ui.write("%-12s %s\n" % (key, " ".join(value)),
825 830 label='ui.debug log.files')
826 831 elif ctx.files() and self.ui.verbose:
827 832 self.ui.write(_("files: %s\n") % " ".join(ctx.files()),
828 833 label='ui.note log.files')
829 834 if copies and self.ui.verbose:
830 835 copies = ['%s (%s)' % c for c in copies]
831 836 self.ui.write(_("copies: %s\n") % ' '.join(copies),
832 837 label='ui.note log.copies')
833 838
834 839 extra = ctx.extra()
835 840 if extra and self.ui.debugflag:
836 841 for key, value in sorted(extra.items()):
837 842 self.ui.write(_("extra: %s=%s\n")
838 843 % (key, value.encode('string_escape')),
839 844 label='ui.debug log.extra')
840 845
841 846 description = ctx.description().strip()
842 847 if description:
843 848 if self.ui.verbose:
844 849 self.ui.write(_("description:\n"),
845 850 label='ui.note log.description')
846 851 self.ui.write(description,
847 852 label='ui.note log.description')
848 853 self.ui.write("\n\n")
849 854 else:
850 855 self.ui.write(_("summary: %s\n") %
851 856 description.splitlines()[0],
852 857 label='log.summary')
853 858 self.ui.write("\n")
854 859
855 860 self.showpatch(changenode, matchfn)
856 861
857 862 def showpatch(self, node, matchfn):
858 863 if not matchfn:
859 864 matchfn = self.patch
860 865 if matchfn:
861 866 stat = self.diffopts.get('stat')
862 867 diff = self.diffopts.get('patch')
863 868 diffopts = patch.diffopts(self.ui, self.diffopts)
864 869 prev = self.repo.changelog.parents(node)[0]
865 870 if stat:
866 871 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
867 872 match=matchfn, stat=True)
868 873 if diff:
869 874 if stat:
870 875 self.ui.write("\n")
871 876 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
872 877 match=matchfn, stat=False)
873 878 self.ui.write("\n")
874 879
875 880 def _meaningful_parentrevs(self, log, rev):
876 881 """Return list of meaningful (or all if debug) parentrevs for rev.
877 882
878 883 For merges (two non-nullrev revisions) both parents are meaningful.
879 884 Otherwise the first parent revision is considered meaningful if it
880 885 is not the preceding revision.
881 886 """
882 887 parents = log.parentrevs(rev)
883 888 if not self.ui.debugflag and parents[1] == nullrev:
884 889 if parents[0] >= rev - 1:
885 890 parents = []
886 891 else:
887 892 parents = [parents[0]]
888 893 return parents
889 894
890 895
891 896 class changeset_templater(changeset_printer):
892 897 '''format changeset information.'''
893 898
894 899 def __init__(self, ui, repo, patch, diffopts, mapfile, buffered):
895 900 changeset_printer.__init__(self, ui, repo, patch, diffopts, buffered)
896 901 formatnode = ui.debugflag and (lambda x: x) or (lambda x: x[:12])
897 902 defaulttempl = {
898 903 'parent': '{rev}:{node|formatnode} ',
899 904 'manifest': '{rev}:{node|formatnode}',
900 905 'file_copy': '{name} ({source})',
901 906 'extra': '{key}={value|stringescape}'
902 907 }
903 908 # filecopy is preserved for compatibility reasons
904 909 defaulttempl['filecopy'] = defaulttempl['file_copy']
905 910 self.t = templater.templater(mapfile, {'formatnode': formatnode},
906 911 cache=defaulttempl)
907 912 self.cache = {}
908 913
909 914 def use_template(self, t):
910 915 '''set template string to use'''
911 916 self.t.cache['changeset'] = t
912 917
913 918 def _meaningful_parentrevs(self, ctx):
914 919 """Return list of meaningful (or all if debug) parentrevs for rev.
915 920 """
916 921 parents = ctx.parents()
917 922 if len(parents) > 1:
918 923 return parents
919 924 if self.ui.debugflag:
920 925 return [parents[0], self.repo['null']]
921 926 if parents[0].rev() >= ctx.rev() - 1:
922 927 return []
923 928 return parents
924 929
925 930 def _show(self, ctx, copies, matchfn, props):
926 931 '''show a single changeset or file revision'''
927 932
928 933 showlist = templatekw.showlist
929 934
930 935 # showparents() behaviour depends on ui trace level which
931 936 # causes unexpected behaviours at templating level and makes
932 937 # it harder to extract it in a standalone function. Its
933 938 # behaviour cannot be changed so leave it here for now.
934 939 def showparents(**args):
935 940 ctx = args['ctx']
936 941 parents = [[('rev', p.rev()), ('node', p.hex())]
937 942 for p in self._meaningful_parentrevs(ctx)]
938 943 return showlist('parent', parents, **args)
939 944
940 945 props = props.copy()
941 946 props.update(templatekw.keywords)
942 947 props['parents'] = showparents
943 948 props['templ'] = self.t
944 949 props['ctx'] = ctx
945 950 props['repo'] = self.repo
946 951 props['revcache'] = {'copies': copies}
947 952 props['cache'] = self.cache
948 953
949 954 # find correct templates for current mode
950 955
951 956 tmplmodes = [
952 957 (True, None),
953 958 (self.ui.verbose, 'verbose'),
954 959 (self.ui.quiet, 'quiet'),
955 960 (self.ui.debugflag, 'debug'),
956 961 ]
957 962
958 963 types = {'header': '', 'footer':'', 'changeset': 'changeset'}
959 964 for mode, postfix in tmplmodes:
960 965 for type in types:
961 966 cur = postfix and ('%s_%s' % (type, postfix)) or type
962 967 if mode and cur in self.t:
963 968 types[type] = cur
964 969
965 970 try:
966 971
967 972 # write header
968 973 if types['header']:
969 974 h = templater.stringify(self.t(types['header'], **props))
970 975 if self.buffered:
971 976 self.header[ctx.rev()] = h
972 977 else:
973 978 if self.lastheader != h:
974 979 self.lastheader = h
975 980 self.ui.write(h)
976 981
977 982 # write changeset metadata, then patch if requested
978 983 key = types['changeset']
979 984 self.ui.write(templater.stringify(self.t(key, **props)))
980 985 self.showpatch(ctx.node(), matchfn)
981 986
982 987 if types['footer']:
983 988 if not self.footer:
984 989 self.footer = templater.stringify(self.t(types['footer'],
985 990 **props))
986 991
987 992 except KeyError, inst:
988 993 msg = _("%s: no key named '%s'")
989 994 raise util.Abort(msg % (self.t.mapfile, inst.args[0]))
990 995 except SyntaxError, inst:
991 996 raise util.Abort('%s: %s' % (self.t.mapfile, inst.args[0]))
992 997
993 998 def show_changeset(ui, repo, opts, buffered=False):
994 999 """show one changeset using template or regular display.
995 1000
996 1001 Display format will be the first non-empty hit of:
997 1002 1. option 'template'
998 1003 2. option 'style'
999 1004 3. [ui] setting 'logtemplate'
1000 1005 4. [ui] setting 'style'
1001 1006 If all of these values are either the unset or the empty string,
1002 1007 regular display via changeset_printer() is done.
1003 1008 """
1004 1009 # options
1005 1010 patch = False
1006 1011 if opts.get('patch') or opts.get('stat'):
1007 1012 patch = matchall(repo)
1008 1013
1009 1014 tmpl = opts.get('template')
1010 1015 style = None
1011 1016 if tmpl:
1012 1017 tmpl = templater.parsestring(tmpl, quoted=False)
1013 1018 else:
1014 1019 style = opts.get('style')
1015 1020
1016 1021 # ui settings
1017 1022 if not (tmpl or style):
1018 1023 tmpl = ui.config('ui', 'logtemplate')
1019 1024 if tmpl:
1020 1025 tmpl = templater.parsestring(tmpl)
1021 1026 else:
1022 1027 style = util.expandpath(ui.config('ui', 'style', ''))
1023 1028
1024 1029 if not (tmpl or style):
1025 1030 return changeset_printer(ui, repo, patch, opts, buffered)
1026 1031
1027 1032 mapfile = None
1028 1033 if style and not tmpl:
1029 1034 mapfile = style
1030 1035 if not os.path.split(mapfile)[0]:
1031 1036 mapname = (templater.templatepath('map-cmdline.' + mapfile)
1032 1037 or templater.templatepath(mapfile))
1033 1038 if mapname:
1034 1039 mapfile = mapname
1035 1040
1036 1041 try:
1037 1042 t = changeset_templater(ui, repo, patch, opts, mapfile, buffered)
1038 1043 except SyntaxError, inst:
1039 1044 raise util.Abort(inst.args[0])
1040 1045 if tmpl:
1041 1046 t.use_template(tmpl)
1042 1047 return t
1043 1048
1044 1049 def finddate(ui, repo, date):
1045 1050 """Find the tipmost changeset that matches the given date spec"""
1046 1051
1047 1052 df = util.matchdate(date)
1048 1053 m = matchall(repo)
1049 1054 results = {}
1050 1055
1051 1056 def prep(ctx, fns):
1052 1057 d = ctx.date()
1053 1058 if df(d[0]):
1054 1059 results[ctx.rev()] = d
1055 1060
1056 1061 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
1057 1062 rev = ctx.rev()
1058 1063 if rev in results:
1059 1064 ui.status(_("Found revision %s from %s\n") %
1060 1065 (rev, util.datestr(results[rev])))
1061 1066 return str(rev)
1062 1067
1063 1068 raise util.Abort(_("revision matching date not found"))
1064 1069
1065 1070 def walkchangerevs(repo, match, opts, prepare):
1066 1071 '''Iterate over files and the revs in which they changed.
1067 1072
1068 1073 Callers most commonly need to iterate backwards over the history
1069 1074 in which they are interested. Doing so has awful (quadratic-looking)
1070 1075 performance, so we use iterators in a "windowed" way.
1071 1076
1072 1077 We walk a window of revisions in the desired order. Within the
1073 1078 window, we first walk forwards to gather data, then in the desired
1074 1079 order (usually backwards) to display it.
1075 1080
1076 1081 This function returns an iterator yielding contexts. Before
1077 1082 yielding each context, the iterator will first call the prepare
1078 1083 function on each context in the window in forward order.'''
1079 1084
1080 1085 def increasing_windows(start, end, windowsize=8, sizelimit=512):
1081 1086 if start < end:
1082 1087 while start < end:
1083 1088 yield start, min(windowsize, end - start)
1084 1089 start += windowsize
1085 1090 if windowsize < sizelimit:
1086 1091 windowsize *= 2
1087 1092 else:
1088 1093 while start > end:
1089 1094 yield start, min(windowsize, start - end - 1)
1090 1095 start -= windowsize
1091 1096 if windowsize < sizelimit:
1092 1097 windowsize *= 2
1093 1098
1094 1099 follow = opts.get('follow') or opts.get('follow_first')
1095 1100
1096 1101 if not len(repo):
1097 1102 return []
1098 1103
1099 1104 if follow:
1100 1105 defrange = '%s:0' % repo['.'].rev()
1101 1106 else:
1102 1107 defrange = '-1:0'
1103 1108 revs = revrange(repo, opts['rev'] or [defrange])
1104 1109 if not revs:
1105 1110 return []
1106 1111 wanted = set()
1107 1112 slowpath = match.anypats() or (match.files() and opts.get('removed'))
1108 1113 fncache = {}
1109 1114 change = util.cachefunc(repo.changectx)
1110 1115
1111 1116 # First step is to fill wanted, the set of revisions that we want to yield.
1112 1117 # When it does not induce extra cost, we also fill fncache for revisions in
1113 1118 # wanted: a cache of filenames that were changed (ctx.files()) and that
1114 1119 # match the file filtering conditions.
1115 1120
1116 1121 if not slowpath and not match.files():
1117 1122 # No files, no patterns. Display all revs.
1118 1123 wanted = set(revs)
1119 1124 copies = []
1120 1125
1121 1126 if not slowpath:
1122 1127 # We only have to read through the filelog to find wanted revisions
1123 1128
1124 1129 minrev, maxrev = min(revs), max(revs)
1125 1130 def filerevgen(filelog, last):
1126 1131 """
1127 1132 Only files, no patterns. Check the history of each file.
1128 1133
1129 1134 Examines filelog entries within minrev, maxrev linkrev range
1130 1135 Returns an iterator yielding (linkrev, parentlinkrevs, copied)
1131 1136 tuples in backwards order
1132 1137 """
1133 1138 cl_count = len(repo)
1134 1139 revs = []
1135 1140 for j in xrange(0, last + 1):
1136 1141 linkrev = filelog.linkrev(j)
1137 1142 if linkrev < minrev:
1138 1143 continue
1139 1144 # only yield rev for which we have the changelog, it can
1140 1145 # happen while doing "hg log" during a pull or commit
1141 1146 if linkrev > maxrev or linkrev >= cl_count:
1142 1147 break
1143 1148
1144 1149 parentlinkrevs = []
1145 1150 for p in filelog.parentrevs(j):
1146 1151 if p != nullrev:
1147 1152 parentlinkrevs.append(filelog.linkrev(p))
1148 1153 n = filelog.node(j)
1149 1154 revs.append((linkrev, parentlinkrevs,
1150 1155 follow and filelog.renamed(n)))
1151 1156
1152 1157 return reversed(revs)
1153 1158 def iterfiles():
1154 1159 for filename in match.files():
1155 1160 yield filename, None
1156 1161 for filename_node in copies:
1157 1162 yield filename_node
1158 1163 for file_, node in iterfiles():
1159 1164 filelog = repo.file(file_)
1160 1165 if not len(filelog):
1161 1166 if node is None:
1162 1167 # A zero count may be a directory or deleted file, so
1163 1168 # try to find matching entries on the slow path.
1164 1169 if follow:
1165 1170 raise util.Abort(
1166 1171 _('cannot follow nonexistent file: "%s"') % file_)
1167 1172 slowpath = True
1168 1173 break
1169 1174 else:
1170 1175 continue
1171 1176
1172 1177 if node is None:
1173 1178 last = len(filelog) - 1
1174 1179 else:
1175 1180 last = filelog.rev(node)
1176 1181
1177 1182
1178 1183 # keep track of all ancestors of the file
1179 1184 ancestors = set([filelog.linkrev(last)])
1180 1185
1181 1186 # iterate from latest to oldest revision
1182 1187 for rev, flparentlinkrevs, copied in filerevgen(filelog, last):
1183 1188 if rev not in ancestors:
1184 1189 continue
1185 1190 # XXX insert 1327 fix here
1186 1191 if flparentlinkrevs:
1187 1192 ancestors.update(flparentlinkrevs)
1188 1193
1189 1194 fncache.setdefault(rev, []).append(file_)
1190 1195 wanted.add(rev)
1191 1196 if copied:
1192 1197 copies.append(copied)
1193 1198 if slowpath:
1194 1199 # We have to read the changelog to match filenames against
1195 1200 # changed files
1196 1201
1197 1202 if follow:
1198 1203 raise util.Abort(_('can only follow copies/renames for explicit '
1199 1204 'filenames'))
1200 1205
1201 1206 # The slow path checks files modified in every changeset.
1202 1207 for i in sorted(revs):
1203 1208 ctx = change(i)
1204 1209 matches = filter(match, ctx.files())
1205 1210 if matches:
1206 1211 fncache[i] = matches
1207 1212 wanted.add(i)
1208 1213
1209 1214 class followfilter(object):
1210 1215 def __init__(self, onlyfirst=False):
1211 1216 self.startrev = nullrev
1212 1217 self.roots = set()
1213 1218 self.onlyfirst = onlyfirst
1214 1219
1215 1220 def match(self, rev):
1216 1221 def realparents(rev):
1217 1222 if self.onlyfirst:
1218 1223 return repo.changelog.parentrevs(rev)[0:1]
1219 1224 else:
1220 1225 return filter(lambda x: x != nullrev,
1221 1226 repo.changelog.parentrevs(rev))
1222 1227
1223 1228 if self.startrev == nullrev:
1224 1229 self.startrev = rev
1225 1230 return True
1226 1231
1227 1232 if rev > self.startrev:
1228 1233 # forward: all descendants
1229 1234 if not self.roots:
1230 1235 self.roots.add(self.startrev)
1231 1236 for parent in realparents(rev):
1232 1237 if parent in self.roots:
1233 1238 self.roots.add(rev)
1234 1239 return True
1235 1240 else:
1236 1241 # backwards: all parents
1237 1242 if not self.roots:
1238 1243 self.roots.update(realparents(self.startrev))
1239 1244 if rev in self.roots:
1240 1245 self.roots.remove(rev)
1241 1246 self.roots.update(realparents(rev))
1242 1247 return True
1243 1248
1244 1249 return False
1245 1250
1246 1251 # it might be worthwhile to do this in the iterator if the rev range
1247 1252 # is descending and the prune args are all within that range
1248 1253 for rev in opts.get('prune', ()):
1249 1254 rev = repo.changelog.rev(repo.lookup(rev))
1250 1255 ff = followfilter()
1251 1256 stop = min(revs[0], revs[-1])
1252 1257 for x in xrange(rev, stop - 1, -1):
1253 1258 if ff.match(x):
1254 1259 wanted.discard(x)
1255 1260
1256 1261 # Now that wanted is correctly initialized, we can iterate over the
1257 1262 # revision range, yielding only revisions in wanted.
1258 1263 def iterate():
1259 1264 if follow and not match.files():
1260 1265 ff = followfilter(onlyfirst=opts.get('follow_first'))
1261 1266 def want(rev):
1262 1267 return ff.match(rev) and rev in wanted
1263 1268 else:
1264 1269 def want(rev):
1265 1270 return rev in wanted
1266 1271
1267 1272 for i, window in increasing_windows(0, len(revs)):
1268 1273 nrevs = [rev for rev in revs[i:i + window] if want(rev)]
1269 1274 for rev in sorted(nrevs):
1270 1275 fns = fncache.get(rev)
1271 1276 ctx = change(rev)
1272 1277 if not fns:
1273 1278 def fns_generator():
1274 1279 for f in ctx.files():
1275 1280 if match(f):
1276 1281 yield f
1277 1282 fns = fns_generator()
1278 1283 prepare(ctx, fns)
1279 1284 for rev in nrevs:
1280 1285 yield change(rev)
1281 1286 return iterate()
1282 1287
1283 1288 def add(ui, repo, match, dryrun, listsubrepos, prefix):
1284 1289 join = lambda f: os.path.join(prefix, f)
1285 1290 bad = []
1286 1291 oldbad = match.bad
1287 1292 match.bad = lambda x, y: bad.append(x) or oldbad(x, y)
1288 1293 names = []
1289 1294 wctx = repo[None]
1290 1295 for f in repo.walk(match):
1291 1296 exact = match.exact(f)
1292 1297 if exact or f not in repo.dirstate:
1293 1298 names.append(f)
1294 1299 if ui.verbose or not exact:
1295 1300 ui.status(_('adding %s\n') % match.rel(join(f)))
1296 1301
1297 1302 if listsubrepos:
1298 1303 for subpath in wctx.substate:
1299 1304 sub = wctx.sub(subpath)
1300 1305 try:
1301 1306 submatch = matchmod.narrowmatcher(subpath, match)
1302 1307 bad.extend(sub.add(ui, submatch, dryrun, prefix))
1303 1308 except error.LookupError:
1304 1309 ui.status(_("skipping missing subrepository: %s\n")
1305 1310 % join(subpath))
1306 1311
1307 1312 if not dryrun:
1308 1313 rejected = wctx.add(names, prefix)
1309 1314 bad.extend(f for f in rejected if f in match.files())
1310 1315 return bad
1311 1316
1312 1317 def commit(ui, repo, commitfunc, pats, opts):
1313 1318 '''commit the specified files or all outstanding changes'''
1314 1319 date = opts.get('date')
1315 1320 if date:
1316 1321 opts['date'] = util.parsedate(date)
1317 1322 message = logmessage(opts)
1318 1323
1319 1324 # extract addremove carefully -- this function can be called from a command
1320 1325 # that doesn't support addremove
1321 1326 if opts.get('addremove'):
1322 1327 addremove(repo, pats, opts)
1323 1328
1324 1329 return commitfunc(ui, repo, message, match(repo, pats, opts), opts)
1325 1330
1326 1331 def commiteditor(repo, ctx, subs):
1327 1332 if ctx.description():
1328 1333 return ctx.description()
1329 1334 return commitforceeditor(repo, ctx, subs)
1330 1335
1331 1336 def commitforceeditor(repo, ctx, subs):
1332 1337 edittext = []
1333 1338 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
1334 1339 if ctx.description():
1335 1340 edittext.append(ctx.description())
1336 1341 edittext.append("")
1337 1342 edittext.append("") # Empty line between message and comments.
1338 1343 edittext.append(_("HG: Enter commit message."
1339 1344 " Lines beginning with 'HG:' are removed."))
1340 1345 edittext.append(_("HG: Leave message empty to abort commit."))
1341 1346 edittext.append("HG: --")
1342 1347 edittext.append(_("HG: user: %s") % ctx.user())
1343 1348 if ctx.p2():
1344 1349 edittext.append(_("HG: branch merge"))
1345 1350 if ctx.branch():
1346 1351 edittext.append(_("HG: branch '%s'")
1347 1352 % encoding.tolocal(ctx.branch()))
1348 1353 edittext.extend([_("HG: subrepo %s") % s for s in subs])
1349 1354 edittext.extend([_("HG: added %s") % f for f in added])
1350 1355 edittext.extend([_("HG: changed %s") % f for f in modified])
1351 1356 edittext.extend([_("HG: removed %s") % f for f in removed])
1352 1357 if not added and not modified and not removed:
1353 1358 edittext.append(_("HG: no files changed"))
1354 1359 edittext.append("")
1355 1360 # run editor in the repository root
1356 1361 olddir = os.getcwd()
1357 1362 os.chdir(repo.root)
1358 1363 text = repo.ui.edit("\n".join(edittext), ctx.user())
1359 1364 text = re.sub("(?m)^HG:.*(\n|$)", "", text)
1360 1365 os.chdir(olddir)
1361 1366
1362 1367 if not text.strip():
1363 1368 raise util.Abort(_("empty commit message"))
1364 1369
1365 1370 return text
@@ -1,4525 +1,4526 b''
1 1 # commands.py - command processing for mercurial
2 2 #
3 3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 from node import hex, nullid, nullrev, short
9 9 from lock import release
10 10 from i18n import _, gettext
11 11 import os, re, sys, difflib, time, tempfile
12 12 import hg, util, revlog, extensions, copies, error
13 13 import patch, help, mdiff, url, encoding, templatekw, discovery
14 14 import archival, changegroup, cmdutil, sshserver, hbisect, hgweb, hgweb.server
15 15 import merge as mergemod
16 16 import minirst, revset
17 17 import dagparser
18 18
19 19 # Commands start here, listed alphabetically
20 20
21 21 def add(ui, repo, *pats, **opts):
22 22 """add the specified files on the next commit
23 23
24 24 Schedule files to be version controlled and added to the
25 25 repository.
26 26
27 27 The files will be added to the repository at the next commit. To
28 28 undo an add before that, see :hg:`forget`.
29 29
30 30 If no names are given, add all files to the repository.
31 31
32 32 .. container:: verbose
33 33
34 34 An example showing how new (unknown) files are added
35 35 automatically by :hg:`add`::
36 36
37 37 $ ls
38 38 foo.c
39 39 $ hg status
40 40 ? foo.c
41 41 $ hg add
42 42 adding foo.c
43 43 $ hg status
44 44 A foo.c
45 45
46 46 Returns 0 if all files are successfully added.
47 47 """
48 48
49 49 m = cmdutil.match(repo, pats, opts)
50 50 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
51 51 opts.get('subrepos'), prefix="")
52 52 return rejected and 1 or 0
53 53
54 54 def addremove(ui, repo, *pats, **opts):
55 55 """add all new files, delete all missing files
56 56
57 57 Add all new files and remove all missing files from the
58 58 repository.
59 59
60 60 New files are ignored if they match any of the patterns in
61 61 .hgignore. As with add, these changes take effect at the next
62 62 commit.
63 63
64 64 Use the -s/--similarity option to detect renamed files. With a
65 65 parameter greater than 0, this compares every removed file with
66 66 every added file and records those similar enough as renames. This
67 67 option takes a percentage between 0 (disabled) and 100 (files must
68 68 be identical) as its parameter. Detecting renamed files this way
69 69 can be expensive. After using this option, :hg:`status -C` can be
70 70 used to check which files were identified as moved or renamed.
71 71
72 72 Returns 0 if all files are successfully added.
73 73 """
74 74 try:
75 75 sim = float(opts.get('similarity') or 100)
76 76 except ValueError:
77 77 raise util.Abort(_('similarity must be a number'))
78 78 if sim < 0 or sim > 100:
79 79 raise util.Abort(_('similarity must be between 0 and 100'))
80 80 return cmdutil.addremove(repo, pats, opts, similarity=sim / 100.0)
81 81
82 82 def annotate(ui, repo, *pats, **opts):
83 83 """show changeset information by line for each file
84 84
85 85 List changes in files, showing the revision id responsible for
86 86 each line
87 87
88 88 This command is useful for discovering when a change was made and
89 89 by whom.
90 90
91 91 Without the -a/--text option, annotate will avoid processing files
92 92 it detects as binary. With -a, annotate will annotate the file
93 93 anyway, although the results will probably be neither useful
94 94 nor desirable.
95 95
96 96 Returns 0 on success.
97 97 """
98 98 if opts.get('follow'):
99 99 # --follow is deprecated and now just an alias for -f/--file
100 100 # to mimic the behavior of Mercurial before version 1.5
101 101 opts['file'] = 1
102 102
103 103 datefunc = ui.quiet and util.shortdate or util.datestr
104 104 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
105 105
106 106 if not pats:
107 107 raise util.Abort(_('at least one filename or pattern is required'))
108 108
109 109 opmap = [('user', lambda x: ui.shortuser(x[0].user())),
110 110 ('number', lambda x: str(x[0].rev())),
111 111 ('changeset', lambda x: short(x[0].node())),
112 112 ('date', getdate),
113 113 ('file', lambda x: x[0].path()),
114 114 ]
115 115
116 116 if (not opts.get('user') and not opts.get('changeset')
117 117 and not opts.get('date') and not opts.get('file')):
118 118 opts['number'] = 1
119 119
120 120 linenumber = opts.get('line_number') is not None
121 121 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
122 122 raise util.Abort(_('at least one of -n/-c is required for -l'))
123 123
124 124 funcmap = [func for op, func in opmap if opts.get(op)]
125 125 if linenumber:
126 126 lastfunc = funcmap[-1]
127 127 funcmap[-1] = lambda x: "%s:%s" % (lastfunc(x), x[1])
128 128
129 ctx = repo[opts.get('rev')]
129 ctx = cmdutil.revsingle(repo, opts.get('rev'))
130 130 m = cmdutil.match(repo, pats, opts)
131 131 follow = not opts.get('no_follow')
132 132 for abs in ctx.walk(m):
133 133 fctx = ctx[abs]
134 134 if not opts.get('text') and util.binary(fctx.data()):
135 135 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
136 136 continue
137 137
138 138 lines = fctx.annotate(follow=follow, linenumber=linenumber)
139 139 pieces = []
140 140
141 141 for f in funcmap:
142 142 l = [f(n) for n, dummy in lines]
143 143 if l:
144 144 sized = [(x, encoding.colwidth(x)) for x in l]
145 145 ml = max([w for x, w in sized])
146 146 pieces.append(["%s%s" % (' ' * (ml - w), x) for x, w in sized])
147 147
148 148 if pieces:
149 149 for p, l in zip(zip(*pieces), lines):
150 150 ui.write("%s: %s" % (" ".join(p), l[1]))
151 151
152 152 def archive(ui, repo, dest, **opts):
153 153 '''create an unversioned archive of a repository revision
154 154
155 155 By default, the revision used is the parent of the working
156 156 directory; use -r/--rev to specify a different revision.
157 157
158 158 The archive type is automatically detected based on file
159 159 extension (or override using -t/--type).
160 160
161 161 Valid types are:
162 162
163 163 :``files``: a directory full of files (default)
164 164 :``tar``: tar archive, uncompressed
165 165 :``tbz2``: tar archive, compressed using bzip2
166 166 :``tgz``: tar archive, compressed using gzip
167 167 :``uzip``: zip archive, uncompressed
168 168 :``zip``: zip archive, compressed using deflate
169 169
170 170 The exact name of the destination archive or directory is given
171 171 using a format string; see :hg:`help export` for details.
172 172
173 173 Each member added to an archive file has a directory prefix
174 174 prepended. Use -p/--prefix to specify a format string for the
175 175 prefix. The default is the basename of the archive, with suffixes
176 176 removed.
177 177
178 178 Returns 0 on success.
179 179 '''
180 180
181 ctx = repo[opts.get('rev')]
181 ctx = cmdutil.revsingle(repo, opts.get('rev'))
182 182 if not ctx:
183 183 raise util.Abort(_('no working directory: please specify a revision'))
184 184 node = ctx.node()
185 185 dest = cmdutil.make_filename(repo, dest, node)
186 186 if os.path.realpath(dest) == repo.root:
187 187 raise util.Abort(_('repository root cannot be destination'))
188 188
189 189 kind = opts.get('type') or archival.guesskind(dest) or 'files'
190 190 prefix = opts.get('prefix')
191 191
192 192 if dest == '-':
193 193 if kind == 'files':
194 194 raise util.Abort(_('cannot archive plain files to stdout'))
195 195 dest = sys.stdout
196 196 if not prefix:
197 197 prefix = os.path.basename(repo.root) + '-%h'
198 198
199 199 prefix = cmdutil.make_filename(repo, prefix, node)
200 200 matchfn = cmdutil.match(repo, [], opts)
201 201 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
202 202 matchfn, prefix, subrepos=opts.get('subrepos'))
203 203
204 204 def backout(ui, repo, node=None, rev=None, **opts):
205 205 '''reverse effect of earlier changeset
206 206
207 207 The backout command merges the reverse effect of the reverted
208 208 changeset into the working directory.
209 209
210 210 With the --merge option, it first commits the reverted changes
211 211 as a new changeset. This new changeset is a child of the reverted
212 212 changeset.
213 213 The --merge option remembers the parent of the working directory
214 214 before starting the backout, then merges the new head with that
215 215 changeset afterwards.
216 216 This will result in an explicit merge in the history.
217 217
218 218 If you backout a changeset other than the original parent of the
219 219 working directory, the result of this merge is not committed,
220 220 as with a normal merge. Otherwise, no merge is needed and the
221 221 commit is automatic.
222 222
223 223 Note that the default behavior (without --merge) has changed in
224 224 version 1.7. To restore the previous default behavior, use
225 225 :hg:`backout --merge` and then :hg:`update --clean .` to get rid of
226 226 the ongoing merge.
227 227
228 228 See :hg:`help dates` for a list of formats valid for -d/--date.
229 229
230 230 Returns 0 on success.
231 231 '''
232 232 if rev and node:
233 233 raise util.Abort(_("please specify just one revision"))
234 234
235 235 if not rev:
236 236 rev = node
237 237
238 238 if not rev:
239 239 raise util.Abort(_("please specify a revision to backout"))
240 240
241 241 date = opts.get('date')
242 242 if date:
243 243 opts['date'] = util.parsedate(date)
244 244
245 245 cmdutil.bail_if_changed(repo)
246 node = repo.lookup(rev)
246 node = cmdutil.revsingle(repo, rev).node()
247 247
248 248 op1, op2 = repo.dirstate.parents()
249 249 a = repo.changelog.ancestor(op1, node)
250 250 if a != node:
251 251 raise util.Abort(_('cannot backout change on a different branch'))
252 252
253 253 p1, p2 = repo.changelog.parents(node)
254 254 if p1 == nullid:
255 255 raise util.Abort(_('cannot backout a change with no parents'))
256 256 if p2 != nullid:
257 257 if not opts.get('parent'):
258 258 raise util.Abort(_('cannot backout a merge changeset without '
259 259 '--parent'))
260 260 p = repo.lookup(opts['parent'])
261 261 if p not in (p1, p2):
262 262 raise util.Abort(_('%s is not a parent of %s') %
263 263 (short(p), short(node)))
264 264 parent = p
265 265 else:
266 266 if opts.get('parent'):
267 267 raise util.Abort(_('cannot use --parent on non-merge changeset'))
268 268 parent = p1
269 269
270 270 # the backout should appear on the same branch
271 271 branch = repo.dirstate.branch()
272 272 hg.clean(repo, node, show_stats=False)
273 273 repo.dirstate.setbranch(branch)
274 274 revert_opts = opts.copy()
275 275 revert_opts['date'] = None
276 276 revert_opts['all'] = True
277 277 revert_opts['rev'] = hex(parent)
278 278 revert_opts['no_backup'] = None
279 279 revert(ui, repo, **revert_opts)
280 280 if not opts.get('merge') and op1 != node:
281 281 try:
282 282 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
283 283 return hg.update(repo, op1)
284 284 finally:
285 285 ui.setconfig('ui', 'forcemerge', '')
286 286
287 287 commit_opts = opts.copy()
288 288 commit_opts['addremove'] = False
289 289 if not commit_opts['message'] and not commit_opts['logfile']:
290 290 # we don't translate commit messages
291 291 commit_opts['message'] = "Backed out changeset %s" % short(node)
292 292 commit_opts['force_editor'] = True
293 293 commit(ui, repo, **commit_opts)
294 294 def nice(node):
295 295 return '%d:%s' % (repo.changelog.rev(node), short(node))
296 296 ui.status(_('changeset %s backs out changeset %s\n') %
297 297 (nice(repo.changelog.tip()), nice(node)))
298 298 if opts.get('merge') and op1 != node:
299 299 hg.clean(repo, op1, show_stats=False)
300 300 ui.status(_('merging with changeset %s\n')
301 301 % nice(repo.changelog.tip()))
302 302 try:
303 303 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
304 304 return hg.merge(repo, hex(repo.changelog.tip()))
305 305 finally:
306 306 ui.setconfig('ui', 'forcemerge', '')
307 307 return 0
308 308
309 309 def bisect(ui, repo, rev=None, extra=None, command=None,
310 310 reset=None, good=None, bad=None, skip=None, noupdate=None):
311 311 """subdivision search of changesets
312 312
313 313 This command helps to find changesets which introduce problems. To
314 314 use, mark the earliest changeset you know exhibits the problem as
315 315 bad, then mark the latest changeset which is free from the problem
316 316 as good. Bisect will update your working directory to a revision
317 317 for testing (unless the -U/--noupdate option is specified). Once
318 318 you have performed tests, mark the working directory as good or
319 319 bad, and bisect will either update to another candidate changeset
320 320 or announce that it has found the bad revision.
321 321
322 322 As a shortcut, you can also use the revision argument to mark a
323 323 revision as good or bad without checking it out first.
324 324
325 325 If you supply a command, it will be used for automatic bisection.
326 326 Its exit status will be used to mark revisions as good or bad:
327 327 status 0 means good, 125 means to skip the revision, 127
328 328 (command not found) will abort the bisection, and any other
329 329 non-zero exit status means the revision is bad.
330 330
331 331 Returns 0 on success.
332 332 """
333 333 def print_result(nodes, good):
334 334 displayer = cmdutil.show_changeset(ui, repo, {})
335 335 if len(nodes) == 1:
336 336 # narrowed it down to a single revision
337 337 if good:
338 338 ui.write(_("The first good revision is:\n"))
339 339 else:
340 340 ui.write(_("The first bad revision is:\n"))
341 341 displayer.show(repo[nodes[0]])
342 342 parents = repo[nodes[0]].parents()
343 343 if len(parents) > 1:
344 344 side = good and state['bad'] or state['good']
345 345 num = len(set(i.node() for i in parents) & set(side))
346 346 if num == 1:
347 347 common = parents[0].ancestor(parents[1])
348 348 ui.write(_('Not all ancestors of this changeset have been'
349 349 ' checked.\nTo check the other ancestors, start'
350 350 ' from the common ancestor, %s.\n' % common))
351 351 else:
352 352 # multiple possible revisions
353 353 if good:
354 354 ui.write(_("Due to skipped revisions, the first "
355 355 "good revision could be any of:\n"))
356 356 else:
357 357 ui.write(_("Due to skipped revisions, the first "
358 358 "bad revision could be any of:\n"))
359 359 for n in nodes:
360 360 displayer.show(repo[n])
361 361 displayer.close()
362 362
363 363 def check_state(state, interactive=True):
364 364 if not state['good'] or not state['bad']:
365 365 if (good or bad or skip or reset) and interactive:
366 366 return
367 367 if not state['good']:
368 368 raise util.Abort(_('cannot bisect (no known good revisions)'))
369 369 else:
370 370 raise util.Abort(_('cannot bisect (no known bad revisions)'))
371 371 return True
372 372
373 373 # backward compatibility
374 374 if rev in "good bad reset init".split():
375 375 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
376 376 cmd, rev, extra = rev, extra, None
377 377 if cmd == "good":
378 378 good = True
379 379 elif cmd == "bad":
380 380 bad = True
381 381 else:
382 382 reset = True
383 383 elif extra or good + bad + skip + reset + bool(command) > 1:
384 384 raise util.Abort(_('incompatible arguments'))
385 385
386 386 if reset:
387 387 p = repo.join("bisect.state")
388 388 if os.path.exists(p):
389 389 os.unlink(p)
390 390 return
391 391
392 392 state = hbisect.load_state(repo)
393 393
394 394 if command:
395 395 changesets = 1
396 396 try:
397 397 while changesets:
398 398 # update state
399 399 status = util.system(command)
400 400 if status == 125:
401 401 transition = "skip"
402 402 elif status == 0:
403 403 transition = "good"
404 404 # status < 0 means process was killed
405 405 elif status == 127:
406 406 raise util.Abort(_("failed to execute %s") % command)
407 407 elif status < 0:
408 408 raise util.Abort(_("%s killed") % command)
409 409 else:
410 410 transition = "bad"
411 ctx = repo[rev or '.']
411 ctx = cmdutil.revsingle(repo, rev)
412 rev = None # clear for future iterations
412 413 state[transition].append(ctx.node())
413 414 ui.status(_('Changeset %d:%s: %s\n') % (ctx, ctx, transition))
414 415 check_state(state, interactive=False)
415 416 # bisect
416 417 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
417 418 # update to next check
418 419 cmdutil.bail_if_changed(repo)
419 420 hg.clean(repo, nodes[0], show_stats=False)
420 421 finally:
421 422 hbisect.save_state(repo, state)
422 423 print_result(nodes, good)
423 424 return
424 425
425 426 # update state
426 427
427 428 if rev:
428 429 nodes = [repo.lookup(i) for i in cmdutil.revrange(repo, [rev])]
429 430 else:
430 431 nodes = [repo.lookup('.')]
431 432
432 433 if good or bad or skip:
433 434 if good:
434 435 state['good'] += nodes
435 436 elif bad:
436 437 state['bad'] += nodes
437 438 elif skip:
438 439 state['skip'] += nodes
439 440 hbisect.save_state(repo, state)
440 441
441 442 if not check_state(state):
442 443 return
443 444
444 445 # actually bisect
445 446 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
446 447 if changesets == 0:
447 448 print_result(nodes, good)
448 449 else:
449 450 assert len(nodes) == 1 # only a single node can be tested next
450 451 node = nodes[0]
451 452 # compute the approximate number of remaining tests
452 453 tests, size = 0, 2
453 454 while size <= changesets:
454 455 tests, size = tests + 1, size * 2
455 456 rev = repo.changelog.rev(node)
456 457 ui.write(_("Testing changeset %d:%s "
457 458 "(%d changesets remaining, ~%d tests)\n")
458 459 % (rev, short(node), changesets, tests))
459 460 if not noupdate:
460 461 cmdutil.bail_if_changed(repo)
461 462 return hg.clean(repo, node)
462 463
463 464 def branch(ui, repo, label=None, **opts):
464 465 """set or show the current branch name
465 466
466 467 With no argument, show the current branch name. With one argument,
467 468 set the working directory branch name (the branch will not exist
468 469 in the repository until the next commit). Standard practice
469 470 recommends that primary development take place on the 'default'
470 471 branch.
471 472
472 473 Unless -f/--force is specified, branch will not let you set a
473 474 branch name that already exists, even if it's inactive.
474 475
475 476 Use -C/--clean to reset the working directory branch to that of
476 477 the parent of the working directory, negating a previous branch
477 478 change.
478 479
479 480 Use the command :hg:`update` to switch to an existing branch. Use
480 481 :hg:`commit --close-branch` to mark this branch as closed.
481 482
482 483 Returns 0 on success.
483 484 """
484 485
485 486 if opts.get('clean'):
486 487 label = repo[None].parents()[0].branch()
487 488 repo.dirstate.setbranch(label)
488 489 ui.status(_('reset working directory to branch %s\n') % label)
489 490 elif label:
490 491 utflabel = encoding.fromlocal(label)
491 492 if not opts.get('force') and utflabel in repo.branchtags():
492 493 if label not in [p.branch() for p in repo.parents()]:
493 494 raise util.Abort(_('a branch of the same name already exists'
494 495 " (use 'hg update' to switch to it)"))
495 496 repo.dirstate.setbranch(utflabel)
496 497 ui.status(_('marked working directory as branch %s\n') % label)
497 498 else:
498 499 ui.write("%s\n" % encoding.tolocal(repo.dirstate.branch()))
499 500
500 501 def branches(ui, repo, active=False, closed=False):
501 502 """list repository named branches
502 503
503 504 List the repository's named branches, indicating which ones are
504 505 inactive. If -c/--closed is specified, also list branches which have
505 506 been marked closed (see :hg:`commit --close-branch`).
506 507
507 508 If -a/--active is specified, only show active branches. A branch
508 509 is considered active if it contains repository heads.
509 510
510 511 Use the command :hg:`update` to switch to an existing branch.
511 512
512 513 Returns 0.
513 514 """
514 515
515 516 hexfunc = ui.debugflag and hex or short
516 517 activebranches = [repo[n].branch() for n in repo.heads()]
517 518 def testactive(tag, node):
518 519 realhead = tag in activebranches
519 520 open = node in repo.branchheads(tag, closed=False)
520 521 return realhead and open
521 522 branches = sorted([(testactive(tag, node), repo.changelog.rev(node), tag)
522 523 for tag, node in repo.branchtags().items()],
523 524 reverse=True)
524 525
525 526 for isactive, node, tag in branches:
526 527 if (not active) or isactive:
527 528 encodedtag = encoding.tolocal(tag)
528 529 if ui.quiet:
529 530 ui.write("%s\n" % encodedtag)
530 531 else:
531 532 hn = repo.lookup(node)
532 533 if isactive:
533 534 label = 'branches.active'
534 535 notice = ''
535 536 elif hn not in repo.branchheads(tag, closed=False):
536 537 if not closed:
537 538 continue
538 539 label = 'branches.closed'
539 540 notice = _(' (closed)')
540 541 else:
541 542 label = 'branches.inactive'
542 543 notice = _(' (inactive)')
543 544 if tag == repo.dirstate.branch():
544 545 label = 'branches.current'
545 546 rev = str(node).rjust(31 - encoding.colwidth(encodedtag))
546 547 rev = ui.label('%s:%s' % (rev, hexfunc(hn)), 'log.changeset')
547 548 encodedtag = ui.label(encodedtag, label)
548 549 ui.write("%s %s%s\n" % (encodedtag, rev, notice))
549 550
550 551 def bundle(ui, repo, fname, dest=None, **opts):
551 552 """create a changegroup file
552 553
553 554 Generate a compressed changegroup file collecting changesets not
554 555 known to be in another repository.
555 556
556 557 If you omit the destination repository, then hg assumes the
557 558 destination will have all the nodes you specify with --base
558 559 parameters. To create a bundle containing all changesets, use
559 560 -a/--all (or --base null).
560 561
561 562 You can change compression method with the -t/--type option.
562 563 The available compression methods are: none, bzip2, and
563 564 gzip (by default, bundles are compressed using bzip2).
564 565
565 566 The bundle file can then be transferred using conventional means
566 567 and applied to another repository with the unbundle or pull
567 568 command. This is useful when direct push and pull are not
568 569 available or when exporting an entire repository is undesirable.
569 570
570 571 Applying bundles preserves all changeset contents including
571 572 permissions, copy/rename information, and revision history.
572 573
573 574 Returns 0 on success, 1 if no changes found.
574 575 """
575 revs = opts.get('rev') or None
576 revs = None
577 if 'rev' in opts:
578 revs = cmdutil.revrange(repo, opts['rev'])
579
576 580 if opts.get('all'):
577 581 base = ['null']
578 582 else:
579 base = opts.get('base')
583 base = cmdutil.revrange(repo, opts.get('base'))
580 584 if base:
581 585 if dest:
582 586 raise util.Abort(_("--base is incompatible with specifying "
583 587 "a destination"))
584 588 base = [repo.lookup(rev) for rev in base]
585 589 # create the right base
586 590 # XXX: nodesbetween / changegroup* should be "fixed" instead
587 591 o = []
588 592 has = set((nullid,))
589 593 for n in base:
590 594 has.update(repo.changelog.reachable(n))
591 595 if revs:
592 596 revs = [repo.lookup(rev) for rev in revs]
593 597 visit = revs[:]
594 598 has.difference_update(visit)
595 599 else:
596 600 visit = repo.changelog.heads()
597 601 seen = {}
598 602 while visit:
599 603 n = visit.pop(0)
600 604 parents = [p for p in repo.changelog.parents(n) if p not in has]
601 605 if len(parents) == 0:
602 606 if n not in has:
603 607 o.append(n)
604 608 else:
605 609 for p in parents:
606 610 if p not in seen:
607 611 seen[p] = 1
608 612 visit.append(p)
609 613 else:
610 614 dest = ui.expandpath(dest or 'default-push', dest or 'default')
611 615 dest, branches = hg.parseurl(dest, opts.get('branch'))
612 616 other = hg.repository(hg.remoteui(repo, opts), dest)
613 617 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
614 618 if revs:
615 619 revs = [repo.lookup(rev) for rev in revs]
616 620 o = discovery.findoutgoing(repo, other, force=opts.get('force'))
617 621
618 622 if not o:
619 623 ui.status(_("no changes found\n"))
620 624 return 1
621 625
622 626 if revs:
623 627 cg = repo.changegroupsubset(o, revs, 'bundle')
624 628 else:
625 629 cg = repo.changegroup(o, 'bundle')
626 630
627 631 bundletype = opts.get('type', 'bzip2').lower()
628 632 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
629 633 bundletype = btypes.get(bundletype)
630 634 if bundletype not in changegroup.bundletypes:
631 635 raise util.Abort(_('unknown bundle type specified with --type'))
632 636
633 637 changegroup.writebundle(cg, fname, bundletype)
634 638
635 639 def cat(ui, repo, file1, *pats, **opts):
636 640 """output the current or given revision of files
637 641
638 642 Print the specified files as they were at the given revision. If
639 643 no revision is given, the parent of the working directory is used,
640 644 or tip if no revision is checked out.
641 645
642 646 Output may be to a file, in which case the name of the file is
643 647 given using a format string. The formatting rules are the same as
644 648 for the export command, with the following additions:
645 649
646 650 :``%s``: basename of file being printed
647 651 :``%d``: dirname of file being printed, or '.' if in repository root
648 652 :``%p``: root-relative path name of file being printed
649 653
650 654 Returns 0 on success.
651 655 """
652 656 ctx = cmdutil.revsingle(repo, opts.get('rev'))
653 657 err = 1
654 658 m = cmdutil.match(repo, (file1,) + pats, opts)
655 659 for abs in ctx.walk(m):
656 660 fp = cmdutil.make_file(repo, opts.get('output'), ctx.node(), pathname=abs)
657 661 data = ctx[abs].data()
658 662 if opts.get('decode'):
659 663 data = repo.wwritedata(abs, data)
660 664 fp.write(data)
661 665 err = 0
662 666 return err
663 667
664 668 def clone(ui, source, dest=None, **opts):
665 669 """make a copy of an existing repository
666 670
667 671 Create a copy of an existing repository in a new directory.
668 672
669 673 If no destination directory name is specified, it defaults to the
670 674 basename of the source.
671 675
672 676 The location of the source is added to the new repository's
673 677 .hg/hgrc file, as the default to be used for future pulls.
674 678
675 679 See :hg:`help urls` for valid source format details.
676 680
677 681 It is possible to specify an ``ssh://`` URL as the destination, but no
678 682 .hg/hgrc and working directory will be created on the remote side.
679 683 Please see :hg:`help urls` for important details about ``ssh://`` URLs.
680 684
681 685 A set of changesets (tags, or branch names) to pull may be specified
682 686 by listing each changeset (tag, or branch name) with -r/--rev.
683 687 If -r/--rev is used, the cloned repository will contain only a subset
684 688 of the changesets of the source repository. Only the set of changesets
685 689 defined by all -r/--rev options (including all their ancestors)
686 690 will be pulled into the destination repository.
687 691 No subsequent changesets (including subsequent tags) will be present
688 692 in the destination.
689 693
690 694 Using -r/--rev (or 'clone src#rev dest') implies --pull, even for
691 695 local source repositories.
692 696
693 697 For efficiency, hardlinks are used for cloning whenever the source
694 698 and destination are on the same filesystem (note this applies only
695 699 to the repository data, not to the working directory). Some
696 700 filesystems, such as AFS, implement hardlinking incorrectly, but
697 701 do not report errors. In these cases, use the --pull option to
698 702 avoid hardlinking.
699 703
700 704 In some cases, you can clone repositories and the working directory
701 705 using full hardlinks with ::
702 706
703 707 $ cp -al REPO REPOCLONE
704 708
705 709 This is the fastest way to clone, but it is not always safe. The
706 710 operation is not atomic (making sure REPO is not modified during
707 711 the operation is up to you) and you have to make sure your editor
708 712 breaks hardlinks (Emacs and most Linux Kernel tools do so). Also,
709 713 this is not compatible with certain extensions that place their
710 714 metadata under the .hg directory, such as mq.
711 715
712 716 Mercurial will update the working directory to the first applicable
713 717 revision from this list:
714 718
715 719 a) null if -U or the source repository has no changesets
716 720 b) if -u . and the source repository is local, the first parent of
717 721 the source repository's working directory
718 722 c) the changeset specified with -u (if a branch name, this means the
719 723 latest head of that branch)
720 724 d) the changeset specified with -r
721 725 e) the tipmost head specified with -b
722 726 f) the tipmost head specified with the url#branch source syntax
723 727 g) the tipmost head of the default branch
724 728 h) tip
725 729
726 730 Returns 0 on success.
727 731 """
728 732 if opts.get('noupdate') and opts.get('updaterev'):
729 733 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
730 734
731 735 r = hg.clone(hg.remoteui(ui, opts), source, dest,
732 736 pull=opts.get('pull'),
733 737 stream=opts.get('uncompressed'),
734 738 rev=opts.get('rev'),
735 739 update=opts.get('updaterev') or not opts.get('noupdate'),
736 740 branch=opts.get('branch'))
737 741
738 742 return r is None
739 743
740 744 def commit(ui, repo, *pats, **opts):
741 745 """commit the specified files or all outstanding changes
742 746
743 747 Commit changes to the given files into the repository. Unlike a
744 748 centralized RCS, this operation is a local operation. See
745 749 :hg:`push` for a way to actively distribute your changes.
746 750
747 751 If a list of files is omitted, all changes reported by :hg:`status`
748 752 will be committed.
749 753
750 754 If you are committing the result of a merge, do not provide any
751 755 filenames or -I/-X filters.
752 756
753 757 If no commit message is specified, Mercurial starts your
754 758 configured editor where you can enter a message. In case your
755 759 commit fails, you will find a backup of your message in
756 760 ``.hg/last-message.txt``.
757 761
758 762 See :hg:`help dates` for a list of formats valid for -d/--date.
759 763
760 764 Returns 0 on success, 1 if nothing changed.
761 765 """
762 766 extra = {}
763 767 if opts.get('close_branch'):
764 768 if repo['.'].node() not in repo.branchheads():
765 769 # The topo heads set is included in the branch heads set of the
766 770 # current branch, so it's sufficient to test branchheads
767 771 raise util.Abort(_('can only close branch heads'))
768 772 extra['close'] = 1
769 773 e = cmdutil.commiteditor
770 774 if opts.get('force_editor'):
771 775 e = cmdutil.commitforceeditor
772 776
773 777 def commitfunc(ui, repo, message, match, opts):
774 778 return repo.commit(message, opts.get('user'), opts.get('date'), match,
775 779 editor=e, extra=extra)
776 780
777 781 branch = repo[None].branch()
778 782 bheads = repo.branchheads(branch)
779 783
780 784 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
781 785 if not node:
782 786 ui.status(_("nothing changed\n"))
783 787 return 1
784 788
785 789 ctx = repo[node]
786 790 parents = ctx.parents()
787 791
788 792 if bheads and not [x for x in parents
789 793 if x.node() in bheads and x.branch() == branch]:
790 794 ui.status(_('created new head\n'))
791 795 # The message is not printed for initial roots. For the other
792 796 # changesets, it is printed in the following situations:
793 797 #
794 798 # Par column: for the 2 parents with ...
795 799 # N: null or no parent
796 800 # B: parent is on another named branch
797 801 # C: parent is a regular non head changeset
798 802 # H: parent was a branch head of the current branch
799 803 # Msg column: whether we print "created new head" message
800 804 # In the following, it is assumed that there already exists some
801 805 # initial branch heads of the current branch, otherwise nothing is
802 806 # printed anyway.
803 807 #
804 808 # Par Msg Comment
805 809 # NN y additional topo root
806 810 #
807 811 # BN y additional branch root
808 812 # CN y additional topo head
809 813 # HN n usual case
810 814 #
811 815 # BB y weird additional branch root
812 816 # CB y branch merge
813 817 # HB n merge with named branch
814 818 #
815 819 # CC y additional head from merge
816 820 # CH n merge with a head
817 821 #
818 822 # HH n head merge: head count decreases
819 823
820 824 if not opts.get('close_branch'):
821 825 for r in parents:
822 826 if r.extra().get('close') and r.branch() == branch:
823 827 ui.status(_('reopening closed branch head %d\n') % r)
824 828
825 829 if ui.debugflag:
826 830 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
827 831 elif ui.verbose:
828 832 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
829 833
830 834 def copy(ui, repo, *pats, **opts):
831 835 """mark files as copied for the next commit
832 836
833 837 Mark dest as having copies of source files. If dest is a
834 838 directory, copies are put in that directory. If dest is a file,
835 839 the source must be a single file.
836 840
837 841 By default, this command copies the contents of files as they
838 842 exist in the working directory. If invoked with -A/--after, the
839 843 operation is recorded, but no copying is performed.
840 844
841 845 This command takes effect with the next commit. To undo a copy
842 846 before that, see :hg:`revert`.
843 847
844 848 Returns 0 on success, 1 if errors are encountered.
845 849 """
846 850 wlock = repo.wlock(False)
847 851 try:
848 852 return cmdutil.copy(ui, repo, pats, opts)
849 853 finally:
850 854 wlock.release()
851 855
852 856 def debugancestor(ui, repo, *args):
853 857 """find the ancestor revision of two revisions in a given index"""
854 858 if len(args) == 3:
855 859 index, rev1, rev2 = args
856 860 r = revlog.revlog(util.opener(os.getcwd(), audit=False), index)
857 861 lookup = r.lookup
858 862 elif len(args) == 2:
859 863 if not repo:
860 864 raise util.Abort(_("there is no Mercurial repository here "
861 865 "(.hg not found)"))
862 866 rev1, rev2 = args
863 867 r = repo.changelog
864 868 lookup = repo.lookup
865 869 else:
866 870 raise util.Abort(_('either two or three arguments required'))
867 871 a = r.ancestor(lookup(rev1), lookup(rev2))
868 872 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
869 873
870 874 def debugbuilddag(ui, repo, text,
871 875 mergeable_file=False,
872 876 appended_file=False,
873 877 overwritten_file=False,
874 878 new_file=False):
875 879 """builds a repo with a given dag from scratch in the current empty repo
876 880
877 881 Elements:
878 882
879 883 - "+n" is a linear run of n nodes based on the current default parent
880 884 - "." is a single node based on the current default parent
881 885 - "$" resets the default parent to null (implied at the start);
882 886 otherwise the default parent is always the last node created
883 887 - "<p" sets the default parent to the backref p
884 888 - "*p" is a fork at parent p, which is a backref
885 889 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
886 890 - "/p2" is a merge of the preceding node and p2
887 891 - ":tag" defines a local tag for the preceding node
888 892 - "@branch" sets the named branch for subsequent nodes
889 893 - "!command" runs the command using your shell
890 894 - "!!my command\\n" is like "!", but to the end of the line
891 895 - "#...\\n" is a comment up to the end of the line
892 896
893 897 Whitespace between the above elements is ignored.
894 898
895 899 A backref is either
896 900
897 901 - a number n, which references the node curr-n, where curr is the current
898 902 node, or
899 903 - the name of a local tag you placed earlier using ":tag", or
900 904 - empty to denote the default parent.
901 905
902 906 All string valued-elements are either strictly alphanumeric, or must
903 907 be enclosed in double quotes ("..."), with "\\" as escape character.
904 908
905 909 Note that the --overwritten-file and --appended-file options imply the
906 910 use of "HGMERGE=internal:local" during DAG buildup.
907 911 """
908 912
909 913 if not (mergeable_file or appended_file or overwritten_file or new_file):
910 914 raise util.Abort(_('need at least one of -m, -a, -o, -n'))
911 915
912 916 if len(repo.changelog) > 0:
913 917 raise util.Abort(_('repository is not empty'))
914 918
915 919 if overwritten_file or appended_file:
916 920 # we don't want to fail in merges during buildup
917 921 os.environ['HGMERGE'] = 'internal:local'
918 922
919 923 def writefile(fname, text, fmode="wb"):
920 924 f = open(fname, fmode)
921 925 try:
922 926 f.write(text)
923 927 finally:
924 928 f.close()
925 929
926 930 if mergeable_file:
927 931 linesperrev = 2
928 932 # determine number of revs in DAG
929 933 n = 0
930 934 for type, data in dagparser.parsedag(text):
931 935 if type == 'n':
932 936 n += 1
933 937 # make a file with k lines per rev
934 938 writefile("mf", "\n".join(str(i) for i in xrange(0, n * linesperrev))
935 939 + "\n")
936 940
937 941 at = -1
938 942 atbranch = 'default'
939 943 for type, data in dagparser.parsedag(text):
940 944 if type == 'n':
941 945 ui.status('node %s\n' % str(data))
942 946 id, ps = data
943 947 p1 = ps[0]
944 948 if p1 != at:
945 949 update(ui, repo, node=str(p1), clean=True)
946 950 at = p1
947 951 if repo.dirstate.branch() != atbranch:
948 952 branch(ui, repo, atbranch, force=True)
949 953 if len(ps) > 1:
950 954 p2 = ps[1]
951 955 merge(ui, repo, node=p2)
952 956
953 957 if mergeable_file:
954 958 f = open("mf", "rb+")
955 959 try:
956 960 lines = f.read().split("\n")
957 961 lines[id * linesperrev] += " r%i" % id
958 962 f.seek(0)
959 963 f.write("\n".join(lines))
960 964 finally:
961 965 f.close()
962 966
963 967 if appended_file:
964 968 writefile("af", "r%i\n" % id, "ab")
965 969
966 970 if overwritten_file:
967 971 writefile("of", "r%i\n" % id)
968 972
969 973 if new_file:
970 974 writefile("nf%i" % id, "r%i\n" % id)
971 975
972 976 commit(ui, repo, addremove=True, message="r%i" % id, date=(id, 0))
973 977 at = id
974 978 elif type == 'l':
975 979 id, name = data
976 980 ui.status('tag %s\n' % name)
977 981 tag(ui, repo, name, local=True)
978 982 elif type == 'a':
979 983 ui.status('branch %s\n' % data)
980 984 atbranch = data
981 985 elif type in 'cC':
982 986 r = util.system(data, cwd=repo.root)
983 987 if r:
984 988 desc, r = util.explain_exit(r)
985 989 raise util.Abort(_('%s command %s') % (data, desc))
986 990
987 991 def debugcommands(ui, cmd='', *args):
988 992 """list all available commands and options"""
989 993 for cmd, vals in sorted(table.iteritems()):
990 994 cmd = cmd.split('|')[0].strip('^')
991 995 opts = ', '.join([i[1] for i in vals[1]])
992 996 ui.write('%s: %s\n' % (cmd, opts))
993 997
994 998 def debugcomplete(ui, cmd='', **opts):
995 999 """returns the completion list associated with the given command"""
996 1000
997 1001 if opts.get('options'):
998 1002 options = []
999 1003 otables = [globalopts]
1000 1004 if cmd:
1001 1005 aliases, entry = cmdutil.findcmd(cmd, table, False)
1002 1006 otables.append(entry[1])
1003 1007 for t in otables:
1004 1008 for o in t:
1005 1009 if "(DEPRECATED)" in o[3]:
1006 1010 continue
1007 1011 if o[0]:
1008 1012 options.append('-%s' % o[0])
1009 1013 options.append('--%s' % o[1])
1010 1014 ui.write("%s\n" % "\n".join(options))
1011 1015 return
1012 1016
1013 1017 cmdlist = cmdutil.findpossible(cmd, table)
1014 1018 if ui.verbose:
1015 1019 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1016 1020 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1017 1021
1018 1022 def debugfsinfo(ui, path = "."):
1019 1023 """show information detected about current filesystem"""
1020 1024 open('.debugfsinfo', 'w').write('')
1021 1025 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
1022 1026 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
1023 1027 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
1024 1028 and 'yes' or 'no'))
1025 1029 os.unlink('.debugfsinfo')
1026 1030
1027 1031 def debugrebuildstate(ui, repo, rev="tip"):
1028 1032 """rebuild the dirstate as it would look like for the given revision"""
1029 ctx = repo[rev]
1033 ctx = cmdutil.revsingle(repo, rev)
1030 1034 wlock = repo.wlock()
1031 1035 try:
1032 1036 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1033 1037 finally:
1034 1038 wlock.release()
1035 1039
1036 1040 def debugcheckstate(ui, repo):
1037 1041 """validate the correctness of the current dirstate"""
1038 1042 parent1, parent2 = repo.dirstate.parents()
1039 1043 m1 = repo[parent1].manifest()
1040 1044 m2 = repo[parent2].manifest()
1041 1045 errors = 0
1042 1046 for f in repo.dirstate:
1043 1047 state = repo.dirstate[f]
1044 1048 if state in "nr" and f not in m1:
1045 1049 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1046 1050 errors += 1
1047 1051 if state in "a" and f in m1:
1048 1052 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1049 1053 errors += 1
1050 1054 if state in "m" and f not in m1 and f not in m2:
1051 1055 ui.warn(_("%s in state %s, but not in either manifest\n") %
1052 1056 (f, state))
1053 1057 errors += 1
1054 1058 for f in m1:
1055 1059 state = repo.dirstate[f]
1056 1060 if state not in "nrm":
1057 1061 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1058 1062 errors += 1
1059 1063 if errors:
1060 1064 error = _(".hg/dirstate inconsistent with current parent's manifest")
1061 1065 raise util.Abort(error)
1062 1066
1063 1067 def showconfig(ui, repo, *values, **opts):
1064 1068 """show combined config settings from all hgrc files
1065 1069
1066 1070 With no arguments, print names and values of all config items.
1067 1071
1068 1072 With one argument of the form section.name, print just the value
1069 1073 of that config item.
1070 1074
1071 1075 With multiple arguments, print names and values of all config
1072 1076 items with matching section names.
1073 1077
1074 1078 With --debug, the source (filename and line number) is printed
1075 1079 for each config item.
1076 1080
1077 1081 Returns 0 on success.
1078 1082 """
1079 1083
1080 1084 for f in util.rcpath():
1081 1085 ui.debug(_('read config from: %s\n') % f)
1082 1086 untrusted = bool(opts.get('untrusted'))
1083 1087 if values:
1084 1088 sections = [v for v in values if '.' not in v]
1085 1089 items = [v for v in values if '.' in v]
1086 1090 if len(items) > 1 or items and sections:
1087 1091 raise util.Abort(_('only one config item permitted'))
1088 1092 for section, name, value in ui.walkconfig(untrusted=untrusted):
1089 1093 sectname = section + '.' + name
1090 1094 if values:
1091 1095 for v in values:
1092 1096 if v == section:
1093 1097 ui.debug('%s: ' %
1094 1098 ui.configsource(section, name, untrusted))
1095 1099 ui.write('%s=%s\n' % (sectname, value))
1096 1100 elif v == sectname:
1097 1101 ui.debug('%s: ' %
1098 1102 ui.configsource(section, name, untrusted))
1099 1103 ui.write(value, '\n')
1100 1104 else:
1101 1105 ui.debug('%s: ' %
1102 1106 ui.configsource(section, name, untrusted))
1103 1107 ui.write('%s=%s\n' % (sectname, value))
1104 1108
1105 1109 def debugpushkey(ui, repopath, namespace, *keyinfo):
1106 1110 '''access the pushkey key/value protocol
1107 1111
1108 1112 With two args, list the keys in the given namespace.
1109 1113
1110 1114 With five args, set a key to new if it currently is set to old.
1111 1115 Reports success or failure.
1112 1116 '''
1113 1117
1114 1118 target = hg.repository(ui, repopath)
1115 1119 if keyinfo:
1116 1120 key, old, new = keyinfo
1117 1121 r = target.pushkey(namespace, key, old, new)
1118 1122 ui.status(str(r) + '\n')
1119 1123 return not(r)
1120 1124 else:
1121 1125 for k, v in target.listkeys(namespace).iteritems():
1122 1126 ui.write("%s\t%s\n" % (k.encode('string-escape'),
1123 1127 v.encode('string-escape')))
1124 1128
1125 1129 def debugrevspec(ui, repo, expr):
1126 1130 '''parse and apply a revision specification'''
1127 1131 if ui.verbose:
1128 1132 tree = revset.parse(expr)
1129 1133 ui.note(tree, "\n")
1130 1134 func = revset.match(expr)
1131 1135 for c in func(repo, range(len(repo))):
1132 1136 ui.write("%s\n" % c)
1133 1137
1134 1138 def debugsetparents(ui, repo, rev1, rev2=None):
1135 1139 """manually set the parents of the current working directory
1136 1140
1137 1141 This is useful for writing repository conversion tools, but should
1138 1142 be used with care.
1139 1143
1140 1144 Returns 0 on success.
1141 1145 """
1142 1146
1143 if not rev2:
1144 rev2 = hex(nullid)
1147 r1 = cmdutil.revsingle(repo, rev1).node()
1148 r2 = cmdutil.revsingle(repo, rev2, 'null').node()
1145 1149
1146 1150 wlock = repo.wlock()
1147 1151 try:
1148 repo.dirstate.setparents(repo.lookup(rev1), repo.lookup(rev2))
1152 repo.dirstate.setparents(r1, r2)
1149 1153 finally:
1150 1154 wlock.release()
1151 1155
1152 1156 def debugstate(ui, repo, nodates=None):
1153 1157 """show the contents of the current dirstate"""
1154 1158 timestr = ""
1155 1159 showdate = not nodates
1156 1160 for file_, ent in sorted(repo.dirstate._map.iteritems()):
1157 1161 if showdate:
1158 1162 if ent[3] == -1:
1159 1163 # Pad or slice to locale representation
1160 1164 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
1161 1165 time.localtime(0)))
1162 1166 timestr = 'unset'
1163 1167 timestr = (timestr[:locale_len] +
1164 1168 ' ' * (locale_len - len(timestr)))
1165 1169 else:
1166 1170 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
1167 1171 time.localtime(ent[3]))
1168 1172 if ent[1] & 020000:
1169 1173 mode = 'lnk'
1170 1174 else:
1171 1175 mode = '%3o' % (ent[1] & 0777)
1172 1176 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
1173 1177 for f in repo.dirstate.copies():
1174 1178 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
1175 1179
1176 1180 def debugsub(ui, repo, rev=None):
1177 if rev == '':
1178 rev = None
1179 for k, v in sorted(repo[rev].substate.items()):
1181 ctx = cmdutil.revsingle(repo, rev, None)
1182 for k, v in sorted(ctx.substate.items()):
1180 1183 ui.write('path %s\n' % k)
1181 1184 ui.write(' source %s\n' % v[0])
1182 1185 ui.write(' revision %s\n' % v[1])
1183 1186
1184 1187 def debugdag(ui, repo, file_=None, *revs, **opts):
1185 1188 """format the changelog or an index DAG as a concise textual description
1186 1189
1187 1190 If you pass a revlog index, the revlog's DAG is emitted. If you list
1188 1191 revision numbers, they get labelled in the output as rN.
1189 1192
1190 1193 Otherwise, the changelog DAG of the current repo is emitted.
1191 1194 """
1192 1195 spaces = opts.get('spaces')
1193 1196 dots = opts.get('dots')
1194 1197 if file_:
1195 1198 rlog = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
1196 1199 revs = set((int(r) for r in revs))
1197 1200 def events():
1198 1201 for r in rlog:
1199 1202 yield 'n', (r, list(set(p for p in rlog.parentrevs(r) if p != -1)))
1200 1203 if r in revs:
1201 1204 yield 'l', (r, "r%i" % r)
1202 1205 elif repo:
1203 1206 cl = repo.changelog
1204 1207 tags = opts.get('tags')
1205 1208 branches = opts.get('branches')
1206 1209 if tags:
1207 1210 labels = {}
1208 1211 for l, n in repo.tags().items():
1209 1212 labels.setdefault(cl.rev(n), []).append(l)
1210 1213 def events():
1211 1214 b = "default"
1212 1215 for r in cl:
1213 1216 if branches:
1214 1217 newb = cl.read(cl.node(r))[5]['branch']
1215 1218 if newb != b:
1216 1219 yield 'a', newb
1217 1220 b = newb
1218 1221 yield 'n', (r, list(set(p for p in cl.parentrevs(r) if p != -1)))
1219 1222 if tags:
1220 1223 ls = labels.get(r)
1221 1224 if ls:
1222 1225 for l in ls:
1223 1226 yield 'l', (r, l)
1224 1227 else:
1225 1228 raise util.Abort(_('need repo for changelog dag'))
1226 1229
1227 1230 for line in dagparser.dagtextlines(events(),
1228 1231 addspaces=spaces,
1229 1232 wraplabels=True,
1230 1233 wrapannotations=True,
1231 1234 wrapnonlinear=dots,
1232 1235 usedots=dots,
1233 1236 maxlinewidth=70):
1234 1237 ui.write(line)
1235 1238 ui.write("\n")
1236 1239
1237 1240 def debugdata(ui, repo, file_, rev):
1238 1241 """dump the contents of a data file revision"""
1239 1242 r = None
1240 1243 if repo:
1241 1244 filelog = repo.file(file_)
1242 1245 if len(filelog):
1243 1246 r = filelog
1244 1247 if not r:
1245 1248 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_[:-2] + ".i")
1246 1249 try:
1247 1250 ui.write(r.revision(r.lookup(rev)))
1248 1251 except KeyError:
1249 1252 raise util.Abort(_('invalid revision identifier %s') % rev)
1250 1253
1251 1254 def debugdate(ui, date, range=None, **opts):
1252 1255 """parse and display a date"""
1253 1256 if opts["extended"]:
1254 1257 d = util.parsedate(date, util.extendeddateformats)
1255 1258 else:
1256 1259 d = util.parsedate(date)
1257 1260 ui.write("internal: %s %s\n" % d)
1258 1261 ui.write("standard: %s\n" % util.datestr(d))
1259 1262 if range:
1260 1263 m = util.matchdate(range)
1261 1264 ui.write("match: %s\n" % m(d[0]))
1262 1265
1263 1266 def debugindex(ui, repo, file_, **opts):
1264 1267 """dump the contents of an index file"""
1265 1268 r = None
1266 1269 if repo:
1267 1270 filelog = repo.file(file_)
1268 1271 if len(filelog):
1269 1272 r = filelog
1270 1273
1271 1274 format = opts.get('format', 0)
1272 1275 if format not in (0, 1):
1273 1276 raise util.abort("unknown format %d" % format)
1274 1277
1275 1278 if not r:
1276 1279 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
1277 1280
1278 1281 if format == 0:
1279 1282 ui.write(" rev offset length base linkrev"
1280 1283 " nodeid p1 p2\n")
1281 1284 elif format == 1:
1282 1285 ui.write(" rev flag offset length"
1283 1286 " size base link p1 p2 nodeid\n")
1284 1287
1285 1288 for i in r:
1286 1289 node = r.node(i)
1287 1290 if format == 0:
1288 1291 try:
1289 1292 pp = r.parents(node)
1290 1293 except:
1291 1294 pp = [nullid, nullid]
1292 1295 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1293 1296 i, r.start(i), r.length(i), r.base(i), r.linkrev(i),
1294 1297 short(node), short(pp[0]), short(pp[1])))
1295 1298 elif format == 1:
1296 1299 pr = r.parentrevs(i)
1297 1300 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
1298 1301 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
1299 1302 r.base(i), r.linkrev(i), pr[0], pr[1], short(node)))
1300 1303
1301 1304 def debugindexdot(ui, repo, file_):
1302 1305 """dump an index DAG as a graphviz dot file"""
1303 1306 r = None
1304 1307 if repo:
1305 1308 filelog = repo.file(file_)
1306 1309 if len(filelog):
1307 1310 r = filelog
1308 1311 if not r:
1309 1312 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
1310 1313 ui.write("digraph G {\n")
1311 1314 for i in r:
1312 1315 node = r.node(i)
1313 1316 pp = r.parents(node)
1314 1317 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1315 1318 if pp[1] != nullid:
1316 1319 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1317 1320 ui.write("}\n")
1318 1321
1319 1322 def debuginstall(ui):
1320 1323 '''test Mercurial installation
1321 1324
1322 1325 Returns 0 on success.
1323 1326 '''
1324 1327
1325 1328 def writetemp(contents):
1326 1329 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
1327 1330 f = os.fdopen(fd, "wb")
1328 1331 f.write(contents)
1329 1332 f.close()
1330 1333 return name
1331 1334
1332 1335 problems = 0
1333 1336
1334 1337 # encoding
1335 1338 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
1336 1339 try:
1337 1340 encoding.fromlocal("test")
1338 1341 except util.Abort, inst:
1339 1342 ui.write(" %s\n" % inst)
1340 1343 ui.write(_(" (check that your locale is properly set)\n"))
1341 1344 problems += 1
1342 1345
1343 1346 # compiled modules
1344 1347 ui.status(_("Checking installed modules (%s)...\n")
1345 1348 % os.path.dirname(__file__))
1346 1349 try:
1347 1350 import bdiff, mpatch, base85, osutil
1348 1351 except Exception, inst:
1349 1352 ui.write(" %s\n" % inst)
1350 1353 ui.write(_(" One or more extensions could not be found"))
1351 1354 ui.write(_(" (check that you compiled the extensions)\n"))
1352 1355 problems += 1
1353 1356
1354 1357 # templates
1355 1358 ui.status(_("Checking templates...\n"))
1356 1359 try:
1357 1360 import templater
1358 1361 templater.templater(templater.templatepath("map-cmdline.default"))
1359 1362 except Exception, inst:
1360 1363 ui.write(" %s\n" % inst)
1361 1364 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
1362 1365 problems += 1
1363 1366
1364 1367 # patch
1365 1368 ui.status(_("Checking patch...\n"))
1366 1369 patchproblems = 0
1367 1370 a = "1\n2\n3\n4\n"
1368 1371 b = "1\n2\n3\ninsert\n4\n"
1369 1372 fa = writetemp(a)
1370 1373 d = mdiff.unidiff(a, None, b, None, os.path.basename(fa),
1371 1374 os.path.basename(fa))
1372 1375 fd = writetemp(d)
1373 1376
1374 1377 files = {}
1375 1378 try:
1376 1379 patch.patch(fd, ui, cwd=os.path.dirname(fa), files=files)
1377 1380 except util.Abort, e:
1378 1381 ui.write(_(" patch call failed:\n"))
1379 1382 ui.write(" " + str(e) + "\n")
1380 1383 patchproblems += 1
1381 1384 else:
1382 1385 if list(files) != [os.path.basename(fa)]:
1383 1386 ui.write(_(" unexpected patch output!\n"))
1384 1387 patchproblems += 1
1385 1388 a = open(fa).read()
1386 1389 if a != b:
1387 1390 ui.write(_(" patch test failed!\n"))
1388 1391 patchproblems += 1
1389 1392
1390 1393 if patchproblems:
1391 1394 if ui.config('ui', 'patch'):
1392 1395 ui.write(_(" (Current patch tool may be incompatible with patch,"
1393 1396 " or misconfigured. Please check your configuration"
1394 1397 " file)\n"))
1395 1398 else:
1396 1399 ui.write(_(" Internal patcher failure, please report this error"
1397 1400 " to http://mercurial.selenic.com/wiki/BugTracker\n"))
1398 1401 problems += patchproblems
1399 1402
1400 1403 os.unlink(fa)
1401 1404 os.unlink(fd)
1402 1405
1403 1406 # editor
1404 1407 ui.status(_("Checking commit editor...\n"))
1405 1408 editor = ui.geteditor()
1406 1409 cmdpath = util.find_exe(editor) or util.find_exe(editor.split()[0])
1407 1410 if not cmdpath:
1408 1411 if editor == 'vi':
1409 1412 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
1410 1413 ui.write(_(" (specify a commit editor in your configuration"
1411 1414 " file)\n"))
1412 1415 else:
1413 1416 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
1414 1417 ui.write(_(" (specify a commit editor in your configuration"
1415 1418 " file)\n"))
1416 1419 problems += 1
1417 1420
1418 1421 # check username
1419 1422 ui.status(_("Checking username...\n"))
1420 1423 try:
1421 1424 ui.username()
1422 1425 except util.Abort, e:
1423 1426 ui.write(" %s\n" % e)
1424 1427 ui.write(_(" (specify a username in your configuration file)\n"))
1425 1428 problems += 1
1426 1429
1427 1430 if not problems:
1428 1431 ui.status(_("No problems detected\n"))
1429 1432 else:
1430 1433 ui.write(_("%s problems detected,"
1431 1434 " please check your install!\n") % problems)
1432 1435
1433 1436 return problems
1434 1437
1435 1438 def debugrename(ui, repo, file1, *pats, **opts):
1436 1439 """dump rename information"""
1437 1440
1438 ctx = repo[opts.get('rev')]
1441 ctx = cmdutil.revsingle(repo, opts.get('rev'))
1439 1442 m = cmdutil.match(repo, (file1,) + pats, opts)
1440 1443 for abs in ctx.walk(m):
1441 1444 fctx = ctx[abs]
1442 1445 o = fctx.filelog().renamed(fctx.filenode())
1443 1446 rel = m.rel(abs)
1444 1447 if o:
1445 1448 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
1446 1449 else:
1447 1450 ui.write(_("%s not renamed\n") % rel)
1448 1451
1449 1452 def debugwalk(ui, repo, *pats, **opts):
1450 1453 """show how files match on given patterns"""
1451 1454 m = cmdutil.match(repo, pats, opts)
1452 1455 items = list(repo.walk(m))
1453 1456 if not items:
1454 1457 return
1455 1458 fmt = 'f %%-%ds %%-%ds %%s' % (
1456 1459 max([len(abs) for abs in items]),
1457 1460 max([len(m.rel(abs)) for abs in items]))
1458 1461 for abs in items:
1459 1462 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
1460 1463 ui.write("%s\n" % line.rstrip())
1461 1464
1462 1465 def diff(ui, repo, *pats, **opts):
1463 1466 """diff repository (or selected files)
1464 1467
1465 1468 Show differences between revisions for the specified files.
1466 1469
1467 1470 Differences between files are shown using the unified diff format.
1468 1471
1469 1472 .. note::
1470 1473 diff may generate unexpected results for merges, as it will
1471 1474 default to comparing against the working directory's first
1472 1475 parent changeset if no revisions are specified.
1473 1476
1474 1477 When two revision arguments are given, then changes are shown
1475 1478 between those revisions. If only one revision is specified then
1476 1479 that revision is compared to the working directory, and, when no
1477 1480 revisions are specified, the working directory files are compared
1478 1481 to its parent.
1479 1482
1480 1483 Alternatively you can specify -c/--change with a revision to see
1481 1484 the changes in that changeset relative to its first parent.
1482 1485
1483 1486 Without the -a/--text option, diff will avoid generating diffs of
1484 1487 files it detects as binary. With -a, diff will generate a diff
1485 1488 anyway, probably with undesirable results.
1486 1489
1487 1490 Use the -g/--git option to generate diffs in the git extended diff
1488 1491 format. For more information, read :hg:`help diffs`.
1489 1492
1490 1493 Returns 0 on success.
1491 1494 """
1492 1495
1493 1496 revs = opts.get('rev')
1494 1497 change = opts.get('change')
1495 1498 stat = opts.get('stat')
1496 1499 reverse = opts.get('reverse')
1497 1500
1498 1501 if revs and change:
1499 1502 msg = _('cannot specify --rev and --change at the same time')
1500 1503 raise util.Abort(msg)
1501 1504 elif change:
1502 1505 node2 = repo.lookup(change)
1503 1506 node1 = repo[node2].parents()[0].node()
1504 1507 else:
1505 1508 node1, node2 = cmdutil.revpair(repo, revs)
1506 1509
1507 1510 if reverse:
1508 1511 node1, node2 = node2, node1
1509 1512
1510 1513 diffopts = patch.diffopts(ui, opts)
1511 1514 m = cmdutil.match(repo, pats, opts)
1512 1515 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
1513 1516 listsubrepos=opts.get('subrepos'))
1514 1517
1515 1518 def export(ui, repo, *changesets, **opts):
1516 1519 """dump the header and diffs for one or more changesets
1517 1520
1518 1521 Print the changeset header and diffs for one or more revisions.
1519 1522
1520 1523 The information shown in the changeset header is: author, date,
1521 1524 branch name (if non-default), changeset hash, parent(s) and commit
1522 1525 comment.
1523 1526
1524 1527 .. note::
1525 1528 export may generate unexpected diff output for merge
1526 1529 changesets, as it will compare the merge changeset against its
1527 1530 first parent only.
1528 1531
1529 1532 Output may be to a file, in which case the name of the file is
1530 1533 given using a format string. The formatting rules are as follows:
1531 1534
1532 1535 :``%%``: literal "%" character
1533 1536 :``%H``: changeset hash (40 hexadecimal digits)
1534 1537 :``%N``: number of patches being generated
1535 1538 :``%R``: changeset revision number
1536 1539 :``%b``: basename of the exporting repository
1537 1540 :``%h``: short-form changeset hash (12 hexadecimal digits)
1538 1541 :``%n``: zero-padded sequence number, starting at 1
1539 1542 :``%r``: zero-padded changeset revision number
1540 1543
1541 1544 Without the -a/--text option, export will avoid generating diffs
1542 1545 of files it detects as binary. With -a, export will generate a
1543 1546 diff anyway, probably with undesirable results.
1544 1547
1545 1548 Use the -g/--git option to generate diffs in the git extended diff
1546 1549 format. See :hg:`help diffs` for more information.
1547 1550
1548 1551 With the --switch-parent option, the diff will be against the
1549 1552 second parent. It can be useful to review a merge.
1550 1553
1551 1554 Returns 0 on success.
1552 1555 """
1553 1556 changesets += tuple(opts.get('rev', []))
1554 1557 if not changesets:
1555 1558 raise util.Abort(_("export requires at least one changeset"))
1556 1559 revs = cmdutil.revrange(repo, changesets)
1557 1560 if len(revs) > 1:
1558 1561 ui.note(_('exporting patches:\n'))
1559 1562 else:
1560 1563 ui.note(_('exporting patch:\n'))
1561 1564 cmdutil.export(repo, revs, template=opts.get('output'),
1562 1565 switch_parent=opts.get('switch_parent'),
1563 1566 opts=patch.diffopts(ui, opts))
1564 1567
1565 1568 def forget(ui, repo, *pats, **opts):
1566 1569 """forget the specified files on the next commit
1567 1570
1568 1571 Mark the specified files so they will no longer be tracked
1569 1572 after the next commit.
1570 1573
1571 1574 This only removes files from the current branch, not from the
1572 1575 entire project history, and it does not delete them from the
1573 1576 working directory.
1574 1577
1575 1578 To undo a forget before the next commit, see :hg:`add`.
1576 1579
1577 1580 Returns 0 on success.
1578 1581 """
1579 1582
1580 1583 if not pats:
1581 1584 raise util.Abort(_('no files specified'))
1582 1585
1583 1586 m = cmdutil.match(repo, pats, opts)
1584 1587 s = repo.status(match=m, clean=True)
1585 1588 forget = sorted(s[0] + s[1] + s[3] + s[6])
1586 1589 errs = 0
1587 1590
1588 1591 for f in m.files():
1589 1592 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
1590 1593 ui.warn(_('not removing %s: file is already untracked\n')
1591 1594 % m.rel(f))
1592 1595 errs = 1
1593 1596
1594 1597 for f in forget:
1595 1598 if ui.verbose or not m.exact(f):
1596 1599 ui.status(_('removing %s\n') % m.rel(f))
1597 1600
1598 1601 repo[None].remove(forget, unlink=False)
1599 1602 return errs
1600 1603
1601 1604 def grep(ui, repo, pattern, *pats, **opts):
1602 1605 """search for a pattern in specified files and revisions
1603 1606
1604 1607 Search revisions of files for a regular expression.
1605 1608
1606 1609 This command behaves differently than Unix grep. It only accepts
1607 1610 Python/Perl regexps. It searches repository history, not the
1608 1611 working directory. It always prints the revision number in which a
1609 1612 match appears.
1610 1613
1611 1614 By default, grep only prints output for the first revision of a
1612 1615 file in which it finds a match. To get it to print every revision
1613 1616 that contains a change in match status ("-" for a match that
1614 1617 becomes a non-match, or "+" for a non-match that becomes a match),
1615 1618 use the --all flag.
1616 1619
1617 1620 Returns 0 if a match is found, 1 otherwise.
1618 1621 """
1619 1622 reflags = 0
1620 1623 if opts.get('ignore_case'):
1621 1624 reflags |= re.I
1622 1625 try:
1623 1626 regexp = re.compile(pattern, reflags)
1624 1627 except re.error, inst:
1625 1628 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
1626 1629 return 1
1627 1630 sep, eol = ':', '\n'
1628 1631 if opts.get('print0'):
1629 1632 sep = eol = '\0'
1630 1633
1631 1634 getfile = util.lrucachefunc(repo.file)
1632 1635
1633 1636 def matchlines(body):
1634 1637 begin = 0
1635 1638 linenum = 0
1636 1639 while True:
1637 1640 match = regexp.search(body, begin)
1638 1641 if not match:
1639 1642 break
1640 1643 mstart, mend = match.span()
1641 1644 linenum += body.count('\n', begin, mstart) + 1
1642 1645 lstart = body.rfind('\n', begin, mstart) + 1 or begin
1643 1646 begin = body.find('\n', mend) + 1 or len(body)
1644 1647 lend = begin - 1
1645 1648 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
1646 1649
1647 1650 class linestate(object):
1648 1651 def __init__(self, line, linenum, colstart, colend):
1649 1652 self.line = line
1650 1653 self.linenum = linenum
1651 1654 self.colstart = colstart
1652 1655 self.colend = colend
1653 1656
1654 1657 def __hash__(self):
1655 1658 return hash((self.linenum, self.line))
1656 1659
1657 1660 def __eq__(self, other):
1658 1661 return self.line == other.line
1659 1662
1660 1663 matches = {}
1661 1664 copies = {}
1662 1665 def grepbody(fn, rev, body):
1663 1666 matches[rev].setdefault(fn, [])
1664 1667 m = matches[rev][fn]
1665 1668 for lnum, cstart, cend, line in matchlines(body):
1666 1669 s = linestate(line, lnum, cstart, cend)
1667 1670 m.append(s)
1668 1671
1669 1672 def difflinestates(a, b):
1670 1673 sm = difflib.SequenceMatcher(None, a, b)
1671 1674 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
1672 1675 if tag == 'insert':
1673 1676 for i in xrange(blo, bhi):
1674 1677 yield ('+', b[i])
1675 1678 elif tag == 'delete':
1676 1679 for i in xrange(alo, ahi):
1677 1680 yield ('-', a[i])
1678 1681 elif tag == 'replace':
1679 1682 for i in xrange(alo, ahi):
1680 1683 yield ('-', a[i])
1681 1684 for i in xrange(blo, bhi):
1682 1685 yield ('+', b[i])
1683 1686
1684 1687 def display(fn, ctx, pstates, states):
1685 1688 rev = ctx.rev()
1686 1689 datefunc = ui.quiet and util.shortdate or util.datestr
1687 1690 found = False
1688 1691 filerevmatches = {}
1689 1692 if opts.get('all'):
1690 1693 iter = difflinestates(pstates, states)
1691 1694 else:
1692 1695 iter = [('', l) for l in states]
1693 1696 for change, l in iter:
1694 1697 cols = [fn, str(rev)]
1695 1698 before, match, after = None, None, None
1696 1699 if opts.get('line_number'):
1697 1700 cols.append(str(l.linenum))
1698 1701 if opts.get('all'):
1699 1702 cols.append(change)
1700 1703 if opts.get('user'):
1701 1704 cols.append(ui.shortuser(ctx.user()))
1702 1705 if opts.get('date'):
1703 1706 cols.append(datefunc(ctx.date()))
1704 1707 if opts.get('files_with_matches'):
1705 1708 c = (fn, rev)
1706 1709 if c in filerevmatches:
1707 1710 continue
1708 1711 filerevmatches[c] = 1
1709 1712 else:
1710 1713 before = l.line[:l.colstart]
1711 1714 match = l.line[l.colstart:l.colend]
1712 1715 after = l.line[l.colend:]
1713 1716 ui.write(sep.join(cols))
1714 1717 if before is not None:
1715 1718 ui.write(sep + before)
1716 1719 ui.write(match, label='grep.match')
1717 1720 ui.write(after)
1718 1721 ui.write(eol)
1719 1722 found = True
1720 1723 return found
1721 1724
1722 1725 skip = {}
1723 1726 revfiles = {}
1724 1727 matchfn = cmdutil.match(repo, pats, opts)
1725 1728 found = False
1726 1729 follow = opts.get('follow')
1727 1730
1728 1731 def prep(ctx, fns):
1729 1732 rev = ctx.rev()
1730 1733 pctx = ctx.parents()[0]
1731 1734 parent = pctx.rev()
1732 1735 matches.setdefault(rev, {})
1733 1736 matches.setdefault(parent, {})
1734 1737 files = revfiles.setdefault(rev, [])
1735 1738 for fn in fns:
1736 1739 flog = getfile(fn)
1737 1740 try:
1738 1741 fnode = ctx.filenode(fn)
1739 1742 except error.LookupError:
1740 1743 continue
1741 1744
1742 1745 copied = flog.renamed(fnode)
1743 1746 copy = follow and copied and copied[0]
1744 1747 if copy:
1745 1748 copies.setdefault(rev, {})[fn] = copy
1746 1749 if fn in skip:
1747 1750 if copy:
1748 1751 skip[copy] = True
1749 1752 continue
1750 1753 files.append(fn)
1751 1754
1752 1755 if fn not in matches[rev]:
1753 1756 grepbody(fn, rev, flog.read(fnode))
1754 1757
1755 1758 pfn = copy or fn
1756 1759 if pfn not in matches[parent]:
1757 1760 try:
1758 1761 fnode = pctx.filenode(pfn)
1759 1762 grepbody(pfn, parent, flog.read(fnode))
1760 1763 except error.LookupError:
1761 1764 pass
1762 1765
1763 1766 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
1764 1767 rev = ctx.rev()
1765 1768 parent = ctx.parents()[0].rev()
1766 1769 for fn in sorted(revfiles.get(rev, [])):
1767 1770 states = matches[rev][fn]
1768 1771 copy = copies.get(rev, {}).get(fn)
1769 1772 if fn in skip:
1770 1773 if copy:
1771 1774 skip[copy] = True
1772 1775 continue
1773 1776 pstates = matches.get(parent, {}).get(copy or fn, [])
1774 1777 if pstates or states:
1775 1778 r = display(fn, ctx, pstates, states)
1776 1779 found = found or r
1777 1780 if r and not opts.get('all'):
1778 1781 skip[fn] = True
1779 1782 if copy:
1780 1783 skip[copy] = True
1781 1784 del matches[rev]
1782 1785 del revfiles[rev]
1783 1786
1784 1787 return not found
1785 1788
1786 1789 def heads(ui, repo, *branchrevs, **opts):
1787 1790 """show current repository heads or show branch heads
1788 1791
1789 1792 With no arguments, show all repository branch heads.
1790 1793
1791 1794 Repository "heads" are changesets with no child changesets. They are
1792 1795 where development generally takes place and are the usual targets
1793 1796 for update and merge operations. Branch heads are changesets that have
1794 1797 no child changeset on the same branch.
1795 1798
1796 1799 If one or more REVs are given, only branch heads on the branches
1797 1800 associated with the specified changesets are shown.
1798 1801
1799 1802 If -c/--closed is specified, also show branch heads marked closed
1800 1803 (see :hg:`commit --close-branch`).
1801 1804
1802 1805 If STARTREV is specified, only those heads that are descendants of
1803 1806 STARTREV will be displayed.
1804 1807
1805 1808 If -t/--topo is specified, named branch mechanics will be ignored and only
1806 1809 changesets without children will be shown.
1807 1810
1808 1811 Returns 0 if matching heads are found, 1 if not.
1809 1812 """
1810 1813
1811 if opts.get('rev'):
1812 start = repo.lookup(opts['rev'])
1813 else:
1814 start = None
1814 start = None
1815 if 'rev' in opts:
1816 start = cmdutil.revsingle(repo, opts['rev'], None).node()
1815 1817
1816 1818 if opts.get('topo'):
1817 1819 heads = [repo[h] for h in repo.heads(start)]
1818 1820 else:
1819 1821 heads = []
1820 1822 for b, ls in repo.branchmap().iteritems():
1821 1823 if start is None:
1822 1824 heads += [repo[h] for h in ls]
1823 1825 continue
1824 1826 startrev = repo.changelog.rev(start)
1825 1827 descendants = set(repo.changelog.descendants(startrev))
1826 1828 descendants.add(startrev)
1827 1829 rev = repo.changelog.rev
1828 1830 heads += [repo[h] for h in ls if rev(h) in descendants]
1829 1831
1830 1832 if branchrevs:
1831 1833 decode, encode = encoding.fromlocal, encoding.tolocal
1832 1834 branches = set(repo[decode(br)].branch() for br in branchrevs)
1833 1835 heads = [h for h in heads if h.branch() in branches]
1834 1836
1835 1837 if not opts.get('closed'):
1836 1838 heads = [h for h in heads if not h.extra().get('close')]
1837 1839
1838 1840 if opts.get('active') and branchrevs:
1839 1841 dagheads = repo.heads(start)
1840 1842 heads = [h for h in heads if h.node() in dagheads]
1841 1843
1842 1844 if branchrevs:
1843 1845 haveheads = set(h.branch() for h in heads)
1844 1846 if branches - haveheads:
1845 1847 headless = ', '.join(encode(b) for b in branches - haveheads)
1846 1848 msg = _('no open branch heads found on branches %s')
1847 1849 if opts.get('rev'):
1848 1850 msg += _(' (started at %s)' % opts['rev'])
1849 1851 ui.warn((msg + '\n') % headless)
1850 1852
1851 1853 if not heads:
1852 1854 return 1
1853 1855
1854 1856 heads = sorted(heads, key=lambda x: -x.rev())
1855 1857 displayer = cmdutil.show_changeset(ui, repo, opts)
1856 1858 for ctx in heads:
1857 1859 displayer.show(ctx)
1858 1860 displayer.close()
1859 1861
1860 1862 def help_(ui, name=None, with_version=False, unknowncmd=False):
1861 1863 """show help for a given topic or a help overview
1862 1864
1863 1865 With no arguments, print a list of commands with short help messages.
1864 1866
1865 1867 Given a topic, extension, or command name, print help for that
1866 1868 topic.
1867 1869
1868 1870 Returns 0 if successful.
1869 1871 """
1870 1872 option_lists = []
1871 1873 textwidth = ui.termwidth() - 2
1872 1874
1873 1875 def addglobalopts(aliases):
1874 1876 if ui.verbose:
1875 1877 option_lists.append((_("global options:"), globalopts))
1876 1878 if name == 'shortlist':
1877 1879 option_lists.append((_('use "hg help" for the full list '
1878 1880 'of commands'), ()))
1879 1881 else:
1880 1882 if name == 'shortlist':
1881 1883 msg = _('use "hg help" for the full list of commands '
1882 1884 'or "hg -v" for details')
1883 1885 elif aliases:
1884 1886 msg = _('use "hg -v help%s" to show aliases and '
1885 1887 'global options') % (name and " " + name or "")
1886 1888 else:
1887 1889 msg = _('use "hg -v help %s" to show global options') % name
1888 1890 option_lists.append((msg, ()))
1889 1891
1890 1892 def helpcmd(name):
1891 1893 if with_version:
1892 1894 version_(ui)
1893 1895 ui.write('\n')
1894 1896
1895 1897 try:
1896 1898 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
1897 1899 except error.AmbiguousCommand, inst:
1898 1900 # py3k fix: except vars can't be used outside the scope of the
1899 1901 # except block, nor can be used inside a lambda. python issue4617
1900 1902 prefix = inst.args[0]
1901 1903 select = lambda c: c.lstrip('^').startswith(prefix)
1902 1904 helplist(_('list of commands:\n\n'), select)
1903 1905 return
1904 1906
1905 1907 # check if it's an invalid alias and display its error if it is
1906 1908 if getattr(entry[0], 'badalias', False):
1907 1909 if not unknowncmd:
1908 1910 entry[0](ui)
1909 1911 return
1910 1912
1911 1913 # synopsis
1912 1914 if len(entry) > 2:
1913 1915 if entry[2].startswith('hg'):
1914 1916 ui.write("%s\n" % entry[2])
1915 1917 else:
1916 1918 ui.write('hg %s %s\n' % (aliases[0], entry[2]))
1917 1919 else:
1918 1920 ui.write('hg %s\n' % aliases[0])
1919 1921
1920 1922 # aliases
1921 1923 if not ui.quiet and len(aliases) > 1:
1922 1924 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
1923 1925
1924 1926 # description
1925 1927 doc = gettext(entry[0].__doc__)
1926 1928 if not doc:
1927 1929 doc = _("(no help text available)")
1928 1930 if hasattr(entry[0], 'definition'): # aliased command
1929 1931 if entry[0].definition.startswith('!'): # shell alias
1930 1932 doc = _('shell alias for::\n\n %s') % entry[0].definition[1:]
1931 1933 else:
1932 1934 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
1933 1935 if ui.quiet:
1934 1936 doc = doc.splitlines()[0]
1935 1937 keep = ui.verbose and ['verbose'] or []
1936 1938 formatted, pruned = minirst.format(doc, textwidth, keep=keep)
1937 1939 ui.write("\n%s\n" % formatted)
1938 1940 if pruned:
1939 1941 ui.write(_('\nuse "hg -v help %s" to show verbose help\n') % name)
1940 1942
1941 1943 if not ui.quiet:
1942 1944 # options
1943 1945 if entry[1]:
1944 1946 option_lists.append((_("options:\n"), entry[1]))
1945 1947
1946 1948 addglobalopts(False)
1947 1949
1948 1950 def helplist(header, select=None):
1949 1951 h = {}
1950 1952 cmds = {}
1951 1953 for c, e in table.iteritems():
1952 1954 f = c.split("|", 1)[0]
1953 1955 if select and not select(f):
1954 1956 continue
1955 1957 if (not select and name != 'shortlist' and
1956 1958 e[0].__module__ != __name__):
1957 1959 continue
1958 1960 if name == "shortlist" and not f.startswith("^"):
1959 1961 continue
1960 1962 f = f.lstrip("^")
1961 1963 if not ui.debugflag and f.startswith("debug"):
1962 1964 continue
1963 1965 doc = e[0].__doc__
1964 1966 if doc and 'DEPRECATED' in doc and not ui.verbose:
1965 1967 continue
1966 1968 doc = gettext(doc)
1967 1969 if not doc:
1968 1970 doc = _("(no help text available)")
1969 1971 h[f] = doc.splitlines()[0].rstrip()
1970 1972 cmds[f] = c.lstrip("^")
1971 1973
1972 1974 if not h:
1973 1975 ui.status(_('no commands defined\n'))
1974 1976 return
1975 1977
1976 1978 ui.status(header)
1977 1979 fns = sorted(h)
1978 1980 m = max(map(len, fns))
1979 1981 for f in fns:
1980 1982 if ui.verbose:
1981 1983 commands = cmds[f].replace("|",", ")
1982 1984 ui.write(" %s:\n %s\n"%(commands, h[f]))
1983 1985 else:
1984 1986 ui.write('%s\n' % (util.wrap(h[f], textwidth,
1985 1987 initindent=' %-*s ' % (m, f),
1986 1988 hangindent=' ' * (m + 4))))
1987 1989
1988 1990 if not ui.quiet:
1989 1991 addglobalopts(True)
1990 1992
1991 1993 def helptopic(name):
1992 1994 for names, header, doc in help.helptable:
1993 1995 if name in names:
1994 1996 break
1995 1997 else:
1996 1998 raise error.UnknownCommand(name)
1997 1999
1998 2000 # description
1999 2001 if not doc:
2000 2002 doc = _("(no help text available)")
2001 2003 if hasattr(doc, '__call__'):
2002 2004 doc = doc()
2003 2005
2004 2006 ui.write("%s\n\n" % header)
2005 2007 ui.write("%s\n" % minirst.format(doc, textwidth, indent=4))
2006 2008
2007 2009 def helpext(name):
2008 2010 try:
2009 2011 mod = extensions.find(name)
2010 2012 doc = gettext(mod.__doc__) or _('no help text available')
2011 2013 except KeyError:
2012 2014 mod = None
2013 2015 doc = extensions.disabledext(name)
2014 2016 if not doc:
2015 2017 raise error.UnknownCommand(name)
2016 2018
2017 2019 if '\n' not in doc:
2018 2020 head, tail = doc, ""
2019 2021 else:
2020 2022 head, tail = doc.split('\n', 1)
2021 2023 ui.write(_('%s extension - %s\n\n') % (name.split('.')[-1], head))
2022 2024 if tail:
2023 2025 ui.write(minirst.format(tail, textwidth))
2024 2026 ui.status('\n\n')
2025 2027
2026 2028 if mod:
2027 2029 try:
2028 2030 ct = mod.cmdtable
2029 2031 except AttributeError:
2030 2032 ct = {}
2031 2033 modcmds = set([c.split('|', 1)[0] for c in ct])
2032 2034 helplist(_('list of commands:\n\n'), modcmds.__contains__)
2033 2035 else:
2034 2036 ui.write(_('use "hg help extensions" for information on enabling '
2035 2037 'extensions\n'))
2036 2038
2037 2039 def helpextcmd(name):
2038 2040 cmd, ext, mod = extensions.disabledcmd(name, ui.config('ui', 'strict'))
2039 2041 doc = gettext(mod.__doc__).splitlines()[0]
2040 2042
2041 2043 msg = help.listexts(_("'%s' is provided by the following "
2042 2044 "extension:") % cmd, {ext: doc}, len(ext),
2043 2045 indent=4)
2044 2046 ui.write(minirst.format(msg, textwidth))
2045 2047 ui.write('\n\n')
2046 2048 ui.write(_('use "hg help extensions" for information on enabling '
2047 2049 'extensions\n'))
2048 2050
2049 2051 help.addtopichook('revsets', revset.makedoc)
2050 2052
2051 2053 if name and name != 'shortlist':
2052 2054 i = None
2053 2055 if unknowncmd:
2054 2056 queries = (helpextcmd,)
2055 2057 else:
2056 2058 queries = (helptopic, helpcmd, helpext, helpextcmd)
2057 2059 for f in queries:
2058 2060 try:
2059 2061 f(name)
2060 2062 i = None
2061 2063 break
2062 2064 except error.UnknownCommand, inst:
2063 2065 i = inst
2064 2066 if i:
2065 2067 raise i
2066 2068
2067 2069 else:
2068 2070 # program name
2069 2071 if ui.verbose or with_version:
2070 2072 version_(ui)
2071 2073 else:
2072 2074 ui.status(_("Mercurial Distributed SCM\n"))
2073 2075 ui.status('\n')
2074 2076
2075 2077 # list of commands
2076 2078 if name == "shortlist":
2077 2079 header = _('basic commands:\n\n')
2078 2080 else:
2079 2081 header = _('list of commands:\n\n')
2080 2082
2081 2083 helplist(header)
2082 2084 if name != 'shortlist':
2083 2085 exts, maxlength = extensions.enabled()
2084 2086 text = help.listexts(_('enabled extensions:'), exts, maxlength)
2085 2087 if text:
2086 2088 ui.write("\n%s\n" % minirst.format(text, textwidth))
2087 2089
2088 2090 # list all option lists
2089 2091 opt_output = []
2090 2092 multioccur = False
2091 2093 for title, options in option_lists:
2092 2094 opt_output.append(("\n%s" % title, None))
2093 2095 for option in options:
2094 2096 if len(option) == 5:
2095 2097 shortopt, longopt, default, desc, optlabel = option
2096 2098 else:
2097 2099 shortopt, longopt, default, desc = option
2098 2100 optlabel = _("VALUE") # default label
2099 2101
2100 2102 if _("DEPRECATED") in desc and not ui.verbose:
2101 2103 continue
2102 2104 if isinstance(default, list):
2103 2105 numqualifier = " %s [+]" % optlabel
2104 2106 multioccur = True
2105 2107 elif (default is not None) and not isinstance(default, bool):
2106 2108 numqualifier = " %s" % optlabel
2107 2109 else:
2108 2110 numqualifier = ""
2109 2111 opt_output.append(("%2s%s" %
2110 2112 (shortopt and "-%s" % shortopt,
2111 2113 longopt and " --%s%s" %
2112 2114 (longopt, numqualifier)),
2113 2115 "%s%s" % (desc,
2114 2116 default
2115 2117 and _(" (default: %s)") % default
2116 2118 or "")))
2117 2119 if multioccur:
2118 2120 msg = _("\n[+] marked option can be specified multiple times")
2119 2121 if ui.verbose and name != 'shortlist':
2120 2122 opt_output.append((msg, None))
2121 2123 else:
2122 2124 opt_output.insert(-1, (msg, None))
2123 2125
2124 2126 if not name:
2125 2127 ui.write(_("\nadditional help topics:\n\n"))
2126 2128 topics = []
2127 2129 for names, header, doc in help.helptable:
2128 2130 topics.append((sorted(names, key=len, reverse=True)[0], header))
2129 2131 topics_len = max([len(s[0]) for s in topics])
2130 2132 for t, desc in topics:
2131 2133 ui.write(" %-*s %s\n" % (topics_len, t, desc))
2132 2134
2133 2135 if opt_output:
2134 2136 colwidth = encoding.colwidth
2135 2137 # normalize: (opt or message, desc or None, width of opt)
2136 2138 entries = [desc and (opt, desc, colwidth(opt)) or (opt, None, 0)
2137 2139 for opt, desc in opt_output]
2138 2140 hanging = max([e[2] for e in entries])
2139 2141 for opt, desc, width in entries:
2140 2142 if desc:
2141 2143 initindent = ' %s%s ' % (opt, ' ' * (hanging - width))
2142 2144 hangindent = ' ' * (hanging + 3)
2143 2145 ui.write('%s\n' % (util.wrap(desc, textwidth,
2144 2146 initindent=initindent,
2145 2147 hangindent=hangindent)))
2146 2148 else:
2147 2149 ui.write("%s\n" % opt)
2148 2150
2149 2151 def identify(ui, repo, source=None,
2150 2152 rev=None, num=None, id=None, branch=None, tags=None):
2151 2153 """identify the working copy or specified revision
2152 2154
2153 2155 With no revision, print a summary of the current state of the
2154 2156 repository.
2155 2157
2156 2158 Specifying a path to a repository root or Mercurial bundle will
2157 2159 cause lookup to operate on that repository/bundle.
2158 2160
2159 2161 This summary identifies the repository state using one or two
2160 2162 parent hash identifiers, followed by a "+" if there are
2161 2163 uncommitted changes in the working directory, a list of tags for
2162 2164 this revision and a branch name for non-default branches.
2163 2165
2164 2166 Returns 0 if successful.
2165 2167 """
2166 2168
2167 2169 if not repo and not source:
2168 2170 raise util.Abort(_("there is no Mercurial repository here "
2169 2171 "(.hg not found)"))
2170 2172
2171 2173 hexfunc = ui.debugflag and hex or short
2172 2174 default = not (num or id or branch or tags)
2173 2175 output = []
2174 2176
2175 2177 revs = []
2176 2178 if source:
2177 2179 source, branches = hg.parseurl(ui.expandpath(source))
2178 2180 repo = hg.repository(ui, source)
2179 2181 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
2180 2182
2181 2183 if not repo.local():
2182 2184 if not rev and revs:
2183 2185 rev = revs[0]
2184 2186 if not rev:
2185 2187 rev = "tip"
2186 2188 if num or branch or tags:
2187 2189 raise util.Abort(
2188 2190 "can't query remote revision number, branch, or tags")
2189 2191 output = [hexfunc(repo.lookup(rev))]
2190 2192 elif not rev:
2191 2193 ctx = repo[None]
2192 2194 parents = ctx.parents()
2193 2195 changed = False
2194 2196 if default or id or num:
2195 2197 changed = util.any(repo.status())
2196 2198 if default or id:
2197 2199 output = ["%s%s" % ('+'.join([hexfunc(p.node()) for p in parents]),
2198 2200 (changed) and "+" or "")]
2199 2201 if num:
2200 2202 output.append("%s%s" % ('+'.join([str(p.rev()) for p in parents]),
2201 2203 (changed) and "+" or ""))
2202 2204 else:
2203 ctx = repo[rev]
2205 ctx = cmdutil.revsingle(repo, rev)
2204 2206 if default or id:
2205 2207 output = [hexfunc(ctx.node())]
2206 2208 if num:
2207 2209 output.append(str(ctx.rev()))
2208 2210
2209 2211 if repo.local() and default and not ui.quiet:
2210 2212 b = encoding.tolocal(ctx.branch())
2211 2213 if b != 'default':
2212 2214 output.append("(%s)" % b)
2213 2215
2214 2216 # multiple tags for a single parent separated by '/'
2215 2217 t = "/".join(ctx.tags())
2216 2218 if t:
2217 2219 output.append(t)
2218 2220
2219 2221 if branch:
2220 2222 output.append(encoding.tolocal(ctx.branch()))
2221 2223
2222 2224 if tags:
2223 2225 output.extend(ctx.tags())
2224 2226
2225 2227 ui.write("%s\n" % ' '.join(output))
2226 2228
2227 2229 def import_(ui, repo, patch1, *patches, **opts):
2228 2230 """import an ordered set of patches
2229 2231
2230 2232 Import a list of patches and commit them individually (unless
2231 2233 --no-commit is specified).
2232 2234
2233 2235 If there are outstanding changes in the working directory, import
2234 2236 will abort unless given the -f/--force flag.
2235 2237
2236 2238 You can import a patch straight from a mail message. Even patches
2237 2239 as attachments work (to use the body part, it must have type
2238 2240 text/plain or text/x-patch). From and Subject headers of email
2239 2241 message are used as default committer and commit message. All
2240 2242 text/plain body parts before first diff are added to commit
2241 2243 message.
2242 2244
2243 2245 If the imported patch was generated by :hg:`export`, user and
2244 2246 description from patch override values from message headers and
2245 2247 body. Values given on command line with -m/--message and -u/--user
2246 2248 override these.
2247 2249
2248 2250 If --exact is specified, import will set the working directory to
2249 2251 the parent of each patch before applying it, and will abort if the
2250 2252 resulting changeset has a different ID than the one recorded in
2251 2253 the patch. This may happen due to character set problems or other
2252 2254 deficiencies in the text patch format.
2253 2255
2254 2256 With -s/--similarity, hg will attempt to discover renames and
2255 2257 copies in the patch in the same way as 'addremove'.
2256 2258
2257 2259 To read a patch from standard input, use "-" as the patch name. If
2258 2260 a URL is specified, the patch will be downloaded from it.
2259 2261 See :hg:`help dates` for a list of formats valid for -d/--date.
2260 2262
2261 2263 Returns 0 on success.
2262 2264 """
2263 2265 patches = (patch1,) + patches
2264 2266
2265 2267 date = opts.get('date')
2266 2268 if date:
2267 2269 opts['date'] = util.parsedate(date)
2268 2270
2269 2271 try:
2270 2272 sim = float(opts.get('similarity') or 0)
2271 2273 except ValueError:
2272 2274 raise util.Abort(_('similarity must be a number'))
2273 2275 if sim < 0 or sim > 100:
2274 2276 raise util.Abort(_('similarity must be between 0 and 100'))
2275 2277
2276 2278 if opts.get('exact') or not opts.get('force'):
2277 2279 cmdutil.bail_if_changed(repo)
2278 2280
2279 2281 d = opts["base"]
2280 2282 strip = opts["strip"]
2281 2283 wlock = lock = None
2282 2284 msgs = []
2283 2285
2284 2286 def tryone(ui, hunk):
2285 2287 tmpname, message, user, date, branch, nodeid, p1, p2 = \
2286 2288 patch.extract(ui, hunk)
2287 2289
2288 2290 if not tmpname:
2289 2291 return None
2290 2292 commitid = _('to working directory')
2291 2293
2292 2294 try:
2293 2295 cmdline_message = cmdutil.logmessage(opts)
2294 2296 if cmdline_message:
2295 2297 # pickup the cmdline msg
2296 2298 message = cmdline_message
2297 2299 elif message:
2298 2300 # pickup the patch msg
2299 2301 message = message.strip()
2300 2302 else:
2301 2303 # launch the editor
2302 2304 message = None
2303 2305 ui.debug('message:\n%s\n' % message)
2304 2306
2305 2307 wp = repo.parents()
2306 2308 if opts.get('exact'):
2307 2309 if not nodeid or not p1:
2308 2310 raise util.Abort(_('not a Mercurial patch'))
2309 2311 p1 = repo.lookup(p1)
2310 2312 p2 = repo.lookup(p2 or hex(nullid))
2311 2313
2312 2314 if p1 != wp[0].node():
2313 2315 hg.clean(repo, p1)
2314 2316 repo.dirstate.setparents(p1, p2)
2315 2317 elif p2:
2316 2318 try:
2317 2319 p1 = repo.lookup(p1)
2318 2320 p2 = repo.lookup(p2)
2319 2321 if p1 == wp[0].node():
2320 2322 repo.dirstate.setparents(p1, p2)
2321 2323 except error.RepoError:
2322 2324 pass
2323 2325 if opts.get('exact') or opts.get('import_branch'):
2324 2326 repo.dirstate.setbranch(branch or 'default')
2325 2327
2326 2328 files = {}
2327 2329 try:
2328 2330 patch.patch(tmpname, ui, strip=strip, cwd=repo.root,
2329 2331 files=files, eolmode=None)
2330 2332 finally:
2331 2333 files = cmdutil.updatedir(ui, repo, files,
2332 2334 similarity=sim / 100.0)
2333 2335 if opts.get('no_commit'):
2334 2336 if message:
2335 2337 msgs.append(message)
2336 2338 else:
2337 2339 if opts.get('exact'):
2338 2340 m = None
2339 2341 else:
2340 2342 m = cmdutil.matchfiles(repo, files or [])
2341 2343 n = repo.commit(message, opts.get('user') or user,
2342 2344 opts.get('date') or date, match=m,
2343 2345 editor=cmdutil.commiteditor)
2344 2346 if opts.get('exact'):
2345 2347 if hex(n) != nodeid:
2346 2348 repo.rollback()
2347 2349 raise util.Abort(_('patch is damaged'
2348 2350 ' or loses information'))
2349 2351 # Force a dirstate write so that the next transaction
2350 2352 # backups an up-do-date file.
2351 2353 repo.dirstate.write()
2352 2354 if n:
2353 2355 commitid = short(n)
2354 2356
2355 2357 return commitid
2356 2358 finally:
2357 2359 os.unlink(tmpname)
2358 2360
2359 2361 try:
2360 2362 wlock = repo.wlock()
2361 2363 lock = repo.lock()
2362 2364 lastcommit = None
2363 2365 for p in patches:
2364 2366 pf = os.path.join(d, p)
2365 2367
2366 2368 if pf == '-':
2367 2369 ui.status(_("applying patch from stdin\n"))
2368 2370 pf = sys.stdin
2369 2371 else:
2370 2372 ui.status(_("applying %s\n") % p)
2371 2373 pf = url.open(ui, pf)
2372 2374
2373 2375 haspatch = False
2374 2376 for hunk in patch.split(pf):
2375 2377 commitid = tryone(ui, hunk)
2376 2378 if commitid:
2377 2379 haspatch = True
2378 2380 if lastcommit:
2379 2381 ui.status(_('applied %s\n') % lastcommit)
2380 2382 lastcommit = commitid
2381 2383
2382 2384 if not haspatch:
2383 2385 raise util.Abort(_('no diffs found'))
2384 2386
2385 2387 if msgs:
2386 2388 repo.opener('last-message.txt', 'wb').write('\n* * *\n'.join(msgs))
2387 2389 finally:
2388 2390 release(lock, wlock)
2389 2391
2390 2392 def incoming(ui, repo, source="default", **opts):
2391 2393 """show new changesets found in source
2392 2394
2393 2395 Show new changesets found in the specified path/URL or the default
2394 2396 pull location. These are the changesets that would have been pulled
2395 2397 if a pull at the time you issued this command.
2396 2398
2397 2399 For remote repository, using --bundle avoids downloading the
2398 2400 changesets twice if the incoming is followed by a pull.
2399 2401
2400 2402 See pull for valid source format details.
2401 2403
2402 2404 Returns 0 if there are incoming changes, 1 otherwise.
2403 2405 """
2404 2406 if opts.get('bundle') and opts.get('subrepos'):
2405 2407 raise util.Abort(_('cannot combine --bundle and --subrepos'))
2406 2408
2407 2409 ret = hg.incoming(ui, repo, source, opts)
2408 2410 return ret
2409 2411
2410 2412 def init(ui, dest=".", **opts):
2411 2413 """create a new repository in the given directory
2412 2414
2413 2415 Initialize a new repository in the given directory. If the given
2414 2416 directory does not exist, it will be created.
2415 2417
2416 2418 If no directory is given, the current directory is used.
2417 2419
2418 2420 It is possible to specify an ``ssh://`` URL as the destination.
2419 2421 See :hg:`help urls` for more information.
2420 2422
2421 2423 Returns 0 on success.
2422 2424 """
2423 2425 hg.repository(hg.remoteui(ui, opts), ui.expandpath(dest), create=1)
2424 2426
2425 2427 def locate(ui, repo, *pats, **opts):
2426 2428 """locate files matching specific patterns
2427 2429
2428 2430 Print files under Mercurial control in the working directory whose
2429 2431 names match the given patterns.
2430 2432
2431 2433 By default, this command searches all directories in the working
2432 2434 directory. To search just the current directory and its
2433 2435 subdirectories, use "--include .".
2434 2436
2435 2437 If no patterns are given to match, this command prints the names
2436 2438 of all files under Mercurial control in the working directory.
2437 2439
2438 2440 If you want to feed the output of this command into the "xargs"
2439 2441 command, use the -0 option to both this command and "xargs". This
2440 2442 will avoid the problem of "xargs" treating single filenames that
2441 2443 contain whitespace as multiple filenames.
2442 2444
2443 2445 Returns 0 if a match is found, 1 otherwise.
2444 2446 """
2445 2447 end = opts.get('print0') and '\0' or '\n'
2446 rev = opts.get('rev') or None
2448 rev = cmdutil.revsingle(repo, opts.get('rev'), None).node()
2447 2449
2448 2450 ret = 1
2449 2451 m = cmdutil.match(repo, pats, opts, default='relglob')
2450 2452 m.bad = lambda x, y: False
2451 2453 for abs in repo[rev].walk(m):
2452 2454 if not rev and abs not in repo.dirstate:
2453 2455 continue
2454 2456 if opts.get('fullpath'):
2455 2457 ui.write(repo.wjoin(abs), end)
2456 2458 else:
2457 2459 ui.write(((pats and m.rel(abs)) or abs), end)
2458 2460 ret = 0
2459 2461
2460 2462 return ret
2461 2463
2462 2464 def log(ui, repo, *pats, **opts):
2463 2465 """show revision history of entire repository or files
2464 2466
2465 2467 Print the revision history of the specified files or the entire
2466 2468 project.
2467 2469
2468 2470 File history is shown without following rename or copy history of
2469 2471 files. Use -f/--follow with a filename to follow history across
2470 2472 renames and copies. --follow without a filename will only show
2471 2473 ancestors or descendants of the starting revision. --follow-first
2472 2474 only follows the first parent of merge revisions.
2473 2475
2474 2476 If no revision range is specified, the default is ``tip:0`` unless
2475 2477 --follow is set, in which case the working directory parent is
2476 2478 used as the starting revision. You can specify a revision set for
2477 2479 log, see :hg:`help revsets` for more information.
2478 2480
2479 2481 See :hg:`help dates` for a list of formats valid for -d/--date.
2480 2482
2481 2483 By default this command prints revision number and changeset id,
2482 2484 tags, non-trivial parents, user, date and time, and a summary for
2483 2485 each commit. When the -v/--verbose switch is used, the list of
2484 2486 changed files and full commit message are shown.
2485 2487
2486 2488 .. note::
2487 2489 log -p/--patch may generate unexpected diff output for merge
2488 2490 changesets, as it will only compare the merge changeset against
2489 2491 its first parent. Also, only files different from BOTH parents
2490 2492 will appear in files:.
2491 2493
2492 2494 Returns 0 on success.
2493 2495 """
2494 2496
2495 2497 matchfn = cmdutil.match(repo, pats, opts)
2496 2498 limit = cmdutil.loglimit(opts)
2497 2499 count = 0
2498 2500
2499 2501 endrev = None
2500 2502 if opts.get('copies') and opts.get('rev'):
2501 2503 endrev = max(cmdutil.revrange(repo, opts.get('rev'))) + 1
2502 2504
2503 2505 df = False
2504 2506 if opts["date"]:
2505 2507 df = util.matchdate(opts["date"])
2506 2508
2507 2509 branches = opts.get('branch', []) + opts.get('only_branch', [])
2508 2510 opts['branch'] = [repo.lookupbranch(b) for b in branches]
2509 2511
2510 2512 displayer = cmdutil.show_changeset(ui, repo, opts, True)
2511 2513 def prep(ctx, fns):
2512 2514 rev = ctx.rev()
2513 2515 parents = [p for p in repo.changelog.parentrevs(rev)
2514 2516 if p != nullrev]
2515 2517 if opts.get('no_merges') and len(parents) == 2:
2516 2518 return
2517 2519 if opts.get('only_merges') and len(parents) != 2:
2518 2520 return
2519 2521 if opts.get('branch') and ctx.branch() not in opts['branch']:
2520 2522 return
2521 2523 if df and not df(ctx.date()[0]):
2522 2524 return
2523 2525 if opts['user'] and not [k for k in opts['user']
2524 2526 if k.lower() in ctx.user().lower()]:
2525 2527 return
2526 2528 if opts.get('keyword'):
2527 2529 for k in [kw.lower() for kw in opts['keyword']]:
2528 2530 if (k in ctx.user().lower() or
2529 2531 k in ctx.description().lower() or
2530 2532 k in " ".join(ctx.files()).lower()):
2531 2533 break
2532 2534 else:
2533 2535 return
2534 2536
2535 2537 copies = None
2536 2538 if opts.get('copies') and rev:
2537 2539 copies = []
2538 2540 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
2539 2541 for fn in ctx.files():
2540 2542 rename = getrenamed(fn, rev)
2541 2543 if rename:
2542 2544 copies.append((fn, rename[0]))
2543 2545
2544 2546 revmatchfn = None
2545 2547 if opts.get('patch') or opts.get('stat'):
2546 2548 if opts.get('follow') or opts.get('follow_first'):
2547 2549 # note: this might be wrong when following through merges
2548 2550 revmatchfn = cmdutil.match(repo, fns, default='path')
2549 2551 else:
2550 2552 revmatchfn = matchfn
2551 2553
2552 2554 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
2553 2555
2554 2556 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2555 2557 if count == limit:
2556 2558 break
2557 2559 if displayer.flush(ctx.rev()):
2558 2560 count += 1
2559 2561 displayer.close()
2560 2562
2561 2563 def manifest(ui, repo, node=None, rev=None):
2562 2564 """output the current or given revision of the project manifest
2563 2565
2564 2566 Print a list of version controlled files for the given revision.
2565 2567 If no revision is given, the first parent of the working directory
2566 2568 is used, or the null revision if no revision is checked out.
2567 2569
2568 2570 With -v, print file permissions, symlink and executable bits.
2569 2571 With --debug, print file revision hashes.
2570 2572
2571 2573 Returns 0 on success.
2572 2574 """
2573 2575
2574 2576 if rev and node:
2575 2577 raise util.Abort(_("please specify just one revision"))
2576 2578
2577 2579 if not node:
2578 2580 node = rev
2579 2581
2580 2582 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
2581 ctx = repo[node]
2583 ctx = cmdutil.revsingle(repo, node)
2582 2584 for f in ctx:
2583 2585 if ui.debugflag:
2584 2586 ui.write("%40s " % hex(ctx.manifest()[f]))
2585 2587 if ui.verbose:
2586 2588 ui.write(decor[ctx.flags(f)])
2587 2589 ui.write("%s\n" % f)
2588 2590
2589 2591 def merge(ui, repo, node=None, **opts):
2590 2592 """merge working directory with another revision
2591 2593
2592 2594 The current working directory is updated with all changes made in
2593 2595 the requested revision since the last common predecessor revision.
2594 2596
2595 2597 Files that changed between either parent are marked as changed for
2596 2598 the next commit and a commit must be performed before any further
2597 2599 updates to the repository are allowed. The next commit will have
2598 2600 two parents.
2599 2601
2600 2602 ``--tool`` can be used to specify the merge tool used for file
2601 2603 merges. It overrides the HGMERGE environment variable and your
2602 2604 configuration files.
2603 2605
2604 2606 If no revision is specified, the working directory's parent is a
2605 2607 head revision, and the current branch contains exactly one other
2606 2608 head, the other head is merged with by default. Otherwise, an
2607 2609 explicit revision with which to merge with must be provided.
2608 2610
2609 2611 :hg:`resolve` must be used to resolve unresolved files.
2610 2612
2611 2613 To undo an uncommitted merge, use :hg:`update --clean .` which
2612 2614 will check out a clean copy of the original merge parent, losing
2613 2615 all changes.
2614 2616
2615 2617 Returns 0 on success, 1 if there are unresolved files.
2616 2618 """
2617 2619
2618 2620 if opts.get('rev') and node:
2619 2621 raise util.Abort(_("please specify just one revision"))
2620 2622 if not node:
2621 2623 node = opts.get('rev')
2622 2624
2623 2625 if not node:
2624 2626 branch = repo.changectx(None).branch()
2625 2627 bheads = repo.branchheads(branch)
2626 2628 if len(bheads) > 2:
2627 2629 raise util.Abort(_(
2628 2630 'branch \'%s\' has %d heads - '
2629 2631 'please merge with an explicit rev\n'
2630 2632 '(run \'hg heads .\' to see heads)')
2631 2633 % (branch, len(bheads)))
2632 2634
2633 2635 parent = repo.dirstate.parents()[0]
2634 2636 if len(bheads) == 1:
2635 2637 if len(repo.heads()) > 1:
2636 2638 raise util.Abort(_(
2637 2639 'branch \'%s\' has one head - '
2638 2640 'please merge with an explicit rev\n'
2639 2641 '(run \'hg heads\' to see all heads)')
2640 2642 % branch)
2641 2643 msg = _('there is nothing to merge')
2642 2644 if parent != repo.lookup(repo[None].branch()):
2643 2645 msg = _('%s - use "hg update" instead') % msg
2644 2646 raise util.Abort(msg)
2645 2647
2646 2648 if parent not in bheads:
2647 2649 raise util.Abort(_('working dir not at a head rev - '
2648 2650 'use "hg update" or merge with an explicit rev'))
2649 2651 node = parent == bheads[0] and bheads[-1] or bheads[0]
2652 else:
2653 node = cmdutil.revsingle(repo, node).node()
2650 2654
2651 2655 if opts.get('preview'):
2652 2656 # find nodes that are ancestors of p2 but not of p1
2653 2657 p1 = repo.lookup('.')
2654 2658 p2 = repo.lookup(node)
2655 2659 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
2656 2660
2657 2661 displayer = cmdutil.show_changeset(ui, repo, opts)
2658 2662 for node in nodes:
2659 2663 displayer.show(repo[node])
2660 2664 displayer.close()
2661 2665 return 0
2662 2666
2663 2667 try:
2664 2668 # ui.forcemerge is an internal variable, do not document
2665 2669 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
2666 2670 return hg.merge(repo, node, force=opts.get('force'))
2667 2671 finally:
2668 2672 ui.setconfig('ui', 'forcemerge', '')
2669 2673
2670 2674 def outgoing(ui, repo, dest=None, **opts):
2671 2675 """show changesets not found in the destination
2672 2676
2673 2677 Show changesets not found in the specified destination repository
2674 2678 or the default push location. These are the changesets that would
2675 2679 be pushed if a push was requested.
2676 2680
2677 2681 See pull for details of valid destination formats.
2678 2682
2679 2683 Returns 0 if there are outgoing changes, 1 otherwise.
2680 2684 """
2681 2685 ret = hg.outgoing(ui, repo, dest, opts)
2682 2686 return ret
2683 2687
2684 2688 def parents(ui, repo, file_=None, **opts):
2685 2689 """show the parents of the working directory or revision
2686 2690
2687 2691 Print the working directory's parent revisions. If a revision is
2688 2692 given via -r/--rev, the parent of that revision will be printed.
2689 2693 If a file argument is given, the revision in which the file was
2690 2694 last changed (before the working directory revision or the
2691 2695 argument to --rev if given) is printed.
2692 2696
2693 2697 Returns 0 on success.
2694 2698 """
2695 rev = opts.get('rev')
2696 if rev:
2697 ctx = repo[rev]
2698 else:
2699 ctx = repo[None]
2699
2700 ctx = cmdutil.revsingle(repo, opts.get('rev'), None)
2700 2701
2701 2702 if file_:
2702 2703 m = cmdutil.match(repo, (file_,), opts)
2703 2704 if m.anypats() or len(m.files()) != 1:
2704 2705 raise util.Abort(_('can only specify an explicit filename'))
2705 2706 file_ = m.files()[0]
2706 2707 filenodes = []
2707 2708 for cp in ctx.parents():
2708 2709 if not cp:
2709 2710 continue
2710 2711 try:
2711 2712 filenodes.append(cp.filenode(file_))
2712 2713 except error.LookupError:
2713 2714 pass
2714 2715 if not filenodes:
2715 2716 raise util.Abort(_("'%s' not found in manifest!") % file_)
2716 2717 fl = repo.file(file_)
2717 2718 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
2718 2719 else:
2719 2720 p = [cp.node() for cp in ctx.parents()]
2720 2721
2721 2722 displayer = cmdutil.show_changeset(ui, repo, opts)
2722 2723 for n in p:
2723 2724 if n != nullid:
2724 2725 displayer.show(repo[n])
2725 2726 displayer.close()
2726 2727
2727 2728 def paths(ui, repo, search=None):
2728 2729 """show aliases for remote repositories
2729 2730
2730 2731 Show definition of symbolic path name NAME. If no name is given,
2731 2732 show definition of all available names.
2732 2733
2733 2734 Path names are defined in the [paths] section of your
2734 2735 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
2735 2736 repository, ``.hg/hgrc`` is used, too.
2736 2737
2737 2738 The path names ``default`` and ``default-push`` have a special
2738 2739 meaning. When performing a push or pull operation, they are used
2739 2740 as fallbacks if no location is specified on the command-line.
2740 2741 When ``default-push`` is set, it will be used for push and
2741 2742 ``default`` will be used for pull; otherwise ``default`` is used
2742 2743 as the fallback for both. When cloning a repository, the clone
2743 2744 source is written as ``default`` in ``.hg/hgrc``. Note that
2744 2745 ``default`` and ``default-push`` apply to all inbound (e.g.
2745 2746 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
2746 2747 :hg:`bundle`) operations.
2747 2748
2748 2749 See :hg:`help urls` for more information.
2749 2750
2750 2751 Returns 0 on success.
2751 2752 """
2752 2753 if search:
2753 2754 for name, path in ui.configitems("paths"):
2754 2755 if name == search:
2755 2756 ui.write("%s\n" % url.hidepassword(path))
2756 2757 return
2757 2758 ui.warn(_("not found!\n"))
2758 2759 return 1
2759 2760 else:
2760 2761 for name, path in ui.configitems("paths"):
2761 2762 ui.write("%s = %s\n" % (name, url.hidepassword(path)))
2762 2763
2763 2764 def postincoming(ui, repo, modheads, optupdate, checkout):
2764 2765 if modheads == 0:
2765 2766 return
2766 2767 if optupdate:
2767 2768 if (modheads <= 1 or len(repo.branchheads()) == 1) or checkout:
2768 2769 return hg.update(repo, checkout)
2769 2770 else:
2770 2771 ui.status(_("not updating, since new heads added\n"))
2771 2772 if modheads > 1:
2772 2773 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
2773 2774 else:
2774 2775 ui.status(_("(run 'hg update' to get a working copy)\n"))
2775 2776
2776 2777 def pull(ui, repo, source="default", **opts):
2777 2778 """pull changes from the specified source
2778 2779
2779 2780 Pull changes from a remote repository to a local one.
2780 2781
2781 2782 This finds all changes from the repository at the specified path
2782 2783 or URL and adds them to a local repository (the current one unless
2783 2784 -R is specified). By default, this does not update the copy of the
2784 2785 project in the working directory.
2785 2786
2786 2787 Use :hg:`incoming` if you want to see what would have been added
2787 2788 by a pull at the time you issued this command. If you then decide
2788 2789 to add those changes to the repository, you should use :hg:`pull
2789 2790 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
2790 2791
2791 2792 If SOURCE is omitted, the 'default' path will be used.
2792 2793 See :hg:`help urls` for more information.
2793 2794
2794 2795 Returns 0 on success, 1 if an update had unresolved files.
2795 2796 """
2796 2797 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
2797 2798 other = hg.repository(hg.remoteui(repo, opts), source)
2798 2799 ui.status(_('pulling from %s\n') % url.hidepassword(source))
2799 2800 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
2800 2801 if revs:
2801 2802 try:
2802 2803 revs = [other.lookup(rev) for rev in revs]
2803 2804 except error.CapabilityError:
2804 2805 err = _("other repository doesn't support revision lookup, "
2805 2806 "so a rev cannot be specified.")
2806 2807 raise util.Abort(err)
2807 2808
2808 2809 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
2809 2810 if checkout:
2810 2811 checkout = str(repo.changelog.rev(other.lookup(checkout)))
2811 2812 repo._subtoppath = source
2812 2813 try:
2813 2814 return postincoming(ui, repo, modheads, opts.get('update'), checkout)
2814 2815 finally:
2815 2816 del repo._subtoppath
2816 2817
2817 2818 def push(ui, repo, dest=None, **opts):
2818 2819 """push changes to the specified destination
2819 2820
2820 2821 Push changesets from the local repository to the specified
2821 2822 destination.
2822 2823
2823 2824 This operation is symmetrical to pull: it is identical to a pull
2824 2825 in the destination repository from the current one.
2825 2826
2826 2827 By default, push will not allow creation of new heads at the
2827 2828 destination, since multiple heads would make it unclear which head
2828 2829 to use. In this situation, it is recommended to pull and merge
2829 2830 before pushing.
2830 2831
2831 2832 Use --new-branch if you want to allow push to create a new named
2832 2833 branch that is not present at the destination. This allows you to
2833 2834 only create a new branch without forcing other changes.
2834 2835
2835 2836 Use -f/--force to override the default behavior and push all
2836 2837 changesets on all branches.
2837 2838
2838 2839 If -r/--rev is used, the specified revision and all its ancestors
2839 2840 will be pushed to the remote repository.
2840 2841
2841 2842 Please see :hg:`help urls` for important details about ``ssh://``
2842 2843 URLs. If DESTINATION is omitted, a default path will be used.
2843 2844
2844 2845 Returns 0 if push was successful, 1 if nothing to push.
2845 2846 """
2846 2847 dest = ui.expandpath(dest or 'default-push', dest or 'default')
2847 2848 dest, branches = hg.parseurl(dest, opts.get('branch'))
2848 2849 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
2849 2850 other = hg.repository(hg.remoteui(repo, opts), dest)
2850 2851 ui.status(_('pushing to %s\n') % url.hidepassword(dest))
2851 2852 if revs:
2852 2853 revs = [repo.lookup(rev) for rev in revs]
2853 2854
2854 2855 repo._subtoppath = dest
2855 2856 try:
2856 2857 # push subrepos depth-first for coherent ordering
2857 2858 c = repo['']
2858 2859 subs = c.substate # only repos that are committed
2859 2860 for s in sorted(subs):
2860 2861 if not c.sub(s).push(opts.get('force')):
2861 2862 return False
2862 2863 finally:
2863 2864 del repo._subtoppath
2864 2865 r = repo.push(other, opts.get('force'), revs=revs,
2865 2866 newbranch=opts.get('new_branch'))
2866 2867 return r == 0
2867 2868
2868 2869 def recover(ui, repo):
2869 2870 """roll back an interrupted transaction
2870 2871
2871 2872 Recover from an interrupted commit or pull.
2872 2873
2873 2874 This command tries to fix the repository status after an
2874 2875 interrupted operation. It should only be necessary when Mercurial
2875 2876 suggests it.
2876 2877
2877 2878 Returns 0 if successful, 1 if nothing to recover or verify fails.
2878 2879 """
2879 2880 if repo.recover():
2880 2881 return hg.verify(repo)
2881 2882 return 1
2882 2883
2883 2884 def remove(ui, repo, *pats, **opts):
2884 2885 """remove the specified files on the next commit
2885 2886
2886 2887 Schedule the indicated files for removal from the repository.
2887 2888
2888 2889 This only removes files from the current branch, not from the
2889 2890 entire project history. -A/--after can be used to remove only
2890 2891 files that have already been deleted, -f/--force can be used to
2891 2892 force deletion, and -Af can be used to remove files from the next
2892 2893 revision without deleting them from the working directory.
2893 2894
2894 2895 The following table details the behavior of remove for different
2895 2896 file states (columns) and option combinations (rows). The file
2896 2897 states are Added [A], Clean [C], Modified [M] and Missing [!] (as
2897 2898 reported by :hg:`status`). The actions are Warn, Remove (from
2898 2899 branch) and Delete (from disk)::
2899 2900
2900 2901 A C M !
2901 2902 none W RD W R
2902 2903 -f R RD RD R
2903 2904 -A W W W R
2904 2905 -Af R R R R
2905 2906
2906 2907 This command schedules the files to be removed at the next commit.
2907 2908 To undo a remove before that, see :hg:`revert`.
2908 2909
2909 2910 Returns 0 on success, 1 if any warnings encountered.
2910 2911 """
2911 2912
2912 2913 ret = 0
2913 2914 after, force = opts.get('after'), opts.get('force')
2914 2915 if not pats and not after:
2915 2916 raise util.Abort(_('no files specified'))
2916 2917
2917 2918 m = cmdutil.match(repo, pats, opts)
2918 2919 s = repo.status(match=m, clean=True)
2919 2920 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
2920 2921
2921 2922 for f in m.files():
2922 2923 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
2923 2924 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
2924 2925 ret = 1
2925 2926
2926 2927 if force:
2927 2928 remove, forget = modified + deleted + clean, added
2928 2929 elif after:
2929 2930 remove, forget = deleted, []
2930 2931 for f in modified + added + clean:
2931 2932 ui.warn(_('not removing %s: file still exists (use -f'
2932 2933 ' to force removal)\n') % m.rel(f))
2933 2934 ret = 1
2934 2935 else:
2935 2936 remove, forget = deleted + clean, []
2936 2937 for f in modified:
2937 2938 ui.warn(_('not removing %s: file is modified (use -f'
2938 2939 ' to force removal)\n') % m.rel(f))
2939 2940 ret = 1
2940 2941 for f in added:
2941 2942 ui.warn(_('not removing %s: file has been marked for add (use -f'
2942 2943 ' to force removal)\n') % m.rel(f))
2943 2944 ret = 1
2944 2945
2945 2946 for f in sorted(remove + forget):
2946 2947 if ui.verbose or not m.exact(f):
2947 2948 ui.status(_('removing %s\n') % m.rel(f))
2948 2949
2949 2950 repo[None].forget(forget)
2950 2951 repo[None].remove(remove, unlink=not after)
2951 2952 return ret
2952 2953
2953 2954 def rename(ui, repo, *pats, **opts):
2954 2955 """rename files; equivalent of copy + remove
2955 2956
2956 2957 Mark dest as copies of sources; mark sources for deletion. If dest
2957 2958 is a directory, copies are put in that directory. If dest is a
2958 2959 file, there can only be one source.
2959 2960
2960 2961 By default, this command copies the contents of files as they
2961 2962 exist in the working directory. If invoked with -A/--after, the
2962 2963 operation is recorded, but no copying is performed.
2963 2964
2964 2965 This command takes effect at the next commit. To undo a rename
2965 2966 before that, see :hg:`revert`.
2966 2967
2967 2968 Returns 0 on success, 1 if errors are encountered.
2968 2969 """
2969 2970 wlock = repo.wlock(False)
2970 2971 try:
2971 2972 return cmdutil.copy(ui, repo, pats, opts, rename=True)
2972 2973 finally:
2973 2974 wlock.release()
2974 2975
2975 2976 def resolve(ui, repo, *pats, **opts):
2976 2977 """redo merges or set/view the merge status of files
2977 2978
2978 2979 Merges with unresolved conflicts are often the result of
2979 2980 non-interactive merging using the ``internal:merge`` configuration
2980 2981 setting, or a command-line merge tool like ``diff3``. The resolve
2981 2982 command is used to manage the files involved in a merge, after
2982 2983 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
2983 2984 working directory must have two parents).
2984 2985
2985 2986 The resolve command can be used in the following ways:
2986 2987
2987 2988 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
2988 2989 files, discarding any previous merge attempts. Re-merging is not
2989 2990 performed for files already marked as resolved. Use ``--all/-a``
2990 2991 to selects all unresolved files. ``--tool`` can be used to specify
2991 2992 the merge tool used for the given files. It overrides the HGMERGE
2992 2993 environment variable and your configuration files.
2993 2994
2994 2995 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
2995 2996 (e.g. after having manually fixed-up the files). The default is
2996 2997 to mark all unresolved files.
2997 2998
2998 2999 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
2999 3000 default is to mark all resolved files.
3000 3001
3001 3002 - :hg:`resolve -l`: list files which had or still have conflicts.
3002 3003 In the printed list, ``U`` = unresolved and ``R`` = resolved.
3003 3004
3004 3005 Note that Mercurial will not let you commit files with unresolved
3005 3006 merge conflicts. You must use :hg:`resolve -m ...` before you can
3006 3007 commit after a conflicting merge.
3007 3008
3008 3009 Returns 0 on success, 1 if any files fail a resolve attempt.
3009 3010 """
3010 3011
3011 3012 all, mark, unmark, show, nostatus = \
3012 3013 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
3013 3014
3014 3015 if (show and (mark or unmark)) or (mark and unmark):
3015 3016 raise util.Abort(_("too many options specified"))
3016 3017 if pats and all:
3017 3018 raise util.Abort(_("can't specify --all and patterns"))
3018 3019 if not (all or pats or show or mark or unmark):
3019 3020 raise util.Abort(_('no files or directories specified; '
3020 3021 'use --all to remerge all files'))
3021 3022
3022 3023 ms = mergemod.mergestate(repo)
3023 3024 m = cmdutil.match(repo, pats, opts)
3024 3025 ret = 0
3025 3026
3026 3027 for f in ms:
3027 3028 if m(f):
3028 3029 if show:
3029 3030 if nostatus:
3030 3031 ui.write("%s\n" % f)
3031 3032 else:
3032 3033 ui.write("%s %s\n" % (ms[f].upper(), f),
3033 3034 label='resolve.' +
3034 3035 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
3035 3036 elif mark:
3036 3037 ms.mark(f, "r")
3037 3038 elif unmark:
3038 3039 ms.mark(f, "u")
3039 3040 else:
3040 3041 wctx = repo[None]
3041 3042 mctx = wctx.parents()[-1]
3042 3043
3043 3044 # backup pre-resolve (merge uses .orig for its own purposes)
3044 3045 a = repo.wjoin(f)
3045 3046 util.copyfile(a, a + ".resolve")
3046 3047
3047 3048 try:
3048 3049 # resolve file
3049 3050 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
3050 3051 if ms.resolve(f, wctx, mctx):
3051 3052 ret = 1
3052 3053 finally:
3053 3054 ui.setconfig('ui', 'forcemerge', '')
3054 3055
3055 3056 # replace filemerge's .orig file with our resolve file
3056 3057 util.rename(a + ".resolve", a + ".orig")
3057 3058
3058 3059 ms.commit()
3059 3060 return ret
3060 3061
3061 3062 def revert(ui, repo, *pats, **opts):
3062 3063 """restore individual files or directories to an earlier state
3063 3064
3064 3065 .. note::
3065 3066 This command is most likely not what you are looking for.
3066 3067 Revert will partially overwrite content in the working
3067 3068 directory without changing the working directory parents. Use
3068 3069 :hg:`update -r rev` to check out earlier revisions, or
3069 3070 :hg:`update --clean .` to undo a merge which has added another
3070 3071 parent.
3071 3072
3072 3073 With no revision specified, revert the named files or directories
3073 3074 to the contents they had in the parent of the working directory.
3074 3075 This restores the contents of the affected files to an unmodified
3075 3076 state and unschedules adds, removes, copies, and renames. If the
3076 3077 working directory has two parents, you must explicitly specify a
3077 3078 revision.
3078 3079
3079 3080 Using the -r/--rev option, revert the given files or directories
3080 3081 to their contents as of a specific revision. This can be helpful
3081 3082 to "roll back" some or all of an earlier change. See :hg:`help
3082 3083 dates` for a list of formats valid for -d/--date.
3083 3084
3084 3085 Revert modifies the working directory. It does not commit any
3085 3086 changes, or change the parent of the working directory. If you
3086 3087 revert to a revision other than the parent of the working
3087 3088 directory, the reverted files will thus appear modified
3088 3089 afterwards.
3089 3090
3090 3091 If a file has been deleted, it is restored. If the executable mode
3091 3092 of a file was changed, it is reset.
3092 3093
3093 3094 If names are given, all files matching the names are reverted.
3094 3095 If no arguments are given, no files are reverted.
3095 3096
3096 3097 Modified files are saved with a .orig suffix before reverting.
3097 3098 To disable these backups, use --no-backup.
3098 3099
3099 3100 Returns 0 on success.
3100 3101 """
3101 3102
3102 3103 if opts.get("date"):
3103 3104 if opts.get("rev"):
3104 3105 raise util.Abort(_("you can't specify a revision and a date"))
3105 3106 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
3106 3107
3107 3108 if not pats and not opts.get('all'):
3108 3109 raise util.Abort(_('no files or directories specified; '
3109 3110 'use --all to revert the whole repo'))
3110 3111
3111 3112 parent, p2 = repo.dirstate.parents()
3112 3113 if not opts.get('rev') and p2 != nullid:
3113 3114 raise util.Abort(_('uncommitted merge - please provide a '
3114 3115 'specific revision'))
3115 ctx = repo[opts.get('rev')]
3116 ctx = cmdutil.revsingle(repo, opts.get('rev'))
3116 3117 node = ctx.node()
3117 3118 mf = ctx.manifest()
3118 3119 if node == parent:
3119 3120 pmf = mf
3120 3121 else:
3121 3122 pmf = None
3122 3123
3123 3124 # need all matching names in dirstate and manifest of target rev,
3124 3125 # so have to walk both. do not print errors if files exist in one
3125 3126 # but not other.
3126 3127
3127 3128 names = {}
3128 3129
3129 3130 wlock = repo.wlock()
3130 3131 try:
3131 3132 # walk dirstate.
3132 3133
3133 3134 m = cmdutil.match(repo, pats, opts)
3134 3135 m.bad = lambda x, y: False
3135 3136 for abs in repo.walk(m):
3136 3137 names[abs] = m.rel(abs), m.exact(abs)
3137 3138
3138 3139 # walk target manifest.
3139 3140
3140 3141 def badfn(path, msg):
3141 3142 if path in names:
3142 3143 return
3143 3144 path_ = path + '/'
3144 3145 for f in names:
3145 3146 if f.startswith(path_):
3146 3147 return
3147 3148 ui.warn("%s: %s\n" % (m.rel(path), msg))
3148 3149
3149 3150 m = cmdutil.match(repo, pats, opts)
3150 3151 m.bad = badfn
3151 3152 for abs in repo[node].walk(m):
3152 3153 if abs not in names:
3153 3154 names[abs] = m.rel(abs), m.exact(abs)
3154 3155
3155 3156 m = cmdutil.matchfiles(repo, names)
3156 3157 changes = repo.status(match=m)[:4]
3157 3158 modified, added, removed, deleted = map(set, changes)
3158 3159
3159 3160 # if f is a rename, also revert the source
3160 3161 cwd = repo.getcwd()
3161 3162 for f in added:
3162 3163 src = repo.dirstate.copied(f)
3163 3164 if src and src not in names and repo.dirstate[src] == 'r':
3164 3165 removed.add(src)
3165 3166 names[src] = (repo.pathto(src, cwd), True)
3166 3167
3167 3168 def removeforget(abs):
3168 3169 if repo.dirstate[abs] == 'a':
3169 3170 return _('forgetting %s\n')
3170 3171 return _('removing %s\n')
3171 3172
3172 3173 revert = ([], _('reverting %s\n'))
3173 3174 add = ([], _('adding %s\n'))
3174 3175 remove = ([], removeforget)
3175 3176 undelete = ([], _('undeleting %s\n'))
3176 3177
3177 3178 disptable = (
3178 3179 # dispatch table:
3179 3180 # file state
3180 3181 # action if in target manifest
3181 3182 # action if not in target manifest
3182 3183 # make backup if in target manifest
3183 3184 # make backup if not in target manifest
3184 3185 (modified, revert, remove, True, True),
3185 3186 (added, revert, remove, True, False),
3186 3187 (removed, undelete, None, False, False),
3187 3188 (deleted, revert, remove, False, False),
3188 3189 )
3189 3190
3190 3191 for abs, (rel, exact) in sorted(names.items()):
3191 3192 mfentry = mf.get(abs)
3192 3193 target = repo.wjoin(abs)
3193 3194 def handle(xlist, dobackup):
3194 3195 xlist[0].append(abs)
3195 3196 if (dobackup and not opts.get('no_backup') and
3196 3197 os.path.lexists(target)):
3197 3198 bakname = "%s.orig" % rel
3198 3199 ui.note(_('saving current version of %s as %s\n') %
3199 3200 (rel, bakname))
3200 3201 if not opts.get('dry_run'):
3201 3202 util.rename(target, bakname)
3202 3203 if ui.verbose or not exact:
3203 3204 msg = xlist[1]
3204 3205 if not isinstance(msg, basestring):
3205 3206 msg = msg(abs)
3206 3207 ui.status(msg % rel)
3207 3208 for table, hitlist, misslist, backuphit, backupmiss in disptable:
3208 3209 if abs not in table:
3209 3210 continue
3210 3211 # file has changed in dirstate
3211 3212 if mfentry:
3212 3213 handle(hitlist, backuphit)
3213 3214 elif misslist is not None:
3214 3215 handle(misslist, backupmiss)
3215 3216 break
3216 3217 else:
3217 3218 if abs not in repo.dirstate:
3218 3219 if mfentry:
3219 3220 handle(add, True)
3220 3221 elif exact:
3221 3222 ui.warn(_('file not managed: %s\n') % rel)
3222 3223 continue
3223 3224 # file has not changed in dirstate
3224 3225 if node == parent:
3225 3226 if exact:
3226 3227 ui.warn(_('no changes needed to %s\n') % rel)
3227 3228 continue
3228 3229 if pmf is None:
3229 3230 # only need parent manifest in this unlikely case,
3230 3231 # so do not read by default
3231 3232 pmf = repo[parent].manifest()
3232 3233 if abs in pmf:
3233 3234 if mfentry:
3234 3235 # if version of file is same in parent and target
3235 3236 # manifests, do nothing
3236 3237 if (pmf[abs] != mfentry or
3237 3238 pmf.flags(abs) != mf.flags(abs)):
3238 3239 handle(revert, False)
3239 3240 else:
3240 3241 handle(remove, False)
3241 3242
3242 3243 if not opts.get('dry_run'):
3243 3244 def checkout(f):
3244 3245 fc = ctx[f]
3245 3246 repo.wwrite(f, fc.data(), fc.flags())
3246 3247
3247 3248 audit_path = util.path_auditor(repo.root)
3248 3249 for f in remove[0]:
3249 3250 if repo.dirstate[f] == 'a':
3250 3251 repo.dirstate.forget(f)
3251 3252 continue
3252 3253 audit_path(f)
3253 3254 try:
3254 3255 util.unlink(repo.wjoin(f))
3255 3256 except OSError:
3256 3257 pass
3257 3258 repo.dirstate.remove(f)
3258 3259
3259 3260 normal = None
3260 3261 if node == parent:
3261 3262 # We're reverting to our parent. If possible, we'd like status
3262 3263 # to report the file as clean. We have to use normallookup for
3263 3264 # merges to avoid losing information about merged/dirty files.
3264 3265 if p2 != nullid:
3265 3266 normal = repo.dirstate.normallookup
3266 3267 else:
3267 3268 normal = repo.dirstate.normal
3268 3269 for f in revert[0]:
3269 3270 checkout(f)
3270 3271 if normal:
3271 3272 normal(f)
3272 3273
3273 3274 for f in add[0]:
3274 3275 checkout(f)
3275 3276 repo.dirstate.add(f)
3276 3277
3277 3278 normal = repo.dirstate.normallookup
3278 3279 if node == parent and p2 == nullid:
3279 3280 normal = repo.dirstate.normal
3280 3281 for f in undelete[0]:
3281 3282 checkout(f)
3282 3283 normal(f)
3283 3284
3284 3285 finally:
3285 3286 wlock.release()
3286 3287
3287 3288 def rollback(ui, repo, **opts):
3288 3289 """roll back the last transaction (dangerous)
3289 3290
3290 3291 This command should be used with care. There is only one level of
3291 3292 rollback, and there is no way to undo a rollback. It will also
3292 3293 restore the dirstate at the time of the last transaction, losing
3293 3294 any dirstate changes since that time. This command does not alter
3294 3295 the working directory.
3295 3296
3296 3297 Transactions are used to encapsulate the effects of all commands
3297 3298 that create new changesets or propagate existing changesets into a
3298 3299 repository. For example, the following commands are transactional,
3299 3300 and their effects can be rolled back:
3300 3301
3301 3302 - commit
3302 3303 - import
3303 3304 - pull
3304 3305 - push (with this repository as the destination)
3305 3306 - unbundle
3306 3307
3307 3308 This command is not intended for use on public repositories. Once
3308 3309 changes are visible for pull by other users, rolling a transaction
3309 3310 back locally is ineffective (someone else may already have pulled
3310 3311 the changes). Furthermore, a race is possible with readers of the
3311 3312 repository; for example an in-progress pull from the repository
3312 3313 may fail if a rollback is performed.
3313 3314
3314 3315 Returns 0 on success, 1 if no rollback data is available.
3315 3316 """
3316 3317 return repo.rollback(opts.get('dry_run'))
3317 3318
3318 3319 def root(ui, repo):
3319 3320 """print the root (top) of the current working directory
3320 3321
3321 3322 Print the root directory of the current repository.
3322 3323
3323 3324 Returns 0 on success.
3324 3325 """
3325 3326 ui.write(repo.root + "\n")
3326 3327
3327 3328 def serve(ui, repo, **opts):
3328 3329 """start stand-alone webserver
3329 3330
3330 3331 Start a local HTTP repository browser and pull server. You can use
3331 3332 this for ad-hoc sharing and browing of repositories. It is
3332 3333 recommended to use a real web server to serve a repository for
3333 3334 longer periods of time.
3334 3335
3335 3336 Please note that the server does not implement access control.
3336 3337 This means that, by default, anybody can read from the server and
3337 3338 nobody can write to it by default. Set the ``web.allow_push``
3338 3339 option to ``*`` to allow everybody to push to the server. You
3339 3340 should use a real web server if you need to authenticate users.
3340 3341
3341 3342 By default, the server logs accesses to stdout and errors to
3342 3343 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
3343 3344 files.
3344 3345
3345 3346 To have the server choose a free port number to listen on, specify
3346 3347 a port number of 0; in this case, the server will print the port
3347 3348 number it uses.
3348 3349
3349 3350 Returns 0 on success.
3350 3351 """
3351 3352
3352 3353 if opts["stdio"]:
3353 3354 if repo is None:
3354 3355 raise error.RepoError(_("There is no Mercurial repository here"
3355 3356 " (.hg not found)"))
3356 3357 s = sshserver.sshserver(ui, repo)
3357 3358 s.serve_forever()
3358 3359
3359 3360 # this way we can check if something was given in the command-line
3360 3361 if opts.get('port'):
3361 3362 opts['port'] = util.getport(opts.get('port'))
3362 3363
3363 3364 baseui = repo and repo.baseui or ui
3364 3365 optlist = ("name templates style address port prefix ipv6"
3365 3366 " accesslog errorlog certificate encoding")
3366 3367 for o in optlist.split():
3367 3368 val = opts.get(o, '')
3368 3369 if val in (None, ''): # should check against default options instead
3369 3370 continue
3370 3371 baseui.setconfig("web", o, val)
3371 3372 if repo and repo.ui != baseui:
3372 3373 repo.ui.setconfig("web", o, val)
3373 3374
3374 3375 o = opts.get('web_conf') or opts.get('webdir_conf')
3375 3376 if not o:
3376 3377 if not repo:
3377 3378 raise error.RepoError(_("There is no Mercurial repository"
3378 3379 " here (.hg not found)"))
3379 3380 o = repo.root
3380 3381
3381 3382 app = hgweb.hgweb(o, baseui=ui)
3382 3383
3383 3384 class service(object):
3384 3385 def init(self):
3385 3386 util.set_signal_handler()
3386 3387 self.httpd = hgweb.server.create_server(ui, app)
3387 3388
3388 3389 if opts['port'] and not ui.verbose:
3389 3390 return
3390 3391
3391 3392 if self.httpd.prefix:
3392 3393 prefix = self.httpd.prefix.strip('/') + '/'
3393 3394 else:
3394 3395 prefix = ''
3395 3396
3396 3397 port = ':%d' % self.httpd.port
3397 3398 if port == ':80':
3398 3399 port = ''
3399 3400
3400 3401 bindaddr = self.httpd.addr
3401 3402 if bindaddr == '0.0.0.0':
3402 3403 bindaddr = '*'
3403 3404 elif ':' in bindaddr: # IPv6
3404 3405 bindaddr = '[%s]' % bindaddr
3405 3406
3406 3407 fqaddr = self.httpd.fqaddr
3407 3408 if ':' in fqaddr:
3408 3409 fqaddr = '[%s]' % fqaddr
3409 3410 if opts['port']:
3410 3411 write = ui.status
3411 3412 else:
3412 3413 write = ui.write
3413 3414 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
3414 3415 (fqaddr, port, prefix, bindaddr, self.httpd.port))
3415 3416
3416 3417 def run(self):
3417 3418 self.httpd.serve_forever()
3418 3419
3419 3420 service = service()
3420 3421
3421 3422 cmdutil.service(opts, initfn=service.init, runfn=service.run)
3422 3423
3423 3424 def status(ui, repo, *pats, **opts):
3424 3425 """show changed files in the working directory
3425 3426
3426 3427 Show status of files in the repository. If names are given, only
3427 3428 files that match are shown. Files that are clean or ignored or
3428 3429 the source of a copy/move operation, are not listed unless
3429 3430 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
3430 3431 Unless options described with "show only ..." are given, the
3431 3432 options -mardu are used.
3432 3433
3433 3434 Option -q/--quiet hides untracked (unknown and ignored) files
3434 3435 unless explicitly requested with -u/--unknown or -i/--ignored.
3435 3436
3436 3437 .. note::
3437 3438 status may appear to disagree with diff if permissions have
3438 3439 changed or a merge has occurred. The standard diff format does
3439 3440 not report permission changes and diff only reports changes
3440 3441 relative to one merge parent.
3441 3442
3442 3443 If one revision is given, it is used as the base revision.
3443 3444 If two revisions are given, the differences between them are
3444 3445 shown. The --change option can also be used as a shortcut to list
3445 3446 the changed files of a revision from its first parent.
3446 3447
3447 3448 The codes used to show the status of files are::
3448 3449
3449 3450 M = modified
3450 3451 A = added
3451 3452 R = removed
3452 3453 C = clean
3453 3454 ! = missing (deleted by non-hg command, but still tracked)
3454 3455 ? = not tracked
3455 3456 I = ignored
3456 3457 = origin of the previous file listed as A (added)
3457 3458
3458 3459 Returns 0 on success.
3459 3460 """
3460 3461
3461 3462 revs = opts.get('rev')
3462 3463 change = opts.get('change')
3463 3464
3464 3465 if revs and change:
3465 3466 msg = _('cannot specify --rev and --change at the same time')
3466 3467 raise util.Abort(msg)
3467 3468 elif change:
3468 3469 node2 = repo.lookup(change)
3469 3470 node1 = repo[node2].parents()[0].node()
3470 3471 else:
3471 3472 node1, node2 = cmdutil.revpair(repo, revs)
3472 3473
3473 3474 cwd = (pats and repo.getcwd()) or ''
3474 3475 end = opts.get('print0') and '\0' or '\n'
3475 3476 copy = {}
3476 3477 states = 'modified added removed deleted unknown ignored clean'.split()
3477 3478 show = [k for k in states if opts.get(k)]
3478 3479 if opts.get('all'):
3479 3480 show += ui.quiet and (states[:4] + ['clean']) or states
3480 3481 if not show:
3481 3482 show = ui.quiet and states[:4] or states[:5]
3482 3483
3483 3484 stat = repo.status(node1, node2, cmdutil.match(repo, pats, opts),
3484 3485 'ignored' in show, 'clean' in show, 'unknown' in show,
3485 3486 opts.get('subrepos'))
3486 3487 changestates = zip(states, 'MAR!?IC', stat)
3487 3488
3488 3489 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
3489 3490 ctxn = repo[nullid]
3490 3491 ctx1 = repo[node1]
3491 3492 ctx2 = repo[node2]
3492 3493 added = stat[1]
3493 3494 if node2 is None:
3494 3495 added = stat[0] + stat[1] # merged?
3495 3496
3496 3497 for k, v in copies.copies(repo, ctx1, ctx2, ctxn)[0].iteritems():
3497 3498 if k in added:
3498 3499 copy[k] = v
3499 3500 elif v in added:
3500 3501 copy[v] = k
3501 3502
3502 3503 for state, char, files in changestates:
3503 3504 if state in show:
3504 3505 format = "%s %%s%s" % (char, end)
3505 3506 if opts.get('no_status'):
3506 3507 format = "%%s%s" % end
3507 3508
3508 3509 for f in files:
3509 3510 ui.write(format % repo.pathto(f, cwd),
3510 3511 label='status.' + state)
3511 3512 if f in copy:
3512 3513 ui.write(' %s%s' % (repo.pathto(copy[f], cwd), end),
3513 3514 label='status.copied')
3514 3515
3515 3516 def summary(ui, repo, **opts):
3516 3517 """summarize working directory state
3517 3518
3518 3519 This generates a brief summary of the working directory state,
3519 3520 including parents, branch, commit status, and available updates.
3520 3521
3521 3522 With the --remote option, this will check the default paths for
3522 3523 incoming and outgoing changes. This can be time-consuming.
3523 3524
3524 3525 Returns 0 on success.
3525 3526 """
3526 3527
3527 3528 ctx = repo[None]
3528 3529 parents = ctx.parents()
3529 3530 pnode = parents[0].node()
3530 3531
3531 3532 for p in parents:
3532 3533 # label with log.changeset (instead of log.parent) since this
3533 3534 # shows a working directory parent *changeset*:
3534 3535 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
3535 3536 label='log.changeset')
3536 3537 ui.write(' '.join(p.tags()), label='log.tag')
3537 3538 if p.rev() == -1:
3538 3539 if not len(repo):
3539 3540 ui.write(_(' (empty repository)'))
3540 3541 else:
3541 3542 ui.write(_(' (no revision checked out)'))
3542 3543 ui.write('\n')
3543 3544 if p.description():
3544 3545 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
3545 3546 label='log.summary')
3546 3547
3547 3548 branch = ctx.branch()
3548 3549 bheads = repo.branchheads(branch)
3549 3550 m = _('branch: %s\n') % branch
3550 3551 if branch != 'default':
3551 3552 ui.write(m, label='log.branch')
3552 3553 else:
3553 3554 ui.status(m, label='log.branch')
3554 3555
3555 3556 st = list(repo.status(unknown=True))[:6]
3556 3557
3557 3558 c = repo.dirstate.copies()
3558 3559 copied, renamed = [], []
3559 3560 for d, s in c.iteritems():
3560 3561 if s in st[2]:
3561 3562 st[2].remove(s)
3562 3563 renamed.append(d)
3563 3564 else:
3564 3565 copied.append(d)
3565 3566 if d in st[1]:
3566 3567 st[1].remove(d)
3567 3568 st.insert(3, renamed)
3568 3569 st.insert(4, copied)
3569 3570
3570 3571 ms = mergemod.mergestate(repo)
3571 3572 st.append([f for f in ms if ms[f] == 'u'])
3572 3573
3573 3574 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
3574 3575 st.append(subs)
3575 3576
3576 3577 labels = [ui.label(_('%d modified'), 'status.modified'),
3577 3578 ui.label(_('%d added'), 'status.added'),
3578 3579 ui.label(_('%d removed'), 'status.removed'),
3579 3580 ui.label(_('%d renamed'), 'status.copied'),
3580 3581 ui.label(_('%d copied'), 'status.copied'),
3581 3582 ui.label(_('%d deleted'), 'status.deleted'),
3582 3583 ui.label(_('%d unknown'), 'status.unknown'),
3583 3584 ui.label(_('%d ignored'), 'status.ignored'),
3584 3585 ui.label(_('%d unresolved'), 'resolve.unresolved'),
3585 3586 ui.label(_('%d subrepos'), 'status.modified')]
3586 3587 t = []
3587 3588 for s, l in zip(st, labels):
3588 3589 if s:
3589 3590 t.append(l % len(s))
3590 3591
3591 3592 t = ', '.join(t)
3592 3593 cleanworkdir = False
3593 3594
3594 3595 if len(parents) > 1:
3595 3596 t += _(' (merge)')
3596 3597 elif branch != parents[0].branch():
3597 3598 t += _(' (new branch)')
3598 3599 elif (parents[0].extra().get('close') and
3599 3600 pnode in repo.branchheads(branch, closed=True)):
3600 3601 t += _(' (head closed)')
3601 3602 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
3602 3603 t += _(' (clean)')
3603 3604 cleanworkdir = True
3604 3605 elif pnode not in bheads:
3605 3606 t += _(' (new branch head)')
3606 3607
3607 3608 if cleanworkdir:
3608 3609 ui.status(_('commit: %s\n') % t.strip())
3609 3610 else:
3610 3611 ui.write(_('commit: %s\n') % t.strip())
3611 3612
3612 3613 # all ancestors of branch heads - all ancestors of parent = new csets
3613 3614 new = [0] * len(repo)
3614 3615 cl = repo.changelog
3615 3616 for a in [cl.rev(n) for n in bheads]:
3616 3617 new[a] = 1
3617 3618 for a in cl.ancestors(*[cl.rev(n) for n in bheads]):
3618 3619 new[a] = 1
3619 3620 for a in [p.rev() for p in parents]:
3620 3621 if a >= 0:
3621 3622 new[a] = 0
3622 3623 for a in cl.ancestors(*[p.rev() for p in parents]):
3623 3624 new[a] = 0
3624 3625 new = sum(new)
3625 3626
3626 3627 if new == 0:
3627 3628 ui.status(_('update: (current)\n'))
3628 3629 elif pnode not in bheads:
3629 3630 ui.write(_('update: %d new changesets (update)\n') % new)
3630 3631 else:
3631 3632 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
3632 3633 (new, len(bheads)))
3633 3634
3634 3635 if opts.get('remote'):
3635 3636 t = []
3636 3637 source, branches = hg.parseurl(ui.expandpath('default'))
3637 3638 other = hg.repository(hg.remoteui(repo, {}), source)
3638 3639 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
3639 3640 ui.debug('comparing with %s\n' % url.hidepassword(source))
3640 3641 repo.ui.pushbuffer()
3641 3642 common, incoming, rheads = discovery.findcommonincoming(repo, other)
3642 3643 repo.ui.popbuffer()
3643 3644 if incoming:
3644 3645 t.append(_('1 or more incoming'))
3645 3646
3646 3647 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
3647 3648 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
3648 3649 other = hg.repository(hg.remoteui(repo, {}), dest)
3649 3650 ui.debug('comparing with %s\n' % url.hidepassword(dest))
3650 3651 repo.ui.pushbuffer()
3651 3652 o = discovery.findoutgoing(repo, other)
3652 3653 repo.ui.popbuffer()
3653 3654 o = repo.changelog.nodesbetween(o, None)[0]
3654 3655 if o:
3655 3656 t.append(_('%d outgoing') % len(o))
3656 3657
3657 3658 if t:
3658 3659 ui.write(_('remote: %s\n') % (', '.join(t)))
3659 3660 else:
3660 3661 ui.status(_('remote: (synced)\n'))
3661 3662
3662 3663 def tag(ui, repo, name1, *names, **opts):
3663 3664 """add one or more tags for the current or given revision
3664 3665
3665 3666 Name a particular revision using <name>.
3666 3667
3667 3668 Tags are used to name particular revisions of the repository and are
3668 3669 very useful to compare different revisions, to go back to significant
3669 3670 earlier versions or to mark branch points as releases, etc.
3670 3671
3671 3672 If no revision is given, the parent of the working directory is
3672 3673 used, or tip if no revision is checked out.
3673 3674
3674 3675 To facilitate version control, distribution, and merging of tags,
3675 3676 they are stored as a file named ".hgtags" which is managed
3676 3677 similarly to other project files and can be hand-edited if
3677 3678 necessary. The file '.hg/localtags' is used for local tags (not
3678 3679 shared among repositories).
3679 3680
3680 3681 See :hg:`help dates` for a list of formats valid for -d/--date.
3681 3682
3682 3683 Since tag names have priority over branch names during revision
3683 3684 lookup, using an existing branch name as a tag name is discouraged.
3684 3685
3685 3686 Returns 0 on success.
3686 3687 """
3687 3688
3688 3689 rev_ = "."
3689 3690 names = [t.strip() for t in (name1,) + names]
3690 3691 if len(names) != len(set(names)):
3691 3692 raise util.Abort(_('tag names must be unique'))
3692 3693 for n in names:
3693 3694 if n in ['tip', '.', 'null']:
3694 3695 raise util.Abort(_('the name \'%s\' is reserved') % n)
3695 3696 if not n:
3696 3697 raise util.Abort(_('tag names cannot consist entirely of whitespace'))
3697 3698 if opts.get('rev') and opts.get('remove'):
3698 3699 raise util.Abort(_("--rev and --remove are incompatible"))
3699 3700 if opts.get('rev'):
3700 3701 rev_ = opts['rev']
3701 3702 message = opts.get('message')
3702 3703 if opts.get('remove'):
3703 3704 expectedtype = opts.get('local') and 'local' or 'global'
3704 3705 for n in names:
3705 3706 if not repo.tagtype(n):
3706 3707 raise util.Abort(_('tag \'%s\' does not exist') % n)
3707 3708 if repo.tagtype(n) != expectedtype:
3708 3709 if expectedtype == 'global':
3709 3710 raise util.Abort(_('tag \'%s\' is not a global tag') % n)
3710 3711 else:
3711 3712 raise util.Abort(_('tag \'%s\' is not a local tag') % n)
3712 3713 rev_ = nullid
3713 3714 if not message:
3714 3715 # we don't translate commit messages
3715 3716 message = 'Removed tag %s' % ', '.join(names)
3716 3717 elif not opts.get('force'):
3717 3718 for n in names:
3718 3719 if n in repo.tags():
3719 3720 raise util.Abort(_('tag \'%s\' already exists '
3720 3721 '(use -f to force)') % n)
3721 3722 if not rev_ and repo.dirstate.parents()[1] != nullid:
3722 3723 raise util.Abort(_('uncommitted merge - please provide a '
3723 3724 'specific revision'))
3724 r = repo[rev_].node()
3725 r = cmdutil.revsingle(repo, rev_).node()
3725 3726
3726 3727 if not message:
3727 3728 # we don't translate commit messages
3728 3729 message = ('Added tag %s for changeset %s' %
3729 3730 (', '.join(names), short(r)))
3730 3731
3731 3732 date = opts.get('date')
3732 3733 if date:
3733 3734 date = util.parsedate(date)
3734 3735
3735 3736 if opts.get('edit'):
3736 3737 message = ui.edit(message, ui.username())
3737 3738
3738 3739 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
3739 3740
3740 3741 def tags(ui, repo):
3741 3742 """list repository tags
3742 3743
3743 3744 This lists both regular and local tags. When the -v/--verbose
3744 3745 switch is used, a third column "local" is printed for local tags.
3745 3746
3746 3747 Returns 0 on success.
3747 3748 """
3748 3749
3749 3750 hexfunc = ui.debugflag and hex or short
3750 3751 tagtype = ""
3751 3752
3752 3753 for t, n in reversed(repo.tagslist()):
3753 3754 if ui.quiet:
3754 3755 ui.write("%s\n" % t)
3755 3756 continue
3756 3757
3757 3758 try:
3758 3759 hn = hexfunc(n)
3759 3760 r = "%5d:%s" % (repo.changelog.rev(n), hn)
3760 3761 except error.LookupError:
3761 3762 r = " ?:%s" % hn
3762 3763 else:
3763 3764 spaces = " " * (30 - encoding.colwidth(t))
3764 3765 if ui.verbose:
3765 3766 if repo.tagtype(t) == 'local':
3766 3767 tagtype = " local"
3767 3768 else:
3768 3769 tagtype = ""
3769 3770 ui.write("%s%s %s%s\n" % (t, spaces, r, tagtype))
3770 3771
3771 3772 def tip(ui, repo, **opts):
3772 3773 """show the tip revision
3773 3774
3774 3775 The tip revision (usually just called the tip) is the changeset
3775 3776 most recently added to the repository (and therefore the most
3776 3777 recently changed head).
3777 3778
3778 3779 If you have just made a commit, that commit will be the tip. If
3779 3780 you have just pulled changes from another repository, the tip of
3780 3781 that repository becomes the current tip. The "tip" tag is special
3781 3782 and cannot be renamed or assigned to a different changeset.
3782 3783
3783 3784 Returns 0 on success.
3784 3785 """
3785 3786 displayer = cmdutil.show_changeset(ui, repo, opts)
3786 3787 displayer.show(repo[len(repo) - 1])
3787 3788 displayer.close()
3788 3789
3789 3790 def unbundle(ui, repo, fname1, *fnames, **opts):
3790 3791 """apply one or more changegroup files
3791 3792
3792 3793 Apply one or more compressed changegroup files generated by the
3793 3794 bundle command.
3794 3795
3795 3796 Returns 0 on success, 1 if an update has unresolved files.
3796 3797 """
3797 3798 fnames = (fname1,) + fnames
3798 3799
3799 3800 lock = repo.lock()
3800 3801 try:
3801 3802 for fname in fnames:
3802 3803 f = url.open(ui, fname)
3803 3804 gen = changegroup.readbundle(f, fname)
3804 3805 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname,
3805 3806 lock=lock)
3806 3807 finally:
3807 3808 lock.release()
3808 3809
3809 3810 return postincoming(ui, repo, modheads, opts.get('update'), None)
3810 3811
3811 3812 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
3812 3813 """update working directory (or switch revisions)
3813 3814
3814 3815 Update the repository's working directory to the specified
3815 3816 changeset. If no changeset is specified, update to the tip of the
3816 3817 current named branch.
3817 3818
3818 3819 If the changeset is not a descendant of the working directory's
3819 3820 parent, the update is aborted. With the -c/--check option, the
3820 3821 working directory is checked for uncommitted changes; if none are
3821 3822 found, the working directory is updated to the specified
3822 3823 changeset.
3823 3824
3824 3825 The following rules apply when the working directory contains
3825 3826 uncommitted changes:
3826 3827
3827 3828 1. If neither -c/--check nor -C/--clean is specified, and if
3828 3829 the requested changeset is an ancestor or descendant of
3829 3830 the working directory's parent, the uncommitted changes
3830 3831 are merged into the requested changeset and the merged
3831 3832 result is left uncommitted. If the requested changeset is
3832 3833 not an ancestor or descendant (that is, it is on another
3833 3834 branch), the update is aborted and the uncommitted changes
3834 3835 are preserved.
3835 3836
3836 3837 2. With the -c/--check option, the update is aborted and the
3837 3838 uncommitted changes are preserved.
3838 3839
3839 3840 3. With the -C/--clean option, uncommitted changes are discarded and
3840 3841 the working directory is updated to the requested changeset.
3841 3842
3842 3843 Use null as the changeset to remove the working directory (like
3843 3844 :hg:`clone -U`).
3844 3845
3845 3846 If you want to update just one file to an older changeset, use
3846 3847 :hg:`revert`.
3847 3848
3848 3849 See :hg:`help dates` for a list of formats valid for -d/--date.
3849 3850
3850 3851 Returns 0 on success, 1 if there are unresolved files.
3851 3852 """
3852 3853 if rev and node:
3853 3854 raise util.Abort(_("please specify just one revision"))
3854 3855
3855 3856 if not rev:
3856 3857 rev = node
3857 3858
3858 3859 rev = cmdutil.revsingle(repo, rev, rev).rev()
3859 3860
3860 3861 if check and clean:
3861 3862 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
3862 3863
3863 3864 if check:
3864 3865 # we could use dirty() but we can ignore merge and branch trivia
3865 3866 c = repo[None]
3866 3867 if c.modified() or c.added() or c.removed():
3867 3868 raise util.Abort(_("uncommitted local changes"))
3868 3869
3869 3870 if date:
3870 3871 if rev:
3871 3872 raise util.Abort(_("you can't specify a revision and a date"))
3872 3873 rev = cmdutil.finddate(ui, repo, date)
3873 3874
3874 3875 if clean or check:
3875 3876 return hg.clean(repo, rev)
3876 3877 else:
3877 3878 return hg.update(repo, rev)
3878 3879
3879 3880 def verify(ui, repo):
3880 3881 """verify the integrity of the repository
3881 3882
3882 3883 Verify the integrity of the current repository.
3883 3884
3884 3885 This will perform an extensive check of the repository's
3885 3886 integrity, validating the hashes and checksums of each entry in
3886 3887 the changelog, manifest, and tracked files, as well as the
3887 3888 integrity of their crosslinks and indices.
3888 3889
3889 3890 Returns 0 on success, 1 if errors are encountered.
3890 3891 """
3891 3892 return hg.verify(repo)
3892 3893
3893 3894 def version_(ui):
3894 3895 """output version and copyright information"""
3895 3896 ui.write(_("Mercurial Distributed SCM (version %s)\n")
3896 3897 % util.version())
3897 3898 ui.status(_(
3898 3899 "(see http://mercurial.selenic.com for more information)\n"
3899 3900 "\nCopyright (C) 2005-2010 Matt Mackall and others\n"
3900 3901 "This is free software; see the source for copying conditions. "
3901 3902 "There is NO\nwarranty; "
3902 3903 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
3903 3904 ))
3904 3905
3905 3906 # Command options and aliases are listed here, alphabetically
3906 3907
3907 3908 globalopts = [
3908 3909 ('R', 'repository', '',
3909 3910 _('repository root directory or name of overlay bundle file'),
3910 3911 _('REPO')),
3911 3912 ('', 'cwd', '',
3912 3913 _('change working directory'), _('DIR')),
3913 3914 ('y', 'noninteractive', None,
3914 3915 _('do not prompt, assume \'yes\' for any required answers')),
3915 3916 ('q', 'quiet', None, _('suppress output')),
3916 3917 ('v', 'verbose', None, _('enable additional output')),
3917 3918 ('', 'config', [],
3918 3919 _('set/override config option (use \'section.name=value\')'),
3919 3920 _('CONFIG')),
3920 3921 ('', 'debug', None, _('enable debugging output')),
3921 3922 ('', 'debugger', None, _('start debugger')),
3922 3923 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
3923 3924 _('ENCODE')),
3924 3925 ('', 'encodingmode', encoding.encodingmode,
3925 3926 _('set the charset encoding mode'), _('MODE')),
3926 3927 ('', 'traceback', None, _('always print a traceback on exception')),
3927 3928 ('', 'time', None, _('time how long the command takes')),
3928 3929 ('', 'profile', None, _('print command execution profile')),
3929 3930 ('', 'version', None, _('output version information and exit')),
3930 3931 ('h', 'help', None, _('display help and exit')),
3931 3932 ]
3932 3933
3933 3934 dryrunopts = [('n', 'dry-run', None,
3934 3935 _('do not perform actions, just print output'))]
3935 3936
3936 3937 remoteopts = [
3937 3938 ('e', 'ssh', '',
3938 3939 _('specify ssh command to use'), _('CMD')),
3939 3940 ('', 'remotecmd', '',
3940 3941 _('specify hg command to run on the remote side'), _('CMD')),
3941 3942 ]
3942 3943
3943 3944 walkopts = [
3944 3945 ('I', 'include', [],
3945 3946 _('include names matching the given patterns'), _('PATTERN')),
3946 3947 ('X', 'exclude', [],
3947 3948 _('exclude names matching the given patterns'), _('PATTERN')),
3948 3949 ]
3949 3950
3950 3951 commitopts = [
3951 3952 ('m', 'message', '',
3952 3953 _('use text as commit message'), _('TEXT')),
3953 3954 ('l', 'logfile', '',
3954 3955 _('read commit message from file'), _('FILE')),
3955 3956 ]
3956 3957
3957 3958 commitopts2 = [
3958 3959 ('d', 'date', '',
3959 3960 _('record datecode as commit date'), _('DATE')),
3960 3961 ('u', 'user', '',
3961 3962 _('record the specified user as committer'), _('USER')),
3962 3963 ]
3963 3964
3964 3965 templateopts = [
3965 3966 ('', 'style', '',
3966 3967 _('display using template map file'), _('STYLE')),
3967 3968 ('', 'template', '',
3968 3969 _('display with template'), _('TEMPLATE')),
3969 3970 ]
3970 3971
3971 3972 logopts = [
3972 3973 ('p', 'patch', None, _('show patch')),
3973 3974 ('g', 'git', None, _('use git extended diff format')),
3974 3975 ('l', 'limit', '',
3975 3976 _('limit number of changes displayed'), _('NUM')),
3976 3977 ('M', 'no-merges', None, _('do not show merges')),
3977 3978 ('', 'stat', None, _('output diffstat-style summary of changes')),
3978 3979 ] + templateopts
3979 3980
3980 3981 diffopts = [
3981 3982 ('a', 'text', None, _('treat all files as text')),
3982 3983 ('g', 'git', None, _('use git extended diff format')),
3983 3984 ('', 'nodates', None, _('omit dates from diff headers'))
3984 3985 ]
3985 3986
3986 3987 diffopts2 = [
3987 3988 ('p', 'show-function', None, _('show which function each change is in')),
3988 3989 ('', 'reverse', None, _('produce a diff that undoes the changes')),
3989 3990 ('w', 'ignore-all-space', None,
3990 3991 _('ignore white space when comparing lines')),
3991 3992 ('b', 'ignore-space-change', None,
3992 3993 _('ignore changes in the amount of white space')),
3993 3994 ('B', 'ignore-blank-lines', None,
3994 3995 _('ignore changes whose lines are all blank')),
3995 3996 ('U', 'unified', '',
3996 3997 _('number of lines of context to show'), _('NUM')),
3997 3998 ('', 'stat', None, _('output diffstat-style summary of changes')),
3998 3999 ]
3999 4000
4000 4001 similarityopts = [
4001 4002 ('s', 'similarity', '',
4002 4003 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
4003 4004 ]
4004 4005
4005 4006 subrepoopts = [
4006 4007 ('S', 'subrepos', None,
4007 4008 _('recurse into subrepositories'))
4008 4009 ]
4009 4010
4010 4011 table = {
4011 4012 "^add": (add, walkopts + subrepoopts + dryrunopts,
4012 4013 _('[OPTION]... [FILE]...')),
4013 4014 "addremove":
4014 4015 (addremove, similarityopts + walkopts + dryrunopts,
4015 4016 _('[OPTION]... [FILE]...')),
4016 4017 "^annotate|blame":
4017 4018 (annotate,
4018 4019 [('r', 'rev', '',
4019 4020 _('annotate the specified revision'), _('REV')),
4020 4021 ('', 'follow', None,
4021 4022 _('follow copies/renames and list the filename (DEPRECATED)')),
4022 4023 ('', 'no-follow', None, _("don't follow copies and renames")),
4023 4024 ('a', 'text', None, _('treat all files as text')),
4024 4025 ('u', 'user', None, _('list the author (long with -v)')),
4025 4026 ('f', 'file', None, _('list the filename')),
4026 4027 ('d', 'date', None, _('list the date (short with -q)')),
4027 4028 ('n', 'number', None, _('list the revision number (default)')),
4028 4029 ('c', 'changeset', None, _('list the changeset')),
4029 4030 ('l', 'line-number', None,
4030 4031 _('show line number at the first appearance'))
4031 4032 ] + walkopts,
4032 4033 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...')),
4033 4034 "archive":
4034 4035 (archive,
4035 4036 [('', 'no-decode', None, _('do not pass files through decoders')),
4036 4037 ('p', 'prefix', '',
4037 4038 _('directory prefix for files in archive'), _('PREFIX')),
4038 4039 ('r', 'rev', '',
4039 4040 _('revision to distribute'), _('REV')),
4040 4041 ('t', 'type', '',
4041 4042 _('type of distribution to create'), _('TYPE')),
4042 4043 ] + subrepoopts + walkopts,
4043 4044 _('[OPTION]... DEST')),
4044 4045 "backout":
4045 4046 (backout,
4046 4047 [('', 'merge', None,
4047 4048 _('merge with old dirstate parent after backout')),
4048 4049 ('', 'parent', '',
4049 4050 _('parent to choose when backing out merge'), _('REV')),
4050 4051 ('t', 'tool', '',
4051 4052 _('specify merge tool')),
4052 4053 ('r', 'rev', '',
4053 4054 _('revision to backout'), _('REV')),
4054 4055 ] + walkopts + commitopts + commitopts2,
4055 4056 _('[OPTION]... [-r] REV')),
4056 4057 "bisect":
4057 4058 (bisect,
4058 4059 [('r', 'reset', False, _('reset bisect state')),
4059 4060 ('g', 'good', False, _('mark changeset good')),
4060 4061 ('b', 'bad', False, _('mark changeset bad')),
4061 4062 ('s', 'skip', False, _('skip testing changeset')),
4062 4063 ('c', 'command', '',
4063 4064 _('use command to check changeset state'), _('CMD')),
4064 4065 ('U', 'noupdate', False, _('do not update to target'))],
4065 4066 _("[-gbsr] [-U] [-c CMD] [REV]")),
4066 4067 "branch":
4067 4068 (branch,
4068 4069 [('f', 'force', None,
4069 4070 _('set branch name even if it shadows an existing branch')),
4070 4071 ('C', 'clean', None, _('reset branch name to parent branch name'))],
4071 4072 _('[-fC] [NAME]')),
4072 4073 "branches":
4073 4074 (branches,
4074 4075 [('a', 'active', False,
4075 4076 _('show only branches that have unmerged heads')),
4076 4077 ('c', 'closed', False,
4077 4078 _('show normal and closed branches'))],
4078 4079 _('[-ac]')),
4079 4080 "bundle":
4080 4081 (bundle,
4081 4082 [('f', 'force', None,
4082 4083 _('run even when the destination is unrelated')),
4083 4084 ('r', 'rev', [],
4084 4085 _('a changeset intended to be added to the destination'),
4085 4086 _('REV')),
4086 4087 ('b', 'branch', [],
4087 4088 _('a specific branch you would like to bundle'),
4088 4089 _('BRANCH')),
4089 4090 ('', 'base', [],
4090 4091 _('a base changeset assumed to be available at the destination'),
4091 4092 _('REV')),
4092 4093 ('a', 'all', None, _('bundle all changesets in the repository')),
4093 4094 ('t', 'type', 'bzip2',
4094 4095 _('bundle compression type to use'), _('TYPE')),
4095 4096 ] + remoteopts,
4096 4097 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]')),
4097 4098 "cat":
4098 4099 (cat,
4099 4100 [('o', 'output', '',
4100 4101 _('print output to file with formatted name'), _('FORMAT')),
4101 4102 ('r', 'rev', '',
4102 4103 _('print the given revision'), _('REV')),
4103 4104 ('', 'decode', None, _('apply any matching decode filter')),
4104 4105 ] + walkopts,
4105 4106 _('[OPTION]... FILE...')),
4106 4107 "^clone":
4107 4108 (clone,
4108 4109 [('U', 'noupdate', None,
4109 4110 _('the clone will include an empty working copy (only a repository)')),
4110 4111 ('u', 'updaterev', '',
4111 4112 _('revision, tag or branch to check out'), _('REV')),
4112 4113 ('r', 'rev', [],
4113 4114 _('include the specified changeset'), _('REV')),
4114 4115 ('b', 'branch', [],
4115 4116 _('clone only the specified branch'), _('BRANCH')),
4116 4117 ('', 'pull', None, _('use pull protocol to copy metadata')),
4117 4118 ('', 'uncompressed', None,
4118 4119 _('use uncompressed transfer (fast over LAN)')),
4119 4120 ] + remoteopts,
4120 4121 _('[OPTION]... SOURCE [DEST]')),
4121 4122 "^commit|ci":
4122 4123 (commit,
4123 4124 [('A', 'addremove', None,
4124 4125 _('mark new/missing files as added/removed before committing')),
4125 4126 ('', 'close-branch', None,
4126 4127 _('mark a branch as closed, hiding it from the branch list')),
4127 4128 ] + walkopts + commitopts + commitopts2,
4128 4129 _('[OPTION]... [FILE]...')),
4129 4130 "copy|cp":
4130 4131 (copy,
4131 4132 [('A', 'after', None, _('record a copy that has already occurred')),
4132 4133 ('f', 'force', None,
4133 4134 _('forcibly copy over an existing managed file')),
4134 4135 ] + walkopts + dryrunopts,
4135 4136 _('[OPTION]... [SOURCE]... DEST')),
4136 4137 "debugancestor": (debugancestor, [], _('[INDEX] REV1 REV2')),
4137 4138 "debugbuilddag":
4138 4139 (debugbuilddag,
4139 4140 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
4140 4141 ('a', 'appended-file', None, _('add single file all revs append to')),
4141 4142 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
4142 4143 ('n', 'new-file', None, _('add new file at each rev')),
4143 4144 ],
4144 4145 _('[OPTION]... TEXT')),
4145 4146 "debugcheckstate": (debugcheckstate, [], ''),
4146 4147 "debugcommands": (debugcommands, [], _('[COMMAND]')),
4147 4148 "debugcomplete":
4148 4149 (debugcomplete,
4149 4150 [('o', 'options', None, _('show the command options'))],
4150 4151 _('[-o] CMD')),
4151 4152 "debugdag":
4152 4153 (debugdag,
4153 4154 [('t', 'tags', None, _('use tags as labels')),
4154 4155 ('b', 'branches', None, _('annotate with branch names')),
4155 4156 ('', 'dots', None, _('use dots for runs')),
4156 4157 ('s', 'spaces', None, _('separate elements by spaces')),
4157 4158 ],
4158 4159 _('[OPTION]... [FILE [REV]...]')),
4159 4160 "debugdate":
4160 4161 (debugdate,
4161 4162 [('e', 'extended', None, _('try extended date formats'))],
4162 4163 _('[-e] DATE [RANGE]')),
4163 4164 "debugdata": (debugdata, [], _('FILE REV')),
4164 4165 "debugfsinfo": (debugfsinfo, [], _('[PATH]')),
4165 4166 "debugindex": (debugindex,
4166 4167 [('f', 'format', 0, _('revlog format'), _('FORMAT'))],
4167 4168 _('FILE')),
4168 4169 "debugindexdot": (debugindexdot, [], _('FILE')),
4169 4170 "debuginstall": (debuginstall, [], ''),
4170 4171 "debugpushkey": (debugpushkey, [], _('REPO NAMESPACE [KEY OLD NEW]')),
4171 4172 "debugrebuildstate":
4172 4173 (debugrebuildstate,
4173 4174 [('r', 'rev', '',
4174 4175 _('revision to rebuild to'), _('REV'))],
4175 4176 _('[-r REV] [REV]')),
4176 4177 "debugrename":
4177 4178 (debugrename,
4178 4179 [('r', 'rev', '',
4179 4180 _('revision to debug'), _('REV'))],
4180 4181 _('[-r REV] FILE')),
4181 4182 "debugrevspec":
4182 4183 (debugrevspec, [], ('REVSPEC')),
4183 4184 "debugsetparents":
4184 4185 (debugsetparents, [], _('REV1 [REV2]')),
4185 4186 "debugstate":
4186 4187 (debugstate,
4187 4188 [('', 'nodates', None, _('do not display the saved mtime'))],
4188 4189 _('[OPTION]...')),
4189 4190 "debugsub":
4190 4191 (debugsub,
4191 4192 [('r', 'rev', '',
4192 4193 _('revision to check'), _('REV'))],
4193 4194 _('[-r REV] [REV]')),
4194 4195 "debugwalk": (debugwalk, walkopts, _('[OPTION]... [FILE]...')),
4195 4196 "^diff":
4196 4197 (diff,
4197 4198 [('r', 'rev', [],
4198 4199 _('revision'), _('REV')),
4199 4200 ('c', 'change', '',
4200 4201 _('change made by revision'), _('REV'))
4201 4202 ] + diffopts + diffopts2 + walkopts + subrepoopts,
4202 4203 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...')),
4203 4204 "^export":
4204 4205 (export,
4205 4206 [('o', 'output', '',
4206 4207 _('print output to file with formatted name'), _('FORMAT')),
4207 4208 ('', 'switch-parent', None, _('diff against the second parent')),
4208 4209 ('r', 'rev', [],
4209 4210 _('revisions to export'), _('REV')),
4210 4211 ] + diffopts,
4211 4212 _('[OPTION]... [-o OUTFILESPEC] REV...')),
4212 4213 "^forget":
4213 4214 (forget,
4214 4215 [] + walkopts,
4215 4216 _('[OPTION]... FILE...')),
4216 4217 "grep":
4217 4218 (grep,
4218 4219 [('0', 'print0', None, _('end fields with NUL')),
4219 4220 ('', 'all', None, _('print all revisions that match')),
4220 4221 ('f', 'follow', None,
4221 4222 _('follow changeset history,'
4222 4223 ' or file history across copies and renames')),
4223 4224 ('i', 'ignore-case', None, _('ignore case when matching')),
4224 4225 ('l', 'files-with-matches', None,
4225 4226 _('print only filenames and revisions that match')),
4226 4227 ('n', 'line-number', None, _('print matching line numbers')),
4227 4228 ('r', 'rev', [],
4228 4229 _('only search files changed within revision range'), _('REV')),
4229 4230 ('u', 'user', None, _('list the author (long with -v)')),
4230 4231 ('d', 'date', None, _('list the date (short with -q)')),
4231 4232 ] + walkopts,
4232 4233 _('[OPTION]... PATTERN [FILE]...')),
4233 4234 "heads":
4234 4235 (heads,
4235 4236 [('r', 'rev', '',
4236 4237 _('show only heads which are descendants of STARTREV'),
4237 4238 _('STARTREV')),
4238 4239 ('t', 'topo', False, _('show topological heads only')),
4239 4240 ('a', 'active', False,
4240 4241 _('show active branchheads only (DEPRECATED)')),
4241 4242 ('c', 'closed', False,
4242 4243 _('show normal and closed branch heads')),
4243 4244 ] + templateopts,
4244 4245 _('[-ac] [-r STARTREV] [REV]...')),
4245 4246 "help": (help_, [], _('[TOPIC]')),
4246 4247 "identify|id":
4247 4248 (identify,
4248 4249 [('r', 'rev', '',
4249 4250 _('identify the specified revision'), _('REV')),
4250 4251 ('n', 'num', None, _('show local revision number')),
4251 4252 ('i', 'id', None, _('show global revision id')),
4252 4253 ('b', 'branch', None, _('show branch')),
4253 4254 ('t', 'tags', None, _('show tags'))],
4254 4255 _('[-nibt] [-r REV] [SOURCE]')),
4255 4256 "import|patch":
4256 4257 (import_,
4257 4258 [('p', 'strip', 1,
4258 4259 _('directory strip option for patch. This has the same '
4259 4260 'meaning as the corresponding patch option'),
4260 4261 _('NUM')),
4261 4262 ('b', 'base', '',
4262 4263 _('base path'), _('PATH')),
4263 4264 ('f', 'force', None,
4264 4265 _('skip check for outstanding uncommitted changes')),
4265 4266 ('', 'no-commit', None,
4266 4267 _("don't commit, just update the working directory")),
4267 4268 ('', 'exact', None,
4268 4269 _('apply patch to the nodes from which it was generated')),
4269 4270 ('', 'import-branch', None,
4270 4271 _('use any branch information in patch (implied by --exact)'))] +
4271 4272 commitopts + commitopts2 + similarityopts,
4272 4273 _('[OPTION]... PATCH...')),
4273 4274 "incoming|in":
4274 4275 (incoming,
4275 4276 [('f', 'force', None,
4276 4277 _('run even if remote repository is unrelated')),
4277 4278 ('n', 'newest-first', None, _('show newest record first')),
4278 4279 ('', 'bundle', '',
4279 4280 _('file to store the bundles into'), _('FILE')),
4280 4281 ('r', 'rev', [],
4281 4282 _('a remote changeset intended to be added'), _('REV')),
4282 4283 ('b', 'branch', [],
4283 4284 _('a specific branch you would like to pull'), _('BRANCH')),
4284 4285 ] + logopts + remoteopts + subrepoopts,
4285 4286 _('[-p] [-n] [-M] [-f] [-r REV]...'
4286 4287 ' [--bundle FILENAME] [SOURCE]')),
4287 4288 "^init":
4288 4289 (init,
4289 4290 remoteopts,
4290 4291 _('[-e CMD] [--remotecmd CMD] [DEST]')),
4291 4292 "locate":
4292 4293 (locate,
4293 4294 [('r', 'rev', '',
4294 4295 _('search the repository as it is in REV'), _('REV')),
4295 4296 ('0', 'print0', None,
4296 4297 _('end filenames with NUL, for use with xargs')),
4297 4298 ('f', 'fullpath', None,
4298 4299 _('print complete paths from the filesystem root')),
4299 4300 ] + walkopts,
4300 4301 _('[OPTION]... [PATTERN]...')),
4301 4302 "^log|history":
4302 4303 (log,
4303 4304 [('f', 'follow', None,
4304 4305 _('follow changeset history,'
4305 4306 ' or file history across copies and renames')),
4306 4307 ('', 'follow-first', None,
4307 4308 _('only follow the first parent of merge changesets')),
4308 4309 ('d', 'date', '',
4309 4310 _('show revisions matching date spec'), _('DATE')),
4310 4311 ('C', 'copies', None, _('show copied files')),
4311 4312 ('k', 'keyword', [],
4312 4313 _('do case-insensitive search for a given text'), _('TEXT')),
4313 4314 ('r', 'rev', [],
4314 4315 _('show the specified revision or range'), _('REV')),
4315 4316 ('', 'removed', None, _('include revisions where files were removed')),
4316 4317 ('m', 'only-merges', None, _('show only merges')),
4317 4318 ('u', 'user', [],
4318 4319 _('revisions committed by user'), _('USER')),
4319 4320 ('', 'only-branch', [],
4320 4321 _('show only changesets within the given named branch (DEPRECATED)'),
4321 4322 _('BRANCH')),
4322 4323 ('b', 'branch', [],
4323 4324 _('show changesets within the given named branch'), _('BRANCH')),
4324 4325 ('P', 'prune', [],
4325 4326 _('do not display revision or any of its ancestors'), _('REV')),
4326 4327 ] + logopts + walkopts,
4327 4328 _('[OPTION]... [FILE]')),
4328 4329 "manifest":
4329 4330 (manifest,
4330 4331 [('r', 'rev', '',
4331 4332 _('revision to display'), _('REV'))],
4332 4333 _('[-r REV]')),
4333 4334 "^merge":
4334 4335 (merge,
4335 4336 [('f', 'force', None, _('force a merge with outstanding changes')),
4336 4337 ('t', 'tool', '', _('specify merge tool')),
4337 4338 ('r', 'rev', '',
4338 4339 _('revision to merge'), _('REV')),
4339 4340 ('P', 'preview', None,
4340 4341 _('review revisions to merge (no merge is performed)'))],
4341 4342 _('[-P] [-f] [[-r] REV]')),
4342 4343 "outgoing|out":
4343 4344 (outgoing,
4344 4345 [('f', 'force', None,
4345 4346 _('run even when the destination is unrelated')),
4346 4347 ('r', 'rev', [],
4347 4348 _('a changeset intended to be included in the destination'),
4348 4349 _('REV')),
4349 4350 ('n', 'newest-first', None, _('show newest record first')),
4350 4351 ('b', 'branch', [],
4351 4352 _('a specific branch you would like to push'), _('BRANCH')),
4352 4353 ] + logopts + remoteopts + subrepoopts,
4353 4354 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]')),
4354 4355 "parents":
4355 4356 (parents,
4356 4357 [('r', 'rev', '',
4357 4358 _('show parents of the specified revision'), _('REV')),
4358 4359 ] + templateopts,
4359 4360 _('[-r REV] [FILE]')),
4360 4361 "paths": (paths, [], _('[NAME]')),
4361 4362 "^pull":
4362 4363 (pull,
4363 4364 [('u', 'update', None,
4364 4365 _('update to new branch head if changesets were pulled')),
4365 4366 ('f', 'force', None,
4366 4367 _('run even when remote repository is unrelated')),
4367 4368 ('r', 'rev', [],
4368 4369 _('a remote changeset intended to be added'), _('REV')),
4369 4370 ('b', 'branch', [],
4370 4371 _('a specific branch you would like to pull'), _('BRANCH')),
4371 4372 ] + remoteopts,
4372 4373 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]')),
4373 4374 "^push":
4374 4375 (push,
4375 4376 [('f', 'force', None, _('force push')),
4376 4377 ('r', 'rev', [],
4377 4378 _('a changeset intended to be included in the destination'),
4378 4379 _('REV')),
4379 4380 ('b', 'branch', [],
4380 4381 _('a specific branch you would like to push'), _('BRANCH')),
4381 4382 ('', 'new-branch', False, _('allow pushing a new branch')),
4382 4383 ] + remoteopts,
4383 4384 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]')),
4384 4385 "recover": (recover, []),
4385 4386 "^remove|rm":
4386 4387 (remove,
4387 4388 [('A', 'after', None, _('record delete for missing files')),
4388 4389 ('f', 'force', None,
4389 4390 _('remove (and delete) file even if added or modified')),
4390 4391 ] + walkopts,
4391 4392 _('[OPTION]... FILE...')),
4392 4393 "rename|move|mv":
4393 4394 (rename,
4394 4395 [('A', 'after', None, _('record a rename that has already occurred')),
4395 4396 ('f', 'force', None,
4396 4397 _('forcibly copy over an existing managed file')),
4397 4398 ] + walkopts + dryrunopts,
4398 4399 _('[OPTION]... SOURCE... DEST')),
4399 4400 "resolve":
4400 4401 (resolve,
4401 4402 [('a', 'all', None, _('select all unresolved files')),
4402 4403 ('l', 'list', None, _('list state of files needing merge')),
4403 4404 ('m', 'mark', None, _('mark files as resolved')),
4404 4405 ('u', 'unmark', None, _('mark files as unresolved')),
4405 4406 ('t', 'tool', '', _('specify merge tool')),
4406 4407 ('n', 'no-status', None, _('hide status prefix'))]
4407 4408 + walkopts,
4408 4409 _('[OPTION]... [FILE]...')),
4409 4410 "revert":
4410 4411 (revert,
4411 4412 [('a', 'all', None, _('revert all changes when no arguments given')),
4412 4413 ('d', 'date', '',
4413 4414 _('tipmost revision matching date'), _('DATE')),
4414 4415 ('r', 'rev', '',
4415 4416 _('revert to the specified revision'), _('REV')),
4416 4417 ('', 'no-backup', None, _('do not save backup copies of files')),
4417 4418 ] + walkopts + dryrunopts,
4418 4419 _('[OPTION]... [-r REV] [NAME]...')),
4419 4420 "rollback": (rollback, dryrunopts),
4420 4421 "root": (root, []),
4421 4422 "^serve":
4422 4423 (serve,
4423 4424 [('A', 'accesslog', '',
4424 4425 _('name of access log file to write to'), _('FILE')),
4425 4426 ('d', 'daemon', None, _('run server in background')),
4426 4427 ('', 'daemon-pipefds', '',
4427 4428 _('used internally by daemon mode'), _('NUM')),
4428 4429 ('E', 'errorlog', '',
4429 4430 _('name of error log file to write to'), _('FILE')),
4430 4431 # use string type, then we can check if something was passed
4431 4432 ('p', 'port', '',
4432 4433 _('port to listen on (default: 8000)'), _('PORT')),
4433 4434 ('a', 'address', '',
4434 4435 _('address to listen on (default: all interfaces)'), _('ADDR')),
4435 4436 ('', 'prefix', '',
4436 4437 _('prefix path to serve from (default: server root)'), _('PREFIX')),
4437 4438 ('n', 'name', '',
4438 4439 _('name to show in web pages (default: working directory)'),
4439 4440 _('NAME')),
4440 4441 ('', 'web-conf', '',
4441 4442 _('name of the hgweb config file (see "hg help hgweb")'),
4442 4443 _('FILE')),
4443 4444 ('', 'webdir-conf', '',
4444 4445 _('name of the hgweb config file (DEPRECATED)'), _('FILE')),
4445 4446 ('', 'pid-file', '',
4446 4447 _('name of file to write process ID to'), _('FILE')),
4447 4448 ('', 'stdio', None, _('for remote clients')),
4448 4449 ('t', 'templates', '',
4449 4450 _('web templates to use'), _('TEMPLATE')),
4450 4451 ('', 'style', '',
4451 4452 _('template style to use'), _('STYLE')),
4452 4453 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4453 4454 ('', 'certificate', '',
4454 4455 _('SSL certificate file'), _('FILE'))],
4455 4456 _('[OPTION]...')),
4456 4457 "showconfig|debugconfig":
4457 4458 (showconfig,
4458 4459 [('u', 'untrusted', None, _('show untrusted configuration options'))],
4459 4460 _('[-u] [NAME]...')),
4460 4461 "^summary|sum":
4461 4462 (summary,
4462 4463 [('', 'remote', None, _('check for push and pull'))], '[--remote]'),
4463 4464 "^status|st":
4464 4465 (status,
4465 4466 [('A', 'all', None, _('show status of all files')),
4466 4467 ('m', 'modified', None, _('show only modified files')),
4467 4468 ('a', 'added', None, _('show only added files')),
4468 4469 ('r', 'removed', None, _('show only removed files')),
4469 4470 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4470 4471 ('c', 'clean', None, _('show only files without changes')),
4471 4472 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4472 4473 ('i', 'ignored', None, _('show only ignored files')),
4473 4474 ('n', 'no-status', None, _('hide status prefix')),
4474 4475 ('C', 'copies', None, _('show source of copied files')),
4475 4476 ('0', 'print0', None,
4476 4477 _('end filenames with NUL, for use with xargs')),
4477 4478 ('', 'rev', [],
4478 4479 _('show difference from revision'), _('REV')),
4479 4480 ('', 'change', '',
4480 4481 _('list the changed files of a revision'), _('REV')),
4481 4482 ] + walkopts + subrepoopts,
4482 4483 _('[OPTION]... [FILE]...')),
4483 4484 "tag":
4484 4485 (tag,
4485 4486 [('f', 'force', None, _('replace existing tag')),
4486 4487 ('l', 'local', None, _('make the tag local')),
4487 4488 ('r', 'rev', '',
4488 4489 _('revision to tag'), _('REV')),
4489 4490 ('', 'remove', None, _('remove a tag')),
4490 4491 # -l/--local is already there, commitopts cannot be used
4491 4492 ('e', 'edit', None, _('edit commit message')),
4492 4493 ('m', 'message', '',
4493 4494 _('use <text> as commit message'), _('TEXT')),
4494 4495 ] + commitopts2,
4495 4496 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...')),
4496 4497 "tags": (tags, [], ''),
4497 4498 "tip":
4498 4499 (tip,
4499 4500 [('p', 'patch', None, _('show patch')),
4500 4501 ('g', 'git', None, _('use git extended diff format')),
4501 4502 ] + templateopts,
4502 4503 _('[-p] [-g]')),
4503 4504 "unbundle":
4504 4505 (unbundle,
4505 4506 [('u', 'update', None,
4506 4507 _('update to new branch head if changesets were unbundled'))],
4507 4508 _('[-u] FILE...')),
4508 4509 "^update|up|checkout|co":
4509 4510 (update,
4510 4511 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
4511 4512 ('c', 'check', None,
4512 4513 _('update across branches if no uncommitted changes')),
4513 4514 ('d', 'date', '',
4514 4515 _('tipmost revision matching date'), _('DATE')),
4515 4516 ('r', 'rev', '',
4516 4517 _('revision'), _('REV'))],
4517 4518 _('[-c] [-C] [-d DATE] [[-r] REV]')),
4518 4519 "verify": (verify, []),
4519 4520 "version": (version_, []),
4520 4521 }
4521 4522
4522 4523 norepo = ("clone init version help debugcommands debugcomplete"
4523 4524 " debugdate debuginstall debugfsinfo debugpushkey")
4524 4525 optionalrepo = ("identify paths serve showconfig debugancestor debugdag"
4525 4526 " debugdata debugindex debugindexdot")
@@ -1,105 +1,105 b''
1 1
2 2 $ commit()
3 3 > {
4 4 > msg=$1
5 5 > p1=$2
6 6 > p2=$3
7 7 >
8 8 > if [ "$p1" ]; then
9 9 > hg up -qC $p1
10 10 > fi
11 11 >
12 12 > if [ "$p2" ]; then
13 13 > HGMERGE=true hg merge -q $p2
14 14 > fi
15 15 >
16 16 > echo >> foo
17 17 >
18 18 > hg commit -qAm "$msg"
19 19 > }
20 20 $ hg init repo
21 21 $ cd repo
22 22 $ echo '[extensions]' > .hg/hgrc
23 23 $ echo 'parentrevspec =' >> .hg/hgrc
24 24 $ commit '0: add foo'
25 25 $ commit '1: change foo 1'
26 26 $ commit '2: change foo 2a'
27 27 $ commit '3: change foo 3a'
28 28 $ commit '4: change foo 2b' 1
29 29 $ commit '5: merge' 3 4
30 30 $ commit '6: change foo again'
31 31 $ hg log --template '{rev}:{node|short} {parents}\n'
32 32 6:755d1e0d79e9
33 33 5:9ce2ce29723a 3:a3e00c7dbf11 4:bb4475edb621
34 34 4:bb4475edb621 1:5d953a1917d1
35 35 3:a3e00c7dbf11
36 36 2:befc7d89d081
37 37 1:5d953a1917d1
38 38 0:837088b6e1d9
39 39 $ echo
40 40
41 41 $ lookup()
42 42 > {
43 43 > for rev in "$@"; do
44 44 > printf "$rev: "
45 45 > hg id -nr $rev
46 46 > done
47 47 > true
48 48 > }
49 49 $ tipnode=`hg id -ir tip`
50 50
51 51 should work with tag/branch/node/rev
52 52
53 53 $ for r in tip default $tipnode 6; do
54 54 > lookup "$r^"
55 55 > done
56 56 tip^: 5
57 57 default^: 5
58 58 755d1e0d79e9^: 5
59 59 6^: 5
60 60 $ echo
61 61
62 62
63 63 some random lookups
64 64
65 65 $ lookup "6^^" "6^^^" "6^^^^" "6^^^^^" "6^^^^^^" "6^1" "6^2" "6^^2" "6^1^2" "6^^3"
66 66 6^^: 3
67 67 6^^^: 2
68 68 6^^^^: 1
69 69 6^^^^^: 0
70 70 6^^^^^^: -1
71 71 6^1: 5
72 6^2: abort: unknown revision '6^2'!
72 6^2: hg: parse error at 1: syntax error
73 73 6^^2: 4
74 74 6^1^2: 4
75 6^^3: abort: unknown revision '6^^3'!
75 6^^3: hg: parse error at 1: syntax error
76 76 $ lookup "6~" "6~1" "6~2" "6~3" "6~4" "6~5" "6~42" "6~1^2" "6~1^2~2"
77 6~: abort: unknown revision '6~'!
77 6~: hg: parse error at 1: syntax error
78 78 6~1: 5
79 79 6~2: 3
80 80 6~3: 2
81 81 6~4: 1
82 82 6~5: 0
83 83 6~42: -1
84 84 6~1^2: 4
85 85 6~1^2~2: 0
86 86 $ echo
87 87
88 88
89 89 with a tag "6^" pointing to rev 1
90 90
91 91 $ hg tag -l -r 1 "6^"
92 92 $ lookup "6^" "6^1" "6~1" "6^^"
93 93 6^: 1
94 94 6^1: 5
95 95 6~1: 5
96 96 6^^: 3
97 97 $ echo
98 98
99 99
100 100 with a tag "foo^bar" pointing to rev 2
101 101
102 102 $ hg tag -l -r 2 "foo^bar"
103 103 $ lookup "foo^bar" "foo^bar^"
104 104 foo^bar: 2
105 foo^bar^: abort: unknown revision 'foo^bar^'!
105 foo^bar^: hg: parse error at 3: syntax error
General Comments 0
You need to be logged in to leave comments. Login now