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