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