##// END OF EJS Templates
forget: fix subrepo recursion for explicit path handling...
David M. Carr -
r15912:2bd54ffa default
parent child Browse files
Show More
@@ -1,1277 +1,1319 b''
1 1 # cmdutil.py - help for command processing in mercurial
2 2 #
3 3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 from node import hex, nullid, nullrev, short
9 9 from i18n import _
10 10 import os, sys, errno, re, tempfile
11 11 import util, scmutil, templater, patch, error, templatekw, revlog, copies
12 12 import match as matchmod
13 13 import subrepo
14 14
15 15 def parsealiases(cmd):
16 16 return cmd.lstrip("^").split("|")
17 17
18 18 def findpossible(cmd, table, strict=False):
19 19 """
20 20 Return cmd -> (aliases, command table entry)
21 21 for each matching command.
22 22 Return debug commands (or their aliases) only if no normal command matches.
23 23 """
24 24 choice = {}
25 25 debugchoice = {}
26 26
27 27 if cmd in table:
28 28 # short-circuit exact matches, "log" alias beats "^log|history"
29 29 keys = [cmd]
30 30 else:
31 31 keys = table.keys()
32 32
33 33 for e in keys:
34 34 aliases = parsealiases(e)
35 35 found = None
36 36 if cmd in aliases:
37 37 found = cmd
38 38 elif not strict:
39 39 for a in aliases:
40 40 if a.startswith(cmd):
41 41 found = a
42 42 break
43 43 if found is not None:
44 44 if aliases[0].startswith("debug") or found.startswith("debug"):
45 45 debugchoice[found] = (aliases, table[e])
46 46 else:
47 47 choice[found] = (aliases, table[e])
48 48
49 49 if not choice and debugchoice:
50 50 choice = debugchoice
51 51
52 52 return choice
53 53
54 54 def findcmd(cmd, table, strict=True):
55 55 """Return (aliases, command table entry) for command string."""
56 56 choice = findpossible(cmd, table, strict)
57 57
58 58 if cmd in choice:
59 59 return choice[cmd]
60 60
61 61 if len(choice) > 1:
62 62 clist = choice.keys()
63 63 clist.sort()
64 64 raise error.AmbiguousCommand(cmd, clist)
65 65
66 66 if choice:
67 67 return choice.values()[0]
68 68
69 69 raise error.UnknownCommand(cmd)
70 70
71 71 def findrepo(p):
72 72 while not os.path.isdir(os.path.join(p, ".hg")):
73 73 oldp, p = p, os.path.dirname(p)
74 74 if p == oldp:
75 75 return None
76 76
77 77 return p
78 78
79 79 def bailifchanged(repo):
80 80 if repo.dirstate.p2() != nullid:
81 81 raise util.Abort(_('outstanding uncommitted merge'))
82 82 modified, added, removed, deleted = repo.status()[:4]
83 83 if modified or added or removed or deleted:
84 84 raise util.Abort(_("outstanding uncommitted changes"))
85 85 ctx = repo[None]
86 86 for s in ctx.substate:
87 87 if ctx.sub(s).dirty():
88 88 raise util.Abort(_("uncommitted changes in subrepo %s") % s)
89 89
90 90 def logmessage(ui, opts):
91 91 """ get the log message according to -m and -l option """
92 92 message = opts.get('message')
93 93 logfile = opts.get('logfile')
94 94
95 95 if message and logfile:
96 96 raise util.Abort(_('options --message and --logfile are mutually '
97 97 'exclusive'))
98 98 if not message and logfile:
99 99 try:
100 100 if logfile == '-':
101 101 message = ui.fin.read()
102 102 else:
103 103 message = '\n'.join(util.readfile(logfile).splitlines())
104 104 except IOError, inst:
105 105 raise util.Abort(_("can't read commit message '%s': %s") %
106 106 (logfile, inst.strerror))
107 107 return message
108 108
109 109 def loglimit(opts):
110 110 """get the log limit according to option -l/--limit"""
111 111 limit = opts.get('limit')
112 112 if limit:
113 113 try:
114 114 limit = int(limit)
115 115 except ValueError:
116 116 raise util.Abort(_('limit must be a positive integer'))
117 117 if limit <= 0:
118 118 raise util.Abort(_('limit must be positive'))
119 119 else:
120 120 limit = None
121 121 return limit
122 122
123 123 def makefilename(repo, pat, node, desc=None,
124 124 total=None, seqno=None, revwidth=None, pathname=None):
125 125 node_expander = {
126 126 'H': lambda: hex(node),
127 127 'R': lambda: str(repo.changelog.rev(node)),
128 128 'h': lambda: short(node),
129 129 'm': lambda: re.sub('[^\w]', '_', str(desc))
130 130 }
131 131 expander = {
132 132 '%': lambda: '%',
133 133 'b': lambda: os.path.basename(repo.root),
134 134 }
135 135
136 136 try:
137 137 if node:
138 138 expander.update(node_expander)
139 139 if node:
140 140 expander['r'] = (lambda:
141 141 str(repo.changelog.rev(node)).zfill(revwidth or 0))
142 142 if total is not None:
143 143 expander['N'] = lambda: str(total)
144 144 if seqno is not None:
145 145 expander['n'] = lambda: str(seqno)
146 146 if total is not None and seqno is not None:
147 147 expander['n'] = lambda: str(seqno).zfill(len(str(total)))
148 148 if pathname is not None:
149 149 expander['s'] = lambda: os.path.basename(pathname)
150 150 expander['d'] = lambda: os.path.dirname(pathname) or '.'
151 151 expander['p'] = lambda: pathname
152 152
153 153 newname = []
154 154 patlen = len(pat)
155 155 i = 0
156 156 while i < patlen:
157 157 c = pat[i]
158 158 if c == '%':
159 159 i += 1
160 160 c = pat[i]
161 161 c = expander[c]()
162 162 newname.append(c)
163 163 i += 1
164 164 return ''.join(newname)
165 165 except KeyError, inst:
166 166 raise util.Abort(_("invalid format spec '%%%s' in output filename") %
167 167 inst.args[0])
168 168
169 169 def makefileobj(repo, pat, node=None, desc=None, total=None,
170 170 seqno=None, revwidth=None, mode='wb', pathname=None):
171 171
172 172 writable = mode not in ('r', 'rb')
173 173
174 174 if not pat or pat == '-':
175 175 fp = writable and repo.ui.fout or repo.ui.fin
176 176 if util.safehasattr(fp, 'fileno'):
177 177 return os.fdopen(os.dup(fp.fileno()), mode)
178 178 else:
179 179 # if this fp can't be duped properly, return
180 180 # a dummy object that can be closed
181 181 class wrappedfileobj(object):
182 182 noop = lambda x: None
183 183 def __init__(self, f):
184 184 self.f = f
185 185 def __getattr__(self, attr):
186 186 if attr == 'close':
187 187 return self.noop
188 188 else:
189 189 return getattr(self.f, attr)
190 190
191 191 return wrappedfileobj(fp)
192 192 if util.safehasattr(pat, 'write') and writable:
193 193 return pat
194 194 if util.safehasattr(pat, 'read') and 'r' in mode:
195 195 return pat
196 196 return open(makefilename(repo, pat, node, desc, total, seqno, revwidth,
197 197 pathname),
198 198 mode)
199 199
200 200 def openrevlog(repo, cmd, file_, opts):
201 201 """opens the changelog, manifest, a filelog or a given revlog"""
202 202 cl = opts['changelog']
203 203 mf = opts['manifest']
204 204 msg = None
205 205 if cl and mf:
206 206 msg = _('cannot specify --changelog and --manifest at the same time')
207 207 elif cl or mf:
208 208 if file_:
209 209 msg = _('cannot specify filename with --changelog or --manifest')
210 210 elif not repo:
211 211 msg = _('cannot specify --changelog or --manifest '
212 212 'without a repository')
213 213 if msg:
214 214 raise util.Abort(msg)
215 215
216 216 r = None
217 217 if repo:
218 218 if cl:
219 219 r = repo.changelog
220 220 elif mf:
221 221 r = repo.manifest
222 222 elif file_:
223 223 filelog = repo.file(file_)
224 224 if len(filelog):
225 225 r = filelog
226 226 if not r:
227 227 if not file_:
228 228 raise error.CommandError(cmd, _('invalid arguments'))
229 229 if not os.path.isfile(file_):
230 230 raise util.Abort(_("revlog '%s' not found") % file_)
231 231 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False),
232 232 file_[:-2] + ".i")
233 233 return r
234 234
235 235 def copy(ui, repo, pats, opts, rename=False):
236 236 # called with the repo lock held
237 237 #
238 238 # hgsep => pathname that uses "/" to separate directories
239 239 # ossep => pathname that uses os.sep to separate directories
240 240 cwd = repo.getcwd()
241 241 targets = {}
242 242 after = opts.get("after")
243 243 dryrun = opts.get("dry_run")
244 244 wctx = repo[None]
245 245
246 246 def walkpat(pat):
247 247 srcs = []
248 248 badstates = after and '?' or '?r'
249 249 m = scmutil.match(repo[None], [pat], opts, globbed=True)
250 250 for abs in repo.walk(m):
251 251 state = repo.dirstate[abs]
252 252 rel = m.rel(abs)
253 253 exact = m.exact(abs)
254 254 if state in badstates:
255 255 if exact and state == '?':
256 256 ui.warn(_('%s: not copying - file is not managed\n') % rel)
257 257 if exact and state == 'r':
258 258 ui.warn(_('%s: not copying - file has been marked for'
259 259 ' remove\n') % rel)
260 260 continue
261 261 # abs: hgsep
262 262 # rel: ossep
263 263 srcs.append((abs, rel, exact))
264 264 return srcs
265 265
266 266 # abssrc: hgsep
267 267 # relsrc: ossep
268 268 # otarget: ossep
269 269 def copyfile(abssrc, relsrc, otarget, exact):
270 270 abstarget = scmutil.canonpath(repo.root, cwd, otarget)
271 271 reltarget = repo.pathto(abstarget, cwd)
272 272 target = repo.wjoin(abstarget)
273 273 src = repo.wjoin(abssrc)
274 274 state = repo.dirstate[abstarget]
275 275
276 276 scmutil.checkportable(ui, abstarget)
277 277
278 278 # check for collisions
279 279 prevsrc = targets.get(abstarget)
280 280 if prevsrc is not None:
281 281 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
282 282 (reltarget, repo.pathto(abssrc, cwd),
283 283 repo.pathto(prevsrc, cwd)))
284 284 return
285 285
286 286 # check for overwrites
287 287 exists = os.path.lexists(target)
288 288 if not after and exists or after and state in 'mn':
289 289 if not opts['force']:
290 290 ui.warn(_('%s: not overwriting - file exists\n') %
291 291 reltarget)
292 292 return
293 293
294 294 if after:
295 295 if not exists:
296 296 if rename:
297 297 ui.warn(_('%s: not recording move - %s does not exist\n') %
298 298 (relsrc, reltarget))
299 299 else:
300 300 ui.warn(_('%s: not recording copy - %s does not exist\n') %
301 301 (relsrc, reltarget))
302 302 return
303 303 elif not dryrun:
304 304 try:
305 305 if exists:
306 306 os.unlink(target)
307 307 targetdir = os.path.dirname(target) or '.'
308 308 if not os.path.isdir(targetdir):
309 309 os.makedirs(targetdir)
310 310 util.copyfile(src, target)
311 311 srcexists = True
312 312 except IOError, inst:
313 313 if inst.errno == errno.ENOENT:
314 314 ui.warn(_('%s: deleted in working copy\n') % relsrc)
315 315 srcexists = False
316 316 else:
317 317 ui.warn(_('%s: cannot copy - %s\n') %
318 318 (relsrc, inst.strerror))
319 319 return True # report a failure
320 320
321 321 if ui.verbose or not exact:
322 322 if rename:
323 323 ui.status(_('moving %s to %s\n') % (relsrc, reltarget))
324 324 else:
325 325 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
326 326
327 327 targets[abstarget] = abssrc
328 328
329 329 # fix up dirstate
330 330 scmutil.dirstatecopy(ui, repo, wctx, abssrc, abstarget,
331 331 dryrun=dryrun, cwd=cwd)
332 332 if rename and not dryrun:
333 333 if not after and srcexists:
334 334 util.unlinkpath(repo.wjoin(abssrc))
335 335 wctx.forget([abssrc])
336 336
337 337 # pat: ossep
338 338 # dest ossep
339 339 # srcs: list of (hgsep, hgsep, ossep, bool)
340 340 # return: function that takes hgsep and returns ossep
341 341 def targetpathfn(pat, dest, srcs):
342 342 if os.path.isdir(pat):
343 343 abspfx = scmutil.canonpath(repo.root, cwd, pat)
344 344 abspfx = util.localpath(abspfx)
345 345 if destdirexists:
346 346 striplen = len(os.path.split(abspfx)[0])
347 347 else:
348 348 striplen = len(abspfx)
349 349 if striplen:
350 350 striplen += len(os.sep)
351 351 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
352 352 elif destdirexists:
353 353 res = lambda p: os.path.join(dest,
354 354 os.path.basename(util.localpath(p)))
355 355 else:
356 356 res = lambda p: dest
357 357 return res
358 358
359 359 # pat: ossep
360 360 # dest ossep
361 361 # srcs: list of (hgsep, hgsep, ossep, bool)
362 362 # return: function that takes hgsep and returns ossep
363 363 def targetpathafterfn(pat, dest, srcs):
364 364 if matchmod.patkind(pat):
365 365 # a mercurial pattern
366 366 res = lambda p: os.path.join(dest,
367 367 os.path.basename(util.localpath(p)))
368 368 else:
369 369 abspfx = scmutil.canonpath(repo.root, cwd, pat)
370 370 if len(abspfx) < len(srcs[0][0]):
371 371 # A directory. Either the target path contains the last
372 372 # component of the source path or it does not.
373 373 def evalpath(striplen):
374 374 score = 0
375 375 for s in srcs:
376 376 t = os.path.join(dest, util.localpath(s[0])[striplen:])
377 377 if os.path.lexists(t):
378 378 score += 1
379 379 return score
380 380
381 381 abspfx = util.localpath(abspfx)
382 382 striplen = len(abspfx)
383 383 if striplen:
384 384 striplen += len(os.sep)
385 385 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
386 386 score = evalpath(striplen)
387 387 striplen1 = len(os.path.split(abspfx)[0])
388 388 if striplen1:
389 389 striplen1 += len(os.sep)
390 390 if evalpath(striplen1) > score:
391 391 striplen = striplen1
392 392 res = lambda p: os.path.join(dest,
393 393 util.localpath(p)[striplen:])
394 394 else:
395 395 # a file
396 396 if destdirexists:
397 397 res = lambda p: os.path.join(dest,
398 398 os.path.basename(util.localpath(p)))
399 399 else:
400 400 res = lambda p: dest
401 401 return res
402 402
403 403
404 404 pats = scmutil.expandpats(pats)
405 405 if not pats:
406 406 raise util.Abort(_('no source or destination specified'))
407 407 if len(pats) == 1:
408 408 raise util.Abort(_('no destination specified'))
409 409 dest = pats.pop()
410 410 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
411 411 if not destdirexists:
412 412 if len(pats) > 1 or matchmod.patkind(pats[0]):
413 413 raise util.Abort(_('with multiple sources, destination must be an '
414 414 'existing directory'))
415 415 if util.endswithsep(dest):
416 416 raise util.Abort(_('destination %s is not a directory') % dest)
417 417
418 418 tfn = targetpathfn
419 419 if after:
420 420 tfn = targetpathafterfn
421 421 copylist = []
422 422 for pat in pats:
423 423 srcs = walkpat(pat)
424 424 if not srcs:
425 425 continue
426 426 copylist.append((tfn(pat, dest, srcs), srcs))
427 427 if not copylist:
428 428 raise util.Abort(_('no files to copy'))
429 429
430 430 errors = 0
431 431 for targetpath, srcs in copylist:
432 432 for abssrc, relsrc, exact in srcs:
433 433 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
434 434 errors += 1
435 435
436 436 if errors:
437 437 ui.warn(_('(consider using --after)\n'))
438 438
439 439 return errors != 0
440 440
441 441 def service(opts, parentfn=None, initfn=None, runfn=None, logfile=None,
442 442 runargs=None, appendpid=False):
443 443 '''Run a command as a service.'''
444 444
445 445 if opts['daemon'] and not opts['daemon_pipefds']:
446 446 # Signal child process startup with file removal
447 447 lockfd, lockpath = tempfile.mkstemp(prefix='hg-service-')
448 448 os.close(lockfd)
449 449 try:
450 450 if not runargs:
451 451 runargs = util.hgcmd() + sys.argv[1:]
452 452 runargs.append('--daemon-pipefds=%s' % lockpath)
453 453 # Don't pass --cwd to the child process, because we've already
454 454 # changed directory.
455 455 for i in xrange(1, len(runargs)):
456 456 if runargs[i].startswith('--cwd='):
457 457 del runargs[i]
458 458 break
459 459 elif runargs[i].startswith('--cwd'):
460 460 del runargs[i:i + 2]
461 461 break
462 462 def condfn():
463 463 return not os.path.exists(lockpath)
464 464 pid = util.rundetached(runargs, condfn)
465 465 if pid < 0:
466 466 raise util.Abort(_('child process failed to start'))
467 467 finally:
468 468 try:
469 469 os.unlink(lockpath)
470 470 except OSError, e:
471 471 if e.errno != errno.ENOENT:
472 472 raise
473 473 if parentfn:
474 474 return parentfn(pid)
475 475 else:
476 476 return
477 477
478 478 if initfn:
479 479 initfn()
480 480
481 481 if opts['pid_file']:
482 482 mode = appendpid and 'a' or 'w'
483 483 fp = open(opts['pid_file'], mode)
484 484 fp.write(str(os.getpid()) + '\n')
485 485 fp.close()
486 486
487 487 if opts['daemon_pipefds']:
488 488 lockpath = opts['daemon_pipefds']
489 489 try:
490 490 os.setsid()
491 491 except AttributeError:
492 492 pass
493 493 os.unlink(lockpath)
494 494 util.hidewindow()
495 495 sys.stdout.flush()
496 496 sys.stderr.flush()
497 497
498 498 nullfd = os.open(util.nulldev, os.O_RDWR)
499 499 logfilefd = nullfd
500 500 if logfile:
501 501 logfilefd = os.open(logfile, os.O_RDWR | os.O_CREAT | os.O_APPEND)
502 502 os.dup2(nullfd, 0)
503 503 os.dup2(logfilefd, 1)
504 504 os.dup2(logfilefd, 2)
505 505 if nullfd not in (0, 1, 2):
506 506 os.close(nullfd)
507 507 if logfile and logfilefd not in (0, 1, 2):
508 508 os.close(logfilefd)
509 509
510 510 if runfn:
511 511 return runfn()
512 512
513 513 def export(repo, revs, template='hg-%h.patch', fp=None, switch_parent=False,
514 514 opts=None):
515 515 '''export changesets as hg patches.'''
516 516
517 517 total = len(revs)
518 518 revwidth = max([len(str(rev)) for rev in revs])
519 519
520 520 def single(rev, seqno, fp):
521 521 ctx = repo[rev]
522 522 node = ctx.node()
523 523 parents = [p.node() for p in ctx.parents() if p]
524 524 branch = ctx.branch()
525 525 if switch_parent:
526 526 parents.reverse()
527 527 prev = (parents and parents[0]) or nullid
528 528
529 529 shouldclose = False
530 530 if not fp:
531 531 desc_lines = ctx.description().rstrip().split('\n')
532 532 desc = desc_lines[0] #Commit always has a first line.
533 533 fp = makefileobj(repo, template, node, desc=desc, total=total,
534 534 seqno=seqno, revwidth=revwidth, mode='ab')
535 535 if fp != template:
536 536 shouldclose = True
537 537 if fp != sys.stdout and util.safehasattr(fp, 'name'):
538 538 repo.ui.note("%s\n" % fp.name)
539 539
540 540 fp.write("# HG changeset patch\n")
541 541 fp.write("# User %s\n" % ctx.user())
542 542 fp.write("# Date %d %d\n" % ctx.date())
543 543 if branch and branch != 'default':
544 544 fp.write("# Branch %s\n" % branch)
545 545 fp.write("# Node ID %s\n" % hex(node))
546 546 fp.write("# Parent %s\n" % hex(prev))
547 547 if len(parents) > 1:
548 548 fp.write("# Parent %s\n" % hex(parents[1]))
549 549 fp.write(ctx.description().rstrip())
550 550 fp.write("\n\n")
551 551
552 552 for chunk in patch.diff(repo, prev, node, opts=opts):
553 553 fp.write(chunk)
554 554
555 555 if shouldclose:
556 556 fp.close()
557 557
558 558 for seqno, rev in enumerate(revs):
559 559 single(rev, seqno + 1, fp)
560 560
561 561 def diffordiffstat(ui, repo, diffopts, node1, node2, match,
562 562 changes=None, stat=False, fp=None, prefix='',
563 563 listsubrepos=False):
564 564 '''show diff or diffstat.'''
565 565 if fp is None:
566 566 write = ui.write
567 567 else:
568 568 def write(s, **kw):
569 569 fp.write(s)
570 570
571 571 if stat:
572 572 diffopts = diffopts.copy(context=0)
573 573 width = 80
574 574 if not ui.plain():
575 575 width = ui.termwidth()
576 576 chunks = patch.diff(repo, node1, node2, match, changes, diffopts,
577 577 prefix=prefix)
578 578 for chunk, label in patch.diffstatui(util.iterlines(chunks),
579 579 width=width,
580 580 git=diffopts.git):
581 581 write(chunk, label=label)
582 582 else:
583 583 for chunk, label in patch.diffui(repo, node1, node2, match,
584 584 changes, diffopts, prefix=prefix):
585 585 write(chunk, label=label)
586 586
587 587 if listsubrepos:
588 588 ctx1 = repo[node1]
589 589 ctx2 = repo[node2]
590 590 for subpath, sub in subrepo.itersubrepos(ctx1, ctx2):
591 591 tempnode2 = node2
592 592 try:
593 593 if node2 is not None:
594 594 tempnode2 = ctx2.substate[subpath][1]
595 595 except KeyError:
596 596 # A subrepo that existed in node1 was deleted between node1 and
597 597 # node2 (inclusive). Thus, ctx2's substate won't contain that
598 598 # subpath. The best we can do is to ignore it.
599 599 tempnode2 = None
600 600 submatch = matchmod.narrowmatcher(subpath, match)
601 601 sub.diff(diffopts, tempnode2, submatch, changes=changes,
602 602 stat=stat, fp=fp, prefix=prefix)
603 603
604 604 class changeset_printer(object):
605 605 '''show changeset information when templating not requested.'''
606 606
607 607 def __init__(self, ui, repo, patch, diffopts, buffered):
608 608 self.ui = ui
609 609 self.repo = repo
610 610 self.buffered = buffered
611 611 self.patch = patch
612 612 self.diffopts = diffopts
613 613 self.header = {}
614 614 self.hunk = {}
615 615 self.lastheader = None
616 616 self.footer = None
617 617
618 618 def flush(self, rev):
619 619 if rev in self.header:
620 620 h = self.header[rev]
621 621 if h != self.lastheader:
622 622 self.lastheader = h
623 623 self.ui.write(h)
624 624 del self.header[rev]
625 625 if rev in self.hunk:
626 626 self.ui.write(self.hunk[rev])
627 627 del self.hunk[rev]
628 628 return 1
629 629 return 0
630 630
631 631 def close(self):
632 632 if self.footer:
633 633 self.ui.write(self.footer)
634 634
635 635 def show(self, ctx, copies=None, matchfn=None, **props):
636 636 if self.buffered:
637 637 self.ui.pushbuffer()
638 638 self._show(ctx, copies, matchfn, props)
639 639 self.hunk[ctx.rev()] = self.ui.popbuffer(labeled=True)
640 640 else:
641 641 self._show(ctx, copies, matchfn, props)
642 642
643 643 def _show(self, ctx, copies, matchfn, props):
644 644 '''show a single changeset or file revision'''
645 645 changenode = ctx.node()
646 646 rev = ctx.rev()
647 647
648 648 if self.ui.quiet:
649 649 self.ui.write("%d:%s\n" % (rev, short(changenode)),
650 650 label='log.node')
651 651 return
652 652
653 653 log = self.repo.changelog
654 654 date = util.datestr(ctx.date())
655 655
656 656 hexfunc = self.ui.debugflag and hex or short
657 657
658 658 parents = [(p, hexfunc(log.node(p)))
659 659 for p in self._meaningful_parentrevs(log, rev)]
660 660
661 661 self.ui.write(_("changeset: %d:%s\n") % (rev, hexfunc(changenode)),
662 662 label='log.changeset')
663 663
664 664 branch = ctx.branch()
665 665 # don't show the default branch name
666 666 if branch != 'default':
667 667 self.ui.write(_("branch: %s\n") % branch,
668 668 label='log.branch')
669 669 for bookmark in self.repo.nodebookmarks(changenode):
670 670 self.ui.write(_("bookmark: %s\n") % bookmark,
671 671 label='log.bookmark')
672 672 for tag in self.repo.nodetags(changenode):
673 673 self.ui.write(_("tag: %s\n") % tag,
674 674 label='log.tag')
675 675 if self.ui.debugflag and ctx.phase():
676 676 self.ui.write(_("phase: %s\n") % _(ctx.phasestr()),
677 677 label='log.phase')
678 678 for parent in parents:
679 679 self.ui.write(_("parent: %d:%s\n") % parent,
680 680 label='log.parent')
681 681
682 682 if self.ui.debugflag:
683 683 mnode = ctx.manifestnode()
684 684 self.ui.write(_("manifest: %d:%s\n") %
685 685 (self.repo.manifest.rev(mnode), hex(mnode)),
686 686 label='ui.debug log.manifest')
687 687 self.ui.write(_("user: %s\n") % ctx.user(),
688 688 label='log.user')
689 689 self.ui.write(_("date: %s\n") % date,
690 690 label='log.date')
691 691
692 692 if self.ui.debugflag:
693 693 files = self.repo.status(log.parents(changenode)[0], changenode)[:3]
694 694 for key, value in zip([_("files:"), _("files+:"), _("files-:")],
695 695 files):
696 696 if value:
697 697 self.ui.write("%-12s %s\n" % (key, " ".join(value)),
698 698 label='ui.debug log.files')
699 699 elif ctx.files() and self.ui.verbose:
700 700 self.ui.write(_("files: %s\n") % " ".join(ctx.files()),
701 701 label='ui.note log.files')
702 702 if copies and self.ui.verbose:
703 703 copies = ['%s (%s)' % c for c in copies]
704 704 self.ui.write(_("copies: %s\n") % ' '.join(copies),
705 705 label='ui.note log.copies')
706 706
707 707 extra = ctx.extra()
708 708 if extra and self.ui.debugflag:
709 709 for key, value in sorted(extra.items()):
710 710 self.ui.write(_("extra: %s=%s\n")
711 711 % (key, value.encode('string_escape')),
712 712 label='ui.debug log.extra')
713 713
714 714 description = ctx.description().strip()
715 715 if description:
716 716 if self.ui.verbose:
717 717 self.ui.write(_("description:\n"),
718 718 label='ui.note log.description')
719 719 self.ui.write(description,
720 720 label='ui.note log.description')
721 721 self.ui.write("\n\n")
722 722 else:
723 723 self.ui.write(_("summary: %s\n") %
724 724 description.splitlines()[0],
725 725 label='log.summary')
726 726 self.ui.write("\n")
727 727
728 728 self.showpatch(changenode, matchfn)
729 729
730 730 def showpatch(self, node, matchfn):
731 731 if not matchfn:
732 732 matchfn = self.patch
733 733 if matchfn:
734 734 stat = self.diffopts.get('stat')
735 735 diff = self.diffopts.get('patch')
736 736 diffopts = patch.diffopts(self.ui, self.diffopts)
737 737 prev = self.repo.changelog.parents(node)[0]
738 738 if stat:
739 739 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
740 740 match=matchfn, stat=True)
741 741 if diff:
742 742 if stat:
743 743 self.ui.write("\n")
744 744 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
745 745 match=matchfn, stat=False)
746 746 self.ui.write("\n")
747 747
748 748 def _meaningful_parentrevs(self, log, rev):
749 749 """Return list of meaningful (or all if debug) parentrevs for rev.
750 750
751 751 For merges (two non-nullrev revisions) both parents are meaningful.
752 752 Otherwise the first parent revision is considered meaningful if it
753 753 is not the preceding revision.
754 754 """
755 755 parents = log.parentrevs(rev)
756 756 if not self.ui.debugflag and parents[1] == nullrev:
757 757 if parents[0] >= rev - 1:
758 758 parents = []
759 759 else:
760 760 parents = [parents[0]]
761 761 return parents
762 762
763 763
764 764 class changeset_templater(changeset_printer):
765 765 '''format changeset information.'''
766 766
767 767 def __init__(self, ui, repo, patch, diffopts, mapfile, buffered):
768 768 changeset_printer.__init__(self, ui, repo, patch, diffopts, buffered)
769 769 formatnode = ui.debugflag and (lambda x: x) or (lambda x: x[:12])
770 770 defaulttempl = {
771 771 'parent': '{rev}:{node|formatnode} ',
772 772 'manifest': '{rev}:{node|formatnode}',
773 773 'file_copy': '{name} ({source})',
774 774 'extra': '{key}={value|stringescape}'
775 775 }
776 776 # filecopy is preserved for compatibility reasons
777 777 defaulttempl['filecopy'] = defaulttempl['file_copy']
778 778 self.t = templater.templater(mapfile, {'formatnode': formatnode},
779 779 cache=defaulttempl)
780 780 self.cache = {}
781 781
782 782 def use_template(self, t):
783 783 '''set template string to use'''
784 784 self.t.cache['changeset'] = t
785 785
786 786 def _meaningful_parentrevs(self, ctx):
787 787 """Return list of meaningful (or all if debug) parentrevs for rev.
788 788 """
789 789 parents = ctx.parents()
790 790 if len(parents) > 1:
791 791 return parents
792 792 if self.ui.debugflag:
793 793 return [parents[0], self.repo['null']]
794 794 if parents[0].rev() >= ctx.rev() - 1:
795 795 return []
796 796 return parents
797 797
798 798 def _show(self, ctx, copies, matchfn, props):
799 799 '''show a single changeset or file revision'''
800 800
801 801 showlist = templatekw.showlist
802 802
803 803 # showparents() behaviour depends on ui trace level which
804 804 # causes unexpected behaviours at templating level and makes
805 805 # it harder to extract it in a standalone function. Its
806 806 # behaviour cannot be changed so leave it here for now.
807 807 def showparents(**args):
808 808 ctx = args['ctx']
809 809 parents = [[('rev', p.rev()), ('node', p.hex())]
810 810 for p in self._meaningful_parentrevs(ctx)]
811 811 return showlist('parent', parents, **args)
812 812
813 813 props = props.copy()
814 814 props.update(templatekw.keywords)
815 815 props['parents'] = showparents
816 816 props['templ'] = self.t
817 817 props['ctx'] = ctx
818 818 props['repo'] = self.repo
819 819 props['revcache'] = {'copies': copies}
820 820 props['cache'] = self.cache
821 821
822 822 # find correct templates for current mode
823 823
824 824 tmplmodes = [
825 825 (True, None),
826 826 (self.ui.verbose, 'verbose'),
827 827 (self.ui.quiet, 'quiet'),
828 828 (self.ui.debugflag, 'debug'),
829 829 ]
830 830
831 831 types = {'header': '', 'footer':'', 'changeset': 'changeset'}
832 832 for mode, postfix in tmplmodes:
833 833 for type in types:
834 834 cur = postfix and ('%s_%s' % (type, postfix)) or type
835 835 if mode and cur in self.t:
836 836 types[type] = cur
837 837
838 838 try:
839 839
840 840 # write header
841 841 if types['header']:
842 842 h = templater.stringify(self.t(types['header'], **props))
843 843 if self.buffered:
844 844 self.header[ctx.rev()] = h
845 845 else:
846 846 if self.lastheader != h:
847 847 self.lastheader = h
848 848 self.ui.write(h)
849 849
850 850 # write changeset metadata, then patch if requested
851 851 key = types['changeset']
852 852 self.ui.write(templater.stringify(self.t(key, **props)))
853 853 self.showpatch(ctx.node(), matchfn)
854 854
855 855 if types['footer']:
856 856 if not self.footer:
857 857 self.footer = templater.stringify(self.t(types['footer'],
858 858 **props))
859 859
860 860 except KeyError, inst:
861 861 msg = _("%s: no key named '%s'")
862 862 raise util.Abort(msg % (self.t.mapfile, inst.args[0]))
863 863 except SyntaxError, inst:
864 864 raise util.Abort('%s: %s' % (self.t.mapfile, inst.args[0]))
865 865
866 866 def show_changeset(ui, repo, opts, buffered=False):
867 867 """show one changeset using template or regular display.
868 868
869 869 Display format will be the first non-empty hit of:
870 870 1. option 'template'
871 871 2. option 'style'
872 872 3. [ui] setting 'logtemplate'
873 873 4. [ui] setting 'style'
874 874 If all of these values are either the unset or the empty string,
875 875 regular display via changeset_printer() is done.
876 876 """
877 877 # options
878 878 patch = False
879 879 if opts.get('patch') or opts.get('stat'):
880 880 patch = scmutil.matchall(repo)
881 881
882 882 tmpl = opts.get('template')
883 883 style = None
884 884 if tmpl:
885 885 tmpl = templater.parsestring(tmpl, quoted=False)
886 886 else:
887 887 style = opts.get('style')
888 888
889 889 # ui settings
890 890 if not (tmpl or style):
891 891 tmpl = ui.config('ui', 'logtemplate')
892 892 if tmpl:
893 893 tmpl = templater.parsestring(tmpl)
894 894 else:
895 895 style = util.expandpath(ui.config('ui', 'style', ''))
896 896
897 897 if not (tmpl or style):
898 898 return changeset_printer(ui, repo, patch, opts, buffered)
899 899
900 900 mapfile = None
901 901 if style and not tmpl:
902 902 mapfile = style
903 903 if not os.path.split(mapfile)[0]:
904 904 mapname = (templater.templatepath('map-cmdline.' + mapfile)
905 905 or templater.templatepath(mapfile))
906 906 if mapname:
907 907 mapfile = mapname
908 908
909 909 try:
910 910 t = changeset_templater(ui, repo, patch, opts, mapfile, buffered)
911 911 except SyntaxError, inst:
912 912 raise util.Abort(inst.args[0])
913 913 if tmpl:
914 914 t.use_template(tmpl)
915 915 return t
916 916
917 917 def finddate(ui, repo, date):
918 918 """Find the tipmost changeset that matches the given date spec"""
919 919
920 920 df = util.matchdate(date)
921 921 m = scmutil.matchall(repo)
922 922 results = {}
923 923
924 924 def prep(ctx, fns):
925 925 d = ctx.date()
926 926 if df(d[0]):
927 927 results[ctx.rev()] = d
928 928
929 929 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
930 930 rev = ctx.rev()
931 931 if rev in results:
932 932 ui.status(_("Found revision %s from %s\n") %
933 933 (rev, util.datestr(results[rev])))
934 934 return str(rev)
935 935
936 936 raise util.Abort(_("revision matching date not found"))
937 937
938 938 def walkchangerevs(repo, match, opts, prepare):
939 939 '''Iterate over files and the revs in which they changed.
940 940
941 941 Callers most commonly need to iterate backwards over the history
942 942 in which they are interested. Doing so has awful (quadratic-looking)
943 943 performance, so we use iterators in a "windowed" way.
944 944
945 945 We walk a window of revisions in the desired order. Within the
946 946 window, we first walk forwards to gather data, then in the desired
947 947 order (usually backwards) to display it.
948 948
949 949 This function returns an iterator yielding contexts. Before
950 950 yielding each context, the iterator will first call the prepare
951 951 function on each context in the window in forward order.'''
952 952
953 953 def increasing_windows(start, end, windowsize=8, sizelimit=512):
954 954 if start < end:
955 955 while start < end:
956 956 yield start, min(windowsize, end - start)
957 957 start += windowsize
958 958 if windowsize < sizelimit:
959 959 windowsize *= 2
960 960 else:
961 961 while start > end:
962 962 yield start, min(windowsize, start - end - 1)
963 963 start -= windowsize
964 964 if windowsize < sizelimit:
965 965 windowsize *= 2
966 966
967 967 follow = opts.get('follow') or opts.get('follow_first')
968 968
969 969 if not len(repo):
970 970 return []
971 971
972 972 if follow:
973 973 defrange = '%s:0' % repo['.'].rev()
974 974 else:
975 975 defrange = '-1:0'
976 976 revs = scmutil.revrange(repo, opts['rev'] or [defrange])
977 977 if not revs:
978 978 return []
979 979 wanted = set()
980 980 slowpath = match.anypats() or (match.files() and opts.get('removed'))
981 981 fncache = {}
982 982 change = util.cachefunc(repo.changectx)
983 983
984 984 # First step is to fill wanted, the set of revisions that we want to yield.
985 985 # When it does not induce extra cost, we also fill fncache for revisions in
986 986 # wanted: a cache of filenames that were changed (ctx.files()) and that
987 987 # match the file filtering conditions.
988 988
989 989 if not slowpath and not match.files():
990 990 # No files, no patterns. Display all revs.
991 991 wanted = set(revs)
992 992 copies = []
993 993
994 994 if not slowpath:
995 995 # We only have to read through the filelog to find wanted revisions
996 996
997 997 minrev, maxrev = min(revs), max(revs)
998 998 def filerevgen(filelog, last):
999 999 """
1000 1000 Only files, no patterns. Check the history of each file.
1001 1001
1002 1002 Examines filelog entries within minrev, maxrev linkrev range
1003 1003 Returns an iterator yielding (linkrev, parentlinkrevs, copied)
1004 1004 tuples in backwards order
1005 1005 """
1006 1006 cl_count = len(repo)
1007 1007 revs = []
1008 1008 for j in xrange(0, last + 1):
1009 1009 linkrev = filelog.linkrev(j)
1010 1010 if linkrev < minrev:
1011 1011 continue
1012 1012 # only yield rev for which we have the changelog, it can
1013 1013 # happen while doing "hg log" during a pull or commit
1014 1014 if linkrev >= cl_count:
1015 1015 break
1016 1016
1017 1017 parentlinkrevs = []
1018 1018 for p in filelog.parentrevs(j):
1019 1019 if p != nullrev:
1020 1020 parentlinkrevs.append(filelog.linkrev(p))
1021 1021 n = filelog.node(j)
1022 1022 revs.append((linkrev, parentlinkrevs,
1023 1023 follow and filelog.renamed(n)))
1024 1024
1025 1025 return reversed(revs)
1026 1026 def iterfiles():
1027 1027 for filename in match.files():
1028 1028 yield filename, None
1029 1029 for filename_node in copies:
1030 1030 yield filename_node
1031 1031 for file_, node in iterfiles():
1032 1032 filelog = repo.file(file_)
1033 1033 if not len(filelog):
1034 1034 if node is None:
1035 1035 # A zero count may be a directory or deleted file, so
1036 1036 # try to find matching entries on the slow path.
1037 1037 if follow:
1038 1038 raise util.Abort(
1039 1039 _('cannot follow nonexistent file: "%s"') % file_)
1040 1040 slowpath = True
1041 1041 break
1042 1042 else:
1043 1043 continue
1044 1044
1045 1045 if node is None:
1046 1046 last = len(filelog) - 1
1047 1047 else:
1048 1048 last = filelog.rev(node)
1049 1049
1050 1050
1051 1051 # keep track of all ancestors of the file
1052 1052 ancestors = set([filelog.linkrev(last)])
1053 1053
1054 1054 # iterate from latest to oldest revision
1055 1055 for rev, flparentlinkrevs, copied in filerevgen(filelog, last):
1056 1056 if not follow:
1057 1057 if rev > maxrev:
1058 1058 continue
1059 1059 else:
1060 1060 # Note that last might not be the first interesting
1061 1061 # rev to us:
1062 1062 # if the file has been changed after maxrev, we'll
1063 1063 # have linkrev(last) > maxrev, and we still need
1064 1064 # to explore the file graph
1065 1065 if rev not in ancestors:
1066 1066 continue
1067 1067 # XXX insert 1327 fix here
1068 1068 if flparentlinkrevs:
1069 1069 ancestors.update(flparentlinkrevs)
1070 1070
1071 1071 fncache.setdefault(rev, []).append(file_)
1072 1072 wanted.add(rev)
1073 1073 if copied:
1074 1074 copies.append(copied)
1075 1075 if slowpath:
1076 1076 # We have to read the changelog to match filenames against
1077 1077 # changed files
1078 1078
1079 1079 if follow:
1080 1080 raise util.Abort(_('can only follow copies/renames for explicit '
1081 1081 'filenames'))
1082 1082
1083 1083 # The slow path checks files modified in every changeset.
1084 1084 for i in sorted(revs):
1085 1085 ctx = change(i)
1086 1086 matches = filter(match, ctx.files())
1087 1087 if matches:
1088 1088 fncache[i] = matches
1089 1089 wanted.add(i)
1090 1090
1091 1091 class followfilter(object):
1092 1092 def __init__(self, onlyfirst=False):
1093 1093 self.startrev = nullrev
1094 1094 self.roots = set()
1095 1095 self.onlyfirst = onlyfirst
1096 1096
1097 1097 def match(self, rev):
1098 1098 def realparents(rev):
1099 1099 if self.onlyfirst:
1100 1100 return repo.changelog.parentrevs(rev)[0:1]
1101 1101 else:
1102 1102 return filter(lambda x: x != nullrev,
1103 1103 repo.changelog.parentrevs(rev))
1104 1104
1105 1105 if self.startrev == nullrev:
1106 1106 self.startrev = rev
1107 1107 return True
1108 1108
1109 1109 if rev > self.startrev:
1110 1110 # forward: all descendants
1111 1111 if not self.roots:
1112 1112 self.roots.add(self.startrev)
1113 1113 for parent in realparents(rev):
1114 1114 if parent in self.roots:
1115 1115 self.roots.add(rev)
1116 1116 return True
1117 1117 else:
1118 1118 # backwards: all parents
1119 1119 if not self.roots:
1120 1120 self.roots.update(realparents(self.startrev))
1121 1121 if rev in self.roots:
1122 1122 self.roots.remove(rev)
1123 1123 self.roots.update(realparents(rev))
1124 1124 return True
1125 1125
1126 1126 return False
1127 1127
1128 1128 # it might be worthwhile to do this in the iterator if the rev range
1129 1129 # is descending and the prune args are all within that range
1130 1130 for rev in opts.get('prune', ()):
1131 1131 rev = repo.changelog.rev(repo.lookup(rev))
1132 1132 ff = followfilter()
1133 1133 stop = min(revs[0], revs[-1])
1134 1134 for x in xrange(rev, stop - 1, -1):
1135 1135 if ff.match(x):
1136 1136 wanted.discard(x)
1137 1137
1138 1138 # Now that wanted is correctly initialized, we can iterate over the
1139 1139 # revision range, yielding only revisions in wanted.
1140 1140 def iterate():
1141 1141 if follow and not match.files():
1142 1142 ff = followfilter(onlyfirst=opts.get('follow_first'))
1143 1143 def want(rev):
1144 1144 return ff.match(rev) and rev in wanted
1145 1145 else:
1146 1146 def want(rev):
1147 1147 return rev in wanted
1148 1148
1149 1149 for i, window in increasing_windows(0, len(revs)):
1150 1150 nrevs = [rev for rev in revs[i:i + window] if want(rev)]
1151 1151 for rev in sorted(nrevs):
1152 1152 fns = fncache.get(rev)
1153 1153 ctx = change(rev)
1154 1154 if not fns:
1155 1155 def fns_generator():
1156 1156 for f in ctx.files():
1157 1157 if match(f):
1158 1158 yield f
1159 1159 fns = fns_generator()
1160 1160 prepare(ctx, fns)
1161 1161 for rev in nrevs:
1162 1162 yield change(rev)
1163 1163 return iterate()
1164 1164
1165 1165 def add(ui, repo, match, dryrun, listsubrepos, prefix, explicitonly):
1166 1166 join = lambda f: os.path.join(prefix, f)
1167 1167 bad = []
1168 1168 oldbad = match.bad
1169 1169 match.bad = lambda x, y: bad.append(x) or oldbad(x, y)
1170 1170 names = []
1171 1171 wctx = repo[None]
1172 1172 cca = None
1173 1173 abort, warn = scmutil.checkportabilityalert(ui)
1174 1174 if abort or warn:
1175 1175 cca = scmutil.casecollisionauditor(ui, abort, wctx)
1176 1176 for f in repo.walk(match):
1177 1177 exact = match.exact(f)
1178 1178 if exact or not explicitonly and f not in repo.dirstate:
1179 1179 if cca:
1180 1180 cca(f)
1181 1181 names.append(f)
1182 1182 if ui.verbose or not exact:
1183 1183 ui.status(_('adding %s\n') % match.rel(join(f)))
1184 1184
1185 1185 for subpath in wctx.substate:
1186 1186 sub = wctx.sub(subpath)
1187 1187 try:
1188 1188 submatch = matchmod.narrowmatcher(subpath, match)
1189 1189 if listsubrepos:
1190 1190 bad.extend(sub.add(ui, submatch, dryrun, listsubrepos, prefix,
1191 1191 False))
1192 1192 else:
1193 1193 bad.extend(sub.add(ui, submatch, dryrun, listsubrepos, prefix,
1194 1194 True))
1195 1195 except error.LookupError:
1196 1196 ui.status(_("skipping missing subrepository: %s\n")
1197 1197 % join(subpath))
1198 1198
1199 1199 if not dryrun:
1200 1200 rejected = wctx.add(names, prefix)
1201 1201 bad.extend(f for f in rejected if f in match.files())
1202 1202 return bad
1203 1203
1204 def forget(ui, repo, match, prefix, explicitonly):
1205 join = lambda f: os.path.join(prefix, f)
1206 bad = []
1207 oldbad = match.bad
1208 match.bad = lambda x, y: bad.append(x) or oldbad(x, y)
1209 wctx = repo[None]
1210 forgot = []
1211 s = repo.status(match=match, clean=True)
1212 forget = sorted(s[0] + s[1] + s[3] + s[6])
1213 if explicitonly:
1214 forget = [f for f in forget if match.exact(f)]
1215
1216 for subpath in wctx.substate:
1217 sub = wctx.sub(subpath)
1218 try:
1219 submatch = matchmod.narrowmatcher(subpath, match)
1220 subbad, subforgot = sub.forget(ui, submatch, prefix)
1221 bad.extend([subpath + '/' + f for f in subbad])
1222 forgot.extend([subpath + '/' + f for f in subforgot])
1223 except error.LookupError:
1224 ui.status(_("skipping missing subrepository: %s\n")
1225 % join(subpath))
1226
1227 for f in match.files():
1228 if match.exact(f) or not explicitonly:
1229 if f not in repo.dirstate and not os.path.isdir(match.rel(join(f))):
1230 if f not in forgot:
1231 if os.path.exists(match.rel(join(f))):
1232 ui.warn(_('not removing %s: '
1233 'file is already untracked\n')
1234 % match.rel(join(f)))
1235 bad.append(f)
1236
1237 for f in forget:
1238 if ui.verbose or not match.exact(f):
1239 ui.status(_('removing %s\n') % match.rel(join(f)))
1240
1241 rejected = wctx.forget(forget, prefix)
1242 bad.extend(f for f in rejected if f in match.files())
1243 forgot.extend(forget)
1244 return bad, forgot
1245
1204 1246 def duplicatecopies(repo, rev, p1):
1205 1247 "Reproduce copies found in the source revision in the dirstate for grafts"
1206 1248 for dst, src in copies.pathcopies(repo[p1], repo[rev]).iteritems():
1207 1249 repo.dirstate.copy(src, dst)
1208 1250
1209 1251 def commit(ui, repo, commitfunc, pats, opts):
1210 1252 '''commit the specified files or all outstanding changes'''
1211 1253 date = opts.get('date')
1212 1254 if date:
1213 1255 opts['date'] = util.parsedate(date)
1214 1256 message = logmessage(ui, opts)
1215 1257
1216 1258 # extract addremove carefully -- this function can be called from a command
1217 1259 # that doesn't support addremove
1218 1260 if opts.get('addremove'):
1219 1261 scmutil.addremove(repo, pats, opts)
1220 1262
1221 1263 return commitfunc(ui, repo, message,
1222 1264 scmutil.match(repo[None], pats, opts), opts)
1223 1265
1224 1266 def commiteditor(repo, ctx, subs):
1225 1267 if ctx.description():
1226 1268 return ctx.description()
1227 1269 return commitforceeditor(repo, ctx, subs)
1228 1270
1229 1271 def commitforceeditor(repo, ctx, subs):
1230 1272 edittext = []
1231 1273 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
1232 1274 if ctx.description():
1233 1275 edittext.append(ctx.description())
1234 1276 edittext.append("")
1235 1277 edittext.append("") # Empty line between message and comments.
1236 1278 edittext.append(_("HG: Enter commit message."
1237 1279 " Lines beginning with 'HG:' are removed."))
1238 1280 edittext.append(_("HG: Leave message empty to abort commit."))
1239 1281 edittext.append("HG: --")
1240 1282 edittext.append(_("HG: user: %s") % ctx.user())
1241 1283 if ctx.p2():
1242 1284 edittext.append(_("HG: branch merge"))
1243 1285 if ctx.branch():
1244 1286 edittext.append(_("HG: branch '%s'") % ctx.branch())
1245 1287 edittext.extend([_("HG: subrepo %s") % s for s in subs])
1246 1288 edittext.extend([_("HG: added %s") % f for f in added])
1247 1289 edittext.extend([_("HG: changed %s") % f for f in modified])
1248 1290 edittext.extend([_("HG: removed %s") % f for f in removed])
1249 1291 if not added and not modified and not removed:
1250 1292 edittext.append(_("HG: no files changed"))
1251 1293 edittext.append("")
1252 1294 # run editor in the repository root
1253 1295 olddir = os.getcwd()
1254 1296 os.chdir(repo.root)
1255 1297 text = repo.ui.edit("\n".join(edittext), ctx.user())
1256 1298 text = re.sub("(?m)^HG:.*(\n|$)", "", text)
1257 1299 os.chdir(olddir)
1258 1300
1259 1301 if not text.strip():
1260 1302 raise util.Abort(_("empty commit message"))
1261 1303
1262 1304 return text
1263 1305
1264 1306 def command(table):
1265 1307 '''returns a function object bound to table which can be used as
1266 1308 a decorator for populating table as a command table'''
1267 1309
1268 1310 def cmd(name, options, synopsis=None):
1269 1311 def decorator(func):
1270 1312 if synopsis:
1271 1313 table[name] = func, options[:], synopsis
1272 1314 else:
1273 1315 table[name] = func, options[:]
1274 1316 return func
1275 1317 return decorator
1276 1318
1277 1319 return cmd
@@ -1,5779 +1,5741 b''
1 1 # commands.py - command processing for mercurial
2 2 #
3 3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 from node import hex, bin, nullid, nullrev, short
9 9 from lock import release
10 10 from i18n import _, gettext
11 11 import os, re, difflib, time, tempfile, errno
12 12 import hg, scmutil, util, revlog, extensions, copies, error, bookmarks
13 13 import patch, help, url, encoding, templatekw, discovery
14 14 import archival, changegroup, cmdutil, hbisect
15 15 import sshserver, hgweb, hgweb.server, commandserver
16 import match as matchmod
17 16 import merge as mergemod
18 17 import minirst, revset, fileset
19 18 import dagparser, context, simplemerge
20 19 import random, setdiscovery, treediscovery, dagutil
21 20 import phases
22 21
23 22 table = {}
24 23
25 24 command = cmdutil.command(table)
26 25
27 26 # common command options
28 27
29 28 globalopts = [
30 29 ('R', 'repository', '',
31 30 _('repository root directory or name of overlay bundle file'),
32 31 _('REPO')),
33 32 ('', 'cwd', '',
34 33 _('change working directory'), _('DIR')),
35 34 ('y', 'noninteractive', None,
36 35 _('do not prompt, automatically pick the first choice for all prompts')),
37 36 ('q', 'quiet', None, _('suppress output')),
38 37 ('v', 'verbose', None, _('enable additional output')),
39 38 ('', 'config', [],
40 39 _('set/override config option (use \'section.name=value\')'),
41 40 _('CONFIG')),
42 41 ('', 'debug', None, _('enable debugging output')),
43 42 ('', 'debugger', None, _('start debugger')),
44 43 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
45 44 _('ENCODE')),
46 45 ('', 'encodingmode', encoding.encodingmode,
47 46 _('set the charset encoding mode'), _('MODE')),
48 47 ('', 'traceback', None, _('always print a traceback on exception')),
49 48 ('', 'time', None, _('time how long the command takes')),
50 49 ('', 'profile', None, _('print command execution profile')),
51 50 ('', 'version', None, _('output version information and exit')),
52 51 ('h', 'help', None, _('display help and exit')),
53 52 ]
54 53
55 54 dryrunopts = [('n', 'dry-run', None,
56 55 _('do not perform actions, just print output'))]
57 56
58 57 remoteopts = [
59 58 ('e', 'ssh', '',
60 59 _('specify ssh command to use'), _('CMD')),
61 60 ('', 'remotecmd', '',
62 61 _('specify hg command to run on the remote side'), _('CMD')),
63 62 ('', 'insecure', None,
64 63 _('do not verify server certificate (ignoring web.cacerts config)')),
65 64 ]
66 65
67 66 walkopts = [
68 67 ('I', 'include', [],
69 68 _('include names matching the given patterns'), _('PATTERN')),
70 69 ('X', 'exclude', [],
71 70 _('exclude names matching the given patterns'), _('PATTERN')),
72 71 ]
73 72
74 73 commitopts = [
75 74 ('m', 'message', '',
76 75 _('use text as commit message'), _('TEXT')),
77 76 ('l', 'logfile', '',
78 77 _('read commit message from file'), _('FILE')),
79 78 ]
80 79
81 80 commitopts2 = [
82 81 ('d', 'date', '',
83 82 _('record the specified date as commit date'), _('DATE')),
84 83 ('u', 'user', '',
85 84 _('record the specified user as committer'), _('USER')),
86 85 ]
87 86
88 87 templateopts = [
89 88 ('', 'style', '',
90 89 _('display using template map file'), _('STYLE')),
91 90 ('', 'template', '',
92 91 _('display with template'), _('TEMPLATE')),
93 92 ]
94 93
95 94 logopts = [
96 95 ('p', 'patch', None, _('show patch')),
97 96 ('g', 'git', None, _('use git extended diff format')),
98 97 ('l', 'limit', '',
99 98 _('limit number of changes displayed'), _('NUM')),
100 99 ('M', 'no-merges', None, _('do not show merges')),
101 100 ('', 'stat', None, _('output diffstat-style summary of changes')),
102 101 ] + templateopts
103 102
104 103 diffopts = [
105 104 ('a', 'text', None, _('treat all files as text')),
106 105 ('g', 'git', None, _('use git extended diff format')),
107 106 ('', 'nodates', None, _('omit dates from diff headers'))
108 107 ]
109 108
110 109 diffwsopts = [
111 110 ('w', 'ignore-all-space', None,
112 111 _('ignore white space when comparing lines')),
113 112 ('b', 'ignore-space-change', None,
114 113 _('ignore changes in the amount of white space')),
115 114 ('B', 'ignore-blank-lines', None,
116 115 _('ignore changes whose lines are all blank')),
117 116 ]
118 117
119 118 diffopts2 = [
120 119 ('p', 'show-function', None, _('show which function each change is in')),
121 120 ('', 'reverse', None, _('produce a diff that undoes the changes')),
122 121 ] + diffwsopts + [
123 122 ('U', 'unified', '',
124 123 _('number of lines of context to show'), _('NUM')),
125 124 ('', 'stat', None, _('output diffstat-style summary of changes')),
126 125 ]
127 126
128 127 mergetoolopts = [
129 128 ('t', 'tool', '', _('specify merge tool')),
130 129 ]
131 130
132 131 similarityopts = [
133 132 ('s', 'similarity', '',
134 133 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
135 134 ]
136 135
137 136 subrepoopts = [
138 137 ('S', 'subrepos', None,
139 138 _('recurse into subrepositories'))
140 139 ]
141 140
142 141 # Commands start here, listed alphabetically
143 142
144 143 @command('^add',
145 144 walkopts + subrepoopts + dryrunopts,
146 145 _('[OPTION]... [FILE]...'))
147 146 def add(ui, repo, *pats, **opts):
148 147 """add the specified files on the next commit
149 148
150 149 Schedule files to be version controlled and added to the
151 150 repository.
152 151
153 152 The files will be added to the repository at the next commit. To
154 153 undo an add before that, see :hg:`forget`.
155 154
156 155 If no names are given, add all files to the repository.
157 156
158 157 .. container:: verbose
159 158
160 159 An example showing how new (unknown) files are added
161 160 automatically by :hg:`add`::
162 161
163 162 $ ls
164 163 foo.c
165 164 $ hg status
166 165 ? foo.c
167 166 $ hg add
168 167 adding foo.c
169 168 $ hg status
170 169 A foo.c
171 170
172 171 Returns 0 if all files are successfully added.
173 172 """
174 173
175 174 m = scmutil.match(repo[None], pats, opts)
176 175 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
177 176 opts.get('subrepos'), prefix="", explicitonly=False)
178 177 return rejected and 1 or 0
179 178
180 179 @command('addremove',
181 180 similarityopts + walkopts + dryrunopts,
182 181 _('[OPTION]... [FILE]...'))
183 182 def addremove(ui, repo, *pats, **opts):
184 183 """add all new files, delete all missing files
185 184
186 185 Add all new files and remove all missing files from the
187 186 repository.
188 187
189 188 New files are ignored if they match any of the patterns in
190 189 ``.hgignore``. As with add, these changes take effect at the next
191 190 commit.
192 191
193 192 Use the -s/--similarity option to detect renamed files. With a
194 193 parameter greater than 0, this compares every removed file with
195 194 every added file and records those similar enough as renames. This
196 195 option takes a percentage between 0 (disabled) and 100 (files must
197 196 be identical) as its parameter. Detecting renamed files this way
198 197 can be expensive. After using this option, :hg:`status -C` can be
199 198 used to check which files were identified as moved or renamed.
200 199
201 200 Returns 0 if all files are successfully added.
202 201 """
203 202 try:
204 203 sim = float(opts.get('similarity') or 100)
205 204 except ValueError:
206 205 raise util.Abort(_('similarity must be a number'))
207 206 if sim < 0 or sim > 100:
208 207 raise util.Abort(_('similarity must be between 0 and 100'))
209 208 return scmutil.addremove(repo, pats, opts, similarity=sim / 100.0)
210 209
211 210 @command('^annotate|blame',
212 211 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
213 212 ('', 'follow', None,
214 213 _('follow copies/renames and list the filename (DEPRECATED)')),
215 214 ('', 'no-follow', None, _("don't follow copies and renames")),
216 215 ('a', 'text', None, _('treat all files as text')),
217 216 ('u', 'user', None, _('list the author (long with -v)')),
218 217 ('f', 'file', None, _('list the filename')),
219 218 ('d', 'date', None, _('list the date (short with -q)')),
220 219 ('n', 'number', None, _('list the revision number (default)')),
221 220 ('c', 'changeset', None, _('list the changeset')),
222 221 ('l', 'line-number', None, _('show line number at the first appearance'))
223 222 ] + diffwsopts + walkopts,
224 223 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'))
225 224 def annotate(ui, repo, *pats, **opts):
226 225 """show changeset information by line for each file
227 226
228 227 List changes in files, showing the revision id responsible for
229 228 each line
230 229
231 230 This command is useful for discovering when a change was made and
232 231 by whom.
233 232
234 233 Without the -a/--text option, annotate will avoid processing files
235 234 it detects as binary. With -a, annotate will annotate the file
236 235 anyway, although the results will probably be neither useful
237 236 nor desirable.
238 237
239 238 Returns 0 on success.
240 239 """
241 240 if opts.get('follow'):
242 241 # --follow is deprecated and now just an alias for -f/--file
243 242 # to mimic the behavior of Mercurial before version 1.5
244 243 opts['file'] = True
245 244
246 245 datefunc = ui.quiet and util.shortdate or util.datestr
247 246 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
248 247
249 248 if not pats:
250 249 raise util.Abort(_('at least one filename or pattern is required'))
251 250
252 251 hexfn = ui.debugflag and hex or short
253 252
254 253 opmap = [('user', ' ', lambda x: ui.shortuser(x[0].user())),
255 254 ('number', ' ', lambda x: str(x[0].rev())),
256 255 ('changeset', ' ', lambda x: hexfn(x[0].node())),
257 256 ('date', ' ', getdate),
258 257 ('file', ' ', lambda x: x[0].path()),
259 258 ('line_number', ':', lambda x: str(x[1])),
260 259 ]
261 260
262 261 if (not opts.get('user') and not opts.get('changeset')
263 262 and not opts.get('date') and not opts.get('file')):
264 263 opts['number'] = True
265 264
266 265 linenumber = opts.get('line_number') is not None
267 266 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
268 267 raise util.Abort(_('at least one of -n/-c is required for -l'))
269 268
270 269 funcmap = [(func, sep) for op, sep, func in opmap if opts.get(op)]
271 270 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
272 271
273 272 def bad(x, y):
274 273 raise util.Abort("%s: %s" % (x, y))
275 274
276 275 ctx = scmutil.revsingle(repo, opts.get('rev'))
277 276 m = scmutil.match(ctx, pats, opts)
278 277 m.bad = bad
279 278 follow = not opts.get('no_follow')
280 279 diffopts = patch.diffopts(ui, opts, section='annotate')
281 280 for abs in ctx.walk(m):
282 281 fctx = ctx[abs]
283 282 if not opts.get('text') and util.binary(fctx.data()):
284 283 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
285 284 continue
286 285
287 286 lines = fctx.annotate(follow=follow, linenumber=linenumber,
288 287 diffopts=diffopts)
289 288 pieces = []
290 289
291 290 for f, sep in funcmap:
292 291 l = [f(n) for n, dummy in lines]
293 292 if l:
294 293 sized = [(x, encoding.colwidth(x)) for x in l]
295 294 ml = max([w for x, w in sized])
296 295 pieces.append(["%s%s%s" % (sep, ' ' * (ml - w), x)
297 296 for x, w in sized])
298 297
299 298 if pieces:
300 299 for p, l in zip(zip(*pieces), lines):
301 300 ui.write("%s: %s" % ("".join(p), l[1]))
302 301
303 302 if lines and not lines[-1][1].endswith('\n'):
304 303 ui.write('\n')
305 304
306 305 @command('archive',
307 306 [('', 'no-decode', None, _('do not pass files through decoders')),
308 307 ('p', 'prefix', '', _('directory prefix for files in archive'),
309 308 _('PREFIX')),
310 309 ('r', 'rev', '', _('revision to distribute'), _('REV')),
311 310 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
312 311 ] + subrepoopts + walkopts,
313 312 _('[OPTION]... DEST'))
314 313 def archive(ui, repo, dest, **opts):
315 314 '''create an unversioned archive of a repository revision
316 315
317 316 By default, the revision used is the parent of the working
318 317 directory; use -r/--rev to specify a different revision.
319 318
320 319 The archive type is automatically detected based on file
321 320 extension (or override using -t/--type).
322 321
323 322 .. container:: verbose
324 323
325 324 Examples:
326 325
327 326 - create a zip file containing the 1.0 release::
328 327
329 328 hg archive -r 1.0 project-1.0.zip
330 329
331 330 - create a tarball excluding .hg files::
332 331
333 332 hg archive project.tar.gz -X ".hg*"
334 333
335 334 Valid types are:
336 335
337 336 :``files``: a directory full of files (default)
338 337 :``tar``: tar archive, uncompressed
339 338 :``tbz2``: tar archive, compressed using bzip2
340 339 :``tgz``: tar archive, compressed using gzip
341 340 :``uzip``: zip archive, uncompressed
342 341 :``zip``: zip archive, compressed using deflate
343 342
344 343 The exact name of the destination archive or directory is given
345 344 using a format string; see :hg:`help export` for details.
346 345
347 346 Each member added to an archive file has a directory prefix
348 347 prepended. Use -p/--prefix to specify a format string for the
349 348 prefix. The default is the basename of the archive, with suffixes
350 349 removed.
351 350
352 351 Returns 0 on success.
353 352 '''
354 353
355 354 ctx = scmutil.revsingle(repo, opts.get('rev'))
356 355 if not ctx:
357 356 raise util.Abort(_('no working directory: please specify a revision'))
358 357 node = ctx.node()
359 358 dest = cmdutil.makefilename(repo, dest, node)
360 359 if os.path.realpath(dest) == repo.root:
361 360 raise util.Abort(_('repository root cannot be destination'))
362 361
363 362 kind = opts.get('type') or archival.guesskind(dest) or 'files'
364 363 prefix = opts.get('prefix')
365 364
366 365 if dest == '-':
367 366 if kind == 'files':
368 367 raise util.Abort(_('cannot archive plain files to stdout'))
369 368 dest = cmdutil.makefileobj(repo, dest)
370 369 if not prefix:
371 370 prefix = os.path.basename(repo.root) + '-%h'
372 371
373 372 prefix = cmdutil.makefilename(repo, prefix, node)
374 373 matchfn = scmutil.match(ctx, [], opts)
375 374 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
376 375 matchfn, prefix, subrepos=opts.get('subrepos'))
377 376
378 377 @command('backout',
379 378 [('', 'merge', None, _('merge with old dirstate parent after backout')),
380 379 ('', 'parent', '',
381 380 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
382 381 ('r', 'rev', '', _('revision to backout'), _('REV')),
383 382 ] + mergetoolopts + walkopts + commitopts + commitopts2,
384 383 _('[OPTION]... [-r] REV'))
385 384 def backout(ui, repo, node=None, rev=None, **opts):
386 385 '''reverse effect of earlier changeset
387 386
388 387 Prepare a new changeset with the effect of REV undone in the
389 388 current working directory.
390 389
391 390 If REV is the parent of the working directory, then this new changeset
392 391 is committed automatically. Otherwise, hg needs to merge the
393 392 changes and the merged result is left uncommitted.
394 393
395 394 .. note::
396 395 backout cannot be used to fix either an unwanted or
397 396 incorrect merge.
398 397
399 398 .. container:: verbose
400 399
401 400 By default, the pending changeset will have one parent,
402 401 maintaining a linear history. With --merge, the pending
403 402 changeset will instead have two parents: the old parent of the
404 403 working directory and a new child of REV that simply undoes REV.
405 404
406 405 Before version 1.7, the behavior without --merge was equivalent
407 406 to specifying --merge followed by :hg:`update --clean .` to
408 407 cancel the merge and leave the child of REV as a head to be
409 408 merged separately.
410 409
411 410 See :hg:`help dates` for a list of formats valid for -d/--date.
412 411
413 412 Returns 0 on success.
414 413 '''
415 414 if rev and node:
416 415 raise util.Abort(_("please specify just one revision"))
417 416
418 417 if not rev:
419 418 rev = node
420 419
421 420 if not rev:
422 421 raise util.Abort(_("please specify a revision to backout"))
423 422
424 423 date = opts.get('date')
425 424 if date:
426 425 opts['date'] = util.parsedate(date)
427 426
428 427 cmdutil.bailifchanged(repo)
429 428 node = scmutil.revsingle(repo, rev).node()
430 429
431 430 op1, op2 = repo.dirstate.parents()
432 431 a = repo.changelog.ancestor(op1, node)
433 432 if a != node:
434 433 raise util.Abort(_('cannot backout change on a different branch'))
435 434
436 435 p1, p2 = repo.changelog.parents(node)
437 436 if p1 == nullid:
438 437 raise util.Abort(_('cannot backout a change with no parents'))
439 438 if p2 != nullid:
440 439 if not opts.get('parent'):
441 440 raise util.Abort(_('cannot backout a merge changeset'))
442 441 p = repo.lookup(opts['parent'])
443 442 if p not in (p1, p2):
444 443 raise util.Abort(_('%s is not a parent of %s') %
445 444 (short(p), short(node)))
446 445 parent = p
447 446 else:
448 447 if opts.get('parent'):
449 448 raise util.Abort(_('cannot use --parent on non-merge changeset'))
450 449 parent = p1
451 450
452 451 # the backout should appear on the same branch
453 452 branch = repo.dirstate.branch()
454 453 hg.clean(repo, node, show_stats=False)
455 454 repo.dirstate.setbranch(branch)
456 455 revert_opts = opts.copy()
457 456 revert_opts['date'] = None
458 457 revert_opts['all'] = True
459 458 revert_opts['rev'] = hex(parent)
460 459 revert_opts['no_backup'] = None
461 460 revert(ui, repo, **revert_opts)
462 461 if not opts.get('merge') and op1 != node:
463 462 try:
464 463 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
465 464 return hg.update(repo, op1)
466 465 finally:
467 466 ui.setconfig('ui', 'forcemerge', '')
468 467
469 468 commit_opts = opts.copy()
470 469 commit_opts['addremove'] = False
471 470 if not commit_opts['message'] and not commit_opts['logfile']:
472 471 # we don't translate commit messages
473 472 commit_opts['message'] = "Backed out changeset %s" % short(node)
474 473 commit_opts['force_editor'] = True
475 474 commit(ui, repo, **commit_opts)
476 475 def nice(node):
477 476 return '%d:%s' % (repo.changelog.rev(node), short(node))
478 477 ui.status(_('changeset %s backs out changeset %s\n') %
479 478 (nice(repo.changelog.tip()), nice(node)))
480 479 if opts.get('merge') and op1 != node:
481 480 hg.clean(repo, op1, show_stats=False)
482 481 ui.status(_('merging with changeset %s\n')
483 482 % nice(repo.changelog.tip()))
484 483 try:
485 484 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
486 485 return hg.merge(repo, hex(repo.changelog.tip()))
487 486 finally:
488 487 ui.setconfig('ui', 'forcemerge', '')
489 488 return 0
490 489
491 490 @command('bisect',
492 491 [('r', 'reset', False, _('reset bisect state')),
493 492 ('g', 'good', False, _('mark changeset good')),
494 493 ('b', 'bad', False, _('mark changeset bad')),
495 494 ('s', 'skip', False, _('skip testing changeset')),
496 495 ('e', 'extend', False, _('extend the bisect range')),
497 496 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
498 497 ('U', 'noupdate', False, _('do not update to target'))],
499 498 _("[-gbsr] [-U] [-c CMD] [REV]"))
500 499 def bisect(ui, repo, rev=None, extra=None, command=None,
501 500 reset=None, good=None, bad=None, skip=None, extend=None,
502 501 noupdate=None):
503 502 """subdivision search of changesets
504 503
505 504 This command helps to find changesets which introduce problems. To
506 505 use, mark the earliest changeset you know exhibits the problem as
507 506 bad, then mark the latest changeset which is free from the problem
508 507 as good. Bisect will update your working directory to a revision
509 508 for testing (unless the -U/--noupdate option is specified). Once
510 509 you have performed tests, mark the working directory as good or
511 510 bad, and bisect will either update to another candidate changeset
512 511 or announce that it has found the bad revision.
513 512
514 513 As a shortcut, you can also use the revision argument to mark a
515 514 revision as good or bad without checking it out first.
516 515
517 516 If you supply a command, it will be used for automatic bisection.
518 517 Its exit status will be used to mark revisions as good or bad:
519 518 status 0 means good, 125 means to skip the revision, 127
520 519 (command not found) will abort the bisection, and any other
521 520 non-zero exit status means the revision is bad.
522 521
523 522 .. container:: verbose
524 523
525 524 Some examples:
526 525
527 526 - start a bisection with known bad revision 12, and good revision 34::
528 527
529 528 hg bisect --bad 34
530 529 hg bisect --good 12
531 530
532 531 - advance the current bisection by marking current revision as good or
533 532 bad::
534 533
535 534 hg bisect --good
536 535 hg bisect --bad
537 536
538 537 - mark the current revision, or a known revision, to be skipped (eg. if
539 538 that revision is not usable because of another issue)::
540 539
541 540 hg bisect --skip
542 541 hg bisect --skip 23
543 542
544 543 - forget the current bisection::
545 544
546 545 hg bisect --reset
547 546
548 547 - use 'make && make tests' to automatically find the first broken
549 548 revision::
550 549
551 550 hg bisect --reset
552 551 hg bisect --bad 34
553 552 hg bisect --good 12
554 553 hg bisect --command 'make && make tests'
555 554
556 555 - see all changesets whose states are already known in the current
557 556 bisection::
558 557
559 558 hg log -r "bisect(pruned)"
560 559
561 560 - see all changesets that took part in the current bisection::
562 561
563 562 hg log -r "bisect(range)"
564 563
565 564 - with the graphlog extension, you can even get a nice graph::
566 565
567 566 hg log --graph -r "bisect(range)"
568 567
569 568 See :hg:`help revsets` for more about the `bisect()` keyword.
570 569
571 570 Returns 0 on success.
572 571 """
573 572 def extendbisectrange(nodes, good):
574 573 # bisect is incomplete when it ends on a merge node and
575 574 # one of the parent was not checked.
576 575 parents = repo[nodes[0]].parents()
577 576 if len(parents) > 1:
578 577 side = good and state['bad'] or state['good']
579 578 num = len(set(i.node() for i in parents) & set(side))
580 579 if num == 1:
581 580 return parents[0].ancestor(parents[1])
582 581 return None
583 582
584 583 def print_result(nodes, good):
585 584 displayer = cmdutil.show_changeset(ui, repo, {})
586 585 if len(nodes) == 1:
587 586 # narrowed it down to a single revision
588 587 if good:
589 588 ui.write(_("The first good revision is:\n"))
590 589 else:
591 590 ui.write(_("The first bad revision is:\n"))
592 591 displayer.show(repo[nodes[0]])
593 592 extendnode = extendbisectrange(nodes, good)
594 593 if extendnode is not None:
595 594 ui.write(_('Not all ancestors of this changeset have been'
596 595 ' checked.\nUse bisect --extend to continue the '
597 596 'bisection from\nthe common ancestor, %s.\n')
598 597 % extendnode)
599 598 else:
600 599 # multiple possible revisions
601 600 if good:
602 601 ui.write(_("Due to skipped revisions, the first "
603 602 "good revision could be any of:\n"))
604 603 else:
605 604 ui.write(_("Due to skipped revisions, the first "
606 605 "bad revision could be any of:\n"))
607 606 for n in nodes:
608 607 displayer.show(repo[n])
609 608 displayer.close()
610 609
611 610 def check_state(state, interactive=True):
612 611 if not state['good'] or not state['bad']:
613 612 if (good or bad or skip or reset) and interactive:
614 613 return
615 614 if not state['good']:
616 615 raise util.Abort(_('cannot bisect (no known good revisions)'))
617 616 else:
618 617 raise util.Abort(_('cannot bisect (no known bad revisions)'))
619 618 return True
620 619
621 620 # backward compatibility
622 621 if rev in "good bad reset init".split():
623 622 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
624 623 cmd, rev, extra = rev, extra, None
625 624 if cmd == "good":
626 625 good = True
627 626 elif cmd == "bad":
628 627 bad = True
629 628 else:
630 629 reset = True
631 630 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
632 631 raise util.Abort(_('incompatible arguments'))
633 632
634 633 if reset:
635 634 p = repo.join("bisect.state")
636 635 if os.path.exists(p):
637 636 os.unlink(p)
638 637 return
639 638
640 639 state = hbisect.load_state(repo)
641 640
642 641 if command:
643 642 changesets = 1
644 643 try:
645 644 while changesets:
646 645 # update state
647 646 status = util.system(command, out=ui.fout)
648 647 if status == 125:
649 648 transition = "skip"
650 649 elif status == 0:
651 650 transition = "good"
652 651 # status < 0 means process was killed
653 652 elif status == 127:
654 653 raise util.Abort(_("failed to execute %s") % command)
655 654 elif status < 0:
656 655 raise util.Abort(_("%s killed") % command)
657 656 else:
658 657 transition = "bad"
659 658 ctx = scmutil.revsingle(repo, rev)
660 659 rev = None # clear for future iterations
661 660 state[transition].append(ctx.node())
662 661 ui.status(_('Changeset %d:%s: %s\n') % (ctx, ctx, transition))
663 662 check_state(state, interactive=False)
664 663 # bisect
665 664 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
666 665 # update to next check
667 666 cmdutil.bailifchanged(repo)
668 667 hg.clean(repo, nodes[0], show_stats=False)
669 668 finally:
670 669 hbisect.save_state(repo, state)
671 670 print_result(nodes, good)
672 671 return
673 672
674 673 # update state
675 674
676 675 if rev:
677 676 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
678 677 else:
679 678 nodes = [repo.lookup('.')]
680 679
681 680 if good or bad or skip:
682 681 if good:
683 682 state['good'] += nodes
684 683 elif bad:
685 684 state['bad'] += nodes
686 685 elif skip:
687 686 state['skip'] += nodes
688 687 hbisect.save_state(repo, state)
689 688
690 689 if not check_state(state):
691 690 return
692 691
693 692 # actually bisect
694 693 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
695 694 if extend:
696 695 if not changesets:
697 696 extendnode = extendbisectrange(nodes, good)
698 697 if extendnode is not None:
699 698 ui.write(_("Extending search to changeset %d:%s\n"
700 699 % (extendnode.rev(), extendnode)))
701 700 if noupdate:
702 701 return
703 702 cmdutil.bailifchanged(repo)
704 703 return hg.clean(repo, extendnode.node())
705 704 raise util.Abort(_("nothing to extend"))
706 705
707 706 if changesets == 0:
708 707 print_result(nodes, good)
709 708 else:
710 709 assert len(nodes) == 1 # only a single node can be tested next
711 710 node = nodes[0]
712 711 # compute the approximate number of remaining tests
713 712 tests, size = 0, 2
714 713 while size <= changesets:
715 714 tests, size = tests + 1, size * 2
716 715 rev = repo.changelog.rev(node)
717 716 ui.write(_("Testing changeset %d:%s "
718 717 "(%d changesets remaining, ~%d tests)\n")
719 718 % (rev, short(node), changesets, tests))
720 719 if not noupdate:
721 720 cmdutil.bailifchanged(repo)
722 721 return hg.clean(repo, node)
723 722
724 723 @command('bookmarks',
725 724 [('f', 'force', False, _('force')),
726 725 ('r', 'rev', '', _('revision'), _('REV')),
727 726 ('d', 'delete', False, _('delete a given bookmark')),
728 727 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
729 728 ('i', 'inactive', False, _('do not mark a new bookmark active'))],
730 729 _('hg bookmarks [-f] [-d] [-i] [-m NAME] [-r REV] [NAME]'))
731 730 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False,
732 731 rename=None, inactive=False):
733 732 '''track a line of development with movable markers
734 733
735 734 Bookmarks are pointers to certain commits that move when committing.
736 735 Bookmarks are local. They can be renamed, copied and deleted. It is
737 736 possible to use :hg:`merge NAME` to merge from a given bookmark, and
738 737 :hg:`update NAME` to update to a given bookmark.
739 738
740 739 You can use :hg:`bookmark NAME` to set a bookmark on the working
741 740 directory's parent revision with the given name. If you specify
742 741 a revision using -r REV (where REV may be an existing bookmark),
743 742 the bookmark is assigned to that revision.
744 743
745 744 Bookmarks can be pushed and pulled between repositories (see :hg:`help
746 745 push` and :hg:`help pull`). This requires both the local and remote
747 746 repositories to support bookmarks. For versions prior to 1.8, this means
748 747 the bookmarks extension must be enabled.
749 748 '''
750 749 hexfn = ui.debugflag and hex or short
751 750 marks = repo._bookmarks
752 751 cur = repo.changectx('.').node()
753 752
754 753 if delete:
755 754 if mark is None:
756 755 raise util.Abort(_("bookmark name required"))
757 756 if mark not in marks:
758 757 raise util.Abort(_("bookmark '%s' does not exist") % mark)
759 758 if mark == repo._bookmarkcurrent:
760 759 bookmarks.setcurrent(repo, None)
761 760 del marks[mark]
762 761 bookmarks.write(repo)
763 762 return
764 763
765 764 if rename:
766 765 if rename not in marks:
767 766 raise util.Abort(_("bookmark '%s' does not exist") % rename)
768 767 if mark in marks and not force:
769 768 raise util.Abort(_("bookmark '%s' already exists "
770 769 "(use -f to force)") % mark)
771 770 if mark is None:
772 771 raise util.Abort(_("new bookmark name required"))
773 772 marks[mark] = marks[rename]
774 773 if repo._bookmarkcurrent == rename and not inactive:
775 774 bookmarks.setcurrent(repo, mark)
776 775 del marks[rename]
777 776 bookmarks.write(repo)
778 777 return
779 778
780 779 if mark is not None:
781 780 if "\n" in mark:
782 781 raise util.Abort(_("bookmark name cannot contain newlines"))
783 782 mark = mark.strip()
784 783 if not mark:
785 784 raise util.Abort(_("bookmark names cannot consist entirely of "
786 785 "whitespace"))
787 786 if inactive and mark == repo._bookmarkcurrent:
788 787 bookmarks.setcurrent(repo, None)
789 788 return
790 789 if mark in marks and not force:
791 790 raise util.Abort(_("bookmark '%s' already exists "
792 791 "(use -f to force)") % mark)
793 792 if ((mark in repo.branchtags() or mark == repo.dirstate.branch())
794 793 and not force):
795 794 raise util.Abort(
796 795 _("a bookmark cannot have the name of an existing branch"))
797 796 if rev:
798 797 marks[mark] = repo.lookup(rev)
799 798 else:
800 799 marks[mark] = cur
801 800 if not inactive and cur == marks[mark]:
802 801 bookmarks.setcurrent(repo, mark)
803 802 bookmarks.write(repo)
804 803 return
805 804
806 805 if mark is None:
807 806 if rev:
808 807 raise util.Abort(_("bookmark name required"))
809 808 if len(marks) == 0:
810 809 ui.status(_("no bookmarks set\n"))
811 810 else:
812 811 for bmark, n in sorted(marks.iteritems()):
813 812 current = repo._bookmarkcurrent
814 813 if bmark == current and n == cur:
815 814 prefix, label = '*', 'bookmarks.current'
816 815 else:
817 816 prefix, label = ' ', ''
818 817
819 818 if ui.quiet:
820 819 ui.write("%s\n" % bmark, label=label)
821 820 else:
822 821 ui.write(" %s %-25s %d:%s\n" % (
823 822 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
824 823 label=label)
825 824 return
826 825
827 826 @command('branch',
828 827 [('f', 'force', None,
829 828 _('set branch name even if it shadows an existing branch')),
830 829 ('C', 'clean', None, _('reset branch name to parent branch name'))],
831 830 _('[-fC] [NAME]'))
832 831 def branch(ui, repo, label=None, **opts):
833 832 """set or show the current branch name
834 833
835 834 .. note::
836 835 Branch names are permanent and global. Use :hg:`bookmark` to create a
837 836 light-weight bookmark instead. See :hg:`help glossary` for more
838 837 information about named branches and bookmarks.
839 838
840 839 With no argument, show the current branch name. With one argument,
841 840 set the working directory branch name (the branch will not exist
842 841 in the repository until the next commit). Standard practice
843 842 recommends that primary development take place on the 'default'
844 843 branch.
845 844
846 845 Unless -f/--force is specified, branch will not let you set a
847 846 branch name that already exists, even if it's inactive.
848 847
849 848 Use -C/--clean to reset the working directory branch to that of
850 849 the parent of the working directory, negating a previous branch
851 850 change.
852 851
853 852 Use the command :hg:`update` to switch to an existing branch. Use
854 853 :hg:`commit --close-branch` to mark this branch as closed.
855 854
856 855 Returns 0 on success.
857 856 """
858 857
859 858 if opts.get('clean'):
860 859 label = repo[None].p1().branch()
861 860 repo.dirstate.setbranch(label)
862 861 ui.status(_('reset working directory to branch %s\n') % label)
863 862 elif label:
864 863 if not opts.get('force') and label in repo.branchtags():
865 864 if label not in [p.branch() for p in repo.parents()]:
866 865 raise util.Abort(_('a branch of the same name already exists'),
867 866 # i18n: "it" refers to an existing branch
868 867 hint=_("use 'hg update' to switch to it"))
869 868 repo.dirstate.setbranch(label)
870 869 ui.status(_('marked working directory as branch %s\n') % label)
871 870 ui.status(_('(branches are permanent and global, '
872 871 'did you want a bookmark?)\n'))
873 872 else:
874 873 ui.write("%s\n" % repo.dirstate.branch())
875 874
876 875 @command('branches',
877 876 [('a', 'active', False, _('show only branches that have unmerged heads')),
878 877 ('c', 'closed', False, _('show normal and closed branches'))],
879 878 _('[-ac]'))
880 879 def branches(ui, repo, active=False, closed=False):
881 880 """list repository named branches
882 881
883 882 List the repository's named branches, indicating which ones are
884 883 inactive. If -c/--closed is specified, also list branches which have
885 884 been marked closed (see :hg:`commit --close-branch`).
886 885
887 886 If -a/--active is specified, only show active branches. A branch
888 887 is considered active if it contains repository heads.
889 888
890 889 Use the command :hg:`update` to switch to an existing branch.
891 890
892 891 Returns 0.
893 892 """
894 893
895 894 hexfunc = ui.debugflag and hex or short
896 895 activebranches = [repo[n].branch() for n in repo.heads()]
897 896 def testactive(tag, node):
898 897 realhead = tag in activebranches
899 898 open = node in repo.branchheads(tag, closed=False)
900 899 return realhead and open
901 900 branches = sorted([(testactive(tag, node), repo.changelog.rev(node), tag)
902 901 for tag, node in repo.branchtags().items()],
903 902 reverse=True)
904 903
905 904 for isactive, node, tag in branches:
906 905 if (not active) or isactive:
907 906 if ui.quiet:
908 907 ui.write("%s\n" % tag)
909 908 else:
910 909 hn = repo.lookup(node)
911 910 if isactive:
912 911 label = 'branches.active'
913 912 notice = ''
914 913 elif hn not in repo.branchheads(tag, closed=False):
915 914 if not closed:
916 915 continue
917 916 label = 'branches.closed'
918 917 notice = _(' (closed)')
919 918 else:
920 919 label = 'branches.inactive'
921 920 notice = _(' (inactive)')
922 921 if tag == repo.dirstate.branch():
923 922 label = 'branches.current'
924 923 rev = str(node).rjust(31 - encoding.colwidth(tag))
925 924 rev = ui.label('%s:%s' % (rev, hexfunc(hn)), 'log.changeset')
926 925 tag = ui.label(tag, label)
927 926 ui.write("%s %s%s\n" % (tag, rev, notice))
928 927
929 928 @command('bundle',
930 929 [('f', 'force', None, _('run even when the destination is unrelated')),
931 930 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
932 931 _('REV')),
933 932 ('b', 'branch', [], _('a specific branch you would like to bundle'),
934 933 _('BRANCH')),
935 934 ('', 'base', [],
936 935 _('a base changeset assumed to be available at the destination'),
937 936 _('REV')),
938 937 ('a', 'all', None, _('bundle all changesets in the repository')),
939 938 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
940 939 ] + remoteopts,
941 940 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
942 941 def bundle(ui, repo, fname, dest=None, **opts):
943 942 """create a changegroup file
944 943
945 944 Generate a compressed changegroup file collecting changesets not
946 945 known to be in another repository.
947 946
948 947 If you omit the destination repository, then hg assumes the
949 948 destination will have all the nodes you specify with --base
950 949 parameters. To create a bundle containing all changesets, use
951 950 -a/--all (or --base null).
952 951
953 952 You can change compression method with the -t/--type option.
954 953 The available compression methods are: none, bzip2, and
955 954 gzip (by default, bundles are compressed using bzip2).
956 955
957 956 The bundle file can then be transferred using conventional means
958 957 and applied to another repository with the unbundle or pull
959 958 command. This is useful when direct push and pull are not
960 959 available or when exporting an entire repository is undesirable.
961 960
962 961 Applying bundles preserves all changeset contents including
963 962 permissions, copy/rename information, and revision history.
964 963
965 964 Returns 0 on success, 1 if no changes found.
966 965 """
967 966 revs = None
968 967 if 'rev' in opts:
969 968 revs = scmutil.revrange(repo, opts['rev'])
970 969
971 970 if opts.get('all'):
972 971 base = ['null']
973 972 else:
974 973 base = scmutil.revrange(repo, opts.get('base'))
975 974 if base:
976 975 if dest:
977 976 raise util.Abort(_("--base is incompatible with specifying "
978 977 "a destination"))
979 978 common = [repo.lookup(rev) for rev in base]
980 979 heads = revs and map(repo.lookup, revs) or revs
981 980 cg = repo.getbundle('bundle', heads=heads, common=common)
982 981 else:
983 982 dest = ui.expandpath(dest or 'default-push', dest or 'default')
984 983 dest, branches = hg.parseurl(dest, opts.get('branch'))
985 984 other = hg.peer(repo, opts, dest)
986 985 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
987 986 heads = revs and map(repo.lookup, revs) or revs
988 987 outgoing = discovery.findcommonoutgoing(repo, other,
989 988 onlyheads=heads,
990 989 force=opts.get('force'))
991 990 cg = repo.getlocalbundle('bundle', outgoing)
992 991 if not cg:
993 992 ui.status(_("no changes found\n"))
994 993 return 1
995 994
996 995 bundletype = opts.get('type', 'bzip2').lower()
997 996 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
998 997 bundletype = btypes.get(bundletype)
999 998 if bundletype not in changegroup.bundletypes:
1000 999 raise util.Abort(_('unknown bundle type specified with --type'))
1001 1000
1002 1001 changegroup.writebundle(cg, fname, bundletype)
1003 1002
1004 1003 @command('cat',
1005 1004 [('o', 'output', '',
1006 1005 _('print output to file with formatted name'), _('FORMAT')),
1007 1006 ('r', 'rev', '', _('print the given revision'), _('REV')),
1008 1007 ('', 'decode', None, _('apply any matching decode filter')),
1009 1008 ] + walkopts,
1010 1009 _('[OPTION]... FILE...'))
1011 1010 def cat(ui, repo, file1, *pats, **opts):
1012 1011 """output the current or given revision of files
1013 1012
1014 1013 Print the specified files as they were at the given revision. If
1015 1014 no revision is given, the parent of the working directory is used,
1016 1015 or tip if no revision is checked out.
1017 1016
1018 1017 Output may be to a file, in which case the name of the file is
1019 1018 given using a format string. The formatting rules are the same as
1020 1019 for the export command, with the following additions:
1021 1020
1022 1021 :``%s``: basename of file being printed
1023 1022 :``%d``: dirname of file being printed, or '.' if in repository root
1024 1023 :``%p``: root-relative path name of file being printed
1025 1024
1026 1025 Returns 0 on success.
1027 1026 """
1028 1027 ctx = scmutil.revsingle(repo, opts.get('rev'))
1029 1028 err = 1
1030 1029 m = scmutil.match(ctx, (file1,) + pats, opts)
1031 1030 for abs in ctx.walk(m):
1032 1031 fp = cmdutil.makefileobj(repo, opts.get('output'), ctx.node(),
1033 1032 pathname=abs)
1034 1033 data = ctx[abs].data()
1035 1034 if opts.get('decode'):
1036 1035 data = repo.wwritedata(abs, data)
1037 1036 fp.write(data)
1038 1037 fp.close()
1039 1038 err = 0
1040 1039 return err
1041 1040
1042 1041 @command('^clone',
1043 1042 [('U', 'noupdate', None,
1044 1043 _('the clone will include an empty working copy (only a repository)')),
1045 1044 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
1046 1045 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1047 1046 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1048 1047 ('', 'pull', None, _('use pull protocol to copy metadata')),
1049 1048 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1050 1049 ] + remoteopts,
1051 1050 _('[OPTION]... SOURCE [DEST]'))
1052 1051 def clone(ui, source, dest=None, **opts):
1053 1052 """make a copy of an existing repository
1054 1053
1055 1054 Create a copy of an existing repository in a new directory.
1056 1055
1057 1056 If no destination directory name is specified, it defaults to the
1058 1057 basename of the source.
1059 1058
1060 1059 The location of the source is added to the new repository's
1061 1060 ``.hg/hgrc`` file, as the default to be used for future pulls.
1062 1061
1063 1062 Only local paths and ``ssh://`` URLs are supported as
1064 1063 destinations. For ``ssh://`` destinations, no working directory or
1065 1064 ``.hg/hgrc`` will be created on the remote side.
1066 1065
1067 1066 To pull only a subset of changesets, specify one or more revisions
1068 1067 identifiers with -r/--rev or branches with -b/--branch. The
1069 1068 resulting clone will contain only the specified changesets and
1070 1069 their ancestors. These options (or 'clone src#rev dest') imply
1071 1070 --pull, even for local source repositories. Note that specifying a
1072 1071 tag will include the tagged changeset but not the changeset
1073 1072 containing the tag.
1074 1073
1075 1074 To check out a particular version, use -u/--update, or
1076 1075 -U/--noupdate to create a clone with no working directory.
1077 1076
1078 1077 .. container:: verbose
1079 1078
1080 1079 For efficiency, hardlinks are used for cloning whenever the
1081 1080 source and destination are on the same filesystem (note this
1082 1081 applies only to the repository data, not to the working
1083 1082 directory). Some filesystems, such as AFS, implement hardlinking
1084 1083 incorrectly, but do not report errors. In these cases, use the
1085 1084 --pull option to avoid hardlinking.
1086 1085
1087 1086 In some cases, you can clone repositories and the working
1088 1087 directory using full hardlinks with ::
1089 1088
1090 1089 $ cp -al REPO REPOCLONE
1091 1090
1092 1091 This is the fastest way to clone, but it is not always safe. The
1093 1092 operation is not atomic (making sure REPO is not modified during
1094 1093 the operation is up to you) and you have to make sure your
1095 1094 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1096 1095 so). Also, this is not compatible with certain extensions that
1097 1096 place their metadata under the .hg directory, such as mq.
1098 1097
1099 1098 Mercurial will update the working directory to the first applicable
1100 1099 revision from this list:
1101 1100
1102 1101 a) null if -U or the source repository has no changesets
1103 1102 b) if -u . and the source repository is local, the first parent of
1104 1103 the source repository's working directory
1105 1104 c) the changeset specified with -u (if a branch name, this means the
1106 1105 latest head of that branch)
1107 1106 d) the changeset specified with -r
1108 1107 e) the tipmost head specified with -b
1109 1108 f) the tipmost head specified with the url#branch source syntax
1110 1109 g) the tipmost head of the default branch
1111 1110 h) tip
1112 1111
1113 1112 Examples:
1114 1113
1115 1114 - clone a remote repository to a new directory named hg/::
1116 1115
1117 1116 hg clone http://selenic.com/hg
1118 1117
1119 1118 - create a lightweight local clone::
1120 1119
1121 1120 hg clone project/ project-feature/
1122 1121
1123 1122 - clone from an absolute path on an ssh server (note double-slash)::
1124 1123
1125 1124 hg clone ssh://user@server//home/projects/alpha/
1126 1125
1127 1126 - do a high-speed clone over a LAN while checking out a
1128 1127 specified version::
1129 1128
1130 1129 hg clone --uncompressed http://server/repo -u 1.5
1131 1130
1132 1131 - create a repository without changesets after a particular revision::
1133 1132
1134 1133 hg clone -r 04e544 experimental/ good/
1135 1134
1136 1135 - clone (and track) a particular named branch::
1137 1136
1138 1137 hg clone http://selenic.com/hg#stable
1139 1138
1140 1139 See :hg:`help urls` for details on specifying URLs.
1141 1140
1142 1141 Returns 0 on success.
1143 1142 """
1144 1143 if opts.get('noupdate') and opts.get('updaterev'):
1145 1144 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1146 1145
1147 1146 r = hg.clone(ui, opts, source, dest,
1148 1147 pull=opts.get('pull'),
1149 1148 stream=opts.get('uncompressed'),
1150 1149 rev=opts.get('rev'),
1151 1150 update=opts.get('updaterev') or not opts.get('noupdate'),
1152 1151 branch=opts.get('branch'))
1153 1152
1154 1153 return r is None
1155 1154
1156 1155 @command('^commit|ci',
1157 1156 [('A', 'addremove', None,
1158 1157 _('mark new/missing files as added/removed before committing')),
1159 1158 ('', 'close-branch', None,
1160 1159 _('mark a branch as closed, hiding it from the branch list')),
1161 1160 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1162 1161 _('[OPTION]... [FILE]...'))
1163 1162 def commit(ui, repo, *pats, **opts):
1164 1163 """commit the specified files or all outstanding changes
1165 1164
1166 1165 Commit changes to the given files into the repository. Unlike a
1167 1166 centralized SCM, this operation is a local operation. See
1168 1167 :hg:`push` for a way to actively distribute your changes.
1169 1168
1170 1169 If a list of files is omitted, all changes reported by :hg:`status`
1171 1170 will be committed.
1172 1171
1173 1172 If you are committing the result of a merge, do not provide any
1174 1173 filenames or -I/-X filters.
1175 1174
1176 1175 If no commit message is specified, Mercurial starts your
1177 1176 configured editor where you can enter a message. In case your
1178 1177 commit fails, you will find a backup of your message in
1179 1178 ``.hg/last-message.txt``.
1180 1179
1181 1180 See :hg:`help dates` for a list of formats valid for -d/--date.
1182 1181
1183 1182 Returns 0 on success, 1 if nothing changed.
1184 1183 """
1185 1184 if opts.get('subrepos'):
1186 1185 # Let --subrepos on the command line overide config setting.
1187 1186 ui.setconfig('ui', 'commitsubrepos', True)
1188 1187
1189 1188 extra = {}
1190 1189 if opts.get('close_branch'):
1191 1190 if repo['.'].node() not in repo.branchheads():
1192 1191 # The topo heads set is included in the branch heads set of the
1193 1192 # current branch, so it's sufficient to test branchheads
1194 1193 raise util.Abort(_('can only close branch heads'))
1195 1194 extra['close'] = 1
1196 1195 e = cmdutil.commiteditor
1197 1196 if opts.get('force_editor'):
1198 1197 e = cmdutil.commitforceeditor
1199 1198
1200 1199 def commitfunc(ui, repo, message, match, opts):
1201 1200 return repo.commit(message, opts.get('user'), opts.get('date'), match,
1202 1201 editor=e, extra=extra)
1203 1202
1204 1203 branch = repo[None].branch()
1205 1204 bheads = repo.branchheads(branch)
1206 1205
1207 1206 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1208 1207 if not node:
1209 1208 stat = repo.status(match=scmutil.match(repo[None], pats, opts))
1210 1209 if stat[3]:
1211 1210 ui.status(_("nothing changed (%d missing files, see 'hg status')\n")
1212 1211 % len(stat[3]))
1213 1212 else:
1214 1213 ui.status(_("nothing changed\n"))
1215 1214 return 1
1216 1215
1217 1216 ctx = repo[node]
1218 1217 parents = ctx.parents()
1219 1218
1220 1219 if (bheads and node not in bheads and not
1221 1220 [x for x in parents if x.node() in bheads and x.branch() == branch]):
1222 1221 ui.status(_('created new head\n'))
1223 1222 # The message is not printed for initial roots. For the other
1224 1223 # changesets, it is printed in the following situations:
1225 1224 #
1226 1225 # Par column: for the 2 parents with ...
1227 1226 # N: null or no parent
1228 1227 # B: parent is on another named branch
1229 1228 # C: parent is a regular non head changeset
1230 1229 # H: parent was a branch head of the current branch
1231 1230 # Msg column: whether we print "created new head" message
1232 1231 # In the following, it is assumed that there already exists some
1233 1232 # initial branch heads of the current branch, otherwise nothing is
1234 1233 # printed anyway.
1235 1234 #
1236 1235 # Par Msg Comment
1237 1236 # NN y additional topo root
1238 1237 #
1239 1238 # BN y additional branch root
1240 1239 # CN y additional topo head
1241 1240 # HN n usual case
1242 1241 #
1243 1242 # BB y weird additional branch root
1244 1243 # CB y branch merge
1245 1244 # HB n merge with named branch
1246 1245 #
1247 1246 # CC y additional head from merge
1248 1247 # CH n merge with a head
1249 1248 #
1250 1249 # HH n head merge: head count decreases
1251 1250
1252 1251 if not opts.get('close_branch'):
1253 1252 for r in parents:
1254 1253 if r.extra().get('close') and r.branch() == branch:
1255 1254 ui.status(_('reopening closed branch head %d\n') % r)
1256 1255
1257 1256 if ui.debugflag:
1258 1257 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
1259 1258 elif ui.verbose:
1260 1259 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
1261 1260
1262 1261 @command('copy|cp',
1263 1262 [('A', 'after', None, _('record a copy that has already occurred')),
1264 1263 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1265 1264 ] + walkopts + dryrunopts,
1266 1265 _('[OPTION]... [SOURCE]... DEST'))
1267 1266 def copy(ui, repo, *pats, **opts):
1268 1267 """mark files as copied for the next commit
1269 1268
1270 1269 Mark dest as having copies of source files. If dest is a
1271 1270 directory, copies are put in that directory. If dest is a file,
1272 1271 the source must be a single file.
1273 1272
1274 1273 By default, this command copies the contents of files as they
1275 1274 exist in the working directory. If invoked with -A/--after, the
1276 1275 operation is recorded, but no copying is performed.
1277 1276
1278 1277 This command takes effect with the next commit. To undo a copy
1279 1278 before that, see :hg:`revert`.
1280 1279
1281 1280 Returns 0 on success, 1 if errors are encountered.
1282 1281 """
1283 1282 wlock = repo.wlock(False)
1284 1283 try:
1285 1284 return cmdutil.copy(ui, repo, pats, opts)
1286 1285 finally:
1287 1286 wlock.release()
1288 1287
1289 1288 @command('debugancestor', [], _('[INDEX] REV1 REV2'))
1290 1289 def debugancestor(ui, repo, *args):
1291 1290 """find the ancestor revision of two revisions in a given index"""
1292 1291 if len(args) == 3:
1293 1292 index, rev1, rev2 = args
1294 1293 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1295 1294 lookup = r.lookup
1296 1295 elif len(args) == 2:
1297 1296 if not repo:
1298 1297 raise util.Abort(_("there is no Mercurial repository here "
1299 1298 "(.hg not found)"))
1300 1299 rev1, rev2 = args
1301 1300 r = repo.changelog
1302 1301 lookup = repo.lookup
1303 1302 else:
1304 1303 raise util.Abort(_('either two or three arguments required'))
1305 1304 a = r.ancestor(lookup(rev1), lookup(rev2))
1306 1305 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1307 1306
1308 1307 @command('debugbuilddag',
1309 1308 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1310 1309 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1311 1310 ('n', 'new-file', None, _('add new file at each rev'))],
1312 1311 _('[OPTION]... [TEXT]'))
1313 1312 def debugbuilddag(ui, repo, text=None,
1314 1313 mergeable_file=False,
1315 1314 overwritten_file=False,
1316 1315 new_file=False):
1317 1316 """builds a repo with a given DAG from scratch in the current empty repo
1318 1317
1319 1318 The description of the DAG is read from stdin if not given on the
1320 1319 command line.
1321 1320
1322 1321 Elements:
1323 1322
1324 1323 - "+n" is a linear run of n nodes based on the current default parent
1325 1324 - "." is a single node based on the current default parent
1326 1325 - "$" resets the default parent to null (implied at the start);
1327 1326 otherwise the default parent is always the last node created
1328 1327 - "<p" sets the default parent to the backref p
1329 1328 - "*p" is a fork at parent p, which is a backref
1330 1329 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1331 1330 - "/p2" is a merge of the preceding node and p2
1332 1331 - ":tag" defines a local tag for the preceding node
1333 1332 - "@branch" sets the named branch for subsequent nodes
1334 1333 - "#...\\n" is a comment up to the end of the line
1335 1334
1336 1335 Whitespace between the above elements is ignored.
1337 1336
1338 1337 A backref is either
1339 1338
1340 1339 - a number n, which references the node curr-n, where curr is the current
1341 1340 node, or
1342 1341 - the name of a local tag you placed earlier using ":tag", or
1343 1342 - empty to denote the default parent.
1344 1343
1345 1344 All string valued-elements are either strictly alphanumeric, or must
1346 1345 be enclosed in double quotes ("..."), with "\\" as escape character.
1347 1346 """
1348 1347
1349 1348 if text is None:
1350 1349 ui.status(_("reading DAG from stdin\n"))
1351 1350 text = ui.fin.read()
1352 1351
1353 1352 cl = repo.changelog
1354 1353 if len(cl) > 0:
1355 1354 raise util.Abort(_('repository is not empty'))
1356 1355
1357 1356 # determine number of revs in DAG
1358 1357 total = 0
1359 1358 for type, data in dagparser.parsedag(text):
1360 1359 if type == 'n':
1361 1360 total += 1
1362 1361
1363 1362 if mergeable_file:
1364 1363 linesperrev = 2
1365 1364 # make a file with k lines per rev
1366 1365 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1367 1366 initialmergedlines.append("")
1368 1367
1369 1368 tags = []
1370 1369
1371 1370 lock = tr = None
1372 1371 try:
1373 1372 lock = repo.lock()
1374 1373 tr = repo.transaction("builddag")
1375 1374
1376 1375 at = -1
1377 1376 atbranch = 'default'
1378 1377 nodeids = []
1379 1378 ui.progress(_('building'), 0, unit=_('revisions'), total=total)
1380 1379 for type, data in dagparser.parsedag(text):
1381 1380 if type == 'n':
1382 1381 ui.note('node %s\n' % str(data))
1383 1382 id, ps = data
1384 1383
1385 1384 files = []
1386 1385 fctxs = {}
1387 1386
1388 1387 p2 = None
1389 1388 if mergeable_file:
1390 1389 fn = "mf"
1391 1390 p1 = repo[ps[0]]
1392 1391 if len(ps) > 1:
1393 1392 p2 = repo[ps[1]]
1394 1393 pa = p1.ancestor(p2)
1395 1394 base, local, other = [x[fn].data() for x in pa, p1, p2]
1396 1395 m3 = simplemerge.Merge3Text(base, local, other)
1397 1396 ml = [l.strip() for l in m3.merge_lines()]
1398 1397 ml.append("")
1399 1398 elif at > 0:
1400 1399 ml = p1[fn].data().split("\n")
1401 1400 else:
1402 1401 ml = initialmergedlines
1403 1402 ml[id * linesperrev] += " r%i" % id
1404 1403 mergedtext = "\n".join(ml)
1405 1404 files.append(fn)
1406 1405 fctxs[fn] = context.memfilectx(fn, mergedtext)
1407 1406
1408 1407 if overwritten_file:
1409 1408 fn = "of"
1410 1409 files.append(fn)
1411 1410 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1412 1411
1413 1412 if new_file:
1414 1413 fn = "nf%i" % id
1415 1414 files.append(fn)
1416 1415 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1417 1416 if len(ps) > 1:
1418 1417 if not p2:
1419 1418 p2 = repo[ps[1]]
1420 1419 for fn in p2:
1421 1420 if fn.startswith("nf"):
1422 1421 files.append(fn)
1423 1422 fctxs[fn] = p2[fn]
1424 1423
1425 1424 def fctxfn(repo, cx, path):
1426 1425 return fctxs.get(path)
1427 1426
1428 1427 if len(ps) == 0 or ps[0] < 0:
1429 1428 pars = [None, None]
1430 1429 elif len(ps) == 1:
1431 1430 pars = [nodeids[ps[0]], None]
1432 1431 else:
1433 1432 pars = [nodeids[p] for p in ps]
1434 1433 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1435 1434 date=(id, 0),
1436 1435 user="debugbuilddag",
1437 1436 extra={'branch': atbranch})
1438 1437 nodeid = repo.commitctx(cx)
1439 1438 nodeids.append(nodeid)
1440 1439 at = id
1441 1440 elif type == 'l':
1442 1441 id, name = data
1443 1442 ui.note('tag %s\n' % name)
1444 1443 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1445 1444 elif type == 'a':
1446 1445 ui.note('branch %s\n' % data)
1447 1446 atbranch = data
1448 1447 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1449 1448 tr.close()
1450 1449
1451 1450 if tags:
1452 1451 repo.opener.write("localtags", "".join(tags))
1453 1452 finally:
1454 1453 ui.progress(_('building'), None)
1455 1454 release(tr, lock)
1456 1455
1457 1456 @command('debugbundle', [('a', 'all', None, _('show all details'))], _('FILE'))
1458 1457 def debugbundle(ui, bundlepath, all=None, **opts):
1459 1458 """lists the contents of a bundle"""
1460 1459 f = url.open(ui, bundlepath)
1461 1460 try:
1462 1461 gen = changegroup.readbundle(f, bundlepath)
1463 1462 if all:
1464 1463 ui.write("format: id, p1, p2, cset, delta base, len(delta)\n")
1465 1464
1466 1465 def showchunks(named):
1467 1466 ui.write("\n%s\n" % named)
1468 1467 chain = None
1469 1468 while True:
1470 1469 chunkdata = gen.deltachunk(chain)
1471 1470 if not chunkdata:
1472 1471 break
1473 1472 node = chunkdata['node']
1474 1473 p1 = chunkdata['p1']
1475 1474 p2 = chunkdata['p2']
1476 1475 cs = chunkdata['cs']
1477 1476 deltabase = chunkdata['deltabase']
1478 1477 delta = chunkdata['delta']
1479 1478 ui.write("%s %s %s %s %s %s\n" %
1480 1479 (hex(node), hex(p1), hex(p2),
1481 1480 hex(cs), hex(deltabase), len(delta)))
1482 1481 chain = node
1483 1482
1484 1483 chunkdata = gen.changelogheader()
1485 1484 showchunks("changelog")
1486 1485 chunkdata = gen.manifestheader()
1487 1486 showchunks("manifest")
1488 1487 while True:
1489 1488 chunkdata = gen.filelogheader()
1490 1489 if not chunkdata:
1491 1490 break
1492 1491 fname = chunkdata['filename']
1493 1492 showchunks(fname)
1494 1493 else:
1495 1494 chunkdata = gen.changelogheader()
1496 1495 chain = None
1497 1496 while True:
1498 1497 chunkdata = gen.deltachunk(chain)
1499 1498 if not chunkdata:
1500 1499 break
1501 1500 node = chunkdata['node']
1502 1501 ui.write("%s\n" % hex(node))
1503 1502 chain = node
1504 1503 finally:
1505 1504 f.close()
1506 1505
1507 1506 @command('debugcheckstate', [], '')
1508 1507 def debugcheckstate(ui, repo):
1509 1508 """validate the correctness of the current dirstate"""
1510 1509 parent1, parent2 = repo.dirstate.parents()
1511 1510 m1 = repo[parent1].manifest()
1512 1511 m2 = repo[parent2].manifest()
1513 1512 errors = 0
1514 1513 for f in repo.dirstate:
1515 1514 state = repo.dirstate[f]
1516 1515 if state in "nr" and f not in m1:
1517 1516 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1518 1517 errors += 1
1519 1518 if state in "a" and f in m1:
1520 1519 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1521 1520 errors += 1
1522 1521 if state in "m" and f not in m1 and f not in m2:
1523 1522 ui.warn(_("%s in state %s, but not in either manifest\n") %
1524 1523 (f, state))
1525 1524 errors += 1
1526 1525 for f in m1:
1527 1526 state = repo.dirstate[f]
1528 1527 if state not in "nrm":
1529 1528 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1530 1529 errors += 1
1531 1530 if errors:
1532 1531 error = _(".hg/dirstate inconsistent with current parent's manifest")
1533 1532 raise util.Abort(error)
1534 1533
1535 1534 @command('debugcommands', [], _('[COMMAND]'))
1536 1535 def debugcommands(ui, cmd='', *args):
1537 1536 """list all available commands and options"""
1538 1537 for cmd, vals in sorted(table.iteritems()):
1539 1538 cmd = cmd.split('|')[0].strip('^')
1540 1539 opts = ', '.join([i[1] for i in vals[1]])
1541 1540 ui.write('%s: %s\n' % (cmd, opts))
1542 1541
1543 1542 @command('debugcomplete',
1544 1543 [('o', 'options', None, _('show the command options'))],
1545 1544 _('[-o] CMD'))
1546 1545 def debugcomplete(ui, cmd='', **opts):
1547 1546 """returns the completion list associated with the given command"""
1548 1547
1549 1548 if opts.get('options'):
1550 1549 options = []
1551 1550 otables = [globalopts]
1552 1551 if cmd:
1553 1552 aliases, entry = cmdutil.findcmd(cmd, table, False)
1554 1553 otables.append(entry[1])
1555 1554 for t in otables:
1556 1555 for o in t:
1557 1556 if "(DEPRECATED)" in o[3]:
1558 1557 continue
1559 1558 if o[0]:
1560 1559 options.append('-%s' % o[0])
1561 1560 options.append('--%s' % o[1])
1562 1561 ui.write("%s\n" % "\n".join(options))
1563 1562 return
1564 1563
1565 1564 cmdlist = cmdutil.findpossible(cmd, table)
1566 1565 if ui.verbose:
1567 1566 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1568 1567 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1569 1568
1570 1569 @command('debugdag',
1571 1570 [('t', 'tags', None, _('use tags as labels')),
1572 1571 ('b', 'branches', None, _('annotate with branch names')),
1573 1572 ('', 'dots', None, _('use dots for runs')),
1574 1573 ('s', 'spaces', None, _('separate elements by spaces'))],
1575 1574 _('[OPTION]... [FILE [REV]...]'))
1576 1575 def debugdag(ui, repo, file_=None, *revs, **opts):
1577 1576 """format the changelog or an index DAG as a concise textual description
1578 1577
1579 1578 If you pass a revlog index, the revlog's DAG is emitted. If you list
1580 1579 revision numbers, they get labelled in the output as rN.
1581 1580
1582 1581 Otherwise, the changelog DAG of the current repo is emitted.
1583 1582 """
1584 1583 spaces = opts.get('spaces')
1585 1584 dots = opts.get('dots')
1586 1585 if file_:
1587 1586 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1588 1587 revs = set((int(r) for r in revs))
1589 1588 def events():
1590 1589 for r in rlog:
1591 1590 yield 'n', (r, list(set(p for p in rlog.parentrevs(r) if p != -1)))
1592 1591 if r in revs:
1593 1592 yield 'l', (r, "r%i" % r)
1594 1593 elif repo:
1595 1594 cl = repo.changelog
1596 1595 tags = opts.get('tags')
1597 1596 branches = opts.get('branches')
1598 1597 if tags:
1599 1598 labels = {}
1600 1599 for l, n in repo.tags().items():
1601 1600 labels.setdefault(cl.rev(n), []).append(l)
1602 1601 def events():
1603 1602 b = "default"
1604 1603 for r in cl:
1605 1604 if branches:
1606 1605 newb = cl.read(cl.node(r))[5]['branch']
1607 1606 if newb != b:
1608 1607 yield 'a', newb
1609 1608 b = newb
1610 1609 yield 'n', (r, list(set(p for p in cl.parentrevs(r) if p != -1)))
1611 1610 if tags:
1612 1611 ls = labels.get(r)
1613 1612 if ls:
1614 1613 for l in ls:
1615 1614 yield 'l', (r, l)
1616 1615 else:
1617 1616 raise util.Abort(_('need repo for changelog dag'))
1618 1617
1619 1618 for line in dagparser.dagtextlines(events(),
1620 1619 addspaces=spaces,
1621 1620 wraplabels=True,
1622 1621 wrapannotations=True,
1623 1622 wrapnonlinear=dots,
1624 1623 usedots=dots,
1625 1624 maxlinewidth=70):
1626 1625 ui.write(line)
1627 1626 ui.write("\n")
1628 1627
1629 1628 @command('debugdata',
1630 1629 [('c', 'changelog', False, _('open changelog')),
1631 1630 ('m', 'manifest', False, _('open manifest'))],
1632 1631 _('-c|-m|FILE REV'))
1633 1632 def debugdata(ui, repo, file_, rev = None, **opts):
1634 1633 """dump the contents of a data file revision"""
1635 1634 if opts.get('changelog') or opts.get('manifest'):
1636 1635 file_, rev = None, file_
1637 1636 elif rev is None:
1638 1637 raise error.CommandError('debugdata', _('invalid arguments'))
1639 1638 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1640 1639 try:
1641 1640 ui.write(r.revision(r.lookup(rev)))
1642 1641 except KeyError:
1643 1642 raise util.Abort(_('invalid revision identifier %s') % rev)
1644 1643
1645 1644 @command('debugdate',
1646 1645 [('e', 'extended', None, _('try extended date formats'))],
1647 1646 _('[-e] DATE [RANGE]'))
1648 1647 def debugdate(ui, date, range=None, **opts):
1649 1648 """parse and display a date"""
1650 1649 if opts["extended"]:
1651 1650 d = util.parsedate(date, util.extendeddateformats)
1652 1651 else:
1653 1652 d = util.parsedate(date)
1654 1653 ui.write("internal: %s %s\n" % d)
1655 1654 ui.write("standard: %s\n" % util.datestr(d))
1656 1655 if range:
1657 1656 m = util.matchdate(range)
1658 1657 ui.write("match: %s\n" % m(d[0]))
1659 1658
1660 1659 @command('debugdiscovery',
1661 1660 [('', 'old', None, _('use old-style discovery')),
1662 1661 ('', 'nonheads', None,
1663 1662 _('use old-style discovery with non-heads included')),
1664 1663 ] + remoteopts,
1665 1664 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1666 1665 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1667 1666 """runs the changeset discovery protocol in isolation"""
1668 1667 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl), opts.get('branch'))
1669 1668 remote = hg.peer(repo, opts, remoteurl)
1670 1669 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1671 1670
1672 1671 # make sure tests are repeatable
1673 1672 random.seed(12323)
1674 1673
1675 1674 def doit(localheads, remoteheads):
1676 1675 if opts.get('old'):
1677 1676 if localheads:
1678 1677 raise util.Abort('cannot use localheads with old style discovery')
1679 1678 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
1680 1679 force=True)
1681 1680 common = set(common)
1682 1681 if not opts.get('nonheads'):
1683 1682 ui.write("unpruned common: %s\n" % " ".join([short(n)
1684 1683 for n in common]))
1685 1684 dag = dagutil.revlogdag(repo.changelog)
1686 1685 all = dag.ancestorset(dag.internalizeall(common))
1687 1686 common = dag.externalizeall(dag.headsetofconnecteds(all))
1688 1687 else:
1689 1688 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
1690 1689 common = set(common)
1691 1690 rheads = set(hds)
1692 1691 lheads = set(repo.heads())
1693 1692 ui.write("common heads: %s\n" % " ".join([short(n) for n in common]))
1694 1693 if lheads <= common:
1695 1694 ui.write("local is subset\n")
1696 1695 elif rheads <= common:
1697 1696 ui.write("remote is subset\n")
1698 1697
1699 1698 serverlogs = opts.get('serverlog')
1700 1699 if serverlogs:
1701 1700 for filename in serverlogs:
1702 1701 logfile = open(filename, 'r')
1703 1702 try:
1704 1703 line = logfile.readline()
1705 1704 while line:
1706 1705 parts = line.strip().split(';')
1707 1706 op = parts[1]
1708 1707 if op == 'cg':
1709 1708 pass
1710 1709 elif op == 'cgss':
1711 1710 doit(parts[2].split(' '), parts[3].split(' '))
1712 1711 elif op == 'unb':
1713 1712 doit(parts[3].split(' '), parts[2].split(' '))
1714 1713 line = logfile.readline()
1715 1714 finally:
1716 1715 logfile.close()
1717 1716
1718 1717 else:
1719 1718 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
1720 1719 opts.get('remote_head'))
1721 1720 localrevs = opts.get('local_head')
1722 1721 doit(localrevs, remoterevs)
1723 1722
1724 1723 @command('debugfileset', [], ('REVSPEC'))
1725 1724 def debugfileset(ui, repo, expr):
1726 1725 '''parse and apply a fileset specification'''
1727 1726 if ui.verbose:
1728 1727 tree = fileset.parse(expr)[0]
1729 1728 ui.note(tree, "\n")
1730 1729
1731 1730 for f in fileset.getfileset(repo[None], expr):
1732 1731 ui.write("%s\n" % f)
1733 1732
1734 1733 @command('debugfsinfo', [], _('[PATH]'))
1735 1734 def debugfsinfo(ui, path = "."):
1736 1735 """show information detected about current filesystem"""
1737 1736 util.writefile('.debugfsinfo', '')
1738 1737 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
1739 1738 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
1740 1739 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
1741 1740 and 'yes' or 'no'))
1742 1741 os.unlink('.debugfsinfo')
1743 1742
1744 1743 @command('debuggetbundle',
1745 1744 [('H', 'head', [], _('id of head node'), _('ID')),
1746 1745 ('C', 'common', [], _('id of common node'), _('ID')),
1747 1746 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
1748 1747 _('REPO FILE [-H|-C ID]...'))
1749 1748 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1750 1749 """retrieves a bundle from a repo
1751 1750
1752 1751 Every ID must be a full-length hex node id string. Saves the bundle to the
1753 1752 given file.
1754 1753 """
1755 1754 repo = hg.peer(ui, opts, repopath)
1756 1755 if not repo.capable('getbundle'):
1757 1756 raise util.Abort("getbundle() not supported by target repository")
1758 1757 args = {}
1759 1758 if common:
1760 1759 args['common'] = [bin(s) for s in common]
1761 1760 if head:
1762 1761 args['heads'] = [bin(s) for s in head]
1763 1762 bundle = repo.getbundle('debug', **args)
1764 1763
1765 1764 bundletype = opts.get('type', 'bzip2').lower()
1766 1765 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1767 1766 bundletype = btypes.get(bundletype)
1768 1767 if bundletype not in changegroup.bundletypes:
1769 1768 raise util.Abort(_('unknown bundle type specified with --type'))
1770 1769 changegroup.writebundle(bundle, bundlepath, bundletype)
1771 1770
1772 1771 @command('debugignore', [], '')
1773 1772 def debugignore(ui, repo, *values, **opts):
1774 1773 """display the combined ignore pattern"""
1775 1774 ignore = repo.dirstate._ignore
1776 1775 includepat = getattr(ignore, 'includepat', None)
1777 1776 if includepat is not None:
1778 1777 ui.write("%s\n" % includepat)
1779 1778 else:
1780 1779 raise util.Abort(_("no ignore patterns found"))
1781 1780
1782 1781 @command('debugindex',
1783 1782 [('c', 'changelog', False, _('open changelog')),
1784 1783 ('m', 'manifest', False, _('open manifest')),
1785 1784 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
1786 1785 _('[-f FORMAT] -c|-m|FILE'))
1787 1786 def debugindex(ui, repo, file_ = None, **opts):
1788 1787 """dump the contents of an index file"""
1789 1788 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
1790 1789 format = opts.get('format', 0)
1791 1790 if format not in (0, 1):
1792 1791 raise util.Abort(_("unknown format %d") % format)
1793 1792
1794 1793 generaldelta = r.version & revlog.REVLOGGENERALDELTA
1795 1794 if generaldelta:
1796 1795 basehdr = ' delta'
1797 1796 else:
1798 1797 basehdr = ' base'
1799 1798
1800 1799 if format == 0:
1801 1800 ui.write(" rev offset length " + basehdr + " linkrev"
1802 1801 " nodeid p1 p2\n")
1803 1802 elif format == 1:
1804 1803 ui.write(" rev flag offset length"
1805 1804 " size " + basehdr + " link p1 p2 nodeid\n")
1806 1805
1807 1806 for i in r:
1808 1807 node = r.node(i)
1809 1808 if generaldelta:
1810 1809 base = r.deltaparent(i)
1811 1810 else:
1812 1811 base = r.chainbase(i)
1813 1812 if format == 0:
1814 1813 try:
1815 1814 pp = r.parents(node)
1816 1815 except:
1817 1816 pp = [nullid, nullid]
1818 1817 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1819 1818 i, r.start(i), r.length(i), base, r.linkrev(i),
1820 1819 short(node), short(pp[0]), short(pp[1])))
1821 1820 elif format == 1:
1822 1821 pr = r.parentrevs(i)
1823 1822 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
1824 1823 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
1825 1824 base, r.linkrev(i), pr[0], pr[1], short(node)))
1826 1825
1827 1826 @command('debugindexdot', [], _('FILE'))
1828 1827 def debugindexdot(ui, repo, file_):
1829 1828 """dump an index DAG as a graphviz dot file"""
1830 1829 r = None
1831 1830 if repo:
1832 1831 filelog = repo.file(file_)
1833 1832 if len(filelog):
1834 1833 r = filelog
1835 1834 if not r:
1836 1835 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1837 1836 ui.write("digraph G {\n")
1838 1837 for i in r:
1839 1838 node = r.node(i)
1840 1839 pp = r.parents(node)
1841 1840 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1842 1841 if pp[1] != nullid:
1843 1842 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1844 1843 ui.write("}\n")
1845 1844
1846 1845 @command('debuginstall', [], '')
1847 1846 def debuginstall(ui):
1848 1847 '''test Mercurial installation
1849 1848
1850 1849 Returns 0 on success.
1851 1850 '''
1852 1851
1853 1852 def writetemp(contents):
1854 1853 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
1855 1854 f = os.fdopen(fd, "wb")
1856 1855 f.write(contents)
1857 1856 f.close()
1858 1857 return name
1859 1858
1860 1859 problems = 0
1861 1860
1862 1861 # encoding
1863 1862 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
1864 1863 try:
1865 1864 encoding.fromlocal("test")
1866 1865 except util.Abort, inst:
1867 1866 ui.write(" %s\n" % inst)
1868 1867 ui.write(_(" (check that your locale is properly set)\n"))
1869 1868 problems += 1
1870 1869
1871 1870 # compiled modules
1872 1871 ui.status(_("Checking installed modules (%s)...\n")
1873 1872 % os.path.dirname(__file__))
1874 1873 try:
1875 1874 import bdiff, mpatch, base85, osutil
1876 1875 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
1877 1876 except Exception, inst:
1878 1877 ui.write(" %s\n" % inst)
1879 1878 ui.write(_(" One or more extensions could not be found"))
1880 1879 ui.write(_(" (check that you compiled the extensions)\n"))
1881 1880 problems += 1
1882 1881
1883 1882 # templates
1884 1883 import templater
1885 1884 p = templater.templatepath()
1886 1885 ui.status(_("Checking templates (%s)...\n") % ' '.join(p))
1887 1886 try:
1888 1887 templater.templater(templater.templatepath("map-cmdline.default"))
1889 1888 except Exception, inst:
1890 1889 ui.write(" %s\n" % inst)
1891 1890 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
1892 1891 problems += 1
1893 1892
1894 1893 # editor
1895 1894 ui.status(_("Checking commit editor...\n"))
1896 1895 editor = ui.geteditor()
1897 1896 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
1898 1897 if not cmdpath:
1899 1898 if editor == 'vi':
1900 1899 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
1901 1900 ui.write(_(" (specify a commit editor in your configuration"
1902 1901 " file)\n"))
1903 1902 else:
1904 1903 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
1905 1904 ui.write(_(" (specify a commit editor in your configuration"
1906 1905 " file)\n"))
1907 1906 problems += 1
1908 1907
1909 1908 # check username
1910 1909 ui.status(_("Checking username...\n"))
1911 1910 try:
1912 1911 ui.username()
1913 1912 except util.Abort, e:
1914 1913 ui.write(" %s\n" % e)
1915 1914 ui.write(_(" (specify a username in your configuration file)\n"))
1916 1915 problems += 1
1917 1916
1918 1917 if not problems:
1919 1918 ui.status(_("No problems detected\n"))
1920 1919 else:
1921 1920 ui.write(_("%s problems detected,"
1922 1921 " please check your install!\n") % problems)
1923 1922
1924 1923 return problems
1925 1924
1926 1925 @command('debugknown', [], _('REPO ID...'))
1927 1926 def debugknown(ui, repopath, *ids, **opts):
1928 1927 """test whether node ids are known to a repo
1929 1928
1930 1929 Every ID must be a full-length hex node id string. Returns a list of 0s and 1s
1931 1930 indicating unknown/known.
1932 1931 """
1933 1932 repo = hg.peer(ui, opts, repopath)
1934 1933 if not repo.capable('known'):
1935 1934 raise util.Abort("known() not supported by target repository")
1936 1935 flags = repo.known([bin(s) for s in ids])
1937 1936 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
1938 1937
1939 1938 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
1940 1939 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
1941 1940 '''access the pushkey key/value protocol
1942 1941
1943 1942 With two args, list the keys in the given namespace.
1944 1943
1945 1944 With five args, set a key to new if it currently is set to old.
1946 1945 Reports success or failure.
1947 1946 '''
1948 1947
1949 1948 target = hg.peer(ui, {}, repopath)
1950 1949 if keyinfo:
1951 1950 key, old, new = keyinfo
1952 1951 r = target.pushkey(namespace, key, old, new)
1953 1952 ui.status(str(r) + '\n')
1954 1953 return not r
1955 1954 else:
1956 1955 for k, v in target.listkeys(namespace).iteritems():
1957 1956 ui.write("%s\t%s\n" % (k.encode('string-escape'),
1958 1957 v.encode('string-escape')))
1959 1958
1960 1959 @command('debugrebuildstate',
1961 1960 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
1962 1961 _('[-r REV] [REV]'))
1963 1962 def debugrebuildstate(ui, repo, rev="tip"):
1964 1963 """rebuild the dirstate as it would look like for the given revision"""
1965 1964 ctx = scmutil.revsingle(repo, rev)
1966 1965 wlock = repo.wlock()
1967 1966 try:
1968 1967 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1969 1968 finally:
1970 1969 wlock.release()
1971 1970
1972 1971 @command('debugrename',
1973 1972 [('r', 'rev', '', _('revision to debug'), _('REV'))],
1974 1973 _('[-r REV] FILE'))
1975 1974 def debugrename(ui, repo, file1, *pats, **opts):
1976 1975 """dump rename information"""
1977 1976
1978 1977 ctx = scmutil.revsingle(repo, opts.get('rev'))
1979 1978 m = scmutil.match(ctx, (file1,) + pats, opts)
1980 1979 for abs in ctx.walk(m):
1981 1980 fctx = ctx[abs]
1982 1981 o = fctx.filelog().renamed(fctx.filenode())
1983 1982 rel = m.rel(abs)
1984 1983 if o:
1985 1984 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
1986 1985 else:
1987 1986 ui.write(_("%s not renamed\n") % rel)
1988 1987
1989 1988 @command('debugrevlog',
1990 1989 [('c', 'changelog', False, _('open changelog')),
1991 1990 ('m', 'manifest', False, _('open manifest')),
1992 1991 ('d', 'dump', False, _('dump index data'))],
1993 1992 _('-c|-m|FILE'))
1994 1993 def debugrevlog(ui, repo, file_ = None, **opts):
1995 1994 """show data and statistics about a revlog"""
1996 1995 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
1997 1996
1998 1997 if opts.get("dump"):
1999 1998 numrevs = len(r)
2000 1999 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
2001 2000 " rawsize totalsize compression heads\n")
2002 2001 ts = 0
2003 2002 heads = set()
2004 2003 for rev in xrange(numrevs):
2005 2004 dbase = r.deltaparent(rev)
2006 2005 if dbase == -1:
2007 2006 dbase = rev
2008 2007 cbase = r.chainbase(rev)
2009 2008 p1, p2 = r.parentrevs(rev)
2010 2009 rs = r.rawsize(rev)
2011 2010 ts = ts + rs
2012 2011 heads -= set(r.parentrevs(rev))
2013 2012 heads.add(rev)
2014 2013 ui.write("%d %d %d %d %d %d %d %d %d %d %d %d %d\n" %
2015 2014 (rev, p1, p2, r.start(rev), r.end(rev),
2016 2015 r.start(dbase), r.start(cbase),
2017 2016 r.start(p1), r.start(p2),
2018 2017 rs, ts, ts / r.end(rev), len(heads)))
2019 2018 return 0
2020 2019
2021 2020 v = r.version
2022 2021 format = v & 0xFFFF
2023 2022 flags = []
2024 2023 gdelta = False
2025 2024 if v & revlog.REVLOGNGINLINEDATA:
2026 2025 flags.append('inline')
2027 2026 if v & revlog.REVLOGGENERALDELTA:
2028 2027 gdelta = True
2029 2028 flags.append('generaldelta')
2030 2029 if not flags:
2031 2030 flags = ['(none)']
2032 2031
2033 2032 nummerges = 0
2034 2033 numfull = 0
2035 2034 numprev = 0
2036 2035 nump1 = 0
2037 2036 nump2 = 0
2038 2037 numother = 0
2039 2038 nump1prev = 0
2040 2039 nump2prev = 0
2041 2040 chainlengths = []
2042 2041
2043 2042 datasize = [None, 0, 0L]
2044 2043 fullsize = [None, 0, 0L]
2045 2044 deltasize = [None, 0, 0L]
2046 2045
2047 2046 def addsize(size, l):
2048 2047 if l[0] is None or size < l[0]:
2049 2048 l[0] = size
2050 2049 if size > l[1]:
2051 2050 l[1] = size
2052 2051 l[2] += size
2053 2052
2054 2053 numrevs = len(r)
2055 2054 for rev in xrange(numrevs):
2056 2055 p1, p2 = r.parentrevs(rev)
2057 2056 delta = r.deltaparent(rev)
2058 2057 if format > 0:
2059 2058 addsize(r.rawsize(rev), datasize)
2060 2059 if p2 != nullrev:
2061 2060 nummerges += 1
2062 2061 size = r.length(rev)
2063 2062 if delta == nullrev:
2064 2063 chainlengths.append(0)
2065 2064 numfull += 1
2066 2065 addsize(size, fullsize)
2067 2066 else:
2068 2067 chainlengths.append(chainlengths[delta] + 1)
2069 2068 addsize(size, deltasize)
2070 2069 if delta == rev - 1:
2071 2070 numprev += 1
2072 2071 if delta == p1:
2073 2072 nump1prev += 1
2074 2073 elif delta == p2:
2075 2074 nump2prev += 1
2076 2075 elif delta == p1:
2077 2076 nump1 += 1
2078 2077 elif delta == p2:
2079 2078 nump2 += 1
2080 2079 elif delta != nullrev:
2081 2080 numother += 1
2082 2081
2083 2082 numdeltas = numrevs - numfull
2084 2083 numoprev = numprev - nump1prev - nump2prev
2085 2084 totalrawsize = datasize[2]
2086 2085 datasize[2] /= numrevs
2087 2086 fulltotal = fullsize[2]
2088 2087 fullsize[2] /= numfull
2089 2088 deltatotal = deltasize[2]
2090 2089 deltasize[2] /= numrevs - numfull
2091 2090 totalsize = fulltotal + deltatotal
2092 2091 avgchainlen = sum(chainlengths) / numrevs
2093 2092 compratio = totalrawsize / totalsize
2094 2093
2095 2094 basedfmtstr = '%%%dd\n'
2096 2095 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
2097 2096
2098 2097 def dfmtstr(max):
2099 2098 return basedfmtstr % len(str(max))
2100 2099 def pcfmtstr(max, padding=0):
2101 2100 return basepcfmtstr % (len(str(max)), ' ' * padding)
2102 2101
2103 2102 def pcfmt(value, total):
2104 2103 return (value, 100 * float(value) / total)
2105 2104
2106 2105 ui.write('format : %d\n' % format)
2107 2106 ui.write('flags : %s\n' % ', '.join(flags))
2108 2107
2109 2108 ui.write('\n')
2110 2109 fmt = pcfmtstr(totalsize)
2111 2110 fmt2 = dfmtstr(totalsize)
2112 2111 ui.write('revisions : ' + fmt2 % numrevs)
2113 2112 ui.write(' merges : ' + fmt % pcfmt(nummerges, numrevs))
2114 2113 ui.write(' normal : ' + fmt % pcfmt(numrevs - nummerges, numrevs))
2115 2114 ui.write('revisions : ' + fmt2 % numrevs)
2116 2115 ui.write(' full : ' + fmt % pcfmt(numfull, numrevs))
2117 2116 ui.write(' deltas : ' + fmt % pcfmt(numdeltas, numrevs))
2118 2117 ui.write('revision size : ' + fmt2 % totalsize)
2119 2118 ui.write(' full : ' + fmt % pcfmt(fulltotal, totalsize))
2120 2119 ui.write(' deltas : ' + fmt % pcfmt(deltatotal, totalsize))
2121 2120
2122 2121 ui.write('\n')
2123 2122 fmt = dfmtstr(max(avgchainlen, compratio))
2124 2123 ui.write('avg chain length : ' + fmt % avgchainlen)
2125 2124 ui.write('compression ratio : ' + fmt % compratio)
2126 2125
2127 2126 if format > 0:
2128 2127 ui.write('\n')
2129 2128 ui.write('uncompressed data size (min/max/avg) : %d / %d / %d\n'
2130 2129 % tuple(datasize))
2131 2130 ui.write('full revision size (min/max/avg) : %d / %d / %d\n'
2132 2131 % tuple(fullsize))
2133 2132 ui.write('delta size (min/max/avg) : %d / %d / %d\n'
2134 2133 % tuple(deltasize))
2135 2134
2136 2135 if numdeltas > 0:
2137 2136 ui.write('\n')
2138 2137 fmt = pcfmtstr(numdeltas)
2139 2138 fmt2 = pcfmtstr(numdeltas, 4)
2140 2139 ui.write('deltas against prev : ' + fmt % pcfmt(numprev, numdeltas))
2141 2140 if numprev > 0:
2142 2141 ui.write(' where prev = p1 : ' + fmt2 % pcfmt(nump1prev, numprev))
2143 2142 ui.write(' where prev = p2 : ' + fmt2 % pcfmt(nump2prev, numprev))
2144 2143 ui.write(' other : ' + fmt2 % pcfmt(numoprev, numprev))
2145 2144 if gdelta:
2146 2145 ui.write('deltas against p1 : ' + fmt % pcfmt(nump1, numdeltas))
2147 2146 ui.write('deltas against p2 : ' + fmt % pcfmt(nump2, numdeltas))
2148 2147 ui.write('deltas against other : ' + fmt % pcfmt(numother, numdeltas))
2149 2148
2150 2149 @command('debugrevspec', [], ('REVSPEC'))
2151 2150 def debugrevspec(ui, repo, expr):
2152 2151 '''parse and apply a revision specification'''
2153 2152 if ui.verbose:
2154 2153 tree = revset.parse(expr)[0]
2155 2154 ui.note(tree, "\n")
2156 2155 newtree = revset.findaliases(ui, tree)
2157 2156 if newtree != tree:
2158 2157 ui.note(newtree, "\n")
2159 2158 func = revset.match(ui, expr)
2160 2159 for c in func(repo, range(len(repo))):
2161 2160 ui.write("%s\n" % c)
2162 2161
2163 2162 @command('debugsetparents', [], _('REV1 [REV2]'))
2164 2163 def debugsetparents(ui, repo, rev1, rev2=None):
2165 2164 """manually set the parents of the current working directory
2166 2165
2167 2166 This is useful for writing repository conversion tools, but should
2168 2167 be used with care.
2169 2168
2170 2169 Returns 0 on success.
2171 2170 """
2172 2171
2173 2172 r1 = scmutil.revsingle(repo, rev1).node()
2174 2173 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2175 2174
2176 2175 wlock = repo.wlock()
2177 2176 try:
2178 2177 repo.dirstate.setparents(r1, r2)
2179 2178 finally:
2180 2179 wlock.release()
2181 2180
2182 2181 @command('debugstate',
2183 2182 [('', 'nodates', None, _('do not display the saved mtime')),
2184 2183 ('', 'datesort', None, _('sort by saved mtime'))],
2185 2184 _('[OPTION]...'))
2186 2185 def debugstate(ui, repo, nodates=None, datesort=None):
2187 2186 """show the contents of the current dirstate"""
2188 2187 timestr = ""
2189 2188 showdate = not nodates
2190 2189 if datesort:
2191 2190 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2192 2191 else:
2193 2192 keyfunc = None # sort by filename
2194 2193 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2195 2194 if showdate:
2196 2195 if ent[3] == -1:
2197 2196 # Pad or slice to locale representation
2198 2197 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2199 2198 time.localtime(0)))
2200 2199 timestr = 'unset'
2201 2200 timestr = (timestr[:locale_len] +
2202 2201 ' ' * (locale_len - len(timestr)))
2203 2202 else:
2204 2203 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2205 2204 time.localtime(ent[3]))
2206 2205 if ent[1] & 020000:
2207 2206 mode = 'lnk'
2208 2207 else:
2209 2208 mode = '%3o' % (ent[1] & 0777 & ~util.umask)
2210 2209 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2211 2210 for f in repo.dirstate.copies():
2212 2211 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2213 2212
2214 2213 @command('debugsub',
2215 2214 [('r', 'rev', '',
2216 2215 _('revision to check'), _('REV'))],
2217 2216 _('[-r REV] [REV]'))
2218 2217 def debugsub(ui, repo, rev=None):
2219 2218 ctx = scmutil.revsingle(repo, rev, None)
2220 2219 for k, v in sorted(ctx.substate.items()):
2221 2220 ui.write('path %s\n' % k)
2222 2221 ui.write(' source %s\n' % v[0])
2223 2222 ui.write(' revision %s\n' % v[1])
2224 2223
2225 2224 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2226 2225 def debugwalk(ui, repo, *pats, **opts):
2227 2226 """show how files match on given patterns"""
2228 2227 m = scmutil.match(repo[None], pats, opts)
2229 2228 items = list(repo.walk(m))
2230 2229 if not items:
2231 2230 return
2232 2231 fmt = 'f %%-%ds %%-%ds %%s' % (
2233 2232 max([len(abs) for abs in items]),
2234 2233 max([len(m.rel(abs)) for abs in items]))
2235 2234 for abs in items:
2236 2235 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
2237 2236 ui.write("%s\n" % line.rstrip())
2238 2237
2239 2238 @command('debugwireargs',
2240 2239 [('', 'three', '', 'three'),
2241 2240 ('', 'four', '', 'four'),
2242 2241 ('', 'five', '', 'five'),
2243 2242 ] + remoteopts,
2244 2243 _('REPO [OPTIONS]... [ONE [TWO]]'))
2245 2244 def debugwireargs(ui, repopath, *vals, **opts):
2246 2245 repo = hg.peer(ui, opts, repopath)
2247 2246 for opt in remoteopts:
2248 2247 del opts[opt[1]]
2249 2248 args = {}
2250 2249 for k, v in opts.iteritems():
2251 2250 if v:
2252 2251 args[k] = v
2253 2252 # run twice to check that we don't mess up the stream for the next command
2254 2253 res1 = repo.debugwireargs(*vals, **args)
2255 2254 res2 = repo.debugwireargs(*vals, **args)
2256 2255 ui.write("%s\n" % res1)
2257 2256 if res1 != res2:
2258 2257 ui.warn("%s\n" % res2)
2259 2258
2260 2259 @command('^diff',
2261 2260 [('r', 'rev', [], _('revision'), _('REV')),
2262 2261 ('c', 'change', '', _('change made by revision'), _('REV'))
2263 2262 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2264 2263 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2265 2264 def diff(ui, repo, *pats, **opts):
2266 2265 """diff repository (or selected files)
2267 2266
2268 2267 Show differences between revisions for the specified files.
2269 2268
2270 2269 Differences between files are shown using the unified diff format.
2271 2270
2272 2271 .. note::
2273 2272 diff may generate unexpected results for merges, as it will
2274 2273 default to comparing against the working directory's first
2275 2274 parent changeset if no revisions are specified.
2276 2275
2277 2276 When two revision arguments are given, then changes are shown
2278 2277 between those revisions. If only one revision is specified then
2279 2278 that revision is compared to the working directory, and, when no
2280 2279 revisions are specified, the working directory files are compared
2281 2280 to its parent.
2282 2281
2283 2282 Alternatively you can specify -c/--change with a revision to see
2284 2283 the changes in that changeset relative to its first parent.
2285 2284
2286 2285 Without the -a/--text option, diff will avoid generating diffs of
2287 2286 files it detects as binary. With -a, diff will generate a diff
2288 2287 anyway, probably with undesirable results.
2289 2288
2290 2289 Use the -g/--git option to generate diffs in the git extended diff
2291 2290 format. For more information, read :hg:`help diffs`.
2292 2291
2293 2292 .. container:: verbose
2294 2293
2295 2294 Examples:
2296 2295
2297 2296 - compare a file in the current working directory to its parent::
2298 2297
2299 2298 hg diff foo.c
2300 2299
2301 2300 - compare two historical versions of a directory, with rename info::
2302 2301
2303 2302 hg diff --git -r 1.0:1.2 lib/
2304 2303
2305 2304 - get change stats relative to the last change on some date::
2306 2305
2307 2306 hg diff --stat -r "date('may 2')"
2308 2307
2309 2308 - diff all newly-added files that contain a keyword::
2310 2309
2311 2310 hg diff "set:added() and grep(GNU)"
2312 2311
2313 2312 - compare a revision and its parents::
2314 2313
2315 2314 hg diff -c 9353 # compare against first parent
2316 2315 hg diff -r 9353^:9353 # same using revset syntax
2317 2316 hg diff -r 9353^2:9353 # compare against the second parent
2318 2317
2319 2318 Returns 0 on success.
2320 2319 """
2321 2320
2322 2321 revs = opts.get('rev')
2323 2322 change = opts.get('change')
2324 2323 stat = opts.get('stat')
2325 2324 reverse = opts.get('reverse')
2326 2325
2327 2326 if revs and change:
2328 2327 msg = _('cannot specify --rev and --change at the same time')
2329 2328 raise util.Abort(msg)
2330 2329 elif change:
2331 2330 node2 = scmutil.revsingle(repo, change, None).node()
2332 2331 node1 = repo[node2].p1().node()
2333 2332 else:
2334 2333 node1, node2 = scmutil.revpair(repo, revs)
2335 2334
2336 2335 if reverse:
2337 2336 node1, node2 = node2, node1
2338 2337
2339 2338 diffopts = patch.diffopts(ui, opts)
2340 2339 m = scmutil.match(repo[node2], pats, opts)
2341 2340 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2342 2341 listsubrepos=opts.get('subrepos'))
2343 2342
2344 2343 @command('^export',
2345 2344 [('o', 'output', '',
2346 2345 _('print output to file with formatted name'), _('FORMAT')),
2347 2346 ('', 'switch-parent', None, _('diff against the second parent')),
2348 2347 ('r', 'rev', [], _('revisions to export'), _('REV')),
2349 2348 ] + diffopts,
2350 2349 _('[OPTION]... [-o OUTFILESPEC] REV...'))
2351 2350 def export(ui, repo, *changesets, **opts):
2352 2351 """dump the header and diffs for one or more changesets
2353 2352
2354 2353 Print the changeset header and diffs for one or more revisions.
2355 2354
2356 2355 The information shown in the changeset header is: author, date,
2357 2356 branch name (if non-default), changeset hash, parent(s) and commit
2358 2357 comment.
2359 2358
2360 2359 .. note::
2361 2360 export may generate unexpected diff output for merge
2362 2361 changesets, as it will compare the merge changeset against its
2363 2362 first parent only.
2364 2363
2365 2364 Output may be to a file, in which case the name of the file is
2366 2365 given using a format string. The formatting rules are as follows:
2367 2366
2368 2367 :``%%``: literal "%" character
2369 2368 :``%H``: changeset hash (40 hexadecimal digits)
2370 2369 :``%N``: number of patches being generated
2371 2370 :``%R``: changeset revision number
2372 2371 :``%b``: basename of the exporting repository
2373 2372 :``%h``: short-form changeset hash (12 hexadecimal digits)
2374 2373 :``%m``: first line of the commit message (only alphanumeric characters)
2375 2374 :``%n``: zero-padded sequence number, starting at 1
2376 2375 :``%r``: zero-padded changeset revision number
2377 2376
2378 2377 Without the -a/--text option, export will avoid generating diffs
2379 2378 of files it detects as binary. With -a, export will generate a
2380 2379 diff anyway, probably with undesirable results.
2381 2380
2382 2381 Use the -g/--git option to generate diffs in the git extended diff
2383 2382 format. See :hg:`help diffs` for more information.
2384 2383
2385 2384 With the --switch-parent option, the diff will be against the
2386 2385 second parent. It can be useful to review a merge.
2387 2386
2388 2387 .. container:: verbose
2389 2388
2390 2389 Examples:
2391 2390
2392 2391 - use export and import to transplant a bugfix to the current
2393 2392 branch::
2394 2393
2395 2394 hg export -r 9353 | hg import -
2396 2395
2397 2396 - export all the changesets between two revisions to a file with
2398 2397 rename information::
2399 2398
2400 2399 hg export --git -r 123:150 > changes.txt
2401 2400
2402 2401 - split outgoing changes into a series of patches with
2403 2402 descriptive names::
2404 2403
2405 2404 hg export -r "outgoing()" -o "%n-%m.patch"
2406 2405
2407 2406 Returns 0 on success.
2408 2407 """
2409 2408 changesets += tuple(opts.get('rev', []))
2410 2409 if not changesets:
2411 2410 raise util.Abort(_("export requires at least one changeset"))
2412 2411 revs = scmutil.revrange(repo, changesets)
2413 2412 if len(revs) > 1:
2414 2413 ui.note(_('exporting patches:\n'))
2415 2414 else:
2416 2415 ui.note(_('exporting patch:\n'))
2417 2416 cmdutil.export(repo, revs, template=opts.get('output'),
2418 2417 switch_parent=opts.get('switch_parent'),
2419 2418 opts=patch.diffopts(ui, opts))
2420 2419
2421 2420 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2422 2421 def forget(ui, repo, *pats, **opts):
2423 2422 """forget the specified files on the next commit
2424 2423
2425 2424 Mark the specified files so they will no longer be tracked
2426 2425 after the next commit.
2427 2426
2428 2427 This only removes files from the current branch, not from the
2429 2428 entire project history, and it does not delete them from the
2430 2429 working directory.
2431 2430
2432 2431 To undo a forget before the next commit, see :hg:`add`.
2433 2432
2434 2433 .. container:: verbose
2435 2434
2436 2435 Examples:
2437 2436
2438 2437 - forget newly-added binary files::
2439 2438
2440 2439 hg forget "set:added() and binary()"
2441 2440
2442 2441 - forget files that would be excluded by .hgignore::
2443 2442
2444 2443 hg forget "set:hgignore()"
2445 2444
2446 2445 Returns 0 on success.
2447 2446 """
2448 2447
2449 2448 if not pats:
2450 2449 raise util.Abort(_('no files specified'))
2451 2450
2452 wctx = repo[None]
2453 m = scmutil.match(wctx, pats, opts)
2454 s = repo.status(match=m, clean=True)
2455 forget = sorted(s[0] + s[1] + s[3] + s[6])
2456 subforget = {}
2457 errs = 0
2458
2459 for subpath in wctx.substate:
2460 sub = wctx.sub(subpath)
2461 try:
2462 submatch = matchmod.narrowmatcher(subpath, m)
2463 for fsub in sub.walk(submatch):
2464 if submatch.exact(fsub):
2465 subforget[subpath + '/' + fsub] = (fsub, sub)
2466 except error.LookupError:
2467 ui.status(_("skipping missing subrepository: %s\n") % subpath)
2468
2469 for f in m.files():
2470 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
2471 if f not in subforget:
2472 if os.path.exists(m.rel(f)):
2473 ui.warn(_('not removing %s: file is already untracked\n')
2474 % m.rel(f))
2475 errs = 1
2476
2477 for f in forget:
2478 if ui.verbose or not m.exact(f):
2479 ui.status(_('removing %s\n') % m.rel(f))
2480
2481 if ui.verbose:
2482 for f in sorted(subforget.keys()):
2483 ui.status(_('removing %s\n') % m.rel(f))
2484
2485 wctx.forget(forget)
2486
2487 for f in sorted(subforget.keys()):
2488 fsub, sub = subforget[f]
2489 sub.forget([fsub])
2490
2491 return errs
2451 m = scmutil.match(repo[None], pats, opts)
2452 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
2453 return rejected and 1 or 0
2492 2454
2493 2455 @command(
2494 2456 'graft',
2495 2457 [('c', 'continue', False, _('resume interrupted graft')),
2496 2458 ('e', 'edit', False, _('invoke editor on commit messages')),
2497 2459 ('D', 'currentdate', False,
2498 2460 _('record the current date as commit date')),
2499 2461 ('U', 'currentuser', False,
2500 2462 _('record the current user as committer'), _('DATE'))]
2501 2463 + commitopts2 + mergetoolopts,
2502 2464 _('[OPTION]... REVISION...'))
2503 2465 def graft(ui, repo, *revs, **opts):
2504 2466 '''copy changes from other branches onto the current branch
2505 2467
2506 2468 This command uses Mercurial's merge logic to copy individual
2507 2469 changes from other branches without merging branches in the
2508 2470 history graph. This is sometimes known as 'backporting' or
2509 2471 'cherry-picking'. By default, graft will copy user, date, and
2510 2472 description from the source changesets.
2511 2473
2512 2474 Changesets that are ancestors of the current revision, that have
2513 2475 already been grafted, or that are merges will be skipped.
2514 2476
2515 2477 If a graft merge results in conflicts, the graft process is
2516 2478 interrupted so that the current merge can be manually resolved.
2517 2479 Once all conflicts are addressed, the graft process can be
2518 2480 continued with the -c/--continue option.
2519 2481
2520 2482 .. note::
2521 2483 The -c/--continue option does not reapply earlier options.
2522 2484
2523 2485 .. container:: verbose
2524 2486
2525 2487 Examples:
2526 2488
2527 2489 - copy a single change to the stable branch and edit its description::
2528 2490
2529 2491 hg update stable
2530 2492 hg graft --edit 9393
2531 2493
2532 2494 - graft a range of changesets with one exception, updating dates::
2533 2495
2534 2496 hg graft -D "2085::2093 and not 2091"
2535 2497
2536 2498 - continue a graft after resolving conflicts::
2537 2499
2538 2500 hg graft -c
2539 2501
2540 2502 - show the source of a grafted changeset::
2541 2503
2542 2504 hg log --debug -r tip
2543 2505
2544 2506 Returns 0 on successful completion.
2545 2507 '''
2546 2508
2547 2509 if not opts.get('user') and opts.get('currentuser'):
2548 2510 opts['user'] = ui.username()
2549 2511 if not opts.get('date') and opts.get('currentdate'):
2550 2512 opts['date'] = "%d %d" % util.makedate()
2551 2513
2552 2514 editor = None
2553 2515 if opts.get('edit'):
2554 2516 editor = cmdutil.commitforceeditor
2555 2517
2556 2518 cont = False
2557 2519 if opts['continue']:
2558 2520 cont = True
2559 2521 if revs:
2560 2522 raise util.Abort(_("can't specify --continue and revisions"))
2561 2523 # read in unfinished revisions
2562 2524 try:
2563 2525 nodes = repo.opener.read('graftstate').splitlines()
2564 2526 revs = [repo[node].rev() for node in nodes]
2565 2527 except IOError, inst:
2566 2528 if inst.errno != errno.ENOENT:
2567 2529 raise
2568 2530 raise util.Abort(_("no graft state found, can't continue"))
2569 2531 else:
2570 2532 cmdutil.bailifchanged(repo)
2571 2533 if not revs:
2572 2534 raise util.Abort(_('no revisions specified'))
2573 2535 revs = scmutil.revrange(repo, revs)
2574 2536
2575 2537 # check for merges
2576 2538 for rev in repo.revs('%ld and merge()', revs):
2577 2539 ui.warn(_('skipping ungraftable merge revision %s\n') % rev)
2578 2540 revs.remove(rev)
2579 2541 if not revs:
2580 2542 return -1
2581 2543
2582 2544 # check for ancestors of dest branch
2583 2545 for rev in repo.revs('::. and %ld', revs):
2584 2546 ui.warn(_('skipping ancestor revision %s\n') % rev)
2585 2547 revs.remove(rev)
2586 2548 if not revs:
2587 2549 return -1
2588 2550
2589 2551 # analyze revs for earlier grafts
2590 2552 ids = {}
2591 2553 for ctx in repo.set("%ld", revs):
2592 2554 ids[ctx.hex()] = ctx.rev()
2593 2555 n = ctx.extra().get('source')
2594 2556 if n:
2595 2557 ids[n] = ctx.rev()
2596 2558
2597 2559 # check ancestors for earlier grafts
2598 2560 ui.debug('scanning for duplicate grafts\n')
2599 2561 for ctx in repo.set("::. - ::%ld", revs):
2600 2562 n = ctx.extra().get('source')
2601 2563 if n in ids:
2602 2564 r = repo[n].rev()
2603 2565 if r in revs:
2604 2566 ui.warn(_('skipping already grafted revision %s\n') % r)
2605 2567 revs.remove(r)
2606 2568 elif ids[n] in revs:
2607 2569 ui.warn(_('skipping already grafted revision %s '
2608 2570 '(same origin %d)\n') % (ids[n], r))
2609 2571 revs.remove(ids[n])
2610 2572 elif ctx.hex() in ids:
2611 2573 r = ids[ctx.hex()]
2612 2574 ui.warn(_('skipping already grafted revision %s '
2613 2575 '(was grafted from %d)\n') % (r, ctx.rev()))
2614 2576 revs.remove(r)
2615 2577 if not revs:
2616 2578 return -1
2617 2579
2618 2580 for pos, ctx in enumerate(repo.set("%ld", revs)):
2619 2581 current = repo['.']
2620 2582 ui.status(_('grafting revision %s\n') % ctx.rev())
2621 2583
2622 2584 # we don't merge the first commit when continuing
2623 2585 if not cont:
2624 2586 # perform the graft merge with p1(rev) as 'ancestor'
2625 2587 try:
2626 2588 # ui.forcemerge is an internal variable, do not document
2627 2589 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
2628 2590 stats = mergemod.update(repo, ctx.node(), True, True, False,
2629 2591 ctx.p1().node())
2630 2592 finally:
2631 2593 ui.setconfig('ui', 'forcemerge', '')
2632 2594 # drop the second merge parent
2633 2595 repo.dirstate.setparents(current.node(), nullid)
2634 2596 repo.dirstate.write()
2635 2597 # fix up dirstate for copies and renames
2636 2598 cmdutil.duplicatecopies(repo, ctx.rev(), current.node())
2637 2599 # report any conflicts
2638 2600 if stats and stats[3] > 0:
2639 2601 # write out state for --continue
2640 2602 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
2641 2603 repo.opener.write('graftstate', ''.join(nodelines))
2642 2604 raise util.Abort(
2643 2605 _("unresolved conflicts, can't continue"),
2644 2606 hint=_('use hg resolve and hg graft --continue'))
2645 2607 else:
2646 2608 cont = False
2647 2609
2648 2610 # commit
2649 2611 source = ctx.extra().get('source')
2650 2612 if not source:
2651 2613 source = ctx.hex()
2652 2614 extra = {'source': source}
2653 2615 user = ctx.user()
2654 2616 if opts.get('user'):
2655 2617 user = opts['user']
2656 2618 date = ctx.date()
2657 2619 if opts.get('date'):
2658 2620 date = opts['date']
2659 2621 repo.commit(text=ctx.description(), user=user,
2660 2622 date=date, extra=extra, editor=editor)
2661 2623
2662 2624 # remove state when we complete successfully
2663 2625 if os.path.exists(repo.join('graftstate')):
2664 2626 util.unlinkpath(repo.join('graftstate'))
2665 2627
2666 2628 return 0
2667 2629
2668 2630 @command('grep',
2669 2631 [('0', 'print0', None, _('end fields with NUL')),
2670 2632 ('', 'all', None, _('print all revisions that match')),
2671 2633 ('a', 'text', None, _('treat all files as text')),
2672 2634 ('f', 'follow', None,
2673 2635 _('follow changeset history,'
2674 2636 ' or file history across copies and renames')),
2675 2637 ('i', 'ignore-case', None, _('ignore case when matching')),
2676 2638 ('l', 'files-with-matches', None,
2677 2639 _('print only filenames and revisions that match')),
2678 2640 ('n', 'line-number', None, _('print matching line numbers')),
2679 2641 ('r', 'rev', [],
2680 2642 _('only search files changed within revision range'), _('REV')),
2681 2643 ('u', 'user', None, _('list the author (long with -v)')),
2682 2644 ('d', 'date', None, _('list the date (short with -q)')),
2683 2645 ] + walkopts,
2684 2646 _('[OPTION]... PATTERN [FILE]...'))
2685 2647 def grep(ui, repo, pattern, *pats, **opts):
2686 2648 """search for a pattern in specified files and revisions
2687 2649
2688 2650 Search revisions of files for a regular expression.
2689 2651
2690 2652 This command behaves differently than Unix grep. It only accepts
2691 2653 Python/Perl regexps. It searches repository history, not the
2692 2654 working directory. It always prints the revision number in which a
2693 2655 match appears.
2694 2656
2695 2657 By default, grep only prints output for the first revision of a
2696 2658 file in which it finds a match. To get it to print every revision
2697 2659 that contains a change in match status ("-" for a match that
2698 2660 becomes a non-match, or "+" for a non-match that becomes a match),
2699 2661 use the --all flag.
2700 2662
2701 2663 Returns 0 if a match is found, 1 otherwise.
2702 2664 """
2703 2665 reflags = re.M
2704 2666 if opts.get('ignore_case'):
2705 2667 reflags |= re.I
2706 2668 try:
2707 2669 regexp = re.compile(pattern, reflags)
2708 2670 except re.error, inst:
2709 2671 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2710 2672 return 1
2711 2673 sep, eol = ':', '\n'
2712 2674 if opts.get('print0'):
2713 2675 sep = eol = '\0'
2714 2676
2715 2677 getfile = util.lrucachefunc(repo.file)
2716 2678
2717 2679 def matchlines(body):
2718 2680 begin = 0
2719 2681 linenum = 0
2720 2682 while True:
2721 2683 match = regexp.search(body, begin)
2722 2684 if not match:
2723 2685 break
2724 2686 mstart, mend = match.span()
2725 2687 linenum += body.count('\n', begin, mstart) + 1
2726 2688 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2727 2689 begin = body.find('\n', mend) + 1 or len(body) + 1
2728 2690 lend = begin - 1
2729 2691 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2730 2692
2731 2693 class linestate(object):
2732 2694 def __init__(self, line, linenum, colstart, colend):
2733 2695 self.line = line
2734 2696 self.linenum = linenum
2735 2697 self.colstart = colstart
2736 2698 self.colend = colend
2737 2699
2738 2700 def __hash__(self):
2739 2701 return hash((self.linenum, self.line))
2740 2702
2741 2703 def __eq__(self, other):
2742 2704 return self.line == other.line
2743 2705
2744 2706 matches = {}
2745 2707 copies = {}
2746 2708 def grepbody(fn, rev, body):
2747 2709 matches[rev].setdefault(fn, [])
2748 2710 m = matches[rev][fn]
2749 2711 for lnum, cstart, cend, line in matchlines(body):
2750 2712 s = linestate(line, lnum, cstart, cend)
2751 2713 m.append(s)
2752 2714
2753 2715 def difflinestates(a, b):
2754 2716 sm = difflib.SequenceMatcher(None, a, b)
2755 2717 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2756 2718 if tag == 'insert':
2757 2719 for i in xrange(blo, bhi):
2758 2720 yield ('+', b[i])
2759 2721 elif tag == 'delete':
2760 2722 for i in xrange(alo, ahi):
2761 2723 yield ('-', a[i])
2762 2724 elif tag == 'replace':
2763 2725 for i in xrange(alo, ahi):
2764 2726 yield ('-', a[i])
2765 2727 for i in xrange(blo, bhi):
2766 2728 yield ('+', b[i])
2767 2729
2768 2730 def display(fn, ctx, pstates, states):
2769 2731 rev = ctx.rev()
2770 2732 datefunc = ui.quiet and util.shortdate or util.datestr
2771 2733 found = False
2772 2734 filerevmatches = {}
2773 2735 def binary():
2774 2736 flog = getfile(fn)
2775 2737 return util.binary(flog.read(ctx.filenode(fn)))
2776 2738
2777 2739 if opts.get('all'):
2778 2740 iter = difflinestates(pstates, states)
2779 2741 else:
2780 2742 iter = [('', l) for l in states]
2781 2743 for change, l in iter:
2782 2744 cols = [fn, str(rev)]
2783 2745 before, match, after = None, None, None
2784 2746 if opts.get('line_number'):
2785 2747 cols.append(str(l.linenum))
2786 2748 if opts.get('all'):
2787 2749 cols.append(change)
2788 2750 if opts.get('user'):
2789 2751 cols.append(ui.shortuser(ctx.user()))
2790 2752 if opts.get('date'):
2791 2753 cols.append(datefunc(ctx.date()))
2792 2754 if opts.get('files_with_matches'):
2793 2755 c = (fn, rev)
2794 2756 if c in filerevmatches:
2795 2757 continue
2796 2758 filerevmatches[c] = 1
2797 2759 else:
2798 2760 before = l.line[:l.colstart]
2799 2761 match = l.line[l.colstart:l.colend]
2800 2762 after = l.line[l.colend:]
2801 2763 ui.write(sep.join(cols))
2802 2764 if before is not None:
2803 2765 if not opts.get('text') and binary():
2804 2766 ui.write(sep + " Binary file matches")
2805 2767 else:
2806 2768 ui.write(sep + before)
2807 2769 ui.write(match, label='grep.match')
2808 2770 ui.write(after)
2809 2771 ui.write(eol)
2810 2772 found = True
2811 2773 return found
2812 2774
2813 2775 skip = {}
2814 2776 revfiles = {}
2815 2777 matchfn = scmutil.match(repo[None], pats, opts)
2816 2778 found = False
2817 2779 follow = opts.get('follow')
2818 2780
2819 2781 def prep(ctx, fns):
2820 2782 rev = ctx.rev()
2821 2783 pctx = ctx.p1()
2822 2784 parent = pctx.rev()
2823 2785 matches.setdefault(rev, {})
2824 2786 matches.setdefault(parent, {})
2825 2787 files = revfiles.setdefault(rev, [])
2826 2788 for fn in fns:
2827 2789 flog = getfile(fn)
2828 2790 try:
2829 2791 fnode = ctx.filenode(fn)
2830 2792 except error.LookupError:
2831 2793 continue
2832 2794
2833 2795 copied = flog.renamed(fnode)
2834 2796 copy = follow and copied and copied[0]
2835 2797 if copy:
2836 2798 copies.setdefault(rev, {})[fn] = copy
2837 2799 if fn in skip:
2838 2800 if copy:
2839 2801 skip[copy] = True
2840 2802 continue
2841 2803 files.append(fn)
2842 2804
2843 2805 if fn not in matches[rev]:
2844 2806 grepbody(fn, rev, flog.read(fnode))
2845 2807
2846 2808 pfn = copy or fn
2847 2809 if pfn not in matches[parent]:
2848 2810 try:
2849 2811 fnode = pctx.filenode(pfn)
2850 2812 grepbody(pfn, parent, flog.read(fnode))
2851 2813 except error.LookupError:
2852 2814 pass
2853 2815
2854 2816 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2855 2817 rev = ctx.rev()
2856 2818 parent = ctx.p1().rev()
2857 2819 for fn in sorted(revfiles.get(rev, [])):
2858 2820 states = matches[rev][fn]
2859 2821 copy = copies.get(rev, {}).get(fn)
2860 2822 if fn in skip:
2861 2823 if copy:
2862 2824 skip[copy] = True
2863 2825 continue
2864 2826 pstates = matches.get(parent, {}).get(copy or fn, [])
2865 2827 if pstates or states:
2866 2828 r = display(fn, ctx, pstates, states)
2867 2829 found = found or r
2868 2830 if r and not opts.get('all'):
2869 2831 skip[fn] = True
2870 2832 if copy:
2871 2833 skip[copy] = True
2872 2834 del matches[rev]
2873 2835 del revfiles[rev]
2874 2836
2875 2837 return not found
2876 2838
2877 2839 @command('heads',
2878 2840 [('r', 'rev', '',
2879 2841 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
2880 2842 ('t', 'topo', False, _('show topological heads only')),
2881 2843 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
2882 2844 ('c', 'closed', False, _('show normal and closed branch heads')),
2883 2845 ] + templateopts,
2884 2846 _('[-ac] [-r STARTREV] [REV]...'))
2885 2847 def heads(ui, repo, *branchrevs, **opts):
2886 2848 """show current repository heads or show branch heads
2887 2849
2888 2850 With no arguments, show all repository branch heads.
2889 2851
2890 2852 Repository "heads" are changesets with no child changesets. They are
2891 2853 where development generally takes place and are the usual targets
2892 2854 for update and merge operations. Branch heads are changesets that have
2893 2855 no child changeset on the same branch.
2894 2856
2895 2857 If one or more REVs are given, only branch heads on the branches
2896 2858 associated with the specified changesets are shown. This means
2897 2859 that you can use :hg:`heads foo` to see the heads on a branch
2898 2860 named ``foo``.
2899 2861
2900 2862 If -c/--closed is specified, also show branch heads marked closed
2901 2863 (see :hg:`commit --close-branch`).
2902 2864
2903 2865 If STARTREV is specified, only those heads that are descendants of
2904 2866 STARTREV will be displayed.
2905 2867
2906 2868 If -t/--topo is specified, named branch mechanics will be ignored and only
2907 2869 changesets without children will be shown.
2908 2870
2909 2871 Returns 0 if matching heads are found, 1 if not.
2910 2872 """
2911 2873
2912 2874 start = None
2913 2875 if 'rev' in opts:
2914 2876 start = scmutil.revsingle(repo, opts['rev'], None).node()
2915 2877
2916 2878 if opts.get('topo'):
2917 2879 heads = [repo[h] for h in repo.heads(start)]
2918 2880 else:
2919 2881 heads = []
2920 2882 for branch in repo.branchmap():
2921 2883 heads += repo.branchheads(branch, start, opts.get('closed'))
2922 2884 heads = [repo[h] for h in heads]
2923 2885
2924 2886 if branchrevs:
2925 2887 branches = set(repo[br].branch() for br in branchrevs)
2926 2888 heads = [h for h in heads if h.branch() in branches]
2927 2889
2928 2890 if opts.get('active') and branchrevs:
2929 2891 dagheads = repo.heads(start)
2930 2892 heads = [h for h in heads if h.node() in dagheads]
2931 2893
2932 2894 if branchrevs:
2933 2895 haveheads = set(h.branch() for h in heads)
2934 2896 if branches - haveheads:
2935 2897 headless = ', '.join(b for b in branches - haveheads)
2936 2898 msg = _('no open branch heads found on branches %s')
2937 2899 if opts.get('rev'):
2938 2900 msg += _(' (started at %s)' % opts['rev'])
2939 2901 ui.warn((msg + '\n') % headless)
2940 2902
2941 2903 if not heads:
2942 2904 return 1
2943 2905
2944 2906 heads = sorted(heads, key=lambda x: -x.rev())
2945 2907 displayer = cmdutil.show_changeset(ui, repo, opts)
2946 2908 for ctx in heads:
2947 2909 displayer.show(ctx)
2948 2910 displayer.close()
2949 2911
2950 2912 @command('help',
2951 2913 [('e', 'extension', None, _('show only help for extensions')),
2952 2914 ('c', 'command', None, _('show only help for commands'))],
2953 2915 _('[-ec] [TOPIC]'))
2954 2916 def help_(ui, name=None, unknowncmd=False, full=True, **opts):
2955 2917 """show help for a given topic or a help overview
2956 2918
2957 2919 With no arguments, print a list of commands with short help messages.
2958 2920
2959 2921 Given a topic, extension, or command name, print help for that
2960 2922 topic.
2961 2923
2962 2924 Returns 0 if successful.
2963 2925 """
2964 2926
2965 2927 textwidth = min(ui.termwidth(), 80) - 2
2966 2928
2967 2929 def optrst(options):
2968 2930 data = []
2969 2931 multioccur = False
2970 2932 for option in options:
2971 2933 if len(option) == 5:
2972 2934 shortopt, longopt, default, desc, optlabel = option
2973 2935 else:
2974 2936 shortopt, longopt, default, desc = option
2975 2937 optlabel = _("VALUE") # default label
2976 2938
2977 2939 if _("DEPRECATED") in desc and not ui.verbose:
2978 2940 continue
2979 2941
2980 2942 so = ''
2981 2943 if shortopt:
2982 2944 so = '-' + shortopt
2983 2945 lo = '--' + longopt
2984 2946 if default:
2985 2947 desc += _(" (default: %s)") % default
2986 2948
2987 2949 if isinstance(default, list):
2988 2950 lo += " %s [+]" % optlabel
2989 2951 multioccur = True
2990 2952 elif (default is not None) and not isinstance(default, bool):
2991 2953 lo += " %s" % optlabel
2992 2954
2993 2955 data.append((so, lo, desc))
2994 2956
2995 2957 rst = minirst.maketable(data, 1)
2996 2958
2997 2959 if multioccur:
2998 2960 rst += _("\n[+] marked option can be specified multiple times\n")
2999 2961
3000 2962 return rst
3001 2963
3002 2964 # list all option lists
3003 2965 def opttext(optlist, width):
3004 2966 rst = ''
3005 2967 if not optlist:
3006 2968 return ''
3007 2969
3008 2970 for title, options in optlist:
3009 2971 rst += '\n%s\n' % title
3010 2972 if options:
3011 2973 rst += "\n"
3012 2974 rst += optrst(options)
3013 2975 rst += '\n'
3014 2976
3015 2977 return '\n' + minirst.format(rst, width)
3016 2978
3017 2979 def addglobalopts(optlist, aliases):
3018 2980 if ui.quiet:
3019 2981 return []
3020 2982
3021 2983 if ui.verbose:
3022 2984 optlist.append((_("global options:"), globalopts))
3023 2985 if name == 'shortlist':
3024 2986 optlist.append((_('use "hg help" for the full list '
3025 2987 'of commands'), ()))
3026 2988 else:
3027 2989 if name == 'shortlist':
3028 2990 msg = _('use "hg help" for the full list of commands '
3029 2991 'or "hg -v" for details')
3030 2992 elif name and not full:
3031 2993 msg = _('use "hg help %s" to show the full help text' % name)
3032 2994 elif aliases:
3033 2995 msg = _('use "hg -v help%s" to show builtin aliases and '
3034 2996 'global options') % (name and " " + name or "")
3035 2997 else:
3036 2998 msg = _('use "hg -v help %s" to show more info') % name
3037 2999 optlist.append((msg, ()))
3038 3000
3039 3001 def helpcmd(name):
3040 3002 try:
3041 3003 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
3042 3004 except error.AmbiguousCommand, inst:
3043 3005 # py3k fix: except vars can't be used outside the scope of the
3044 3006 # except block, nor can be used inside a lambda. python issue4617
3045 3007 prefix = inst.args[0]
3046 3008 select = lambda c: c.lstrip('^').startswith(prefix)
3047 3009 helplist(select)
3048 3010 return
3049 3011
3050 3012 # check if it's an invalid alias and display its error if it is
3051 3013 if getattr(entry[0], 'badalias', False):
3052 3014 if not unknowncmd:
3053 3015 entry[0](ui)
3054 3016 return
3055 3017
3056 3018 rst = ""
3057 3019
3058 3020 # synopsis
3059 3021 if len(entry) > 2:
3060 3022 if entry[2].startswith('hg'):
3061 3023 rst += "%s\n" % entry[2]
3062 3024 else:
3063 3025 rst += 'hg %s %s\n' % (aliases[0], entry[2])
3064 3026 else:
3065 3027 rst += 'hg %s\n' % aliases[0]
3066 3028
3067 3029 # aliases
3068 3030 if full and not ui.quiet and len(aliases) > 1:
3069 3031 rst += _("\naliases: %s\n") % ', '.join(aliases[1:])
3070 3032
3071 3033 # description
3072 3034 doc = gettext(entry[0].__doc__)
3073 3035 if not doc:
3074 3036 doc = _("(no help text available)")
3075 3037 if util.safehasattr(entry[0], 'definition'): # aliased command
3076 3038 if entry[0].definition.startswith('!'): # shell alias
3077 3039 doc = _('shell alias for::\n\n %s') % entry[0].definition[1:]
3078 3040 else:
3079 3041 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
3080 3042 if ui.quiet or not full:
3081 3043 doc = doc.splitlines()[0]
3082 3044 rst += "\n" + doc + "\n"
3083 3045
3084 3046 # check if this command shadows a non-trivial (multi-line)
3085 3047 # extension help text
3086 3048 try:
3087 3049 mod = extensions.find(name)
3088 3050 doc = gettext(mod.__doc__) or ''
3089 3051 if '\n' in doc.strip():
3090 3052 msg = _('use "hg help -e %s" to show help for '
3091 3053 'the %s extension') % (name, name)
3092 3054 rst += '\n%s\n' % msg
3093 3055 except KeyError:
3094 3056 pass
3095 3057
3096 3058 # options
3097 3059 if not ui.quiet and entry[1]:
3098 3060 rst += '\noptions:\n\n'
3099 3061 rst += optrst(entry[1])
3100 3062
3101 3063 if ui.verbose:
3102 3064 rst += '\nglobal options:\n\n'
3103 3065 rst += optrst(globalopts)
3104 3066
3105 3067 keep = ui.verbose and ['verbose'] or []
3106 3068 formatted, pruned = minirst.format(rst, textwidth, keep=keep)
3107 3069 ui.write(formatted)
3108 3070
3109 3071 if not ui.verbose:
3110 3072 if not full:
3111 3073 ui.write(_('\nuse "hg help %s" to show the full help text\n')
3112 3074 % name)
3113 3075 elif not ui.quiet:
3114 3076 ui.write(_('\nuse "hg -v help %s" to show more info\n') % name)
3115 3077
3116 3078
3117 3079 def helplist(select=None):
3118 3080 # list of commands
3119 3081 if name == "shortlist":
3120 3082 header = _('basic commands:\n\n')
3121 3083 else:
3122 3084 header = _('list of commands:\n\n')
3123 3085
3124 3086 h = {}
3125 3087 cmds = {}
3126 3088 for c, e in table.iteritems():
3127 3089 f = c.split("|", 1)[0]
3128 3090 if select and not select(f):
3129 3091 continue
3130 3092 if (not select and name != 'shortlist' and
3131 3093 e[0].__module__ != __name__):
3132 3094 continue
3133 3095 if name == "shortlist" and not f.startswith("^"):
3134 3096 continue
3135 3097 f = f.lstrip("^")
3136 3098 if not ui.debugflag and f.startswith("debug"):
3137 3099 continue
3138 3100 doc = e[0].__doc__
3139 3101 if doc and 'DEPRECATED' in doc and not ui.verbose:
3140 3102 continue
3141 3103 doc = gettext(doc)
3142 3104 if not doc:
3143 3105 doc = _("(no help text available)")
3144 3106 h[f] = doc.splitlines()[0].rstrip()
3145 3107 cmds[f] = c.lstrip("^")
3146 3108
3147 3109 if not h:
3148 3110 ui.status(_('no commands defined\n'))
3149 3111 return
3150 3112
3151 3113 ui.status(header)
3152 3114 fns = sorted(h)
3153 3115 m = max(map(len, fns))
3154 3116 for f in fns:
3155 3117 if ui.verbose:
3156 3118 commands = cmds[f].replace("|",", ")
3157 3119 ui.write(" %s:\n %s\n"%(commands, h[f]))
3158 3120 else:
3159 3121 ui.write('%s\n' % (util.wrap(h[f], textwidth,
3160 3122 initindent=' %-*s ' % (m, f),
3161 3123 hangindent=' ' * (m + 4))))
3162 3124
3163 3125 if not name:
3164 3126 text = help.listexts(_('enabled extensions:'), extensions.enabled())
3165 3127 if text:
3166 3128 ui.write("\n%s" % minirst.format(text, textwidth))
3167 3129
3168 3130 ui.write(_("\nadditional help topics:\n\n"))
3169 3131 topics = []
3170 3132 for names, header, doc in help.helptable:
3171 3133 topics.append((sorted(names, key=len, reverse=True)[0], header))
3172 3134 topics_len = max([len(s[0]) for s in topics])
3173 3135 for t, desc in topics:
3174 3136 ui.write(" %-*s %s\n" % (topics_len, t, desc))
3175 3137
3176 3138 optlist = []
3177 3139 addglobalopts(optlist, True)
3178 3140 ui.write(opttext(optlist, textwidth))
3179 3141
3180 3142 def helptopic(name):
3181 3143 for names, header, doc in help.helptable:
3182 3144 if name in names:
3183 3145 break
3184 3146 else:
3185 3147 raise error.UnknownCommand(name)
3186 3148
3187 3149 # description
3188 3150 if not doc:
3189 3151 doc = _("(no help text available)")
3190 3152 if util.safehasattr(doc, '__call__'):
3191 3153 doc = doc()
3192 3154
3193 3155 ui.write("%s\n\n" % header)
3194 3156 ui.write("%s" % minirst.format(doc, textwidth, indent=4))
3195 3157 try:
3196 3158 cmdutil.findcmd(name, table)
3197 3159 ui.write(_('\nuse "hg help -c %s" to see help for '
3198 3160 'the %s command\n') % (name, name))
3199 3161 except error.UnknownCommand:
3200 3162 pass
3201 3163
3202 3164 def helpext(name):
3203 3165 try:
3204 3166 mod = extensions.find(name)
3205 3167 doc = gettext(mod.__doc__) or _('no help text available')
3206 3168 except KeyError:
3207 3169 mod = None
3208 3170 doc = extensions.disabledext(name)
3209 3171 if not doc:
3210 3172 raise error.UnknownCommand(name)
3211 3173
3212 3174 if '\n' not in doc:
3213 3175 head, tail = doc, ""
3214 3176 else:
3215 3177 head, tail = doc.split('\n', 1)
3216 3178 ui.write(_('%s extension - %s\n\n') % (name.split('.')[-1], head))
3217 3179 if tail:
3218 3180 ui.write(minirst.format(tail, textwidth))
3219 3181 ui.status('\n')
3220 3182
3221 3183 if mod:
3222 3184 try:
3223 3185 ct = mod.cmdtable
3224 3186 except AttributeError:
3225 3187 ct = {}
3226 3188 modcmds = set([c.split('|', 1)[0] for c in ct])
3227 3189 helplist(modcmds.__contains__)
3228 3190 else:
3229 3191 ui.write(_('use "hg help extensions" for information on enabling '
3230 3192 'extensions\n'))
3231 3193
3232 3194 def helpextcmd(name):
3233 3195 cmd, ext, mod = extensions.disabledcmd(ui, name, ui.config('ui', 'strict'))
3234 3196 doc = gettext(mod.__doc__).splitlines()[0]
3235 3197
3236 3198 msg = help.listexts(_("'%s' is provided by the following "
3237 3199 "extension:") % cmd, {ext: doc}, indent=4)
3238 3200 ui.write(minirst.format(msg, textwidth))
3239 3201 ui.write('\n')
3240 3202 ui.write(_('use "hg help extensions" for information on enabling '
3241 3203 'extensions\n'))
3242 3204
3243 3205 if name and name != 'shortlist':
3244 3206 i = None
3245 3207 if unknowncmd:
3246 3208 queries = (helpextcmd,)
3247 3209 elif opts.get('extension'):
3248 3210 queries = (helpext,)
3249 3211 elif opts.get('command'):
3250 3212 queries = (helpcmd,)
3251 3213 else:
3252 3214 queries = (helptopic, helpcmd, helpext, helpextcmd)
3253 3215 for f in queries:
3254 3216 try:
3255 3217 f(name)
3256 3218 i = None
3257 3219 break
3258 3220 except error.UnknownCommand, inst:
3259 3221 i = inst
3260 3222 if i:
3261 3223 raise i
3262 3224 else:
3263 3225 # program name
3264 3226 ui.status(_("Mercurial Distributed SCM\n"))
3265 3227 ui.status('\n')
3266 3228 helplist()
3267 3229
3268 3230
3269 3231 @command('identify|id',
3270 3232 [('r', 'rev', '',
3271 3233 _('identify the specified revision'), _('REV')),
3272 3234 ('n', 'num', None, _('show local revision number')),
3273 3235 ('i', 'id', None, _('show global revision id')),
3274 3236 ('b', 'branch', None, _('show branch')),
3275 3237 ('t', 'tags', None, _('show tags')),
3276 3238 ('B', 'bookmarks', None, _('show bookmarks')),
3277 3239 ] + remoteopts,
3278 3240 _('[-nibtB] [-r REV] [SOURCE]'))
3279 3241 def identify(ui, repo, source=None, rev=None,
3280 3242 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
3281 3243 """identify the working copy or specified revision
3282 3244
3283 3245 Print a summary identifying the repository state at REV using one or
3284 3246 two parent hash identifiers, followed by a "+" if the working
3285 3247 directory has uncommitted changes, the branch name (if not default),
3286 3248 a list of tags, and a list of bookmarks.
3287 3249
3288 3250 When REV is not given, print a summary of the current state of the
3289 3251 repository.
3290 3252
3291 3253 Specifying a path to a repository root or Mercurial bundle will
3292 3254 cause lookup to operate on that repository/bundle.
3293 3255
3294 3256 .. container:: verbose
3295 3257
3296 3258 Examples:
3297 3259
3298 3260 - generate a build identifier for the working directory::
3299 3261
3300 3262 hg id --id > build-id.dat
3301 3263
3302 3264 - find the revision corresponding to a tag::
3303 3265
3304 3266 hg id -n -r 1.3
3305 3267
3306 3268 - check the most recent revision of a remote repository::
3307 3269
3308 3270 hg id -r tip http://selenic.com/hg/
3309 3271
3310 3272 Returns 0 if successful.
3311 3273 """
3312 3274
3313 3275 if not repo and not source:
3314 3276 raise util.Abort(_("there is no Mercurial repository here "
3315 3277 "(.hg not found)"))
3316 3278
3317 3279 hexfunc = ui.debugflag and hex or short
3318 3280 default = not (num or id or branch or tags or bookmarks)
3319 3281 output = []
3320 3282 revs = []
3321 3283
3322 3284 if source:
3323 3285 source, branches = hg.parseurl(ui.expandpath(source))
3324 3286 repo = hg.peer(ui, opts, source)
3325 3287 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
3326 3288
3327 3289 if not repo.local():
3328 3290 if num or branch or tags:
3329 3291 raise util.Abort(
3330 3292 _("can't query remote revision number, branch, or tags"))
3331 3293 if not rev and revs:
3332 3294 rev = revs[0]
3333 3295 if not rev:
3334 3296 rev = "tip"
3335 3297
3336 3298 remoterev = repo.lookup(rev)
3337 3299 if default or id:
3338 3300 output = [hexfunc(remoterev)]
3339 3301
3340 3302 def getbms():
3341 3303 bms = []
3342 3304
3343 3305 if 'bookmarks' in repo.listkeys('namespaces'):
3344 3306 hexremoterev = hex(remoterev)
3345 3307 bms = [bm for bm, bmr in repo.listkeys('bookmarks').iteritems()
3346 3308 if bmr == hexremoterev]
3347 3309
3348 3310 return bms
3349 3311
3350 3312 if bookmarks:
3351 3313 output.extend(getbms())
3352 3314 elif default and not ui.quiet:
3353 3315 # multiple bookmarks for a single parent separated by '/'
3354 3316 bm = '/'.join(getbms())
3355 3317 if bm:
3356 3318 output.append(bm)
3357 3319 else:
3358 3320 if not rev:
3359 3321 ctx = repo[None]
3360 3322 parents = ctx.parents()
3361 3323 changed = ""
3362 3324 if default or id or num:
3363 3325 changed = util.any(repo.status()) and "+" or ""
3364 3326 if default or id:
3365 3327 output = ["%s%s" %
3366 3328 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
3367 3329 if num:
3368 3330 output.append("%s%s" %
3369 3331 ('+'.join([str(p.rev()) for p in parents]), changed))
3370 3332 else:
3371 3333 ctx = scmutil.revsingle(repo, rev)
3372 3334 if default or id:
3373 3335 output = [hexfunc(ctx.node())]
3374 3336 if num:
3375 3337 output.append(str(ctx.rev()))
3376 3338
3377 3339 if default and not ui.quiet:
3378 3340 b = ctx.branch()
3379 3341 if b != 'default':
3380 3342 output.append("(%s)" % b)
3381 3343
3382 3344 # multiple tags for a single parent separated by '/'
3383 3345 t = '/'.join(ctx.tags())
3384 3346 if t:
3385 3347 output.append(t)
3386 3348
3387 3349 # multiple bookmarks for a single parent separated by '/'
3388 3350 bm = '/'.join(ctx.bookmarks())
3389 3351 if bm:
3390 3352 output.append(bm)
3391 3353 else:
3392 3354 if branch:
3393 3355 output.append(ctx.branch())
3394 3356
3395 3357 if tags:
3396 3358 output.extend(ctx.tags())
3397 3359
3398 3360 if bookmarks:
3399 3361 output.extend(ctx.bookmarks())
3400 3362
3401 3363 ui.write("%s\n" % ' '.join(output))
3402 3364
3403 3365 @command('import|patch',
3404 3366 [('p', 'strip', 1,
3405 3367 _('directory strip option for patch. This has the same '
3406 3368 'meaning as the corresponding patch option'), _('NUM')),
3407 3369 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
3408 3370 ('e', 'edit', False, _('invoke editor on commit messages')),
3409 3371 ('f', 'force', None, _('skip check for outstanding uncommitted changes')),
3410 3372 ('', 'no-commit', None,
3411 3373 _("don't commit, just update the working directory")),
3412 3374 ('', 'bypass', None,
3413 3375 _("apply patch without touching the working directory")),
3414 3376 ('', 'exact', None,
3415 3377 _('apply patch to the nodes from which it was generated')),
3416 3378 ('', 'import-branch', None,
3417 3379 _('use any branch information in patch (implied by --exact)'))] +
3418 3380 commitopts + commitopts2 + similarityopts,
3419 3381 _('[OPTION]... PATCH...'))
3420 3382 def import_(ui, repo, patch1=None, *patches, **opts):
3421 3383 """import an ordered set of patches
3422 3384
3423 3385 Import a list of patches and commit them individually (unless
3424 3386 --no-commit is specified).
3425 3387
3426 3388 If there are outstanding changes in the working directory, import
3427 3389 will abort unless given the -f/--force flag.
3428 3390
3429 3391 You can import a patch straight from a mail message. Even patches
3430 3392 as attachments work (to use the body part, it must have type
3431 3393 text/plain or text/x-patch). From and Subject headers of email
3432 3394 message are used as default committer and commit message. All
3433 3395 text/plain body parts before first diff are added to commit
3434 3396 message.
3435 3397
3436 3398 If the imported patch was generated by :hg:`export`, user and
3437 3399 description from patch override values from message headers and
3438 3400 body. Values given on command line with -m/--message and -u/--user
3439 3401 override these.
3440 3402
3441 3403 If --exact is specified, import will set the working directory to
3442 3404 the parent of each patch before applying it, and will abort if the
3443 3405 resulting changeset has a different ID than the one recorded in
3444 3406 the patch. This may happen due to character set problems or other
3445 3407 deficiencies in the text patch format.
3446 3408
3447 3409 Use --bypass to apply and commit patches directly to the
3448 3410 repository, not touching the working directory. Without --exact,
3449 3411 patches will be applied on top of the working directory parent
3450 3412 revision.
3451 3413
3452 3414 With -s/--similarity, hg will attempt to discover renames and
3453 3415 copies in the patch in the same way as :hg:`addremove`.
3454 3416
3455 3417 To read a patch from standard input, use "-" as the patch name. If
3456 3418 a URL is specified, the patch will be downloaded from it.
3457 3419 See :hg:`help dates` for a list of formats valid for -d/--date.
3458 3420
3459 3421 .. container:: verbose
3460 3422
3461 3423 Examples:
3462 3424
3463 3425 - import a traditional patch from a website and detect renames::
3464 3426
3465 3427 hg import -s 80 http://example.com/bugfix.patch
3466 3428
3467 3429 - import a changeset from an hgweb server::
3468 3430
3469 3431 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
3470 3432
3471 3433 - import all the patches in an Unix-style mbox::
3472 3434
3473 3435 hg import incoming-patches.mbox
3474 3436
3475 3437 - attempt to exactly restore an exported changeset (not always
3476 3438 possible)::
3477 3439
3478 3440 hg import --exact proposed-fix.patch
3479 3441
3480 3442 Returns 0 on success.
3481 3443 """
3482 3444
3483 3445 if not patch1:
3484 3446 raise util.Abort(_('need at least one patch to import'))
3485 3447
3486 3448 patches = (patch1,) + patches
3487 3449
3488 3450 date = opts.get('date')
3489 3451 if date:
3490 3452 opts['date'] = util.parsedate(date)
3491 3453
3492 3454 editor = cmdutil.commiteditor
3493 3455 if opts.get('edit'):
3494 3456 editor = cmdutil.commitforceeditor
3495 3457
3496 3458 update = not opts.get('bypass')
3497 3459 if not update and opts.get('no_commit'):
3498 3460 raise util.Abort(_('cannot use --no-commit with --bypass'))
3499 3461 try:
3500 3462 sim = float(opts.get('similarity') or 0)
3501 3463 except ValueError:
3502 3464 raise util.Abort(_('similarity must be a number'))
3503 3465 if sim < 0 or sim > 100:
3504 3466 raise util.Abort(_('similarity must be between 0 and 100'))
3505 3467 if sim and not update:
3506 3468 raise util.Abort(_('cannot use --similarity with --bypass'))
3507 3469
3508 3470 if (opts.get('exact') or not opts.get('force')) and update:
3509 3471 cmdutil.bailifchanged(repo)
3510 3472
3511 3473 base = opts["base"]
3512 3474 strip = opts["strip"]
3513 3475 wlock = lock = tr = None
3514 3476 msgs = []
3515 3477
3516 3478 def checkexact(repo, n, nodeid):
3517 3479 if opts.get('exact') and hex(n) != nodeid:
3518 3480 repo.rollback()
3519 3481 raise util.Abort(_('patch is damaged or loses information'))
3520 3482
3521 3483 def tryone(ui, hunk, parents):
3522 3484 tmpname, message, user, date, branch, nodeid, p1, p2 = \
3523 3485 patch.extract(ui, hunk)
3524 3486
3525 3487 if not tmpname:
3526 3488 return (None, None)
3527 3489 msg = _('applied to working directory')
3528 3490
3529 3491 try:
3530 3492 cmdline_message = cmdutil.logmessage(ui, opts)
3531 3493 if cmdline_message:
3532 3494 # pickup the cmdline msg
3533 3495 message = cmdline_message
3534 3496 elif message:
3535 3497 # pickup the patch msg
3536 3498 message = message.strip()
3537 3499 else:
3538 3500 # launch the editor
3539 3501 message = None
3540 3502 ui.debug('message:\n%s\n' % message)
3541 3503
3542 3504 if len(parents) == 1:
3543 3505 parents.append(repo[nullid])
3544 3506 if opts.get('exact'):
3545 3507 if not nodeid or not p1:
3546 3508 raise util.Abort(_('not a Mercurial patch'))
3547 3509 p1 = repo[p1]
3548 3510 p2 = repo[p2 or nullid]
3549 3511 elif p2:
3550 3512 try:
3551 3513 p1 = repo[p1]
3552 3514 p2 = repo[p2]
3553 3515 # Without any options, consider p2 only if the
3554 3516 # patch is being applied on top of the recorded
3555 3517 # first parent.
3556 3518 if p1 != parents[0]:
3557 3519 p1 = parents[0]
3558 3520 p2 = repo[nullid]
3559 3521 except error.RepoError:
3560 3522 p1, p2 = parents
3561 3523 else:
3562 3524 p1, p2 = parents
3563 3525
3564 3526 n = None
3565 3527 if update:
3566 3528 if p1 != parents[0]:
3567 3529 hg.clean(repo, p1.node())
3568 3530 if p2 != parents[1]:
3569 3531 repo.dirstate.setparents(p1.node(), p2.node())
3570 3532
3571 3533 if opts.get('exact') or opts.get('import_branch'):
3572 3534 repo.dirstate.setbranch(branch or 'default')
3573 3535
3574 3536 files = set()
3575 3537 patch.patch(ui, repo, tmpname, strip=strip, files=files,
3576 3538 eolmode=None, similarity=sim / 100.0)
3577 3539 files = list(files)
3578 3540 if opts.get('no_commit'):
3579 3541 if message:
3580 3542 msgs.append(message)
3581 3543 else:
3582 3544 if opts.get('exact') or p2:
3583 3545 # If you got here, you either use --force and know what
3584 3546 # you are doing or used --exact or a merge patch while
3585 3547 # being updated to its first parent.
3586 3548 m = None
3587 3549 else:
3588 3550 m = scmutil.matchfiles(repo, files or [])
3589 3551 n = repo.commit(message, opts.get('user') or user,
3590 3552 opts.get('date') or date, match=m,
3591 3553 editor=editor)
3592 3554 checkexact(repo, n, nodeid)
3593 3555 else:
3594 3556 if opts.get('exact') or opts.get('import_branch'):
3595 3557 branch = branch or 'default'
3596 3558 else:
3597 3559 branch = p1.branch()
3598 3560 store = patch.filestore()
3599 3561 try:
3600 3562 files = set()
3601 3563 try:
3602 3564 patch.patchrepo(ui, repo, p1, store, tmpname, strip,
3603 3565 files, eolmode=None)
3604 3566 except patch.PatchError, e:
3605 3567 raise util.Abort(str(e))
3606 3568 memctx = patch.makememctx(repo, (p1.node(), p2.node()),
3607 3569 message,
3608 3570 opts.get('user') or user,
3609 3571 opts.get('date') or date,
3610 3572 branch, files, store,
3611 3573 editor=cmdutil.commiteditor)
3612 3574 repo.savecommitmessage(memctx.description())
3613 3575 n = memctx.commit()
3614 3576 checkexact(repo, n, nodeid)
3615 3577 finally:
3616 3578 store.close()
3617 3579 if n:
3618 3580 # i18n: refers to a short changeset id
3619 3581 msg = _('created %s') % short(n)
3620 3582 return (msg, n)
3621 3583 finally:
3622 3584 os.unlink(tmpname)
3623 3585
3624 3586 try:
3625 3587 try:
3626 3588 wlock = repo.wlock()
3627 3589 lock = repo.lock()
3628 3590 tr = repo.transaction('import')
3629 3591 parents = repo.parents()
3630 3592 for patchurl in patches:
3631 3593 if patchurl == '-':
3632 3594 ui.status(_('applying patch from stdin\n'))
3633 3595 patchfile = ui.fin
3634 3596 patchurl = 'stdin' # for error message
3635 3597 else:
3636 3598 patchurl = os.path.join(base, patchurl)
3637 3599 ui.status(_('applying %s\n') % patchurl)
3638 3600 patchfile = url.open(ui, patchurl)
3639 3601
3640 3602 haspatch = False
3641 3603 for hunk in patch.split(patchfile):
3642 3604 (msg, node) = tryone(ui, hunk, parents)
3643 3605 if msg:
3644 3606 haspatch = True
3645 3607 ui.note(msg + '\n')
3646 3608 if update or opts.get('exact'):
3647 3609 parents = repo.parents()
3648 3610 else:
3649 3611 parents = [repo[node]]
3650 3612
3651 3613 if not haspatch:
3652 3614 raise util.Abort(_('%s: no diffs found') % patchurl)
3653 3615
3654 3616 tr.close()
3655 3617 if msgs:
3656 3618 repo.savecommitmessage('\n* * *\n'.join(msgs))
3657 3619 except:
3658 3620 # wlock.release() indirectly calls dirstate.write(): since
3659 3621 # we're crashing, we do not want to change the working dir
3660 3622 # parent after all, so make sure it writes nothing
3661 3623 repo.dirstate.invalidate()
3662 3624 raise
3663 3625 finally:
3664 3626 if tr:
3665 3627 tr.release()
3666 3628 release(lock, wlock)
3667 3629
3668 3630 @command('incoming|in',
3669 3631 [('f', 'force', None,
3670 3632 _('run even if remote repository is unrelated')),
3671 3633 ('n', 'newest-first', None, _('show newest record first')),
3672 3634 ('', 'bundle', '',
3673 3635 _('file to store the bundles into'), _('FILE')),
3674 3636 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3675 3637 ('B', 'bookmarks', False, _("compare bookmarks")),
3676 3638 ('b', 'branch', [],
3677 3639 _('a specific branch you would like to pull'), _('BRANCH')),
3678 3640 ] + logopts + remoteopts + subrepoopts,
3679 3641 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3680 3642 def incoming(ui, repo, source="default", **opts):
3681 3643 """show new changesets found in source
3682 3644
3683 3645 Show new changesets found in the specified path/URL or the default
3684 3646 pull location. These are the changesets that would have been pulled
3685 3647 if a pull at the time you issued this command.
3686 3648
3687 3649 For remote repository, using --bundle avoids downloading the
3688 3650 changesets twice if the incoming is followed by a pull.
3689 3651
3690 3652 See pull for valid source format details.
3691 3653
3692 3654 Returns 0 if there are incoming changes, 1 otherwise.
3693 3655 """
3694 3656 if opts.get('bundle') and opts.get('subrepos'):
3695 3657 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3696 3658
3697 3659 if opts.get('bookmarks'):
3698 3660 source, branches = hg.parseurl(ui.expandpath(source),
3699 3661 opts.get('branch'))
3700 3662 other = hg.peer(repo, opts, source)
3701 3663 if 'bookmarks' not in other.listkeys('namespaces'):
3702 3664 ui.warn(_("remote doesn't support bookmarks\n"))
3703 3665 return 0
3704 3666 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3705 3667 return bookmarks.diff(ui, repo, other)
3706 3668
3707 3669 repo._subtoppath = ui.expandpath(source)
3708 3670 try:
3709 3671 return hg.incoming(ui, repo, source, opts)
3710 3672 finally:
3711 3673 del repo._subtoppath
3712 3674
3713 3675
3714 3676 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3715 3677 def init(ui, dest=".", **opts):
3716 3678 """create a new repository in the given directory
3717 3679
3718 3680 Initialize a new repository in the given directory. If the given
3719 3681 directory does not exist, it will be created.
3720 3682
3721 3683 If no directory is given, the current directory is used.
3722 3684
3723 3685 It is possible to specify an ``ssh://`` URL as the destination.
3724 3686 See :hg:`help urls` for more information.
3725 3687
3726 3688 Returns 0 on success.
3727 3689 """
3728 3690 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3729 3691
3730 3692 @command('locate',
3731 3693 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3732 3694 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3733 3695 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3734 3696 ] + walkopts,
3735 3697 _('[OPTION]... [PATTERN]...'))
3736 3698 def locate(ui, repo, *pats, **opts):
3737 3699 """locate files matching specific patterns
3738 3700
3739 3701 Print files under Mercurial control in the working directory whose
3740 3702 names match the given patterns.
3741 3703
3742 3704 By default, this command searches all directories in the working
3743 3705 directory. To search just the current directory and its
3744 3706 subdirectories, use "--include .".
3745 3707
3746 3708 If no patterns are given to match, this command prints the names
3747 3709 of all files under Mercurial control in the working directory.
3748 3710
3749 3711 If you want to feed the output of this command into the "xargs"
3750 3712 command, use the -0 option to both this command and "xargs". This
3751 3713 will avoid the problem of "xargs" treating single filenames that
3752 3714 contain whitespace as multiple filenames.
3753 3715
3754 3716 Returns 0 if a match is found, 1 otherwise.
3755 3717 """
3756 3718 end = opts.get('print0') and '\0' or '\n'
3757 3719 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3758 3720
3759 3721 ret = 1
3760 3722 m = scmutil.match(repo[rev], pats, opts, default='relglob')
3761 3723 m.bad = lambda x, y: False
3762 3724 for abs in repo[rev].walk(m):
3763 3725 if not rev and abs not in repo.dirstate:
3764 3726 continue
3765 3727 if opts.get('fullpath'):
3766 3728 ui.write(repo.wjoin(abs), end)
3767 3729 else:
3768 3730 ui.write(((pats and m.rel(abs)) or abs), end)
3769 3731 ret = 0
3770 3732
3771 3733 return ret
3772 3734
3773 3735 @command('^log|history',
3774 3736 [('f', 'follow', None,
3775 3737 _('follow changeset history, or file history across copies and renames')),
3776 3738 ('', 'follow-first', None,
3777 3739 _('only follow the first parent of merge changesets (DEPRECATED)')),
3778 3740 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3779 3741 ('C', 'copies', None, _('show copied files')),
3780 3742 ('k', 'keyword', [],
3781 3743 _('do case-insensitive search for a given text'), _('TEXT')),
3782 3744 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
3783 3745 ('', 'removed', None, _('include revisions where files were removed')),
3784 3746 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
3785 3747 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3786 3748 ('', 'only-branch', [],
3787 3749 _('show only changesets within the given named branch (DEPRECATED)'),
3788 3750 _('BRANCH')),
3789 3751 ('b', 'branch', [],
3790 3752 _('show changesets within the given named branch'), _('BRANCH')),
3791 3753 ('P', 'prune', [],
3792 3754 _('do not display revision or any of its ancestors'), _('REV')),
3793 3755 ('', 'hidden', False, _('show hidden changesets (DEPRECATED)')),
3794 3756 ] + logopts + walkopts,
3795 3757 _('[OPTION]... [FILE]'))
3796 3758 def log(ui, repo, *pats, **opts):
3797 3759 """show revision history of entire repository or files
3798 3760
3799 3761 Print the revision history of the specified files or the entire
3800 3762 project.
3801 3763
3802 3764 If no revision range is specified, the default is ``tip:0`` unless
3803 3765 --follow is set, in which case the working directory parent is
3804 3766 used as the starting revision.
3805 3767
3806 3768 File history is shown without following rename or copy history of
3807 3769 files. Use -f/--follow with a filename to follow history across
3808 3770 renames and copies. --follow without a filename will only show
3809 3771 ancestors or descendants of the starting revision.
3810 3772
3811 3773 By default this command prints revision number and changeset id,
3812 3774 tags, non-trivial parents, user, date and time, and a summary for
3813 3775 each commit. When the -v/--verbose switch is used, the list of
3814 3776 changed files and full commit message are shown.
3815 3777
3816 3778 .. note::
3817 3779 log -p/--patch may generate unexpected diff output for merge
3818 3780 changesets, as it will only compare the merge changeset against
3819 3781 its first parent. Also, only files different from BOTH parents
3820 3782 will appear in files:.
3821 3783
3822 3784 .. note::
3823 3785 for performance reasons, log FILE may omit duplicate changes
3824 3786 made on branches and will not show deletions. To see all
3825 3787 changes including duplicates and deletions, use the --removed
3826 3788 switch.
3827 3789
3828 3790 .. container:: verbose
3829 3791
3830 3792 Some examples:
3831 3793
3832 3794 - changesets with full descriptions and file lists::
3833 3795
3834 3796 hg log -v
3835 3797
3836 3798 - changesets ancestral to the working directory::
3837 3799
3838 3800 hg log -f
3839 3801
3840 3802 - last 10 commits on the current branch::
3841 3803
3842 3804 hg log -l 10 -b .
3843 3805
3844 3806 - changesets showing all modifications of a file, including removals::
3845 3807
3846 3808 hg log --removed file.c
3847 3809
3848 3810 - all changesets that touch a directory, with diffs, excluding merges::
3849 3811
3850 3812 hg log -Mp lib/
3851 3813
3852 3814 - all revision numbers that match a keyword::
3853 3815
3854 3816 hg log -k bug --template "{rev}\\n"
3855 3817
3856 3818 - check if a given changeset is included is a tagged release::
3857 3819
3858 3820 hg log -r "a21ccf and ancestor(1.9)"
3859 3821
3860 3822 - find all changesets by some user in a date range::
3861 3823
3862 3824 hg log -k alice -d "may 2008 to jul 2008"
3863 3825
3864 3826 - summary of all changesets after the last tag::
3865 3827
3866 3828 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
3867 3829
3868 3830 See :hg:`help dates` for a list of formats valid for -d/--date.
3869 3831
3870 3832 See :hg:`help revisions` and :hg:`help revsets` for more about
3871 3833 specifying revisions.
3872 3834
3873 3835 Returns 0 on success.
3874 3836 """
3875 3837
3876 3838 matchfn = scmutil.match(repo[None], pats, opts)
3877 3839 limit = cmdutil.loglimit(opts)
3878 3840 count = 0
3879 3841
3880 3842 endrev = None
3881 3843 if opts.get('copies') and opts.get('rev'):
3882 3844 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
3883 3845
3884 3846 df = False
3885 3847 if opts["date"]:
3886 3848 df = util.matchdate(opts["date"])
3887 3849
3888 3850 branches = opts.get('branch', []) + opts.get('only_branch', [])
3889 3851 opts['branch'] = [repo.lookupbranch(b) for b in branches]
3890 3852
3891 3853 displayer = cmdutil.show_changeset(ui, repo, opts, True)
3892 3854 def prep(ctx, fns):
3893 3855 rev = ctx.rev()
3894 3856 parents = [p for p in repo.changelog.parentrevs(rev)
3895 3857 if p != nullrev]
3896 3858 if opts.get('no_merges') and len(parents) == 2:
3897 3859 return
3898 3860 if opts.get('only_merges') and len(parents) != 2:
3899 3861 return
3900 3862 if opts.get('branch') and ctx.branch() not in opts['branch']:
3901 3863 return
3902 3864 if not opts.get('hidden') and ctx.hidden():
3903 3865 return
3904 3866 if df and not df(ctx.date()[0]):
3905 3867 return
3906 3868
3907 3869 lower = encoding.lower
3908 3870 if opts.get('user'):
3909 3871 luser = lower(ctx.user())
3910 3872 for k in [lower(x) for x in opts['user']]:
3911 3873 if (k in luser):
3912 3874 break
3913 3875 else:
3914 3876 return
3915 3877 if opts.get('keyword'):
3916 3878 luser = lower(ctx.user())
3917 3879 ldesc = lower(ctx.description())
3918 3880 lfiles = lower(" ".join(ctx.files()))
3919 3881 for k in [lower(x) for x in opts['keyword']]:
3920 3882 if (k in luser or k in ldesc or k in lfiles):
3921 3883 break
3922 3884 else:
3923 3885 return
3924 3886
3925 3887 copies = None
3926 3888 if opts.get('copies') and rev:
3927 3889 copies = []
3928 3890 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3929 3891 for fn in ctx.files():
3930 3892 rename = getrenamed(fn, rev)
3931 3893 if rename:
3932 3894 copies.append((fn, rename[0]))
3933 3895
3934 3896 revmatchfn = None
3935 3897 if opts.get('patch') or opts.get('stat'):
3936 3898 if opts.get('follow') or opts.get('follow_first'):
3937 3899 # note: this might be wrong when following through merges
3938 3900 revmatchfn = scmutil.match(repo[None], fns, default='path')
3939 3901 else:
3940 3902 revmatchfn = matchfn
3941 3903
3942 3904 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
3943 3905
3944 3906 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3945 3907 if count == limit:
3946 3908 break
3947 3909 if displayer.flush(ctx.rev()):
3948 3910 count += 1
3949 3911 displayer.close()
3950 3912
3951 3913 @command('manifest',
3952 3914 [('r', 'rev', '', _('revision to display'), _('REV')),
3953 3915 ('', 'all', False, _("list files from all revisions"))],
3954 3916 _('[-r REV]'))
3955 3917 def manifest(ui, repo, node=None, rev=None, **opts):
3956 3918 """output the current or given revision of the project manifest
3957 3919
3958 3920 Print a list of version controlled files for the given revision.
3959 3921 If no revision is given, the first parent of the working directory
3960 3922 is used, or the null revision if no revision is checked out.
3961 3923
3962 3924 With -v, print file permissions, symlink and executable bits.
3963 3925 With --debug, print file revision hashes.
3964 3926
3965 3927 If option --all is specified, the list of all files from all revisions
3966 3928 is printed. This includes deleted and renamed files.
3967 3929
3968 3930 Returns 0 on success.
3969 3931 """
3970 3932 if opts.get('all'):
3971 3933 if rev or node:
3972 3934 raise util.Abort(_("can't specify a revision with --all"))
3973 3935
3974 3936 res = []
3975 3937 prefix = "data/"
3976 3938 suffix = ".i"
3977 3939 plen = len(prefix)
3978 3940 slen = len(suffix)
3979 3941 lock = repo.lock()
3980 3942 try:
3981 3943 for fn, b, size in repo.store.datafiles():
3982 3944 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
3983 3945 res.append(fn[plen:-slen])
3984 3946 finally:
3985 3947 lock.release()
3986 3948 for f in sorted(res):
3987 3949 ui.write("%s\n" % f)
3988 3950 return
3989 3951
3990 3952 if rev and node:
3991 3953 raise util.Abort(_("please specify just one revision"))
3992 3954
3993 3955 if not node:
3994 3956 node = rev
3995 3957
3996 3958 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
3997 3959 ctx = scmutil.revsingle(repo, node)
3998 3960 for f in ctx:
3999 3961 if ui.debugflag:
4000 3962 ui.write("%40s " % hex(ctx.manifest()[f]))
4001 3963 if ui.verbose:
4002 3964 ui.write(decor[ctx.flags(f)])
4003 3965 ui.write("%s\n" % f)
4004 3966
4005 3967 @command('^merge',
4006 3968 [('f', 'force', None, _('force a merge with outstanding changes')),
4007 3969 ('r', 'rev', '', _('revision to merge'), _('REV')),
4008 3970 ('P', 'preview', None,
4009 3971 _('review revisions to merge (no merge is performed)'))
4010 3972 ] + mergetoolopts,
4011 3973 _('[-P] [-f] [[-r] REV]'))
4012 3974 def merge(ui, repo, node=None, **opts):
4013 3975 """merge working directory with another revision
4014 3976
4015 3977 The current working directory is updated with all changes made in
4016 3978 the requested revision since the last common predecessor revision.
4017 3979
4018 3980 Files that changed between either parent are marked as changed for
4019 3981 the next commit and a commit must be performed before any further
4020 3982 updates to the repository are allowed. The next commit will have
4021 3983 two parents.
4022 3984
4023 3985 ``--tool`` can be used to specify the merge tool used for file
4024 3986 merges. It overrides the HGMERGE environment variable and your
4025 3987 configuration files. See :hg:`help merge-tools` for options.
4026 3988
4027 3989 If no revision is specified, the working directory's parent is a
4028 3990 head revision, and the current branch contains exactly one other
4029 3991 head, the other head is merged with by default. Otherwise, an
4030 3992 explicit revision with which to merge with must be provided.
4031 3993
4032 3994 :hg:`resolve` must be used to resolve unresolved files.
4033 3995
4034 3996 To undo an uncommitted merge, use :hg:`update --clean .` which
4035 3997 will check out a clean copy of the original merge parent, losing
4036 3998 all changes.
4037 3999
4038 4000 Returns 0 on success, 1 if there are unresolved files.
4039 4001 """
4040 4002
4041 4003 if opts.get('rev') and node:
4042 4004 raise util.Abort(_("please specify just one revision"))
4043 4005 if not node:
4044 4006 node = opts.get('rev')
4045 4007
4046 4008 if not node:
4047 4009 branch = repo[None].branch()
4048 4010 bheads = repo.branchheads(branch)
4049 4011 if len(bheads) > 2:
4050 4012 raise util.Abort(_("branch '%s' has %d heads - "
4051 4013 "please merge with an explicit rev")
4052 4014 % (branch, len(bheads)),
4053 4015 hint=_("run 'hg heads .' to see heads"))
4054 4016
4055 4017 parent = repo.dirstate.p1()
4056 4018 if len(bheads) == 1:
4057 4019 if len(repo.heads()) > 1:
4058 4020 raise util.Abort(_("branch '%s' has one head - "
4059 4021 "please merge with an explicit rev")
4060 4022 % branch,
4061 4023 hint=_("run 'hg heads' to see all heads"))
4062 4024 msg, hint = _('nothing to merge'), None
4063 4025 if parent != repo.lookup(branch):
4064 4026 hint = _("use 'hg update' instead")
4065 4027 raise util.Abort(msg, hint=hint)
4066 4028
4067 4029 if parent not in bheads:
4068 4030 raise util.Abort(_('working directory not at a head revision'),
4069 4031 hint=_("use 'hg update' or merge with an "
4070 4032 "explicit revision"))
4071 4033 node = parent == bheads[0] and bheads[-1] or bheads[0]
4072 4034 else:
4073 4035 node = scmutil.revsingle(repo, node).node()
4074 4036
4075 4037 if opts.get('preview'):
4076 4038 # find nodes that are ancestors of p2 but not of p1
4077 4039 p1 = repo.lookup('.')
4078 4040 p2 = repo.lookup(node)
4079 4041 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4080 4042
4081 4043 displayer = cmdutil.show_changeset(ui, repo, opts)
4082 4044 for node in nodes:
4083 4045 displayer.show(repo[node])
4084 4046 displayer.close()
4085 4047 return 0
4086 4048
4087 4049 try:
4088 4050 # ui.forcemerge is an internal variable, do not document
4089 4051 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4090 4052 return hg.merge(repo, node, force=opts.get('force'))
4091 4053 finally:
4092 4054 ui.setconfig('ui', 'forcemerge', '')
4093 4055
4094 4056 @command('outgoing|out',
4095 4057 [('f', 'force', None, _('run even when the destination is unrelated')),
4096 4058 ('r', 'rev', [],
4097 4059 _('a changeset intended to be included in the destination'), _('REV')),
4098 4060 ('n', 'newest-first', None, _('show newest record first')),
4099 4061 ('B', 'bookmarks', False, _('compare bookmarks')),
4100 4062 ('b', 'branch', [], _('a specific branch you would like to push'),
4101 4063 _('BRANCH')),
4102 4064 ] + logopts + remoteopts + subrepoopts,
4103 4065 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
4104 4066 def outgoing(ui, repo, dest=None, **opts):
4105 4067 """show changesets not found in the destination
4106 4068
4107 4069 Show changesets not found in the specified destination repository
4108 4070 or the default push location. These are the changesets that would
4109 4071 be pushed if a push was requested.
4110 4072
4111 4073 See pull for details of valid destination formats.
4112 4074
4113 4075 Returns 0 if there are outgoing changes, 1 otherwise.
4114 4076 """
4115 4077
4116 4078 if opts.get('bookmarks'):
4117 4079 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4118 4080 dest, branches = hg.parseurl(dest, opts.get('branch'))
4119 4081 other = hg.peer(repo, opts, dest)
4120 4082 if 'bookmarks' not in other.listkeys('namespaces'):
4121 4083 ui.warn(_("remote doesn't support bookmarks\n"))
4122 4084 return 0
4123 4085 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
4124 4086 return bookmarks.diff(ui, other, repo)
4125 4087
4126 4088 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
4127 4089 try:
4128 4090 return hg.outgoing(ui, repo, dest, opts)
4129 4091 finally:
4130 4092 del repo._subtoppath
4131 4093
4132 4094 @command('parents',
4133 4095 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
4134 4096 ] + templateopts,
4135 4097 _('[-r REV] [FILE]'))
4136 4098 def parents(ui, repo, file_=None, **opts):
4137 4099 """show the parents of the working directory or revision
4138 4100
4139 4101 Print the working directory's parent revisions. If a revision is
4140 4102 given via -r/--rev, the parent of that revision will be printed.
4141 4103 If a file argument is given, the revision in which the file was
4142 4104 last changed (before the working directory revision or the
4143 4105 argument to --rev if given) is printed.
4144 4106
4145 4107 Returns 0 on success.
4146 4108 """
4147 4109
4148 4110 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
4149 4111
4150 4112 if file_:
4151 4113 m = scmutil.match(ctx, (file_,), opts)
4152 4114 if m.anypats() or len(m.files()) != 1:
4153 4115 raise util.Abort(_('can only specify an explicit filename'))
4154 4116 file_ = m.files()[0]
4155 4117 filenodes = []
4156 4118 for cp in ctx.parents():
4157 4119 if not cp:
4158 4120 continue
4159 4121 try:
4160 4122 filenodes.append(cp.filenode(file_))
4161 4123 except error.LookupError:
4162 4124 pass
4163 4125 if not filenodes:
4164 4126 raise util.Abort(_("'%s' not found in manifest!") % file_)
4165 4127 fl = repo.file(file_)
4166 4128 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
4167 4129 else:
4168 4130 p = [cp.node() for cp in ctx.parents()]
4169 4131
4170 4132 displayer = cmdutil.show_changeset(ui, repo, opts)
4171 4133 for n in p:
4172 4134 if n != nullid:
4173 4135 displayer.show(repo[n])
4174 4136 displayer.close()
4175 4137
4176 4138 @command('paths', [], _('[NAME]'))
4177 4139 def paths(ui, repo, search=None):
4178 4140 """show aliases for remote repositories
4179 4141
4180 4142 Show definition of symbolic path name NAME. If no name is given,
4181 4143 show definition of all available names.
4182 4144
4183 4145 Option -q/--quiet suppresses all output when searching for NAME
4184 4146 and shows only the path names when listing all definitions.
4185 4147
4186 4148 Path names are defined in the [paths] section of your
4187 4149 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
4188 4150 repository, ``.hg/hgrc`` is used, too.
4189 4151
4190 4152 The path names ``default`` and ``default-push`` have a special
4191 4153 meaning. When performing a push or pull operation, they are used
4192 4154 as fallbacks if no location is specified on the command-line.
4193 4155 When ``default-push`` is set, it will be used for push and
4194 4156 ``default`` will be used for pull; otherwise ``default`` is used
4195 4157 as the fallback for both. When cloning a repository, the clone
4196 4158 source is written as ``default`` in ``.hg/hgrc``. Note that
4197 4159 ``default`` and ``default-push`` apply to all inbound (e.g.
4198 4160 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
4199 4161 :hg:`bundle`) operations.
4200 4162
4201 4163 See :hg:`help urls` for more information.
4202 4164
4203 4165 Returns 0 on success.
4204 4166 """
4205 4167 if search:
4206 4168 for name, path in ui.configitems("paths"):
4207 4169 if name == search:
4208 4170 ui.status("%s\n" % util.hidepassword(path))
4209 4171 return
4210 4172 if not ui.quiet:
4211 4173 ui.warn(_("not found!\n"))
4212 4174 return 1
4213 4175 else:
4214 4176 for name, path in ui.configitems("paths"):
4215 4177 if ui.quiet:
4216 4178 ui.write("%s\n" % name)
4217 4179 else:
4218 4180 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
4219 4181
4220 4182 @command('^phase',
4221 4183 [('p', 'public', False, _('set changeset phase to public')),
4222 4184 ('d', 'draft', False, _('set changeset phase to draft')),
4223 4185 ('s', 'secret', False, _('set changeset phase to secret')),
4224 4186 ('f', 'force', False, _('allow to move boundary backward')),
4225 4187 ('r', 'rev', [], _('target revision'), _('REV')),
4226 4188 ],
4227 4189 _('[-p|-d|-s] [-f] [-r] REV...'))
4228 4190 def phase(ui, repo, *revs, **opts):
4229 4191 """set or show the current phase name
4230 4192
4231 4193 With no argument, show the phase name of specified revisions.
4232 4194
4233 4195 With one of -p/--public, -d/--draft or -s/--secret, change the
4234 4196 phase value of the specified revisions.
4235 4197
4236 4198 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
4237 4199 lower phase to an higher phase. Phases are ordered as follows::
4238 4200
4239 4201 public < draft < secret
4240 4202
4241 4203 Return 0 on success, 1 if no phases were changed.
4242 4204 """
4243 4205 # search for a unique phase argument
4244 4206 targetphase = None
4245 4207 for idx, name in enumerate(phases.phasenames):
4246 4208 if opts[name]:
4247 4209 if targetphase is not None:
4248 4210 raise util.Abort(_('only one phase can be specified'))
4249 4211 targetphase = idx
4250 4212
4251 4213 # look for specified revision
4252 4214 revs = list(revs)
4253 4215 revs.extend(opts['rev'])
4254 4216 if not revs:
4255 4217 raise util.Abort(_('no revisions specified!'))
4256 4218
4257 4219 lock = None
4258 4220 ret = 0
4259 4221 if targetphase is None:
4260 4222 # display
4261 4223 for ctx in repo.set('%lr', revs):
4262 4224 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
4263 4225 else:
4264 4226 lock = repo.lock()
4265 4227 try:
4266 4228 # set phase
4267 4229 nodes = [ctx.node() for ctx in repo.set('%lr', revs)]
4268 4230 if not nodes:
4269 4231 raise util.Abort(_('empty revision set'))
4270 4232 olddata = repo._phaserev[:]
4271 4233 phases.advanceboundary(repo, targetphase, nodes)
4272 4234 if opts['force']:
4273 4235 phases.retractboundary(repo, targetphase, nodes)
4274 4236 finally:
4275 4237 lock.release()
4276 4238 if olddata is not None:
4277 4239 changes = 0
4278 4240 newdata = repo._phaserev
4279 4241 changes = sum(o != newdata[i] for i, o in enumerate(olddata))
4280 4242 if changes:
4281 4243 ui.note(_('phase change for %i changesets\n') % changes)
4282 4244 else:
4283 4245 ui.warn(_('no phases changed\n'))
4284 4246 ret = 1
4285 4247 return ret
4286 4248
4287 4249 def postincoming(ui, repo, modheads, optupdate, checkout):
4288 4250 if modheads == 0:
4289 4251 return
4290 4252 if optupdate:
4291 4253 try:
4292 4254 return hg.update(repo, checkout)
4293 4255 except util.Abort, inst:
4294 4256 ui.warn(_("not updating: %s\n" % str(inst)))
4295 4257 return 0
4296 4258 if modheads > 1:
4297 4259 currentbranchheads = len(repo.branchheads())
4298 4260 if currentbranchheads == modheads:
4299 4261 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
4300 4262 elif currentbranchheads > 1:
4301 4263 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to merge)\n"))
4302 4264 else:
4303 4265 ui.status(_("(run 'hg heads' to see heads)\n"))
4304 4266 else:
4305 4267 ui.status(_("(run 'hg update' to get a working copy)\n"))
4306 4268
4307 4269 @command('^pull',
4308 4270 [('u', 'update', None,
4309 4271 _('update to new branch head if changesets were pulled')),
4310 4272 ('f', 'force', None, _('run even when remote repository is unrelated')),
4311 4273 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4312 4274 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
4313 4275 ('b', 'branch', [], _('a specific branch you would like to pull'),
4314 4276 _('BRANCH')),
4315 4277 ] + remoteopts,
4316 4278 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
4317 4279 def pull(ui, repo, source="default", **opts):
4318 4280 """pull changes from the specified source
4319 4281
4320 4282 Pull changes from a remote repository to a local one.
4321 4283
4322 4284 This finds all changes from the repository at the specified path
4323 4285 or URL and adds them to a local repository (the current one unless
4324 4286 -R is specified). By default, this does not update the copy of the
4325 4287 project in the working directory.
4326 4288
4327 4289 Use :hg:`incoming` if you want to see what would have been added
4328 4290 by a pull at the time you issued this command. If you then decide
4329 4291 to add those changes to the repository, you should use :hg:`pull
4330 4292 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4331 4293
4332 4294 If SOURCE is omitted, the 'default' path will be used.
4333 4295 See :hg:`help urls` for more information.
4334 4296
4335 4297 Returns 0 on success, 1 if an update had unresolved files.
4336 4298 """
4337 4299 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4338 4300 other = hg.peer(repo, opts, source)
4339 4301 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4340 4302 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
4341 4303
4342 4304 if opts.get('bookmark'):
4343 4305 if not revs:
4344 4306 revs = []
4345 4307 rb = other.listkeys('bookmarks')
4346 4308 for b in opts['bookmark']:
4347 4309 if b not in rb:
4348 4310 raise util.Abort(_('remote bookmark %s not found!') % b)
4349 4311 revs.append(rb[b])
4350 4312
4351 4313 if revs:
4352 4314 try:
4353 4315 revs = [other.lookup(rev) for rev in revs]
4354 4316 except error.CapabilityError:
4355 4317 err = _("other repository doesn't support revision lookup, "
4356 4318 "so a rev cannot be specified.")
4357 4319 raise util.Abort(err)
4358 4320
4359 4321 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
4360 4322 bookmarks.updatefromremote(ui, repo, other, source)
4361 4323 if checkout:
4362 4324 checkout = str(repo.changelog.rev(other.lookup(checkout)))
4363 4325 repo._subtoppath = source
4364 4326 try:
4365 4327 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
4366 4328
4367 4329 finally:
4368 4330 del repo._subtoppath
4369 4331
4370 4332 # update specified bookmarks
4371 4333 if opts.get('bookmark'):
4372 4334 for b in opts['bookmark']:
4373 4335 # explicit pull overrides local bookmark if any
4374 4336 ui.status(_("importing bookmark %s\n") % b)
4375 4337 repo._bookmarks[b] = repo[rb[b]].node()
4376 4338 bookmarks.write(repo)
4377 4339
4378 4340 return ret
4379 4341
4380 4342 @command('^push',
4381 4343 [('f', 'force', None, _('force push')),
4382 4344 ('r', 'rev', [],
4383 4345 _('a changeset intended to be included in the destination'),
4384 4346 _('REV')),
4385 4347 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4386 4348 ('b', 'branch', [],
4387 4349 _('a specific branch you would like to push'), _('BRANCH')),
4388 4350 ('', 'new-branch', False, _('allow pushing a new branch')),
4389 4351 ] + remoteopts,
4390 4352 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4391 4353 def push(ui, repo, dest=None, **opts):
4392 4354 """push changes to the specified destination
4393 4355
4394 4356 Push changesets from the local repository to the specified
4395 4357 destination.
4396 4358
4397 4359 This operation is symmetrical to pull: it is identical to a pull
4398 4360 in the destination repository from the current one.
4399 4361
4400 4362 By default, push will not allow creation of new heads at the
4401 4363 destination, since multiple heads would make it unclear which head
4402 4364 to use. In this situation, it is recommended to pull and merge
4403 4365 before pushing.
4404 4366
4405 4367 Use --new-branch if you want to allow push to create a new named
4406 4368 branch that is not present at the destination. This allows you to
4407 4369 only create a new branch without forcing other changes.
4408 4370
4409 4371 Use -f/--force to override the default behavior and push all
4410 4372 changesets on all branches.
4411 4373
4412 4374 If -r/--rev is used, the specified revision and all its ancestors
4413 4375 will be pushed to the remote repository.
4414 4376
4415 4377 Please see :hg:`help urls` for important details about ``ssh://``
4416 4378 URLs. If DESTINATION is omitted, a default path will be used.
4417 4379
4418 4380 Returns 0 if push was successful, 1 if nothing to push.
4419 4381 """
4420 4382
4421 4383 if opts.get('bookmark'):
4422 4384 for b in opts['bookmark']:
4423 4385 # translate -B options to -r so changesets get pushed
4424 4386 if b in repo._bookmarks:
4425 4387 opts.setdefault('rev', []).append(b)
4426 4388 else:
4427 4389 # if we try to push a deleted bookmark, translate it to null
4428 4390 # this lets simultaneous -r, -b options continue working
4429 4391 opts.setdefault('rev', []).append("null")
4430 4392
4431 4393 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4432 4394 dest, branches = hg.parseurl(dest, opts.get('branch'))
4433 4395 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4434 4396 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4435 4397 other = hg.peer(repo, opts, dest)
4436 4398 if revs:
4437 4399 revs = [repo.lookup(rev) for rev in revs]
4438 4400
4439 4401 repo._subtoppath = dest
4440 4402 try:
4441 4403 # push subrepos depth-first for coherent ordering
4442 4404 c = repo['']
4443 4405 subs = c.substate # only repos that are committed
4444 4406 for s in sorted(subs):
4445 4407 if not c.sub(s).push(opts):
4446 4408 return False
4447 4409 finally:
4448 4410 del repo._subtoppath
4449 4411 result = repo.push(other, opts.get('force'), revs=revs,
4450 4412 newbranch=opts.get('new_branch'))
4451 4413
4452 4414 result = (result == 0)
4453 4415
4454 4416 if opts.get('bookmark'):
4455 4417 rb = other.listkeys('bookmarks')
4456 4418 for b in opts['bookmark']:
4457 4419 # explicit push overrides remote bookmark if any
4458 4420 if b in repo._bookmarks:
4459 4421 ui.status(_("exporting bookmark %s\n") % b)
4460 4422 new = repo[b].hex()
4461 4423 elif b in rb:
4462 4424 ui.status(_("deleting remote bookmark %s\n") % b)
4463 4425 new = '' # delete
4464 4426 else:
4465 4427 ui.warn(_('bookmark %s does not exist on the local '
4466 4428 'or remote repository!\n') % b)
4467 4429 return 2
4468 4430 old = rb.get(b, '')
4469 4431 r = other.pushkey('bookmarks', b, old, new)
4470 4432 if not r:
4471 4433 ui.warn(_('updating bookmark %s failed!\n') % b)
4472 4434 if not result:
4473 4435 result = 2
4474 4436
4475 4437 return result
4476 4438
4477 4439 @command('recover', [])
4478 4440 def recover(ui, repo):
4479 4441 """roll back an interrupted transaction
4480 4442
4481 4443 Recover from an interrupted commit or pull.
4482 4444
4483 4445 This command tries to fix the repository status after an
4484 4446 interrupted operation. It should only be necessary when Mercurial
4485 4447 suggests it.
4486 4448
4487 4449 Returns 0 if successful, 1 if nothing to recover or verify fails.
4488 4450 """
4489 4451 if repo.recover():
4490 4452 return hg.verify(repo)
4491 4453 return 1
4492 4454
4493 4455 @command('^remove|rm',
4494 4456 [('A', 'after', None, _('record delete for missing files')),
4495 4457 ('f', 'force', None,
4496 4458 _('remove (and delete) file even if added or modified')),
4497 4459 ] + walkopts,
4498 4460 _('[OPTION]... FILE...'))
4499 4461 def remove(ui, repo, *pats, **opts):
4500 4462 """remove the specified files on the next commit
4501 4463
4502 4464 Schedule the indicated files for removal from the current branch.
4503 4465
4504 4466 This command schedules the files to be removed at the next commit.
4505 4467 To undo a remove before that, see :hg:`revert`. To undo added
4506 4468 files, see :hg:`forget`.
4507 4469
4508 4470 .. container:: verbose
4509 4471
4510 4472 -A/--after can be used to remove only files that have already
4511 4473 been deleted, -f/--force can be used to force deletion, and -Af
4512 4474 can be used to remove files from the next revision without
4513 4475 deleting them from the working directory.
4514 4476
4515 4477 The following table details the behavior of remove for different
4516 4478 file states (columns) and option combinations (rows). The file
4517 4479 states are Added [A], Clean [C], Modified [M] and Missing [!]
4518 4480 (as reported by :hg:`status`). The actions are Warn, Remove
4519 4481 (from branch) and Delete (from disk):
4520 4482
4521 4483 ======= == == == ==
4522 4484 A C M !
4523 4485 ======= == == == ==
4524 4486 none W RD W R
4525 4487 -f R RD RD R
4526 4488 -A W W W R
4527 4489 -Af R R R R
4528 4490 ======= == == == ==
4529 4491
4530 4492 Note that remove never deletes files in Added [A] state from the
4531 4493 working directory, not even if option --force is specified.
4532 4494
4533 4495 Returns 0 on success, 1 if any warnings encountered.
4534 4496 """
4535 4497
4536 4498 ret = 0
4537 4499 after, force = opts.get('after'), opts.get('force')
4538 4500 if not pats and not after:
4539 4501 raise util.Abort(_('no files specified'))
4540 4502
4541 4503 m = scmutil.match(repo[None], pats, opts)
4542 4504 s = repo.status(match=m, clean=True)
4543 4505 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
4544 4506
4545 4507 for f in m.files():
4546 4508 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
4547 4509 if os.path.exists(m.rel(f)):
4548 4510 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
4549 4511 ret = 1
4550 4512
4551 4513 if force:
4552 4514 list = modified + deleted + clean + added
4553 4515 elif after:
4554 4516 list = deleted
4555 4517 for f in modified + added + clean:
4556 4518 ui.warn(_('not removing %s: file still exists (use -f'
4557 4519 ' to force removal)\n') % m.rel(f))
4558 4520 ret = 1
4559 4521 else:
4560 4522 list = deleted + clean
4561 4523 for f in modified:
4562 4524 ui.warn(_('not removing %s: file is modified (use -f'
4563 4525 ' to force removal)\n') % m.rel(f))
4564 4526 ret = 1
4565 4527 for f in added:
4566 4528 ui.warn(_('not removing %s: file has been marked for add'
4567 4529 ' (use forget to undo)\n') % m.rel(f))
4568 4530 ret = 1
4569 4531
4570 4532 for f in sorted(list):
4571 4533 if ui.verbose or not m.exact(f):
4572 4534 ui.status(_('removing %s\n') % m.rel(f))
4573 4535
4574 4536 wlock = repo.wlock()
4575 4537 try:
4576 4538 if not after:
4577 4539 for f in list:
4578 4540 if f in added:
4579 4541 continue # we never unlink added files on remove
4580 4542 try:
4581 4543 util.unlinkpath(repo.wjoin(f))
4582 4544 except OSError, inst:
4583 4545 if inst.errno != errno.ENOENT:
4584 4546 raise
4585 4547 repo[None].forget(list)
4586 4548 finally:
4587 4549 wlock.release()
4588 4550
4589 4551 return ret
4590 4552
4591 4553 @command('rename|move|mv',
4592 4554 [('A', 'after', None, _('record a rename that has already occurred')),
4593 4555 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4594 4556 ] + walkopts + dryrunopts,
4595 4557 _('[OPTION]... SOURCE... DEST'))
4596 4558 def rename(ui, repo, *pats, **opts):
4597 4559 """rename files; equivalent of copy + remove
4598 4560
4599 4561 Mark dest as copies of sources; mark sources for deletion. If dest
4600 4562 is a directory, copies are put in that directory. If dest is a
4601 4563 file, there can only be one source.
4602 4564
4603 4565 By default, this command copies the contents of files as they
4604 4566 exist in the working directory. If invoked with -A/--after, the
4605 4567 operation is recorded, but no copying is performed.
4606 4568
4607 4569 This command takes effect at the next commit. To undo a rename
4608 4570 before that, see :hg:`revert`.
4609 4571
4610 4572 Returns 0 on success, 1 if errors are encountered.
4611 4573 """
4612 4574 wlock = repo.wlock(False)
4613 4575 try:
4614 4576 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4615 4577 finally:
4616 4578 wlock.release()
4617 4579
4618 4580 @command('resolve',
4619 4581 [('a', 'all', None, _('select all unresolved files')),
4620 4582 ('l', 'list', None, _('list state of files needing merge')),
4621 4583 ('m', 'mark', None, _('mark files as resolved')),
4622 4584 ('u', 'unmark', None, _('mark files as unresolved')),
4623 4585 ('n', 'no-status', None, _('hide status prefix'))]
4624 4586 + mergetoolopts + walkopts,
4625 4587 _('[OPTION]... [FILE]...'))
4626 4588 def resolve(ui, repo, *pats, **opts):
4627 4589 """redo merges or set/view the merge status of files
4628 4590
4629 4591 Merges with unresolved conflicts are often the result of
4630 4592 non-interactive merging using the ``internal:merge`` configuration
4631 4593 setting, or a command-line merge tool like ``diff3``. The resolve
4632 4594 command is used to manage the files involved in a merge, after
4633 4595 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4634 4596 working directory must have two parents).
4635 4597
4636 4598 The resolve command can be used in the following ways:
4637 4599
4638 4600 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4639 4601 files, discarding any previous merge attempts. Re-merging is not
4640 4602 performed for files already marked as resolved. Use ``--all/-a``
4641 4603 to select all unresolved files. ``--tool`` can be used to specify
4642 4604 the merge tool used for the given files. It overrides the HGMERGE
4643 4605 environment variable and your configuration files. Previous file
4644 4606 contents are saved with a ``.orig`` suffix.
4645 4607
4646 4608 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4647 4609 (e.g. after having manually fixed-up the files). The default is
4648 4610 to mark all unresolved files.
4649 4611
4650 4612 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4651 4613 default is to mark all resolved files.
4652 4614
4653 4615 - :hg:`resolve -l`: list files which had or still have conflicts.
4654 4616 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4655 4617
4656 4618 Note that Mercurial will not let you commit files with unresolved
4657 4619 merge conflicts. You must use :hg:`resolve -m ...` before you can
4658 4620 commit after a conflicting merge.
4659 4621
4660 4622 Returns 0 on success, 1 if any files fail a resolve attempt.
4661 4623 """
4662 4624
4663 4625 all, mark, unmark, show, nostatus = \
4664 4626 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4665 4627
4666 4628 if (show and (mark or unmark)) or (mark and unmark):
4667 4629 raise util.Abort(_("too many options specified"))
4668 4630 if pats and all:
4669 4631 raise util.Abort(_("can't specify --all and patterns"))
4670 4632 if not (all or pats or show or mark or unmark):
4671 4633 raise util.Abort(_('no files or directories specified; '
4672 4634 'use --all to remerge all files'))
4673 4635
4674 4636 ms = mergemod.mergestate(repo)
4675 4637 m = scmutil.match(repo[None], pats, opts)
4676 4638 ret = 0
4677 4639
4678 4640 for f in ms:
4679 4641 if m(f):
4680 4642 if show:
4681 4643 if nostatus:
4682 4644 ui.write("%s\n" % f)
4683 4645 else:
4684 4646 ui.write("%s %s\n" % (ms[f].upper(), f),
4685 4647 label='resolve.' +
4686 4648 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
4687 4649 elif mark:
4688 4650 ms.mark(f, "r")
4689 4651 elif unmark:
4690 4652 ms.mark(f, "u")
4691 4653 else:
4692 4654 wctx = repo[None]
4693 4655 mctx = wctx.parents()[-1]
4694 4656
4695 4657 # backup pre-resolve (merge uses .orig for its own purposes)
4696 4658 a = repo.wjoin(f)
4697 4659 util.copyfile(a, a + ".resolve")
4698 4660
4699 4661 try:
4700 4662 # resolve file
4701 4663 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4702 4664 if ms.resolve(f, wctx, mctx):
4703 4665 ret = 1
4704 4666 finally:
4705 4667 ui.setconfig('ui', 'forcemerge', '')
4706 4668
4707 4669 # replace filemerge's .orig file with our resolve file
4708 4670 util.rename(a + ".resolve", a + ".orig")
4709 4671
4710 4672 ms.commit()
4711 4673 return ret
4712 4674
4713 4675 @command('revert',
4714 4676 [('a', 'all', None, _('revert all changes when no arguments given')),
4715 4677 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4716 4678 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4717 4679 ('C', 'no-backup', None, _('do not save backup copies of files')),
4718 4680 ] + walkopts + dryrunopts,
4719 4681 _('[OPTION]... [-r REV] [NAME]...'))
4720 4682 def revert(ui, repo, *pats, **opts):
4721 4683 """restore files to their checkout state
4722 4684
4723 4685 .. note::
4724 4686 To check out earlier revisions, you should use :hg:`update REV`.
4725 4687 To cancel a merge (and lose your changes), use :hg:`update --clean .`.
4726 4688
4727 4689 With no revision specified, revert the specified files or directories
4728 4690 to the contents they had in the parent of the working directory.
4729 4691 This restores the contents of files to an unmodified
4730 4692 state and unschedules adds, removes, copies, and renames. If the
4731 4693 working directory has two parents, you must explicitly specify a
4732 4694 revision.
4733 4695
4734 4696 Using the -r/--rev or -d/--date options, revert the given files or
4735 4697 directories to their states as of a specific revision. Because
4736 4698 revert does not change the working directory parents, this will
4737 4699 cause these files to appear modified. This can be helpful to "back
4738 4700 out" some or all of an earlier change. See :hg:`backout` for a
4739 4701 related method.
4740 4702
4741 4703 Modified files are saved with a .orig suffix before reverting.
4742 4704 To disable these backups, use --no-backup.
4743 4705
4744 4706 See :hg:`help dates` for a list of formats valid for -d/--date.
4745 4707
4746 4708 Returns 0 on success.
4747 4709 """
4748 4710
4749 4711 if opts.get("date"):
4750 4712 if opts.get("rev"):
4751 4713 raise util.Abort(_("you can't specify a revision and a date"))
4752 4714 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4753 4715
4754 4716 parent, p2 = repo.dirstate.parents()
4755 4717 if not opts.get('rev') and p2 != nullid:
4756 4718 # revert after merge is a trap for new users (issue2915)
4757 4719 raise util.Abort(_('uncommitted merge with no revision specified'),
4758 4720 hint=_('use "hg update" or see "hg help revert"'))
4759 4721
4760 4722 ctx = scmutil.revsingle(repo, opts.get('rev'))
4761 4723 node = ctx.node()
4762 4724
4763 4725 if not pats and not opts.get('all'):
4764 4726 msg = _("no files or directories specified")
4765 4727 if p2 != nullid:
4766 4728 hint = _("uncommitted merge, use --all to discard all changes,"
4767 4729 " or 'hg update -C .' to abort the merge")
4768 4730 raise util.Abort(msg, hint=hint)
4769 4731 dirty = util.any(repo.status())
4770 4732 if node != parent:
4771 4733 if dirty:
4772 4734 hint = _("uncommitted changes, use --all to discard all"
4773 4735 " changes, or 'hg update %s' to update") % ctx.rev()
4774 4736 else:
4775 4737 hint = _("use --all to revert all files,"
4776 4738 " or 'hg update %s' to update") % ctx.rev()
4777 4739 elif dirty:
4778 4740 hint = _("uncommitted changes, use --all to discard all changes")
4779 4741 else:
4780 4742 hint = _("use --all to revert all files")
4781 4743 raise util.Abort(msg, hint=hint)
4782 4744
4783 4745 mf = ctx.manifest()
4784 4746 if node == parent:
4785 4747 pmf = mf
4786 4748 else:
4787 4749 pmf = None
4788 4750
4789 4751 # need all matching names in dirstate and manifest of target rev,
4790 4752 # so have to walk both. do not print errors if files exist in one
4791 4753 # but not other.
4792 4754
4793 4755 names = {}
4794 4756
4795 4757 wlock = repo.wlock()
4796 4758 try:
4797 4759 # walk dirstate.
4798 4760
4799 4761 m = scmutil.match(repo[None], pats, opts)
4800 4762 m.bad = lambda x, y: False
4801 4763 for abs in repo.walk(m):
4802 4764 names[abs] = m.rel(abs), m.exact(abs)
4803 4765
4804 4766 # walk target manifest.
4805 4767
4806 4768 def badfn(path, msg):
4807 4769 if path in names:
4808 4770 return
4809 4771 if path in repo[node].substate:
4810 4772 ui.warn("%s: %s\n" % (m.rel(path),
4811 4773 'reverting subrepos is unsupported'))
4812 4774 return
4813 4775 path_ = path + '/'
4814 4776 for f in names:
4815 4777 if f.startswith(path_):
4816 4778 return
4817 4779 ui.warn("%s: %s\n" % (m.rel(path), msg))
4818 4780
4819 4781 m = scmutil.match(repo[node], pats, opts)
4820 4782 m.bad = badfn
4821 4783 for abs in repo[node].walk(m):
4822 4784 if abs not in names:
4823 4785 names[abs] = m.rel(abs), m.exact(abs)
4824 4786
4825 4787 m = scmutil.matchfiles(repo, names)
4826 4788 changes = repo.status(match=m)[:4]
4827 4789 modified, added, removed, deleted = map(set, changes)
4828 4790
4829 4791 # if f is a rename, also revert the source
4830 4792 cwd = repo.getcwd()
4831 4793 for f in added:
4832 4794 src = repo.dirstate.copied(f)
4833 4795 if src and src not in names and repo.dirstate[src] == 'r':
4834 4796 removed.add(src)
4835 4797 names[src] = (repo.pathto(src, cwd), True)
4836 4798
4837 4799 def removeforget(abs):
4838 4800 if repo.dirstate[abs] == 'a':
4839 4801 return _('forgetting %s\n')
4840 4802 return _('removing %s\n')
4841 4803
4842 4804 revert = ([], _('reverting %s\n'))
4843 4805 add = ([], _('adding %s\n'))
4844 4806 remove = ([], removeforget)
4845 4807 undelete = ([], _('undeleting %s\n'))
4846 4808
4847 4809 disptable = (
4848 4810 # dispatch table:
4849 4811 # file state
4850 4812 # action if in target manifest
4851 4813 # action if not in target manifest
4852 4814 # make backup if in target manifest
4853 4815 # make backup if not in target manifest
4854 4816 (modified, revert, remove, True, True),
4855 4817 (added, revert, remove, True, False),
4856 4818 (removed, undelete, None, False, False),
4857 4819 (deleted, revert, remove, False, False),
4858 4820 )
4859 4821
4860 4822 for abs, (rel, exact) in sorted(names.items()):
4861 4823 mfentry = mf.get(abs)
4862 4824 target = repo.wjoin(abs)
4863 4825 def handle(xlist, dobackup):
4864 4826 xlist[0].append(abs)
4865 4827 if (dobackup and not opts.get('no_backup') and
4866 4828 os.path.lexists(target)):
4867 4829 bakname = "%s.orig" % rel
4868 4830 ui.note(_('saving current version of %s as %s\n') %
4869 4831 (rel, bakname))
4870 4832 if not opts.get('dry_run'):
4871 4833 util.rename(target, bakname)
4872 4834 if ui.verbose or not exact:
4873 4835 msg = xlist[1]
4874 4836 if not isinstance(msg, basestring):
4875 4837 msg = msg(abs)
4876 4838 ui.status(msg % rel)
4877 4839 for table, hitlist, misslist, backuphit, backupmiss in disptable:
4878 4840 if abs not in table:
4879 4841 continue
4880 4842 # file has changed in dirstate
4881 4843 if mfentry:
4882 4844 handle(hitlist, backuphit)
4883 4845 elif misslist is not None:
4884 4846 handle(misslist, backupmiss)
4885 4847 break
4886 4848 else:
4887 4849 if abs not in repo.dirstate:
4888 4850 if mfentry:
4889 4851 handle(add, True)
4890 4852 elif exact:
4891 4853 ui.warn(_('file not managed: %s\n') % rel)
4892 4854 continue
4893 4855 # file has not changed in dirstate
4894 4856 if node == parent:
4895 4857 if exact:
4896 4858 ui.warn(_('no changes needed to %s\n') % rel)
4897 4859 continue
4898 4860 if pmf is None:
4899 4861 # only need parent manifest in this unlikely case,
4900 4862 # so do not read by default
4901 4863 pmf = repo[parent].manifest()
4902 4864 if abs in pmf and mfentry:
4903 4865 # if version of file is same in parent and target
4904 4866 # manifests, do nothing
4905 4867 if (pmf[abs] != mfentry or
4906 4868 pmf.flags(abs) != mf.flags(abs)):
4907 4869 handle(revert, False)
4908 4870 else:
4909 4871 handle(remove, False)
4910 4872
4911 4873 if not opts.get('dry_run'):
4912 4874 def checkout(f):
4913 4875 fc = ctx[f]
4914 4876 repo.wwrite(f, fc.data(), fc.flags())
4915 4877
4916 4878 audit_path = scmutil.pathauditor(repo.root)
4917 4879 for f in remove[0]:
4918 4880 if repo.dirstate[f] == 'a':
4919 4881 repo.dirstate.drop(f)
4920 4882 continue
4921 4883 audit_path(f)
4922 4884 try:
4923 4885 util.unlinkpath(repo.wjoin(f))
4924 4886 except OSError:
4925 4887 pass
4926 4888 repo.dirstate.remove(f)
4927 4889
4928 4890 normal = None
4929 4891 if node == parent:
4930 4892 # We're reverting to our parent. If possible, we'd like status
4931 4893 # to report the file as clean. We have to use normallookup for
4932 4894 # merges to avoid losing information about merged/dirty files.
4933 4895 if p2 != nullid:
4934 4896 normal = repo.dirstate.normallookup
4935 4897 else:
4936 4898 normal = repo.dirstate.normal
4937 4899 for f in revert[0]:
4938 4900 checkout(f)
4939 4901 if normal:
4940 4902 normal(f)
4941 4903
4942 4904 for f in add[0]:
4943 4905 checkout(f)
4944 4906 repo.dirstate.add(f)
4945 4907
4946 4908 normal = repo.dirstate.normallookup
4947 4909 if node == parent and p2 == nullid:
4948 4910 normal = repo.dirstate.normal
4949 4911 for f in undelete[0]:
4950 4912 checkout(f)
4951 4913 normal(f)
4952 4914
4953 4915 finally:
4954 4916 wlock.release()
4955 4917
4956 4918 @command('rollback', dryrunopts +
4957 4919 [('f', 'force', False, _('ignore safety measures'))])
4958 4920 def rollback(ui, repo, **opts):
4959 4921 """roll back the last transaction (dangerous)
4960 4922
4961 4923 This command should be used with care. There is only one level of
4962 4924 rollback, and there is no way to undo a rollback. It will also
4963 4925 restore the dirstate at the time of the last transaction, losing
4964 4926 any dirstate changes since that time. This command does not alter
4965 4927 the working directory.
4966 4928
4967 4929 Transactions are used to encapsulate the effects of all commands
4968 4930 that create new changesets or propagate existing changesets into a
4969 4931 repository. For example, the following commands are transactional,
4970 4932 and their effects can be rolled back:
4971 4933
4972 4934 - commit
4973 4935 - import
4974 4936 - pull
4975 4937 - push (with this repository as the destination)
4976 4938 - unbundle
4977 4939
4978 4940 To avoid permanent data loss, rollback will refuse to rollback a
4979 4941 commit transaction if it isn't checked out. Use --force to
4980 4942 override this protection.
4981 4943
4982 4944 This command is not intended for use on public repositories. Once
4983 4945 changes are visible for pull by other users, rolling a transaction
4984 4946 back locally is ineffective (someone else may already have pulled
4985 4947 the changes). Furthermore, a race is possible with readers of the
4986 4948 repository; for example an in-progress pull from the repository
4987 4949 may fail if a rollback is performed.
4988 4950
4989 4951 Returns 0 on success, 1 if no rollback data is available.
4990 4952 """
4991 4953 return repo.rollback(dryrun=opts.get('dry_run'),
4992 4954 force=opts.get('force'))
4993 4955
4994 4956 @command('root', [])
4995 4957 def root(ui, repo):
4996 4958 """print the root (top) of the current working directory
4997 4959
4998 4960 Print the root directory of the current repository.
4999 4961
5000 4962 Returns 0 on success.
5001 4963 """
5002 4964 ui.write(repo.root + "\n")
5003 4965
5004 4966 @command('^serve',
5005 4967 [('A', 'accesslog', '', _('name of access log file to write to'),
5006 4968 _('FILE')),
5007 4969 ('d', 'daemon', None, _('run server in background')),
5008 4970 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
5009 4971 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
5010 4972 # use string type, then we can check if something was passed
5011 4973 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
5012 4974 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
5013 4975 _('ADDR')),
5014 4976 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
5015 4977 _('PREFIX')),
5016 4978 ('n', 'name', '',
5017 4979 _('name to show in web pages (default: working directory)'), _('NAME')),
5018 4980 ('', 'web-conf', '',
5019 4981 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
5020 4982 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
5021 4983 _('FILE')),
5022 4984 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
5023 4985 ('', 'stdio', None, _('for remote clients')),
5024 4986 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
5025 4987 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
5026 4988 ('', 'style', '', _('template style to use'), _('STYLE')),
5027 4989 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
5028 4990 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
5029 4991 _('[OPTION]...'))
5030 4992 def serve(ui, repo, **opts):
5031 4993 """start stand-alone webserver
5032 4994
5033 4995 Start a local HTTP repository browser and pull server. You can use
5034 4996 this for ad-hoc sharing and browsing of repositories. It is
5035 4997 recommended to use a real web server to serve a repository for
5036 4998 longer periods of time.
5037 4999
5038 5000 Please note that the server does not implement access control.
5039 5001 This means that, by default, anybody can read from the server and
5040 5002 nobody can write to it by default. Set the ``web.allow_push``
5041 5003 option to ``*`` to allow everybody to push to the server. You
5042 5004 should use a real web server if you need to authenticate users.
5043 5005
5044 5006 By default, the server logs accesses to stdout and errors to
5045 5007 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
5046 5008 files.
5047 5009
5048 5010 To have the server choose a free port number to listen on, specify
5049 5011 a port number of 0; in this case, the server will print the port
5050 5012 number it uses.
5051 5013
5052 5014 Returns 0 on success.
5053 5015 """
5054 5016
5055 5017 if opts["stdio"] and opts["cmdserver"]:
5056 5018 raise util.Abort(_("cannot use --stdio with --cmdserver"))
5057 5019
5058 5020 def checkrepo():
5059 5021 if repo is None:
5060 5022 raise error.RepoError(_("There is no Mercurial repository here"
5061 5023 " (.hg not found)"))
5062 5024
5063 5025 if opts["stdio"]:
5064 5026 checkrepo()
5065 5027 s = sshserver.sshserver(ui, repo)
5066 5028 s.serve_forever()
5067 5029
5068 5030 if opts["cmdserver"]:
5069 5031 checkrepo()
5070 5032 s = commandserver.server(ui, repo, opts["cmdserver"])
5071 5033 return s.serve()
5072 5034
5073 5035 # this way we can check if something was given in the command-line
5074 5036 if opts.get('port'):
5075 5037 opts['port'] = util.getport(opts.get('port'))
5076 5038
5077 5039 baseui = repo and repo.baseui or ui
5078 5040 optlist = ("name templates style address port prefix ipv6"
5079 5041 " accesslog errorlog certificate encoding")
5080 5042 for o in optlist.split():
5081 5043 val = opts.get(o, '')
5082 5044 if val in (None, ''): # should check against default options instead
5083 5045 continue
5084 5046 baseui.setconfig("web", o, val)
5085 5047 if repo and repo.ui != baseui:
5086 5048 repo.ui.setconfig("web", o, val)
5087 5049
5088 5050 o = opts.get('web_conf') or opts.get('webdir_conf')
5089 5051 if not o:
5090 5052 if not repo:
5091 5053 raise error.RepoError(_("There is no Mercurial repository"
5092 5054 " here (.hg not found)"))
5093 5055 o = repo.root
5094 5056
5095 5057 app = hgweb.hgweb(o, baseui=ui)
5096 5058
5097 5059 class service(object):
5098 5060 def init(self):
5099 5061 util.setsignalhandler()
5100 5062 self.httpd = hgweb.server.create_server(ui, app)
5101 5063
5102 5064 if opts['port'] and not ui.verbose:
5103 5065 return
5104 5066
5105 5067 if self.httpd.prefix:
5106 5068 prefix = self.httpd.prefix.strip('/') + '/'
5107 5069 else:
5108 5070 prefix = ''
5109 5071
5110 5072 port = ':%d' % self.httpd.port
5111 5073 if port == ':80':
5112 5074 port = ''
5113 5075
5114 5076 bindaddr = self.httpd.addr
5115 5077 if bindaddr == '0.0.0.0':
5116 5078 bindaddr = '*'
5117 5079 elif ':' in bindaddr: # IPv6
5118 5080 bindaddr = '[%s]' % bindaddr
5119 5081
5120 5082 fqaddr = self.httpd.fqaddr
5121 5083 if ':' in fqaddr:
5122 5084 fqaddr = '[%s]' % fqaddr
5123 5085 if opts['port']:
5124 5086 write = ui.status
5125 5087 else:
5126 5088 write = ui.write
5127 5089 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
5128 5090 (fqaddr, port, prefix, bindaddr, self.httpd.port))
5129 5091
5130 5092 def run(self):
5131 5093 self.httpd.serve_forever()
5132 5094
5133 5095 service = service()
5134 5096
5135 5097 cmdutil.service(opts, initfn=service.init, runfn=service.run)
5136 5098
5137 5099 @command('showconfig|debugconfig',
5138 5100 [('u', 'untrusted', None, _('show untrusted configuration options'))],
5139 5101 _('[-u] [NAME]...'))
5140 5102 def showconfig(ui, repo, *values, **opts):
5141 5103 """show combined config settings from all hgrc files
5142 5104
5143 5105 With no arguments, print names and values of all config items.
5144 5106
5145 5107 With one argument of the form section.name, print just the value
5146 5108 of that config item.
5147 5109
5148 5110 With multiple arguments, print names and values of all config
5149 5111 items with matching section names.
5150 5112
5151 5113 With --debug, the source (filename and line number) is printed
5152 5114 for each config item.
5153 5115
5154 5116 Returns 0 on success.
5155 5117 """
5156 5118
5157 5119 for f in scmutil.rcpath():
5158 5120 ui.debug('read config from: %s\n' % f)
5159 5121 untrusted = bool(opts.get('untrusted'))
5160 5122 if values:
5161 5123 sections = [v for v in values if '.' not in v]
5162 5124 items = [v for v in values if '.' in v]
5163 5125 if len(items) > 1 or items and sections:
5164 5126 raise util.Abort(_('only one config item permitted'))
5165 5127 for section, name, value in ui.walkconfig(untrusted=untrusted):
5166 5128 value = str(value).replace('\n', '\\n')
5167 5129 sectname = section + '.' + name
5168 5130 if values:
5169 5131 for v in values:
5170 5132 if v == section:
5171 5133 ui.debug('%s: ' %
5172 5134 ui.configsource(section, name, untrusted))
5173 5135 ui.write('%s=%s\n' % (sectname, value))
5174 5136 elif v == sectname:
5175 5137 ui.debug('%s: ' %
5176 5138 ui.configsource(section, name, untrusted))
5177 5139 ui.write(value, '\n')
5178 5140 else:
5179 5141 ui.debug('%s: ' %
5180 5142 ui.configsource(section, name, untrusted))
5181 5143 ui.write('%s=%s\n' % (sectname, value))
5182 5144
5183 5145 @command('^status|st',
5184 5146 [('A', 'all', None, _('show status of all files')),
5185 5147 ('m', 'modified', None, _('show only modified files')),
5186 5148 ('a', 'added', None, _('show only added files')),
5187 5149 ('r', 'removed', None, _('show only removed files')),
5188 5150 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
5189 5151 ('c', 'clean', None, _('show only files without changes')),
5190 5152 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
5191 5153 ('i', 'ignored', None, _('show only ignored files')),
5192 5154 ('n', 'no-status', None, _('hide status prefix')),
5193 5155 ('C', 'copies', None, _('show source of copied files')),
5194 5156 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
5195 5157 ('', 'rev', [], _('show difference from revision'), _('REV')),
5196 5158 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
5197 5159 ] + walkopts + subrepoopts,
5198 5160 _('[OPTION]... [FILE]...'))
5199 5161 def status(ui, repo, *pats, **opts):
5200 5162 """show changed files in the working directory
5201 5163
5202 5164 Show status of files in the repository. If names are given, only
5203 5165 files that match are shown. Files that are clean or ignored or
5204 5166 the source of a copy/move operation, are not listed unless
5205 5167 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
5206 5168 Unless options described with "show only ..." are given, the
5207 5169 options -mardu are used.
5208 5170
5209 5171 Option -q/--quiet hides untracked (unknown and ignored) files
5210 5172 unless explicitly requested with -u/--unknown or -i/--ignored.
5211 5173
5212 5174 .. note::
5213 5175 status may appear to disagree with diff if permissions have
5214 5176 changed or a merge has occurred. The standard diff format does
5215 5177 not report permission changes and diff only reports changes
5216 5178 relative to one merge parent.
5217 5179
5218 5180 If one revision is given, it is used as the base revision.
5219 5181 If two revisions are given, the differences between them are
5220 5182 shown. The --change option can also be used as a shortcut to list
5221 5183 the changed files of a revision from its first parent.
5222 5184
5223 5185 The codes used to show the status of files are::
5224 5186
5225 5187 M = modified
5226 5188 A = added
5227 5189 R = removed
5228 5190 C = clean
5229 5191 ! = missing (deleted by non-hg command, but still tracked)
5230 5192 ? = not tracked
5231 5193 I = ignored
5232 5194 = origin of the previous file listed as A (added)
5233 5195
5234 5196 .. container:: verbose
5235 5197
5236 5198 Examples:
5237 5199
5238 5200 - show changes in the working directory relative to a
5239 5201 changeset::
5240 5202
5241 5203 hg status --rev 9353
5242 5204
5243 5205 - show all changes including copies in an existing changeset::
5244 5206
5245 5207 hg status --copies --change 9353
5246 5208
5247 5209 - get a NUL separated list of added files, suitable for xargs::
5248 5210
5249 5211 hg status -an0
5250 5212
5251 5213 Returns 0 on success.
5252 5214 """
5253 5215
5254 5216 revs = opts.get('rev')
5255 5217 change = opts.get('change')
5256 5218
5257 5219 if revs and change:
5258 5220 msg = _('cannot specify --rev and --change at the same time')
5259 5221 raise util.Abort(msg)
5260 5222 elif change:
5261 5223 node2 = scmutil.revsingle(repo, change, None).node()
5262 5224 node1 = repo[node2].p1().node()
5263 5225 else:
5264 5226 node1, node2 = scmutil.revpair(repo, revs)
5265 5227
5266 5228 cwd = (pats and repo.getcwd()) or ''
5267 5229 end = opts.get('print0') and '\0' or '\n'
5268 5230 copy = {}
5269 5231 states = 'modified added removed deleted unknown ignored clean'.split()
5270 5232 show = [k for k in states if opts.get(k)]
5271 5233 if opts.get('all'):
5272 5234 show += ui.quiet and (states[:4] + ['clean']) or states
5273 5235 if not show:
5274 5236 show = ui.quiet and states[:4] or states[:5]
5275 5237
5276 5238 stat = repo.status(node1, node2, scmutil.match(repo[node2], pats, opts),
5277 5239 'ignored' in show, 'clean' in show, 'unknown' in show,
5278 5240 opts.get('subrepos'))
5279 5241 changestates = zip(states, 'MAR!?IC', stat)
5280 5242
5281 5243 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
5282 5244 copy = copies.pathcopies(repo[node1], repo[node2])
5283 5245
5284 5246 for state, char, files in changestates:
5285 5247 if state in show:
5286 5248 format = "%s %%s%s" % (char, end)
5287 5249 if opts.get('no_status'):
5288 5250 format = "%%s%s" % end
5289 5251
5290 5252 for f in files:
5291 5253 ui.write(format % repo.pathto(f, cwd),
5292 5254 label='status.' + state)
5293 5255 if f in copy:
5294 5256 ui.write(' %s%s' % (repo.pathto(copy[f], cwd), end),
5295 5257 label='status.copied')
5296 5258
5297 5259 @command('^summary|sum',
5298 5260 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
5299 5261 def summary(ui, repo, **opts):
5300 5262 """summarize working directory state
5301 5263
5302 5264 This generates a brief summary of the working directory state,
5303 5265 including parents, branch, commit status, and available updates.
5304 5266
5305 5267 With the --remote option, this will check the default paths for
5306 5268 incoming and outgoing changes. This can be time-consuming.
5307 5269
5308 5270 Returns 0 on success.
5309 5271 """
5310 5272
5311 5273 ctx = repo[None]
5312 5274 parents = ctx.parents()
5313 5275 pnode = parents[0].node()
5314 5276 marks = []
5315 5277
5316 5278 for p in parents:
5317 5279 # label with log.changeset (instead of log.parent) since this
5318 5280 # shows a working directory parent *changeset*:
5319 5281 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
5320 5282 label='log.changeset')
5321 5283 ui.write(' '.join(p.tags()), label='log.tag')
5322 5284 if p.bookmarks():
5323 5285 marks.extend(p.bookmarks())
5324 5286 if p.rev() == -1:
5325 5287 if not len(repo):
5326 5288 ui.write(_(' (empty repository)'))
5327 5289 else:
5328 5290 ui.write(_(' (no revision checked out)'))
5329 5291 ui.write('\n')
5330 5292 if p.description():
5331 5293 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5332 5294 label='log.summary')
5333 5295
5334 5296 branch = ctx.branch()
5335 5297 bheads = repo.branchheads(branch)
5336 5298 m = _('branch: %s\n') % branch
5337 5299 if branch != 'default':
5338 5300 ui.write(m, label='log.branch')
5339 5301 else:
5340 5302 ui.status(m, label='log.branch')
5341 5303
5342 5304 if marks:
5343 5305 current = repo._bookmarkcurrent
5344 5306 ui.write(_('bookmarks:'), label='log.bookmark')
5345 5307 if current is not None:
5346 5308 try:
5347 5309 marks.remove(current)
5348 5310 ui.write(' *' + current, label='bookmarks.current')
5349 5311 except ValueError:
5350 5312 # current bookmark not in parent ctx marks
5351 5313 pass
5352 5314 for m in marks:
5353 5315 ui.write(' ' + m, label='log.bookmark')
5354 5316 ui.write('\n', label='log.bookmark')
5355 5317
5356 5318 st = list(repo.status(unknown=True))[:6]
5357 5319
5358 5320 c = repo.dirstate.copies()
5359 5321 copied, renamed = [], []
5360 5322 for d, s in c.iteritems():
5361 5323 if s in st[2]:
5362 5324 st[2].remove(s)
5363 5325 renamed.append(d)
5364 5326 else:
5365 5327 copied.append(d)
5366 5328 if d in st[1]:
5367 5329 st[1].remove(d)
5368 5330 st.insert(3, renamed)
5369 5331 st.insert(4, copied)
5370 5332
5371 5333 ms = mergemod.mergestate(repo)
5372 5334 st.append([f for f in ms if ms[f] == 'u'])
5373 5335
5374 5336 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5375 5337 st.append(subs)
5376 5338
5377 5339 labels = [ui.label(_('%d modified'), 'status.modified'),
5378 5340 ui.label(_('%d added'), 'status.added'),
5379 5341 ui.label(_('%d removed'), 'status.removed'),
5380 5342 ui.label(_('%d renamed'), 'status.copied'),
5381 5343 ui.label(_('%d copied'), 'status.copied'),
5382 5344 ui.label(_('%d deleted'), 'status.deleted'),
5383 5345 ui.label(_('%d unknown'), 'status.unknown'),
5384 5346 ui.label(_('%d ignored'), 'status.ignored'),
5385 5347 ui.label(_('%d unresolved'), 'resolve.unresolved'),
5386 5348 ui.label(_('%d subrepos'), 'status.modified')]
5387 5349 t = []
5388 5350 for s, l in zip(st, labels):
5389 5351 if s:
5390 5352 t.append(l % len(s))
5391 5353
5392 5354 t = ', '.join(t)
5393 5355 cleanworkdir = False
5394 5356
5395 5357 if len(parents) > 1:
5396 5358 t += _(' (merge)')
5397 5359 elif branch != parents[0].branch():
5398 5360 t += _(' (new branch)')
5399 5361 elif (parents[0].extra().get('close') and
5400 5362 pnode in repo.branchheads(branch, closed=True)):
5401 5363 t += _(' (head closed)')
5402 5364 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
5403 5365 t += _(' (clean)')
5404 5366 cleanworkdir = True
5405 5367 elif pnode not in bheads:
5406 5368 t += _(' (new branch head)')
5407 5369
5408 5370 if cleanworkdir:
5409 5371 ui.status(_('commit: %s\n') % t.strip())
5410 5372 else:
5411 5373 ui.write(_('commit: %s\n') % t.strip())
5412 5374
5413 5375 # all ancestors of branch heads - all ancestors of parent = new csets
5414 5376 new = [0] * len(repo)
5415 5377 cl = repo.changelog
5416 5378 for a in [cl.rev(n) for n in bheads]:
5417 5379 new[a] = 1
5418 5380 for a in cl.ancestors(*[cl.rev(n) for n in bheads]):
5419 5381 new[a] = 1
5420 5382 for a in [p.rev() for p in parents]:
5421 5383 if a >= 0:
5422 5384 new[a] = 0
5423 5385 for a in cl.ancestors(*[p.rev() for p in parents]):
5424 5386 new[a] = 0
5425 5387 new = sum(new)
5426 5388
5427 5389 if new == 0:
5428 5390 ui.status(_('update: (current)\n'))
5429 5391 elif pnode not in bheads:
5430 5392 ui.write(_('update: %d new changesets (update)\n') % new)
5431 5393 else:
5432 5394 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5433 5395 (new, len(bheads)))
5434 5396
5435 5397 if opts.get('remote'):
5436 5398 t = []
5437 5399 source, branches = hg.parseurl(ui.expandpath('default'))
5438 5400 other = hg.peer(repo, {}, source)
5439 5401 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
5440 5402 ui.debug('comparing with %s\n' % util.hidepassword(source))
5441 5403 repo.ui.pushbuffer()
5442 5404 commoninc = discovery.findcommonincoming(repo, other)
5443 5405 _common, incoming, _rheads = commoninc
5444 5406 repo.ui.popbuffer()
5445 5407 if incoming:
5446 5408 t.append(_('1 or more incoming'))
5447 5409
5448 5410 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5449 5411 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5450 5412 if source != dest:
5451 5413 other = hg.peer(repo, {}, dest)
5452 5414 commoninc = None
5453 5415 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5454 5416 repo.ui.pushbuffer()
5455 5417 outgoing = discovery.findcommonoutgoing(repo, other,
5456 5418 commoninc=commoninc)
5457 5419 repo.ui.popbuffer()
5458 5420 o = outgoing.missing
5459 5421 if o:
5460 5422 t.append(_('%d outgoing') % len(o))
5461 5423 if 'bookmarks' in other.listkeys('namespaces'):
5462 5424 lmarks = repo.listkeys('bookmarks')
5463 5425 rmarks = other.listkeys('bookmarks')
5464 5426 diff = set(rmarks) - set(lmarks)
5465 5427 if len(diff) > 0:
5466 5428 t.append(_('%d incoming bookmarks') % len(diff))
5467 5429 diff = set(lmarks) - set(rmarks)
5468 5430 if len(diff) > 0:
5469 5431 t.append(_('%d outgoing bookmarks') % len(diff))
5470 5432
5471 5433 if t:
5472 5434 ui.write(_('remote: %s\n') % (', '.join(t)))
5473 5435 else:
5474 5436 ui.status(_('remote: (synced)\n'))
5475 5437
5476 5438 @command('tag',
5477 5439 [('f', 'force', None, _('force tag')),
5478 5440 ('l', 'local', None, _('make the tag local')),
5479 5441 ('r', 'rev', '', _('revision to tag'), _('REV')),
5480 5442 ('', 'remove', None, _('remove a tag')),
5481 5443 # -l/--local is already there, commitopts cannot be used
5482 5444 ('e', 'edit', None, _('edit commit message')),
5483 5445 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
5484 5446 ] + commitopts2,
5485 5447 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5486 5448 def tag(ui, repo, name1, *names, **opts):
5487 5449 """add one or more tags for the current or given revision
5488 5450
5489 5451 Name a particular revision using <name>.
5490 5452
5491 5453 Tags are used to name particular revisions of the repository and are
5492 5454 very useful to compare different revisions, to go back to significant
5493 5455 earlier versions or to mark branch points as releases, etc. Changing
5494 5456 an existing tag is normally disallowed; use -f/--force to override.
5495 5457
5496 5458 If no revision is given, the parent of the working directory is
5497 5459 used, or tip if no revision is checked out.
5498 5460
5499 5461 To facilitate version control, distribution, and merging of tags,
5500 5462 they are stored as a file named ".hgtags" which is managed similarly
5501 5463 to other project files and can be hand-edited if necessary. This
5502 5464 also means that tagging creates a new commit. The file
5503 5465 ".hg/localtags" is used for local tags (not shared among
5504 5466 repositories).
5505 5467
5506 5468 Tag commits are usually made at the head of a branch. If the parent
5507 5469 of the working directory is not a branch head, :hg:`tag` aborts; use
5508 5470 -f/--force to force the tag commit to be based on a non-head
5509 5471 changeset.
5510 5472
5511 5473 See :hg:`help dates` for a list of formats valid for -d/--date.
5512 5474
5513 5475 Since tag names have priority over branch names during revision
5514 5476 lookup, using an existing branch name as a tag name is discouraged.
5515 5477
5516 5478 Returns 0 on success.
5517 5479 """
5518 5480 wlock = lock = None
5519 5481 try:
5520 5482 wlock = repo.wlock()
5521 5483 lock = repo.lock()
5522 5484 rev_ = "."
5523 5485 names = [t.strip() for t in (name1,) + names]
5524 5486 if len(names) != len(set(names)):
5525 5487 raise util.Abort(_('tag names must be unique'))
5526 5488 for n in names:
5527 5489 if n in ['tip', '.', 'null']:
5528 5490 raise util.Abort(_("the name '%s' is reserved") % n)
5529 5491 if not n:
5530 5492 raise util.Abort(_('tag names cannot consist entirely of '
5531 5493 'whitespace'))
5532 5494 if opts.get('rev') and opts.get('remove'):
5533 5495 raise util.Abort(_("--rev and --remove are incompatible"))
5534 5496 if opts.get('rev'):
5535 5497 rev_ = opts['rev']
5536 5498 message = opts.get('message')
5537 5499 if opts.get('remove'):
5538 5500 expectedtype = opts.get('local') and 'local' or 'global'
5539 5501 for n in names:
5540 5502 if not repo.tagtype(n):
5541 5503 raise util.Abort(_("tag '%s' does not exist") % n)
5542 5504 if repo.tagtype(n) != expectedtype:
5543 5505 if expectedtype == 'global':
5544 5506 raise util.Abort(_("tag '%s' is not a global tag") % n)
5545 5507 else:
5546 5508 raise util.Abort(_("tag '%s' is not a local tag") % n)
5547 5509 rev_ = nullid
5548 5510 if not message:
5549 5511 # we don't translate commit messages
5550 5512 message = 'Removed tag %s' % ', '.join(names)
5551 5513 elif not opts.get('force'):
5552 5514 for n in names:
5553 5515 if n in repo.tags():
5554 5516 raise util.Abort(_("tag '%s' already exists "
5555 5517 "(use -f to force)") % n)
5556 5518 if not opts.get('local'):
5557 5519 p1, p2 = repo.dirstate.parents()
5558 5520 if p2 != nullid:
5559 5521 raise util.Abort(_('uncommitted merge'))
5560 5522 bheads = repo.branchheads()
5561 5523 if not opts.get('force') and bheads and p1 not in bheads:
5562 5524 raise util.Abort(_('not at a branch head (use -f to force)'))
5563 5525 r = scmutil.revsingle(repo, rev_).node()
5564 5526
5565 5527 if not message:
5566 5528 # we don't translate commit messages
5567 5529 message = ('Added tag %s for changeset %s' %
5568 5530 (', '.join(names), short(r)))
5569 5531
5570 5532 date = opts.get('date')
5571 5533 if date:
5572 5534 date = util.parsedate(date)
5573 5535
5574 5536 if opts.get('edit'):
5575 5537 message = ui.edit(message, ui.username())
5576 5538
5577 5539 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
5578 5540 finally:
5579 5541 release(lock, wlock)
5580 5542
5581 5543 @command('tags', [], '')
5582 5544 def tags(ui, repo):
5583 5545 """list repository tags
5584 5546
5585 5547 This lists both regular and local tags. When the -v/--verbose
5586 5548 switch is used, a third column "local" is printed for local tags.
5587 5549
5588 5550 Returns 0 on success.
5589 5551 """
5590 5552
5591 5553 hexfunc = ui.debugflag and hex or short
5592 5554 tagtype = ""
5593 5555
5594 5556 for t, n in reversed(repo.tagslist()):
5595 5557 if ui.quiet:
5596 5558 ui.write("%s\n" % t, label='tags.normal')
5597 5559 continue
5598 5560
5599 5561 hn = hexfunc(n)
5600 5562 r = "%5d:%s" % (repo.changelog.rev(n), hn)
5601 5563 rev = ui.label(r, 'log.changeset')
5602 5564 spaces = " " * (30 - encoding.colwidth(t))
5603 5565
5604 5566 tag = ui.label(t, 'tags.normal')
5605 5567 if ui.verbose:
5606 5568 if repo.tagtype(t) == 'local':
5607 5569 tagtype = " local"
5608 5570 tag = ui.label(t, 'tags.local')
5609 5571 else:
5610 5572 tagtype = ""
5611 5573 ui.write("%s%s %s%s\n" % (tag, spaces, rev, tagtype))
5612 5574
5613 5575 @command('tip',
5614 5576 [('p', 'patch', None, _('show patch')),
5615 5577 ('g', 'git', None, _('use git extended diff format')),
5616 5578 ] + templateopts,
5617 5579 _('[-p] [-g]'))
5618 5580 def tip(ui, repo, **opts):
5619 5581 """show the tip revision
5620 5582
5621 5583 The tip revision (usually just called the tip) is the changeset
5622 5584 most recently added to the repository (and therefore the most
5623 5585 recently changed head).
5624 5586
5625 5587 If you have just made a commit, that commit will be the tip. If
5626 5588 you have just pulled changes from another repository, the tip of
5627 5589 that repository becomes the current tip. The "tip" tag is special
5628 5590 and cannot be renamed or assigned to a different changeset.
5629 5591
5630 5592 Returns 0 on success.
5631 5593 """
5632 5594 displayer = cmdutil.show_changeset(ui, repo, opts)
5633 5595 displayer.show(repo[len(repo) - 1])
5634 5596 displayer.close()
5635 5597
5636 5598 @command('unbundle',
5637 5599 [('u', 'update', None,
5638 5600 _('update to new branch head if changesets were unbundled'))],
5639 5601 _('[-u] FILE...'))
5640 5602 def unbundle(ui, repo, fname1, *fnames, **opts):
5641 5603 """apply one or more changegroup files
5642 5604
5643 5605 Apply one or more compressed changegroup files generated by the
5644 5606 bundle command.
5645 5607
5646 5608 Returns 0 on success, 1 if an update has unresolved files.
5647 5609 """
5648 5610 fnames = (fname1,) + fnames
5649 5611
5650 5612 lock = repo.lock()
5651 5613 wc = repo['.']
5652 5614 try:
5653 5615 for fname in fnames:
5654 5616 f = url.open(ui, fname)
5655 5617 gen = changegroup.readbundle(f, fname)
5656 5618 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname)
5657 5619 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
5658 5620 finally:
5659 5621 lock.release()
5660 5622 return postincoming(ui, repo, modheads, opts.get('update'), None)
5661 5623
5662 5624 @command('^update|up|checkout|co',
5663 5625 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5664 5626 ('c', 'check', None,
5665 5627 _('update across branches if no uncommitted changes')),
5666 5628 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5667 5629 ('r', 'rev', '', _('revision'), _('REV'))],
5668 5630 _('[-c] [-C] [-d DATE] [[-r] REV]'))
5669 5631 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
5670 5632 """update working directory (or switch revisions)
5671 5633
5672 5634 Update the repository's working directory to the specified
5673 5635 changeset. If no changeset is specified, update to the tip of the
5674 5636 current named branch.
5675 5637
5676 5638 If the changeset is not a descendant of the working directory's
5677 5639 parent, the update is aborted. With the -c/--check option, the
5678 5640 working directory is checked for uncommitted changes; if none are
5679 5641 found, the working directory is updated to the specified
5680 5642 changeset.
5681 5643
5682 5644 Update sets the working directory's parent revison to the specified
5683 5645 changeset (see :hg:`help parents`).
5684 5646
5685 5647 The following rules apply when the working directory contains
5686 5648 uncommitted changes:
5687 5649
5688 5650 1. If neither -c/--check nor -C/--clean is specified, and if
5689 5651 the requested changeset is an ancestor or descendant of
5690 5652 the working directory's parent, the uncommitted changes
5691 5653 are merged into the requested changeset and the merged
5692 5654 result is left uncommitted. If the requested changeset is
5693 5655 not an ancestor or descendant (that is, it is on another
5694 5656 branch), the update is aborted and the uncommitted changes
5695 5657 are preserved.
5696 5658
5697 5659 2. With the -c/--check option, the update is aborted and the
5698 5660 uncommitted changes are preserved.
5699 5661
5700 5662 3. With the -C/--clean option, uncommitted changes are discarded and
5701 5663 the working directory is updated to the requested changeset.
5702 5664
5703 5665 Use null as the changeset to remove the working directory (like
5704 5666 :hg:`clone -U`).
5705 5667
5706 5668 If you want to revert just one file to an older revision, use
5707 5669 :hg:`revert [-r REV] NAME`.
5708 5670
5709 5671 See :hg:`help dates` for a list of formats valid for -d/--date.
5710 5672
5711 5673 Returns 0 on success, 1 if there are unresolved files.
5712 5674 """
5713 5675 if rev and node:
5714 5676 raise util.Abort(_("please specify just one revision"))
5715 5677
5716 5678 if rev is None or rev == '':
5717 5679 rev = node
5718 5680
5719 5681 # if we defined a bookmark, we have to remember the original bookmark name
5720 5682 brev = rev
5721 5683 rev = scmutil.revsingle(repo, rev, rev).rev()
5722 5684
5723 5685 if check and clean:
5724 5686 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5725 5687
5726 5688 if check:
5727 5689 # we could use dirty() but we can ignore merge and branch trivia
5728 5690 c = repo[None]
5729 5691 if c.modified() or c.added() or c.removed():
5730 5692 raise util.Abort(_("uncommitted local changes"))
5731 5693
5732 5694 if date:
5733 5695 if rev is not None:
5734 5696 raise util.Abort(_("you can't specify a revision and a date"))
5735 5697 rev = cmdutil.finddate(ui, repo, date)
5736 5698
5737 5699 if clean or check:
5738 5700 ret = hg.clean(repo, rev)
5739 5701 else:
5740 5702 ret = hg.update(repo, rev)
5741 5703
5742 5704 if brev in repo._bookmarks:
5743 5705 bookmarks.setcurrent(repo, brev)
5744 5706
5745 5707 return ret
5746 5708
5747 5709 @command('verify', [])
5748 5710 def verify(ui, repo):
5749 5711 """verify the integrity of the repository
5750 5712
5751 5713 Verify the integrity of the current repository.
5752 5714
5753 5715 This will perform an extensive check of the repository's
5754 5716 integrity, validating the hashes and checksums of each entry in
5755 5717 the changelog, manifest, and tracked files, as well as the
5756 5718 integrity of their crosslinks and indices.
5757 5719
5758 5720 Returns 0 on success, 1 if errors are encountered.
5759 5721 """
5760 5722 return hg.verify(repo)
5761 5723
5762 5724 @command('version', [])
5763 5725 def version_(ui):
5764 5726 """output version and copyright information"""
5765 5727 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5766 5728 % util.version())
5767 5729 ui.status(_(
5768 5730 "(see http://mercurial.selenic.com for more information)\n"
5769 5731 "\nCopyright (C) 2005-2012 Matt Mackall and others\n"
5770 5732 "This is free software; see the source for copying conditions. "
5771 5733 "There is NO\nwarranty; "
5772 5734 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5773 5735 ))
5774 5736
5775 5737 norepo = ("clone init version help debugcommands debugcomplete"
5776 5738 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5777 5739 " debugknown debuggetbundle debugbundle")
5778 5740 optionalrepo = ("identify paths serve showconfig debugancestor debugdag"
5779 5741 " debugdata debugindex debugindexdot debugrevlog")
@@ -1,1172 +1,1176 b''
1 1 # context.py - changeset and file context objects for mercurial
2 2 #
3 3 # Copyright 2006, 2007 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 from node import nullid, nullrev, short, hex
9 9 from i18n import _
10 10 import ancestor, mdiff, error, util, scmutil, subrepo, patch, encoding, phases
11 11 import match as matchmod
12 12 import os, errno, stat
13 13
14 14 propertycache = util.propertycache
15 15
16 16 class changectx(object):
17 17 """A changecontext object makes access to data related to a particular
18 18 changeset convenient."""
19 19 def __init__(self, repo, changeid=''):
20 20 """changeid is a revision number, node, or tag"""
21 21 if changeid == '':
22 22 changeid = '.'
23 23 self._repo = repo
24 24 if isinstance(changeid, (long, int)):
25 25 self._rev = changeid
26 26 self._node = self._repo.changelog.node(changeid)
27 27 else:
28 28 self._node = self._repo.lookup(changeid)
29 29 self._rev = self._repo.changelog.rev(self._node)
30 30
31 31 def __str__(self):
32 32 return short(self.node())
33 33
34 34 def __int__(self):
35 35 return self.rev()
36 36
37 37 def __repr__(self):
38 38 return "<changectx %s>" % str(self)
39 39
40 40 def __hash__(self):
41 41 try:
42 42 return hash(self._rev)
43 43 except AttributeError:
44 44 return id(self)
45 45
46 46 def __eq__(self, other):
47 47 try:
48 48 return self._rev == other._rev
49 49 except AttributeError:
50 50 return False
51 51
52 52 def __ne__(self, other):
53 53 return not (self == other)
54 54
55 55 def __nonzero__(self):
56 56 return self._rev != nullrev
57 57
58 58 @propertycache
59 59 def _changeset(self):
60 60 return self._repo.changelog.read(self.node())
61 61
62 62 @propertycache
63 63 def _manifest(self):
64 64 return self._repo.manifest.read(self._changeset[0])
65 65
66 66 @propertycache
67 67 def _manifestdelta(self):
68 68 return self._repo.manifest.readdelta(self._changeset[0])
69 69
70 70 @propertycache
71 71 def _parents(self):
72 72 p = self._repo.changelog.parentrevs(self._rev)
73 73 if p[1] == nullrev:
74 74 p = p[:-1]
75 75 return [changectx(self._repo, x) for x in p]
76 76
77 77 @propertycache
78 78 def substate(self):
79 79 return subrepo.state(self, self._repo.ui)
80 80
81 81 def __contains__(self, key):
82 82 return key in self._manifest
83 83
84 84 def __getitem__(self, key):
85 85 return self.filectx(key)
86 86
87 87 def __iter__(self):
88 88 for f in sorted(self._manifest):
89 89 yield f
90 90
91 91 def changeset(self):
92 92 return self._changeset
93 93 def manifest(self):
94 94 return self._manifest
95 95 def manifestnode(self):
96 96 return self._changeset[0]
97 97
98 98 def rev(self):
99 99 return self._rev
100 100 def node(self):
101 101 return self._node
102 102 def hex(self):
103 103 return hex(self._node)
104 104 def user(self):
105 105 return self._changeset[1]
106 106 def date(self):
107 107 return self._changeset[2]
108 108 def files(self):
109 109 return self._changeset[3]
110 110 def description(self):
111 111 return self._changeset[4]
112 112 def branch(self):
113 113 return encoding.tolocal(self._changeset[5].get("branch"))
114 114 def extra(self):
115 115 return self._changeset[5]
116 116 def tags(self):
117 117 return self._repo.nodetags(self._node)
118 118 def bookmarks(self):
119 119 return self._repo.nodebookmarks(self._node)
120 120 def phase(self):
121 121 if self._rev == -1:
122 122 return phases.public
123 123 if self._rev >= len(self._repo._phaserev):
124 124 # outdated cache
125 125 del self._repo._phaserev
126 126 return self._repo._phaserev[self._rev]
127 127 def phasestr(self):
128 128 return phases.phasenames[self.phase()]
129 129 def mutable(self):
130 130 return self._repo._phaserev[self._rev] > phases.public
131 131 def hidden(self):
132 132 return self._rev in self._repo.changelog.hiddenrevs
133 133
134 134 def parents(self):
135 135 """return contexts for each parent changeset"""
136 136 return self._parents
137 137
138 138 def p1(self):
139 139 return self._parents[0]
140 140
141 141 def p2(self):
142 142 if len(self._parents) == 2:
143 143 return self._parents[1]
144 144 return changectx(self._repo, -1)
145 145
146 146 def children(self):
147 147 """return contexts for each child changeset"""
148 148 c = self._repo.changelog.children(self._node)
149 149 return [changectx(self._repo, x) for x in c]
150 150
151 151 def ancestors(self):
152 152 for a in self._repo.changelog.ancestors(self._rev):
153 153 yield changectx(self._repo, a)
154 154
155 155 def descendants(self):
156 156 for d in self._repo.changelog.descendants(self._rev):
157 157 yield changectx(self._repo, d)
158 158
159 159 def _fileinfo(self, path):
160 160 if '_manifest' in self.__dict__:
161 161 try:
162 162 return self._manifest[path], self._manifest.flags(path)
163 163 except KeyError:
164 164 raise error.LookupError(self._node, path,
165 165 _('not found in manifest'))
166 166 if '_manifestdelta' in self.__dict__ or path in self.files():
167 167 if path in self._manifestdelta:
168 168 return self._manifestdelta[path], self._manifestdelta.flags(path)
169 169 node, flag = self._repo.manifest.find(self._changeset[0], path)
170 170 if not node:
171 171 raise error.LookupError(self._node, path,
172 172 _('not found in manifest'))
173 173
174 174 return node, flag
175 175
176 176 def filenode(self, path):
177 177 return self._fileinfo(path)[0]
178 178
179 179 def flags(self, path):
180 180 try:
181 181 return self._fileinfo(path)[1]
182 182 except error.LookupError:
183 183 return ''
184 184
185 185 def filectx(self, path, fileid=None, filelog=None):
186 186 """get a file context from this changeset"""
187 187 if fileid is None:
188 188 fileid = self.filenode(path)
189 189 return filectx(self._repo, path, fileid=fileid,
190 190 changectx=self, filelog=filelog)
191 191
192 192 def ancestor(self, c2):
193 193 """
194 194 return the ancestor context of self and c2
195 195 """
196 196 # deal with workingctxs
197 197 n2 = c2._node
198 198 if n2 is None:
199 199 n2 = c2._parents[0]._node
200 200 n = self._repo.changelog.ancestor(self._node, n2)
201 201 return changectx(self._repo, n)
202 202
203 203 def walk(self, match):
204 204 fset = set(match.files())
205 205 # for dirstate.walk, files=['.'] means "walk the whole tree".
206 206 # follow that here, too
207 207 fset.discard('.')
208 208 for fn in self:
209 209 for ffn in fset:
210 210 # match if the file is the exact name or a directory
211 211 if ffn == fn or fn.startswith("%s/" % ffn):
212 212 fset.remove(ffn)
213 213 break
214 214 if match(fn):
215 215 yield fn
216 216 for fn in sorted(fset):
217 217 if match.bad(fn, _('no such file in rev %s') % self) and match(fn):
218 218 yield fn
219 219
220 220 def sub(self, path):
221 221 return subrepo.subrepo(self, path)
222 222
223 223 def match(self, pats=[], include=None, exclude=None, default='glob'):
224 224 r = self._repo
225 225 return matchmod.match(r.root, r.getcwd(), pats,
226 226 include, exclude, default,
227 227 auditor=r.auditor, ctx=self)
228 228
229 229 def diff(self, ctx2=None, match=None, **opts):
230 230 """Returns a diff generator for the given contexts and matcher"""
231 231 if ctx2 is None:
232 232 ctx2 = self.p1()
233 233 if ctx2 is not None and not isinstance(ctx2, changectx):
234 234 ctx2 = self._repo[ctx2]
235 235 diffopts = patch.diffopts(self._repo.ui, opts)
236 236 return patch.diff(self._repo, ctx2.node(), self.node(),
237 237 match=match, opts=diffopts)
238 238
239 239 class filectx(object):
240 240 """A filecontext object makes access to data related to a particular
241 241 filerevision convenient."""
242 242 def __init__(self, repo, path, changeid=None, fileid=None,
243 243 filelog=None, changectx=None):
244 244 """changeid can be a changeset revision, node, or tag.
245 245 fileid can be a file revision or node."""
246 246 self._repo = repo
247 247 self._path = path
248 248
249 249 assert (changeid is not None
250 250 or fileid is not None
251 251 or changectx is not None), \
252 252 ("bad args: changeid=%r, fileid=%r, changectx=%r"
253 253 % (changeid, fileid, changectx))
254 254
255 255 if filelog:
256 256 self._filelog = filelog
257 257
258 258 if changeid is not None:
259 259 self._changeid = changeid
260 260 if changectx is not None:
261 261 self._changectx = changectx
262 262 if fileid is not None:
263 263 self._fileid = fileid
264 264
265 265 @propertycache
266 266 def _changectx(self):
267 267 return changectx(self._repo, self._changeid)
268 268
269 269 @propertycache
270 270 def _filelog(self):
271 271 return self._repo.file(self._path)
272 272
273 273 @propertycache
274 274 def _changeid(self):
275 275 if '_changectx' in self.__dict__:
276 276 return self._changectx.rev()
277 277 else:
278 278 return self._filelog.linkrev(self._filerev)
279 279
280 280 @propertycache
281 281 def _filenode(self):
282 282 if '_fileid' in self.__dict__:
283 283 return self._filelog.lookup(self._fileid)
284 284 else:
285 285 return self._changectx.filenode(self._path)
286 286
287 287 @propertycache
288 288 def _filerev(self):
289 289 return self._filelog.rev(self._filenode)
290 290
291 291 @propertycache
292 292 def _repopath(self):
293 293 return self._path
294 294
295 295 def __nonzero__(self):
296 296 try:
297 297 self._filenode
298 298 return True
299 299 except error.LookupError:
300 300 # file is missing
301 301 return False
302 302
303 303 def __str__(self):
304 304 return "%s@%s" % (self.path(), short(self.node()))
305 305
306 306 def __repr__(self):
307 307 return "<filectx %s>" % str(self)
308 308
309 309 def __hash__(self):
310 310 try:
311 311 return hash((self._path, self._filenode))
312 312 except AttributeError:
313 313 return id(self)
314 314
315 315 def __eq__(self, other):
316 316 try:
317 317 return (self._path == other._path
318 318 and self._filenode == other._filenode)
319 319 except AttributeError:
320 320 return False
321 321
322 322 def __ne__(self, other):
323 323 return not (self == other)
324 324
325 325 def filectx(self, fileid):
326 326 '''opens an arbitrary revision of the file without
327 327 opening a new filelog'''
328 328 return filectx(self._repo, self._path, fileid=fileid,
329 329 filelog=self._filelog)
330 330
331 331 def filerev(self):
332 332 return self._filerev
333 333 def filenode(self):
334 334 return self._filenode
335 335 def flags(self):
336 336 return self._changectx.flags(self._path)
337 337 def filelog(self):
338 338 return self._filelog
339 339
340 340 def rev(self):
341 341 if '_changectx' in self.__dict__:
342 342 return self._changectx.rev()
343 343 if '_changeid' in self.__dict__:
344 344 return self._changectx.rev()
345 345 return self._filelog.linkrev(self._filerev)
346 346
347 347 def linkrev(self):
348 348 return self._filelog.linkrev(self._filerev)
349 349 def node(self):
350 350 return self._changectx.node()
351 351 def hex(self):
352 352 return hex(self.node())
353 353 def user(self):
354 354 return self._changectx.user()
355 355 def date(self):
356 356 return self._changectx.date()
357 357 def files(self):
358 358 return self._changectx.files()
359 359 def description(self):
360 360 return self._changectx.description()
361 361 def branch(self):
362 362 return self._changectx.branch()
363 363 def extra(self):
364 364 return self._changectx.extra()
365 365 def manifest(self):
366 366 return self._changectx.manifest()
367 367 def changectx(self):
368 368 return self._changectx
369 369
370 370 def data(self):
371 371 return self._filelog.read(self._filenode)
372 372 def path(self):
373 373 return self._path
374 374 def size(self):
375 375 return self._filelog.size(self._filerev)
376 376
377 377 def isbinary(self):
378 378 try:
379 379 return util.binary(self.data())
380 380 except IOError:
381 381 return False
382 382
383 383 def cmp(self, fctx):
384 384 """compare with other file context
385 385
386 386 returns True if different than fctx.
387 387 """
388 388 if (fctx._filerev is None
389 389 and (self._repo._encodefilterpats
390 390 # if file data starts with '\1\n', empty metadata block is
391 391 # prepended, which adds 4 bytes to filelog.size().
392 392 or self.size() - 4 == fctx.size())
393 393 or self.size() == fctx.size()):
394 394 return self._filelog.cmp(self._filenode, fctx.data())
395 395
396 396 return True
397 397
398 398 def renamed(self):
399 399 """check if file was actually renamed in this changeset revision
400 400
401 401 If rename logged in file revision, we report copy for changeset only
402 402 if file revisions linkrev points back to the changeset in question
403 403 or both changeset parents contain different file revisions.
404 404 """
405 405
406 406 renamed = self._filelog.renamed(self._filenode)
407 407 if not renamed:
408 408 return renamed
409 409
410 410 if self.rev() == self.linkrev():
411 411 return renamed
412 412
413 413 name = self.path()
414 414 fnode = self._filenode
415 415 for p in self._changectx.parents():
416 416 try:
417 417 if fnode == p.filenode(name):
418 418 return None
419 419 except error.LookupError:
420 420 pass
421 421 return renamed
422 422
423 423 def parents(self):
424 424 p = self._path
425 425 fl = self._filelog
426 426 pl = [(p, n, fl) for n in self._filelog.parents(self._filenode)]
427 427
428 428 r = self._filelog.renamed(self._filenode)
429 429 if r:
430 430 pl[0] = (r[0], r[1], None)
431 431
432 432 return [filectx(self._repo, p, fileid=n, filelog=l)
433 433 for p, n, l in pl if n != nullid]
434 434
435 435 def p1(self):
436 436 return self.parents()[0]
437 437
438 438 def p2(self):
439 439 p = self.parents()
440 440 if len(p) == 2:
441 441 return p[1]
442 442 return filectx(self._repo, self._path, fileid=-1, filelog=self._filelog)
443 443
444 444 def children(self):
445 445 # hard for renames
446 446 c = self._filelog.children(self._filenode)
447 447 return [filectx(self._repo, self._path, fileid=x,
448 448 filelog=self._filelog) for x in c]
449 449
450 450 def annotate(self, follow=False, linenumber=None, diffopts=None):
451 451 '''returns a list of tuples of (ctx, line) for each line
452 452 in the file, where ctx is the filectx of the node where
453 453 that line was last changed.
454 454 This returns tuples of ((ctx, linenumber), line) for each line,
455 455 if "linenumber" parameter is NOT "None".
456 456 In such tuples, linenumber means one at the first appearance
457 457 in the managed file.
458 458 To reduce annotation cost,
459 459 this returns fixed value(False is used) as linenumber,
460 460 if "linenumber" parameter is "False".'''
461 461
462 462 def decorate_compat(text, rev):
463 463 return ([rev] * len(text.splitlines()), text)
464 464
465 465 def without_linenumber(text, rev):
466 466 return ([(rev, False)] * len(text.splitlines()), text)
467 467
468 468 def with_linenumber(text, rev):
469 469 size = len(text.splitlines())
470 470 return ([(rev, i) for i in xrange(1, size + 1)], text)
471 471
472 472 decorate = (((linenumber is None) and decorate_compat) or
473 473 (linenumber and with_linenumber) or
474 474 without_linenumber)
475 475
476 476 def pair(parent, child):
477 477 blocks = mdiff.allblocks(parent[1], child[1], opts=diffopts,
478 478 refine=True)
479 479 for (a1, a2, b1, b2), t in blocks:
480 480 # Changed blocks ('!') or blocks made only of blank lines ('~')
481 481 # belong to the child.
482 482 if t == '=':
483 483 child[0][b1:b2] = parent[0][a1:a2]
484 484 return child
485 485
486 486 getlog = util.lrucachefunc(lambda x: self._repo.file(x))
487 487 def getctx(path, fileid):
488 488 log = path == self._path and self._filelog or getlog(path)
489 489 return filectx(self._repo, path, fileid=fileid, filelog=log)
490 490 getctx = util.lrucachefunc(getctx)
491 491
492 492 def parents(f):
493 493 # we want to reuse filectx objects as much as possible
494 494 p = f._path
495 495 if f._filerev is None: # working dir
496 496 pl = [(n.path(), n.filerev()) for n in f.parents()]
497 497 else:
498 498 pl = [(p, n) for n in f._filelog.parentrevs(f._filerev)]
499 499
500 500 if follow:
501 501 r = f.renamed()
502 502 if r:
503 503 pl[0] = (r[0], getlog(r[0]).rev(r[1]))
504 504
505 505 return [getctx(p, n) for p, n in pl if n != nullrev]
506 506
507 507 # use linkrev to find the first changeset where self appeared
508 508 if self.rev() != self.linkrev():
509 509 base = self.filectx(self.filerev())
510 510 else:
511 511 base = self
512 512
513 513 # This algorithm would prefer to be recursive, but Python is a
514 514 # bit recursion-hostile. Instead we do an iterative
515 515 # depth-first search.
516 516
517 517 visit = [base]
518 518 hist = {}
519 519 pcache = {}
520 520 needed = {base: 1}
521 521 while visit:
522 522 f = visit[-1]
523 523 if f not in pcache:
524 524 pcache[f] = parents(f)
525 525
526 526 ready = True
527 527 pl = pcache[f]
528 528 for p in pl:
529 529 if p not in hist:
530 530 ready = False
531 531 visit.append(p)
532 532 needed[p] = needed.get(p, 0) + 1
533 533 if ready:
534 534 visit.pop()
535 535 curr = decorate(f.data(), f)
536 536 for p in pl:
537 537 curr = pair(hist[p], curr)
538 538 if needed[p] == 1:
539 539 del hist[p]
540 540 else:
541 541 needed[p] -= 1
542 542
543 543 hist[f] = curr
544 544 pcache[f] = []
545 545
546 546 return zip(hist[base][0], hist[base][1].splitlines(True))
547 547
548 548 def ancestor(self, fc2, actx=None):
549 549 """
550 550 find the common ancestor file context, if any, of self, and fc2
551 551
552 552 If actx is given, it must be the changectx of the common ancestor
553 553 of self's and fc2's respective changesets.
554 554 """
555 555
556 556 if actx is None:
557 557 actx = self.changectx().ancestor(fc2.changectx())
558 558
559 559 # the trivial case: changesets are unrelated, files must be too
560 560 if not actx:
561 561 return None
562 562
563 563 # the easy case: no (relevant) renames
564 564 if fc2.path() == self.path() and self.path() in actx:
565 565 return actx[self.path()]
566 566 acache = {}
567 567
568 568 # prime the ancestor cache for the working directory
569 569 for c in (self, fc2):
570 570 if c._filerev is None:
571 571 pl = [(n.path(), n.filenode()) for n in c.parents()]
572 572 acache[(c._path, None)] = pl
573 573
574 574 flcache = {self._repopath:self._filelog, fc2._repopath:fc2._filelog}
575 575 def parents(vertex):
576 576 if vertex in acache:
577 577 return acache[vertex]
578 578 f, n = vertex
579 579 if f not in flcache:
580 580 flcache[f] = self._repo.file(f)
581 581 fl = flcache[f]
582 582 pl = [(f, p) for p in fl.parents(n) if p != nullid]
583 583 re = fl.renamed(n)
584 584 if re:
585 585 pl.append(re)
586 586 acache[vertex] = pl
587 587 return pl
588 588
589 589 a, b = (self._path, self._filenode), (fc2._path, fc2._filenode)
590 590 v = ancestor.ancestor(a, b, parents)
591 591 if v:
592 592 f, n = v
593 593 return filectx(self._repo, f, fileid=n, filelog=flcache[f])
594 594
595 595 return None
596 596
597 597 def ancestors(self):
598 598 visit = {}
599 599 c = self
600 600 while True:
601 601 for parent in c.parents():
602 602 visit[(parent.rev(), parent.node())] = parent
603 603 if not visit:
604 604 break
605 605 c = visit.pop(max(visit))
606 606 yield c
607 607
608 608 class workingctx(changectx):
609 609 """A workingctx object makes access to data related to
610 610 the current working directory convenient.
611 611 date - any valid date string or (unixtime, offset), or None.
612 612 user - username string, or None.
613 613 extra - a dictionary of extra values, or None.
614 614 changes - a list of file lists as returned by localrepo.status()
615 615 or None to use the repository status.
616 616 """
617 617 def __init__(self, repo, text="", user=None, date=None, extra=None,
618 618 changes=None):
619 619 self._repo = repo
620 620 self._rev = None
621 621 self._node = None
622 622 self._text = text
623 623 if date:
624 624 self._date = util.parsedate(date)
625 625 if user:
626 626 self._user = user
627 627 if changes:
628 628 self._status = list(changes[:4])
629 629 self._unknown = changes[4]
630 630 self._ignored = changes[5]
631 631 self._clean = changes[6]
632 632 else:
633 633 self._unknown = None
634 634 self._ignored = None
635 635 self._clean = None
636 636
637 637 self._extra = {}
638 638 if extra:
639 639 self._extra = extra.copy()
640 640 if 'branch' not in self._extra:
641 641 try:
642 642 branch = encoding.fromlocal(self._repo.dirstate.branch())
643 643 except UnicodeDecodeError:
644 644 raise util.Abort(_('branch name not in UTF-8!'))
645 645 self._extra['branch'] = branch
646 646 if self._extra['branch'] == '':
647 647 self._extra['branch'] = 'default'
648 648
649 649 def __str__(self):
650 650 return str(self._parents[0]) + "+"
651 651
652 652 def __repr__(self):
653 653 return "<workingctx %s>" % str(self)
654 654
655 655 def __nonzero__(self):
656 656 return True
657 657
658 658 def __contains__(self, key):
659 659 return self._repo.dirstate[key] not in "?r"
660 660
661 661 def _buildflagfunc(self):
662 662 # Create a fallback function for getting file flags when the
663 663 # filesystem doesn't support them
664 664
665 665 copiesget = self._repo.dirstate.copies().get
666 666
667 667 if len(self._parents) < 2:
668 668 # when we have one parent, it's easy: copy from parent
669 669 man = self._parents[0].manifest()
670 670 def func(f):
671 671 f = copiesget(f, f)
672 672 return man.flags(f)
673 673 else:
674 674 # merges are tricky: we try to reconstruct the unstored
675 675 # result from the merge (issue1802)
676 676 p1, p2 = self._parents
677 677 pa = p1.ancestor(p2)
678 678 m1, m2, ma = p1.manifest(), p2.manifest(), pa.manifest()
679 679
680 680 def func(f):
681 681 f = copiesget(f, f) # may be wrong for merges with copies
682 682 fl1, fl2, fla = m1.flags(f), m2.flags(f), ma.flags(f)
683 683 if fl1 == fl2:
684 684 return fl1
685 685 if fl1 == fla:
686 686 return fl2
687 687 if fl2 == fla:
688 688 return fl1
689 689 return '' # punt for conflicts
690 690
691 691 return func
692 692
693 693 @propertycache
694 694 def _flagfunc(self):
695 695 return self._repo.dirstate.flagfunc(self._buildflagfunc)
696 696
697 697 @propertycache
698 698 def _manifest(self):
699 699 """generate a manifest corresponding to the working directory"""
700 700
701 701 if self._unknown is None:
702 702 self.status(unknown=True)
703 703
704 704 man = self._parents[0].manifest().copy()
705 705 if len(self._parents) > 1:
706 706 man2 = self.p2().manifest()
707 707 def getman(f):
708 708 if f in man:
709 709 return man
710 710 return man2
711 711 else:
712 712 getman = lambda f: man
713 713
714 714 copied = self._repo.dirstate.copies()
715 715 ff = self._flagfunc
716 716 modified, added, removed, deleted = self._status
717 717 unknown = self._unknown
718 718 for i, l in (("a", added), ("m", modified), ("u", unknown)):
719 719 for f in l:
720 720 orig = copied.get(f, f)
721 721 man[f] = getman(orig).get(orig, nullid) + i
722 722 try:
723 723 man.set(f, ff(f))
724 724 except OSError:
725 725 pass
726 726
727 727 for f in deleted + removed:
728 728 if f in man:
729 729 del man[f]
730 730
731 731 return man
732 732
733 733 def __iter__(self):
734 734 d = self._repo.dirstate
735 735 for f in d:
736 736 if d[f] != 'r':
737 737 yield f
738 738
739 739 @propertycache
740 740 def _status(self):
741 741 return self._repo.status()[:4]
742 742
743 743 @propertycache
744 744 def _user(self):
745 745 return self._repo.ui.username()
746 746
747 747 @propertycache
748 748 def _date(self):
749 749 return util.makedate()
750 750
751 751 @propertycache
752 752 def _parents(self):
753 753 p = self._repo.dirstate.parents()
754 754 if p[1] == nullid:
755 755 p = p[:-1]
756 756 self._parents = [changectx(self._repo, x) for x in p]
757 757 return self._parents
758 758
759 759 def status(self, ignored=False, clean=False, unknown=False):
760 760 """Explicit status query
761 761 Unless this method is used to query the working copy status, the
762 762 _status property will implicitly read the status using its default
763 763 arguments."""
764 764 stat = self._repo.status(ignored=ignored, clean=clean, unknown=unknown)
765 765 self._unknown = self._ignored = self._clean = None
766 766 if unknown:
767 767 self._unknown = stat[4]
768 768 if ignored:
769 769 self._ignored = stat[5]
770 770 if clean:
771 771 self._clean = stat[6]
772 772 self._status = stat[:4]
773 773 return stat
774 774
775 775 def manifest(self):
776 776 return self._manifest
777 777 def user(self):
778 778 return self._user or self._repo.ui.username()
779 779 def date(self):
780 780 return self._date
781 781 def description(self):
782 782 return self._text
783 783 def files(self):
784 784 return sorted(self._status[0] + self._status[1] + self._status[2])
785 785
786 786 def modified(self):
787 787 return self._status[0]
788 788 def added(self):
789 789 return self._status[1]
790 790 def removed(self):
791 791 return self._status[2]
792 792 def deleted(self):
793 793 return self._status[3]
794 794 def unknown(self):
795 795 assert self._unknown is not None # must call status first
796 796 return self._unknown
797 797 def ignored(self):
798 798 assert self._ignored is not None # must call status first
799 799 return self._ignored
800 800 def clean(self):
801 801 assert self._clean is not None # must call status first
802 802 return self._clean
803 803 def branch(self):
804 804 return encoding.tolocal(self._extra['branch'])
805 805 def extra(self):
806 806 return self._extra
807 807
808 808 def tags(self):
809 809 t = []
810 810 for p in self.parents():
811 811 t.extend(p.tags())
812 812 return t
813 813
814 814 def bookmarks(self):
815 815 b = []
816 816 for p in self.parents():
817 817 b.extend(p.bookmarks())
818 818 return b
819 819
820 820 def phase(self):
821 821 phase = phases.draft # default phase to draft
822 822 for p in self.parents():
823 823 phase = max(phase, p.phase())
824 824 return phase
825 825
826 826 def hidden(self):
827 827 return False
828 828
829 829 def children(self):
830 830 return []
831 831
832 832 def flags(self, path):
833 833 if '_manifest' in self.__dict__:
834 834 try:
835 835 return self._manifest.flags(path)
836 836 except KeyError:
837 837 return ''
838 838
839 839 try:
840 840 return self._flagfunc(path)
841 841 except OSError:
842 842 return ''
843 843
844 844 def filectx(self, path, filelog=None):
845 845 """get a file context from the working directory"""
846 846 return workingfilectx(self._repo, path, workingctx=self,
847 847 filelog=filelog)
848 848
849 849 def ancestor(self, c2):
850 850 """return the ancestor context of self and c2"""
851 851 return self._parents[0].ancestor(c2) # punt on two parents for now
852 852
853 853 def walk(self, match):
854 854 return sorted(self._repo.dirstate.walk(match, self.substate.keys(),
855 855 True, False))
856 856
857 857 def dirty(self, missing=False):
858 858 "check whether a working directory is modified"
859 859 # check subrepos first
860 860 for s in self.substate:
861 861 if self.sub(s).dirty():
862 862 return True
863 863 # check current working dir
864 864 return (self.p2() or self.branch() != self.p1().branch() or
865 865 self.modified() or self.added() or self.removed() or
866 866 (missing and self.deleted()))
867 867
868 868 def add(self, list, prefix=""):
869 869 join = lambda f: os.path.join(prefix, f)
870 870 wlock = self._repo.wlock()
871 871 ui, ds = self._repo.ui, self._repo.dirstate
872 872 try:
873 873 rejected = []
874 874 for f in list:
875 875 scmutil.checkportable(ui, join(f))
876 876 p = self._repo.wjoin(f)
877 877 try:
878 878 st = os.lstat(p)
879 879 except OSError:
880 880 ui.warn(_("%s does not exist!\n") % join(f))
881 881 rejected.append(f)
882 882 continue
883 883 if st.st_size > 10000000:
884 884 ui.warn(_("%s: up to %d MB of RAM may be required "
885 885 "to manage this file\n"
886 886 "(use 'hg revert %s' to cancel the "
887 887 "pending addition)\n")
888 888 % (f, 3 * st.st_size // 1000000, join(f)))
889 889 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
890 890 ui.warn(_("%s not added: only files and symlinks "
891 891 "supported currently\n") % join(f))
892 892 rejected.append(p)
893 893 elif ds[f] in 'amn':
894 894 ui.warn(_("%s already tracked!\n") % join(f))
895 895 elif ds[f] == 'r':
896 896 ds.normallookup(f)
897 897 else:
898 898 ds.add(f)
899 899 return rejected
900 900 finally:
901 901 wlock.release()
902 902
903 def forget(self, files):
903 def forget(self, files, prefix=""):
904 join = lambda f: os.path.join(prefix, f)
904 905 wlock = self._repo.wlock()
905 906 try:
907 rejected = []
906 908 for f in files:
907 909 if self._repo.dirstate[f] != 'a':
908 910 self._repo.dirstate.remove(f)
909 911 elif f not in self._repo.dirstate:
910 self._repo.ui.warn(_("%s not tracked!\n") % f)
912 self._repo.ui.warn(_("%s not tracked!\n") % join(f))
913 rejected.append(f)
911 914 else:
912 915 self._repo.dirstate.drop(f)
916 return rejected
913 917 finally:
914 918 wlock.release()
915 919
916 920 def ancestors(self):
917 921 for a in self._repo.changelog.ancestors(
918 922 *[p.rev() for p in self._parents]):
919 923 yield changectx(self._repo, a)
920 924
921 925 def undelete(self, list):
922 926 pctxs = self.parents()
923 927 wlock = self._repo.wlock()
924 928 try:
925 929 for f in list:
926 930 if self._repo.dirstate[f] != 'r':
927 931 self._repo.ui.warn(_("%s not removed!\n") % f)
928 932 else:
929 933 fctx = f in pctxs[0] and pctxs[0][f] or pctxs[1][f]
930 934 t = fctx.data()
931 935 self._repo.wwrite(f, t, fctx.flags())
932 936 self._repo.dirstate.normal(f)
933 937 finally:
934 938 wlock.release()
935 939
936 940 def copy(self, source, dest):
937 941 p = self._repo.wjoin(dest)
938 942 if not os.path.lexists(p):
939 943 self._repo.ui.warn(_("%s does not exist!\n") % dest)
940 944 elif not (os.path.isfile(p) or os.path.islink(p)):
941 945 self._repo.ui.warn(_("copy failed: %s is not a file or a "
942 946 "symbolic link\n") % dest)
943 947 else:
944 948 wlock = self._repo.wlock()
945 949 try:
946 950 if self._repo.dirstate[dest] in '?r':
947 951 self._repo.dirstate.add(dest)
948 952 self._repo.dirstate.copy(source, dest)
949 953 finally:
950 954 wlock.release()
951 955
952 956 class workingfilectx(filectx):
953 957 """A workingfilectx object makes access to data related to a particular
954 958 file in the working directory convenient."""
955 959 def __init__(self, repo, path, filelog=None, workingctx=None):
956 960 """changeid can be a changeset revision, node, or tag.
957 961 fileid can be a file revision or node."""
958 962 self._repo = repo
959 963 self._path = path
960 964 self._changeid = None
961 965 self._filerev = self._filenode = None
962 966
963 967 if filelog:
964 968 self._filelog = filelog
965 969 if workingctx:
966 970 self._changectx = workingctx
967 971
968 972 @propertycache
969 973 def _changectx(self):
970 974 return workingctx(self._repo)
971 975
972 976 def __nonzero__(self):
973 977 return True
974 978
975 979 def __str__(self):
976 980 return "%s@%s" % (self.path(), self._changectx)
977 981
978 982 def __repr__(self):
979 983 return "<workingfilectx %s>" % str(self)
980 984
981 985 def data(self):
982 986 return self._repo.wread(self._path)
983 987 def renamed(self):
984 988 rp = self._repo.dirstate.copied(self._path)
985 989 if not rp:
986 990 return None
987 991 return rp, self._changectx._parents[0]._manifest.get(rp, nullid)
988 992
989 993 def parents(self):
990 994 '''return parent filectxs, following copies if necessary'''
991 995 def filenode(ctx, path):
992 996 return ctx._manifest.get(path, nullid)
993 997
994 998 path = self._path
995 999 fl = self._filelog
996 1000 pcl = self._changectx._parents
997 1001 renamed = self.renamed()
998 1002
999 1003 if renamed:
1000 1004 pl = [renamed + (None,)]
1001 1005 else:
1002 1006 pl = [(path, filenode(pcl[0], path), fl)]
1003 1007
1004 1008 for pc in pcl[1:]:
1005 1009 pl.append((path, filenode(pc, path), fl))
1006 1010
1007 1011 return [filectx(self._repo, p, fileid=n, filelog=l)
1008 1012 for p, n, l in pl if n != nullid]
1009 1013
1010 1014 def children(self):
1011 1015 return []
1012 1016
1013 1017 def size(self):
1014 1018 return os.lstat(self._repo.wjoin(self._path)).st_size
1015 1019 def date(self):
1016 1020 t, tz = self._changectx.date()
1017 1021 try:
1018 1022 return (int(os.lstat(self._repo.wjoin(self._path)).st_mtime), tz)
1019 1023 except OSError, err:
1020 1024 if err.errno != errno.ENOENT:
1021 1025 raise
1022 1026 return (t, tz)
1023 1027
1024 1028 def cmp(self, fctx):
1025 1029 """compare with other file context
1026 1030
1027 1031 returns True if different than fctx.
1028 1032 """
1029 1033 # fctx should be a filectx (not a wfctx)
1030 1034 # invert comparison to reuse the same code path
1031 1035 return fctx.cmp(self)
1032 1036
1033 1037 class memctx(object):
1034 1038 """Use memctx to perform in-memory commits via localrepo.commitctx().
1035 1039
1036 1040 Revision information is supplied at initialization time while
1037 1041 related files data and is made available through a callback
1038 1042 mechanism. 'repo' is the current localrepo, 'parents' is a
1039 1043 sequence of two parent revisions identifiers (pass None for every
1040 1044 missing parent), 'text' is the commit message and 'files' lists
1041 1045 names of files touched by the revision (normalized and relative to
1042 1046 repository root).
1043 1047
1044 1048 filectxfn(repo, memctx, path) is a callable receiving the
1045 1049 repository, the current memctx object and the normalized path of
1046 1050 requested file, relative to repository root. It is fired by the
1047 1051 commit function for every file in 'files', but calls order is
1048 1052 undefined. If the file is available in the revision being
1049 1053 committed (updated or added), filectxfn returns a memfilectx
1050 1054 object. If the file was removed, filectxfn raises an
1051 1055 IOError. Moved files are represented by marking the source file
1052 1056 removed and the new file added with copy information (see
1053 1057 memfilectx).
1054 1058
1055 1059 user receives the committer name and defaults to current
1056 1060 repository username, date is the commit date in any format
1057 1061 supported by util.parsedate() and defaults to current date, extra
1058 1062 is a dictionary of metadata or is left empty.
1059 1063 """
1060 1064 def __init__(self, repo, parents, text, files, filectxfn, user=None,
1061 1065 date=None, extra=None):
1062 1066 self._repo = repo
1063 1067 self._rev = None
1064 1068 self._node = None
1065 1069 self._text = text
1066 1070 self._date = date and util.parsedate(date) or util.makedate()
1067 1071 self._user = user
1068 1072 parents = [(p or nullid) for p in parents]
1069 1073 p1, p2 = parents
1070 1074 self._parents = [changectx(self._repo, p) for p in (p1, p2)]
1071 1075 files = sorted(set(files))
1072 1076 self._status = [files, [], [], [], []]
1073 1077 self._filectxfn = filectxfn
1074 1078
1075 1079 self._extra = extra and extra.copy() or {}
1076 1080 if self._extra.get('branch', '') == '':
1077 1081 self._extra['branch'] = 'default'
1078 1082
1079 1083 def __str__(self):
1080 1084 return str(self._parents[0]) + "+"
1081 1085
1082 1086 def __int__(self):
1083 1087 return self._rev
1084 1088
1085 1089 def __nonzero__(self):
1086 1090 return True
1087 1091
1088 1092 def __getitem__(self, key):
1089 1093 return self.filectx(key)
1090 1094
1091 1095 def p1(self):
1092 1096 return self._parents[0]
1093 1097 def p2(self):
1094 1098 return self._parents[1]
1095 1099
1096 1100 def user(self):
1097 1101 return self._user or self._repo.ui.username()
1098 1102 def date(self):
1099 1103 return self._date
1100 1104 def description(self):
1101 1105 return self._text
1102 1106 def files(self):
1103 1107 return self.modified()
1104 1108 def modified(self):
1105 1109 return self._status[0]
1106 1110 def added(self):
1107 1111 return self._status[1]
1108 1112 def removed(self):
1109 1113 return self._status[2]
1110 1114 def deleted(self):
1111 1115 return self._status[3]
1112 1116 def unknown(self):
1113 1117 return self._status[4]
1114 1118 def ignored(self):
1115 1119 return self._status[5]
1116 1120 def clean(self):
1117 1121 return self._status[6]
1118 1122 def branch(self):
1119 1123 return encoding.tolocal(self._extra['branch'])
1120 1124 def extra(self):
1121 1125 return self._extra
1122 1126 def flags(self, f):
1123 1127 return self[f].flags()
1124 1128
1125 1129 def parents(self):
1126 1130 """return contexts for each parent changeset"""
1127 1131 return self._parents
1128 1132
1129 1133 def filectx(self, path, filelog=None):
1130 1134 """get a file context from the working directory"""
1131 1135 return self._filectxfn(self._repo, self, path)
1132 1136
1133 1137 def commit(self):
1134 1138 """commit context to the repo"""
1135 1139 return self._repo.commitctx(self)
1136 1140
1137 1141 class memfilectx(object):
1138 1142 """memfilectx represents an in-memory file to commit.
1139 1143
1140 1144 See memctx for more details.
1141 1145 """
1142 1146 def __init__(self, path, data, islink=False, isexec=False, copied=None):
1143 1147 """
1144 1148 path is the normalized file path relative to repository root.
1145 1149 data is the file content as a string.
1146 1150 islink is True if the file is a symbolic link.
1147 1151 isexec is True if the file is executable.
1148 1152 copied is the source file path if current file was copied in the
1149 1153 revision being committed, or None."""
1150 1154 self._path = path
1151 1155 self._data = data
1152 1156 self._flags = (islink and 'l' or '') + (isexec and 'x' or '')
1153 1157 self._copied = None
1154 1158 if copied:
1155 1159 self._copied = (copied, nullid)
1156 1160
1157 1161 def __nonzero__(self):
1158 1162 return True
1159 1163 def __str__(self):
1160 1164 return "%s@%s" % (self.path(), self._changectx)
1161 1165 def path(self):
1162 1166 return self._path
1163 1167 def data(self):
1164 1168 return self._data
1165 1169 def flags(self):
1166 1170 return self._flags
1167 1171 def isexec(self):
1168 1172 return 'x' in self._flags
1169 1173 def islink(self):
1170 1174 return 'l' in self._flags
1171 1175 def renamed(self):
1172 1176 return self._copied
@@ -1,1149 +1,1149 b''
1 1 # subrepo.py - sub-repository handling for Mercurial
2 2 #
3 3 # Copyright 2009-2010 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 import errno, os, re, xml.dom.minidom, shutil, posixpath
9 9 import stat, subprocess, tarfile
10 10 from i18n import _
11 11 import config, scmutil, util, node, error, cmdutil, bookmarks
12 12 hg = None
13 13 propertycache = util.propertycache
14 14
15 15 nullstate = ('', '', 'empty')
16 16
17 17 def state(ctx, ui):
18 18 """return a state dict, mapping subrepo paths configured in .hgsub
19 19 to tuple: (source from .hgsub, revision from .hgsubstate, kind
20 20 (key in types dict))
21 21 """
22 22 p = config.config()
23 23 def read(f, sections=None, remap=None):
24 24 if f in ctx:
25 25 try:
26 26 data = ctx[f].data()
27 27 except IOError, err:
28 28 if err.errno != errno.ENOENT:
29 29 raise
30 30 # handle missing subrepo spec files as removed
31 31 ui.warn(_("warning: subrepo spec file %s not found\n") % f)
32 32 return
33 33 p.parse(f, data, sections, remap, read)
34 34 else:
35 35 raise util.Abort(_("subrepo spec file %s not found") % f)
36 36
37 37 if '.hgsub' in ctx:
38 38 read('.hgsub')
39 39
40 40 for path, src in ui.configitems('subpaths'):
41 41 p.set('subpaths', path, src, ui.configsource('subpaths', path))
42 42
43 43 rev = {}
44 44 if '.hgsubstate' in ctx:
45 45 try:
46 46 for l in ctx['.hgsubstate'].data().splitlines():
47 47 revision, path = l.split(" ", 1)
48 48 rev[path] = revision
49 49 except IOError, err:
50 50 if err.errno != errno.ENOENT:
51 51 raise
52 52
53 53 def remap(src):
54 54 for pattern, repl in p.items('subpaths'):
55 55 # Turn r'C:\foo\bar' into r'C:\\foo\\bar' since re.sub
56 56 # does a string decode.
57 57 repl = repl.encode('string-escape')
58 58 # However, we still want to allow back references to go
59 59 # through unharmed, so we turn r'\\1' into r'\1'. Again,
60 60 # extra escapes are needed because re.sub string decodes.
61 61 repl = re.sub(r'\\\\([0-9]+)', r'\\\1', repl)
62 62 try:
63 63 src = re.sub(pattern, repl, src, 1)
64 64 except re.error, e:
65 65 raise util.Abort(_("bad subrepository pattern in %s: %s")
66 66 % (p.source('subpaths', pattern), e))
67 67 return src
68 68
69 69 state = {}
70 70 for path, src in p[''].items():
71 71 kind = 'hg'
72 72 if src.startswith('['):
73 73 if ']' not in src:
74 74 raise util.Abort(_('missing ] in subrepo source'))
75 75 kind, src = src.split(']', 1)
76 76 kind = kind[1:]
77 77 src = src.lstrip() # strip any extra whitespace after ']'
78 78
79 79 if not util.url(src).isabs():
80 80 parent = _abssource(ctx._repo, abort=False)
81 81 if parent:
82 82 parent = util.url(parent)
83 83 parent.path = posixpath.join(parent.path or '', src)
84 84 parent.path = posixpath.normpath(parent.path)
85 85 joined = str(parent)
86 86 # Remap the full joined path and use it if it changes,
87 87 # else remap the original source.
88 88 remapped = remap(joined)
89 89 if remapped == joined:
90 90 src = remap(src)
91 91 else:
92 92 src = remapped
93 93
94 94 src = remap(src)
95 95 state[util.pconvert(path)] = (src.strip(), rev.get(path, ''), kind)
96 96
97 97 return state
98 98
99 99 def writestate(repo, state):
100 100 """rewrite .hgsubstate in (outer) repo with these subrepo states"""
101 101 lines = ['%s %s\n' % (state[s][1], s) for s in sorted(state)]
102 102 repo.wwrite('.hgsubstate', ''.join(lines), '')
103 103
104 104 def submerge(repo, wctx, mctx, actx, overwrite):
105 105 """delegated from merge.applyupdates: merging of .hgsubstate file
106 106 in working context, merging context and ancestor context"""
107 107 if mctx == actx: # backwards?
108 108 actx = wctx.p1()
109 109 s1 = wctx.substate
110 110 s2 = mctx.substate
111 111 sa = actx.substate
112 112 sm = {}
113 113
114 114 repo.ui.debug("subrepo merge %s %s %s\n" % (wctx, mctx, actx))
115 115
116 116 def debug(s, msg, r=""):
117 117 if r:
118 118 r = "%s:%s:%s" % r
119 119 repo.ui.debug(" subrepo %s: %s %s\n" % (s, msg, r))
120 120
121 121 for s, l in s1.items():
122 122 a = sa.get(s, nullstate)
123 123 ld = l # local state with possible dirty flag for compares
124 124 if wctx.sub(s).dirty():
125 125 ld = (l[0], l[1] + "+")
126 126 if wctx == actx: # overwrite
127 127 a = ld
128 128
129 129 if s in s2:
130 130 r = s2[s]
131 131 if ld == r or r == a: # no change or local is newer
132 132 sm[s] = l
133 133 continue
134 134 elif ld == a: # other side changed
135 135 debug(s, "other changed, get", r)
136 136 wctx.sub(s).get(r, overwrite)
137 137 sm[s] = r
138 138 elif ld[0] != r[0]: # sources differ
139 139 if repo.ui.promptchoice(
140 140 _(' subrepository sources for %s differ\n'
141 141 'use (l)ocal source (%s) or (r)emote source (%s)?')
142 142 % (s, l[0], r[0]),
143 143 (_('&Local'), _('&Remote')), 0):
144 144 debug(s, "prompt changed, get", r)
145 145 wctx.sub(s).get(r, overwrite)
146 146 sm[s] = r
147 147 elif ld[1] == a[1]: # local side is unchanged
148 148 debug(s, "other side changed, get", r)
149 149 wctx.sub(s).get(r, overwrite)
150 150 sm[s] = r
151 151 else:
152 152 debug(s, "both sides changed, merge with", r)
153 153 wctx.sub(s).merge(r)
154 154 sm[s] = l
155 155 elif ld == a: # remote removed, local unchanged
156 156 debug(s, "remote removed, remove")
157 157 wctx.sub(s).remove()
158 158 elif a == nullstate: # not present in remote or ancestor
159 159 debug(s, "local added, keep")
160 160 sm[s] = l
161 161 continue
162 162 else:
163 163 if repo.ui.promptchoice(
164 164 _(' local changed subrepository %s which remote removed\n'
165 165 'use (c)hanged version or (d)elete?') % s,
166 166 (_('&Changed'), _('&Delete')), 0):
167 167 debug(s, "prompt remove")
168 168 wctx.sub(s).remove()
169 169
170 170 for s, r in sorted(s2.items()):
171 171 if s in s1:
172 172 continue
173 173 elif s not in sa:
174 174 debug(s, "remote added, get", r)
175 175 mctx.sub(s).get(r)
176 176 sm[s] = r
177 177 elif r != sa[s]:
178 178 if repo.ui.promptchoice(
179 179 _(' remote changed subrepository %s which local removed\n'
180 180 'use (c)hanged version or (d)elete?') % s,
181 181 (_('&Changed'), _('&Delete')), 0) == 0:
182 182 debug(s, "prompt recreate", r)
183 183 wctx.sub(s).get(r)
184 184 sm[s] = r
185 185
186 186 # record merged .hgsubstate
187 187 writestate(repo, sm)
188 188
189 189 def _updateprompt(ui, sub, dirty, local, remote):
190 190 if dirty:
191 191 msg = (_(' subrepository sources for %s differ\n'
192 192 'use (l)ocal source (%s) or (r)emote source (%s)?\n')
193 193 % (subrelpath(sub), local, remote))
194 194 else:
195 195 msg = (_(' subrepository sources for %s differ (in checked out version)\n'
196 196 'use (l)ocal source (%s) or (r)emote source (%s)?\n')
197 197 % (subrelpath(sub), local, remote))
198 198 return ui.promptchoice(msg, (_('&Local'), _('&Remote')), 0)
199 199
200 200 def reporelpath(repo):
201 201 """return path to this (sub)repo as seen from outermost repo"""
202 202 parent = repo
203 203 while util.safehasattr(parent, '_subparent'):
204 204 parent = parent._subparent
205 205 p = parent.root.rstrip(os.sep)
206 206 return repo.root[len(p) + 1:]
207 207
208 208 def subrelpath(sub):
209 209 """return path to this subrepo as seen from outermost repo"""
210 210 if util.safehasattr(sub, '_relpath'):
211 211 return sub._relpath
212 212 if not util.safehasattr(sub, '_repo'):
213 213 return sub._path
214 214 return reporelpath(sub._repo)
215 215
216 216 def _abssource(repo, push=False, abort=True):
217 217 """return pull/push path of repo - either based on parent repo .hgsub info
218 218 or on the top repo config. Abort or return None if no source found."""
219 219 if util.safehasattr(repo, '_subparent'):
220 220 source = util.url(repo._subsource)
221 221 if source.isabs():
222 222 return str(source)
223 223 source.path = posixpath.normpath(source.path)
224 224 parent = _abssource(repo._subparent, push, abort=False)
225 225 if parent:
226 226 parent = util.url(util.pconvert(parent))
227 227 parent.path = posixpath.join(parent.path or '', source.path)
228 228 parent.path = posixpath.normpath(parent.path)
229 229 return str(parent)
230 230 else: # recursion reached top repo
231 231 if util.safehasattr(repo, '_subtoppath'):
232 232 return repo._subtoppath
233 233 if push and repo.ui.config('paths', 'default-push'):
234 234 return repo.ui.config('paths', 'default-push')
235 235 if repo.ui.config('paths', 'default'):
236 236 return repo.ui.config('paths', 'default')
237 237 if abort:
238 238 raise util.Abort(_("default path for subrepository %s not found") %
239 239 reporelpath(repo))
240 240
241 241 def itersubrepos(ctx1, ctx2):
242 242 """find subrepos in ctx1 or ctx2"""
243 243 # Create a (subpath, ctx) mapping where we prefer subpaths from
244 244 # ctx1. The subpaths from ctx2 are important when the .hgsub file
245 245 # has been modified (in ctx2) but not yet committed (in ctx1).
246 246 subpaths = dict.fromkeys(ctx2.substate, ctx2)
247 247 subpaths.update(dict.fromkeys(ctx1.substate, ctx1))
248 248 for subpath, ctx in sorted(subpaths.iteritems()):
249 249 yield subpath, ctx.sub(subpath)
250 250
251 251 def subrepo(ctx, path):
252 252 """return instance of the right subrepo class for subrepo in path"""
253 253 # subrepo inherently violates our import layering rules
254 254 # because it wants to make repo objects from deep inside the stack
255 255 # so we manually delay the circular imports to not break
256 256 # scripts that don't use our demand-loading
257 257 global hg
258 258 import hg as h
259 259 hg = h
260 260
261 261 scmutil.pathauditor(ctx._repo.root)(path)
262 262 state = ctx.substate.get(path, nullstate)
263 263 if state[2] not in types:
264 264 raise util.Abort(_('unknown subrepo type %s') % state[2])
265 265 return types[state[2]](ctx, path, state[:2])
266 266
267 267 # subrepo classes need to implement the following abstract class:
268 268
269 269 class abstractsubrepo(object):
270 270
271 271 def dirty(self, ignoreupdate=False):
272 272 """returns true if the dirstate of the subrepo is dirty or does not
273 273 match current stored state. If ignoreupdate is true, only check
274 274 whether the subrepo has uncommitted changes in its dirstate.
275 275 """
276 276 raise NotImplementedError
277 277
278 278 def checknested(self, path):
279 279 """check if path is a subrepository within this repository"""
280 280 return False
281 281
282 282 def commit(self, text, user, date):
283 283 """commit the current changes to the subrepo with the given
284 284 log message. Use given user and date if possible. Return the
285 285 new state of the subrepo.
286 286 """
287 287 raise NotImplementedError
288 288
289 289 def remove(self):
290 290 """remove the subrepo
291 291
292 292 (should verify the dirstate is not dirty first)
293 293 """
294 294 raise NotImplementedError
295 295
296 296 def get(self, state, overwrite=False):
297 297 """run whatever commands are needed to put the subrepo into
298 298 this state
299 299 """
300 300 raise NotImplementedError
301 301
302 302 def merge(self, state):
303 303 """merge currently-saved state with the new state."""
304 304 raise NotImplementedError
305 305
306 306 def push(self, opts):
307 307 """perform whatever action is analogous to 'hg push'
308 308
309 309 This may be a no-op on some systems.
310 310 """
311 311 raise NotImplementedError
312 312
313 313 def add(self, ui, match, dryrun, listsubrepos, prefix, explicitonly):
314 314 return []
315 315
316 316 def status(self, rev2, **opts):
317 317 return [], [], [], [], [], [], []
318 318
319 319 def diff(self, diffopts, node2, match, prefix, **opts):
320 320 pass
321 321
322 322 def outgoing(self, ui, dest, opts):
323 323 return 1
324 324
325 325 def incoming(self, ui, source, opts):
326 326 return 1
327 327
328 328 def files(self):
329 329 """return filename iterator"""
330 330 raise NotImplementedError
331 331
332 332 def filedata(self, name):
333 333 """return file data"""
334 334 raise NotImplementedError
335 335
336 336 def fileflags(self, name):
337 337 """return file flags"""
338 338 return ''
339 339
340 340 def archive(self, ui, archiver, prefix):
341 341 files = self.files()
342 342 total = len(files)
343 343 relpath = subrelpath(self)
344 344 ui.progress(_('archiving (%s)') % relpath, 0,
345 345 unit=_('files'), total=total)
346 346 for i, name in enumerate(files):
347 347 flags = self.fileflags(name)
348 348 mode = 'x' in flags and 0755 or 0644
349 349 symlink = 'l' in flags
350 350 archiver.addfile(os.path.join(prefix, self._path, name),
351 351 mode, symlink, self.filedata(name))
352 352 ui.progress(_('archiving (%s)') % relpath, i + 1,
353 353 unit=_('files'), total=total)
354 354 ui.progress(_('archiving (%s)') % relpath, None)
355 355
356 356 def walk(self, match):
357 357 '''
358 358 walk recursively through the directory tree, finding all files
359 359 matched by the match function
360 360 '''
361 361 pass
362 362
363 def forget(self, files):
364 pass
363 def forget(self, ui, match, prefix):
364 return []
365 365
366 366 class hgsubrepo(abstractsubrepo):
367 367 def __init__(self, ctx, path, state):
368 368 self._path = path
369 369 self._state = state
370 370 r = ctx._repo
371 371 root = r.wjoin(path)
372 372 create = False
373 373 if not os.path.exists(os.path.join(root, '.hg')):
374 374 create = True
375 375 util.makedirs(root)
376 376 self._repo = hg.repository(r.ui, root, create=create)
377 377 self._initrepo(r, state[0], create)
378 378
379 379 def _initrepo(self, parentrepo, source, create):
380 380 self._repo._subparent = parentrepo
381 381 self._repo._subsource = source
382 382
383 383 if create:
384 384 fp = self._repo.opener("hgrc", "w", text=True)
385 385 fp.write('[paths]\n')
386 386
387 387 def addpathconfig(key, value):
388 388 if value:
389 389 fp.write('%s = %s\n' % (key, value))
390 390 self._repo.ui.setconfig('paths', key, value)
391 391
392 392 defpath = _abssource(self._repo, abort=False)
393 393 defpushpath = _abssource(self._repo, True, abort=False)
394 394 addpathconfig('default', defpath)
395 395 if defpath != defpushpath:
396 396 addpathconfig('default-push', defpushpath)
397 397 fp.close()
398 398
399 399 def add(self, ui, match, dryrun, listsubrepos, prefix, explicitonly):
400 400 return cmdutil.add(ui, self._repo, match, dryrun, listsubrepos,
401 401 os.path.join(prefix, self._path), explicitonly)
402 402
403 403 def status(self, rev2, **opts):
404 404 try:
405 405 rev1 = self._state[1]
406 406 ctx1 = self._repo[rev1]
407 407 ctx2 = self._repo[rev2]
408 408 return self._repo.status(ctx1, ctx2, **opts)
409 409 except error.RepoLookupError, inst:
410 410 self._repo.ui.warn(_('warning: error "%s" in subrepository "%s"\n')
411 411 % (inst, subrelpath(self)))
412 412 return [], [], [], [], [], [], []
413 413
414 414 def diff(self, diffopts, node2, match, prefix, **opts):
415 415 try:
416 416 node1 = node.bin(self._state[1])
417 417 # We currently expect node2 to come from substate and be
418 418 # in hex format
419 419 if node2 is not None:
420 420 node2 = node.bin(node2)
421 421 cmdutil.diffordiffstat(self._repo.ui, self._repo, diffopts,
422 422 node1, node2, match,
423 423 prefix=os.path.join(prefix, self._path),
424 424 listsubrepos=True, **opts)
425 425 except error.RepoLookupError, inst:
426 426 self._repo.ui.warn(_('warning: error "%s" in subrepository "%s"\n')
427 427 % (inst, subrelpath(self)))
428 428
429 429 def archive(self, ui, archiver, prefix):
430 430 self._get(self._state + ('hg',))
431 431 abstractsubrepo.archive(self, ui, archiver, prefix)
432 432
433 433 rev = self._state[1]
434 434 ctx = self._repo[rev]
435 435 for subpath in ctx.substate:
436 436 s = subrepo(ctx, subpath)
437 437 s.archive(ui, archiver, os.path.join(prefix, self._path))
438 438
439 439 def dirty(self, ignoreupdate=False):
440 440 r = self._state[1]
441 441 if r == '' and not ignoreupdate: # no state recorded
442 442 return True
443 443 w = self._repo[None]
444 444 if r != w.p1().hex() and not ignoreupdate:
445 445 # different version checked out
446 446 return True
447 447 return w.dirty() # working directory changed
448 448
449 449 def checknested(self, path):
450 450 return self._repo._checknested(self._repo.wjoin(path))
451 451
452 452 def commit(self, text, user, date):
453 453 # don't bother committing in the subrepo if it's only been
454 454 # updated
455 455 if not self.dirty(True):
456 456 return self._repo['.'].hex()
457 457 self._repo.ui.debug("committing subrepo %s\n" % subrelpath(self))
458 458 n = self._repo.commit(text, user, date)
459 459 if not n:
460 460 return self._repo['.'].hex() # different version checked out
461 461 return node.hex(n)
462 462
463 463 def remove(self):
464 464 # we can't fully delete the repository as it may contain
465 465 # local-only history
466 466 self._repo.ui.note(_('removing subrepo %s\n') % subrelpath(self))
467 467 hg.clean(self._repo, node.nullid, False)
468 468
469 469 def _get(self, state):
470 470 source, revision, kind = state
471 471 if revision not in self._repo:
472 472 self._repo._subsource = source
473 473 srcurl = _abssource(self._repo)
474 474 other = hg.peer(self._repo.ui, {}, srcurl)
475 475 if len(self._repo) == 0:
476 476 self._repo.ui.status(_('cloning subrepo %s from %s\n')
477 477 % (subrelpath(self), srcurl))
478 478 parentrepo = self._repo._subparent
479 479 shutil.rmtree(self._repo.path)
480 480 other, self._repo = hg.clone(self._repo._subparent.ui, {}, other,
481 481 self._repo.root, update=False)
482 482 self._initrepo(parentrepo, source, create=True)
483 483 else:
484 484 self._repo.ui.status(_('pulling subrepo %s from %s\n')
485 485 % (subrelpath(self), srcurl))
486 486 self._repo.pull(other)
487 487 bookmarks.updatefromremote(self._repo.ui, self._repo, other,
488 488 srcurl)
489 489
490 490 def get(self, state, overwrite=False):
491 491 self._get(state)
492 492 source, revision, kind = state
493 493 self._repo.ui.debug("getting subrepo %s\n" % self._path)
494 494 hg.clean(self._repo, revision, False)
495 495
496 496 def merge(self, state):
497 497 self._get(state)
498 498 cur = self._repo['.']
499 499 dst = self._repo[state[1]]
500 500 anc = dst.ancestor(cur)
501 501
502 502 def mergefunc():
503 503 if anc == cur:
504 504 self._repo.ui.debug("updating subrepo %s\n" % subrelpath(self))
505 505 hg.update(self._repo, state[1])
506 506 elif anc == dst:
507 507 self._repo.ui.debug("skipping subrepo %s\n" % subrelpath(self))
508 508 else:
509 509 self._repo.ui.debug("merging subrepo %s\n" % subrelpath(self))
510 510 hg.merge(self._repo, state[1], remind=False)
511 511
512 512 wctx = self._repo[None]
513 513 if self.dirty():
514 514 if anc != dst:
515 515 if _updateprompt(self._repo.ui, self, wctx.dirty(), cur, dst):
516 516 mergefunc()
517 517 else:
518 518 mergefunc()
519 519 else:
520 520 mergefunc()
521 521
522 522 def push(self, opts):
523 523 force = opts.get('force')
524 524 newbranch = opts.get('new_branch')
525 525 ssh = opts.get('ssh')
526 526
527 527 # push subrepos depth-first for coherent ordering
528 528 c = self._repo['']
529 529 subs = c.substate # only repos that are committed
530 530 for s in sorted(subs):
531 531 if not c.sub(s).push(opts):
532 532 return False
533 533
534 534 dsturl = _abssource(self._repo, True)
535 535 self._repo.ui.status(_('pushing subrepo %s to %s\n') %
536 536 (subrelpath(self), dsturl))
537 537 other = hg.peer(self._repo.ui, {'ssh': ssh}, dsturl)
538 538 return self._repo.push(other, force, newbranch=newbranch)
539 539
540 540 def outgoing(self, ui, dest, opts):
541 541 return hg.outgoing(ui, self._repo, _abssource(self._repo, True), opts)
542 542
543 543 def incoming(self, ui, source, opts):
544 544 return hg.incoming(ui, self._repo, _abssource(self._repo, False), opts)
545 545
546 546 def files(self):
547 547 rev = self._state[1]
548 548 ctx = self._repo[rev]
549 549 return ctx.manifest()
550 550
551 551 def filedata(self, name):
552 552 rev = self._state[1]
553 553 return self._repo[rev][name].data()
554 554
555 555 def fileflags(self, name):
556 556 rev = self._state[1]
557 557 ctx = self._repo[rev]
558 558 return ctx.flags(name)
559 559
560 560 def walk(self, match):
561 561 ctx = self._repo[None]
562 562 return ctx.walk(match)
563 563
564 def forget(self, files):
565 ctx = self._repo[None]
566 ctx.forget(files)
564 def forget(self, ui, match, prefix):
565 return cmdutil.forget(ui, self._repo, match,
566 os.path.join(prefix, self._path), True)
567 567
568 568 class svnsubrepo(abstractsubrepo):
569 569 def __init__(self, ctx, path, state):
570 570 self._path = path
571 571 self._state = state
572 572 self._ctx = ctx
573 573 self._ui = ctx._repo.ui
574 574 self._exe = util.findexe('svn')
575 575 if not self._exe:
576 576 raise util.Abort(_("'svn' executable not found for subrepo '%s'")
577 577 % self._path)
578 578
579 579 def _svncommand(self, commands, filename='', failok=False):
580 580 cmd = [self._exe]
581 581 extrakw = {}
582 582 if not self._ui.interactive():
583 583 # Making stdin be a pipe should prevent svn from behaving
584 584 # interactively even if we can't pass --non-interactive.
585 585 extrakw['stdin'] = subprocess.PIPE
586 586 # Starting in svn 1.5 --non-interactive is a global flag
587 587 # instead of being per-command, but we need to support 1.4 so
588 588 # we have to be intelligent about what commands take
589 589 # --non-interactive.
590 590 if commands[0] in ('update', 'checkout', 'commit'):
591 591 cmd.append('--non-interactive')
592 592 cmd.extend(commands)
593 593 if filename is not None:
594 594 path = os.path.join(self._ctx._repo.origroot, self._path, filename)
595 595 cmd.append(path)
596 596 env = dict(os.environ)
597 597 # Avoid localized output, preserve current locale for everything else.
598 598 env['LC_MESSAGES'] = 'C'
599 599 p = subprocess.Popen(cmd, bufsize=-1, close_fds=util.closefds,
600 600 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
601 601 universal_newlines=True, env=env, **extrakw)
602 602 stdout, stderr = p.communicate()
603 603 stderr = stderr.strip()
604 604 if not failok:
605 605 if p.returncode:
606 606 raise util.Abort(stderr or 'exited with code %d' % p.returncode)
607 607 if stderr:
608 608 self._ui.warn(stderr + '\n')
609 609 return stdout, stderr
610 610
611 611 @propertycache
612 612 def _svnversion(self):
613 613 output, err = self._svncommand(['--version'], filename=None)
614 614 m = re.search(r'^svn,\s+version\s+(\d+)\.(\d+)', output)
615 615 if not m:
616 616 raise util.Abort(_('cannot retrieve svn tool version'))
617 617 return (int(m.group(1)), int(m.group(2)))
618 618
619 619 def _wcrevs(self):
620 620 # Get the working directory revision as well as the last
621 621 # commit revision so we can compare the subrepo state with
622 622 # both. We used to store the working directory one.
623 623 output, err = self._svncommand(['info', '--xml'])
624 624 doc = xml.dom.minidom.parseString(output)
625 625 entries = doc.getElementsByTagName('entry')
626 626 lastrev, rev = '0', '0'
627 627 if entries:
628 628 rev = str(entries[0].getAttribute('revision')) or '0'
629 629 commits = entries[0].getElementsByTagName('commit')
630 630 if commits:
631 631 lastrev = str(commits[0].getAttribute('revision')) or '0'
632 632 return (lastrev, rev)
633 633
634 634 def _wcrev(self):
635 635 return self._wcrevs()[0]
636 636
637 637 def _wcchanged(self):
638 638 """Return (changes, extchanges) where changes is True
639 639 if the working directory was changed, and extchanges is
640 640 True if any of these changes concern an external entry.
641 641 """
642 642 output, err = self._svncommand(['status', '--xml'])
643 643 externals, changes = [], []
644 644 doc = xml.dom.minidom.parseString(output)
645 645 for e in doc.getElementsByTagName('entry'):
646 646 s = e.getElementsByTagName('wc-status')
647 647 if not s:
648 648 continue
649 649 item = s[0].getAttribute('item')
650 650 props = s[0].getAttribute('props')
651 651 path = e.getAttribute('path')
652 652 if item == 'external':
653 653 externals.append(path)
654 654 if (item not in ('', 'normal', 'unversioned', 'external')
655 655 or props not in ('', 'none', 'normal')):
656 656 changes.append(path)
657 657 for path in changes:
658 658 for ext in externals:
659 659 if path == ext or path.startswith(ext + os.sep):
660 660 return True, True
661 661 return bool(changes), False
662 662
663 663 def dirty(self, ignoreupdate=False):
664 664 if not self._wcchanged()[0]:
665 665 if self._state[1] in self._wcrevs() or ignoreupdate:
666 666 return False
667 667 return True
668 668
669 669 def commit(self, text, user, date):
670 670 # user and date are out of our hands since svn is centralized
671 671 changed, extchanged = self._wcchanged()
672 672 if not changed:
673 673 return self._wcrev()
674 674 if extchanged:
675 675 # Do not try to commit externals
676 676 raise util.Abort(_('cannot commit svn externals'))
677 677 commitinfo, err = self._svncommand(['commit', '-m', text])
678 678 self._ui.status(commitinfo)
679 679 newrev = re.search('Committed revision ([0-9]+).', commitinfo)
680 680 if not newrev:
681 681 raise util.Abort(commitinfo.splitlines()[-1])
682 682 newrev = newrev.groups()[0]
683 683 self._ui.status(self._svncommand(['update', '-r', newrev])[0])
684 684 return newrev
685 685
686 686 def remove(self):
687 687 if self.dirty():
688 688 self._ui.warn(_('not removing repo %s because '
689 689 'it has changes.\n' % self._path))
690 690 return
691 691 self._ui.note(_('removing subrepo %s\n') % self._path)
692 692
693 693 def onerror(function, path, excinfo):
694 694 if function is not os.remove:
695 695 raise
696 696 # read-only files cannot be unlinked under Windows
697 697 s = os.stat(path)
698 698 if (s.st_mode & stat.S_IWRITE) != 0:
699 699 raise
700 700 os.chmod(path, stat.S_IMODE(s.st_mode) | stat.S_IWRITE)
701 701 os.remove(path)
702 702
703 703 path = self._ctx._repo.wjoin(self._path)
704 704 shutil.rmtree(path, onerror=onerror)
705 705 try:
706 706 os.removedirs(os.path.dirname(path))
707 707 except OSError:
708 708 pass
709 709
710 710 def get(self, state, overwrite=False):
711 711 if overwrite:
712 712 self._svncommand(['revert', '--recursive'])
713 713 args = ['checkout']
714 714 if self._svnversion >= (1, 5):
715 715 args.append('--force')
716 716 # The revision must be specified at the end of the URL to properly
717 717 # update to a directory which has since been deleted and recreated.
718 718 args.append('%s@%s' % (state[0], state[1]))
719 719 status, err = self._svncommand(args, failok=True)
720 720 if not re.search('Checked out revision [0-9]+.', status):
721 721 if ('is already a working copy for a different URL' in err
722 722 and (self._wcchanged() == (False, False))):
723 723 # obstructed but clean working copy, so just blow it away.
724 724 self.remove()
725 725 self.get(state, overwrite=False)
726 726 return
727 727 raise util.Abort((status or err).splitlines()[-1])
728 728 self._ui.status(status)
729 729
730 730 def merge(self, state):
731 731 old = self._state[1]
732 732 new = state[1]
733 733 if new != self._wcrev():
734 734 dirty = old == self._wcrev() or self._wcchanged()[0]
735 735 if _updateprompt(self._ui, self, dirty, self._wcrev(), new):
736 736 self.get(state, False)
737 737
738 738 def push(self, opts):
739 739 # push is a no-op for SVN
740 740 return True
741 741
742 742 def files(self):
743 743 output = self._svncommand(['list'])
744 744 # This works because svn forbids \n in filenames.
745 745 return output.splitlines()
746 746
747 747 def filedata(self, name):
748 748 return self._svncommand(['cat'], name)
749 749
750 750
751 751 class gitsubrepo(abstractsubrepo):
752 752 def __init__(self, ctx, path, state):
753 753 # TODO add git version check.
754 754 self._state = state
755 755 self._ctx = ctx
756 756 self._path = path
757 757 self._relpath = os.path.join(reporelpath(ctx._repo), path)
758 758 self._abspath = ctx._repo.wjoin(path)
759 759 self._subparent = ctx._repo
760 760 self._ui = ctx._repo.ui
761 761
762 762 def _gitcommand(self, commands, env=None, stream=False):
763 763 return self._gitdir(commands, env=env, stream=stream)[0]
764 764
765 765 def _gitdir(self, commands, env=None, stream=False):
766 766 return self._gitnodir(commands, env=env, stream=stream,
767 767 cwd=self._abspath)
768 768
769 769 def _gitnodir(self, commands, env=None, stream=False, cwd=None):
770 770 """Calls the git command
771 771
772 772 The methods tries to call the git command. versions previor to 1.6.0
773 773 are not supported and very probably fail.
774 774 """
775 775 self._ui.debug('%s: git %s\n' % (self._relpath, ' '.join(commands)))
776 776 # unless ui.quiet is set, print git's stderr,
777 777 # which is mostly progress and useful info
778 778 errpipe = None
779 779 if self._ui.quiet:
780 780 errpipe = open(os.devnull, 'w')
781 781 p = subprocess.Popen(['git'] + commands, bufsize=-1, cwd=cwd, env=env,
782 782 close_fds=util.closefds,
783 783 stdout=subprocess.PIPE, stderr=errpipe)
784 784 if stream:
785 785 return p.stdout, None
786 786
787 787 retdata = p.stdout.read().strip()
788 788 # wait for the child to exit to avoid race condition.
789 789 p.wait()
790 790
791 791 if p.returncode != 0 and p.returncode != 1:
792 792 # there are certain error codes that are ok
793 793 command = commands[0]
794 794 if command in ('cat-file', 'symbolic-ref'):
795 795 return retdata, p.returncode
796 796 # for all others, abort
797 797 raise util.Abort('git %s error %d in %s' %
798 798 (command, p.returncode, self._relpath))
799 799
800 800 return retdata, p.returncode
801 801
802 802 def _gitmissing(self):
803 803 return not os.path.exists(os.path.join(self._abspath, '.git'))
804 804
805 805 def _gitstate(self):
806 806 return self._gitcommand(['rev-parse', 'HEAD'])
807 807
808 808 def _gitcurrentbranch(self):
809 809 current, err = self._gitdir(['symbolic-ref', 'HEAD', '--quiet'])
810 810 if err:
811 811 current = None
812 812 return current
813 813
814 814 def _gitremote(self, remote):
815 815 out = self._gitcommand(['remote', 'show', '-n', remote])
816 816 line = out.split('\n')[1]
817 817 i = line.index('URL: ') + len('URL: ')
818 818 return line[i:]
819 819
820 820 def _githavelocally(self, revision):
821 821 out, code = self._gitdir(['cat-file', '-e', revision])
822 822 return code == 0
823 823
824 824 def _gitisancestor(self, r1, r2):
825 825 base = self._gitcommand(['merge-base', r1, r2])
826 826 return base == r1
827 827
828 828 def _gitisbare(self):
829 829 return self._gitcommand(['config', '--bool', 'core.bare']) == 'true'
830 830
831 831 def _gitupdatestat(self):
832 832 """This must be run before git diff-index.
833 833 diff-index only looks at changes to file stat;
834 834 this command looks at file contents and updates the stat."""
835 835 self._gitcommand(['update-index', '-q', '--refresh'])
836 836
837 837 def _gitbranchmap(self):
838 838 '''returns 2 things:
839 839 a map from git branch to revision
840 840 a map from revision to branches'''
841 841 branch2rev = {}
842 842 rev2branch = {}
843 843
844 844 out = self._gitcommand(['for-each-ref', '--format',
845 845 '%(objectname) %(refname)'])
846 846 for line in out.split('\n'):
847 847 revision, ref = line.split(' ')
848 848 if (not ref.startswith('refs/heads/') and
849 849 not ref.startswith('refs/remotes/')):
850 850 continue
851 851 if ref.startswith('refs/remotes/') and ref.endswith('/HEAD'):
852 852 continue # ignore remote/HEAD redirects
853 853 branch2rev[ref] = revision
854 854 rev2branch.setdefault(revision, []).append(ref)
855 855 return branch2rev, rev2branch
856 856
857 857 def _gittracking(self, branches):
858 858 'return map of remote branch to local tracking branch'
859 859 # assumes no more than one local tracking branch for each remote
860 860 tracking = {}
861 861 for b in branches:
862 862 if b.startswith('refs/remotes/'):
863 863 continue
864 864 bname = b.split('/', 2)[2]
865 865 remote = self._gitcommand(['config', 'branch.%s.remote' % bname])
866 866 if remote:
867 867 ref = self._gitcommand(['config', 'branch.%s.merge' % bname])
868 868 tracking['refs/remotes/%s/%s' %
869 869 (remote, ref.split('/', 2)[2])] = b
870 870 return tracking
871 871
872 872 def _abssource(self, source):
873 873 if '://' not in source:
874 874 # recognize the scp syntax as an absolute source
875 875 colon = source.find(':')
876 876 if colon != -1 and '/' not in source[:colon]:
877 877 return source
878 878 self._subsource = source
879 879 return _abssource(self)
880 880
881 881 def _fetch(self, source, revision):
882 882 if self._gitmissing():
883 883 source = self._abssource(source)
884 884 self._ui.status(_('cloning subrepo %s from %s\n') %
885 885 (self._relpath, source))
886 886 self._gitnodir(['clone', source, self._abspath])
887 887 if self._githavelocally(revision):
888 888 return
889 889 self._ui.status(_('pulling subrepo %s from %s\n') %
890 890 (self._relpath, self._gitremote('origin')))
891 891 # try only origin: the originally cloned repo
892 892 self._gitcommand(['fetch'])
893 893 if not self._githavelocally(revision):
894 894 raise util.Abort(_("revision %s does not exist in subrepo %s\n") %
895 895 (revision, self._relpath))
896 896
897 897 def dirty(self, ignoreupdate=False):
898 898 if self._gitmissing():
899 899 return self._state[1] != ''
900 900 if self._gitisbare():
901 901 return True
902 902 if not ignoreupdate and self._state[1] != self._gitstate():
903 903 # different version checked out
904 904 return True
905 905 # check for staged changes or modified files; ignore untracked files
906 906 self._gitupdatestat()
907 907 out, code = self._gitdir(['diff-index', '--quiet', 'HEAD'])
908 908 return code == 1
909 909
910 910 def get(self, state, overwrite=False):
911 911 source, revision, kind = state
912 912 if not revision:
913 913 self.remove()
914 914 return
915 915 self._fetch(source, revision)
916 916 # if the repo was set to be bare, unbare it
917 917 if self._gitisbare():
918 918 self._gitcommand(['config', 'core.bare', 'false'])
919 919 if self._gitstate() == revision:
920 920 self._gitcommand(['reset', '--hard', 'HEAD'])
921 921 return
922 922 elif self._gitstate() == revision:
923 923 if overwrite:
924 924 # first reset the index to unmark new files for commit, because
925 925 # reset --hard will otherwise throw away files added for commit,
926 926 # not just unmark them.
927 927 self._gitcommand(['reset', 'HEAD'])
928 928 self._gitcommand(['reset', '--hard', 'HEAD'])
929 929 return
930 930 branch2rev, rev2branch = self._gitbranchmap()
931 931
932 932 def checkout(args):
933 933 cmd = ['checkout']
934 934 if overwrite:
935 935 # first reset the index to unmark new files for commit, because
936 936 # the -f option will otherwise throw away files added for
937 937 # commit, not just unmark them.
938 938 self._gitcommand(['reset', 'HEAD'])
939 939 cmd.append('-f')
940 940 self._gitcommand(cmd + args)
941 941
942 942 def rawcheckout():
943 943 # no branch to checkout, check it out with no branch
944 944 self._ui.warn(_('checking out detached HEAD in subrepo %s\n') %
945 945 self._relpath)
946 946 self._ui.warn(_('check out a git branch if you intend '
947 947 'to make changes\n'))
948 948 checkout(['-q', revision])
949 949
950 950 if revision not in rev2branch:
951 951 rawcheckout()
952 952 return
953 953 branches = rev2branch[revision]
954 954 firstlocalbranch = None
955 955 for b in branches:
956 956 if b == 'refs/heads/master':
957 957 # master trumps all other branches
958 958 checkout(['refs/heads/master'])
959 959 return
960 960 if not firstlocalbranch and not b.startswith('refs/remotes/'):
961 961 firstlocalbranch = b
962 962 if firstlocalbranch:
963 963 checkout([firstlocalbranch])
964 964 return
965 965
966 966 tracking = self._gittracking(branch2rev.keys())
967 967 # choose a remote branch already tracked if possible
968 968 remote = branches[0]
969 969 if remote not in tracking:
970 970 for b in branches:
971 971 if b in tracking:
972 972 remote = b
973 973 break
974 974
975 975 if remote not in tracking:
976 976 # create a new local tracking branch
977 977 local = remote.split('/', 2)[2]
978 978 checkout(['-b', local, remote])
979 979 elif self._gitisancestor(branch2rev[tracking[remote]], remote):
980 980 # When updating to a tracked remote branch,
981 981 # if the local tracking branch is downstream of it,
982 982 # a normal `git pull` would have performed a "fast-forward merge"
983 983 # which is equivalent to updating the local branch to the remote.
984 984 # Since we are only looking at branching at update, we need to
985 985 # detect this situation and perform this action lazily.
986 986 if tracking[remote] != self._gitcurrentbranch():
987 987 checkout([tracking[remote]])
988 988 self._gitcommand(['merge', '--ff', remote])
989 989 else:
990 990 # a real merge would be required, just checkout the revision
991 991 rawcheckout()
992 992
993 993 def commit(self, text, user, date):
994 994 if self._gitmissing():
995 995 raise util.Abort(_("subrepo %s is missing") % self._relpath)
996 996 cmd = ['commit', '-a', '-m', text]
997 997 env = os.environ.copy()
998 998 if user:
999 999 cmd += ['--author', user]
1000 1000 if date:
1001 1001 # git's date parser silently ignores when seconds < 1e9
1002 1002 # convert to ISO8601
1003 1003 env['GIT_AUTHOR_DATE'] = util.datestr(date,
1004 1004 '%Y-%m-%dT%H:%M:%S %1%2')
1005 1005 self._gitcommand(cmd, env=env)
1006 1006 # make sure commit works otherwise HEAD might not exist under certain
1007 1007 # circumstances
1008 1008 return self._gitstate()
1009 1009
1010 1010 def merge(self, state):
1011 1011 source, revision, kind = state
1012 1012 self._fetch(source, revision)
1013 1013 base = self._gitcommand(['merge-base', revision, self._state[1]])
1014 1014 self._gitupdatestat()
1015 1015 out, code = self._gitdir(['diff-index', '--quiet', 'HEAD'])
1016 1016
1017 1017 def mergefunc():
1018 1018 if base == revision:
1019 1019 self.get(state) # fast forward merge
1020 1020 elif base != self._state[1]:
1021 1021 self._gitcommand(['merge', '--no-commit', revision])
1022 1022
1023 1023 if self.dirty():
1024 1024 if self._gitstate() != revision:
1025 1025 dirty = self._gitstate() == self._state[1] or code != 0
1026 1026 if _updateprompt(self._ui, self, dirty,
1027 1027 self._state[1][:7], revision[:7]):
1028 1028 mergefunc()
1029 1029 else:
1030 1030 mergefunc()
1031 1031
1032 1032 def push(self, opts):
1033 1033 force = opts.get('force')
1034 1034
1035 1035 if not self._state[1]:
1036 1036 return True
1037 1037 if self._gitmissing():
1038 1038 raise util.Abort(_("subrepo %s is missing") % self._relpath)
1039 1039 # if a branch in origin contains the revision, nothing to do
1040 1040 branch2rev, rev2branch = self._gitbranchmap()
1041 1041 if self._state[1] in rev2branch:
1042 1042 for b in rev2branch[self._state[1]]:
1043 1043 if b.startswith('refs/remotes/origin/'):
1044 1044 return True
1045 1045 for b, revision in branch2rev.iteritems():
1046 1046 if b.startswith('refs/remotes/origin/'):
1047 1047 if self._gitisancestor(self._state[1], revision):
1048 1048 return True
1049 1049 # otherwise, try to push the currently checked out branch
1050 1050 cmd = ['push']
1051 1051 if force:
1052 1052 cmd.append('--force')
1053 1053
1054 1054 current = self._gitcurrentbranch()
1055 1055 if current:
1056 1056 # determine if the current branch is even useful
1057 1057 if not self._gitisancestor(self._state[1], current):
1058 1058 self._ui.warn(_('unrelated git branch checked out '
1059 1059 'in subrepo %s\n') % self._relpath)
1060 1060 return False
1061 1061 self._ui.status(_('pushing branch %s of subrepo %s\n') %
1062 1062 (current.split('/', 2)[2], self._relpath))
1063 1063 self._gitcommand(cmd + ['origin', current])
1064 1064 return True
1065 1065 else:
1066 1066 self._ui.warn(_('no branch checked out in subrepo %s\n'
1067 1067 'cannot push revision %s') %
1068 1068 (self._relpath, self._state[1]))
1069 1069 return False
1070 1070
1071 1071 def remove(self):
1072 1072 if self._gitmissing():
1073 1073 return
1074 1074 if self.dirty():
1075 1075 self._ui.warn(_('not removing repo %s because '
1076 1076 'it has changes.\n') % self._relpath)
1077 1077 return
1078 1078 # we can't fully delete the repository as it may contain
1079 1079 # local-only history
1080 1080 self._ui.note(_('removing subrepo %s\n') % self._relpath)
1081 1081 self._gitcommand(['config', 'core.bare', 'true'])
1082 1082 for f in os.listdir(self._abspath):
1083 1083 if f == '.git':
1084 1084 continue
1085 1085 path = os.path.join(self._abspath, f)
1086 1086 if os.path.isdir(path) and not os.path.islink(path):
1087 1087 shutil.rmtree(path)
1088 1088 else:
1089 1089 os.remove(path)
1090 1090
1091 1091 def archive(self, ui, archiver, prefix):
1092 1092 source, revision = self._state
1093 1093 if not revision:
1094 1094 return
1095 1095 self._fetch(source, revision)
1096 1096
1097 1097 # Parse git's native archive command.
1098 1098 # This should be much faster than manually traversing the trees
1099 1099 # and objects with many subprocess calls.
1100 1100 tarstream = self._gitcommand(['archive', revision], stream=True)
1101 1101 tar = tarfile.open(fileobj=tarstream, mode='r|')
1102 1102 relpath = subrelpath(self)
1103 1103 ui.progress(_('archiving (%s)') % relpath, 0, unit=_('files'))
1104 1104 for i, info in enumerate(tar):
1105 1105 if info.isdir():
1106 1106 continue
1107 1107 if info.issym():
1108 1108 data = info.linkname
1109 1109 else:
1110 1110 data = tar.extractfile(info).read()
1111 1111 archiver.addfile(os.path.join(prefix, self._path, info.name),
1112 1112 info.mode, info.issym(), data)
1113 1113 ui.progress(_('archiving (%s)') % relpath, i + 1,
1114 1114 unit=_('files'))
1115 1115 ui.progress(_('archiving (%s)') % relpath, None)
1116 1116
1117 1117
1118 1118 def status(self, rev2, **opts):
1119 1119 rev1 = self._state[1]
1120 1120 if self._gitmissing() or not rev1:
1121 1121 # if the repo is missing, return no results
1122 1122 return [], [], [], [], [], [], []
1123 1123 modified, added, removed = [], [], []
1124 1124 self._gitupdatestat()
1125 1125 if rev2:
1126 1126 command = ['diff-tree', rev1, rev2]
1127 1127 else:
1128 1128 command = ['diff-index', rev1]
1129 1129 out = self._gitcommand(command)
1130 1130 for line in out.split('\n'):
1131 1131 tab = line.find('\t')
1132 1132 if tab == -1:
1133 1133 continue
1134 1134 status, f = line[tab - 1], line[tab + 1:]
1135 1135 if status == 'M':
1136 1136 modified.append(f)
1137 1137 elif status == 'A':
1138 1138 added.append(f)
1139 1139 elif status == 'D':
1140 1140 removed.append(f)
1141 1141
1142 1142 deleted = unknown = ignored = clean = []
1143 1143 return modified, added, removed, deleted, unknown, ignored, clean
1144 1144
1145 1145 types = {
1146 1146 'hg': hgsubrepo,
1147 1147 'svn': svnsubrepo,
1148 1148 'git': gitsubrepo,
1149 1149 }
@@ -1,496 +1,490 b''
1 1 Create test repository:
2 2
3 3 $ hg init repo
4 4 $ cd repo
5 5 $ echo x1 > x.txt
6 6
7 7 $ hg init foo
8 8 $ cd foo
9 9 $ echo y1 > y.txt
10 10
11 11 $ hg init bar
12 12 $ cd bar
13 13 $ echo z1 > z.txt
14 14
15 15 $ cd ..
16 16 $ echo 'bar = bar' > .hgsub
17 17
18 18 $ cd ..
19 19 $ echo 'foo = foo' > .hgsub
20 20
21 21 Add files --- .hgsub files must go first to trigger subrepos:
22 22
23 23 $ hg add -S .hgsub
24 24 $ hg add -S foo/.hgsub
25 25 $ hg add -S foo/bar
26 26 adding foo/bar/z.txt (glob)
27 27 $ hg add -S
28 28 adding x.txt
29 29 adding foo/y.txt (glob)
30 30
31 31 Test recursive status without committing anything:
32 32
33 33 $ hg status -S
34 34 A .hgsub
35 35 A foo/.hgsub
36 36 A foo/bar/z.txt
37 37 A foo/y.txt
38 38 A x.txt
39 39
40 40 Test recursive diff without committing anything:
41 41
42 42 $ hg diff --nodates -S foo
43 43 diff -r 000000000000 foo/.hgsub
44 44 --- /dev/null
45 45 +++ b/foo/.hgsub
46 46 @@ -0,0 +1,1 @@
47 47 +bar = bar
48 48 diff -r 000000000000 foo/y.txt
49 49 --- /dev/null
50 50 +++ b/foo/y.txt
51 51 @@ -0,0 +1,1 @@
52 52 +y1
53 53 diff -r 000000000000 foo/bar/z.txt
54 54 --- /dev/null
55 55 +++ b/foo/bar/z.txt
56 56 @@ -0,0 +1,1 @@
57 57 +z1
58 58
59 59 Commits:
60 60
61 61 $ hg commit -m fails
62 62 abort: uncommitted changes in subrepo foo
63 63 (use --subrepos for recursive commit)
64 64 [255]
65 65
66 66 The --subrepos flag overwrite the config setting:
67 67
68 68 $ hg commit -m 0-0-0 --config ui.commitsubrepos=No --subrepos
69 69 committing subrepository foo
70 70 committing subrepository foo/bar (glob)
71 71
72 72 $ cd foo
73 73 $ echo y2 >> y.txt
74 74 $ hg commit -m 0-1-0
75 75
76 76 $ cd bar
77 77 $ echo z2 >> z.txt
78 78 $ hg commit -m 0-1-1
79 79
80 80 $ cd ..
81 81 $ hg commit -m 0-2-1
82 82 committing subrepository bar
83 83
84 84 $ cd ..
85 85 $ hg commit -m 1-2-1
86 86 committing subrepository foo
87 87
88 88 Change working directory:
89 89
90 90 $ echo y3 >> foo/y.txt
91 91 $ echo z3 >> foo/bar/z.txt
92 92 $ hg status -S
93 93 M foo/bar/z.txt
94 94 M foo/y.txt
95 95 $ hg diff --nodates -S
96 96 diff -r d254738c5f5e foo/y.txt
97 97 --- a/foo/y.txt
98 98 +++ b/foo/y.txt
99 99 @@ -1,2 +1,3 @@
100 100 y1
101 101 y2
102 102 +y3
103 103 diff -r 9647f22de499 foo/bar/z.txt
104 104 --- a/foo/bar/z.txt
105 105 +++ b/foo/bar/z.txt
106 106 @@ -1,2 +1,3 @@
107 107 z1
108 108 z2
109 109 +z3
110 110
111 111 Status call crossing repository boundaries:
112 112
113 113 $ hg status -S foo/bar/z.txt
114 114 M foo/bar/z.txt
115 115 $ hg status -S -I 'foo/?.txt'
116 116 M foo/y.txt
117 117 $ hg status -S -I '**/?.txt'
118 118 M foo/bar/z.txt
119 119 M foo/y.txt
120 120 $ hg diff --nodates -S -I '**/?.txt'
121 121 diff -r d254738c5f5e foo/y.txt
122 122 --- a/foo/y.txt
123 123 +++ b/foo/y.txt
124 124 @@ -1,2 +1,3 @@
125 125 y1
126 126 y2
127 127 +y3
128 128 diff -r 9647f22de499 foo/bar/z.txt
129 129 --- a/foo/bar/z.txt
130 130 +++ b/foo/bar/z.txt
131 131 @@ -1,2 +1,3 @@
132 132 z1
133 133 z2
134 134 +z3
135 135
136 136 Status from within a subdirectory:
137 137
138 138 $ mkdir dir
139 139 $ cd dir
140 140 $ echo a1 > a.txt
141 141 $ hg status -S
142 142 M foo/bar/z.txt
143 143 M foo/y.txt
144 144 ? dir/a.txt
145 145 $ hg diff --nodates -S
146 146 diff -r d254738c5f5e foo/y.txt
147 147 --- a/foo/y.txt
148 148 +++ b/foo/y.txt
149 149 @@ -1,2 +1,3 @@
150 150 y1
151 151 y2
152 152 +y3
153 153 diff -r 9647f22de499 foo/bar/z.txt
154 154 --- a/foo/bar/z.txt
155 155 +++ b/foo/bar/z.txt
156 156 @@ -1,2 +1,3 @@
157 157 z1
158 158 z2
159 159 +z3
160 160
161 161 Status with relative path:
162 162
163 163 $ hg status -S ..
164 164 M ../foo/bar/z.txt
165 165 M ../foo/y.txt
166 166 ? a.txt
167 167 $ hg diff --nodates -S ..
168 168 diff -r d254738c5f5e foo/y.txt
169 169 --- a/foo/y.txt
170 170 +++ b/foo/y.txt
171 171 @@ -1,2 +1,3 @@
172 172 y1
173 173 y2
174 174 +y3
175 175 diff -r 9647f22de499 foo/bar/z.txt
176 176 --- a/foo/bar/z.txt
177 177 +++ b/foo/bar/z.txt
178 178 @@ -1,2 +1,3 @@
179 179 z1
180 180 z2
181 181 +z3
182 182 $ cd ..
183 183
184 184 Cleanup and final commit:
185 185
186 186 $ rm -r dir
187 187 $ hg commit --subrepos -m 2-3-2
188 188 committing subrepository foo
189 189 committing subrepository foo/bar (glob)
190 190
191 191 Test explicit path commands within subrepos: add/forget
192 192 $ echo z1 > foo/bar/z2.txt
193 193 $ hg status -S
194 194 ? foo/bar/z2.txt
195 195 $ hg add foo/bar/z2.txt
196 196 $ hg status -S
197 197 A foo/bar/z2.txt
198 198 This is expected to forget the file, but is currently broken
199 199 $ hg forget foo/bar/z2.txt
200 not removing foo/bar/z2.txt: file is already untracked
201 [1]
202 $ hg status -S
203 A foo/bar/z2.txt
204 When fixed, remove the next two commands
205 $ hg forget -R foo/bar foo/bar/z2.txt
206 200 $ hg status -S
207 201 ? foo/bar/z2.txt
208 202 $ rm foo/bar/z2.txt
209 203
210 204 Log with the relationships between repo and its subrepo:
211 205
212 206 $ hg log --template '{rev}:{node|short} {desc}\n'
213 207 2:1326fa26d0c0 2-3-2
214 208 1:4b3c9ff4f66b 1-2-1
215 209 0:23376cbba0d8 0-0-0
216 210
217 211 $ hg -R foo log --template '{rev}:{node|short} {desc}\n'
218 212 3:65903cebad86 2-3-2
219 213 2:d254738c5f5e 0-2-1
220 214 1:8629ce7dcc39 0-1-0
221 215 0:af048e97ade2 0-0-0
222 216
223 217 $ hg -R foo/bar log --template '{rev}:{node|short} {desc}\n'
224 218 2:31ecbdafd357 2-3-2
225 219 1:9647f22de499 0-1-1
226 220 0:4904098473f9 0-0-0
227 221
228 222 Status between revisions:
229 223
230 224 $ hg status -S
231 225 $ hg status -S --rev 0:1
232 226 M .hgsubstate
233 227 M foo/.hgsubstate
234 228 M foo/bar/z.txt
235 229 M foo/y.txt
236 230 $ hg diff --nodates -S -I '**/?.txt' --rev 0:1
237 231 diff -r af048e97ade2 -r d254738c5f5e foo/y.txt
238 232 --- a/foo/y.txt
239 233 +++ b/foo/y.txt
240 234 @@ -1,1 +1,2 @@
241 235 y1
242 236 +y2
243 237 diff -r 4904098473f9 -r 9647f22de499 foo/bar/z.txt
244 238 --- a/foo/bar/z.txt
245 239 +++ b/foo/bar/z.txt
246 240 @@ -1,1 +1,2 @@
247 241 z1
248 242 +z2
249 243
250 244 Enable progress extension for archive tests:
251 245
252 246 $ cp $HGRCPATH $HGRCPATH.no-progress
253 247 $ cat >> $HGRCPATH <<EOF
254 248 > [extensions]
255 249 > progress =
256 250 > [progress]
257 251 > assume-tty = 1
258 252 > delay = 0
259 253 > format = topic bar number
260 254 > refresh = 0
261 255 > width = 60
262 256 > EOF
263 257
264 258 Test archiving to a directory tree (the doubled lines in the output
265 259 only show up in the test output, not in real usage):
266 260
267 261 $ hg archive --subrepos ../archive 2>&1 | $TESTDIR/filtercr.py
268 262
269 263 archiving [ ] 0/3
270 264 archiving [ ] 0/3
271 265 archiving [=============> ] 1/3
272 266 archiving [=============> ] 1/3
273 267 archiving [===========================> ] 2/3
274 268 archiving [===========================> ] 2/3
275 269 archiving [==========================================>] 3/3
276 270 archiving [==========================================>] 3/3
277 271
278 272 archiving (foo) [ ] 0/3
279 273 archiving (foo) [ ] 0/3
280 274 archiving (foo) [===========> ] 1/3
281 275 archiving (foo) [===========> ] 1/3
282 276 archiving (foo) [=======================> ] 2/3
283 277 archiving (foo) [=======================> ] 2/3
284 278 archiving (foo) [====================================>] 3/3
285 279 archiving (foo) [====================================>] 3/3
286 280
287 281 archiving (foo/bar) [ ] 0/1 (glob)
288 282 archiving (foo/bar) [ ] 0/1 (glob)
289 283 archiving (foo/bar) [================================>] 1/1 (glob)
290 284 archiving (foo/bar) [================================>] 1/1 (glob)
291 285 \r (esc)
292 286 $ find ../archive | sort
293 287 ../archive
294 288 ../archive/.hg_archival.txt
295 289 ../archive/.hgsub
296 290 ../archive/.hgsubstate
297 291 ../archive/foo
298 292 ../archive/foo/.hgsub
299 293 ../archive/foo/.hgsubstate
300 294 ../archive/foo/bar
301 295 ../archive/foo/bar/z.txt
302 296 ../archive/foo/y.txt
303 297 ../archive/x.txt
304 298
305 299 Test archiving to zip file (unzip output is unstable):
306 300
307 301 $ hg archive --subrepos ../archive.zip 2>&1 | $TESTDIR/filtercr.py
308 302
309 303 archiving [ ] 0/3
310 304 archiving [ ] 0/3
311 305 archiving [=============> ] 1/3
312 306 archiving [=============> ] 1/3
313 307 archiving [===========================> ] 2/3
314 308 archiving [===========================> ] 2/3
315 309 archiving [==========================================>] 3/3
316 310 archiving [==========================================>] 3/3
317 311
318 312 archiving (foo) [ ] 0/3
319 313 archiving (foo) [ ] 0/3
320 314 archiving (foo) [===========> ] 1/3
321 315 archiving (foo) [===========> ] 1/3
322 316 archiving (foo) [=======================> ] 2/3
323 317 archiving (foo) [=======================> ] 2/3
324 318 archiving (foo) [====================================>] 3/3
325 319 archiving (foo) [====================================>] 3/3
326 320
327 321 archiving (foo/bar) [ ] 0/1 (glob)
328 322 archiving (foo/bar) [ ] 0/1 (glob)
329 323 archiving (foo/bar) [================================>] 1/1 (glob)
330 324 archiving (foo/bar) [================================>] 1/1 (glob)
331 325 \r (esc)
332 326
333 327 Test archiving a revision that references a subrepo that is not yet
334 328 cloned:
335 329
336 330 $ hg clone -U . ../empty
337 331 $ cd ../empty
338 332 $ hg archive --subrepos -r tip ../archive.tar.gz 2>&1 | $TESTDIR/filtercr.py
339 333
340 334 archiving [ ] 0/3
341 335 archiving [ ] 0/3
342 336 archiving [=============> ] 1/3
343 337 archiving [=============> ] 1/3
344 338 archiving [===========================> ] 2/3
345 339 archiving [===========================> ] 2/3
346 340 archiving [==========================================>] 3/3
347 341 archiving [==========================================>] 3/3
348 342
349 343 archiving (foo) [ ] 0/3
350 344 archiving (foo) [ ] 0/3
351 345 archiving (foo) [===========> ] 1/3
352 346 archiving (foo) [===========> ] 1/3
353 347 archiving (foo) [=======================> ] 2/3
354 348 archiving (foo) [=======================> ] 2/3
355 349 archiving (foo) [====================================>] 3/3
356 350 archiving (foo) [====================================>] 3/3
357 351
358 352 archiving (foo/bar) [ ] 0/1 (glob)
359 353 archiving (foo/bar) [ ] 0/1 (glob)
360 354 archiving (foo/bar) [================================>] 1/1 (glob)
361 355 archiving (foo/bar) [================================>] 1/1 (glob)
362 356
363 357 cloning subrepo foo from $TESTTMP/repo/foo
364 358 cloning subrepo foo/bar from $TESTTMP/repo/foo/bar (glob)
365 359
366 360 The newly cloned subrepos contain no working copy:
367 361
368 362 $ hg -R foo summary
369 363 parent: -1:000000000000 (no revision checked out)
370 364 branch: default
371 365 commit: (clean)
372 366 update: 4 new changesets (update)
373 367
374 368 Disable progress extension and cleanup:
375 369
376 370 $ mv $HGRCPATH.no-progress $HGRCPATH
377 371
378 372 Test archiving when there is a directory in the way for a subrepo
379 373 created by archive:
380 374
381 375 $ hg clone -U . ../almost-empty
382 376 $ cd ../almost-empty
383 377 $ mkdir foo
384 378 $ echo f > foo/f
385 379 $ hg archive --subrepos -r tip archive
386 380 cloning subrepo foo from $TESTTMP/empty/foo
387 381 abort: destination '$TESTTMP/almost-empty/foo' is not empty (glob)
388 382 [255]
389 383
390 384 Clone and test outgoing:
391 385
392 386 $ cd ..
393 387 $ hg clone repo repo2
394 388 updating to branch default
395 389 cloning subrepo foo from $TESTTMP/repo/foo
396 390 cloning subrepo foo/bar from $TESTTMP/repo/foo/bar (glob)
397 391 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
398 392 $ cd repo2
399 393 $ hg outgoing -S
400 394 comparing with $TESTTMP/repo (glob)
401 395 searching for changes
402 396 no changes found
403 397 comparing with $TESTTMP/repo/foo
404 398 searching for changes
405 399 no changes found
406 400 comparing with $TESTTMP/repo/foo/bar
407 401 searching for changes
408 402 no changes found
409 403 [1]
410 404
411 405 Make nested change:
412 406
413 407 $ echo y4 >> foo/y.txt
414 408 $ hg diff --nodates -S
415 409 diff -r 65903cebad86 foo/y.txt
416 410 --- a/foo/y.txt
417 411 +++ b/foo/y.txt
418 412 @@ -1,3 +1,4 @@
419 413 y1
420 414 y2
421 415 y3
422 416 +y4
423 417 $ hg commit --subrepos -m 3-4-2
424 418 committing subrepository foo
425 419 $ hg outgoing -S
426 420 comparing with $TESTTMP/repo (glob)
427 421 searching for changes
428 422 changeset: 3:2655b8ecc4ee
429 423 tag: tip
430 424 user: test
431 425 date: Thu Jan 01 00:00:00 1970 +0000
432 426 summary: 3-4-2
433 427
434 428 comparing with $TESTTMP/repo/foo
435 429 searching for changes
436 430 changeset: 4:e96193d6cb36
437 431 tag: tip
438 432 user: test
439 433 date: Thu Jan 01 00:00:00 1970 +0000
440 434 summary: 3-4-2
441 435
442 436 comparing with $TESTTMP/repo/foo/bar
443 437 searching for changes
444 438 no changes found
445 439
446 440
447 441 Switch to original repo and setup default path:
448 442
449 443 $ cd ../repo
450 444 $ echo '[paths]' >> .hg/hgrc
451 445 $ echo 'default = ../repo2' >> .hg/hgrc
452 446
453 447 Test incoming:
454 448
455 449 $ hg incoming -S
456 450 comparing with $TESTTMP/repo2 (glob)
457 451 searching for changes
458 452 changeset: 3:2655b8ecc4ee
459 453 tag: tip
460 454 user: test
461 455 date: Thu Jan 01 00:00:00 1970 +0000
462 456 summary: 3-4-2
463 457
464 458 comparing with $TESTTMP/repo2/foo
465 459 searching for changes
466 460 changeset: 4:e96193d6cb36
467 461 tag: tip
468 462 user: test
469 463 date: Thu Jan 01 00:00:00 1970 +0000
470 464 summary: 3-4-2
471 465
472 466 comparing with $TESTTMP/repo2/foo/bar
473 467 searching for changes
474 468 no changes found
475 469
476 470 $ hg incoming -S --bundle incoming.hg
477 471 abort: cannot combine --bundle and --subrepos
478 472 [255]
479 473
480 474 Test missing subrepo:
481 475
482 476 $ rm -r foo
483 477 $ hg status -S
484 478 warning: error "unknown revision '65903cebad86f1a84bd4f1134f62fa7dcb7a1c98'" in subrepository "foo"
485 479
486 480 Issue2619: IndexError: list index out of range on hg add with subrepos
487 481 The subrepo must sorts after the explicit filename.
488 482
489 483 $ cd ..
490 484 $ hg init test
491 485 $ cd test
492 486 $ hg init x
493 487 $ echo "x = x" >> .hgsub
494 488 $ hg add .hgsub
495 489 $ touch a x/a
496 490 $ hg add a x/a
General Comments 0
You need to be logged in to leave comments. Login now