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