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