##// END OF EJS Templates
speed up hg log --patch...
Alexis S. L. Carvalho -
r1803:06e7447c default
parent child Browse files
Show More
@@ -1,2910 +1,2916 b''
1 1 # commands.py - command processing for mercurial
2 2 #
3 3 # Copyright 2005 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms
6 6 # of the GNU General Public License, incorporated herein by reference.
7 7
8 8 from demandload import demandload
9 9 from node import *
10 10 from i18n import gettext as _
11 11 demandload(globals(), "os re sys signal shutil imp urllib pdb")
12 12 demandload(globals(), "fancyopts ui hg util lock revlog")
13 13 demandload(globals(), "fnmatch hgweb mdiff random signal time traceback")
14 14 demandload(globals(), "errno socket version struct atexit sets bz2")
15 15
16 16 class UnknownCommand(Exception):
17 17 """Exception raised if command is not in the command table."""
18 18 class AmbiguousCommand(Exception):
19 19 """Exception raised if command shortcut matches more than one command."""
20 20
21 21 def filterfiles(filters, files):
22 22 l = [x for x in files if x in filters]
23 23
24 24 for t in filters:
25 25 if t and t[-1] != "/":
26 26 t += "/"
27 27 l += [x for x in files if x.startswith(t)]
28 28 return l
29 29
30 30 def relpath(repo, args):
31 31 cwd = repo.getcwd()
32 32 if cwd:
33 33 return [util.normpath(os.path.join(cwd, x)) for x in args]
34 34 return args
35 35
36 36 def matchpats(repo, pats=[], opts={}, head=''):
37 37 cwd = repo.getcwd()
38 38 if not pats and cwd:
39 39 opts['include'] = [os.path.join(cwd, i) for i in opts['include']]
40 40 opts['exclude'] = [os.path.join(cwd, x) for x in opts['exclude']]
41 41 cwd = ''
42 42 return util.cmdmatcher(repo.root, cwd, pats or ['.'], opts.get('include'),
43 43 opts.get('exclude'), head)
44 44
45 45 def makewalk(repo, pats, opts, node=None, head=''):
46 46 files, matchfn, anypats = matchpats(repo, pats, opts, head)
47 47 exact = dict(zip(files, files))
48 48 def walk():
49 49 for src, fn in repo.walk(node=node, files=files, match=matchfn):
50 50 yield src, fn, util.pathto(repo.getcwd(), fn), fn in exact
51 51 return files, matchfn, walk()
52 52
53 53 def walk(repo, pats, opts, node=None, head=''):
54 54 files, matchfn, results = makewalk(repo, pats, opts, node, head)
55 55 for r in results:
56 56 yield r
57 57
58 58 def walkchangerevs(ui, repo, pats, opts):
59 59 '''Iterate over files and the revs they changed in.
60 60
61 61 Callers most commonly need to iterate backwards over the history
62 62 it is interested in. Doing so has awful (quadratic-looking)
63 63 performance, so we use iterators in a "windowed" way.
64 64
65 65 We walk a window of revisions in the desired order. Within the
66 66 window, we first walk forwards to gather data, then in the desired
67 67 order (usually backwards) to display it.
68 68
69 69 This function returns an (iterator, getchange, matchfn) tuple. The
70 70 getchange function returns the changelog entry for a numeric
71 71 revision. The iterator yields 3-tuples. They will be of one of
72 72 the following forms:
73 73
74 74 "window", incrementing, lastrev: stepping through a window,
75 75 positive if walking forwards through revs, last rev in the
76 76 sequence iterated over - use to reset state for the current window
77 77
78 78 "add", rev, fns: out-of-order traversal of the given file names
79 79 fns, which changed during revision rev - use to gather data for
80 80 possible display
81 81
82 82 "iter", rev, None: in-order traversal of the revs earlier iterated
83 83 over with "add" - use to display data'''
84 84
85 85 def increasing_windows(start, end, windowsize=8, sizelimit=512):
86 86 if start < end:
87 87 while start < end:
88 88 yield start, min(windowsize, end-start)
89 89 start += windowsize
90 90 if windowsize < sizelimit:
91 91 windowsize *= 2
92 92 else:
93 93 while start > end:
94 94 yield start, min(windowsize, start-end-1)
95 95 start -= windowsize
96 96 if windowsize < sizelimit:
97 97 windowsize *= 2
98 98
99 99
100 100 files, matchfn, anypats = matchpats(repo, pats, opts)
101 101
102 102 if repo.changelog.count() == 0:
103 103 return [], False, matchfn
104 104
105 105 revs = map(int, revrange(ui, repo, opts['rev'] or ['tip:0']))
106 106 wanted = {}
107 107 slowpath = anypats
108 108 fncache = {}
109 109
110 110 chcache = {}
111 111 def getchange(rev):
112 112 ch = chcache.get(rev)
113 113 if ch is None:
114 114 chcache[rev] = ch = repo.changelog.read(repo.lookup(str(rev)))
115 115 return ch
116 116
117 117 if not slowpath and not files:
118 118 # No files, no patterns. Display all revs.
119 119 wanted = dict(zip(revs, revs))
120 120 if not slowpath:
121 121 # Only files, no patterns. Check the history of each file.
122 122 def filerevgen(filelog):
123 123 for i, window in increasing_windows(filelog.count()-1, -1):
124 124 revs = []
125 125 for j in xrange(i - window, i + 1):
126 126 revs.append(filelog.linkrev(filelog.node(j)))
127 127 revs.reverse()
128 128 for rev in revs:
129 129 yield rev
130 130
131 131 minrev, maxrev = min(revs), max(revs)
132 132 for file_ in files:
133 133 filelog = repo.file(file_)
134 134 # A zero count may be a directory or deleted file, so
135 135 # try to find matching entries on the slow path.
136 136 if filelog.count() == 0:
137 137 slowpath = True
138 138 break
139 139 for rev in filerevgen(filelog):
140 140 if rev <= maxrev:
141 141 if rev < minrev:
142 142 break
143 143 fncache.setdefault(rev, [])
144 144 fncache[rev].append(file_)
145 145 wanted[rev] = 1
146 146 if slowpath:
147 147 # The slow path checks files modified in every changeset.
148 148 def changerevgen():
149 149 for i, window in increasing_windows(repo.changelog.count()-1, -1):
150 150 for j in xrange(i - window, i + 1):
151 151 yield j, getchange(j)[3]
152 152
153 153 for rev, changefiles in changerevgen():
154 154 matches = filter(matchfn, changefiles)
155 155 if matches:
156 156 fncache[rev] = matches
157 157 wanted[rev] = 1
158 158
159 159 def iterate():
160 160 for i, window in increasing_windows(0, len(revs)):
161 161 yield 'window', revs[0] < revs[-1], revs[-1]
162 162 nrevs = [rev for rev in revs[i:i+window]
163 163 if rev in wanted]
164 164 srevs = list(nrevs)
165 165 srevs.sort()
166 166 for rev in srevs:
167 167 fns = fncache.get(rev) or filter(matchfn, getchange(rev)[3])
168 168 yield 'add', rev, fns
169 169 for rev in nrevs:
170 170 yield 'iter', rev, None
171 171 return iterate(), getchange, matchfn
172 172
173 173 revrangesep = ':'
174 174
175 175 def revrange(ui, repo, revs, revlog=None):
176 176 """Yield revision as strings from a list of revision specifications."""
177 177 if revlog is None:
178 178 revlog = repo.changelog
179 179 revcount = revlog.count()
180 180 def fix(val, defval):
181 181 if not val:
182 182 return defval
183 183 try:
184 184 num = int(val)
185 185 if str(num) != val:
186 186 raise ValueError
187 187 if num < 0:
188 188 num += revcount
189 189 if num < 0:
190 190 num = 0
191 191 elif num >= revcount:
192 192 raise ValueError
193 193 except ValueError:
194 194 try:
195 195 num = repo.changelog.rev(repo.lookup(val))
196 196 except KeyError:
197 197 try:
198 198 num = revlog.rev(revlog.lookup(val))
199 199 except KeyError:
200 200 raise util.Abort(_('invalid revision identifier %s'), val)
201 201 return num
202 202 seen = {}
203 203 for spec in revs:
204 204 if spec.find(revrangesep) >= 0:
205 205 start, end = spec.split(revrangesep, 1)
206 206 start = fix(start, 0)
207 207 end = fix(end, revcount - 1)
208 208 step = start > end and -1 or 1
209 209 for rev in xrange(start, end+step, step):
210 210 if rev in seen:
211 211 continue
212 212 seen[rev] = 1
213 213 yield str(rev)
214 214 else:
215 215 rev = fix(spec, None)
216 216 if rev in seen:
217 217 continue
218 218 seen[rev] = 1
219 219 yield str(rev)
220 220
221 221 def make_filename(repo, r, pat, node=None,
222 222 total=None, seqno=None, revwidth=None, pathname=None):
223 223 node_expander = {
224 224 'H': lambda: hex(node),
225 225 'R': lambda: str(r.rev(node)),
226 226 'h': lambda: short(node),
227 227 }
228 228 expander = {
229 229 '%': lambda: '%',
230 230 'b': lambda: os.path.basename(repo.root),
231 231 }
232 232
233 233 try:
234 234 if node:
235 235 expander.update(node_expander)
236 236 if node and revwidth is not None:
237 237 expander['r'] = lambda: str(r.rev(node)).zfill(revwidth)
238 238 if total is not None:
239 239 expander['N'] = lambda: str(total)
240 240 if seqno is not None:
241 241 expander['n'] = lambda: str(seqno)
242 242 if total is not None and seqno is not None:
243 243 expander['n'] = lambda:str(seqno).zfill(len(str(total)))
244 244 if pathname is not None:
245 245 expander['s'] = lambda: os.path.basename(pathname)
246 246 expander['d'] = lambda: os.path.dirname(pathname) or '.'
247 247 expander['p'] = lambda: pathname
248 248
249 249 newname = []
250 250 patlen = len(pat)
251 251 i = 0
252 252 while i < patlen:
253 253 c = pat[i]
254 254 if c == '%':
255 255 i += 1
256 256 c = pat[i]
257 257 c = expander[c]()
258 258 newname.append(c)
259 259 i += 1
260 260 return ''.join(newname)
261 261 except KeyError, inst:
262 262 raise util.Abort(_("invalid format spec '%%%s' in output file name"),
263 263 inst.args[0])
264 264
265 265 def make_file(repo, r, pat, node=None,
266 266 total=None, seqno=None, revwidth=None, mode='wb', pathname=None):
267 267 if not pat or pat == '-':
268 268 return 'w' in mode and sys.stdout or sys.stdin
269 269 if hasattr(pat, 'write') and 'w' in mode:
270 270 return pat
271 271 if hasattr(pat, 'read') and 'r' in mode:
272 272 return pat
273 273 return open(make_filename(repo, r, pat, node, total, seqno, revwidth,
274 274 pathname),
275 275 mode)
276 276
277 277 def dodiff(fp, ui, repo, node1, node2, files=None, match=util.always,
278 278 changes=None, text=False, opts={}):
279 if node1:
280 # reading the data for node1 early allows it to play nicely
281 # with repo.changes and the revlog cache.
282 change = repo.changelog.read(node1)
283 mmap = repo.manifest.read(change[0])
284 date1 = util.datestr(change[2])
285
279 286 if not changes:
280 287 changes = repo.changes(node1, node2, files, match=match)
281 288 modified, added, removed, deleted, unknown = changes
282 289 if files:
283 290 modified, added, removed = map(lambda x: filterfiles(files, x),
284 291 (modified, added, removed))
285 292
286 293 if not modified and not added and not removed:
287 294 return
288 295
289 296 if node2:
290 297 change = repo.changelog.read(node2)
291 298 mmap2 = repo.manifest.read(change[0])
292 299 date2 = util.datestr(change[2])
293 300 def read(f):
294 301 return repo.file(f).read(mmap2[f])
295 302 else:
296 303 date2 = util.datestr()
297 304 if not node1:
298 305 node1 = repo.dirstate.parents()[0]
306 change = repo.changelog.read(node1)
307 mmap = repo.manifest.read(change[0])
308 date1 = util.datestr(change[2])
299 309 def read(f):
300 310 return repo.wread(f)
301 311
302 312 if ui.quiet:
303 313 r = None
304 314 else:
305 315 hexfunc = ui.verbose and hex or short
306 316 r = [hexfunc(node) for node in [node1, node2] if node]
307 317
308 change = repo.changelog.read(node1)
309 mmap = repo.manifest.read(change[0])
310 date1 = util.datestr(change[2])
311
312 318 diffopts = ui.diffopts()
313 319 showfunc = opts.get('show_function') or diffopts['showfunc']
314 320 ignorews = opts.get('ignore_all_space') or diffopts['ignorews']
315 321 for f in modified:
316 322 to = None
317 323 if f in mmap:
318 324 to = repo.file(f).read(mmap[f])
319 325 tn = read(f)
320 326 fp.write(mdiff.unidiff(to, date1, tn, date2, f, r, text=text,
321 327 showfunc=showfunc, ignorews=ignorews))
322 328 for f in added:
323 329 to = None
324 330 tn = read(f)
325 331 fp.write(mdiff.unidiff(to, date1, tn, date2, f, r, text=text,
326 332 showfunc=showfunc, ignorews=ignorews))
327 333 for f in removed:
328 334 to = repo.file(f).read(mmap[f])
329 335 tn = None
330 336 fp.write(mdiff.unidiff(to, date1, tn, date2, f, r, text=text,
331 337 showfunc=showfunc, ignorews=ignorews))
332 338
333 339 def trimuser(ui, name, rev, revcache):
334 340 """trim the name of the user who committed a change"""
335 341 user = revcache.get(rev)
336 342 if user is None:
337 343 user = revcache[rev] = ui.shortuser(name)
338 344 return user
339 345
340 346 def show_changeset(ui, repo, rev=0, changenode=None, brinfo=None):
341 347 """show a single changeset or file revision"""
342 348 log = repo.changelog
343 349 if changenode is None:
344 350 changenode = log.node(rev)
345 351 elif not rev:
346 352 rev = log.rev(changenode)
347 353
348 354 if ui.quiet:
349 355 ui.write("%d:%s\n" % (rev, short(changenode)))
350 356 return
351 357
352 358 changes = log.read(changenode)
353 359 date = util.datestr(changes[2])
354 360
355 361 parents = [(log.rev(p), ui.verbose and hex(p) or short(p))
356 362 for p in log.parents(changenode)
357 363 if ui.debugflag or p != nullid]
358 364 if not ui.debugflag and len(parents) == 1 and parents[0][0] == rev-1:
359 365 parents = []
360 366
361 367 if ui.verbose:
362 368 ui.write(_("changeset: %d:%s\n") % (rev, hex(changenode)))
363 369 else:
364 370 ui.write(_("changeset: %d:%s\n") % (rev, short(changenode)))
365 371
366 372 for tag in repo.nodetags(changenode):
367 373 ui.status(_("tag: %s\n") % tag)
368 374 for parent in parents:
369 375 ui.write(_("parent: %d:%s\n") % parent)
370 376
371 377 if brinfo and changenode in brinfo:
372 378 br = brinfo[changenode]
373 379 ui.write(_("branch: %s\n") % " ".join(br))
374 380
375 381 ui.debug(_("manifest: %d:%s\n") % (repo.manifest.rev(changes[0]),
376 382 hex(changes[0])))
377 383 ui.status(_("user: %s\n") % changes[1])
378 384 ui.status(_("date: %s\n") % date)
379 385
380 386 if ui.debugflag:
381 387 files = repo.changes(log.parents(changenode)[0], changenode)
382 388 for key, value in zip([_("files:"), _("files+:"), _("files-:")], files):
383 389 if value:
384 390 ui.note("%-12s %s\n" % (key, " ".join(value)))
385 391 else:
386 392 ui.note(_("files: %s\n") % " ".join(changes[3]))
387 393
388 394 description = changes[4].strip()
389 395 if description:
390 396 if ui.verbose:
391 397 ui.status(_("description:\n"))
392 398 ui.status(description)
393 399 ui.status("\n\n")
394 400 else:
395 401 ui.status(_("summary: %s\n") % description.splitlines()[0])
396 402 ui.status("\n")
397 403
398 404 def show_version(ui):
399 405 """output version and copyright information"""
400 406 ui.write(_("Mercurial Distributed SCM (version %s)\n")
401 407 % version.get_version())
402 408 ui.status(_(
403 409 "\nCopyright (C) 2005 Matt Mackall <mpm@selenic.com>\n"
404 410 "This is free software; see the source for copying conditions. "
405 411 "There is NO\nwarranty; "
406 412 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
407 413 ))
408 414
409 415 def help_(ui, cmd=None, with_version=False):
410 416 """show help for a given command or all commands"""
411 417 option_lists = []
412 418 if cmd and cmd != 'shortlist':
413 419 if with_version:
414 420 show_version(ui)
415 421 ui.write('\n')
416 422 aliases, i = find(cmd)
417 423 # synopsis
418 424 ui.write("%s\n\n" % i[2])
419 425
420 426 # description
421 427 doc = i[0].__doc__
422 428 if not doc:
423 429 doc = _("(No help text available)")
424 430 if ui.quiet:
425 431 doc = doc.splitlines(0)[0]
426 432 ui.write("%s\n" % doc.rstrip())
427 433
428 434 if not ui.quiet:
429 435 # aliases
430 436 if len(aliases) > 1:
431 437 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
432 438
433 439 # options
434 440 if i[1]:
435 441 option_lists.append(("options", i[1]))
436 442
437 443 else:
438 444 # program name
439 445 if ui.verbose or with_version:
440 446 show_version(ui)
441 447 else:
442 448 ui.status(_("Mercurial Distributed SCM\n"))
443 449 ui.status('\n')
444 450
445 451 # list of commands
446 452 if cmd == "shortlist":
447 453 ui.status(_('basic commands (use "hg help" '
448 454 'for the full list or option "-v" for details):\n\n'))
449 455 elif ui.verbose:
450 456 ui.status(_('list of commands:\n\n'))
451 457 else:
452 458 ui.status(_('list of commands (use "hg help -v" '
453 459 'to show aliases and global options):\n\n'))
454 460
455 461 h = {}
456 462 cmds = {}
457 463 for c, e in table.items():
458 464 f = c.split("|")[0]
459 465 if cmd == "shortlist" and not f.startswith("^"):
460 466 continue
461 467 f = f.lstrip("^")
462 468 if not ui.debugflag and f.startswith("debug"):
463 469 continue
464 470 doc = e[0].__doc__
465 471 if not doc:
466 472 doc = _("(No help text available)")
467 473 h[f] = doc.splitlines(0)[0].rstrip()
468 474 cmds[f] = c.lstrip("^")
469 475
470 476 fns = h.keys()
471 477 fns.sort()
472 478 m = max(map(len, fns))
473 479 for f in fns:
474 480 if ui.verbose:
475 481 commands = cmds[f].replace("|",", ")
476 482 ui.write(" %s:\n %s\n"%(commands, h[f]))
477 483 else:
478 484 ui.write(' %-*s %s\n' % (m, f, h[f]))
479 485
480 486 # global options
481 487 if ui.verbose:
482 488 option_lists.append(("global options", globalopts))
483 489
484 490 # list all option lists
485 491 opt_output = []
486 492 for title, options in option_lists:
487 493 opt_output.append(("\n%s:\n" % title, None))
488 494 for shortopt, longopt, default, desc in options:
489 495 opt_output.append(("%2s%s" % (shortopt and "-%s" % shortopt,
490 496 longopt and " --%s" % longopt),
491 497 "%s%s" % (desc,
492 498 default
493 499 and _(" (default: %s)") % default
494 500 or "")))
495 501
496 502 if opt_output:
497 503 opts_len = max([len(line[0]) for line in opt_output if line[1]])
498 504 for first, second in opt_output:
499 505 if second:
500 506 ui.write(" %-*s %s\n" % (opts_len, first, second))
501 507 else:
502 508 ui.write("%s\n" % first)
503 509
504 510 # Commands start here, listed alphabetically
505 511
506 512 def add(ui, repo, *pats, **opts):
507 513 """add the specified files on the next commit
508 514
509 515 Schedule files to be version controlled and added to the repository.
510 516
511 517 The files will be added to the repository at the next commit.
512 518
513 519 If no names are given, add all files in the repository.
514 520 """
515 521
516 522 names = []
517 523 for src, abs, rel, exact in walk(repo, pats, opts):
518 524 if exact:
519 525 if ui.verbose:
520 526 ui.status(_('adding %s\n') % rel)
521 527 names.append(abs)
522 528 elif repo.dirstate.state(abs) == '?':
523 529 ui.status(_('adding %s\n') % rel)
524 530 names.append(abs)
525 531 repo.add(names)
526 532
527 533 def addremove(ui, repo, *pats, **opts):
528 534 """add all new files, delete all missing files
529 535
530 536 Add all new files and remove all missing files from the repository.
531 537
532 538 New files are ignored if they match any of the patterns in .hgignore. As
533 539 with add, these changes take effect at the next commit.
534 540 """
535 541 return addremove_lock(ui, repo, pats, opts)
536 542
537 543 def addremove_lock(ui, repo, pats, opts, wlock=None):
538 544 add, remove = [], []
539 545 for src, abs, rel, exact in walk(repo, pats, opts):
540 546 if src == 'f' and repo.dirstate.state(abs) == '?':
541 547 add.append(abs)
542 548 if ui.verbose or not exact:
543 549 ui.status(_('adding %s\n') % ((pats and rel) or abs))
544 550 if repo.dirstate.state(abs) != 'r' and not os.path.exists(rel):
545 551 remove.append(abs)
546 552 if ui.verbose or not exact:
547 553 ui.status(_('removing %s\n') % ((pats and rel) or abs))
548 554 repo.add(add, wlock=wlock)
549 555 repo.remove(remove, wlock=wlock)
550 556
551 557 def annotate(ui, repo, *pats, **opts):
552 558 """show changeset information per file line
553 559
554 560 List changes in files, showing the revision id responsible for each line
555 561
556 562 This command is useful to discover who did a change or when a change took
557 563 place.
558 564
559 565 Without the -a option, annotate will avoid processing files it
560 566 detects as binary. With -a, annotate will generate an annotation
561 567 anyway, probably with undesirable results.
562 568 """
563 569 def getnode(rev):
564 570 return short(repo.changelog.node(rev))
565 571
566 572 ucache = {}
567 573 def getname(rev):
568 574 cl = repo.changelog.read(repo.changelog.node(rev))
569 575 return trimuser(ui, cl[1], rev, ucache)
570 576
571 577 dcache = {}
572 578 def getdate(rev):
573 579 datestr = dcache.get(rev)
574 580 if datestr is None:
575 581 cl = repo.changelog.read(repo.changelog.node(rev))
576 582 datestr = dcache[rev] = util.datestr(cl[2])
577 583 return datestr
578 584
579 585 if not pats:
580 586 raise util.Abort(_('at least one file name or pattern required'))
581 587
582 588 opmap = [['user', getname], ['number', str], ['changeset', getnode],
583 589 ['date', getdate]]
584 590 if not opts['user'] and not opts['changeset'] and not opts['date']:
585 591 opts['number'] = 1
586 592
587 593 if opts['rev']:
588 594 node = repo.changelog.lookup(opts['rev'])
589 595 else:
590 596 node = repo.dirstate.parents()[0]
591 597 change = repo.changelog.read(node)
592 598 mmap = repo.manifest.read(change[0])
593 599
594 600 for src, abs, rel, exact in walk(repo, pats, opts):
595 601 if abs not in mmap:
596 602 ui.warn(_("warning: %s is not in the repository!\n") %
597 603 ((pats and rel) or abs))
598 604 continue
599 605
600 606 f = repo.file(abs)
601 607 if not opts['text'] and util.binary(f.read(mmap[abs])):
602 608 ui.write(_("%s: binary file\n") % ((pats and rel) or abs))
603 609 continue
604 610
605 611 lines = f.annotate(mmap[abs])
606 612 pieces = []
607 613
608 614 for o, f in opmap:
609 615 if opts[o]:
610 616 l = [f(n) for n, dummy in lines]
611 617 if l:
612 618 m = max(map(len, l))
613 619 pieces.append(["%*s" % (m, x) for x in l])
614 620
615 621 if pieces:
616 622 for p, l in zip(zip(*pieces), lines):
617 623 ui.write("%s: %s" % (" ".join(p), l[1]))
618 624
619 625 def bundle(ui, repo, fname, dest="default-push", **opts):
620 626 """create a changegroup file
621 627
622 628 Generate a compressed changegroup file collecting all changesets
623 629 not found in the other repository.
624 630
625 631 This file can then be transferred using conventional means and
626 632 applied to another repository with the unbundle command. This is
627 633 useful when native push and pull are not available or when
628 634 exporting an entire repository is undesirable. The standard file
629 635 extension is ".hg".
630 636
631 637 Unlike import/export, this exactly preserves all changeset
632 638 contents including permissions, rename data, and revision history.
633 639 """
634 640 f = open(fname, "wb")
635 641 dest = ui.expandpath(dest, repo.root)
636 642 other = hg.repository(ui, dest)
637 643 o = repo.findoutgoing(other)
638 644 cg = repo.changegroup(o, 'bundle')
639 645
640 646 try:
641 647 f.write("HG10")
642 648 z = bz2.BZ2Compressor(9)
643 649 while 1:
644 650 chunk = cg.read(4096)
645 651 if not chunk:
646 652 break
647 653 f.write(z.compress(chunk))
648 654 f.write(z.flush())
649 655 except:
650 656 os.unlink(fname)
651 657 raise
652 658
653 659 def cat(ui, repo, file1, *pats, **opts):
654 660 """output the latest or given revisions of files
655 661
656 662 Print the specified files as they were at the given revision.
657 663 If no revision is given then the tip is used.
658 664
659 665 Output may be to a file, in which case the name of the file is
660 666 given using a format string. The formatting rules are the same as
661 667 for the export command, with the following additions:
662 668
663 669 %s basename of file being printed
664 670 %d dirname of file being printed, or '.' if in repo root
665 671 %p root-relative path name of file being printed
666 672 """
667 673 mf = {}
668 674 rev = opts['rev']
669 675 if rev:
670 676 node = repo.lookup(rev)
671 677 else:
672 678 node = repo.changelog.tip()
673 679 change = repo.changelog.read(node)
674 680 mf = repo.manifest.read(change[0])
675 681 for src, abs, rel, exact in walk(repo, (file1,) + pats, opts, node):
676 682 r = repo.file(abs)
677 683 n = mf[abs]
678 684 fp = make_file(repo, r, opts['output'], node=n, pathname=abs)
679 685 fp.write(r.read(n))
680 686
681 687 def clone(ui, source, dest=None, **opts):
682 688 """make a copy of an existing repository
683 689
684 690 Create a copy of an existing repository in a new directory.
685 691
686 692 If no destination directory name is specified, it defaults to the
687 693 basename of the source.
688 694
689 695 The location of the source is added to the new repository's
690 696 .hg/hgrc file, as the default to be used for future pulls.
691 697
692 698 For efficiency, hardlinks are used for cloning whenever the source
693 699 and destination are on the same filesystem. Some filesystems,
694 700 such as AFS, implement hardlinking incorrectly, but do not report
695 701 errors. In these cases, use the --pull option to avoid
696 702 hardlinking.
697 703 """
698 704 if dest is None:
699 705 dest = os.path.basename(os.path.normpath(source))
700 706
701 707 if os.path.exists(dest):
702 708 raise util.Abort(_("destination '%s' already exists"), dest)
703 709
704 710 dest = os.path.realpath(dest)
705 711
706 712 class Dircleanup(object):
707 713 def __init__(self, dir_):
708 714 self.rmtree = shutil.rmtree
709 715 self.dir_ = dir_
710 716 os.mkdir(dir_)
711 717 def close(self):
712 718 self.dir_ = None
713 719 def __del__(self):
714 720 if self.dir_:
715 721 self.rmtree(self.dir_, True)
716 722
717 723 if opts['ssh']:
718 724 ui.setconfig("ui", "ssh", opts['ssh'])
719 725 if opts['remotecmd']:
720 726 ui.setconfig("ui", "remotecmd", opts['remotecmd'])
721 727
722 728 if not os.path.exists(source):
723 729 source = ui.expandpath(source)
724 730
725 731 d = Dircleanup(dest)
726 732 abspath = source
727 733 other = hg.repository(ui, source)
728 734
729 735 copy = False
730 736 if other.dev() != -1:
731 737 abspath = os.path.abspath(source)
732 738 if not opts['pull'] and not opts['rev']:
733 739 copy = True
734 740
735 741 if copy:
736 742 try:
737 743 # we use a lock here because if we race with commit, we
738 744 # can end up with extra data in the cloned revlogs that's
739 745 # not pointed to by changesets, thus causing verify to
740 746 # fail
741 747 l1 = other.lock()
742 748 except lock.LockException:
743 749 copy = False
744 750
745 751 if copy:
746 752 # we lock here to avoid premature writing to the target
747 753 os.mkdir(os.path.join(dest, ".hg"))
748 754 l2 = lock.lock(os.path.join(dest, ".hg", "lock"))
749 755
750 756 files = "data 00manifest.d 00manifest.i 00changelog.d 00changelog.i"
751 757 for f in files.split():
752 758 src = os.path.join(source, ".hg", f)
753 759 dst = os.path.join(dest, ".hg", f)
754 760 try:
755 761 util.copyfiles(src, dst)
756 762 except OSError, inst:
757 763 if inst.errno != errno.ENOENT:
758 764 raise
759 765
760 766 repo = hg.repository(ui, dest)
761 767
762 768 else:
763 769 revs = None
764 770 if opts['rev']:
765 771 if not other.local():
766 772 error = _("clone -r not supported yet for remote repositories.")
767 773 raise util.Abort(error)
768 774 else:
769 775 revs = [other.lookup(rev) for rev in opts['rev']]
770 776 repo = hg.repository(ui, dest, create=1)
771 777 repo.pull(other, heads = revs)
772 778
773 779 f = repo.opener("hgrc", "w", text=True)
774 780 f.write("[paths]\n")
775 781 f.write("default = %s\n" % abspath)
776 782 f.close()
777 783
778 784 if not opts['noupdate']:
779 785 update(ui, repo)
780 786
781 787 d.close()
782 788
783 789 def commit(ui, repo, *pats, **opts):
784 790 """commit the specified files or all outstanding changes
785 791
786 792 Commit changes to the given files into the repository.
787 793
788 794 If a list of files is omitted, all changes reported by "hg status"
789 795 will be commited.
790 796
791 797 The HGEDITOR or EDITOR environment variables are used to start an
792 798 editor to add a commit comment.
793 799 """
794 800 message = opts['message']
795 801 logfile = opts['logfile']
796 802
797 803 if message and logfile:
798 804 raise util.Abort(_('options --message and --logfile are mutually '
799 805 'exclusive'))
800 806 if not message and logfile:
801 807 try:
802 808 if logfile == '-':
803 809 message = sys.stdin.read()
804 810 else:
805 811 message = open(logfile).read()
806 812 except IOError, inst:
807 813 raise util.Abort(_("can't read commit message '%s': %s") %
808 814 (logfile, inst.strerror))
809 815
810 816 if opts['addremove']:
811 817 addremove(ui, repo, *pats, **opts)
812 818 fns, match, anypats = matchpats(repo, pats, opts)
813 819 if pats:
814 820 modified, added, removed, deleted, unknown = (
815 821 repo.changes(files=fns, match=match))
816 822 files = modified + added + removed
817 823 else:
818 824 files = []
819 825 try:
820 826 repo.commit(files, message, opts['user'], opts['date'], match)
821 827 except ValueError, inst:
822 828 raise util.Abort(str(inst))
823 829
824 830 def docopy(ui, repo, pats, opts):
825 831 cwd = repo.getcwd()
826 832 errors = 0
827 833 copied = []
828 834 targets = {}
829 835
830 836 def okaytocopy(abs, rel, exact):
831 837 reasons = {'?': _('is not managed'),
832 838 'a': _('has been marked for add'),
833 839 'r': _('has been marked for remove')}
834 840 state = repo.dirstate.state(abs)
835 841 reason = reasons.get(state)
836 842 if reason:
837 843 if state == 'a':
838 844 origsrc = repo.dirstate.copied(abs)
839 845 if origsrc is not None:
840 846 return origsrc
841 847 if exact:
842 848 ui.warn(_('%s: not copying - file %s\n') % (rel, reason))
843 849 else:
844 850 return abs
845 851
846 852 def copy(origsrc, abssrc, relsrc, target, exact):
847 853 abstarget = util.canonpath(repo.root, cwd, target)
848 854 reltarget = util.pathto(cwd, abstarget)
849 855 prevsrc = targets.get(abstarget)
850 856 if prevsrc is not None:
851 857 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
852 858 (reltarget, abssrc, prevsrc))
853 859 return
854 860 if (not opts['after'] and os.path.exists(reltarget) or
855 861 opts['after'] and repo.dirstate.state(abstarget) not in '?r'):
856 862 if not opts['force']:
857 863 ui.warn(_('%s: not overwriting - file exists\n') %
858 864 reltarget)
859 865 return
860 866 if not opts['after']:
861 867 os.unlink(reltarget)
862 868 if opts['after']:
863 869 if not os.path.exists(reltarget):
864 870 return
865 871 else:
866 872 targetdir = os.path.dirname(reltarget) or '.'
867 873 if not os.path.isdir(targetdir):
868 874 os.makedirs(targetdir)
869 875 try:
870 876 shutil.copyfile(relsrc, reltarget)
871 877 shutil.copymode(relsrc, reltarget)
872 878 except shutil.Error, inst:
873 879 raise util.Abort(str(inst))
874 880 except IOError, inst:
875 881 if inst.errno == errno.ENOENT:
876 882 ui.warn(_('%s: deleted in working copy\n') % relsrc)
877 883 else:
878 884 ui.warn(_('%s: cannot copy - %s\n') %
879 885 (relsrc, inst.strerror))
880 886 errors += 1
881 887 return
882 888 if ui.verbose or not exact:
883 889 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
884 890 targets[abstarget] = abssrc
885 891 repo.copy(origsrc, abstarget)
886 892 copied.append((abssrc, relsrc, exact))
887 893
888 894 def targetpathfn(pat, dest, srcs):
889 895 if os.path.isdir(pat):
890 896 abspfx = util.canonpath(repo.root, cwd, pat)
891 897 if destdirexists:
892 898 striplen = len(os.path.split(abspfx)[0])
893 899 else:
894 900 striplen = len(abspfx)
895 901 if striplen:
896 902 striplen += len(os.sep)
897 903 res = lambda p: os.path.join(dest, p[striplen:])
898 904 elif destdirexists:
899 905 res = lambda p: os.path.join(dest, os.path.basename(p))
900 906 else:
901 907 res = lambda p: dest
902 908 return res
903 909
904 910 def targetpathafterfn(pat, dest, srcs):
905 911 if util.patkind(pat, None)[0]:
906 912 # a mercurial pattern
907 913 res = lambda p: os.path.join(dest, os.path.basename(p))
908 914 else:
909 915 abspfx = util.canonpath(repo.root, cwd, pat)
910 916 if len(abspfx) < len(srcs[0][0]):
911 917 # A directory. Either the target path contains the last
912 918 # component of the source path or it does not.
913 919 def evalpath(striplen):
914 920 score = 0
915 921 for s in srcs:
916 922 t = os.path.join(dest, s[0][striplen:])
917 923 if os.path.exists(t):
918 924 score += 1
919 925 return score
920 926
921 927 striplen = len(abspfx)
922 928 if striplen:
923 929 striplen += len(os.sep)
924 930 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
925 931 score = evalpath(striplen)
926 932 striplen1 = len(os.path.split(abspfx)[0])
927 933 if striplen1:
928 934 striplen1 += len(os.sep)
929 935 if evalpath(striplen1) > score:
930 936 striplen = striplen1
931 937 res = lambda p: os.path.join(dest, p[striplen:])
932 938 else:
933 939 # a file
934 940 if destdirexists:
935 941 res = lambda p: os.path.join(dest, os.path.basename(p))
936 942 else:
937 943 res = lambda p: dest
938 944 return res
939 945
940 946
941 947 pats = list(pats)
942 948 if not pats:
943 949 raise util.Abort(_('no source or destination specified'))
944 950 if len(pats) == 1:
945 951 raise util.Abort(_('no destination specified'))
946 952 dest = pats.pop()
947 953 destdirexists = os.path.isdir(dest)
948 954 if (len(pats) > 1 or util.patkind(pats[0], None)[0]) and not destdirexists:
949 955 raise util.Abort(_('with multiple sources, destination must be an '
950 956 'existing directory'))
951 957 if opts['after']:
952 958 tfn = targetpathafterfn
953 959 else:
954 960 tfn = targetpathfn
955 961 copylist = []
956 962 for pat in pats:
957 963 srcs = []
958 964 for tag, abssrc, relsrc, exact in walk(repo, [pat], opts):
959 965 origsrc = okaytocopy(abssrc, relsrc, exact)
960 966 if origsrc:
961 967 srcs.append((origsrc, abssrc, relsrc, exact))
962 968 if not srcs:
963 969 continue
964 970 copylist.append((tfn(pat, dest, srcs), srcs))
965 971 if not copylist:
966 972 raise util.Abort(_('no files to copy'))
967 973
968 974 for targetpath, srcs in copylist:
969 975 for origsrc, abssrc, relsrc, exact in srcs:
970 976 copy(origsrc, abssrc, relsrc, targetpath(abssrc), exact)
971 977
972 978 if errors:
973 979 ui.warn(_('(consider using --after)\n'))
974 980 return errors, copied
975 981
976 982 def copy(ui, repo, *pats, **opts):
977 983 """mark files as copied for the next commit
978 984
979 985 Mark dest as having copies of source files. If dest is a
980 986 directory, copies are put in that directory. If dest is a file,
981 987 there can only be one source.
982 988
983 989 By default, this command copies the contents of files as they
984 990 stand in the working directory. If invoked with --after, the
985 991 operation is recorded, but no copying is performed.
986 992
987 993 This command takes effect in the next commit.
988 994
989 995 NOTE: This command should be treated as experimental. While it
990 996 should properly record copied files, this information is not yet
991 997 fully used by merge, nor fully reported by log.
992 998 """
993 999 errs, copied = docopy(ui, repo, pats, opts)
994 1000 return errs
995 1001
996 1002 def debugancestor(ui, index, rev1, rev2):
997 1003 """find the ancestor revision of two revisions in a given index"""
998 1004 r = revlog.revlog(util.opener(os.getcwd()), index, "")
999 1005 a = r.ancestor(r.lookup(rev1), r.lookup(rev2))
1000 1006 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1001 1007
1002 1008 def debugrebuildstate(ui, repo, rev=None):
1003 1009 """rebuild the dirstate as it would look like for the given revision"""
1004 1010 if not rev:
1005 1011 rev = repo.changelog.tip()
1006 1012 else:
1007 1013 rev = repo.lookup(rev)
1008 1014 change = repo.changelog.read(rev)
1009 1015 n = change[0]
1010 1016 files = repo.manifest.readflags(n)
1011 1017 wlock = repo.wlock()
1012 1018 repo.dirstate.rebuild(rev, files.iteritems())
1013 1019
1014 1020 def debugcheckstate(ui, repo):
1015 1021 """validate the correctness of the current dirstate"""
1016 1022 parent1, parent2 = repo.dirstate.parents()
1017 1023 repo.dirstate.read()
1018 1024 dc = repo.dirstate.map
1019 1025 keys = dc.keys()
1020 1026 keys.sort()
1021 1027 m1n = repo.changelog.read(parent1)[0]
1022 1028 m2n = repo.changelog.read(parent2)[0]
1023 1029 m1 = repo.manifest.read(m1n)
1024 1030 m2 = repo.manifest.read(m2n)
1025 1031 errors = 0
1026 1032 for f in dc:
1027 1033 state = repo.dirstate.state(f)
1028 1034 if state in "nr" and f not in m1:
1029 1035 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1030 1036 errors += 1
1031 1037 if state in "a" and f in m1:
1032 1038 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1033 1039 errors += 1
1034 1040 if state in "m" and f not in m1 and f not in m2:
1035 1041 ui.warn(_("%s in state %s, but not in either manifest\n") %
1036 1042 (f, state))
1037 1043 errors += 1
1038 1044 for f in m1:
1039 1045 state = repo.dirstate.state(f)
1040 1046 if state not in "nrm":
1041 1047 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1042 1048 errors += 1
1043 1049 if errors:
1044 1050 error = _(".hg/dirstate inconsistent with current parent's manifest")
1045 1051 raise util.Abort(error)
1046 1052
1047 1053 def debugconfig(ui):
1048 1054 """show combined config settings from all hgrc files"""
1049 1055 try:
1050 1056 repo = hg.repository(ui)
1051 1057 except hg.RepoError:
1052 1058 pass
1053 1059 for section, name, value in ui.walkconfig():
1054 1060 ui.write('%s.%s=%s\n' % (section, name, value))
1055 1061
1056 1062 def debugsetparents(ui, repo, rev1, rev2=None):
1057 1063 """manually set the parents of the current working directory
1058 1064
1059 1065 This is useful for writing repository conversion tools, but should
1060 1066 be used with care.
1061 1067 """
1062 1068
1063 1069 if not rev2:
1064 1070 rev2 = hex(nullid)
1065 1071
1066 1072 repo.dirstate.setparents(repo.lookup(rev1), repo.lookup(rev2))
1067 1073
1068 1074 def debugstate(ui, repo):
1069 1075 """show the contents of the current dirstate"""
1070 1076 repo.dirstate.read()
1071 1077 dc = repo.dirstate.map
1072 1078 keys = dc.keys()
1073 1079 keys.sort()
1074 1080 for file_ in keys:
1075 1081 ui.write("%c %3o %10d %s %s\n"
1076 1082 % (dc[file_][0], dc[file_][1] & 0777, dc[file_][2],
1077 1083 time.strftime("%x %X",
1078 1084 time.localtime(dc[file_][3])), file_))
1079 1085 for f in repo.dirstate.copies:
1080 1086 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copies[f], f))
1081 1087
1082 1088 def debugdata(ui, file_, rev):
1083 1089 """dump the contents of an data file revision"""
1084 1090 r = revlog.revlog(util.opener(os.getcwd()), file_[:-2] + ".i", file_)
1085 1091 try:
1086 1092 ui.write(r.revision(r.lookup(rev)))
1087 1093 except KeyError:
1088 1094 raise util.Abort(_('invalid revision identifier %s'), rev)
1089 1095
1090 1096 def debugindex(ui, file_):
1091 1097 """dump the contents of an index file"""
1092 1098 r = revlog.revlog(util.opener(os.getcwd()), file_, "")
1093 1099 ui.write(" rev offset length base linkrev" +
1094 1100 " nodeid p1 p2\n")
1095 1101 for i in range(r.count()):
1096 1102 e = r.index[i]
1097 1103 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1098 1104 i, e[0], e[1], e[2], e[3],
1099 1105 short(e[6]), short(e[4]), short(e[5])))
1100 1106
1101 1107 def debugindexdot(ui, file_):
1102 1108 """dump an index DAG as a .dot file"""
1103 1109 r = revlog.revlog(util.opener(os.getcwd()), file_, "")
1104 1110 ui.write("digraph G {\n")
1105 1111 for i in range(r.count()):
1106 1112 e = r.index[i]
1107 1113 ui.write("\t%d -> %d\n" % (r.rev(e[4]), i))
1108 1114 if e[5] != nullid:
1109 1115 ui.write("\t%d -> %d\n" % (r.rev(e[5]), i))
1110 1116 ui.write("}\n")
1111 1117
1112 1118 def debugrename(ui, repo, file, rev=None):
1113 1119 """dump rename information"""
1114 1120 r = repo.file(relpath(repo, [file])[0])
1115 1121 if rev:
1116 1122 try:
1117 1123 # assume all revision numbers are for changesets
1118 1124 n = repo.lookup(rev)
1119 1125 change = repo.changelog.read(n)
1120 1126 m = repo.manifest.read(change[0])
1121 1127 n = m[relpath(repo, [file])[0]]
1122 1128 except (hg.RepoError, KeyError):
1123 1129 n = r.lookup(rev)
1124 1130 else:
1125 1131 n = r.tip()
1126 1132 m = r.renamed(n)
1127 1133 if m:
1128 1134 ui.write(_("renamed from %s:%s\n") % (m[0], hex(m[1])))
1129 1135 else:
1130 1136 ui.write(_("not renamed\n"))
1131 1137
1132 1138 def debugwalk(ui, repo, *pats, **opts):
1133 1139 """show how files match on given patterns"""
1134 1140 items = list(walk(repo, pats, opts))
1135 1141 if not items:
1136 1142 return
1137 1143 fmt = '%%s %%-%ds %%-%ds %%s' % (
1138 1144 max([len(abs) for (src, abs, rel, exact) in items]),
1139 1145 max([len(rel) for (src, abs, rel, exact) in items]))
1140 1146 for src, abs, rel, exact in items:
1141 1147 line = fmt % (src, abs, rel, exact and 'exact' or '')
1142 1148 ui.write("%s\n" % line.rstrip())
1143 1149
1144 1150 def diff(ui, repo, *pats, **opts):
1145 1151 """diff repository (or selected files)
1146 1152
1147 1153 Show differences between revisions for the specified files.
1148 1154
1149 1155 Differences between files are shown using the unified diff format.
1150 1156
1151 1157 When two revision arguments are given, then changes are shown
1152 1158 between those revisions. If only one revision is specified then
1153 1159 that revision is compared to the working directory, and, when no
1154 1160 revisions are specified, the working directory files are compared
1155 1161 to its parent.
1156 1162
1157 1163 Without the -a option, diff will avoid generating diffs of files
1158 1164 it detects as binary. With -a, diff will generate a diff anyway,
1159 1165 probably with undesirable results.
1160 1166 """
1161 1167 node1, node2 = None, None
1162 1168 revs = [repo.lookup(x) for x in opts['rev']]
1163 1169
1164 1170 if len(revs) > 0:
1165 1171 node1 = revs[0]
1166 1172 if len(revs) > 1:
1167 1173 node2 = revs[1]
1168 1174 if len(revs) > 2:
1169 1175 raise util.Abort(_("too many revisions to diff"))
1170 1176
1171 1177 fns, matchfn, anypats = matchpats(repo, pats, opts)
1172 1178
1173 1179 dodiff(sys.stdout, ui, repo, node1, node2, fns, match=matchfn,
1174 1180 text=opts['text'], opts=opts)
1175 1181
1176 1182 def doexport(ui, repo, changeset, seqno, total, revwidth, opts):
1177 1183 node = repo.lookup(changeset)
1178 1184 parents = [p for p in repo.changelog.parents(node) if p != nullid]
1179 1185 if opts['switch_parent']:
1180 1186 parents.reverse()
1181 1187 prev = (parents and parents[0]) or nullid
1182 1188 change = repo.changelog.read(node)
1183 1189
1184 1190 fp = make_file(repo, repo.changelog, opts['output'],
1185 1191 node=node, total=total, seqno=seqno,
1186 1192 revwidth=revwidth)
1187 1193 if fp != sys.stdout:
1188 1194 ui.note("%s\n" % fp.name)
1189 1195
1190 1196 fp.write("# HG changeset patch\n")
1191 1197 fp.write("# User %s\n" % change[1])
1192 1198 fp.write("# Node ID %s\n" % hex(node))
1193 1199 fp.write("# Parent %s\n" % hex(prev))
1194 1200 if len(parents) > 1:
1195 1201 fp.write("# Parent %s\n" % hex(parents[1]))
1196 1202 fp.write(change[4].rstrip())
1197 1203 fp.write("\n\n")
1198 1204
1199 1205 dodiff(fp, ui, repo, prev, node, text=opts['text'])
1200 1206 if fp != sys.stdout:
1201 1207 fp.close()
1202 1208
1203 1209 def export(ui, repo, *changesets, **opts):
1204 1210 """dump the header and diffs for one or more changesets
1205 1211
1206 1212 Print the changeset header and diffs for one or more revisions.
1207 1213
1208 1214 The information shown in the changeset header is: author,
1209 1215 changeset hash, parent and commit comment.
1210 1216
1211 1217 Output may be to a file, in which case the name of the file is
1212 1218 given using a format string. The formatting rules are as follows:
1213 1219
1214 1220 %% literal "%" character
1215 1221 %H changeset hash (40 bytes of hexadecimal)
1216 1222 %N number of patches being generated
1217 1223 %R changeset revision number
1218 1224 %b basename of the exporting repository
1219 1225 %h short-form changeset hash (12 bytes of hexadecimal)
1220 1226 %n zero-padded sequence number, starting at 1
1221 1227 %r zero-padded changeset revision number
1222 1228
1223 1229 Without the -a option, export will avoid generating diffs of files
1224 1230 it detects as binary. With -a, export will generate a diff anyway,
1225 1231 probably with undesirable results.
1226 1232
1227 1233 With the --switch-parent option, the diff will be against the second
1228 1234 parent. It can be useful to review a merge.
1229 1235 """
1230 1236 if not changesets:
1231 1237 raise util.Abort(_("export requires at least one changeset"))
1232 1238 seqno = 0
1233 1239 revs = list(revrange(ui, repo, changesets))
1234 1240 total = len(revs)
1235 1241 revwidth = max(map(len, revs))
1236 1242 msg = len(revs) > 1 and _("Exporting patches:\n") or _("Exporting patch:\n")
1237 1243 ui.note(msg)
1238 1244 for cset in revs:
1239 1245 seqno += 1
1240 1246 doexport(ui, repo, cset, seqno, total, revwidth, opts)
1241 1247
1242 1248 def forget(ui, repo, *pats, **opts):
1243 1249 """don't add the specified files on the next commit
1244 1250
1245 1251 Undo an 'hg add' scheduled for the next commit.
1246 1252 """
1247 1253 forget = []
1248 1254 for src, abs, rel, exact in walk(repo, pats, opts):
1249 1255 if repo.dirstate.state(abs) == 'a':
1250 1256 forget.append(abs)
1251 1257 if ui.verbose or not exact:
1252 1258 ui.status(_('forgetting %s\n') % ((pats and rel) or abs))
1253 1259 repo.forget(forget)
1254 1260
1255 1261 def grep(ui, repo, pattern, *pats, **opts):
1256 1262 """search for a pattern in specified files and revisions
1257 1263
1258 1264 Search revisions of files for a regular expression.
1259 1265
1260 1266 This command behaves differently than Unix grep. It only accepts
1261 1267 Python/Perl regexps. It searches repository history, not the
1262 1268 working directory. It always prints the revision number in which
1263 1269 a match appears.
1264 1270
1265 1271 By default, grep only prints output for the first revision of a
1266 1272 file in which it finds a match. To get it to print every revision
1267 1273 that contains a change in match status ("-" for a match that
1268 1274 becomes a non-match, or "+" for a non-match that becomes a match),
1269 1275 use the --all flag.
1270 1276 """
1271 1277 reflags = 0
1272 1278 if opts['ignore_case']:
1273 1279 reflags |= re.I
1274 1280 regexp = re.compile(pattern, reflags)
1275 1281 sep, eol = ':', '\n'
1276 1282 if opts['print0']:
1277 1283 sep = eol = '\0'
1278 1284
1279 1285 fcache = {}
1280 1286 def getfile(fn):
1281 1287 if fn not in fcache:
1282 1288 fcache[fn] = repo.file(fn)
1283 1289 return fcache[fn]
1284 1290
1285 1291 def matchlines(body):
1286 1292 begin = 0
1287 1293 linenum = 0
1288 1294 while True:
1289 1295 match = regexp.search(body, begin)
1290 1296 if not match:
1291 1297 break
1292 1298 mstart, mend = match.span()
1293 1299 linenum += body.count('\n', begin, mstart) + 1
1294 1300 lstart = body.rfind('\n', begin, mstart) + 1 or begin
1295 1301 lend = body.find('\n', mend)
1296 1302 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
1297 1303 begin = lend + 1
1298 1304
1299 1305 class linestate(object):
1300 1306 def __init__(self, line, linenum, colstart, colend):
1301 1307 self.line = line
1302 1308 self.linenum = linenum
1303 1309 self.colstart = colstart
1304 1310 self.colend = colend
1305 1311 def __eq__(self, other):
1306 1312 return self.line == other.line
1307 1313 def __hash__(self):
1308 1314 return hash(self.line)
1309 1315
1310 1316 matches = {}
1311 1317 def grepbody(fn, rev, body):
1312 1318 matches[rev].setdefault(fn, {})
1313 1319 m = matches[rev][fn]
1314 1320 for lnum, cstart, cend, line in matchlines(body):
1315 1321 s = linestate(line, lnum, cstart, cend)
1316 1322 m[s] = s
1317 1323
1318 1324 # FIXME: prev isn't used, why ?
1319 1325 prev = {}
1320 1326 ucache = {}
1321 1327 def display(fn, rev, states, prevstates):
1322 1328 diff = list(sets.Set(states).symmetric_difference(sets.Set(prevstates)))
1323 1329 diff.sort(lambda x, y: cmp(x.linenum, y.linenum))
1324 1330 counts = {'-': 0, '+': 0}
1325 1331 filerevmatches = {}
1326 1332 for l in diff:
1327 1333 if incrementing or not opts['all']:
1328 1334 change = ((l in prevstates) and '-') or '+'
1329 1335 r = rev
1330 1336 else:
1331 1337 change = ((l in states) and '-') or '+'
1332 1338 r = prev[fn]
1333 1339 cols = [fn, str(rev)]
1334 1340 if opts['line_number']:
1335 1341 cols.append(str(l.linenum))
1336 1342 if opts['all']:
1337 1343 cols.append(change)
1338 1344 if opts['user']:
1339 1345 cols.append(trimuser(ui, getchange(rev)[1], rev,
1340 1346 ucache))
1341 1347 if opts['files_with_matches']:
1342 1348 c = (fn, rev)
1343 1349 if c in filerevmatches:
1344 1350 continue
1345 1351 filerevmatches[c] = 1
1346 1352 else:
1347 1353 cols.append(l.line)
1348 1354 ui.write(sep.join(cols), eol)
1349 1355 counts[change] += 1
1350 1356 return counts['+'], counts['-']
1351 1357
1352 1358 fstate = {}
1353 1359 skip = {}
1354 1360 changeiter, getchange, matchfn = walkchangerevs(ui, repo, pats, opts)
1355 1361 count = 0
1356 1362 incrementing = False
1357 1363 for st, rev, fns in changeiter:
1358 1364 if st == 'window':
1359 1365 incrementing = rev
1360 1366 matches.clear()
1361 1367 elif st == 'add':
1362 1368 change = repo.changelog.read(repo.lookup(str(rev)))
1363 1369 mf = repo.manifest.read(change[0])
1364 1370 matches[rev] = {}
1365 1371 for fn in fns:
1366 1372 if fn in skip:
1367 1373 continue
1368 1374 fstate.setdefault(fn, {})
1369 1375 try:
1370 1376 grepbody(fn, rev, getfile(fn).read(mf[fn]))
1371 1377 except KeyError:
1372 1378 pass
1373 1379 elif st == 'iter':
1374 1380 states = matches[rev].items()
1375 1381 states.sort()
1376 1382 for fn, m in states:
1377 1383 if fn in skip:
1378 1384 continue
1379 1385 if incrementing or not opts['all'] or fstate[fn]:
1380 1386 pos, neg = display(fn, rev, m, fstate[fn])
1381 1387 count += pos + neg
1382 1388 if pos and not opts['all']:
1383 1389 skip[fn] = True
1384 1390 fstate[fn] = m
1385 1391 prev[fn] = rev
1386 1392
1387 1393 if not incrementing:
1388 1394 fstate = fstate.items()
1389 1395 fstate.sort()
1390 1396 for fn, state in fstate:
1391 1397 if fn in skip:
1392 1398 continue
1393 1399 display(fn, rev, {}, state)
1394 1400 return (count == 0 and 1) or 0
1395 1401
1396 1402 def heads(ui, repo, **opts):
1397 1403 """show current repository heads
1398 1404
1399 1405 Show all repository head changesets.
1400 1406
1401 1407 Repository "heads" are changesets that don't have children
1402 1408 changesets. They are where development generally takes place and
1403 1409 are the usual targets for update and merge operations.
1404 1410 """
1405 1411 if opts['rev']:
1406 1412 heads = repo.heads(repo.lookup(opts['rev']))
1407 1413 else:
1408 1414 heads = repo.heads()
1409 1415 br = None
1410 1416 if opts['branches']:
1411 1417 br = repo.branchlookup(heads)
1412 1418 for n in heads:
1413 1419 show_changeset(ui, repo, changenode=n, brinfo=br)
1414 1420
1415 1421 def identify(ui, repo):
1416 1422 """print information about the working copy
1417 1423
1418 1424 Print a short summary of the current state of the repo.
1419 1425
1420 1426 This summary identifies the repository state using one or two parent
1421 1427 hash identifiers, followed by a "+" if there are uncommitted changes
1422 1428 in the working directory, followed by a list of tags for this revision.
1423 1429 """
1424 1430 parents = [p for p in repo.dirstate.parents() if p != nullid]
1425 1431 if not parents:
1426 1432 ui.write(_("unknown\n"))
1427 1433 return
1428 1434
1429 1435 hexfunc = ui.verbose and hex or short
1430 1436 modified, added, removed, deleted, unknown = repo.changes()
1431 1437 output = ["%s%s" %
1432 1438 ('+'.join([hexfunc(parent) for parent in parents]),
1433 1439 (modified or added or removed or deleted) and "+" or "")]
1434 1440
1435 1441 if not ui.quiet:
1436 1442 # multiple tags for a single parent separated by '/'
1437 1443 parenttags = ['/'.join(tags)
1438 1444 for tags in map(repo.nodetags, parents) if tags]
1439 1445 # tags for multiple parents separated by ' + '
1440 1446 if parenttags:
1441 1447 output.append(' + '.join(parenttags))
1442 1448
1443 1449 ui.write("%s\n" % ' '.join(output))
1444 1450
1445 1451 def import_(ui, repo, patch1, *patches, **opts):
1446 1452 """import an ordered set of patches
1447 1453
1448 1454 Import a list of patches and commit them individually.
1449 1455
1450 1456 If there are outstanding changes in the working directory, import
1451 1457 will abort unless given the -f flag.
1452 1458
1453 1459 If a patch looks like a mail message (its first line starts with
1454 1460 "From " or looks like an RFC822 header), it will not be applied
1455 1461 unless the -f option is used. The importer neither parses nor
1456 1462 discards mail headers, so use -f only to override the "mailness"
1457 1463 safety check, not to import a real mail message.
1458 1464 """
1459 1465 patches = (patch1,) + patches
1460 1466
1461 1467 if not opts['force']:
1462 1468 modified, added, removed, deleted, unknown = repo.changes()
1463 1469 if modified or added or removed or deleted:
1464 1470 raise util.Abort(_("outstanding uncommitted changes"))
1465 1471
1466 1472 d = opts["base"]
1467 1473 strip = opts["strip"]
1468 1474
1469 1475 mailre = re.compile(r'(?:From |[\w-]+:)')
1470 1476
1471 1477 # attempt to detect the start of a patch
1472 1478 # (this heuristic is borrowed from quilt)
1473 1479 diffre = re.compile(r'(?:Index:[ \t]|diff[ \t]|RCS file: |' +
1474 1480 'retrieving revision [0-9]+(\.[0-9]+)*$|' +
1475 1481 '(---|\*\*\*)[ \t])')
1476 1482
1477 1483 for patch in patches:
1478 1484 ui.status(_("applying %s\n") % patch)
1479 1485 pf = os.path.join(d, patch)
1480 1486
1481 1487 message = []
1482 1488 user = None
1483 1489 hgpatch = False
1484 1490 for line in file(pf):
1485 1491 line = line.rstrip()
1486 1492 if (not message and not hgpatch and
1487 1493 mailre.match(line) and not opts['force']):
1488 1494 if len(line) > 35:
1489 1495 line = line[:32] + '...'
1490 1496 raise util.Abort(_('first line looks like a '
1491 1497 'mail header: ') + line)
1492 1498 if diffre.match(line):
1493 1499 break
1494 1500 elif hgpatch:
1495 1501 # parse values when importing the result of an hg export
1496 1502 if line.startswith("# User "):
1497 1503 user = line[7:]
1498 1504 ui.debug(_('User: %s\n') % user)
1499 1505 elif not line.startswith("# ") and line:
1500 1506 message.append(line)
1501 1507 hgpatch = False
1502 1508 elif line == '# HG changeset patch':
1503 1509 hgpatch = True
1504 1510 message = [] # We may have collected garbage
1505 1511 else:
1506 1512 message.append(line)
1507 1513
1508 1514 # make sure message isn't empty
1509 1515 if not message:
1510 1516 message = _("imported patch %s\n") % patch
1511 1517 else:
1512 1518 message = "%s\n" % '\n'.join(message)
1513 1519 ui.debug(_('message:\n%s\n') % message)
1514 1520
1515 1521 files = util.patch(strip, pf, ui)
1516 1522
1517 1523 if len(files) > 0:
1518 1524 addremove(ui, repo, *files)
1519 1525 repo.commit(files, message, user)
1520 1526
1521 1527 def incoming(ui, repo, source="default", **opts):
1522 1528 """show new changesets found in source
1523 1529
1524 1530 Show new changesets found in the specified repo or the default
1525 1531 pull repo. These are the changesets that would be pulled if a pull
1526 1532 was requested.
1527 1533
1528 1534 Currently only local repositories are supported.
1529 1535 """
1530 1536 source = ui.expandpath(source, repo.root)
1531 1537 other = hg.repository(ui, source)
1532 1538 if not other.local():
1533 1539 raise util.Abort(_("incoming doesn't work for remote repositories yet"))
1534 1540 o = repo.findincoming(other)
1535 1541 if not o:
1536 1542 return
1537 1543 o = other.changelog.nodesbetween(o)[0]
1538 1544 if opts['newest_first']:
1539 1545 o.reverse()
1540 1546 for n in o:
1541 1547 parents = [p for p in other.changelog.parents(n) if p != nullid]
1542 1548 if opts['no_merges'] and len(parents) == 2:
1543 1549 continue
1544 1550 show_changeset(ui, other, changenode=n)
1545 1551 if opts['patch']:
1546 1552 prev = (parents and parents[0]) or nullid
1547 1553 dodiff(ui, ui, other, prev, n)
1548 1554 ui.write("\n")
1549 1555
1550 1556 def init(ui, dest="."):
1551 1557 """create a new repository in the given directory
1552 1558
1553 1559 Initialize a new repository in the given directory. If the given
1554 1560 directory does not exist, it is created.
1555 1561
1556 1562 If no directory is given, the current directory is used.
1557 1563 """
1558 1564 if not os.path.exists(dest):
1559 1565 os.mkdir(dest)
1560 1566 hg.repository(ui, dest, create=1)
1561 1567
1562 1568 def locate(ui, repo, *pats, **opts):
1563 1569 """locate files matching specific patterns
1564 1570
1565 1571 Print all files under Mercurial control whose names match the
1566 1572 given patterns.
1567 1573
1568 1574 This command searches the current directory and its
1569 1575 subdirectories. To search an entire repository, move to the root
1570 1576 of the repository.
1571 1577
1572 1578 If no patterns are given to match, this command prints all file
1573 1579 names.
1574 1580
1575 1581 If you want to feed the output of this command into the "xargs"
1576 1582 command, use the "-0" option to both this command and "xargs".
1577 1583 This will avoid the problem of "xargs" treating single filenames
1578 1584 that contain white space as multiple filenames.
1579 1585 """
1580 1586 end = opts['print0'] and '\0' or '\n'
1581 1587 rev = opts['rev']
1582 1588 if rev:
1583 1589 node = repo.lookup(rev)
1584 1590 else:
1585 1591 node = None
1586 1592
1587 1593 for src, abs, rel, exact in walk(repo, pats, opts, node=node,
1588 1594 head='(?:.*/|)'):
1589 1595 if not node and repo.dirstate.state(abs) == '?':
1590 1596 continue
1591 1597 if opts['fullpath']:
1592 1598 ui.write(os.path.join(repo.root, abs), end)
1593 1599 else:
1594 1600 ui.write(((pats and rel) or abs), end)
1595 1601
1596 1602 def log(ui, repo, *pats, **opts):
1597 1603 """show revision history of entire repository or files
1598 1604
1599 1605 Print the revision history of the specified files or the entire project.
1600 1606
1601 1607 By default this command outputs: changeset id and hash, tags,
1602 1608 non-trivial parents, user, date and time, and a summary for each
1603 1609 commit. When the -v/--verbose switch is used, the list of changed
1604 1610 files and full commit message is shown.
1605 1611 """
1606 1612 class dui(object):
1607 1613 # Implement and delegate some ui protocol. Save hunks of
1608 1614 # output for later display in the desired order.
1609 1615 def __init__(self, ui):
1610 1616 self.ui = ui
1611 1617 self.hunk = {}
1612 1618 def bump(self, rev):
1613 1619 self.rev = rev
1614 1620 self.hunk[rev] = []
1615 1621 def note(self, *args):
1616 1622 if self.verbose:
1617 1623 self.write(*args)
1618 1624 def status(self, *args):
1619 1625 if not self.quiet:
1620 1626 self.write(*args)
1621 1627 def write(self, *args):
1622 1628 self.hunk[self.rev].append(args)
1623 1629 def debug(self, *args):
1624 1630 if self.debugflag:
1625 1631 self.write(*args)
1626 1632 def __getattr__(self, key):
1627 1633 return getattr(self.ui, key)
1628 1634
1629 1635 changeiter, getchange, matchfn = walkchangerevs(ui, repo, pats, opts)
1630 1636
1631 1637 if opts['limit']:
1632 1638 try:
1633 1639 limit = int(opts['limit'])
1634 1640 except ValueError:
1635 1641 raise util.Abort(_('limit must be a positive integer'))
1636 1642 if limit <= 0: raise util.Abort(_('limit must be positive'))
1637 1643 else:
1638 1644 limit = sys.maxint
1639 1645 count = 0
1640 1646
1641 1647 for st, rev, fns in changeiter:
1642 1648 if st == 'window':
1643 1649 du = dui(ui)
1644 1650 elif st == 'add':
1645 1651 du.bump(rev)
1646 1652 changenode = repo.changelog.node(rev)
1647 1653 parents = [p for p in repo.changelog.parents(changenode)
1648 1654 if p != nullid]
1649 1655 if opts['no_merges'] and len(parents) == 2:
1650 1656 continue
1651 1657 if opts['only_merges'] and len(parents) != 2:
1652 1658 continue
1653 1659
1654 1660 if opts['keyword']:
1655 1661 changes = getchange(rev)
1656 1662 miss = 0
1657 1663 for k in [kw.lower() for kw in opts['keyword']]:
1658 1664 if not (k in changes[1].lower() or
1659 1665 k in changes[4].lower() or
1660 1666 k in " ".join(changes[3][:20]).lower()):
1661 1667 miss = 1
1662 1668 break
1663 1669 if miss:
1664 1670 continue
1665 1671
1666 1672 br = None
1667 1673 if opts['branches']:
1668 1674 br = repo.branchlookup([repo.changelog.node(rev)])
1669 1675
1670 1676 show_changeset(du, repo, rev, brinfo=br)
1671 1677 if opts['patch']:
1672 1678 prev = (parents and parents[0]) or nullid
1673 1679 dodiff(du, du, repo, prev, changenode, match=matchfn)
1674 1680 du.write("\n\n")
1675 1681 elif st == 'iter':
1676 1682 if count == limit: break
1677 1683 if du.hunk[rev]:
1678 1684 count += 1
1679 1685 for args in du.hunk[rev]:
1680 1686 ui.write(*args)
1681 1687
1682 1688 def manifest(ui, repo, rev=None):
1683 1689 """output the latest or given revision of the project manifest
1684 1690
1685 1691 Print a list of version controlled files for the given revision.
1686 1692
1687 1693 The manifest is the list of files being version controlled. If no revision
1688 1694 is given then the tip is used.
1689 1695 """
1690 1696 if rev:
1691 1697 try:
1692 1698 # assume all revision numbers are for changesets
1693 1699 n = repo.lookup(rev)
1694 1700 change = repo.changelog.read(n)
1695 1701 n = change[0]
1696 1702 except hg.RepoError:
1697 1703 n = repo.manifest.lookup(rev)
1698 1704 else:
1699 1705 n = repo.manifest.tip()
1700 1706 m = repo.manifest.read(n)
1701 1707 mf = repo.manifest.readflags(n)
1702 1708 files = m.keys()
1703 1709 files.sort()
1704 1710
1705 1711 for f in files:
1706 1712 ui.write("%40s %3s %s\n" % (hex(m[f]), mf[f] and "755" or "644", f))
1707 1713
1708 1714 def outgoing(ui, repo, dest="default-push", **opts):
1709 1715 """show changesets not found in destination
1710 1716
1711 1717 Show changesets not found in the specified destination repo or the
1712 1718 default push repo. These are the changesets that would be pushed
1713 1719 if a push was requested.
1714 1720 """
1715 1721 dest = ui.expandpath(dest, repo.root)
1716 1722 other = hg.repository(ui, dest)
1717 1723 o = repo.findoutgoing(other)
1718 1724 o = repo.changelog.nodesbetween(o)[0]
1719 1725 if opts['newest_first']:
1720 1726 o.reverse()
1721 1727 for n in o:
1722 1728 parents = [p for p in repo.changelog.parents(n) if p != nullid]
1723 1729 if opts['no_merges'] and len(parents) == 2:
1724 1730 continue
1725 1731 show_changeset(ui, repo, changenode=n)
1726 1732 if opts['patch']:
1727 1733 prev = (parents and parents[0]) or nullid
1728 1734 dodiff(ui, ui, repo, prev, n)
1729 1735 ui.write("\n")
1730 1736
1731 1737 def parents(ui, repo, rev=None, branches=None):
1732 1738 """show the parents of the working dir or revision
1733 1739
1734 1740 Print the working directory's parent revisions.
1735 1741 """
1736 1742 if rev:
1737 1743 p = repo.changelog.parents(repo.lookup(rev))
1738 1744 else:
1739 1745 p = repo.dirstate.parents()
1740 1746
1741 1747 br = None
1742 1748 if branches is not None:
1743 1749 br = repo.branchlookup(p)
1744 1750 for n in p:
1745 1751 if n != nullid:
1746 1752 show_changeset(ui, repo, changenode=n, brinfo=br)
1747 1753
1748 1754 def paths(ui, search=None):
1749 1755 """show definition of symbolic path names
1750 1756
1751 1757 Show definition of symbolic path name NAME. If no name is given, show
1752 1758 definition of available names.
1753 1759
1754 1760 Path names are defined in the [paths] section of /etc/mercurial/hgrc
1755 1761 and $HOME/.hgrc. If run inside a repository, .hg/hgrc is used, too.
1756 1762 """
1757 1763 try:
1758 1764 repo = hg.repository(ui=ui)
1759 1765 except hg.RepoError:
1760 1766 pass
1761 1767
1762 1768 if search:
1763 1769 for name, path in ui.configitems("paths"):
1764 1770 if name == search:
1765 1771 ui.write("%s\n" % path)
1766 1772 return
1767 1773 ui.warn(_("not found!\n"))
1768 1774 return 1
1769 1775 else:
1770 1776 for name, path in ui.configitems("paths"):
1771 1777 ui.write("%s = %s\n" % (name, path))
1772 1778
1773 1779 def pull(ui, repo, source="default", **opts):
1774 1780 """pull changes from the specified source
1775 1781
1776 1782 Pull changes from a remote repository to a local one.
1777 1783
1778 1784 This finds all changes from the repository at the specified path
1779 1785 or URL and adds them to the local repository. By default, this
1780 1786 does not update the copy of the project in the working directory.
1781 1787
1782 1788 Valid URLs are of the form:
1783 1789
1784 1790 local/filesystem/path
1785 1791 http://[user@]host[:port][/path]
1786 1792 https://[user@]host[:port][/path]
1787 1793 ssh://[user@]host[:port][/path]
1788 1794
1789 1795 SSH requires an accessible shell account on the destination machine
1790 1796 and a copy of hg in the remote path. With SSH, paths are relative
1791 1797 to the remote user's home directory by default; use two slashes at
1792 1798 the start of a path to specify it as relative to the filesystem root.
1793 1799 """
1794 1800 source = ui.expandpath(source, repo.root)
1795 1801 ui.status(_('pulling from %s\n') % (source))
1796 1802
1797 1803 if opts['ssh']:
1798 1804 ui.setconfig("ui", "ssh", opts['ssh'])
1799 1805 if opts['remotecmd']:
1800 1806 ui.setconfig("ui", "remotecmd", opts['remotecmd'])
1801 1807
1802 1808 other = hg.repository(ui, source)
1803 1809 revs = None
1804 1810 if opts['rev'] and not other.local():
1805 1811 raise util.Abort(_("pull -r doesn't work for remote repositories yet"))
1806 1812 elif opts['rev']:
1807 1813 revs = [other.lookup(rev) for rev in opts['rev']]
1808 1814 r = repo.pull(other, heads=revs)
1809 1815 if not r:
1810 1816 if opts['update']:
1811 1817 return update(ui, repo)
1812 1818 else:
1813 1819 ui.status(_("(run 'hg update' to get a working copy)\n"))
1814 1820
1815 1821 return r
1816 1822
1817 1823 def push(ui, repo, dest="default-push", **opts):
1818 1824 """push changes to the specified destination
1819 1825
1820 1826 Push changes from the local repository to the given destination.
1821 1827
1822 1828 This is the symmetrical operation for pull. It helps to move
1823 1829 changes from the current repository to a different one. If the
1824 1830 destination is local this is identical to a pull in that directory
1825 1831 from the current one.
1826 1832
1827 1833 By default, push will refuse to run if it detects the result would
1828 1834 increase the number of remote heads. This generally indicates the
1829 1835 the client has forgotten to sync and merge before pushing.
1830 1836
1831 1837 Valid URLs are of the form:
1832 1838
1833 1839 local/filesystem/path
1834 1840 ssh://[user@]host[:port][/path]
1835 1841
1836 1842 SSH requires an accessible shell account on the destination
1837 1843 machine and a copy of hg in the remote path.
1838 1844 """
1839 1845 dest = ui.expandpath(dest, repo.root)
1840 1846 ui.status('pushing to %s\n' % (dest))
1841 1847
1842 1848 if opts['ssh']:
1843 1849 ui.setconfig("ui", "ssh", opts['ssh'])
1844 1850 if opts['remotecmd']:
1845 1851 ui.setconfig("ui", "remotecmd", opts['remotecmd'])
1846 1852
1847 1853 other = hg.repository(ui, dest)
1848 1854 revs = None
1849 1855 if opts['rev']:
1850 1856 revs = [repo.lookup(rev) for rev in opts['rev']]
1851 1857 r = repo.push(other, opts['force'], revs=revs)
1852 1858 return r
1853 1859
1854 1860 def rawcommit(ui, repo, *flist, **rc):
1855 1861 """raw commit interface (DEPRECATED)
1856 1862
1857 1863 Lowlevel commit, for use in helper scripts.
1858 1864
1859 1865 This command is not intended to be used by normal users, as it is
1860 1866 primarily useful for importing from other SCMs.
1861 1867
1862 1868 This command is now deprecated and will be removed in a future
1863 1869 release, please use debugsetparents and commit instead.
1864 1870 """
1865 1871
1866 1872 ui.warn(_("(the rawcommit command is deprecated)\n"))
1867 1873
1868 1874 message = rc['message']
1869 1875 if not message and rc['logfile']:
1870 1876 try:
1871 1877 message = open(rc['logfile']).read()
1872 1878 except IOError:
1873 1879 pass
1874 1880 if not message and not rc['logfile']:
1875 1881 raise util.Abort(_("missing commit message"))
1876 1882
1877 1883 files = relpath(repo, list(flist))
1878 1884 if rc['files']:
1879 1885 files += open(rc['files']).read().splitlines()
1880 1886
1881 1887 rc['parent'] = map(repo.lookup, rc['parent'])
1882 1888
1883 1889 try:
1884 1890 repo.rawcommit(files, message, rc['user'], rc['date'], *rc['parent'])
1885 1891 except ValueError, inst:
1886 1892 raise util.Abort(str(inst))
1887 1893
1888 1894 def recover(ui, repo):
1889 1895 """roll back an interrupted transaction
1890 1896
1891 1897 Recover from an interrupted commit or pull.
1892 1898
1893 1899 This command tries to fix the repository status after an interrupted
1894 1900 operation. It should only be necessary when Mercurial suggests it.
1895 1901 """
1896 1902 if repo.recover():
1897 1903 return repo.verify()
1898 1904 return False
1899 1905
1900 1906 def remove(ui, repo, pat, *pats, **opts):
1901 1907 """remove the specified files on the next commit
1902 1908
1903 1909 Schedule the indicated files for removal from the repository.
1904 1910
1905 1911 This command schedules the files to be removed at the next commit.
1906 1912 This only removes files from the current branch, not from the
1907 1913 entire project history. If the files still exist in the working
1908 1914 directory, they will be deleted from it.
1909 1915 """
1910 1916 names = []
1911 1917 def okaytoremove(abs, rel, exact):
1912 1918 modified, added, removed, deleted, unknown = repo.changes(files=[abs])
1913 1919 reason = None
1914 1920 if modified:
1915 1921 reason = _('is modified')
1916 1922 elif added:
1917 1923 reason = _('has been marked for add')
1918 1924 elif unknown:
1919 1925 reason = _('is not managed')
1920 1926 if reason:
1921 1927 if exact:
1922 1928 ui.warn(_('not removing %s: file %s\n') % (rel, reason))
1923 1929 else:
1924 1930 return True
1925 1931 for src, abs, rel, exact in walk(repo, (pat,) + pats, opts):
1926 1932 if okaytoremove(abs, rel, exact):
1927 1933 if ui.verbose or not exact:
1928 1934 ui.status(_('removing %s\n') % rel)
1929 1935 names.append(abs)
1930 1936 repo.remove(names, unlink=True)
1931 1937
1932 1938 def rename(ui, repo, *pats, **opts):
1933 1939 """rename files; equivalent of copy + remove
1934 1940
1935 1941 Mark dest as copies of sources; mark sources for deletion. If
1936 1942 dest is a directory, copies are put in that directory. If dest is
1937 1943 a file, there can only be one source.
1938 1944
1939 1945 By default, this command copies the contents of files as they
1940 1946 stand in the working directory. If invoked with --after, the
1941 1947 operation is recorded, but no copying is performed.
1942 1948
1943 1949 This command takes effect in the next commit.
1944 1950
1945 1951 NOTE: This command should be treated as experimental. While it
1946 1952 should properly record rename files, this information is not yet
1947 1953 fully used by merge, nor fully reported by log.
1948 1954 """
1949 1955 errs, copied = docopy(ui, repo, pats, opts)
1950 1956 names = []
1951 1957 for abs, rel, exact in copied:
1952 1958 if ui.verbose or not exact:
1953 1959 ui.status(_('removing %s\n') % rel)
1954 1960 names.append(abs)
1955 1961 repo.remove(names, unlink=True)
1956 1962 return errs
1957 1963
1958 1964 def revert(ui, repo, *pats, **opts):
1959 1965 """revert modified files or dirs back to their unmodified states
1960 1966
1961 1967 Revert any uncommitted modifications made to the named files or
1962 1968 directories. This restores the contents of the affected files to
1963 1969 an unmodified state.
1964 1970
1965 1971 If a file has been deleted, it is recreated. If the executable
1966 1972 mode of a file was changed, it is reset.
1967 1973
1968 1974 If names are given, all files matching the names are reverted.
1969 1975
1970 1976 If no arguments are given, all files in the repository are reverted.
1971 1977 """
1972 1978 node = opts['rev'] and repo.lookup(opts['rev']) or \
1973 1979 repo.dirstate.parents()[0]
1974 1980
1975 1981 files, choose, anypats = matchpats(repo, pats, opts)
1976 1982 modified, added, removed, deleted, unknown = repo.changes(match=choose)
1977 1983 repo.forget(added)
1978 1984 repo.undelete(removed)
1979 1985
1980 1986 return repo.update(node, False, True, choose, False)
1981 1987
1982 1988 def root(ui, repo):
1983 1989 """print the root (top) of the current working dir
1984 1990
1985 1991 Print the root directory of the current repository.
1986 1992 """
1987 1993 ui.write(repo.root + "\n")
1988 1994
1989 1995 def serve(ui, repo, **opts):
1990 1996 """export the repository via HTTP
1991 1997
1992 1998 Start a local HTTP repository browser and pull server.
1993 1999
1994 2000 By default, the server logs accesses to stdout and errors to
1995 2001 stderr. Use the "-A" and "-E" options to log to files.
1996 2002 """
1997 2003
1998 2004 if opts["stdio"]:
1999 2005 fin, fout = sys.stdin, sys.stdout
2000 2006 sys.stdout = sys.stderr
2001 2007
2002 2008 # Prevent insertion/deletion of CRs
2003 2009 util.set_binary(fin)
2004 2010 util.set_binary(fout)
2005 2011
2006 2012 def getarg():
2007 2013 argline = fin.readline()[:-1]
2008 2014 arg, l = argline.split()
2009 2015 val = fin.read(int(l))
2010 2016 return arg, val
2011 2017 def respond(v):
2012 2018 fout.write("%d\n" % len(v))
2013 2019 fout.write(v)
2014 2020 fout.flush()
2015 2021
2016 2022 lock = None
2017 2023
2018 2024 while 1:
2019 2025 cmd = fin.readline()[:-1]
2020 2026 if cmd == '':
2021 2027 return
2022 2028 if cmd == "heads":
2023 2029 h = repo.heads()
2024 2030 respond(" ".join(map(hex, h)) + "\n")
2025 2031 if cmd == "lock":
2026 2032 lock = repo.lock()
2027 2033 respond("")
2028 2034 if cmd == "unlock":
2029 2035 if lock:
2030 2036 lock.release()
2031 2037 lock = None
2032 2038 respond("")
2033 2039 elif cmd == "branches":
2034 2040 arg, nodes = getarg()
2035 2041 nodes = map(bin, nodes.split(" "))
2036 2042 r = []
2037 2043 for b in repo.branches(nodes):
2038 2044 r.append(" ".join(map(hex, b)) + "\n")
2039 2045 respond("".join(r))
2040 2046 elif cmd == "between":
2041 2047 arg, pairs = getarg()
2042 2048 pairs = [map(bin, p.split("-")) for p in pairs.split(" ")]
2043 2049 r = []
2044 2050 for b in repo.between(pairs):
2045 2051 r.append(" ".join(map(hex, b)) + "\n")
2046 2052 respond("".join(r))
2047 2053 elif cmd == "changegroup":
2048 2054 nodes = []
2049 2055 arg, roots = getarg()
2050 2056 nodes = map(bin, roots.split(" "))
2051 2057
2052 2058 cg = repo.changegroup(nodes, 'serve')
2053 2059 while 1:
2054 2060 d = cg.read(4096)
2055 2061 if not d:
2056 2062 break
2057 2063 fout.write(d)
2058 2064
2059 2065 fout.flush()
2060 2066
2061 2067 elif cmd == "addchangegroup":
2062 2068 if not lock:
2063 2069 respond("not locked")
2064 2070 continue
2065 2071 respond("")
2066 2072
2067 2073 r = repo.addchangegroup(fin)
2068 2074 respond("")
2069 2075
2070 2076 optlist = "name templates style address port ipv6 accesslog errorlog"
2071 2077 for o in optlist.split():
2072 2078 if opts[o]:
2073 2079 ui.setconfig("web", o, opts[o])
2074 2080
2075 2081 if opts['daemon'] and not opts['daemon_pipefds']:
2076 2082 rfd, wfd = os.pipe()
2077 2083 args = sys.argv[:]
2078 2084 args.append('--daemon-pipefds=%d,%d' % (rfd, wfd))
2079 2085 pid = os.spawnvp(os.P_NOWAIT | getattr(os, 'P_DETACH', 0),
2080 2086 args[0], args)
2081 2087 os.close(wfd)
2082 2088 os.read(rfd, 1)
2083 2089 os._exit(0)
2084 2090
2085 2091 try:
2086 2092 httpd = hgweb.create_server(repo)
2087 2093 except socket.error, inst:
2088 2094 raise util.Abort(_('cannot start server: ') + inst.args[1])
2089 2095
2090 2096 if ui.verbose:
2091 2097 addr, port = httpd.socket.getsockname()
2092 2098 if addr == '0.0.0.0':
2093 2099 addr = socket.gethostname()
2094 2100 else:
2095 2101 try:
2096 2102 addr = socket.gethostbyaddr(addr)[0]
2097 2103 except socket.error:
2098 2104 pass
2099 2105 if port != 80:
2100 2106 ui.status(_('listening at http://%s:%d/\n') % (addr, port))
2101 2107 else:
2102 2108 ui.status(_('listening at http://%s/\n') % addr)
2103 2109
2104 2110 if opts['pid_file']:
2105 2111 fp = open(opts['pid_file'], 'w')
2106 2112 fp.write(str(os.getpid()))
2107 2113 fp.close()
2108 2114
2109 2115 if opts['daemon_pipefds']:
2110 2116 rfd, wfd = [int(x) for x in opts['daemon_pipefds'].split(',')]
2111 2117 os.close(rfd)
2112 2118 os.write(wfd, 'y')
2113 2119 os.close(wfd)
2114 2120 sys.stdout.flush()
2115 2121 sys.stderr.flush()
2116 2122 fd = os.open(util.nulldev, os.O_RDWR)
2117 2123 if fd != 0: os.dup2(fd, 0)
2118 2124 if fd != 1: os.dup2(fd, 1)
2119 2125 if fd != 2: os.dup2(fd, 2)
2120 2126 if fd not in (0, 1, 2): os.close(fd)
2121 2127
2122 2128 httpd.serve_forever()
2123 2129
2124 2130 def status(ui, repo, *pats, **opts):
2125 2131 """show changed files in the working directory
2126 2132
2127 2133 Show changed files in the repository. If names are
2128 2134 given, only files that match are shown.
2129 2135
2130 2136 The codes used to show the status of files are:
2131 2137 M = modified
2132 2138 A = added
2133 2139 R = removed
2134 2140 ! = deleted, but still tracked
2135 2141 ? = not tracked
2136 2142 """
2137 2143
2138 2144 files, matchfn, anypats = matchpats(repo, pats, opts)
2139 2145 cwd = (pats and repo.getcwd()) or ''
2140 2146 modified, added, removed, deleted, unknown = [
2141 2147 [util.pathto(cwd, x) for x in n]
2142 2148 for n in repo.changes(files=files, match=matchfn)]
2143 2149
2144 2150 changetypes = [(_('modified'), 'M', modified),
2145 2151 (_('added'), 'A', added),
2146 2152 (_('removed'), 'R', removed),
2147 2153 (_('deleted'), '!', deleted),
2148 2154 (_('unknown'), '?', unknown)]
2149 2155
2150 2156 end = opts['print0'] and '\0' or '\n'
2151 2157
2152 2158 for opt, char, changes in ([ct for ct in changetypes if opts[ct[0]]]
2153 2159 or changetypes):
2154 2160 if opts['no_status']:
2155 2161 format = "%%s%s" % end
2156 2162 else:
2157 2163 format = "%s %%s%s" % (char, end);
2158 2164
2159 2165 for f in changes:
2160 2166 ui.write(format % f)
2161 2167
2162 2168 def tag(ui, repo, name, rev_=None, **opts):
2163 2169 """add a tag for the current tip or a given revision
2164 2170
2165 2171 Name a particular revision using <name>.
2166 2172
2167 2173 Tags are used to name particular revisions of the repository and are
2168 2174 very useful to compare different revision, to go back to significant
2169 2175 earlier versions or to mark branch points as releases, etc.
2170 2176
2171 2177 If no revision is given, the tip is used.
2172 2178
2173 2179 To facilitate version control, distribution, and merging of tags,
2174 2180 they are stored as a file named ".hgtags" which is managed
2175 2181 similarly to other project files and can be hand-edited if
2176 2182 necessary. The file '.hg/localtags' is used for local tags (not
2177 2183 shared among repositories).
2178 2184 """
2179 2185 if name == "tip":
2180 2186 raise util.Abort(_("the name 'tip' is reserved"))
2181 2187 if rev_ is not None:
2182 2188 ui.warn(_("use of 'hg tag NAME [REV]' is deprecated, "
2183 2189 "please use 'hg tag [-r REV] NAME' instead\n"))
2184 2190 if opts['rev']:
2185 2191 raise util.Abort(_("use only one form to specify the revision"))
2186 2192 if opts['rev']:
2187 2193 rev_ = opts['rev']
2188 2194 if rev_:
2189 2195 r = hex(repo.lookup(rev_))
2190 2196 else:
2191 2197 r = hex(repo.changelog.tip())
2192 2198
2193 2199 disallowed = (revrangesep, '\r', '\n')
2194 2200 for c in disallowed:
2195 2201 if name.find(c) >= 0:
2196 2202 raise util.Abort(_("%s cannot be used in a tag name") % repr(c))
2197 2203
2198 2204 repo.hook('pretag', throw=True, node=r, tag=name,
2199 2205 local=int(not not opts['local']))
2200 2206
2201 2207 if opts['local']:
2202 2208 repo.opener("localtags", "a").write("%s %s\n" % (r, name))
2203 2209 repo.hook('tag', node=r, tag=name, local=1)
2204 2210 return
2205 2211
2206 2212 for x in repo.changes():
2207 2213 if ".hgtags" in x:
2208 2214 raise util.Abort(_("working copy of .hgtags is changed "
2209 2215 "(please commit .hgtags manually)"))
2210 2216
2211 2217 repo.wfile(".hgtags", "ab").write("%s %s\n" % (r, name))
2212 2218 if repo.dirstate.state(".hgtags") == '?':
2213 2219 repo.add([".hgtags"])
2214 2220
2215 2221 message = (opts['message'] or
2216 2222 _("Added tag %s for changeset %s") % (name, r))
2217 2223 try:
2218 2224 repo.commit([".hgtags"], message, opts['user'], opts['date'])
2219 2225 repo.hook('tag', node=r, tag=name, local=0)
2220 2226 except ValueError, inst:
2221 2227 raise util.Abort(str(inst))
2222 2228
2223 2229 def tags(ui, repo):
2224 2230 """list repository tags
2225 2231
2226 2232 List the repository tags.
2227 2233
2228 2234 This lists both regular and local tags.
2229 2235 """
2230 2236
2231 2237 l = repo.tagslist()
2232 2238 l.reverse()
2233 2239 for t, n in l:
2234 2240 try:
2235 2241 r = "%5d:%s" % (repo.changelog.rev(n), hex(n))
2236 2242 except KeyError:
2237 2243 r = " ?:?"
2238 2244 ui.write("%-30s %s\n" % (t, r))
2239 2245
2240 2246 def tip(ui, repo, **opts):
2241 2247 """show the tip revision
2242 2248
2243 2249 Show the tip revision.
2244 2250 """
2245 2251 n = repo.changelog.tip()
2246 2252 br = None
2247 2253 if opts['branches']:
2248 2254 br = repo.branchlookup([n])
2249 2255 show_changeset(ui, repo, changenode=n, brinfo=br)
2250 2256 if opts['patch']:
2251 2257 dodiff(ui, ui, repo, repo.changelog.parents(n)[0], n)
2252 2258
2253 2259 def unbundle(ui, repo, fname, **opts):
2254 2260 """apply a changegroup file
2255 2261
2256 2262 Apply a compressed changegroup file generated by the bundle
2257 2263 command.
2258 2264 """
2259 2265 f = urllib.urlopen(fname)
2260 2266
2261 2267 if f.read(4) != "HG10":
2262 2268 raise util.Abort(_("%s: not a Mercurial bundle file") % fname)
2263 2269
2264 2270 def bzgenerator(f):
2265 2271 zd = bz2.BZ2Decompressor()
2266 2272 for chunk in f:
2267 2273 yield zd.decompress(chunk)
2268 2274
2269 2275 bzgen = bzgenerator(util.filechunkiter(f, 4096))
2270 2276 if repo.addchangegroup(util.chunkbuffer(bzgen)):
2271 2277 return 1
2272 2278
2273 2279 if opts['update']:
2274 2280 return update(ui, repo)
2275 2281 else:
2276 2282 ui.status(_("(run 'hg update' to get a working copy)\n"))
2277 2283
2278 2284 def undo(ui, repo):
2279 2285 """undo the last commit or pull
2280 2286
2281 2287 Roll back the last pull or commit transaction on the
2282 2288 repository, restoring the project to its earlier state.
2283 2289
2284 2290 This command should be used with care. There is only one level of
2285 2291 undo and there is no redo.
2286 2292
2287 2293 This command is not intended for use on public repositories. Once
2288 2294 a change is visible for pull by other users, undoing it locally is
2289 2295 ineffective.
2290 2296 """
2291 2297 repo.undo()
2292 2298
2293 2299 def update(ui, repo, node=None, merge=False, clean=False, force=None,
2294 2300 branch=None):
2295 2301 """update or merge working directory
2296 2302
2297 2303 Update the working directory to the specified revision.
2298 2304
2299 2305 If there are no outstanding changes in the working directory and
2300 2306 there is a linear relationship between the current version and the
2301 2307 requested version, the result is the requested version.
2302 2308
2303 2309 Otherwise the result is a merge between the contents of the
2304 2310 current working directory and the requested version. Files that
2305 2311 changed between either parent are marked as changed for the next
2306 2312 commit and a commit must be performed before any further updates
2307 2313 are allowed.
2308 2314
2309 2315 By default, update will refuse to run if doing so would require
2310 2316 merging or discarding local changes.
2311 2317 """
2312 2318 if branch:
2313 2319 br = repo.branchlookup(branch=branch)
2314 2320 found = []
2315 2321 for x in br:
2316 2322 if branch in br[x]:
2317 2323 found.append(x)
2318 2324 if len(found) > 1:
2319 2325 ui.warn(_("Found multiple heads for %s\n") % branch)
2320 2326 for x in found:
2321 2327 show_changeset(ui, repo, changenode=x, brinfo=br)
2322 2328 return 1
2323 2329 if len(found) == 1:
2324 2330 node = found[0]
2325 2331 ui.warn(_("Using head %s for branch %s\n") % (short(node), branch))
2326 2332 else:
2327 2333 ui.warn(_("branch %s not found\n") % (branch))
2328 2334 return 1
2329 2335 else:
2330 2336 node = node and repo.lookup(node) or repo.changelog.tip()
2331 2337 return repo.update(node, allow=merge, force=clean, forcemerge=force)
2332 2338
2333 2339 def verify(ui, repo):
2334 2340 """verify the integrity of the repository
2335 2341
2336 2342 Verify the integrity of the current repository.
2337 2343
2338 2344 This will perform an extensive check of the repository's
2339 2345 integrity, validating the hashes and checksums of each entry in
2340 2346 the changelog, manifest, and tracked files, as well as the
2341 2347 integrity of their crosslinks and indices.
2342 2348 """
2343 2349 return repo.verify()
2344 2350
2345 2351 # Command options and aliases are listed here, alphabetically
2346 2352
2347 2353 table = {
2348 2354 "^add":
2349 2355 (add,
2350 2356 [('I', 'include', [], _('include names matching the given patterns')),
2351 2357 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2352 2358 _('hg add [OPTION]... [FILE]...')),
2353 2359 "addremove":
2354 2360 (addremove,
2355 2361 [('I', 'include', [], _('include names matching the given patterns')),
2356 2362 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2357 2363 _('hg addremove [OPTION]... [FILE]...')),
2358 2364 "^annotate":
2359 2365 (annotate,
2360 2366 [('r', 'rev', '', _('annotate the specified revision')),
2361 2367 ('a', 'text', None, _('treat all files as text')),
2362 2368 ('u', 'user', None, _('list the author')),
2363 2369 ('d', 'date', None, _('list the date')),
2364 2370 ('n', 'number', None, _('list the revision number (default)')),
2365 2371 ('c', 'changeset', None, _('list the changeset')),
2366 2372 ('I', 'include', [], _('include names matching the given patterns')),
2367 2373 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2368 2374 _('hg annotate [OPTION]... FILE...')),
2369 2375 "bundle":
2370 2376 (bundle,
2371 2377 [],
2372 2378 _('hg bundle FILE DEST')),
2373 2379 "cat":
2374 2380 (cat,
2375 2381 [('I', 'include', [], _('include names matching the given patterns')),
2376 2382 ('X', 'exclude', [], _('exclude names matching the given patterns')),
2377 2383 ('o', 'output', '', _('print output to file with formatted name')),
2378 2384 ('r', 'rev', '', _('print the given revision'))],
2379 2385 _('hg cat [OPTION]... FILE...')),
2380 2386 "^clone":
2381 2387 (clone,
2382 2388 [('U', 'noupdate', None, _('do not update the new working directory')),
2383 2389 ('e', 'ssh', '', _('specify ssh command to use')),
2384 2390 ('', 'pull', None, _('use pull protocol to copy metadata')),
2385 2391 ('r', 'rev', [],
2386 2392 _('a changeset you would like to have after cloning')),
2387 2393 ('', 'remotecmd', '',
2388 2394 _('specify hg command to run on the remote side'))],
2389 2395 _('hg clone [OPTION]... SOURCE [DEST]')),
2390 2396 "^commit|ci":
2391 2397 (commit,
2392 2398 [('A', 'addremove', None, _('run addremove during commit')),
2393 2399 ('I', 'include', [], _('include names matching the given patterns')),
2394 2400 ('X', 'exclude', [], _('exclude names matching the given patterns')),
2395 2401 ('m', 'message', '', _('use <text> as commit message')),
2396 2402 ('l', 'logfile', '', _('read the commit message from <file>')),
2397 2403 ('d', 'date', '', _('record datecode as commit date')),
2398 2404 ('u', 'user', '', _('record user as commiter'))],
2399 2405 _('hg commit [OPTION]... [FILE]...')),
2400 2406 "copy|cp":
2401 2407 (copy,
2402 2408 [('I', 'include', [], _('include names matching the given patterns')),
2403 2409 ('X', 'exclude', [], _('exclude names matching the given patterns')),
2404 2410 ('A', 'after', None, _('record a copy that has already occurred')),
2405 2411 ('f', 'force', None,
2406 2412 _('forcibly copy over an existing managed file'))],
2407 2413 _('hg copy [OPTION]... [SOURCE]... DEST')),
2408 2414 "debugancestor": (debugancestor, [], _('debugancestor INDEX REV1 REV2')),
2409 2415 "debugrebuildstate":
2410 2416 (debugrebuildstate,
2411 2417 [('r', 'rev', "", _("revision to rebuild to"))],
2412 2418 _('debugrebuildstate [-r REV] [REV]')),
2413 2419 "debugcheckstate": (debugcheckstate, [], _('debugcheckstate')),
2414 2420 "debugconfig": (debugconfig, [], _('debugconfig')),
2415 2421 "debugsetparents": (debugsetparents, [], _('debugsetparents REV1 [REV2]')),
2416 2422 "debugstate": (debugstate, [], _('debugstate')),
2417 2423 "debugdata": (debugdata, [], _('debugdata FILE REV')),
2418 2424 "debugindex": (debugindex, [], _('debugindex FILE')),
2419 2425 "debugindexdot": (debugindexdot, [], _('debugindexdot FILE')),
2420 2426 "debugrename": (debugrename, [], _('debugrename FILE [REV]')),
2421 2427 "debugwalk":
2422 2428 (debugwalk,
2423 2429 [('I', 'include', [], _('include names matching the given patterns')),
2424 2430 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2425 2431 _('debugwalk [OPTION]... [FILE]...')),
2426 2432 "^diff":
2427 2433 (diff,
2428 2434 [('r', 'rev', [], _('revision')),
2429 2435 ('a', 'text', None, _('treat all files as text')),
2430 2436 ('I', 'include', [], _('include names matching the given patterns')),
2431 2437 ('p', 'show-function', None,
2432 2438 _('show which function each change is in')),
2433 2439 ('w', 'ignore-all-space', None,
2434 2440 _('ignore white space when comparing lines')),
2435 2441 ('X', 'exclude', [],
2436 2442 _('exclude names matching the given patterns'))],
2437 2443 _('hg diff [-a] [-I] [-X] [-r REV1 [-r REV2]] [FILE]...')),
2438 2444 "^export":
2439 2445 (export,
2440 2446 [('o', 'output', '', _('print output to file with formatted name')),
2441 2447 ('a', 'text', None, _('treat all files as text')),
2442 2448 ('', 'switch-parent', None, _('diff against the second parent'))],
2443 2449 _('hg export [-a] [-o OUTFILE] REV...')),
2444 2450 "forget":
2445 2451 (forget,
2446 2452 [('I', 'include', [], _('include names matching the given patterns')),
2447 2453 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2448 2454 _('hg forget [OPTION]... FILE...')),
2449 2455 "grep":
2450 2456 (grep,
2451 2457 [('0', 'print0', None, _('end fields with NUL')),
2452 2458 ('I', 'include', [], _('include names matching the given patterns')),
2453 2459 ('X', 'exclude', [], _('exclude names matching the given patterns')),
2454 2460 ('', 'all', None, _('print all revisions that match')),
2455 2461 ('i', 'ignore-case', None, _('ignore case when matching')),
2456 2462 ('l', 'files-with-matches', None,
2457 2463 _('print only filenames and revs that match')),
2458 2464 ('n', 'line-number', None, _('print matching line numbers')),
2459 2465 ('r', 'rev', [], _('search in given revision range')),
2460 2466 ('u', 'user', None, _('print user who committed change'))],
2461 2467 _('hg grep [OPTION]... PATTERN [FILE]...')),
2462 2468 "heads":
2463 2469 (heads,
2464 2470 [('b', 'branches', None, _('show branches')),
2465 2471 ('r', 'rev', '', _('show only heads which are descendants of rev'))],
2466 2472 _('hg heads [-b] [-r <rev>]')),
2467 2473 "help": (help_, [], _('hg help [COMMAND]')),
2468 2474 "identify|id": (identify, [], _('hg identify')),
2469 2475 "import|patch":
2470 2476 (import_,
2471 2477 [('p', 'strip', 1,
2472 2478 _('directory strip option for patch. This has the same\n') +
2473 2479 _('meaning as the corresponding patch option')),
2474 2480 ('f', 'force', None,
2475 2481 _('skip check for outstanding uncommitted changes')),
2476 2482 ('b', 'base', '', _('base path'))],
2477 2483 _('hg import [-f] [-p NUM] [-b BASE] PATCH...')),
2478 2484 "incoming|in": (incoming,
2479 2485 [('M', 'no-merges', None, _('do not show merges')),
2480 2486 ('p', 'patch', None, _('show patch')),
2481 2487 ('n', 'newest-first', None, _('show newest record first'))],
2482 2488 _('hg incoming [-p] [-n] [-M] [SOURCE]')),
2483 2489 "^init": (init, [], _('hg init [DEST]')),
2484 2490 "locate":
2485 2491 (locate,
2486 2492 [('r', 'rev', '', _('search the repository as it stood at rev')),
2487 2493 ('0', 'print0', None,
2488 2494 _('end filenames with NUL, for use with xargs')),
2489 2495 ('f', 'fullpath', None,
2490 2496 _('print complete paths from the filesystem root')),
2491 2497 ('I', 'include', [], _('include names matching the given patterns')),
2492 2498 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2493 2499 _('hg locate [OPTION]... [PATTERN]...')),
2494 2500 "^log|history":
2495 2501 (log,
2496 2502 [('I', 'include', [], _('include names matching the given patterns')),
2497 2503 ('X', 'exclude', [], _('exclude names matching the given patterns')),
2498 2504 ('b', 'branches', None, _('show branches')),
2499 2505 ('k', 'keyword', [], _('search for a keyword')),
2500 2506 ('l', 'limit', '', _('limit number of changes displayed')),
2501 2507 ('r', 'rev', [], _('show the specified revision or range')),
2502 2508 ('M', 'no-merges', None, _('do not show merges')),
2503 2509 ('m', 'only-merges', None, _('show only merges')),
2504 2510 ('p', 'patch', None, _('show patch'))],
2505 2511 _('hg log [-I] [-X] [-r REV]... [-p] [FILE]')),
2506 2512 "manifest": (manifest, [], _('hg manifest [REV]')),
2507 2513 "outgoing|out": (outgoing,
2508 2514 [('M', 'no-merges', None, _('do not show merges')),
2509 2515 ('p', 'patch', None, _('show patch')),
2510 2516 ('n', 'newest-first', None, _('show newest record first'))],
2511 2517 _('hg outgoing [-p] [-n] [-M] [DEST]')),
2512 2518 "^parents":
2513 2519 (parents,
2514 2520 [('b', 'branches', None, _('show branches'))],
2515 2521 _('hg parents [-b] [REV]')),
2516 2522 "paths": (paths, [], _('hg paths [NAME]')),
2517 2523 "^pull":
2518 2524 (pull,
2519 2525 [('u', 'update', None,
2520 2526 _('update the working directory to tip after pull')),
2521 2527 ('e', 'ssh', '', _('specify ssh command to use')),
2522 2528 ('r', 'rev', [], _('a specific revision you would like to pull')),
2523 2529 ('', 'remotecmd', '',
2524 2530 _('specify hg command to run on the remote side'))],
2525 2531 _('hg pull [-u] [-e FILE] [-r rev]... [--remotecmd FILE] [SOURCE]')),
2526 2532 "^push":
2527 2533 (push,
2528 2534 [('f', 'force', None, _('force push')),
2529 2535 ('e', 'ssh', '', _('specify ssh command to use')),
2530 2536 ('r', 'rev', [], _('a specific revision you would like to push')),
2531 2537 ('', 'remotecmd', '',
2532 2538 _('specify hg command to run on the remote side'))],
2533 2539 _('hg push [-f] [-e FILE] [-r rev]... [--remotecmd FILE] [DEST]')),
2534 2540 "rawcommit":
2535 2541 (rawcommit,
2536 2542 [('p', 'parent', [], _('parent')),
2537 2543 ('d', 'date', '', _('date code')),
2538 2544 ('u', 'user', '', _('user')),
2539 2545 ('F', 'files', '', _('file list')),
2540 2546 ('m', 'message', '', _('commit message')),
2541 2547 ('l', 'logfile', '', _('commit message file'))],
2542 2548 _('hg rawcommit [OPTION]... [FILE]...')),
2543 2549 "recover": (recover, [], _('hg recover')),
2544 2550 "^remove|rm":
2545 2551 (remove,
2546 2552 [('I', 'include', [], _('include names matching the given patterns')),
2547 2553 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2548 2554 _('hg remove [OPTION]... FILE...')),
2549 2555 "rename|mv":
2550 2556 (rename,
2551 2557 [('I', 'include', [], _('include names matching the given patterns')),
2552 2558 ('X', 'exclude', [], _('exclude names matching the given patterns')),
2553 2559 ('A', 'after', None, _('record a rename that has already occurred')),
2554 2560 ('f', 'force', None,
2555 2561 _('forcibly copy over an existing managed file'))],
2556 2562 _('hg rename [OPTION]... [SOURCE]... DEST')),
2557 2563 "^revert":
2558 2564 (revert,
2559 2565 [('I', 'include', [], _('include names matching the given patterns')),
2560 2566 ('X', 'exclude', [], _('exclude names matching the given patterns')),
2561 2567 ('r', 'rev', '', _('revision to revert to'))],
2562 2568 _('hg revert [-n] [-r REV] [NAME]...')),
2563 2569 "root": (root, [], _('hg root')),
2564 2570 "^serve":
2565 2571 (serve,
2566 2572 [('A', 'accesslog', '', _('name of access log file to write to')),
2567 2573 ('d', 'daemon', None, _('run server in background')),
2568 2574 ('', 'daemon-pipefds', '', _('used internally by daemon mode')),
2569 2575 ('E', 'errorlog', '', _('name of error log file to write to')),
2570 2576 ('p', 'port', 0, _('port to use (default: 8000)')),
2571 2577 ('a', 'address', '', _('address to use')),
2572 2578 ('n', 'name', '',
2573 2579 _('name to show in web pages (default: working dir)')),
2574 2580 ('', 'pid-file', '', _('name of file to write process ID to')),
2575 2581 ('', 'stdio', None, _('for remote clients')),
2576 2582 ('t', 'templates', '', _('web templates to use')),
2577 2583 ('', 'style', '', _('template style to use')),
2578 2584 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4'))],
2579 2585 _('hg serve [OPTION]...')),
2580 2586 "^status|st":
2581 2587 (status,
2582 2588 [('m', 'modified', None, _('show only modified files')),
2583 2589 ('a', 'added', None, _('show only added files')),
2584 2590 ('r', 'removed', None, _('show only removed files')),
2585 2591 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
2586 2592 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
2587 2593 ('n', 'no-status', None, _('hide status prefix')),
2588 2594 ('0', 'print0', None,
2589 2595 _('end filenames with NUL, for use with xargs')),
2590 2596 ('I', 'include', [], _('include names matching the given patterns')),
2591 2597 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2592 2598 _('hg status [OPTION]... [FILE]...')),
2593 2599 "tag":
2594 2600 (tag,
2595 2601 [('l', 'local', None, _('make the tag local')),
2596 2602 ('m', 'message', '', _('message for tag commit log entry')),
2597 2603 ('d', 'date', '', _('record datecode as commit date')),
2598 2604 ('u', 'user', '', _('record user as commiter')),
2599 2605 ('r', 'rev', '', _('revision to tag'))],
2600 2606 _('hg tag [-r REV] [OPTION]... NAME')),
2601 2607 "tags": (tags, [], _('hg tags')),
2602 2608 "tip":
2603 2609 (tip,
2604 2610 [('b', 'branches', None, _('show branches')),
2605 2611 ('p', 'patch', None, _('show patch'))],
2606 2612 _('hg [-b] [-p] tip')),
2607 2613 "unbundle":
2608 2614 (unbundle,
2609 2615 [('u', 'update', None,
2610 2616 _('update the working directory to tip after unbundle'))],
2611 2617 _('hg unbundle [-u] FILE')),
2612 2618 "undo": (undo, [], _('hg undo')),
2613 2619 "^update|up|checkout|co":
2614 2620 (update,
2615 2621 [('b', 'branch', '', _('checkout the head of a specific branch')),
2616 2622 ('m', 'merge', None, _('allow merging of branches')),
2617 2623 ('C', 'clean', None, _('overwrite locally modified files')),
2618 2624 ('f', 'force', None, _('force a merge with outstanding changes'))],
2619 2625 _('hg update [-b TAG] [-m] [-C] [-f] [REV]')),
2620 2626 "verify": (verify, [], _('hg verify')),
2621 2627 "version": (show_version, [], _('hg version')),
2622 2628 }
2623 2629
2624 2630 globalopts = [
2625 2631 ('R', 'repository', '', _('repository root directory')),
2626 2632 ('', 'cwd', '', _('change working directory')),
2627 2633 ('y', 'noninteractive', None,
2628 2634 _('do not prompt, assume \'yes\' for any required answers')),
2629 2635 ('q', 'quiet', None, _('suppress output')),
2630 2636 ('v', 'verbose', None, _('enable additional output')),
2631 2637 ('', 'debug', None, _('enable debugging output')),
2632 2638 ('', 'debugger', None, _('start debugger')),
2633 2639 ('', 'traceback', None, _('print traceback on exception')),
2634 2640 ('', 'time', None, _('time how long the command takes')),
2635 2641 ('', 'profile', None, _('print command execution profile')),
2636 2642 ('', 'version', None, _('output version information and exit')),
2637 2643 ('h', 'help', None, _('display help and exit')),
2638 2644 ]
2639 2645
2640 2646 norepo = ("clone init version help debugancestor debugconfig debugdata"
2641 2647 " debugindex debugindexdot paths")
2642 2648
2643 2649 def find(cmd):
2644 2650 """Return (aliases, command table entry) for command string."""
2645 2651 choice = None
2646 2652 count = 0
2647 2653 for e in table.keys():
2648 2654 aliases = e.lstrip("^").split("|")
2649 2655 if cmd in aliases:
2650 2656 return aliases, table[e]
2651 2657 for a in aliases:
2652 2658 if a.startswith(cmd):
2653 2659 count += 1
2654 2660 choice = aliases, table[e]
2655 2661 break
2656 2662
2657 2663 if count > 1:
2658 2664 raise AmbiguousCommand(cmd)
2659 2665
2660 2666 if choice:
2661 2667 return choice
2662 2668
2663 2669 raise UnknownCommand(cmd)
2664 2670
2665 2671 class SignalInterrupt(Exception):
2666 2672 """Exception raised on SIGTERM and SIGHUP."""
2667 2673
2668 2674 def catchterm(*args):
2669 2675 raise SignalInterrupt
2670 2676
2671 2677 def run():
2672 2678 sys.exit(dispatch(sys.argv[1:]))
2673 2679
2674 2680 class ParseError(Exception):
2675 2681 """Exception raised on errors in parsing the command line."""
2676 2682
2677 2683 def parse(ui, args):
2678 2684 options = {}
2679 2685 cmdoptions = {}
2680 2686
2681 2687 try:
2682 2688 args = fancyopts.fancyopts(args, globalopts, options)
2683 2689 except fancyopts.getopt.GetoptError, inst:
2684 2690 raise ParseError(None, inst)
2685 2691
2686 2692 if args:
2687 2693 cmd, args = args[0], args[1:]
2688 2694 aliases, i = find(cmd)
2689 2695 cmd = aliases[0]
2690 2696 defaults = ui.config("defaults", cmd)
2691 2697 if defaults:
2692 2698 args = defaults.split() + args
2693 2699 c = list(i[1])
2694 2700 else:
2695 2701 cmd = None
2696 2702 c = []
2697 2703
2698 2704 # combine global options into local
2699 2705 for o in globalopts:
2700 2706 c.append((o[0], o[1], options[o[1]], o[3]))
2701 2707
2702 2708 try:
2703 2709 args = fancyopts.fancyopts(args, c, cmdoptions)
2704 2710 except fancyopts.getopt.GetoptError, inst:
2705 2711 raise ParseError(cmd, inst)
2706 2712
2707 2713 # separate global options back out
2708 2714 for o in globalopts:
2709 2715 n = o[1]
2710 2716 options[n] = cmdoptions[n]
2711 2717 del cmdoptions[n]
2712 2718
2713 2719 return (cmd, cmd and i[0] or None, args, options, cmdoptions)
2714 2720
2715 2721 def dispatch(args):
2716 2722 signal.signal(signal.SIGTERM, catchterm)
2717 2723 try:
2718 2724 signal.signal(signal.SIGHUP, catchterm)
2719 2725 except AttributeError:
2720 2726 pass
2721 2727
2722 2728 try:
2723 2729 u = ui.ui()
2724 2730 except util.Abort, inst:
2725 2731 sys.stderr.write(_("abort: %s\n") % inst)
2726 2732 sys.exit(1)
2727 2733
2728 2734 external = []
2729 2735 for x in u.extensions():
2730 2736 def on_exception(exc, inst):
2731 2737 u.warn(_("*** failed to import extension %s\n") % x[1])
2732 2738 u.warn("%s\n" % inst)
2733 2739 if "--traceback" in sys.argv[1:]:
2734 2740 traceback.print_exc()
2735 2741 if x[1]:
2736 2742 try:
2737 2743 mod = imp.load_source(x[0], x[1])
2738 2744 except Exception, inst:
2739 2745 on_exception(Exception, inst)
2740 2746 continue
2741 2747 else:
2742 2748 def importh(name):
2743 2749 mod = __import__(name)
2744 2750 components = name.split('.')
2745 2751 for comp in components[1:]:
2746 2752 mod = getattr(mod, comp)
2747 2753 return mod
2748 2754 try:
2749 2755 mod = importh(x[0])
2750 2756 except Exception, inst:
2751 2757 on_exception(Exception, inst)
2752 2758 continue
2753 2759
2754 2760 external.append(mod)
2755 2761 for x in external:
2756 2762 cmdtable = getattr(x, 'cmdtable', {})
2757 2763 for t in cmdtable:
2758 2764 if t in table:
2759 2765 u.warn(_("module %s overrides %s\n") % (x.__name__, t))
2760 2766 table.update(cmdtable)
2761 2767
2762 2768 try:
2763 2769 cmd, func, args, options, cmdoptions = parse(u, args)
2764 2770 except ParseError, inst:
2765 2771 if inst.args[0]:
2766 2772 u.warn(_("hg %s: %s\n") % (inst.args[0], inst.args[1]))
2767 2773 help_(u, inst.args[0])
2768 2774 else:
2769 2775 u.warn(_("hg: %s\n") % inst.args[1])
2770 2776 help_(u, 'shortlist')
2771 2777 sys.exit(-1)
2772 2778 except AmbiguousCommand, inst:
2773 2779 u.warn(_("hg: command '%s' is ambiguous.\n") % inst.args[0])
2774 2780 sys.exit(1)
2775 2781 except UnknownCommand, inst:
2776 2782 u.warn(_("hg: unknown command '%s'\n") % inst.args[0])
2777 2783 help_(u, 'shortlist')
2778 2784 sys.exit(1)
2779 2785
2780 2786 if options["time"]:
2781 2787 def get_times():
2782 2788 t = os.times()
2783 2789 if t[4] == 0.0: # Windows leaves this as zero, so use time.clock()
2784 2790 t = (t[0], t[1], t[2], t[3], time.clock())
2785 2791 return t
2786 2792 s = get_times()
2787 2793 def print_time():
2788 2794 t = get_times()
2789 2795 u.warn(_("Time: real %.3f secs (user %.3f+%.3f sys %.3f+%.3f)\n") %
2790 2796 (t[4]-s[4], t[0]-s[0], t[2]-s[2], t[1]-s[1], t[3]-s[3]))
2791 2797 atexit.register(print_time)
2792 2798
2793 2799 u.updateopts(options["verbose"], options["debug"], options["quiet"],
2794 2800 not options["noninteractive"])
2795 2801
2796 2802 # enter the debugger before command execution
2797 2803 if options['debugger']:
2798 2804 pdb.set_trace()
2799 2805
2800 2806 try:
2801 2807 try:
2802 2808 if options['help']:
2803 2809 help_(u, cmd, options['version'])
2804 2810 sys.exit(0)
2805 2811 elif options['version']:
2806 2812 show_version(u)
2807 2813 sys.exit(0)
2808 2814 elif not cmd:
2809 2815 help_(u, 'shortlist')
2810 2816 sys.exit(0)
2811 2817
2812 2818 if options['cwd']:
2813 2819 try:
2814 2820 os.chdir(options['cwd'])
2815 2821 except OSError, inst:
2816 2822 raise util.Abort('%s: %s' %
2817 2823 (options['cwd'], inst.strerror))
2818 2824
2819 2825 if cmd not in norepo.split():
2820 2826 path = options["repository"] or ""
2821 2827 repo = hg.repository(ui=u, path=path)
2822 2828 for x in external:
2823 2829 if hasattr(x, 'reposetup'):
2824 2830 x.reposetup(u, repo)
2825 2831 d = lambda: func(u, repo, *args, **cmdoptions)
2826 2832 else:
2827 2833 d = lambda: func(u, *args, **cmdoptions)
2828 2834
2829 2835 if options['profile']:
2830 2836 import hotshot, hotshot.stats
2831 2837 prof = hotshot.Profile("hg.prof")
2832 2838 r = prof.runcall(d)
2833 2839 prof.close()
2834 2840 stats = hotshot.stats.load("hg.prof")
2835 2841 stats.strip_dirs()
2836 2842 stats.sort_stats('time', 'calls')
2837 2843 stats.print_stats(40)
2838 2844 return r
2839 2845 else:
2840 2846 return d()
2841 2847 except:
2842 2848 # enter the debugger when we hit an exception
2843 2849 if options['debugger']:
2844 2850 pdb.post_mortem(sys.exc_info()[2])
2845 2851 if options['traceback']:
2846 2852 traceback.print_exc()
2847 2853 raise
2848 2854 except hg.RepoError, inst:
2849 2855 u.warn(_("abort: "), inst, "!\n")
2850 2856 except revlog.RevlogError, inst:
2851 2857 u.warn(_("abort: "), inst, "!\n")
2852 2858 except SignalInterrupt:
2853 2859 u.warn(_("killed!\n"))
2854 2860 except KeyboardInterrupt:
2855 2861 try:
2856 2862 u.warn(_("interrupted!\n"))
2857 2863 except IOError, inst:
2858 2864 if inst.errno == errno.EPIPE:
2859 2865 if u.debugflag:
2860 2866 u.warn(_("\nbroken pipe\n"))
2861 2867 else:
2862 2868 raise
2863 2869 except IOError, inst:
2864 2870 if hasattr(inst, "code"):
2865 2871 u.warn(_("abort: %s\n") % inst)
2866 2872 elif hasattr(inst, "reason"):
2867 2873 u.warn(_("abort: error: %s\n") % inst.reason[1])
2868 2874 elif hasattr(inst, "args") and inst[0] == errno.EPIPE:
2869 2875 if u.debugflag:
2870 2876 u.warn(_("broken pipe\n"))
2871 2877 elif getattr(inst, "strerror", None):
2872 2878 if getattr(inst, "filename", None):
2873 2879 u.warn(_("abort: %s - %s\n") % (inst.strerror, inst.filename))
2874 2880 else:
2875 2881 u.warn(_("abort: %s\n") % inst.strerror)
2876 2882 else:
2877 2883 raise
2878 2884 except OSError, inst:
2879 2885 if hasattr(inst, "filename"):
2880 2886 u.warn(_("abort: %s: %s\n") % (inst.strerror, inst.filename))
2881 2887 else:
2882 2888 u.warn(_("abort: %s\n") % inst.strerror)
2883 2889 except util.Abort, inst:
2884 2890 u.warn(_('abort: '), inst.args[0] % inst.args[1:], '\n')
2885 2891 sys.exit(1)
2886 2892 except TypeError, inst:
2887 2893 # was this an argument error?
2888 2894 tb = traceback.extract_tb(sys.exc_info()[2])
2889 2895 if len(tb) > 2: # no
2890 2896 raise
2891 2897 u.debug(inst, "\n")
2892 2898 u.warn(_("%s: invalid arguments\n") % cmd)
2893 2899 help_(u, cmd)
2894 2900 except AmbiguousCommand, inst:
2895 2901 u.warn(_("hg: command '%s' is ambiguous.\n") % inst.args[0])
2896 2902 help_(u, 'shortlist')
2897 2903 except UnknownCommand, inst:
2898 2904 u.warn(_("hg: unknown command '%s'\n") % inst.args[0])
2899 2905 help_(u, 'shortlist')
2900 2906 except SystemExit:
2901 2907 # don't catch this in the catch-all below
2902 2908 raise
2903 2909 except:
2904 2910 u.warn(_("** unknown exception encountered, details follow\n"))
2905 2911 u.warn(_("** report bug details to mercurial@selenic.com\n"))
2906 2912 u.warn(_("** Mercurial Distributed SCM (version %s)\n")
2907 2913 % version.get_version())
2908 2914 raise
2909 2915
2910 2916 sys.exit(-1)
General Comments 0
You need to be logged in to leave comments. Login now