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