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