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