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