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