##// END OF EJS Templates
formatter: add general way to switch hex/short functions...
Yuya Nishihara -
r22701:cb28d2b3 default
parent child Browse files
Show More
@@ -1,6318 +1,6312 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 _
11 11 import os, re, difflib, time, tempfile, errno, shlex
12 12 import sys, socket
13 13 import hg, scmutil, util, revlog, copies, error, bookmarks
14 14 import patch, help, encoding, templatekw, discovery
15 15 import archival, changegroup, cmdutil, hbisect
16 16 import sshserver, hgweb, commandserver
17 17 import extensions
18 18 from hgweb import server as hgweb_server
19 19 import merge as mergemod
20 20 import minirst, revset, fileset
21 21 import dagparser, context, simplemerge, graphmod
22 22 import random
23 23 import setdiscovery, treediscovery, dagutil, pvec, localrepo
24 24 import phases, obsolete, exchange
25 25
26 26 table = {}
27 27
28 28 command = cmdutil.command(table)
29 29
30 30 # Space delimited list of commands that don't require local repositories.
31 31 # This should be populated by passing norepo=True into the @command decorator.
32 32 norepo = ''
33 33 # Space delimited list of commands that optionally require local repositories.
34 34 # This should be populated by passing optionalrepo=True into the @command
35 35 # decorator.
36 36 optionalrepo = ''
37 37 # Space delimited list of commands that will examine arguments looking for
38 38 # a repository. This should be populated by passing inferrepo=True into the
39 39 # @command decorator.
40 40 inferrepo = ''
41 41
42 42 # common command options
43 43
44 44 globalopts = [
45 45 ('R', 'repository', '',
46 46 _('repository root directory or name of overlay bundle file'),
47 47 _('REPO')),
48 48 ('', 'cwd', '',
49 49 _('change working directory'), _('DIR')),
50 50 ('y', 'noninteractive', None,
51 51 _('do not prompt, automatically pick the first choice for all prompts')),
52 52 ('q', 'quiet', None, _('suppress output')),
53 53 ('v', 'verbose', None, _('enable additional output')),
54 54 ('', 'config', [],
55 55 _('set/override config option (use \'section.name=value\')'),
56 56 _('CONFIG')),
57 57 ('', 'debug', None, _('enable debugging output')),
58 58 ('', 'debugger', None, _('start debugger')),
59 59 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
60 60 _('ENCODE')),
61 61 ('', 'encodingmode', encoding.encodingmode,
62 62 _('set the charset encoding mode'), _('MODE')),
63 63 ('', 'traceback', None, _('always print a traceback on exception')),
64 64 ('', 'time', None, _('time how long the command takes')),
65 65 ('', 'profile', None, _('print command execution profile')),
66 66 ('', 'version', None, _('output version information and exit')),
67 67 ('h', 'help', None, _('display help and exit')),
68 68 ('', 'hidden', False, _('consider hidden changesets')),
69 69 ]
70 70
71 71 dryrunopts = [('n', 'dry-run', None,
72 72 _('do not perform actions, just print output'))]
73 73
74 74 remoteopts = [
75 75 ('e', 'ssh', '',
76 76 _('specify ssh command to use'), _('CMD')),
77 77 ('', 'remotecmd', '',
78 78 _('specify hg command to run on the remote side'), _('CMD')),
79 79 ('', 'insecure', None,
80 80 _('do not verify server certificate (ignoring web.cacerts config)')),
81 81 ]
82 82
83 83 walkopts = [
84 84 ('I', 'include', [],
85 85 _('include names matching the given patterns'), _('PATTERN')),
86 86 ('X', 'exclude', [],
87 87 _('exclude names matching the given patterns'), _('PATTERN')),
88 88 ]
89 89
90 90 commitopts = [
91 91 ('m', 'message', '',
92 92 _('use text as commit message'), _('TEXT')),
93 93 ('l', 'logfile', '',
94 94 _('read commit message from file'), _('FILE')),
95 95 ]
96 96
97 97 commitopts2 = [
98 98 ('d', 'date', '',
99 99 _('record the specified date as commit date'), _('DATE')),
100 100 ('u', 'user', '',
101 101 _('record the specified user as committer'), _('USER')),
102 102 ]
103 103
104 104 # hidden for now
105 105 formatteropts = [
106 106 ('T', 'template', '',
107 107 _('display with template (DEPRECATED)'), _('TEMPLATE')),
108 108 ]
109 109
110 110 templateopts = [
111 111 ('', 'style', '',
112 112 _('display using template map file (DEPRECATED)'), _('STYLE')),
113 113 ('T', 'template', '',
114 114 _('display with template'), _('TEMPLATE')),
115 115 ]
116 116
117 117 logopts = [
118 118 ('p', 'patch', None, _('show patch')),
119 119 ('g', 'git', None, _('use git extended diff format')),
120 120 ('l', 'limit', '',
121 121 _('limit number of changes displayed'), _('NUM')),
122 122 ('M', 'no-merges', None, _('do not show merges')),
123 123 ('', 'stat', None, _('output diffstat-style summary of changes')),
124 124 ('G', 'graph', None, _("show the revision DAG")),
125 125 ] + templateopts
126 126
127 127 diffopts = [
128 128 ('a', 'text', None, _('treat all files as text')),
129 129 ('g', 'git', None, _('use git extended diff format')),
130 130 ('', 'nodates', None, _('omit dates from diff headers'))
131 131 ]
132 132
133 133 diffwsopts = [
134 134 ('w', 'ignore-all-space', None,
135 135 _('ignore white space when comparing lines')),
136 136 ('b', 'ignore-space-change', None,
137 137 _('ignore changes in the amount of white space')),
138 138 ('B', 'ignore-blank-lines', None,
139 139 _('ignore changes whose lines are all blank')),
140 140 ]
141 141
142 142 diffopts2 = [
143 143 ('p', 'show-function', None, _('show which function each change is in')),
144 144 ('', 'reverse', None, _('produce a diff that undoes the changes')),
145 145 ] + diffwsopts + [
146 146 ('U', 'unified', '',
147 147 _('number of lines of context to show'), _('NUM')),
148 148 ('', 'stat', None, _('output diffstat-style summary of changes')),
149 149 ]
150 150
151 151 mergetoolopts = [
152 152 ('t', 'tool', '', _('specify merge tool')),
153 153 ]
154 154
155 155 similarityopts = [
156 156 ('s', 'similarity', '',
157 157 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
158 158 ]
159 159
160 160 subrepoopts = [
161 161 ('S', 'subrepos', None,
162 162 _('recurse into subrepositories'))
163 163 ]
164 164
165 165 # Commands start here, listed alphabetically
166 166
167 167 @command('^add',
168 168 walkopts + subrepoopts + dryrunopts,
169 169 _('[OPTION]... [FILE]...'),
170 170 inferrepo=True)
171 171 def add(ui, repo, *pats, **opts):
172 172 """add the specified files on the next commit
173 173
174 174 Schedule files to be version controlled and added to the
175 175 repository.
176 176
177 177 The files will be added to the repository at the next commit. To
178 178 undo an add before that, see :hg:`forget`.
179 179
180 180 If no names are given, add all files to the repository.
181 181
182 182 .. container:: verbose
183 183
184 184 An example showing how new (unknown) files are added
185 185 automatically by :hg:`add`::
186 186
187 187 $ ls
188 188 foo.c
189 189 $ hg status
190 190 ? foo.c
191 191 $ hg add
192 192 adding foo.c
193 193 $ hg status
194 194 A foo.c
195 195
196 196 Returns 0 if all files are successfully added.
197 197 """
198 198
199 199 m = scmutil.match(repo[None], pats, opts)
200 200 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
201 201 opts.get('subrepos'), prefix="", explicitonly=False)
202 202 return rejected and 1 or 0
203 203
204 204 @command('addremove',
205 205 similarityopts + walkopts + dryrunopts,
206 206 _('[OPTION]... [FILE]...'),
207 207 inferrepo=True)
208 208 def addremove(ui, repo, *pats, **opts):
209 209 """add all new files, delete all missing files
210 210
211 211 Add all new files and remove all missing files from the
212 212 repository.
213 213
214 214 New files are ignored if they match any of the patterns in
215 215 ``.hgignore``. As with add, these changes take effect at the next
216 216 commit.
217 217
218 218 Use the -s/--similarity option to detect renamed files. This
219 219 option takes a percentage between 0 (disabled) and 100 (files must
220 220 be identical) as its parameter. With a parameter greater than 0,
221 221 this compares every removed file with every added file and records
222 222 those similar enough as renames. Detecting renamed files this way
223 223 can be expensive. After using this option, :hg:`status -C` can be
224 224 used to check which files were identified as moved or renamed. If
225 225 not specified, -s/--similarity defaults to 100 and only renames of
226 226 identical files are detected.
227 227
228 228 Returns 0 if all files are successfully added.
229 229 """
230 230 try:
231 231 sim = float(opts.get('similarity') or 100)
232 232 except ValueError:
233 233 raise util.Abort(_('similarity must be a number'))
234 234 if sim < 0 or sim > 100:
235 235 raise util.Abort(_('similarity must be between 0 and 100'))
236 236 return scmutil.addremove(repo, pats, opts, similarity=sim / 100.0)
237 237
238 238 @command('^annotate|blame',
239 239 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
240 240 ('', 'follow', None,
241 241 _('follow copies/renames and list the filename (DEPRECATED)')),
242 242 ('', 'no-follow', None, _("don't follow copies and renames")),
243 243 ('a', 'text', None, _('treat all files as text')),
244 244 ('u', 'user', None, _('list the author (long with -v)')),
245 245 ('f', 'file', None, _('list the filename')),
246 246 ('d', 'date', None, _('list the date (short with -q)')),
247 247 ('n', 'number', None, _('list the revision number (default)')),
248 248 ('c', 'changeset', None, _('list the changeset')),
249 249 ('l', 'line-number', None, _('show line number at the first appearance'))
250 250 ] + diffwsopts + walkopts + formatteropts,
251 251 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
252 252 inferrepo=True)
253 253 def annotate(ui, repo, *pats, **opts):
254 254 """show changeset information by line for each file
255 255
256 256 List changes in files, showing the revision id responsible for
257 257 each line
258 258
259 259 This command is useful for discovering when a change was made and
260 260 by whom.
261 261
262 262 Without the -a/--text option, annotate will avoid processing files
263 263 it detects as binary. With -a, annotate will annotate the file
264 264 anyway, although the results will probably be neither useful
265 265 nor desirable.
266 266
267 267 Returns 0 on success.
268 268 """
269 269 if not pats:
270 270 raise util.Abort(_('at least one filename or pattern is required'))
271 271
272 272 if opts.get('follow'):
273 273 # --follow is deprecated and now just an alias for -f/--file
274 274 # to mimic the behavior of Mercurial before version 1.5
275 275 opts['file'] = True
276 276
277 277 fm = ui.formatter('annotate', opts)
278 278 datefunc = ui.quiet and util.shortdate or util.datestr
279 if fm or ui.debugflag:
280 hexfn = hex
281 else:
282 hexfn = short
279 hexfn = fm.hexfunc
283 280
284 281 opmap = [('user', ' ', lambda x: x[0].user(), ui.shortuser),
285 282 ('number', ' ', lambda x: x[0].rev(), str),
286 283 ('changeset', ' ', lambda x: hexfn(x[0].node()), str),
287 284 ('date', ' ', lambda x: x[0].date(), util.cachefunc(datefunc)),
288 285 ('file', ' ', lambda x: x[0].path(), str),
289 286 ('line_number', ':', lambda x: x[1], str),
290 287 ]
291 288 fieldnamemap = {'number': 'rev', 'changeset': 'node'}
292 289
293 290 if (not opts.get('user') and not opts.get('changeset')
294 291 and not opts.get('date') and not opts.get('file')):
295 292 opts['number'] = True
296 293
297 294 linenumber = opts.get('line_number') is not None
298 295 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
299 296 raise util.Abort(_('at least one of -n/-c is required for -l'))
300 297
301 298 if fm:
302 299 def makefunc(get, fmt):
303 300 return get
304 301 else:
305 302 def makefunc(get, fmt):
306 303 return lambda x: fmt(get(x))
307 304 funcmap = [(makefunc(get, fmt), sep) for op, sep, get, fmt in opmap
308 305 if opts.get(op)]
309 306 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
310 307 fields = ' '.join(fieldnamemap.get(op, op) for op, sep, get, fmt in opmap
311 308 if opts.get(op))
312 309
313 310 def bad(x, y):
314 311 raise util.Abort("%s: %s" % (x, y))
315 312
316 313 ctx = scmutil.revsingle(repo, opts.get('rev'))
317 314 m = scmutil.match(ctx, pats, opts)
318 315 m.bad = bad
319 316 follow = not opts.get('no_follow')
320 317 diffopts = patch.diffopts(ui, opts, section='annotate')
321 318 for abs in ctx.walk(m):
322 319 fctx = ctx[abs]
323 320 if not opts.get('text') and util.binary(fctx.data()):
324 321 fm.plain(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
325 322 continue
326 323
327 324 lines = fctx.annotate(follow=follow, linenumber=linenumber,
328 325 diffopts=diffopts)
329 326 formats = []
330 327 pieces = []
331 328
332 329 for f, sep in funcmap:
333 330 l = [f(n) for n, dummy in lines]
334 331 if l:
335 332 if fm:
336 333 formats.append(['%s' for x in l])
337 334 else:
338 335 sizes = [encoding.colwidth(x) for x in l]
339 336 ml = max(sizes)
340 337 formats.append([sep + ' ' * (ml - w) + '%s' for w in sizes])
341 338 pieces.append(l)
342 339
343 340 for f, p, l in zip(zip(*formats), zip(*pieces), lines):
344 341 fm.startitem()
345 342 fm.write(fields, "".join(f), *p)
346 343 fm.write('line', ": %s", l[1])
347 344
348 345 if lines and not lines[-1][1].endswith('\n'):
349 346 fm.plain('\n')
350 347
351 348 fm.end()
352 349
353 350 @command('archive',
354 351 [('', 'no-decode', None, _('do not pass files through decoders')),
355 352 ('p', 'prefix', '', _('directory prefix for files in archive'),
356 353 _('PREFIX')),
357 354 ('r', 'rev', '', _('revision to distribute'), _('REV')),
358 355 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
359 356 ] + subrepoopts + walkopts,
360 357 _('[OPTION]... DEST'))
361 358 def archive(ui, repo, dest, **opts):
362 359 '''create an unversioned archive of a repository revision
363 360
364 361 By default, the revision used is the parent of the working
365 362 directory; use -r/--rev to specify a different revision.
366 363
367 364 The archive type is automatically detected based on file
368 365 extension (or override using -t/--type).
369 366
370 367 .. container:: verbose
371 368
372 369 Examples:
373 370
374 371 - create a zip file containing the 1.0 release::
375 372
376 373 hg archive -r 1.0 project-1.0.zip
377 374
378 375 - create a tarball excluding .hg files::
379 376
380 377 hg archive project.tar.gz -X ".hg*"
381 378
382 379 Valid types are:
383 380
384 381 :``files``: a directory full of files (default)
385 382 :``tar``: tar archive, uncompressed
386 383 :``tbz2``: tar archive, compressed using bzip2
387 384 :``tgz``: tar archive, compressed using gzip
388 385 :``uzip``: zip archive, uncompressed
389 386 :``zip``: zip archive, compressed using deflate
390 387
391 388 The exact name of the destination archive or directory is given
392 389 using a format string; see :hg:`help export` for details.
393 390
394 391 Each member added to an archive file has a directory prefix
395 392 prepended. Use -p/--prefix to specify a format string for the
396 393 prefix. The default is the basename of the archive, with suffixes
397 394 removed.
398 395
399 396 Returns 0 on success.
400 397 '''
401 398
402 399 ctx = scmutil.revsingle(repo, opts.get('rev'))
403 400 if not ctx:
404 401 raise util.Abort(_('no working directory: please specify a revision'))
405 402 node = ctx.node()
406 403 dest = cmdutil.makefilename(repo, dest, node)
407 404 if os.path.realpath(dest) == repo.root:
408 405 raise util.Abort(_('repository root cannot be destination'))
409 406
410 407 kind = opts.get('type') or archival.guesskind(dest) or 'files'
411 408 prefix = opts.get('prefix')
412 409
413 410 if dest == '-':
414 411 if kind == 'files':
415 412 raise util.Abort(_('cannot archive plain files to stdout'))
416 413 dest = cmdutil.makefileobj(repo, dest)
417 414 if not prefix:
418 415 prefix = os.path.basename(repo.root) + '-%h'
419 416
420 417 prefix = cmdutil.makefilename(repo, prefix, node)
421 418 matchfn = scmutil.match(ctx, [], opts)
422 419 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
423 420 matchfn, prefix, subrepos=opts.get('subrepos'))
424 421
425 422 @command('backout',
426 423 [('', 'merge', None, _('merge with old dirstate parent after backout')),
427 424 ('', 'parent', '',
428 425 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
429 426 ('r', 'rev', '', _('revision to backout'), _('REV')),
430 427 ('e', 'edit', False, _('invoke editor on commit messages')),
431 428 ] + mergetoolopts + walkopts + commitopts + commitopts2,
432 429 _('[OPTION]... [-r] REV'))
433 430 def backout(ui, repo, node=None, rev=None, **opts):
434 431 '''reverse effect of earlier changeset
435 432
436 433 Prepare a new changeset with the effect of REV undone in the
437 434 current working directory.
438 435
439 436 If REV is the parent of the working directory, then this new changeset
440 437 is committed automatically. Otherwise, hg needs to merge the
441 438 changes and the merged result is left uncommitted.
442 439
443 440 .. note::
444 441
445 442 backout cannot be used to fix either an unwanted or
446 443 incorrect merge.
447 444
448 445 .. container:: verbose
449 446
450 447 By default, the pending changeset will have one parent,
451 448 maintaining a linear history. With --merge, the pending
452 449 changeset will instead have two parents: the old parent of the
453 450 working directory and a new child of REV that simply undoes REV.
454 451
455 452 Before version 1.7, the behavior without --merge was equivalent
456 453 to specifying --merge followed by :hg:`update --clean .` to
457 454 cancel the merge and leave the child of REV as a head to be
458 455 merged separately.
459 456
460 457 See :hg:`help dates` for a list of formats valid for -d/--date.
461 458
462 459 Returns 0 on success, 1 if nothing to backout or there are unresolved
463 460 files.
464 461 '''
465 462 if rev and node:
466 463 raise util.Abort(_("please specify just one revision"))
467 464
468 465 if not rev:
469 466 rev = node
470 467
471 468 if not rev:
472 469 raise util.Abort(_("please specify a revision to backout"))
473 470
474 471 date = opts.get('date')
475 472 if date:
476 473 opts['date'] = util.parsedate(date)
477 474
478 475 cmdutil.checkunfinished(repo)
479 476 cmdutil.bailifchanged(repo)
480 477 node = scmutil.revsingle(repo, rev).node()
481 478
482 479 op1, op2 = repo.dirstate.parents()
483 480 if not repo.changelog.isancestor(node, op1):
484 481 raise util.Abort(_('cannot backout change that is not an ancestor'))
485 482
486 483 p1, p2 = repo.changelog.parents(node)
487 484 if p1 == nullid:
488 485 raise util.Abort(_('cannot backout a change with no parents'))
489 486 if p2 != nullid:
490 487 if not opts.get('parent'):
491 488 raise util.Abort(_('cannot backout a merge changeset'))
492 489 p = repo.lookup(opts['parent'])
493 490 if p not in (p1, p2):
494 491 raise util.Abort(_('%s is not a parent of %s') %
495 492 (short(p), short(node)))
496 493 parent = p
497 494 else:
498 495 if opts.get('parent'):
499 496 raise util.Abort(_('cannot use --parent on non-merge changeset'))
500 497 parent = p1
501 498
502 499 # the backout should appear on the same branch
503 500 wlock = repo.wlock()
504 501 try:
505 502 branch = repo.dirstate.branch()
506 503 bheads = repo.branchheads(branch)
507 504 rctx = scmutil.revsingle(repo, hex(parent))
508 505 if not opts.get('merge') and op1 != node:
509 506 try:
510 507 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
511 508 'backout')
512 509 repo.dirstate.beginparentchange()
513 510 stats = mergemod.update(repo, parent, True, True, False,
514 511 node, False)
515 512 repo.setparents(op1, op2)
516 513 repo.dirstate.endparentchange()
517 514 hg._showstats(repo, stats)
518 515 if stats[3]:
519 516 repo.ui.status(_("use 'hg resolve' to retry unresolved "
520 517 "file merges\n"))
521 518 else:
522 519 msg = _("changeset %s backed out, "
523 520 "don't forget to commit.\n")
524 521 ui.status(msg % short(node))
525 522 return stats[3] > 0
526 523 finally:
527 524 ui.setconfig('ui', 'forcemerge', '', '')
528 525 else:
529 526 hg.clean(repo, node, show_stats=False)
530 527 repo.dirstate.setbranch(branch)
531 528 cmdutil.revert(ui, repo, rctx, repo.dirstate.parents())
532 529
533 530
534 531 def commitfunc(ui, repo, message, match, opts):
535 532 editform = 'backout'
536 533 e = cmdutil.getcommiteditor(editform=editform, **opts)
537 534 if not message:
538 535 # we don't translate commit messages
539 536 message = "Backed out changeset %s" % short(node)
540 537 e = cmdutil.getcommiteditor(edit=True, editform=editform)
541 538 return repo.commit(message, opts.get('user'), opts.get('date'),
542 539 match, editor=e)
543 540 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
544 541 if not newnode:
545 542 ui.status(_("nothing changed\n"))
546 543 return 1
547 544 cmdutil.commitstatus(repo, newnode, branch, bheads)
548 545
549 546 def nice(node):
550 547 return '%d:%s' % (repo.changelog.rev(node), short(node))
551 548 ui.status(_('changeset %s backs out changeset %s\n') %
552 549 (nice(repo.changelog.tip()), nice(node)))
553 550 if opts.get('merge') and op1 != node:
554 551 hg.clean(repo, op1, show_stats=False)
555 552 ui.status(_('merging with changeset %s\n')
556 553 % nice(repo.changelog.tip()))
557 554 try:
558 555 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
559 556 'backout')
560 557 return hg.merge(repo, hex(repo.changelog.tip()))
561 558 finally:
562 559 ui.setconfig('ui', 'forcemerge', '', '')
563 560 finally:
564 561 wlock.release()
565 562 return 0
566 563
567 564 @command('bisect',
568 565 [('r', 'reset', False, _('reset bisect state')),
569 566 ('g', 'good', False, _('mark changeset good')),
570 567 ('b', 'bad', False, _('mark changeset bad')),
571 568 ('s', 'skip', False, _('skip testing changeset')),
572 569 ('e', 'extend', False, _('extend the bisect range')),
573 570 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
574 571 ('U', 'noupdate', False, _('do not update to target'))],
575 572 _("[-gbsr] [-U] [-c CMD] [REV]"))
576 573 def bisect(ui, repo, rev=None, extra=None, command=None,
577 574 reset=None, good=None, bad=None, skip=None, extend=None,
578 575 noupdate=None):
579 576 """subdivision search of changesets
580 577
581 578 This command helps to find changesets which introduce problems. To
582 579 use, mark the earliest changeset you know exhibits the problem as
583 580 bad, then mark the latest changeset which is free from the problem
584 581 as good. Bisect will update your working directory to a revision
585 582 for testing (unless the -U/--noupdate option is specified). Once
586 583 you have performed tests, mark the working directory as good or
587 584 bad, and bisect will either update to another candidate changeset
588 585 or announce that it has found the bad revision.
589 586
590 587 As a shortcut, you can also use the revision argument to mark a
591 588 revision as good or bad without checking it out first.
592 589
593 590 If you supply a command, it will be used for automatic bisection.
594 591 The environment variable HG_NODE will contain the ID of the
595 592 changeset being tested. The exit status of the command will be
596 593 used to mark revisions as good or bad: status 0 means good, 125
597 594 means to skip the revision, 127 (command not found) will abort the
598 595 bisection, and any other non-zero exit status means the revision
599 596 is bad.
600 597
601 598 .. container:: verbose
602 599
603 600 Some examples:
604 601
605 602 - start a bisection with known bad revision 34, and good revision 12::
606 603
607 604 hg bisect --bad 34
608 605 hg bisect --good 12
609 606
610 607 - advance the current bisection by marking current revision as good or
611 608 bad::
612 609
613 610 hg bisect --good
614 611 hg bisect --bad
615 612
616 613 - mark the current revision, or a known revision, to be skipped (e.g. if
617 614 that revision is not usable because of another issue)::
618 615
619 616 hg bisect --skip
620 617 hg bisect --skip 23
621 618
622 619 - skip all revisions that do not touch directories ``foo`` or ``bar``::
623 620
624 621 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
625 622
626 623 - forget the current bisection::
627 624
628 625 hg bisect --reset
629 626
630 627 - use 'make && make tests' to automatically find the first broken
631 628 revision::
632 629
633 630 hg bisect --reset
634 631 hg bisect --bad 34
635 632 hg bisect --good 12
636 633 hg bisect --command "make && make tests"
637 634
638 635 - see all changesets whose states are already known in the current
639 636 bisection::
640 637
641 638 hg log -r "bisect(pruned)"
642 639
643 640 - see the changeset currently being bisected (especially useful
644 641 if running with -U/--noupdate)::
645 642
646 643 hg log -r "bisect(current)"
647 644
648 645 - see all changesets that took part in the current bisection::
649 646
650 647 hg log -r "bisect(range)"
651 648
652 649 - you can even get a nice graph::
653 650
654 651 hg log --graph -r "bisect(range)"
655 652
656 653 See :hg:`help revsets` for more about the `bisect()` keyword.
657 654
658 655 Returns 0 on success.
659 656 """
660 657 def extendbisectrange(nodes, good):
661 658 # bisect is incomplete when it ends on a merge node and
662 659 # one of the parent was not checked.
663 660 parents = repo[nodes[0]].parents()
664 661 if len(parents) > 1:
665 662 side = good and state['bad'] or state['good']
666 663 num = len(set(i.node() for i in parents) & set(side))
667 664 if num == 1:
668 665 return parents[0].ancestor(parents[1])
669 666 return None
670 667
671 668 def print_result(nodes, good):
672 669 displayer = cmdutil.show_changeset(ui, repo, {})
673 670 if len(nodes) == 1:
674 671 # narrowed it down to a single revision
675 672 if good:
676 673 ui.write(_("The first good revision is:\n"))
677 674 else:
678 675 ui.write(_("The first bad revision is:\n"))
679 676 displayer.show(repo[nodes[0]])
680 677 extendnode = extendbisectrange(nodes, good)
681 678 if extendnode is not None:
682 679 ui.write(_('Not all ancestors of this changeset have been'
683 680 ' checked.\nUse bisect --extend to continue the '
684 681 'bisection from\nthe common ancestor, %s.\n')
685 682 % extendnode)
686 683 else:
687 684 # multiple possible revisions
688 685 if good:
689 686 ui.write(_("Due to skipped revisions, the first "
690 687 "good revision could be any of:\n"))
691 688 else:
692 689 ui.write(_("Due to skipped revisions, the first "
693 690 "bad revision could be any of:\n"))
694 691 for n in nodes:
695 692 displayer.show(repo[n])
696 693 displayer.close()
697 694
698 695 def check_state(state, interactive=True):
699 696 if not state['good'] or not state['bad']:
700 697 if (good or bad or skip or reset) and interactive:
701 698 return
702 699 if not state['good']:
703 700 raise util.Abort(_('cannot bisect (no known good revisions)'))
704 701 else:
705 702 raise util.Abort(_('cannot bisect (no known bad revisions)'))
706 703 return True
707 704
708 705 # backward compatibility
709 706 if rev in "good bad reset init".split():
710 707 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
711 708 cmd, rev, extra = rev, extra, None
712 709 if cmd == "good":
713 710 good = True
714 711 elif cmd == "bad":
715 712 bad = True
716 713 else:
717 714 reset = True
718 715 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
719 716 raise util.Abort(_('incompatible arguments'))
720 717
721 718 cmdutil.checkunfinished(repo)
722 719
723 720 if reset:
724 721 p = repo.join("bisect.state")
725 722 if os.path.exists(p):
726 723 os.unlink(p)
727 724 return
728 725
729 726 state = hbisect.load_state(repo)
730 727
731 728 if command:
732 729 changesets = 1
733 730 if noupdate:
734 731 try:
735 732 node = state['current'][0]
736 733 except LookupError:
737 734 raise util.Abort(_('current bisect revision is unknown - '
738 735 'start a new bisect to fix'))
739 736 else:
740 737 node, p2 = repo.dirstate.parents()
741 738 if p2 != nullid:
742 739 raise util.Abort(_('current bisect revision is a merge'))
743 740 try:
744 741 while changesets:
745 742 # update state
746 743 state['current'] = [node]
747 744 hbisect.save_state(repo, state)
748 745 status = util.system(command,
749 746 environ={'HG_NODE': hex(node)},
750 747 out=ui.fout)
751 748 if status == 125:
752 749 transition = "skip"
753 750 elif status == 0:
754 751 transition = "good"
755 752 # status < 0 means process was killed
756 753 elif status == 127:
757 754 raise util.Abort(_("failed to execute %s") % command)
758 755 elif status < 0:
759 756 raise util.Abort(_("%s killed") % command)
760 757 else:
761 758 transition = "bad"
762 759 ctx = scmutil.revsingle(repo, rev, node)
763 760 rev = None # clear for future iterations
764 761 state[transition].append(ctx.node())
765 762 ui.status(_('changeset %d:%s: %s\n') % (ctx, ctx, transition))
766 763 check_state(state, interactive=False)
767 764 # bisect
768 765 nodes, changesets, bgood = hbisect.bisect(repo.changelog, state)
769 766 # update to next check
770 767 node = nodes[0]
771 768 if not noupdate:
772 769 cmdutil.bailifchanged(repo)
773 770 hg.clean(repo, node, show_stats=False)
774 771 finally:
775 772 state['current'] = [node]
776 773 hbisect.save_state(repo, state)
777 774 print_result(nodes, bgood)
778 775 return
779 776
780 777 # update state
781 778
782 779 if rev:
783 780 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
784 781 else:
785 782 nodes = [repo.lookup('.')]
786 783
787 784 if good or bad or skip:
788 785 if good:
789 786 state['good'] += nodes
790 787 elif bad:
791 788 state['bad'] += nodes
792 789 elif skip:
793 790 state['skip'] += nodes
794 791 hbisect.save_state(repo, state)
795 792
796 793 if not check_state(state):
797 794 return
798 795
799 796 # actually bisect
800 797 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
801 798 if extend:
802 799 if not changesets:
803 800 extendnode = extendbisectrange(nodes, good)
804 801 if extendnode is not None:
805 802 ui.write(_("Extending search to changeset %d:%s\n")
806 803 % (extendnode.rev(), extendnode))
807 804 state['current'] = [extendnode.node()]
808 805 hbisect.save_state(repo, state)
809 806 if noupdate:
810 807 return
811 808 cmdutil.bailifchanged(repo)
812 809 return hg.clean(repo, extendnode.node())
813 810 raise util.Abort(_("nothing to extend"))
814 811
815 812 if changesets == 0:
816 813 print_result(nodes, good)
817 814 else:
818 815 assert len(nodes) == 1 # only a single node can be tested next
819 816 node = nodes[0]
820 817 # compute the approximate number of remaining tests
821 818 tests, size = 0, 2
822 819 while size <= changesets:
823 820 tests, size = tests + 1, size * 2
824 821 rev = repo.changelog.rev(node)
825 822 ui.write(_("Testing changeset %d:%s "
826 823 "(%d changesets remaining, ~%d tests)\n")
827 824 % (rev, short(node), changesets, tests))
828 825 state['current'] = [node]
829 826 hbisect.save_state(repo, state)
830 827 if not noupdate:
831 828 cmdutil.bailifchanged(repo)
832 829 return hg.clean(repo, node)
833 830
834 831 @command('bookmarks|bookmark',
835 832 [('f', 'force', False, _('force')),
836 833 ('r', 'rev', '', _('revision'), _('REV')),
837 834 ('d', 'delete', False, _('delete a given bookmark')),
838 835 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
839 836 ('i', 'inactive', False, _('mark a bookmark inactive'))],
840 837 _('hg bookmarks [OPTIONS]... [NAME]...'))
841 838 def bookmark(ui, repo, *names, **opts):
842 839 '''create a new bookmark or list existing bookmarks
843 840
844 841 Bookmarks are labels on changesets to help track lines of development.
845 842 Bookmarks are unversioned and can be moved, renamed and deleted.
846 843 Deleting or moving a bookmark has no effect on the associated changesets.
847 844
848 845 Creating or updating to a bookmark causes it to be marked as 'active'.
849 846 The active bookmark is indicated with a '*'.
850 847 When a commit is made, the active bookmark will advance to the new commit.
851 848 A plain :hg:`update` will also advance an active bookmark, if possible.
852 849 Updating away from a bookmark will cause it to be deactivated.
853 850
854 851 Bookmarks can be pushed and pulled between repositories (see
855 852 :hg:`help push` and :hg:`help pull`). If a shared bookmark has
856 853 diverged, a new 'divergent bookmark' of the form 'name@path' will
857 854 be created. Using :hg:'merge' will resolve the divergence.
858 855
859 856 A bookmark named '@' has the special property that :hg:`clone` will
860 857 check it out by default if it exists.
861 858
862 859 .. container:: verbose
863 860
864 861 Examples:
865 862
866 863 - create an active bookmark for a new line of development::
867 864
868 865 hg book new-feature
869 866
870 867 - create an inactive bookmark as a place marker::
871 868
872 869 hg book -i reviewed
873 870
874 871 - create an inactive bookmark on another changeset::
875 872
876 873 hg book -r .^ tested
877 874
878 875 - move the '@' bookmark from another branch::
879 876
880 877 hg book -f @
881 878 '''
882 879 force = opts.get('force')
883 880 rev = opts.get('rev')
884 881 delete = opts.get('delete')
885 882 rename = opts.get('rename')
886 883 inactive = opts.get('inactive')
887 884
888 885 def checkformat(mark):
889 886 mark = mark.strip()
890 887 if not mark:
891 888 raise util.Abort(_("bookmark names cannot consist entirely of "
892 889 "whitespace"))
893 890 scmutil.checknewlabel(repo, mark, 'bookmark')
894 891 return mark
895 892
896 893 def checkconflict(repo, mark, cur, force=False, target=None):
897 894 if mark in marks and not force:
898 895 if target:
899 896 if marks[mark] == target and target == cur:
900 897 # re-activating a bookmark
901 898 return
902 899 anc = repo.changelog.ancestors([repo[target].rev()])
903 900 bmctx = repo[marks[mark]]
904 901 divs = [repo[b].node() for b in marks
905 902 if b.split('@', 1)[0] == mark.split('@', 1)[0]]
906 903
907 904 # allow resolving a single divergent bookmark even if moving
908 905 # the bookmark across branches when a revision is specified
909 906 # that contains a divergent bookmark
910 907 if bmctx.rev() not in anc and target in divs:
911 908 bookmarks.deletedivergent(repo, [target], mark)
912 909 return
913 910
914 911 deletefrom = [b for b in divs
915 912 if repo[b].rev() in anc or b == target]
916 913 bookmarks.deletedivergent(repo, deletefrom, mark)
917 914 if bookmarks.validdest(repo, bmctx, repo[target]):
918 915 ui.status(_("moving bookmark '%s' forward from %s\n") %
919 916 (mark, short(bmctx.node())))
920 917 return
921 918 raise util.Abort(_("bookmark '%s' already exists "
922 919 "(use -f to force)") % mark)
923 920 if ((mark in repo.branchmap() or mark == repo.dirstate.branch())
924 921 and not force):
925 922 raise util.Abort(
926 923 _("a bookmark cannot have the name of an existing branch"))
927 924
928 925 if delete and rename:
929 926 raise util.Abort(_("--delete and --rename are incompatible"))
930 927 if delete and rev:
931 928 raise util.Abort(_("--rev is incompatible with --delete"))
932 929 if rename and rev:
933 930 raise util.Abort(_("--rev is incompatible with --rename"))
934 931 if not names and (delete or rev):
935 932 raise util.Abort(_("bookmark name required"))
936 933
937 934 if delete or rename or names or inactive:
938 935 wlock = repo.wlock()
939 936 try:
940 937 cur = repo.changectx('.').node()
941 938 marks = repo._bookmarks
942 939 if delete:
943 940 for mark in names:
944 941 if mark not in marks:
945 942 raise util.Abort(_("bookmark '%s' does not exist") %
946 943 mark)
947 944 if mark == repo._bookmarkcurrent:
948 945 bookmarks.unsetcurrent(repo)
949 946 del marks[mark]
950 947 marks.write()
951 948
952 949 elif rename:
953 950 if not names:
954 951 raise util.Abort(_("new bookmark name required"))
955 952 elif len(names) > 1:
956 953 raise util.Abort(_("only one new bookmark name allowed"))
957 954 mark = checkformat(names[0])
958 955 if rename not in marks:
959 956 raise util.Abort(_("bookmark '%s' does not exist") % rename)
960 957 checkconflict(repo, mark, cur, force)
961 958 marks[mark] = marks[rename]
962 959 if repo._bookmarkcurrent == rename and not inactive:
963 960 bookmarks.setcurrent(repo, mark)
964 961 del marks[rename]
965 962 marks.write()
966 963
967 964 elif names:
968 965 newact = None
969 966 for mark in names:
970 967 mark = checkformat(mark)
971 968 if newact is None:
972 969 newact = mark
973 970 if inactive and mark == repo._bookmarkcurrent:
974 971 bookmarks.unsetcurrent(repo)
975 972 return
976 973 tgt = cur
977 974 if rev:
978 975 tgt = scmutil.revsingle(repo, rev).node()
979 976 checkconflict(repo, mark, cur, force, tgt)
980 977 marks[mark] = tgt
981 978 if not inactive and cur == marks[newact] and not rev:
982 979 bookmarks.setcurrent(repo, newact)
983 980 elif cur != tgt and newact == repo._bookmarkcurrent:
984 981 bookmarks.unsetcurrent(repo)
985 982 marks.write()
986 983
987 984 elif inactive:
988 985 if len(marks) == 0:
989 986 ui.status(_("no bookmarks set\n"))
990 987 elif not repo._bookmarkcurrent:
991 988 ui.status(_("no active bookmark\n"))
992 989 else:
993 990 bookmarks.unsetcurrent(repo)
994 991 finally:
995 992 wlock.release()
996 993 else: # show bookmarks
997 994 hexfn = ui.debugflag and hex or short
998 995 marks = repo._bookmarks
999 996 if len(marks) == 0:
1000 997 ui.status(_("no bookmarks set\n"))
1001 998 else:
1002 999 for bmark, n in sorted(marks.iteritems()):
1003 1000 current = repo._bookmarkcurrent
1004 1001 if bmark == current:
1005 1002 prefix, label = '*', 'bookmarks.current'
1006 1003 else:
1007 1004 prefix, label = ' ', ''
1008 1005
1009 1006 if ui.quiet:
1010 1007 ui.write("%s\n" % bmark, label=label)
1011 1008 else:
1012 1009 pad = " " * (25 - encoding.colwidth(bmark))
1013 1010 ui.write(" %s %s%s %d:%s\n" % (
1014 1011 prefix, bmark, pad, repo.changelog.rev(n), hexfn(n)),
1015 1012 label=label)
1016 1013
1017 1014 @command('branch',
1018 1015 [('f', 'force', None,
1019 1016 _('set branch name even if it shadows an existing branch')),
1020 1017 ('C', 'clean', None, _('reset branch name to parent branch name'))],
1021 1018 _('[-fC] [NAME]'))
1022 1019 def branch(ui, repo, label=None, **opts):
1023 1020 """set or show the current branch name
1024 1021
1025 1022 .. note::
1026 1023
1027 1024 Branch names are permanent and global. Use :hg:`bookmark` to create a
1028 1025 light-weight bookmark instead. See :hg:`help glossary` for more
1029 1026 information about named branches and bookmarks.
1030 1027
1031 1028 With no argument, show the current branch name. With one argument,
1032 1029 set the working directory branch name (the branch will not exist
1033 1030 in the repository until the next commit). Standard practice
1034 1031 recommends that primary development take place on the 'default'
1035 1032 branch.
1036 1033
1037 1034 Unless -f/--force is specified, branch will not let you set a
1038 1035 branch name that already exists, even if it's inactive.
1039 1036
1040 1037 Use -C/--clean to reset the working directory branch to that of
1041 1038 the parent of the working directory, negating a previous branch
1042 1039 change.
1043 1040
1044 1041 Use the command :hg:`update` to switch to an existing branch. Use
1045 1042 :hg:`commit --close-branch` to mark this branch as closed.
1046 1043
1047 1044 Returns 0 on success.
1048 1045 """
1049 1046 if label:
1050 1047 label = label.strip()
1051 1048
1052 1049 if not opts.get('clean') and not label:
1053 1050 ui.write("%s\n" % repo.dirstate.branch())
1054 1051 return
1055 1052
1056 1053 wlock = repo.wlock()
1057 1054 try:
1058 1055 if opts.get('clean'):
1059 1056 label = repo[None].p1().branch()
1060 1057 repo.dirstate.setbranch(label)
1061 1058 ui.status(_('reset working directory to branch %s\n') % label)
1062 1059 elif label:
1063 1060 if not opts.get('force') and label in repo.branchmap():
1064 1061 if label not in [p.branch() for p in repo.parents()]:
1065 1062 raise util.Abort(_('a branch of the same name already'
1066 1063 ' exists'),
1067 1064 # i18n: "it" refers to an existing branch
1068 1065 hint=_("use 'hg update' to switch to it"))
1069 1066 scmutil.checknewlabel(repo, label, 'branch')
1070 1067 repo.dirstate.setbranch(label)
1071 1068 ui.status(_('marked working directory as branch %s\n') % label)
1072 1069 ui.status(_('(branches are permanent and global, '
1073 1070 'did you want a bookmark?)\n'))
1074 1071 finally:
1075 1072 wlock.release()
1076 1073
1077 1074 @command('branches',
1078 1075 [('a', 'active', False, _('show only branches that have unmerged heads')),
1079 1076 ('c', 'closed', False, _('show normal and closed branches'))],
1080 1077 _('[-ac]'))
1081 1078 def branches(ui, repo, active=False, closed=False):
1082 1079 """list repository named branches
1083 1080
1084 1081 List the repository's named branches, indicating which ones are
1085 1082 inactive. If -c/--closed is specified, also list branches which have
1086 1083 been marked closed (see :hg:`commit --close-branch`).
1087 1084
1088 1085 If -a/--active is specified, only show active branches. A branch
1089 1086 is considered active if it contains repository heads.
1090 1087
1091 1088 Use the command :hg:`update` to switch to an existing branch.
1092 1089
1093 1090 Returns 0.
1094 1091 """
1095 1092
1096 1093 hexfunc = ui.debugflag and hex or short
1097 1094
1098 1095 allheads = set(repo.heads())
1099 1096 branches = []
1100 1097 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1101 1098 isactive = not isclosed and bool(set(heads) & allheads)
1102 1099 branches.append((tag, repo[tip], isactive, not isclosed))
1103 1100 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]),
1104 1101 reverse=True)
1105 1102
1106 1103 for tag, ctx, isactive, isopen in branches:
1107 1104 if active and not isactive:
1108 1105 continue
1109 1106 if isactive:
1110 1107 label = 'branches.active'
1111 1108 notice = ''
1112 1109 elif not isopen:
1113 1110 if not closed:
1114 1111 continue
1115 1112 label = 'branches.closed'
1116 1113 notice = _(' (closed)')
1117 1114 else:
1118 1115 label = 'branches.inactive'
1119 1116 notice = _(' (inactive)')
1120 1117 if tag == repo.dirstate.branch():
1121 1118 label = 'branches.current'
1122 1119 rev = str(ctx.rev()).rjust(31 - encoding.colwidth(tag))
1123 1120 rev = ui.label('%s:%s' % (rev, hexfunc(ctx.node())),
1124 1121 'log.changeset changeset.%s' % ctx.phasestr())
1125 1122 labeledtag = ui.label(tag, label)
1126 1123 if ui.quiet:
1127 1124 ui.write("%s\n" % labeledtag)
1128 1125 else:
1129 1126 ui.write("%s %s%s\n" % (labeledtag, rev, notice))
1130 1127
1131 1128 @command('bundle',
1132 1129 [('f', 'force', None, _('run even when the destination is unrelated')),
1133 1130 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1134 1131 _('REV')),
1135 1132 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1136 1133 _('BRANCH')),
1137 1134 ('', 'base', [],
1138 1135 _('a base changeset assumed to be available at the destination'),
1139 1136 _('REV')),
1140 1137 ('a', 'all', None, _('bundle all changesets in the repository')),
1141 1138 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1142 1139 ] + remoteopts,
1143 1140 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
1144 1141 def bundle(ui, repo, fname, dest=None, **opts):
1145 1142 """create a changegroup file
1146 1143
1147 1144 Generate a compressed changegroup file collecting changesets not
1148 1145 known to be in another repository.
1149 1146
1150 1147 If you omit the destination repository, then hg assumes the
1151 1148 destination will have all the nodes you specify with --base
1152 1149 parameters. To create a bundle containing all changesets, use
1153 1150 -a/--all (or --base null).
1154 1151
1155 1152 You can change compression method with the -t/--type option.
1156 1153 The available compression methods are: none, bzip2, and
1157 1154 gzip (by default, bundles are compressed using bzip2).
1158 1155
1159 1156 The bundle file can then be transferred using conventional means
1160 1157 and applied to another repository with the unbundle or pull
1161 1158 command. This is useful when direct push and pull are not
1162 1159 available or when exporting an entire repository is undesirable.
1163 1160
1164 1161 Applying bundles preserves all changeset contents including
1165 1162 permissions, copy/rename information, and revision history.
1166 1163
1167 1164 Returns 0 on success, 1 if no changes found.
1168 1165 """
1169 1166 revs = None
1170 1167 if 'rev' in opts:
1171 1168 revs = scmutil.revrange(repo, opts['rev'])
1172 1169
1173 1170 bundletype = opts.get('type', 'bzip2').lower()
1174 1171 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1175 1172 bundletype = btypes.get(bundletype)
1176 1173 if bundletype not in changegroup.bundletypes:
1177 1174 raise util.Abort(_('unknown bundle type specified with --type'))
1178 1175
1179 1176 if opts.get('all'):
1180 1177 base = ['null']
1181 1178 else:
1182 1179 base = scmutil.revrange(repo, opts.get('base'))
1183 1180 # TODO: get desired bundlecaps from command line.
1184 1181 bundlecaps = None
1185 1182 if base:
1186 1183 if dest:
1187 1184 raise util.Abort(_("--base is incompatible with specifying "
1188 1185 "a destination"))
1189 1186 common = [repo.lookup(rev) for rev in base]
1190 1187 heads = revs and map(repo.lookup, revs) or revs
1191 1188 cg = changegroup.getchangegroup(repo, 'bundle', heads=heads,
1192 1189 common=common, bundlecaps=bundlecaps)
1193 1190 outgoing = None
1194 1191 else:
1195 1192 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1196 1193 dest, branches = hg.parseurl(dest, opts.get('branch'))
1197 1194 other = hg.peer(repo, opts, dest)
1198 1195 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1199 1196 heads = revs and map(repo.lookup, revs) or revs
1200 1197 outgoing = discovery.findcommonoutgoing(repo, other,
1201 1198 onlyheads=heads,
1202 1199 force=opts.get('force'),
1203 1200 portable=True)
1204 1201 cg = changegroup.getlocalchangegroup(repo, 'bundle', outgoing,
1205 1202 bundlecaps)
1206 1203 if not cg:
1207 1204 scmutil.nochangesfound(ui, repo, outgoing and outgoing.excluded)
1208 1205 return 1
1209 1206
1210 1207 changegroup.writebundle(cg, fname, bundletype)
1211 1208
1212 1209 @command('cat',
1213 1210 [('o', 'output', '',
1214 1211 _('print output to file with formatted name'), _('FORMAT')),
1215 1212 ('r', 'rev', '', _('print the given revision'), _('REV')),
1216 1213 ('', 'decode', None, _('apply any matching decode filter')),
1217 1214 ] + walkopts,
1218 1215 _('[OPTION]... FILE...'),
1219 1216 inferrepo=True)
1220 1217 def cat(ui, repo, file1, *pats, **opts):
1221 1218 """output the current or given revision of files
1222 1219
1223 1220 Print the specified files as they were at the given revision. If
1224 1221 no revision is given, the parent of the working directory is used.
1225 1222
1226 1223 Output may be to a file, in which case the name of the file is
1227 1224 given using a format string. The formatting rules as follows:
1228 1225
1229 1226 :``%%``: literal "%" character
1230 1227 :``%s``: basename of file being printed
1231 1228 :``%d``: dirname of file being printed, or '.' if in repository root
1232 1229 :``%p``: root-relative path name of file being printed
1233 1230 :``%H``: changeset hash (40 hexadecimal digits)
1234 1231 :``%R``: changeset revision number
1235 1232 :``%h``: short-form changeset hash (12 hexadecimal digits)
1236 1233 :``%r``: zero-padded changeset revision number
1237 1234 :``%b``: basename of the exporting repository
1238 1235
1239 1236 Returns 0 on success.
1240 1237 """
1241 1238 ctx = scmutil.revsingle(repo, opts.get('rev'))
1242 1239 m = scmutil.match(ctx, (file1,) + pats, opts)
1243 1240
1244 1241 return cmdutil.cat(ui, repo, ctx, m, '', **opts)
1245 1242
1246 1243 @command('^clone',
1247 1244 [('U', 'noupdate', None,
1248 1245 _('the clone will include an empty working copy (only a repository)')),
1249 1246 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
1250 1247 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1251 1248 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1252 1249 ('', 'pull', None, _('use pull protocol to copy metadata')),
1253 1250 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1254 1251 ] + remoteopts,
1255 1252 _('[OPTION]... SOURCE [DEST]'),
1256 1253 norepo=True)
1257 1254 def clone(ui, source, dest=None, **opts):
1258 1255 """make a copy of an existing repository
1259 1256
1260 1257 Create a copy of an existing repository in a new directory.
1261 1258
1262 1259 If no destination directory name is specified, it defaults to the
1263 1260 basename of the source.
1264 1261
1265 1262 The location of the source is added to the new repository's
1266 1263 ``.hg/hgrc`` file, as the default to be used for future pulls.
1267 1264
1268 1265 Only local paths and ``ssh://`` URLs are supported as
1269 1266 destinations. For ``ssh://`` destinations, no working directory or
1270 1267 ``.hg/hgrc`` will be created on the remote side.
1271 1268
1272 1269 To pull only a subset of changesets, specify one or more revisions
1273 1270 identifiers with -r/--rev or branches with -b/--branch. The
1274 1271 resulting clone will contain only the specified changesets and
1275 1272 their ancestors. These options (or 'clone src#rev dest') imply
1276 1273 --pull, even for local source repositories. Note that specifying a
1277 1274 tag will include the tagged changeset but not the changeset
1278 1275 containing the tag.
1279 1276
1280 1277 If the source repository has a bookmark called '@' set, that
1281 1278 revision will be checked out in the new repository by default.
1282 1279
1283 1280 To check out a particular version, use -u/--update, or
1284 1281 -U/--noupdate to create a clone with no working directory.
1285 1282
1286 1283 .. container:: verbose
1287 1284
1288 1285 For efficiency, hardlinks are used for cloning whenever the
1289 1286 source and destination are on the same filesystem (note this
1290 1287 applies only to the repository data, not to the working
1291 1288 directory). Some filesystems, such as AFS, implement hardlinking
1292 1289 incorrectly, but do not report errors. In these cases, use the
1293 1290 --pull option to avoid hardlinking.
1294 1291
1295 1292 In some cases, you can clone repositories and the working
1296 1293 directory using full hardlinks with ::
1297 1294
1298 1295 $ cp -al REPO REPOCLONE
1299 1296
1300 1297 This is the fastest way to clone, but it is not always safe. The
1301 1298 operation is not atomic (making sure REPO is not modified during
1302 1299 the operation is up to you) and you have to make sure your
1303 1300 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1304 1301 so). Also, this is not compatible with certain extensions that
1305 1302 place their metadata under the .hg directory, such as mq.
1306 1303
1307 1304 Mercurial will update the working directory to the first applicable
1308 1305 revision from this list:
1309 1306
1310 1307 a) null if -U or the source repository has no changesets
1311 1308 b) if -u . and the source repository is local, the first parent of
1312 1309 the source repository's working directory
1313 1310 c) the changeset specified with -u (if a branch name, this means the
1314 1311 latest head of that branch)
1315 1312 d) the changeset specified with -r
1316 1313 e) the tipmost head specified with -b
1317 1314 f) the tipmost head specified with the url#branch source syntax
1318 1315 g) the revision marked with the '@' bookmark, if present
1319 1316 h) the tipmost head of the default branch
1320 1317 i) tip
1321 1318
1322 1319 Examples:
1323 1320
1324 1321 - clone a remote repository to a new directory named hg/::
1325 1322
1326 1323 hg clone http://selenic.com/hg
1327 1324
1328 1325 - create a lightweight local clone::
1329 1326
1330 1327 hg clone project/ project-feature/
1331 1328
1332 1329 - clone from an absolute path on an ssh server (note double-slash)::
1333 1330
1334 1331 hg clone ssh://user@server//home/projects/alpha/
1335 1332
1336 1333 - do a high-speed clone over a LAN while checking out a
1337 1334 specified version::
1338 1335
1339 1336 hg clone --uncompressed http://server/repo -u 1.5
1340 1337
1341 1338 - create a repository without changesets after a particular revision::
1342 1339
1343 1340 hg clone -r 04e544 experimental/ good/
1344 1341
1345 1342 - clone (and track) a particular named branch::
1346 1343
1347 1344 hg clone http://selenic.com/hg#stable
1348 1345
1349 1346 See :hg:`help urls` for details on specifying URLs.
1350 1347
1351 1348 Returns 0 on success.
1352 1349 """
1353 1350 if opts.get('noupdate') and opts.get('updaterev'):
1354 1351 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1355 1352
1356 1353 r = hg.clone(ui, opts, source, dest,
1357 1354 pull=opts.get('pull'),
1358 1355 stream=opts.get('uncompressed'),
1359 1356 rev=opts.get('rev'),
1360 1357 update=opts.get('updaterev') or not opts.get('noupdate'),
1361 1358 branch=opts.get('branch'))
1362 1359
1363 1360 return r is None
1364 1361
1365 1362 @command('^commit|ci',
1366 1363 [('A', 'addremove', None,
1367 1364 _('mark new/missing files as added/removed before committing')),
1368 1365 ('', 'close-branch', None,
1369 1366 _('mark a branch as closed, hiding it from the branch list')),
1370 1367 ('', 'amend', None, _('amend the parent of the working dir')),
1371 1368 ('s', 'secret', None, _('use the secret phase for committing')),
1372 1369 ('e', 'edit', None, _('invoke editor on commit messages')),
1373 1370 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1374 1371 _('[OPTION]... [FILE]...'),
1375 1372 inferrepo=True)
1376 1373 def commit(ui, repo, *pats, **opts):
1377 1374 """commit the specified files or all outstanding changes
1378 1375
1379 1376 Commit changes to the given files into the repository. Unlike a
1380 1377 centralized SCM, this operation is a local operation. See
1381 1378 :hg:`push` for a way to actively distribute your changes.
1382 1379
1383 1380 If a list of files is omitted, all changes reported by :hg:`status`
1384 1381 will be committed.
1385 1382
1386 1383 If you are committing the result of a merge, do not provide any
1387 1384 filenames or -I/-X filters.
1388 1385
1389 1386 If no commit message is specified, Mercurial starts your
1390 1387 configured editor where you can enter a message. In case your
1391 1388 commit fails, you will find a backup of your message in
1392 1389 ``.hg/last-message.txt``.
1393 1390
1394 1391 The --amend flag can be used to amend the parent of the
1395 1392 working directory with a new commit that contains the changes
1396 1393 in the parent in addition to those currently reported by :hg:`status`,
1397 1394 if there are any. The old commit is stored in a backup bundle in
1398 1395 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1399 1396 on how to restore it).
1400 1397
1401 1398 Message, user and date are taken from the amended commit unless
1402 1399 specified. When a message isn't specified on the command line,
1403 1400 the editor will open with the message of the amended commit.
1404 1401
1405 1402 It is not possible to amend public changesets (see :hg:`help phases`)
1406 1403 or changesets that have children.
1407 1404
1408 1405 See :hg:`help dates` for a list of formats valid for -d/--date.
1409 1406
1410 1407 Returns 0 on success, 1 if nothing changed.
1411 1408 """
1412 1409 if opts.get('subrepos'):
1413 1410 if opts.get('amend'):
1414 1411 raise util.Abort(_('cannot amend with --subrepos'))
1415 1412 # Let --subrepos on the command line override config setting.
1416 1413 ui.setconfig('ui', 'commitsubrepos', True, 'commit')
1417 1414
1418 1415 cmdutil.checkunfinished(repo, commit=True)
1419 1416
1420 1417 branch = repo[None].branch()
1421 1418 bheads = repo.branchheads(branch)
1422 1419
1423 1420 extra = {}
1424 1421 if opts.get('close_branch'):
1425 1422 extra['close'] = 1
1426 1423
1427 1424 if not bheads:
1428 1425 raise util.Abort(_('can only close branch heads'))
1429 1426 elif opts.get('amend'):
1430 1427 if repo.parents()[0].p1().branch() != branch and \
1431 1428 repo.parents()[0].p2().branch() != branch:
1432 1429 raise util.Abort(_('can only close branch heads'))
1433 1430
1434 1431 if opts.get('amend'):
1435 1432 if ui.configbool('ui', 'commitsubrepos'):
1436 1433 raise util.Abort(_('cannot amend with ui.commitsubrepos enabled'))
1437 1434
1438 1435 old = repo['.']
1439 1436 if not old.mutable():
1440 1437 raise util.Abort(_('cannot amend public changesets'))
1441 1438 if len(repo[None].parents()) > 1:
1442 1439 raise util.Abort(_('cannot amend while merging'))
1443 1440 if (not obsolete._enabled) and old.children():
1444 1441 raise util.Abort(_('cannot amend changeset with children'))
1445 1442
1446 1443 # commitfunc is used only for temporary amend commit by cmdutil.amend
1447 1444 def commitfunc(ui, repo, message, match, opts):
1448 1445 return repo.commit(message,
1449 1446 opts.get('user') or old.user(),
1450 1447 opts.get('date') or old.date(),
1451 1448 match,
1452 1449 extra=extra)
1453 1450
1454 1451 current = repo._bookmarkcurrent
1455 1452 marks = old.bookmarks()
1456 1453 node = cmdutil.amend(ui, repo, commitfunc, old, extra, pats, opts)
1457 1454 if node == old.node():
1458 1455 ui.status(_("nothing changed\n"))
1459 1456 return 1
1460 1457 elif marks:
1461 1458 ui.debug('moving bookmarks %r from %s to %s\n' %
1462 1459 (marks, old.hex(), hex(node)))
1463 1460 newmarks = repo._bookmarks
1464 1461 for bm in marks:
1465 1462 newmarks[bm] = node
1466 1463 if bm == current:
1467 1464 bookmarks.setcurrent(repo, bm)
1468 1465 newmarks.write()
1469 1466 else:
1470 1467 def commitfunc(ui, repo, message, match, opts):
1471 1468 backup = ui.backupconfig('phases', 'new-commit')
1472 1469 baseui = repo.baseui
1473 1470 basebackup = baseui.backupconfig('phases', 'new-commit')
1474 1471 try:
1475 1472 if opts.get('secret'):
1476 1473 ui.setconfig('phases', 'new-commit', 'secret', 'commit')
1477 1474 # Propagate to subrepos
1478 1475 baseui.setconfig('phases', 'new-commit', 'secret', 'commit')
1479 1476
1480 1477 editform = cmdutil.mergeeditform(repo[None], 'commit.normal')
1481 1478 editor = cmdutil.getcommiteditor(editform=editform, **opts)
1482 1479 return repo.commit(message, opts.get('user'), opts.get('date'),
1483 1480 match,
1484 1481 editor=editor,
1485 1482 extra=extra)
1486 1483 finally:
1487 1484 ui.restoreconfig(backup)
1488 1485 repo.baseui.restoreconfig(basebackup)
1489 1486
1490 1487
1491 1488 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1492 1489
1493 1490 if not node:
1494 1491 stat = repo.status(match=scmutil.match(repo[None], pats, opts))
1495 1492 if stat[3]:
1496 1493 ui.status(_("nothing changed (%d missing files, see "
1497 1494 "'hg status')\n") % len(stat[3]))
1498 1495 else:
1499 1496 ui.status(_("nothing changed\n"))
1500 1497 return 1
1501 1498
1502 1499 cmdutil.commitstatus(repo, node, branch, bheads, opts)
1503 1500
1504 1501 @command('config|showconfig|debugconfig',
1505 1502 [('u', 'untrusted', None, _('show untrusted configuration options')),
1506 1503 ('e', 'edit', None, _('edit user config')),
1507 1504 ('l', 'local', None, _('edit repository config')),
1508 1505 ('g', 'global', None, _('edit global config'))],
1509 1506 _('[-u] [NAME]...'),
1510 1507 optionalrepo=True)
1511 1508 def config(ui, repo, *values, **opts):
1512 1509 """show combined config settings from all hgrc files
1513 1510
1514 1511 With no arguments, print names and values of all config items.
1515 1512
1516 1513 With one argument of the form section.name, print just the value
1517 1514 of that config item.
1518 1515
1519 1516 With multiple arguments, print names and values of all config
1520 1517 items with matching section names.
1521 1518
1522 1519 With --edit, start an editor on the user-level config file. With
1523 1520 --global, edit the system-wide config file. With --local, edit the
1524 1521 repository-level config file.
1525 1522
1526 1523 With --debug, the source (filename and line number) is printed
1527 1524 for each config item.
1528 1525
1529 1526 See :hg:`help config` for more information about config files.
1530 1527
1531 1528 Returns 0 on success, 1 if NAME does not exist.
1532 1529
1533 1530 """
1534 1531
1535 1532 if opts.get('edit') or opts.get('local') or opts.get('global'):
1536 1533 if opts.get('local') and opts.get('global'):
1537 1534 raise util.Abort(_("can't use --local and --global together"))
1538 1535
1539 1536 if opts.get('local'):
1540 1537 if not repo:
1541 1538 raise util.Abort(_("can't use --local outside a repository"))
1542 1539 paths = [repo.join('hgrc')]
1543 1540 elif opts.get('global'):
1544 1541 paths = scmutil.systemrcpath()
1545 1542 else:
1546 1543 paths = scmutil.userrcpath()
1547 1544
1548 1545 for f in paths:
1549 1546 if os.path.exists(f):
1550 1547 break
1551 1548 else:
1552 1549 from ui import samplehgrcs
1553 1550
1554 1551 if opts.get('global'):
1555 1552 samplehgrc = samplehgrcs['global']
1556 1553 elif opts.get('local'):
1557 1554 samplehgrc = samplehgrcs['local']
1558 1555 else:
1559 1556 samplehgrc = samplehgrcs['user']
1560 1557
1561 1558 f = paths[0]
1562 1559 fp = open(f, "w")
1563 1560 fp.write(samplehgrc)
1564 1561 fp.close()
1565 1562
1566 1563 editor = ui.geteditor()
1567 1564 util.system("%s \"%s\"" % (editor, f),
1568 1565 onerr=util.Abort, errprefix=_("edit failed"),
1569 1566 out=ui.fout)
1570 1567 return
1571 1568
1572 1569 for f in scmutil.rcpath():
1573 1570 ui.debug('read config from: %s\n' % f)
1574 1571 untrusted = bool(opts.get('untrusted'))
1575 1572 if values:
1576 1573 sections = [v for v in values if '.' not in v]
1577 1574 items = [v for v in values if '.' in v]
1578 1575 if len(items) > 1 or items and sections:
1579 1576 raise util.Abort(_('only one config item permitted'))
1580 1577 matched = False
1581 1578 for section, name, value in ui.walkconfig(untrusted=untrusted):
1582 1579 value = str(value).replace('\n', '\\n')
1583 1580 sectname = section + '.' + name
1584 1581 if values:
1585 1582 for v in values:
1586 1583 if v == section:
1587 1584 ui.debug('%s: ' %
1588 1585 ui.configsource(section, name, untrusted))
1589 1586 ui.write('%s=%s\n' % (sectname, value))
1590 1587 matched = True
1591 1588 elif v == sectname:
1592 1589 ui.debug('%s: ' %
1593 1590 ui.configsource(section, name, untrusted))
1594 1591 ui.write(value, '\n')
1595 1592 matched = True
1596 1593 else:
1597 1594 ui.debug('%s: ' %
1598 1595 ui.configsource(section, name, untrusted))
1599 1596 ui.write('%s=%s\n' % (sectname, value))
1600 1597 matched = True
1601 1598 if matched:
1602 1599 return 0
1603 1600 return 1
1604 1601
1605 1602 @command('copy|cp',
1606 1603 [('A', 'after', None, _('record a copy that has already occurred')),
1607 1604 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1608 1605 ] + walkopts + dryrunopts,
1609 1606 _('[OPTION]... [SOURCE]... DEST'))
1610 1607 def copy(ui, repo, *pats, **opts):
1611 1608 """mark files as copied for the next commit
1612 1609
1613 1610 Mark dest as having copies of source files. If dest is a
1614 1611 directory, copies are put in that directory. If dest is a file,
1615 1612 the source must be a single file.
1616 1613
1617 1614 By default, this command copies the contents of files as they
1618 1615 exist in the working directory. If invoked with -A/--after, the
1619 1616 operation is recorded, but no copying is performed.
1620 1617
1621 1618 This command takes effect with the next commit. To undo a copy
1622 1619 before that, see :hg:`revert`.
1623 1620
1624 1621 Returns 0 on success, 1 if errors are encountered.
1625 1622 """
1626 1623 wlock = repo.wlock(False)
1627 1624 try:
1628 1625 return cmdutil.copy(ui, repo, pats, opts)
1629 1626 finally:
1630 1627 wlock.release()
1631 1628
1632 1629 @command('debugancestor', [], _('[INDEX] REV1 REV2'), optionalrepo=True)
1633 1630 def debugancestor(ui, repo, *args):
1634 1631 """find the ancestor revision of two revisions in a given index"""
1635 1632 if len(args) == 3:
1636 1633 index, rev1, rev2 = args
1637 1634 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1638 1635 lookup = r.lookup
1639 1636 elif len(args) == 2:
1640 1637 if not repo:
1641 1638 raise util.Abort(_("there is no Mercurial repository here "
1642 1639 "(.hg not found)"))
1643 1640 rev1, rev2 = args
1644 1641 r = repo.changelog
1645 1642 lookup = repo.lookup
1646 1643 else:
1647 1644 raise util.Abort(_('either two or three arguments required'))
1648 1645 a = r.ancestor(lookup(rev1), lookup(rev2))
1649 1646 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1650 1647
1651 1648 @command('debugbuilddag',
1652 1649 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1653 1650 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1654 1651 ('n', 'new-file', None, _('add new file at each rev'))],
1655 1652 _('[OPTION]... [TEXT]'))
1656 1653 def debugbuilddag(ui, repo, text=None,
1657 1654 mergeable_file=False,
1658 1655 overwritten_file=False,
1659 1656 new_file=False):
1660 1657 """builds a repo with a given DAG from scratch in the current empty repo
1661 1658
1662 1659 The description of the DAG is read from stdin if not given on the
1663 1660 command line.
1664 1661
1665 1662 Elements:
1666 1663
1667 1664 - "+n" is a linear run of n nodes based on the current default parent
1668 1665 - "." is a single node based on the current default parent
1669 1666 - "$" resets the default parent to null (implied at the start);
1670 1667 otherwise the default parent is always the last node created
1671 1668 - "<p" sets the default parent to the backref p
1672 1669 - "*p" is a fork at parent p, which is a backref
1673 1670 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1674 1671 - "/p2" is a merge of the preceding node and p2
1675 1672 - ":tag" defines a local tag for the preceding node
1676 1673 - "@branch" sets the named branch for subsequent nodes
1677 1674 - "#...\\n" is a comment up to the end of the line
1678 1675
1679 1676 Whitespace between the above elements is ignored.
1680 1677
1681 1678 A backref is either
1682 1679
1683 1680 - a number n, which references the node curr-n, where curr is the current
1684 1681 node, or
1685 1682 - the name of a local tag you placed earlier using ":tag", or
1686 1683 - empty to denote the default parent.
1687 1684
1688 1685 All string valued-elements are either strictly alphanumeric, or must
1689 1686 be enclosed in double quotes ("..."), with "\\" as escape character.
1690 1687 """
1691 1688
1692 1689 if text is None:
1693 1690 ui.status(_("reading DAG from stdin\n"))
1694 1691 text = ui.fin.read()
1695 1692
1696 1693 cl = repo.changelog
1697 1694 if len(cl) > 0:
1698 1695 raise util.Abort(_('repository is not empty'))
1699 1696
1700 1697 # determine number of revs in DAG
1701 1698 total = 0
1702 1699 for type, data in dagparser.parsedag(text):
1703 1700 if type == 'n':
1704 1701 total += 1
1705 1702
1706 1703 if mergeable_file:
1707 1704 linesperrev = 2
1708 1705 # make a file with k lines per rev
1709 1706 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1710 1707 initialmergedlines.append("")
1711 1708
1712 1709 tags = []
1713 1710
1714 1711 lock = tr = None
1715 1712 try:
1716 1713 lock = repo.lock()
1717 1714 tr = repo.transaction("builddag")
1718 1715
1719 1716 at = -1
1720 1717 atbranch = 'default'
1721 1718 nodeids = []
1722 1719 id = 0
1723 1720 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1724 1721 for type, data in dagparser.parsedag(text):
1725 1722 if type == 'n':
1726 1723 ui.note(('node %s\n' % str(data)))
1727 1724 id, ps = data
1728 1725
1729 1726 files = []
1730 1727 fctxs = {}
1731 1728
1732 1729 p2 = None
1733 1730 if mergeable_file:
1734 1731 fn = "mf"
1735 1732 p1 = repo[ps[0]]
1736 1733 if len(ps) > 1:
1737 1734 p2 = repo[ps[1]]
1738 1735 pa = p1.ancestor(p2)
1739 1736 base, local, other = [x[fn].data() for x in (pa, p1,
1740 1737 p2)]
1741 1738 m3 = simplemerge.Merge3Text(base, local, other)
1742 1739 ml = [l.strip() for l in m3.merge_lines()]
1743 1740 ml.append("")
1744 1741 elif at > 0:
1745 1742 ml = p1[fn].data().split("\n")
1746 1743 else:
1747 1744 ml = initialmergedlines
1748 1745 ml[id * linesperrev] += " r%i" % id
1749 1746 mergedtext = "\n".join(ml)
1750 1747 files.append(fn)
1751 1748 fctxs[fn] = context.memfilectx(repo, fn, mergedtext)
1752 1749
1753 1750 if overwritten_file:
1754 1751 fn = "of"
1755 1752 files.append(fn)
1756 1753 fctxs[fn] = context.memfilectx(repo, fn, "r%i\n" % id)
1757 1754
1758 1755 if new_file:
1759 1756 fn = "nf%i" % id
1760 1757 files.append(fn)
1761 1758 fctxs[fn] = context.memfilectx(repo, fn, "r%i\n" % id)
1762 1759 if len(ps) > 1:
1763 1760 if not p2:
1764 1761 p2 = repo[ps[1]]
1765 1762 for fn in p2:
1766 1763 if fn.startswith("nf"):
1767 1764 files.append(fn)
1768 1765 fctxs[fn] = p2[fn]
1769 1766
1770 1767 def fctxfn(repo, cx, path):
1771 1768 return fctxs.get(path)
1772 1769
1773 1770 if len(ps) == 0 or ps[0] < 0:
1774 1771 pars = [None, None]
1775 1772 elif len(ps) == 1:
1776 1773 pars = [nodeids[ps[0]], None]
1777 1774 else:
1778 1775 pars = [nodeids[p] for p in ps]
1779 1776 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1780 1777 date=(id, 0),
1781 1778 user="debugbuilddag",
1782 1779 extra={'branch': atbranch})
1783 1780 nodeid = repo.commitctx(cx)
1784 1781 nodeids.append(nodeid)
1785 1782 at = id
1786 1783 elif type == 'l':
1787 1784 id, name = data
1788 1785 ui.note(('tag %s\n' % name))
1789 1786 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1790 1787 elif type == 'a':
1791 1788 ui.note(('branch %s\n' % data))
1792 1789 atbranch = data
1793 1790 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1794 1791 tr.close()
1795 1792
1796 1793 if tags:
1797 1794 repo.opener.write("localtags", "".join(tags))
1798 1795 finally:
1799 1796 ui.progress(_('building'), None)
1800 1797 release(tr, lock)
1801 1798
1802 1799 @command('debugbundle',
1803 1800 [('a', 'all', None, _('show all details'))],
1804 1801 _('FILE'),
1805 1802 norepo=True)
1806 1803 def debugbundle(ui, bundlepath, all=None, **opts):
1807 1804 """lists the contents of a bundle"""
1808 1805 f = hg.openpath(ui, bundlepath)
1809 1806 try:
1810 1807 gen = exchange.readbundle(ui, f, bundlepath)
1811 1808 if all:
1812 1809 ui.write(("format: id, p1, p2, cset, delta base, len(delta)\n"))
1813 1810
1814 1811 def showchunks(named):
1815 1812 ui.write("\n%s\n" % named)
1816 1813 chain = None
1817 1814 while True:
1818 1815 chunkdata = gen.deltachunk(chain)
1819 1816 if not chunkdata:
1820 1817 break
1821 1818 node = chunkdata['node']
1822 1819 p1 = chunkdata['p1']
1823 1820 p2 = chunkdata['p2']
1824 1821 cs = chunkdata['cs']
1825 1822 deltabase = chunkdata['deltabase']
1826 1823 delta = chunkdata['delta']
1827 1824 ui.write("%s %s %s %s %s %s\n" %
1828 1825 (hex(node), hex(p1), hex(p2),
1829 1826 hex(cs), hex(deltabase), len(delta)))
1830 1827 chain = node
1831 1828
1832 1829 chunkdata = gen.changelogheader()
1833 1830 showchunks("changelog")
1834 1831 chunkdata = gen.manifestheader()
1835 1832 showchunks("manifest")
1836 1833 while True:
1837 1834 chunkdata = gen.filelogheader()
1838 1835 if not chunkdata:
1839 1836 break
1840 1837 fname = chunkdata['filename']
1841 1838 showchunks(fname)
1842 1839 else:
1843 1840 chunkdata = gen.changelogheader()
1844 1841 chain = None
1845 1842 while True:
1846 1843 chunkdata = gen.deltachunk(chain)
1847 1844 if not chunkdata:
1848 1845 break
1849 1846 node = chunkdata['node']
1850 1847 ui.write("%s\n" % hex(node))
1851 1848 chain = node
1852 1849 finally:
1853 1850 f.close()
1854 1851
1855 1852 @command('debugcheckstate', [], '')
1856 1853 def debugcheckstate(ui, repo):
1857 1854 """validate the correctness of the current dirstate"""
1858 1855 parent1, parent2 = repo.dirstate.parents()
1859 1856 m1 = repo[parent1].manifest()
1860 1857 m2 = repo[parent2].manifest()
1861 1858 errors = 0
1862 1859 for f in repo.dirstate:
1863 1860 state = repo.dirstate[f]
1864 1861 if state in "nr" and f not in m1:
1865 1862 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1866 1863 errors += 1
1867 1864 if state in "a" and f in m1:
1868 1865 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1869 1866 errors += 1
1870 1867 if state in "m" and f not in m1 and f not in m2:
1871 1868 ui.warn(_("%s in state %s, but not in either manifest\n") %
1872 1869 (f, state))
1873 1870 errors += 1
1874 1871 for f in m1:
1875 1872 state = repo.dirstate[f]
1876 1873 if state not in "nrm":
1877 1874 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1878 1875 errors += 1
1879 1876 if errors:
1880 1877 error = _(".hg/dirstate inconsistent with current parent's manifest")
1881 1878 raise util.Abort(error)
1882 1879
1883 1880 @command('debugcommands', [], _('[COMMAND]'), norepo=True)
1884 1881 def debugcommands(ui, cmd='', *args):
1885 1882 """list all available commands and options"""
1886 1883 for cmd, vals in sorted(table.iteritems()):
1887 1884 cmd = cmd.split('|')[0].strip('^')
1888 1885 opts = ', '.join([i[1] for i in vals[1]])
1889 1886 ui.write('%s: %s\n' % (cmd, opts))
1890 1887
1891 1888 @command('debugcomplete',
1892 1889 [('o', 'options', None, _('show the command options'))],
1893 1890 _('[-o] CMD'),
1894 1891 norepo=True)
1895 1892 def debugcomplete(ui, cmd='', **opts):
1896 1893 """returns the completion list associated with the given command"""
1897 1894
1898 1895 if opts.get('options'):
1899 1896 options = []
1900 1897 otables = [globalopts]
1901 1898 if cmd:
1902 1899 aliases, entry = cmdutil.findcmd(cmd, table, False)
1903 1900 otables.append(entry[1])
1904 1901 for t in otables:
1905 1902 for o in t:
1906 1903 if "(DEPRECATED)" in o[3]:
1907 1904 continue
1908 1905 if o[0]:
1909 1906 options.append('-%s' % o[0])
1910 1907 options.append('--%s' % o[1])
1911 1908 ui.write("%s\n" % "\n".join(options))
1912 1909 return
1913 1910
1914 1911 cmdlist = cmdutil.findpossible(cmd, table)
1915 1912 if ui.verbose:
1916 1913 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1917 1914 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1918 1915
1919 1916 @command('debugdag',
1920 1917 [('t', 'tags', None, _('use tags as labels')),
1921 1918 ('b', 'branches', None, _('annotate with branch names')),
1922 1919 ('', 'dots', None, _('use dots for runs')),
1923 1920 ('s', 'spaces', None, _('separate elements by spaces'))],
1924 1921 _('[OPTION]... [FILE [REV]...]'),
1925 1922 optionalrepo=True)
1926 1923 def debugdag(ui, repo, file_=None, *revs, **opts):
1927 1924 """format the changelog or an index DAG as a concise textual description
1928 1925
1929 1926 If you pass a revlog index, the revlog's DAG is emitted. If you list
1930 1927 revision numbers, they get labeled in the output as rN.
1931 1928
1932 1929 Otherwise, the changelog DAG of the current repo is emitted.
1933 1930 """
1934 1931 spaces = opts.get('spaces')
1935 1932 dots = opts.get('dots')
1936 1933 if file_:
1937 1934 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1938 1935 revs = set((int(r) for r in revs))
1939 1936 def events():
1940 1937 for r in rlog:
1941 1938 yield 'n', (r, list(p for p in rlog.parentrevs(r)
1942 1939 if p != -1))
1943 1940 if r in revs:
1944 1941 yield 'l', (r, "r%i" % r)
1945 1942 elif repo:
1946 1943 cl = repo.changelog
1947 1944 tags = opts.get('tags')
1948 1945 branches = opts.get('branches')
1949 1946 if tags:
1950 1947 labels = {}
1951 1948 for l, n in repo.tags().items():
1952 1949 labels.setdefault(cl.rev(n), []).append(l)
1953 1950 def events():
1954 1951 b = "default"
1955 1952 for r in cl:
1956 1953 if branches:
1957 1954 newb = cl.read(cl.node(r))[5]['branch']
1958 1955 if newb != b:
1959 1956 yield 'a', newb
1960 1957 b = newb
1961 1958 yield 'n', (r, list(p for p in cl.parentrevs(r)
1962 1959 if p != -1))
1963 1960 if tags:
1964 1961 ls = labels.get(r)
1965 1962 if ls:
1966 1963 for l in ls:
1967 1964 yield 'l', (r, l)
1968 1965 else:
1969 1966 raise util.Abort(_('need repo for changelog dag'))
1970 1967
1971 1968 for line in dagparser.dagtextlines(events(),
1972 1969 addspaces=spaces,
1973 1970 wraplabels=True,
1974 1971 wrapannotations=True,
1975 1972 wrapnonlinear=dots,
1976 1973 usedots=dots,
1977 1974 maxlinewidth=70):
1978 1975 ui.write(line)
1979 1976 ui.write("\n")
1980 1977
1981 1978 @command('debugdata',
1982 1979 [('c', 'changelog', False, _('open changelog')),
1983 1980 ('m', 'manifest', False, _('open manifest'))],
1984 1981 _('-c|-m|FILE REV'))
1985 1982 def debugdata(ui, repo, file_, rev=None, **opts):
1986 1983 """dump the contents of a data file revision"""
1987 1984 if opts.get('changelog') or opts.get('manifest'):
1988 1985 file_, rev = None, file_
1989 1986 elif rev is None:
1990 1987 raise error.CommandError('debugdata', _('invalid arguments'))
1991 1988 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1992 1989 try:
1993 1990 ui.write(r.revision(r.lookup(rev)))
1994 1991 except KeyError:
1995 1992 raise util.Abort(_('invalid revision identifier %s') % rev)
1996 1993
1997 1994 @command('debugdate',
1998 1995 [('e', 'extended', None, _('try extended date formats'))],
1999 1996 _('[-e] DATE [RANGE]'),
2000 1997 norepo=True, optionalrepo=True)
2001 1998 def debugdate(ui, date, range=None, **opts):
2002 1999 """parse and display a date"""
2003 2000 if opts["extended"]:
2004 2001 d = util.parsedate(date, util.extendeddateformats)
2005 2002 else:
2006 2003 d = util.parsedate(date)
2007 2004 ui.write(("internal: %s %s\n") % d)
2008 2005 ui.write(("standard: %s\n") % util.datestr(d))
2009 2006 if range:
2010 2007 m = util.matchdate(range)
2011 2008 ui.write(("match: %s\n") % m(d[0]))
2012 2009
2013 2010 @command('debugdiscovery',
2014 2011 [('', 'old', None, _('use old-style discovery')),
2015 2012 ('', 'nonheads', None,
2016 2013 _('use old-style discovery with non-heads included')),
2017 2014 ] + remoteopts,
2018 2015 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
2019 2016 def debugdiscovery(ui, repo, remoteurl="default", **opts):
2020 2017 """runs the changeset discovery protocol in isolation"""
2021 2018 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl),
2022 2019 opts.get('branch'))
2023 2020 remote = hg.peer(repo, opts, remoteurl)
2024 2021 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
2025 2022
2026 2023 # make sure tests are repeatable
2027 2024 random.seed(12323)
2028 2025
2029 2026 def doit(localheads, remoteheads, remote=remote):
2030 2027 if opts.get('old'):
2031 2028 if localheads:
2032 2029 raise util.Abort('cannot use localheads with old style '
2033 2030 'discovery')
2034 2031 if not util.safehasattr(remote, 'branches'):
2035 2032 # enable in-client legacy support
2036 2033 remote = localrepo.locallegacypeer(remote.local())
2037 2034 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
2038 2035 force=True)
2039 2036 common = set(common)
2040 2037 if not opts.get('nonheads'):
2041 2038 ui.write(("unpruned common: %s\n") %
2042 2039 " ".join(sorted(short(n) for n in common)))
2043 2040 dag = dagutil.revlogdag(repo.changelog)
2044 2041 all = dag.ancestorset(dag.internalizeall(common))
2045 2042 common = dag.externalizeall(dag.headsetofconnecteds(all))
2046 2043 else:
2047 2044 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
2048 2045 common = set(common)
2049 2046 rheads = set(hds)
2050 2047 lheads = set(repo.heads())
2051 2048 ui.write(("common heads: %s\n") %
2052 2049 " ".join(sorted(short(n) for n in common)))
2053 2050 if lheads <= common:
2054 2051 ui.write(("local is subset\n"))
2055 2052 elif rheads <= common:
2056 2053 ui.write(("remote is subset\n"))
2057 2054
2058 2055 serverlogs = opts.get('serverlog')
2059 2056 if serverlogs:
2060 2057 for filename in serverlogs:
2061 2058 logfile = open(filename, 'r')
2062 2059 try:
2063 2060 line = logfile.readline()
2064 2061 while line:
2065 2062 parts = line.strip().split(';')
2066 2063 op = parts[1]
2067 2064 if op == 'cg':
2068 2065 pass
2069 2066 elif op == 'cgss':
2070 2067 doit(parts[2].split(' '), parts[3].split(' '))
2071 2068 elif op == 'unb':
2072 2069 doit(parts[3].split(' '), parts[2].split(' '))
2073 2070 line = logfile.readline()
2074 2071 finally:
2075 2072 logfile.close()
2076 2073
2077 2074 else:
2078 2075 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
2079 2076 opts.get('remote_head'))
2080 2077 localrevs = opts.get('local_head')
2081 2078 doit(localrevs, remoterevs)
2082 2079
2083 2080 @command('debugfileset',
2084 2081 [('r', 'rev', '', _('apply the filespec on this revision'), _('REV'))],
2085 2082 _('[-r REV] FILESPEC'))
2086 2083 def debugfileset(ui, repo, expr, **opts):
2087 2084 '''parse and apply a fileset specification'''
2088 2085 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
2089 2086 if ui.verbose:
2090 2087 tree = fileset.parse(expr)[0]
2091 2088 ui.note(tree, "\n")
2092 2089
2093 2090 for f in ctx.getfileset(expr):
2094 2091 ui.write("%s\n" % f)
2095 2092
2096 2093 @command('debugfsinfo', [], _('[PATH]'), norepo=True)
2097 2094 def debugfsinfo(ui, path="."):
2098 2095 """show information detected about current filesystem"""
2099 2096 util.writefile('.debugfsinfo', '')
2100 2097 ui.write(('exec: %s\n') % (util.checkexec(path) and 'yes' or 'no'))
2101 2098 ui.write(('symlink: %s\n') % (util.checklink(path) and 'yes' or 'no'))
2102 2099 ui.write(('hardlink: %s\n') % (util.checknlink(path) and 'yes' or 'no'))
2103 2100 ui.write(('case-sensitive: %s\n') % (util.checkcase('.debugfsinfo')
2104 2101 and 'yes' or 'no'))
2105 2102 os.unlink('.debugfsinfo')
2106 2103
2107 2104 @command('debuggetbundle',
2108 2105 [('H', 'head', [], _('id of head node'), _('ID')),
2109 2106 ('C', 'common', [], _('id of common node'), _('ID')),
2110 2107 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
2111 2108 _('REPO FILE [-H|-C ID]...'),
2112 2109 norepo=True)
2113 2110 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
2114 2111 """retrieves a bundle from a repo
2115 2112
2116 2113 Every ID must be a full-length hex node id string. Saves the bundle to the
2117 2114 given file.
2118 2115 """
2119 2116 repo = hg.peer(ui, opts, repopath)
2120 2117 if not repo.capable('getbundle'):
2121 2118 raise util.Abort("getbundle() not supported by target repository")
2122 2119 args = {}
2123 2120 if common:
2124 2121 args['common'] = [bin(s) for s in common]
2125 2122 if head:
2126 2123 args['heads'] = [bin(s) for s in head]
2127 2124 # TODO: get desired bundlecaps from command line.
2128 2125 args['bundlecaps'] = None
2129 2126 bundle = repo.getbundle('debug', **args)
2130 2127
2131 2128 bundletype = opts.get('type', 'bzip2').lower()
2132 2129 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
2133 2130 bundletype = btypes.get(bundletype)
2134 2131 if bundletype not in changegroup.bundletypes:
2135 2132 raise util.Abort(_('unknown bundle type specified with --type'))
2136 2133 changegroup.writebundle(bundle, bundlepath, bundletype)
2137 2134
2138 2135 @command('debugignore', [], '')
2139 2136 def debugignore(ui, repo, *values, **opts):
2140 2137 """display the combined ignore pattern"""
2141 2138 ignore = repo.dirstate._ignore
2142 2139 includepat = getattr(ignore, 'includepat', None)
2143 2140 if includepat is not None:
2144 2141 ui.write("%s\n" % includepat)
2145 2142 else:
2146 2143 raise util.Abort(_("no ignore patterns found"))
2147 2144
2148 2145 @command('debugindex',
2149 2146 [('c', 'changelog', False, _('open changelog')),
2150 2147 ('m', 'manifest', False, _('open manifest')),
2151 2148 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
2152 2149 _('[-f FORMAT] -c|-m|FILE'),
2153 2150 optionalrepo=True)
2154 2151 def debugindex(ui, repo, file_=None, **opts):
2155 2152 """dump the contents of an index file"""
2156 2153 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
2157 2154 format = opts.get('format', 0)
2158 2155 if format not in (0, 1):
2159 2156 raise util.Abort(_("unknown format %d") % format)
2160 2157
2161 2158 generaldelta = r.version & revlog.REVLOGGENERALDELTA
2162 2159 if generaldelta:
2163 2160 basehdr = ' delta'
2164 2161 else:
2165 2162 basehdr = ' base'
2166 2163
2167 2164 if format == 0:
2168 2165 ui.write(" rev offset length " + basehdr + " linkrev"
2169 2166 " nodeid p1 p2\n")
2170 2167 elif format == 1:
2171 2168 ui.write(" rev flag offset length"
2172 2169 " size " + basehdr + " link p1 p2"
2173 2170 " nodeid\n")
2174 2171
2175 2172 for i in r:
2176 2173 node = r.node(i)
2177 2174 if generaldelta:
2178 2175 base = r.deltaparent(i)
2179 2176 else:
2180 2177 base = r.chainbase(i)
2181 2178 if format == 0:
2182 2179 try:
2183 2180 pp = r.parents(node)
2184 2181 except Exception:
2185 2182 pp = [nullid, nullid]
2186 2183 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
2187 2184 i, r.start(i), r.length(i), base, r.linkrev(i),
2188 2185 short(node), short(pp[0]), short(pp[1])))
2189 2186 elif format == 1:
2190 2187 pr = r.parentrevs(i)
2191 2188 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
2192 2189 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
2193 2190 base, r.linkrev(i), pr[0], pr[1], short(node)))
2194 2191
2195 2192 @command('debugindexdot', [], _('FILE'), optionalrepo=True)
2196 2193 def debugindexdot(ui, repo, file_):
2197 2194 """dump an index DAG as a graphviz dot file"""
2198 2195 r = None
2199 2196 if repo:
2200 2197 filelog = repo.file(file_)
2201 2198 if len(filelog):
2202 2199 r = filelog
2203 2200 if not r:
2204 2201 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
2205 2202 ui.write(("digraph G {\n"))
2206 2203 for i in r:
2207 2204 node = r.node(i)
2208 2205 pp = r.parents(node)
2209 2206 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
2210 2207 if pp[1] != nullid:
2211 2208 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
2212 2209 ui.write("}\n")
2213 2210
2214 2211 @command('debuginstall', [], '', norepo=True)
2215 2212 def debuginstall(ui):
2216 2213 '''test Mercurial installation
2217 2214
2218 2215 Returns 0 on success.
2219 2216 '''
2220 2217
2221 2218 def writetemp(contents):
2222 2219 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
2223 2220 f = os.fdopen(fd, "wb")
2224 2221 f.write(contents)
2225 2222 f.close()
2226 2223 return name
2227 2224
2228 2225 problems = 0
2229 2226
2230 2227 # encoding
2231 2228 ui.status(_("checking encoding (%s)...\n") % encoding.encoding)
2232 2229 try:
2233 2230 encoding.fromlocal("test")
2234 2231 except util.Abort, inst:
2235 2232 ui.write(" %s\n" % inst)
2236 2233 ui.write(_(" (check that your locale is properly set)\n"))
2237 2234 problems += 1
2238 2235
2239 2236 # Python
2240 2237 ui.status(_("checking Python executable (%s)\n") % sys.executable)
2241 2238 ui.status(_("checking Python version (%s)\n")
2242 2239 % ("%s.%s.%s" % sys.version_info[:3]))
2243 2240 ui.status(_("checking Python lib (%s)...\n")
2244 2241 % os.path.dirname(os.__file__))
2245 2242
2246 2243 # compiled modules
2247 2244 ui.status(_("checking installed modules (%s)...\n")
2248 2245 % os.path.dirname(__file__))
2249 2246 try:
2250 2247 import bdiff, mpatch, base85, osutil
2251 2248 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
2252 2249 except Exception, inst:
2253 2250 ui.write(" %s\n" % inst)
2254 2251 ui.write(_(" One or more extensions could not be found"))
2255 2252 ui.write(_(" (check that you compiled the extensions)\n"))
2256 2253 problems += 1
2257 2254
2258 2255 # templates
2259 2256 import templater
2260 2257 p = templater.templatepaths()
2261 2258 ui.status(_("checking templates (%s)...\n") % ' '.join(p))
2262 2259 if p:
2263 2260 m = templater.templatepath("map-cmdline.default")
2264 2261 if m:
2265 2262 # template found, check if it is working
2266 2263 try:
2267 2264 templater.templater(m)
2268 2265 except Exception, inst:
2269 2266 ui.write(" %s\n" % inst)
2270 2267 p = None
2271 2268 else:
2272 2269 ui.write(_(" template 'default' not found\n"))
2273 2270 p = None
2274 2271 else:
2275 2272 ui.write(_(" no template directories found\n"))
2276 2273 if not p:
2277 2274 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
2278 2275 problems += 1
2279 2276
2280 2277 # editor
2281 2278 ui.status(_("checking commit editor...\n"))
2282 2279 editor = ui.geteditor()
2283 2280 cmdpath = util.findexe(shlex.split(editor)[0])
2284 2281 if not cmdpath:
2285 2282 if editor == 'vi':
2286 2283 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
2287 2284 ui.write(_(" (specify a commit editor in your configuration"
2288 2285 " file)\n"))
2289 2286 else:
2290 2287 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
2291 2288 ui.write(_(" (specify a commit editor in your configuration"
2292 2289 " file)\n"))
2293 2290 problems += 1
2294 2291
2295 2292 # check username
2296 2293 ui.status(_("checking username...\n"))
2297 2294 try:
2298 2295 ui.username()
2299 2296 except util.Abort, e:
2300 2297 ui.write(" %s\n" % e)
2301 2298 ui.write(_(" (specify a username in your configuration file)\n"))
2302 2299 problems += 1
2303 2300
2304 2301 if not problems:
2305 2302 ui.status(_("no problems detected\n"))
2306 2303 else:
2307 2304 ui.write(_("%s problems detected,"
2308 2305 " please check your install!\n") % problems)
2309 2306
2310 2307 return problems
2311 2308
2312 2309 @command('debugknown', [], _('REPO ID...'), norepo=True)
2313 2310 def debugknown(ui, repopath, *ids, **opts):
2314 2311 """test whether node ids are known to a repo
2315 2312
2316 2313 Every ID must be a full-length hex node id string. Returns a list of 0s
2317 2314 and 1s indicating unknown/known.
2318 2315 """
2319 2316 repo = hg.peer(ui, opts, repopath)
2320 2317 if not repo.capable('known'):
2321 2318 raise util.Abort("known() not supported by target repository")
2322 2319 flags = repo.known([bin(s) for s in ids])
2323 2320 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
2324 2321
2325 2322 @command('debuglabelcomplete', [], _('LABEL...'))
2326 2323 def debuglabelcomplete(ui, repo, *args):
2327 2324 '''complete "labels" - tags, open branch names, bookmark names'''
2328 2325
2329 2326 labels = set()
2330 2327 labels.update(t[0] for t in repo.tagslist())
2331 2328 labels.update(repo._bookmarks.keys())
2332 2329 labels.update(tag for (tag, heads, tip, closed)
2333 2330 in repo.branchmap().iterbranches() if not closed)
2334 2331 completions = set()
2335 2332 if not args:
2336 2333 args = ['']
2337 2334 for a in args:
2338 2335 completions.update(l for l in labels if l.startswith(a))
2339 2336 ui.write('\n'.join(sorted(completions)))
2340 2337 ui.write('\n')
2341 2338
2342 2339 @command('debuglocks',
2343 2340 [('L', 'force-lock', None, _('free the store lock (DANGEROUS)')),
2344 2341 ('W', 'force-wlock', None,
2345 2342 _('free the working state lock (DANGEROUS)'))],
2346 2343 _(''))
2347 2344 def debuglocks(ui, repo, **opts):
2348 2345 """show or modify state of locks
2349 2346
2350 2347 By default, this command will show which locks are held. This
2351 2348 includes the user and process holding the lock, the amount of time
2352 2349 the lock has been held, and the machine name where the process is
2353 2350 running if it's not local.
2354 2351
2355 2352 Locks protect the integrity of Mercurial's data, so should be
2356 2353 treated with care. System crashes or other interruptions may cause
2357 2354 locks to not be properly released, though Mercurial will usually
2358 2355 detect and remove such stale locks automatically.
2359 2356
2360 2357 However, detecting stale locks may not always be possible (for
2361 2358 instance, on a shared filesystem). Removing locks may also be
2362 2359 blocked by filesystem permissions.
2363 2360
2364 2361 Returns 0 if no locks are held.
2365 2362
2366 2363 """
2367 2364
2368 2365 if opts.get('force_lock'):
2369 2366 repo.svfs.unlink('lock')
2370 2367 if opts.get('force_wlock'):
2371 2368 repo.vfs.unlink('wlock')
2372 2369 if opts.get('force_lock') or opts.get('force_lock'):
2373 2370 return 0
2374 2371
2375 2372 now = time.time()
2376 2373 held = 0
2377 2374
2378 2375 def report(vfs, name, method):
2379 2376 # this causes stale locks to get reaped for more accurate reporting
2380 2377 try:
2381 2378 l = method(False)
2382 2379 except error.LockHeld:
2383 2380 l = None
2384 2381
2385 2382 if l:
2386 2383 l.release()
2387 2384 else:
2388 2385 try:
2389 2386 stat = repo.svfs.lstat(name)
2390 2387 age = now - stat.st_mtime
2391 2388 user = util.username(stat.st_uid)
2392 2389 locker = vfs.readlock(name)
2393 2390 if ":" in locker:
2394 2391 host, pid = locker.split(':')
2395 2392 if host == socket.gethostname():
2396 2393 locker = 'user %s, process %s' % (user, pid)
2397 2394 else:
2398 2395 locker = 'user %s, process %s, host %s' \
2399 2396 % (user, pid, host)
2400 2397 ui.write("%-6s %s (%ds)\n" % (name + ":", locker, age))
2401 2398 return 1
2402 2399 except OSError, e:
2403 2400 if e.errno != errno.ENOENT:
2404 2401 raise
2405 2402
2406 2403 ui.write("%-6s free\n" % (name + ":"))
2407 2404 return 0
2408 2405
2409 2406 held += report(repo.svfs, "lock", repo.lock)
2410 2407 held += report(repo.vfs, "wlock", repo.wlock)
2411 2408
2412 2409 return held
2413 2410
2414 2411 @command('debugobsolete',
2415 2412 [('', 'flags', 0, _('markers flag')),
2416 2413 ('', 'record-parents', False,
2417 2414 _('record parent information for the precursor')),
2418 2415 ('r', 'rev', [], _('display markers relevant to REV')),
2419 2416 ] + commitopts2,
2420 2417 _('[OBSOLETED [REPLACEMENT] [REPL... ]'))
2421 2418 def debugobsolete(ui, repo, precursor=None, *successors, **opts):
2422 2419 """create arbitrary obsolete marker
2423 2420
2424 2421 With no arguments, displays the list of obsolescence markers."""
2425 2422
2426 2423 def parsenodeid(s):
2427 2424 try:
2428 2425 # We do not use revsingle/revrange functions here to accept
2429 2426 # arbitrary node identifiers, possibly not present in the
2430 2427 # local repository.
2431 2428 n = bin(s)
2432 2429 if len(n) != len(nullid):
2433 2430 raise TypeError()
2434 2431 return n
2435 2432 except TypeError:
2436 2433 raise util.Abort('changeset references must be full hexadecimal '
2437 2434 'node identifiers')
2438 2435
2439 2436 if precursor is not None:
2440 2437 if opts['rev']:
2441 2438 raise util.Abort('cannot select revision when creating marker')
2442 2439 metadata = {}
2443 2440 metadata['user'] = opts['user'] or ui.username()
2444 2441 succs = tuple(parsenodeid(succ) for succ in successors)
2445 2442 l = repo.lock()
2446 2443 try:
2447 2444 tr = repo.transaction('debugobsolete')
2448 2445 try:
2449 2446 try:
2450 2447 date = opts.get('date')
2451 2448 if date:
2452 2449 date = util.parsedate(date)
2453 2450 else:
2454 2451 date = None
2455 2452 prec = parsenodeid(precursor)
2456 2453 parents = None
2457 2454 if opts['record_parents']:
2458 2455 if prec not in repo.unfiltered():
2459 2456 raise util.Abort('cannot used --record-parents on '
2460 2457 'unknown changesets')
2461 2458 parents = repo.unfiltered()[prec].parents()
2462 2459 parents = tuple(p.node() for p in parents)
2463 2460 repo.obsstore.create(tr, prec, succs, opts['flags'],
2464 2461 parents=parents, date=date,
2465 2462 metadata=metadata)
2466 2463 tr.close()
2467 2464 except ValueError, exc:
2468 2465 raise util.Abort(_('bad obsmarker input: %s') % exc)
2469 2466 finally:
2470 2467 tr.release()
2471 2468 finally:
2472 2469 l.release()
2473 2470 else:
2474 2471 if opts['rev']:
2475 2472 revs = scmutil.revrange(repo, opts['rev'])
2476 2473 nodes = [repo[r].node() for r in revs]
2477 2474 markers = list(obsolete.getmarkers(repo, nodes=nodes))
2478 2475 markers.sort(key=lambda x: x._data)
2479 2476 else:
2480 2477 markers = obsolete.getmarkers(repo)
2481 2478
2482 2479 for m in markers:
2483 2480 cmdutil.showmarker(ui, m)
2484 2481
2485 2482 @command('debugpathcomplete',
2486 2483 [('f', 'full', None, _('complete an entire path')),
2487 2484 ('n', 'normal', None, _('show only normal files')),
2488 2485 ('a', 'added', None, _('show only added files')),
2489 2486 ('r', 'removed', None, _('show only removed files'))],
2490 2487 _('FILESPEC...'))
2491 2488 def debugpathcomplete(ui, repo, *specs, **opts):
2492 2489 '''complete part or all of a tracked path
2493 2490
2494 2491 This command supports shells that offer path name completion. It
2495 2492 currently completes only files already known to the dirstate.
2496 2493
2497 2494 Completion extends only to the next path segment unless
2498 2495 --full is specified, in which case entire paths are used.'''
2499 2496
2500 2497 def complete(path, acceptable):
2501 2498 dirstate = repo.dirstate
2502 2499 spec = os.path.normpath(os.path.join(os.getcwd(), path))
2503 2500 rootdir = repo.root + os.sep
2504 2501 if spec != repo.root and not spec.startswith(rootdir):
2505 2502 return [], []
2506 2503 if os.path.isdir(spec):
2507 2504 spec += '/'
2508 2505 spec = spec[len(rootdir):]
2509 2506 fixpaths = os.sep != '/'
2510 2507 if fixpaths:
2511 2508 spec = spec.replace(os.sep, '/')
2512 2509 speclen = len(spec)
2513 2510 fullpaths = opts['full']
2514 2511 files, dirs = set(), set()
2515 2512 adddir, addfile = dirs.add, files.add
2516 2513 for f, st in dirstate.iteritems():
2517 2514 if f.startswith(spec) and st[0] in acceptable:
2518 2515 if fixpaths:
2519 2516 f = f.replace('/', os.sep)
2520 2517 if fullpaths:
2521 2518 addfile(f)
2522 2519 continue
2523 2520 s = f.find(os.sep, speclen)
2524 2521 if s >= 0:
2525 2522 adddir(f[:s])
2526 2523 else:
2527 2524 addfile(f)
2528 2525 return files, dirs
2529 2526
2530 2527 acceptable = ''
2531 2528 if opts['normal']:
2532 2529 acceptable += 'nm'
2533 2530 if opts['added']:
2534 2531 acceptable += 'a'
2535 2532 if opts['removed']:
2536 2533 acceptable += 'r'
2537 2534 cwd = repo.getcwd()
2538 2535 if not specs:
2539 2536 specs = ['.']
2540 2537
2541 2538 files, dirs = set(), set()
2542 2539 for spec in specs:
2543 2540 f, d = complete(spec, acceptable or 'nmar')
2544 2541 files.update(f)
2545 2542 dirs.update(d)
2546 2543 files.update(dirs)
2547 2544 ui.write('\n'.join(repo.pathto(p, cwd) for p in sorted(files)))
2548 2545 ui.write('\n')
2549 2546
2550 2547 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'), norepo=True)
2551 2548 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
2552 2549 '''access the pushkey key/value protocol
2553 2550
2554 2551 With two args, list the keys in the given namespace.
2555 2552
2556 2553 With five args, set a key to new if it currently is set to old.
2557 2554 Reports success or failure.
2558 2555 '''
2559 2556
2560 2557 target = hg.peer(ui, {}, repopath)
2561 2558 if keyinfo:
2562 2559 key, old, new = keyinfo
2563 2560 r = target.pushkey(namespace, key, old, new)
2564 2561 ui.status(str(r) + '\n')
2565 2562 return not r
2566 2563 else:
2567 2564 for k, v in sorted(target.listkeys(namespace).iteritems()):
2568 2565 ui.write("%s\t%s\n" % (k.encode('string-escape'),
2569 2566 v.encode('string-escape')))
2570 2567
2571 2568 @command('debugpvec', [], _('A B'))
2572 2569 def debugpvec(ui, repo, a, b=None):
2573 2570 ca = scmutil.revsingle(repo, a)
2574 2571 cb = scmutil.revsingle(repo, b)
2575 2572 pa = pvec.ctxpvec(ca)
2576 2573 pb = pvec.ctxpvec(cb)
2577 2574 if pa == pb:
2578 2575 rel = "="
2579 2576 elif pa > pb:
2580 2577 rel = ">"
2581 2578 elif pa < pb:
2582 2579 rel = "<"
2583 2580 elif pa | pb:
2584 2581 rel = "|"
2585 2582 ui.write(_("a: %s\n") % pa)
2586 2583 ui.write(_("b: %s\n") % pb)
2587 2584 ui.write(_("depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
2588 2585 ui.write(_("delta: %d hdist: %d distance: %d relation: %s\n") %
2589 2586 (abs(pa._depth - pb._depth), pvec._hamming(pa._vec, pb._vec),
2590 2587 pa.distance(pb), rel))
2591 2588
2592 2589 @command('debugrebuilddirstate|debugrebuildstate',
2593 2590 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
2594 2591 _('[-r REV]'))
2595 2592 def debugrebuilddirstate(ui, repo, rev):
2596 2593 """rebuild the dirstate as it would look like for the given revision
2597 2594
2598 2595 If no revision is specified the first current parent will be used.
2599 2596
2600 2597 The dirstate will be set to the files of the given revision.
2601 2598 The actual working directory content or existing dirstate
2602 2599 information such as adds or removes is not considered.
2603 2600
2604 2601 One use of this command is to make the next :hg:`status` invocation
2605 2602 check the actual file content.
2606 2603 """
2607 2604 ctx = scmutil.revsingle(repo, rev)
2608 2605 wlock = repo.wlock()
2609 2606 try:
2610 2607 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
2611 2608 finally:
2612 2609 wlock.release()
2613 2610
2614 2611 @command('debugrename',
2615 2612 [('r', 'rev', '', _('revision to debug'), _('REV'))],
2616 2613 _('[-r REV] FILE'))
2617 2614 def debugrename(ui, repo, file1, *pats, **opts):
2618 2615 """dump rename information"""
2619 2616
2620 2617 ctx = scmutil.revsingle(repo, opts.get('rev'))
2621 2618 m = scmutil.match(ctx, (file1,) + pats, opts)
2622 2619 for abs in ctx.walk(m):
2623 2620 fctx = ctx[abs]
2624 2621 o = fctx.filelog().renamed(fctx.filenode())
2625 2622 rel = m.rel(abs)
2626 2623 if o:
2627 2624 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
2628 2625 else:
2629 2626 ui.write(_("%s not renamed\n") % rel)
2630 2627
2631 2628 @command('debugrevlog',
2632 2629 [('c', 'changelog', False, _('open changelog')),
2633 2630 ('m', 'manifest', False, _('open manifest')),
2634 2631 ('d', 'dump', False, _('dump index data'))],
2635 2632 _('-c|-m|FILE'),
2636 2633 optionalrepo=True)
2637 2634 def debugrevlog(ui, repo, file_=None, **opts):
2638 2635 """show data and statistics about a revlog"""
2639 2636 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
2640 2637
2641 2638 if opts.get("dump"):
2642 2639 numrevs = len(r)
2643 2640 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
2644 2641 " rawsize totalsize compression heads chainlen\n")
2645 2642 ts = 0
2646 2643 heads = set()
2647 2644 rindex = r.index
2648 2645
2649 2646 def chainbaseandlen(rev):
2650 2647 clen = 0
2651 2648 base = rindex[rev][3]
2652 2649 while base != rev:
2653 2650 clen += 1
2654 2651 rev = base
2655 2652 base = rindex[rev][3]
2656 2653 return base, clen
2657 2654
2658 2655 for rev in xrange(numrevs):
2659 2656 dbase = r.deltaparent(rev)
2660 2657 if dbase == -1:
2661 2658 dbase = rev
2662 2659 cbase, clen = chainbaseandlen(rev)
2663 2660 p1, p2 = r.parentrevs(rev)
2664 2661 rs = r.rawsize(rev)
2665 2662 ts = ts + rs
2666 2663 heads -= set(r.parentrevs(rev))
2667 2664 heads.add(rev)
2668 2665 ui.write("%5d %5d %5d %5d %5d %10d %4d %4d %4d %7d %9d "
2669 2666 "%11d %5d %8d\n" %
2670 2667 (rev, p1, p2, r.start(rev), r.end(rev),
2671 2668 r.start(dbase), r.start(cbase),
2672 2669 r.start(p1), r.start(p2),
2673 2670 rs, ts, ts / r.end(rev), len(heads), clen))
2674 2671 return 0
2675 2672
2676 2673 v = r.version
2677 2674 format = v & 0xFFFF
2678 2675 flags = []
2679 2676 gdelta = False
2680 2677 if v & revlog.REVLOGNGINLINEDATA:
2681 2678 flags.append('inline')
2682 2679 if v & revlog.REVLOGGENERALDELTA:
2683 2680 gdelta = True
2684 2681 flags.append('generaldelta')
2685 2682 if not flags:
2686 2683 flags = ['(none)']
2687 2684
2688 2685 nummerges = 0
2689 2686 numfull = 0
2690 2687 numprev = 0
2691 2688 nump1 = 0
2692 2689 nump2 = 0
2693 2690 numother = 0
2694 2691 nump1prev = 0
2695 2692 nump2prev = 0
2696 2693 chainlengths = []
2697 2694
2698 2695 datasize = [None, 0, 0L]
2699 2696 fullsize = [None, 0, 0L]
2700 2697 deltasize = [None, 0, 0L]
2701 2698
2702 2699 def addsize(size, l):
2703 2700 if l[0] is None or size < l[0]:
2704 2701 l[0] = size
2705 2702 if size > l[1]:
2706 2703 l[1] = size
2707 2704 l[2] += size
2708 2705
2709 2706 numrevs = len(r)
2710 2707 for rev in xrange(numrevs):
2711 2708 p1, p2 = r.parentrevs(rev)
2712 2709 delta = r.deltaparent(rev)
2713 2710 if format > 0:
2714 2711 addsize(r.rawsize(rev), datasize)
2715 2712 if p2 != nullrev:
2716 2713 nummerges += 1
2717 2714 size = r.length(rev)
2718 2715 if delta == nullrev:
2719 2716 chainlengths.append(0)
2720 2717 numfull += 1
2721 2718 addsize(size, fullsize)
2722 2719 else:
2723 2720 chainlengths.append(chainlengths[delta] + 1)
2724 2721 addsize(size, deltasize)
2725 2722 if delta == rev - 1:
2726 2723 numprev += 1
2727 2724 if delta == p1:
2728 2725 nump1prev += 1
2729 2726 elif delta == p2:
2730 2727 nump2prev += 1
2731 2728 elif delta == p1:
2732 2729 nump1 += 1
2733 2730 elif delta == p2:
2734 2731 nump2 += 1
2735 2732 elif delta != nullrev:
2736 2733 numother += 1
2737 2734
2738 2735 # Adjust size min value for empty cases
2739 2736 for size in (datasize, fullsize, deltasize):
2740 2737 if size[0] is None:
2741 2738 size[0] = 0
2742 2739
2743 2740 numdeltas = numrevs - numfull
2744 2741 numoprev = numprev - nump1prev - nump2prev
2745 2742 totalrawsize = datasize[2]
2746 2743 datasize[2] /= numrevs
2747 2744 fulltotal = fullsize[2]
2748 2745 fullsize[2] /= numfull
2749 2746 deltatotal = deltasize[2]
2750 2747 if numrevs - numfull > 0:
2751 2748 deltasize[2] /= numrevs - numfull
2752 2749 totalsize = fulltotal + deltatotal
2753 2750 avgchainlen = sum(chainlengths) / numrevs
2754 2751 compratio = totalrawsize / totalsize
2755 2752
2756 2753 basedfmtstr = '%%%dd\n'
2757 2754 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
2758 2755
2759 2756 def dfmtstr(max):
2760 2757 return basedfmtstr % len(str(max))
2761 2758 def pcfmtstr(max, padding=0):
2762 2759 return basepcfmtstr % (len(str(max)), ' ' * padding)
2763 2760
2764 2761 def pcfmt(value, total):
2765 2762 return (value, 100 * float(value) / total)
2766 2763
2767 2764 ui.write(('format : %d\n') % format)
2768 2765 ui.write(('flags : %s\n') % ', '.join(flags))
2769 2766
2770 2767 ui.write('\n')
2771 2768 fmt = pcfmtstr(totalsize)
2772 2769 fmt2 = dfmtstr(totalsize)
2773 2770 ui.write(('revisions : ') + fmt2 % numrevs)
2774 2771 ui.write((' merges : ') + fmt % pcfmt(nummerges, numrevs))
2775 2772 ui.write((' normal : ') + fmt % pcfmt(numrevs - nummerges, numrevs))
2776 2773 ui.write(('revisions : ') + fmt2 % numrevs)
2777 2774 ui.write((' full : ') + fmt % pcfmt(numfull, numrevs))
2778 2775 ui.write((' deltas : ') + fmt % pcfmt(numdeltas, numrevs))
2779 2776 ui.write(('revision size : ') + fmt2 % totalsize)
2780 2777 ui.write((' full : ') + fmt % pcfmt(fulltotal, totalsize))
2781 2778 ui.write((' deltas : ') + fmt % pcfmt(deltatotal, totalsize))
2782 2779
2783 2780 ui.write('\n')
2784 2781 fmt = dfmtstr(max(avgchainlen, compratio))
2785 2782 ui.write(('avg chain length : ') + fmt % avgchainlen)
2786 2783 ui.write(('compression ratio : ') + fmt % compratio)
2787 2784
2788 2785 if format > 0:
2789 2786 ui.write('\n')
2790 2787 ui.write(('uncompressed data size (min/max/avg) : %d / %d / %d\n')
2791 2788 % tuple(datasize))
2792 2789 ui.write(('full revision size (min/max/avg) : %d / %d / %d\n')
2793 2790 % tuple(fullsize))
2794 2791 ui.write(('delta size (min/max/avg) : %d / %d / %d\n')
2795 2792 % tuple(deltasize))
2796 2793
2797 2794 if numdeltas > 0:
2798 2795 ui.write('\n')
2799 2796 fmt = pcfmtstr(numdeltas)
2800 2797 fmt2 = pcfmtstr(numdeltas, 4)
2801 2798 ui.write(('deltas against prev : ') + fmt % pcfmt(numprev, numdeltas))
2802 2799 if numprev > 0:
2803 2800 ui.write((' where prev = p1 : ') + fmt2 % pcfmt(nump1prev,
2804 2801 numprev))
2805 2802 ui.write((' where prev = p2 : ') + fmt2 % pcfmt(nump2prev,
2806 2803 numprev))
2807 2804 ui.write((' other : ') + fmt2 % pcfmt(numoprev,
2808 2805 numprev))
2809 2806 if gdelta:
2810 2807 ui.write(('deltas against p1 : ')
2811 2808 + fmt % pcfmt(nump1, numdeltas))
2812 2809 ui.write(('deltas against p2 : ')
2813 2810 + fmt % pcfmt(nump2, numdeltas))
2814 2811 ui.write(('deltas against other : ') + fmt % pcfmt(numother,
2815 2812 numdeltas))
2816 2813
2817 2814 @command('debugrevspec',
2818 2815 [('', 'optimize', None, _('print parsed tree after optimizing'))],
2819 2816 ('REVSPEC'))
2820 2817 def debugrevspec(ui, repo, expr, **opts):
2821 2818 """parse and apply a revision specification
2822 2819
2823 2820 Use --verbose to print the parsed tree before and after aliases
2824 2821 expansion.
2825 2822 """
2826 2823 if ui.verbose:
2827 2824 tree = revset.parse(expr)[0]
2828 2825 ui.note(revset.prettyformat(tree), "\n")
2829 2826 newtree = revset.findaliases(ui, tree)
2830 2827 if newtree != tree:
2831 2828 ui.note(revset.prettyformat(newtree), "\n")
2832 2829 if opts["optimize"]:
2833 2830 weight, optimizedtree = revset.optimize(newtree, True)
2834 2831 ui.note("* optimized:\n", revset.prettyformat(optimizedtree), "\n")
2835 2832 func = revset.match(ui, expr)
2836 2833 for c in func(repo, revset.spanset(repo)):
2837 2834 ui.write("%s\n" % c)
2838 2835
2839 2836 @command('debugsetparents', [], _('REV1 [REV2]'))
2840 2837 def debugsetparents(ui, repo, rev1, rev2=None):
2841 2838 """manually set the parents of the current working directory
2842 2839
2843 2840 This is useful for writing repository conversion tools, but should
2844 2841 be used with care.
2845 2842
2846 2843 Returns 0 on success.
2847 2844 """
2848 2845
2849 2846 r1 = scmutil.revsingle(repo, rev1).node()
2850 2847 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2851 2848
2852 2849 wlock = repo.wlock()
2853 2850 try:
2854 2851 repo.dirstate.beginparentchange()
2855 2852 repo.setparents(r1, r2)
2856 2853 repo.dirstate.endparentchange()
2857 2854 finally:
2858 2855 wlock.release()
2859 2856
2860 2857 @command('debugdirstate|debugstate',
2861 2858 [('', 'nodates', None, _('do not display the saved mtime')),
2862 2859 ('', 'datesort', None, _('sort by saved mtime'))],
2863 2860 _('[OPTION]...'))
2864 2861 def debugstate(ui, repo, nodates=None, datesort=None):
2865 2862 """show the contents of the current dirstate"""
2866 2863 timestr = ""
2867 2864 showdate = not nodates
2868 2865 if datesort:
2869 2866 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2870 2867 else:
2871 2868 keyfunc = None # sort by filename
2872 2869 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2873 2870 if showdate:
2874 2871 if ent[3] == -1:
2875 2872 # Pad or slice to locale representation
2876 2873 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2877 2874 time.localtime(0)))
2878 2875 timestr = 'unset'
2879 2876 timestr = (timestr[:locale_len] +
2880 2877 ' ' * (locale_len - len(timestr)))
2881 2878 else:
2882 2879 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2883 2880 time.localtime(ent[3]))
2884 2881 if ent[1] & 020000:
2885 2882 mode = 'lnk'
2886 2883 else:
2887 2884 mode = '%3o' % (ent[1] & 0777 & ~util.umask)
2888 2885 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2889 2886 for f in repo.dirstate.copies():
2890 2887 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2891 2888
2892 2889 @command('debugsub',
2893 2890 [('r', 'rev', '',
2894 2891 _('revision to check'), _('REV'))],
2895 2892 _('[-r REV] [REV]'))
2896 2893 def debugsub(ui, repo, rev=None):
2897 2894 ctx = scmutil.revsingle(repo, rev, None)
2898 2895 for k, v in sorted(ctx.substate.items()):
2899 2896 ui.write(('path %s\n') % k)
2900 2897 ui.write((' source %s\n') % v[0])
2901 2898 ui.write((' revision %s\n') % v[1])
2902 2899
2903 2900 @command('debugsuccessorssets',
2904 2901 [],
2905 2902 _('[REV]'))
2906 2903 def debugsuccessorssets(ui, repo, *revs):
2907 2904 """show set of successors for revision
2908 2905
2909 2906 A successors set of changeset A is a consistent group of revisions that
2910 2907 succeed A. It contains non-obsolete changesets only.
2911 2908
2912 2909 In most cases a changeset A has a single successors set containing a single
2913 2910 successor (changeset A replaced by A').
2914 2911
2915 2912 A changeset that is made obsolete with no successors are called "pruned".
2916 2913 Such changesets have no successors sets at all.
2917 2914
2918 2915 A changeset that has been "split" will have a successors set containing
2919 2916 more than one successor.
2920 2917
2921 2918 A changeset that has been rewritten in multiple different ways is called
2922 2919 "divergent". Such changesets have multiple successor sets (each of which
2923 2920 may also be split, i.e. have multiple successors).
2924 2921
2925 2922 Results are displayed as follows::
2926 2923
2927 2924 <rev1>
2928 2925 <successors-1A>
2929 2926 <rev2>
2930 2927 <successors-2A>
2931 2928 <successors-2B1> <successors-2B2> <successors-2B3>
2932 2929
2933 2930 Here rev2 has two possible (i.e. divergent) successors sets. The first
2934 2931 holds one element, whereas the second holds three (i.e. the changeset has
2935 2932 been split).
2936 2933 """
2937 2934 # passed to successorssets caching computation from one call to another
2938 2935 cache = {}
2939 2936 ctx2str = str
2940 2937 node2str = short
2941 2938 if ui.debug():
2942 2939 def ctx2str(ctx):
2943 2940 return ctx.hex()
2944 2941 node2str = hex
2945 2942 for rev in scmutil.revrange(repo, revs):
2946 2943 ctx = repo[rev]
2947 2944 ui.write('%s\n'% ctx2str(ctx))
2948 2945 for succsset in obsolete.successorssets(repo, ctx.node(), cache):
2949 2946 if succsset:
2950 2947 ui.write(' ')
2951 2948 ui.write(node2str(succsset[0]))
2952 2949 for node in succsset[1:]:
2953 2950 ui.write(' ')
2954 2951 ui.write(node2str(node))
2955 2952 ui.write('\n')
2956 2953
2957 2954 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'), inferrepo=True)
2958 2955 def debugwalk(ui, repo, *pats, **opts):
2959 2956 """show how files match on given patterns"""
2960 2957 m = scmutil.match(repo[None], pats, opts)
2961 2958 items = list(repo.walk(m))
2962 2959 if not items:
2963 2960 return
2964 2961 f = lambda fn: fn
2965 2962 if ui.configbool('ui', 'slash') and os.sep != '/':
2966 2963 f = lambda fn: util.normpath(fn)
2967 2964 fmt = 'f %%-%ds %%-%ds %%s' % (
2968 2965 max([len(abs) for abs in items]),
2969 2966 max([len(m.rel(abs)) for abs in items]))
2970 2967 for abs in items:
2971 2968 line = fmt % (abs, f(m.rel(abs)), m.exact(abs) and 'exact' or '')
2972 2969 ui.write("%s\n" % line.rstrip())
2973 2970
2974 2971 @command('debugwireargs',
2975 2972 [('', 'three', '', 'three'),
2976 2973 ('', 'four', '', 'four'),
2977 2974 ('', 'five', '', 'five'),
2978 2975 ] + remoteopts,
2979 2976 _('REPO [OPTIONS]... [ONE [TWO]]'),
2980 2977 norepo=True)
2981 2978 def debugwireargs(ui, repopath, *vals, **opts):
2982 2979 repo = hg.peer(ui, opts, repopath)
2983 2980 for opt in remoteopts:
2984 2981 del opts[opt[1]]
2985 2982 args = {}
2986 2983 for k, v in opts.iteritems():
2987 2984 if v:
2988 2985 args[k] = v
2989 2986 # run twice to check that we don't mess up the stream for the next command
2990 2987 res1 = repo.debugwireargs(*vals, **args)
2991 2988 res2 = repo.debugwireargs(*vals, **args)
2992 2989 ui.write("%s\n" % res1)
2993 2990 if res1 != res2:
2994 2991 ui.warn("%s\n" % res2)
2995 2992
2996 2993 @command('^diff',
2997 2994 [('r', 'rev', [], _('revision'), _('REV')),
2998 2995 ('c', 'change', '', _('change made by revision'), _('REV'))
2999 2996 ] + diffopts + diffopts2 + walkopts + subrepoopts,
3000 2997 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'),
3001 2998 inferrepo=True)
3002 2999 def diff(ui, repo, *pats, **opts):
3003 3000 """diff repository (or selected files)
3004 3001
3005 3002 Show differences between revisions for the specified files.
3006 3003
3007 3004 Differences between files are shown using the unified diff format.
3008 3005
3009 3006 .. note::
3010 3007
3011 3008 diff may generate unexpected results for merges, as it will
3012 3009 default to comparing against the working directory's first
3013 3010 parent changeset if no revisions are specified.
3014 3011
3015 3012 When two revision arguments are given, then changes are shown
3016 3013 between those revisions. If only one revision is specified then
3017 3014 that revision is compared to the working directory, and, when no
3018 3015 revisions are specified, the working directory files are compared
3019 3016 to its parent.
3020 3017
3021 3018 Alternatively you can specify -c/--change with a revision to see
3022 3019 the changes in that changeset relative to its first parent.
3023 3020
3024 3021 Without the -a/--text option, diff will avoid generating diffs of
3025 3022 files it detects as binary. With -a, diff will generate a diff
3026 3023 anyway, probably with undesirable results.
3027 3024
3028 3025 Use the -g/--git option to generate diffs in the git extended diff
3029 3026 format. For more information, read :hg:`help diffs`.
3030 3027
3031 3028 .. container:: verbose
3032 3029
3033 3030 Examples:
3034 3031
3035 3032 - compare a file in the current working directory to its parent::
3036 3033
3037 3034 hg diff foo.c
3038 3035
3039 3036 - compare two historical versions of a directory, with rename info::
3040 3037
3041 3038 hg diff --git -r 1.0:1.2 lib/
3042 3039
3043 3040 - get change stats relative to the last change on some date::
3044 3041
3045 3042 hg diff --stat -r "date('may 2')"
3046 3043
3047 3044 - diff all newly-added files that contain a keyword::
3048 3045
3049 3046 hg diff "set:added() and grep(GNU)"
3050 3047
3051 3048 - compare a revision and its parents::
3052 3049
3053 3050 hg diff -c 9353 # compare against first parent
3054 3051 hg diff -r 9353^:9353 # same using revset syntax
3055 3052 hg diff -r 9353^2:9353 # compare against the second parent
3056 3053
3057 3054 Returns 0 on success.
3058 3055 """
3059 3056
3060 3057 revs = opts.get('rev')
3061 3058 change = opts.get('change')
3062 3059 stat = opts.get('stat')
3063 3060 reverse = opts.get('reverse')
3064 3061
3065 3062 if revs and change:
3066 3063 msg = _('cannot specify --rev and --change at the same time')
3067 3064 raise util.Abort(msg)
3068 3065 elif change:
3069 3066 node2 = scmutil.revsingle(repo, change, None).node()
3070 3067 node1 = repo[node2].p1().node()
3071 3068 else:
3072 3069 node1, node2 = scmutil.revpair(repo, revs)
3073 3070
3074 3071 if reverse:
3075 3072 node1, node2 = node2, node1
3076 3073
3077 3074 diffopts = patch.diffopts(ui, opts)
3078 3075 m = scmutil.match(repo[node2], pats, opts)
3079 3076 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
3080 3077 listsubrepos=opts.get('subrepos'))
3081 3078
3082 3079 @command('^export',
3083 3080 [('o', 'output', '',
3084 3081 _('print output to file with formatted name'), _('FORMAT')),
3085 3082 ('', 'switch-parent', None, _('diff against the second parent')),
3086 3083 ('r', 'rev', [], _('revisions to export'), _('REV')),
3087 3084 ] + diffopts,
3088 3085 _('[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'))
3089 3086 def export(ui, repo, *changesets, **opts):
3090 3087 """dump the header and diffs for one or more changesets
3091 3088
3092 3089 Print the changeset header and diffs for one or more revisions.
3093 3090 If no revision is given, the parent of the working directory is used.
3094 3091
3095 3092 The information shown in the changeset header is: author, date,
3096 3093 branch name (if non-default), changeset hash, parent(s) and commit
3097 3094 comment.
3098 3095
3099 3096 .. note::
3100 3097
3101 3098 export may generate unexpected diff output for merge
3102 3099 changesets, as it will compare the merge changeset against its
3103 3100 first parent only.
3104 3101
3105 3102 Output may be to a file, in which case the name of the file is
3106 3103 given using a format string. The formatting rules are as follows:
3107 3104
3108 3105 :``%%``: literal "%" character
3109 3106 :``%H``: changeset hash (40 hexadecimal digits)
3110 3107 :``%N``: number of patches being generated
3111 3108 :``%R``: changeset revision number
3112 3109 :``%b``: basename of the exporting repository
3113 3110 :``%h``: short-form changeset hash (12 hexadecimal digits)
3114 3111 :``%m``: first line of the commit message (only alphanumeric characters)
3115 3112 :``%n``: zero-padded sequence number, starting at 1
3116 3113 :``%r``: zero-padded changeset revision number
3117 3114
3118 3115 Without the -a/--text option, export will avoid generating diffs
3119 3116 of files it detects as binary. With -a, export will generate a
3120 3117 diff anyway, probably with undesirable results.
3121 3118
3122 3119 Use the -g/--git option to generate diffs in the git extended diff
3123 3120 format. See :hg:`help diffs` for more information.
3124 3121
3125 3122 With the --switch-parent option, the diff will be against the
3126 3123 second parent. It can be useful to review a merge.
3127 3124
3128 3125 .. container:: verbose
3129 3126
3130 3127 Examples:
3131 3128
3132 3129 - use export and import to transplant a bugfix to the current
3133 3130 branch::
3134 3131
3135 3132 hg export -r 9353 | hg import -
3136 3133
3137 3134 - export all the changesets between two revisions to a file with
3138 3135 rename information::
3139 3136
3140 3137 hg export --git -r 123:150 > changes.txt
3141 3138
3142 3139 - split outgoing changes into a series of patches with
3143 3140 descriptive names::
3144 3141
3145 3142 hg export -r "outgoing()" -o "%n-%m.patch"
3146 3143
3147 3144 Returns 0 on success.
3148 3145 """
3149 3146 changesets += tuple(opts.get('rev', []))
3150 3147 if not changesets:
3151 3148 changesets = ['.']
3152 3149 revs = scmutil.revrange(repo, changesets)
3153 3150 if not revs:
3154 3151 raise util.Abort(_("export requires at least one changeset"))
3155 3152 if len(revs) > 1:
3156 3153 ui.note(_('exporting patches:\n'))
3157 3154 else:
3158 3155 ui.note(_('exporting patch:\n'))
3159 3156 cmdutil.export(repo, revs, template=opts.get('output'),
3160 3157 switch_parent=opts.get('switch_parent'),
3161 3158 opts=patch.diffopts(ui, opts))
3162 3159
3163 3160 @command('files',
3164 3161 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3165 3162 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3166 3163 ] + walkopts + formatteropts,
3167 3164 _('[OPTION]... [PATTERN]...'))
3168 3165 def files(ui, repo, *pats, **opts):
3169 3166 """list tracked files
3170 3167
3171 3168 Print files under Mercurial control in the working directory or
3172 3169 specified revision whose names match the given patterns (excluding
3173 3170 removed files).
3174 3171
3175 3172 If no patterns are given to match, this command prints the names
3176 3173 of all files under Mercurial control in the working copy.
3177 3174
3178 3175 .. container:: verbose
3179 3176
3180 3177 Examples:
3181 3178
3182 3179 - list all files under the current directory::
3183 3180
3184 3181 hg files .
3185 3182
3186 3183 - shows sizes and flags for current revision::
3187 3184
3188 3185 hg files -vr .
3189 3186
3190 3187 - list all files named README::
3191 3188
3192 3189 hg files -I "**/README"
3193 3190
3194 3191 - list all binary files::
3195 3192
3196 3193 hg files "set:binary()"
3197 3194
3198 3195 - find files containing a regular expression:
3199 3196
3200 3197 hg files "set:grep('bob')"
3201 3198
3202 3199 - search tracked file contents with xargs and grep::
3203 3200
3204 3201 hg files -0 | xargs -0 grep foo
3205 3202
3206 3203 See :hg:'help pattern' and :hg:'help revsets' for more information
3207 3204 on specifying file patterns.
3208 3205
3209 3206 Returns 0 if a match is found, 1 otherwise.
3210 3207
3211 3208 """
3212 3209 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3213 3210 rev = ctx.rev()
3214 3211 ret = 1
3215 3212
3216 3213 end = '\n'
3217 3214 if opts.get('print0'):
3218 3215 end = '\0'
3219 3216 fm = ui.formatter('files', opts)
3220 3217 fmt = '%s' + end
3221 3218
3222 3219 m = scmutil.match(ctx, pats, opts)
3223 3220 ds = repo.dirstate
3224 3221 for f in ctx.matches(m):
3225 3222 if rev is None and ds[f] == 'r':
3226 3223 continue
3227 3224 fm.startitem()
3228 3225 if ui.verbose:
3229 3226 fc = ctx[f]
3230 3227 fm.write('size flags', '% 10d % 1s ', fc.size(), fc.flags())
3231 3228 fm.data(abspath=f)
3232 3229 fm.write('path', fmt, m.rel(f))
3233 3230 ret = 0
3234 3231
3235 3232 fm.end()
3236 3233
3237 3234 return ret
3238 3235
3239 3236 @command('^forget', walkopts, _('[OPTION]... FILE...'), inferrepo=True)
3240 3237 def forget(ui, repo, *pats, **opts):
3241 3238 """forget the specified files on the next commit
3242 3239
3243 3240 Mark the specified files so they will no longer be tracked
3244 3241 after the next commit.
3245 3242
3246 3243 This only removes files from the current branch, not from the
3247 3244 entire project history, and it does not delete them from the
3248 3245 working directory.
3249 3246
3250 3247 To undo a forget before the next commit, see :hg:`add`.
3251 3248
3252 3249 .. container:: verbose
3253 3250
3254 3251 Examples:
3255 3252
3256 3253 - forget newly-added binary files::
3257 3254
3258 3255 hg forget "set:added() and binary()"
3259 3256
3260 3257 - forget files that would be excluded by .hgignore::
3261 3258
3262 3259 hg forget "set:hgignore()"
3263 3260
3264 3261 Returns 0 on success.
3265 3262 """
3266 3263
3267 3264 if not pats:
3268 3265 raise util.Abort(_('no files specified'))
3269 3266
3270 3267 m = scmutil.match(repo[None], pats, opts)
3271 3268 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
3272 3269 return rejected and 1 or 0
3273 3270
3274 3271 @command(
3275 3272 'graft',
3276 3273 [('r', 'rev', [], _('revisions to graft'), _('REV')),
3277 3274 ('c', 'continue', False, _('resume interrupted graft')),
3278 3275 ('e', 'edit', False, _('invoke editor on commit messages')),
3279 3276 ('', 'log', None, _('append graft info to log message')),
3280 3277 ('f', 'force', False, _('force graft')),
3281 3278 ('D', 'currentdate', False,
3282 3279 _('record the current date as commit date')),
3283 3280 ('U', 'currentuser', False,
3284 3281 _('record the current user as committer'), _('DATE'))]
3285 3282 + commitopts2 + mergetoolopts + dryrunopts,
3286 3283 _('[OPTION]... [-r] REV...'))
3287 3284 def graft(ui, repo, *revs, **opts):
3288 3285 '''copy changes from other branches onto the current branch
3289 3286
3290 3287 This command uses Mercurial's merge logic to copy individual
3291 3288 changes from other branches without merging branches in the
3292 3289 history graph. This is sometimes known as 'backporting' or
3293 3290 'cherry-picking'. By default, graft will copy user, date, and
3294 3291 description from the source changesets.
3295 3292
3296 3293 Changesets that are ancestors of the current revision, that have
3297 3294 already been grafted, or that are merges will be skipped.
3298 3295
3299 3296 If --log is specified, log messages will have a comment appended
3300 3297 of the form::
3301 3298
3302 3299 (grafted from CHANGESETHASH)
3303 3300
3304 3301 If --force is specified, revisions will be grafted even if they
3305 3302 are already ancestors of or have been grafted to the destination.
3306 3303 This is useful when the revisions have since been backed out.
3307 3304
3308 3305 If a graft merge results in conflicts, the graft process is
3309 3306 interrupted so that the current merge can be manually resolved.
3310 3307 Once all conflicts are addressed, the graft process can be
3311 3308 continued with the -c/--continue option.
3312 3309
3313 3310 .. note::
3314 3311
3315 3312 The -c/--continue option does not reapply earlier options, except
3316 3313 for --force.
3317 3314
3318 3315 .. container:: verbose
3319 3316
3320 3317 Examples:
3321 3318
3322 3319 - copy a single change to the stable branch and edit its description::
3323 3320
3324 3321 hg update stable
3325 3322 hg graft --edit 9393
3326 3323
3327 3324 - graft a range of changesets with one exception, updating dates::
3328 3325
3329 3326 hg graft -D "2085::2093 and not 2091"
3330 3327
3331 3328 - continue a graft after resolving conflicts::
3332 3329
3333 3330 hg graft -c
3334 3331
3335 3332 - show the source of a grafted changeset::
3336 3333
3337 3334 hg log --debug -r .
3338 3335
3339 3336 See :hg:`help revisions` and :hg:`help revsets` for more about
3340 3337 specifying revisions.
3341 3338
3342 3339 Returns 0 on successful completion.
3343 3340 '''
3344 3341
3345 3342 revs = list(revs)
3346 3343 revs.extend(opts['rev'])
3347 3344
3348 3345 if not opts.get('user') and opts.get('currentuser'):
3349 3346 opts['user'] = ui.username()
3350 3347 if not opts.get('date') and opts.get('currentdate'):
3351 3348 opts['date'] = "%d %d" % util.makedate()
3352 3349
3353 3350 editor = cmdutil.getcommiteditor(editform='graft', **opts)
3354 3351
3355 3352 cont = False
3356 3353 if opts['continue']:
3357 3354 cont = True
3358 3355 if revs:
3359 3356 raise util.Abort(_("can't specify --continue and revisions"))
3360 3357 # read in unfinished revisions
3361 3358 try:
3362 3359 nodes = repo.opener.read('graftstate').splitlines()
3363 3360 revs = [repo[node].rev() for node in nodes]
3364 3361 except IOError, inst:
3365 3362 if inst.errno != errno.ENOENT:
3366 3363 raise
3367 3364 raise util.Abort(_("no graft state found, can't continue"))
3368 3365 else:
3369 3366 cmdutil.checkunfinished(repo)
3370 3367 cmdutil.bailifchanged(repo)
3371 3368 if not revs:
3372 3369 raise util.Abort(_('no revisions specified'))
3373 3370 revs = scmutil.revrange(repo, revs)
3374 3371
3375 3372 # check for merges
3376 3373 for rev in repo.revs('%ld and merge()', revs):
3377 3374 ui.warn(_('skipping ungraftable merge revision %s\n') % rev)
3378 3375 revs.remove(rev)
3379 3376 if not revs:
3380 3377 return -1
3381 3378
3382 3379 # Don't check in the --continue case, in effect retaining --force across
3383 3380 # --continues. That's because without --force, any revisions we decided to
3384 3381 # skip would have been filtered out here, so they wouldn't have made their
3385 3382 # way to the graftstate. With --force, any revisions we would have otherwise
3386 3383 # skipped would not have been filtered out, and if they hadn't been applied
3387 3384 # already, they'd have been in the graftstate.
3388 3385 if not (cont or opts.get('force')):
3389 3386 # check for ancestors of dest branch
3390 3387 crev = repo['.'].rev()
3391 3388 ancestors = repo.changelog.ancestors([crev], inclusive=True)
3392 3389 # Cannot use x.remove(y) on smart set, this has to be a list.
3393 3390 # XXX make this lazy in the future
3394 3391 revs = list(revs)
3395 3392 # don't mutate while iterating, create a copy
3396 3393 for rev in list(revs):
3397 3394 if rev in ancestors:
3398 3395 ui.warn(_('skipping ancestor revision %s\n') % rev)
3399 3396 # XXX remove on list is slow
3400 3397 revs.remove(rev)
3401 3398 if not revs:
3402 3399 return -1
3403 3400
3404 3401 # analyze revs for earlier grafts
3405 3402 ids = {}
3406 3403 for ctx in repo.set("%ld", revs):
3407 3404 ids[ctx.hex()] = ctx.rev()
3408 3405 n = ctx.extra().get('source')
3409 3406 if n:
3410 3407 ids[n] = ctx.rev()
3411 3408
3412 3409 # check ancestors for earlier grafts
3413 3410 ui.debug('scanning for duplicate grafts\n')
3414 3411
3415 3412 for rev in repo.changelog.findmissingrevs(revs, [crev]):
3416 3413 ctx = repo[rev]
3417 3414 n = ctx.extra().get('source')
3418 3415 if n in ids:
3419 3416 try:
3420 3417 r = repo[n].rev()
3421 3418 except error.RepoLookupError:
3422 3419 r = None
3423 3420 if r in revs:
3424 3421 ui.warn(_('skipping revision %s (already grafted to %s)\n')
3425 3422 % (r, rev))
3426 3423 revs.remove(r)
3427 3424 elif ids[n] in revs:
3428 3425 if r is None:
3429 3426 ui.warn(_('skipping already grafted revision %s '
3430 3427 '(%s also has unknown origin %s)\n')
3431 3428 % (ids[n], rev, n))
3432 3429 else:
3433 3430 ui.warn(_('skipping already grafted revision %s '
3434 3431 '(%s also has origin %d)\n')
3435 3432 % (ids[n], rev, r))
3436 3433 revs.remove(ids[n])
3437 3434 elif ctx.hex() in ids:
3438 3435 r = ids[ctx.hex()]
3439 3436 ui.warn(_('skipping already grafted revision %s '
3440 3437 '(was grafted from %d)\n') % (r, rev))
3441 3438 revs.remove(r)
3442 3439 if not revs:
3443 3440 return -1
3444 3441
3445 3442 wlock = repo.wlock()
3446 3443 try:
3447 3444 current = repo['.']
3448 3445 for pos, ctx in enumerate(repo.set("%ld", revs)):
3449 3446
3450 3447 ui.status(_('grafting revision %s\n') % ctx.rev())
3451 3448 if opts.get('dry_run'):
3452 3449 continue
3453 3450
3454 3451 source = ctx.extra().get('source')
3455 3452 if not source:
3456 3453 source = ctx.hex()
3457 3454 extra = {'source': source}
3458 3455 user = ctx.user()
3459 3456 if opts.get('user'):
3460 3457 user = opts['user']
3461 3458 date = ctx.date()
3462 3459 if opts.get('date'):
3463 3460 date = opts['date']
3464 3461 message = ctx.description()
3465 3462 if opts.get('log'):
3466 3463 message += '\n(grafted from %s)' % ctx.hex()
3467 3464
3468 3465 # we don't merge the first commit when continuing
3469 3466 if not cont:
3470 3467 # perform the graft merge with p1(rev) as 'ancestor'
3471 3468 try:
3472 3469 # ui.forcemerge is an internal variable, do not document
3473 3470 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
3474 3471 'graft')
3475 3472 stats = mergemod.update(repo, ctx.node(), True, True, False,
3476 3473 ctx.p1().node(),
3477 3474 labels=['local', 'graft'])
3478 3475 finally:
3479 3476 repo.ui.setconfig('ui', 'forcemerge', '', 'graft')
3480 3477 # report any conflicts
3481 3478 if stats and stats[3] > 0:
3482 3479 # write out state for --continue
3483 3480 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
3484 3481 repo.opener.write('graftstate', ''.join(nodelines))
3485 3482 raise util.Abort(
3486 3483 _("unresolved conflicts, can't continue"),
3487 3484 hint=_('use hg resolve and hg graft --continue'))
3488 3485 else:
3489 3486 cont = False
3490 3487
3491 3488 # drop the second merge parent
3492 3489 repo.dirstate.beginparentchange()
3493 3490 repo.setparents(current.node(), nullid)
3494 3491 repo.dirstate.write()
3495 3492 # fix up dirstate for copies and renames
3496 3493 cmdutil.duplicatecopies(repo, ctx.rev(), ctx.p1().rev())
3497 3494 repo.dirstate.endparentchange()
3498 3495
3499 3496 # commit
3500 3497 node = repo.commit(text=message, user=user,
3501 3498 date=date, extra=extra, editor=editor)
3502 3499 if node is None:
3503 3500 ui.status(_('graft for revision %s is empty\n') % ctx.rev())
3504 3501 else:
3505 3502 current = repo[node]
3506 3503 finally:
3507 3504 wlock.release()
3508 3505
3509 3506 # remove state when we complete successfully
3510 3507 if not opts.get('dry_run'):
3511 3508 util.unlinkpath(repo.join('graftstate'), ignoremissing=True)
3512 3509
3513 3510 return 0
3514 3511
3515 3512 @command('grep',
3516 3513 [('0', 'print0', None, _('end fields with NUL')),
3517 3514 ('', 'all', None, _('print all revisions that match')),
3518 3515 ('a', 'text', None, _('treat all files as text')),
3519 3516 ('f', 'follow', None,
3520 3517 _('follow changeset history,'
3521 3518 ' or file history across copies and renames')),
3522 3519 ('i', 'ignore-case', None, _('ignore case when matching')),
3523 3520 ('l', 'files-with-matches', None,
3524 3521 _('print only filenames and revisions that match')),
3525 3522 ('n', 'line-number', None, _('print matching line numbers')),
3526 3523 ('r', 'rev', [],
3527 3524 _('only search files changed within revision range'), _('REV')),
3528 3525 ('u', 'user', None, _('list the author (long with -v)')),
3529 3526 ('d', 'date', None, _('list the date (short with -q)')),
3530 3527 ] + walkopts,
3531 3528 _('[OPTION]... PATTERN [FILE]...'),
3532 3529 inferrepo=True)
3533 3530 def grep(ui, repo, pattern, *pats, **opts):
3534 3531 """search for a pattern in specified files and revisions
3535 3532
3536 3533 Search revisions of files for a regular expression.
3537 3534
3538 3535 This command behaves differently than Unix grep. It only accepts
3539 3536 Python/Perl regexps. It searches repository history, not the
3540 3537 working directory. It always prints the revision number in which a
3541 3538 match appears.
3542 3539
3543 3540 By default, grep only prints output for the first revision of a
3544 3541 file in which it finds a match. To get it to print every revision
3545 3542 that contains a change in match status ("-" for a match that
3546 3543 becomes a non-match, or "+" for a non-match that becomes a match),
3547 3544 use the --all flag.
3548 3545
3549 3546 Returns 0 if a match is found, 1 otherwise.
3550 3547 """
3551 3548 reflags = re.M
3552 3549 if opts.get('ignore_case'):
3553 3550 reflags |= re.I
3554 3551 try:
3555 3552 regexp = util.re.compile(pattern, reflags)
3556 3553 except re.error, inst:
3557 3554 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
3558 3555 return 1
3559 3556 sep, eol = ':', '\n'
3560 3557 if opts.get('print0'):
3561 3558 sep = eol = '\0'
3562 3559
3563 3560 getfile = util.lrucachefunc(repo.file)
3564 3561
3565 3562 def matchlines(body):
3566 3563 begin = 0
3567 3564 linenum = 0
3568 3565 while begin < len(body):
3569 3566 match = regexp.search(body, begin)
3570 3567 if not match:
3571 3568 break
3572 3569 mstart, mend = match.span()
3573 3570 linenum += body.count('\n', begin, mstart) + 1
3574 3571 lstart = body.rfind('\n', begin, mstart) + 1 or begin
3575 3572 begin = body.find('\n', mend) + 1 or len(body) + 1
3576 3573 lend = begin - 1
3577 3574 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
3578 3575
3579 3576 class linestate(object):
3580 3577 def __init__(self, line, linenum, colstart, colend):
3581 3578 self.line = line
3582 3579 self.linenum = linenum
3583 3580 self.colstart = colstart
3584 3581 self.colend = colend
3585 3582
3586 3583 def __hash__(self):
3587 3584 return hash((self.linenum, self.line))
3588 3585
3589 3586 def __eq__(self, other):
3590 3587 return self.line == other.line
3591 3588
3592 3589 def __iter__(self):
3593 3590 yield (self.line[:self.colstart], '')
3594 3591 yield (self.line[self.colstart:self.colend], 'grep.match')
3595 3592 rest = self.line[self.colend:]
3596 3593 while rest != '':
3597 3594 match = regexp.search(rest)
3598 3595 if not match:
3599 3596 yield (rest, '')
3600 3597 break
3601 3598 mstart, mend = match.span()
3602 3599 yield (rest[:mstart], '')
3603 3600 yield (rest[mstart:mend], 'grep.match')
3604 3601 rest = rest[mend:]
3605 3602
3606 3603 matches = {}
3607 3604 copies = {}
3608 3605 def grepbody(fn, rev, body):
3609 3606 matches[rev].setdefault(fn, [])
3610 3607 m = matches[rev][fn]
3611 3608 for lnum, cstart, cend, line in matchlines(body):
3612 3609 s = linestate(line, lnum, cstart, cend)
3613 3610 m.append(s)
3614 3611
3615 3612 def difflinestates(a, b):
3616 3613 sm = difflib.SequenceMatcher(None, a, b)
3617 3614 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
3618 3615 if tag == 'insert':
3619 3616 for i in xrange(blo, bhi):
3620 3617 yield ('+', b[i])
3621 3618 elif tag == 'delete':
3622 3619 for i in xrange(alo, ahi):
3623 3620 yield ('-', a[i])
3624 3621 elif tag == 'replace':
3625 3622 for i in xrange(alo, ahi):
3626 3623 yield ('-', a[i])
3627 3624 for i in xrange(blo, bhi):
3628 3625 yield ('+', b[i])
3629 3626
3630 3627 def display(fn, ctx, pstates, states):
3631 3628 rev = ctx.rev()
3632 3629 datefunc = ui.quiet and util.shortdate or util.datestr
3633 3630 found = False
3634 3631 @util.cachefunc
3635 3632 def binary():
3636 3633 flog = getfile(fn)
3637 3634 return util.binary(flog.read(ctx.filenode(fn)))
3638 3635
3639 3636 if opts.get('all'):
3640 3637 iter = difflinestates(pstates, states)
3641 3638 else:
3642 3639 iter = [('', l) for l in states]
3643 3640 for change, l in iter:
3644 3641 cols = [(fn, 'grep.filename'), (str(rev), 'grep.rev')]
3645 3642
3646 3643 if opts.get('line_number'):
3647 3644 cols.append((str(l.linenum), 'grep.linenumber'))
3648 3645 if opts.get('all'):
3649 3646 cols.append((change, 'grep.change'))
3650 3647 if opts.get('user'):
3651 3648 cols.append((ui.shortuser(ctx.user()), 'grep.user'))
3652 3649 if opts.get('date'):
3653 3650 cols.append((datefunc(ctx.date()), 'grep.date'))
3654 3651 for col, label in cols[:-1]:
3655 3652 ui.write(col, label=label)
3656 3653 ui.write(sep, label='grep.sep')
3657 3654 ui.write(cols[-1][0], label=cols[-1][1])
3658 3655 if not opts.get('files_with_matches'):
3659 3656 ui.write(sep, label='grep.sep')
3660 3657 if not opts.get('text') and binary():
3661 3658 ui.write(" Binary file matches")
3662 3659 else:
3663 3660 for s, label in l:
3664 3661 ui.write(s, label=label)
3665 3662 ui.write(eol)
3666 3663 found = True
3667 3664 if opts.get('files_with_matches'):
3668 3665 break
3669 3666 return found
3670 3667
3671 3668 skip = {}
3672 3669 revfiles = {}
3673 3670 matchfn = scmutil.match(repo[None], pats, opts)
3674 3671 found = False
3675 3672 follow = opts.get('follow')
3676 3673
3677 3674 def prep(ctx, fns):
3678 3675 rev = ctx.rev()
3679 3676 pctx = ctx.p1()
3680 3677 parent = pctx.rev()
3681 3678 matches.setdefault(rev, {})
3682 3679 matches.setdefault(parent, {})
3683 3680 files = revfiles.setdefault(rev, [])
3684 3681 for fn in fns:
3685 3682 flog = getfile(fn)
3686 3683 try:
3687 3684 fnode = ctx.filenode(fn)
3688 3685 except error.LookupError:
3689 3686 continue
3690 3687
3691 3688 copied = flog.renamed(fnode)
3692 3689 copy = follow and copied and copied[0]
3693 3690 if copy:
3694 3691 copies.setdefault(rev, {})[fn] = copy
3695 3692 if fn in skip:
3696 3693 if copy:
3697 3694 skip[copy] = True
3698 3695 continue
3699 3696 files.append(fn)
3700 3697
3701 3698 if fn not in matches[rev]:
3702 3699 grepbody(fn, rev, flog.read(fnode))
3703 3700
3704 3701 pfn = copy or fn
3705 3702 if pfn not in matches[parent]:
3706 3703 try:
3707 3704 fnode = pctx.filenode(pfn)
3708 3705 grepbody(pfn, parent, flog.read(fnode))
3709 3706 except error.LookupError:
3710 3707 pass
3711 3708
3712 3709 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3713 3710 rev = ctx.rev()
3714 3711 parent = ctx.p1().rev()
3715 3712 for fn in sorted(revfiles.get(rev, [])):
3716 3713 states = matches[rev][fn]
3717 3714 copy = copies.get(rev, {}).get(fn)
3718 3715 if fn in skip:
3719 3716 if copy:
3720 3717 skip[copy] = True
3721 3718 continue
3722 3719 pstates = matches.get(parent, {}).get(copy or fn, [])
3723 3720 if pstates or states:
3724 3721 r = display(fn, ctx, pstates, states)
3725 3722 found = found or r
3726 3723 if r and not opts.get('all'):
3727 3724 skip[fn] = True
3728 3725 if copy:
3729 3726 skip[copy] = True
3730 3727 del matches[rev]
3731 3728 del revfiles[rev]
3732 3729
3733 3730 return not found
3734 3731
3735 3732 @command('heads',
3736 3733 [('r', 'rev', '',
3737 3734 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
3738 3735 ('t', 'topo', False, _('show topological heads only')),
3739 3736 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
3740 3737 ('c', 'closed', False, _('show normal and closed branch heads')),
3741 3738 ] + templateopts,
3742 3739 _('[-ct] [-r STARTREV] [REV]...'))
3743 3740 def heads(ui, repo, *branchrevs, **opts):
3744 3741 """show branch heads
3745 3742
3746 3743 With no arguments, show all open branch heads in the repository.
3747 3744 Branch heads are changesets that have no descendants on the
3748 3745 same branch. They are where development generally takes place and
3749 3746 are the usual targets for update and merge operations.
3750 3747
3751 3748 If one or more REVs are given, only open branch heads on the
3752 3749 branches associated with the specified changesets are shown. This
3753 3750 means that you can use :hg:`heads .` to see the heads on the
3754 3751 currently checked-out branch.
3755 3752
3756 3753 If -c/--closed is specified, also show branch heads marked closed
3757 3754 (see :hg:`commit --close-branch`).
3758 3755
3759 3756 If STARTREV is specified, only those heads that are descendants of
3760 3757 STARTREV will be displayed.
3761 3758
3762 3759 If -t/--topo is specified, named branch mechanics will be ignored and only
3763 3760 topological heads (changesets with no children) will be shown.
3764 3761
3765 3762 Returns 0 if matching heads are found, 1 if not.
3766 3763 """
3767 3764
3768 3765 start = None
3769 3766 if 'rev' in opts:
3770 3767 start = scmutil.revsingle(repo, opts['rev'], None).node()
3771 3768
3772 3769 if opts.get('topo'):
3773 3770 heads = [repo[h] for h in repo.heads(start)]
3774 3771 else:
3775 3772 heads = []
3776 3773 for branch in repo.branchmap():
3777 3774 heads += repo.branchheads(branch, start, opts.get('closed'))
3778 3775 heads = [repo[h] for h in heads]
3779 3776
3780 3777 if branchrevs:
3781 3778 branches = set(repo[br].branch() for br in branchrevs)
3782 3779 heads = [h for h in heads if h.branch() in branches]
3783 3780
3784 3781 if opts.get('active') and branchrevs:
3785 3782 dagheads = repo.heads(start)
3786 3783 heads = [h for h in heads if h.node() in dagheads]
3787 3784
3788 3785 if branchrevs:
3789 3786 haveheads = set(h.branch() for h in heads)
3790 3787 if branches - haveheads:
3791 3788 headless = ', '.join(b for b in branches - haveheads)
3792 3789 msg = _('no open branch heads found on branches %s')
3793 3790 if opts.get('rev'):
3794 3791 msg += _(' (started at %s)') % opts['rev']
3795 3792 ui.warn((msg + '\n') % headless)
3796 3793
3797 3794 if not heads:
3798 3795 return 1
3799 3796
3800 3797 heads = sorted(heads, key=lambda x: -x.rev())
3801 3798 displayer = cmdutil.show_changeset(ui, repo, opts)
3802 3799 for ctx in heads:
3803 3800 displayer.show(ctx)
3804 3801 displayer.close()
3805 3802
3806 3803 @command('help',
3807 3804 [('e', 'extension', None, _('show only help for extensions')),
3808 3805 ('c', 'command', None, _('show only help for commands')),
3809 3806 ('k', 'keyword', '', _('show topics matching keyword')),
3810 3807 ],
3811 3808 _('[-ec] [TOPIC]'),
3812 3809 norepo=True)
3813 3810 def help_(ui, name=None, **opts):
3814 3811 """show help for a given topic or a help overview
3815 3812
3816 3813 With no arguments, print a list of commands with short help messages.
3817 3814
3818 3815 Given a topic, extension, or command name, print help for that
3819 3816 topic.
3820 3817
3821 3818 Returns 0 if successful.
3822 3819 """
3823 3820
3824 3821 textwidth = min(ui.termwidth(), 80) - 2
3825 3822
3826 3823 keep = []
3827 3824 if ui.verbose:
3828 3825 keep.append('verbose')
3829 3826 if sys.platform.startswith('win'):
3830 3827 keep.append('windows')
3831 3828 elif sys.platform == 'OpenVMS':
3832 3829 keep.append('vms')
3833 3830 elif sys.platform == 'plan9':
3834 3831 keep.append('plan9')
3835 3832 else:
3836 3833 keep.append('unix')
3837 3834 keep.append(sys.platform.lower())
3838 3835
3839 3836 section = None
3840 3837 if name and '.' in name:
3841 3838 name, section = name.split('.')
3842 3839
3843 3840 text = help.help_(ui, name, **opts)
3844 3841
3845 3842 formatted, pruned = minirst.format(text, textwidth, keep=keep,
3846 3843 section=section)
3847 3844 if section and not formatted:
3848 3845 raise util.Abort(_("help section not found"))
3849 3846
3850 3847 if 'verbose' in pruned:
3851 3848 keep.append('omitted')
3852 3849 else:
3853 3850 keep.append('notomitted')
3854 3851 formatted, pruned = minirst.format(text, textwidth, keep=keep,
3855 3852 section=section)
3856 3853 ui.write(formatted)
3857 3854
3858 3855
3859 3856 @command('identify|id',
3860 3857 [('r', 'rev', '',
3861 3858 _('identify the specified revision'), _('REV')),
3862 3859 ('n', 'num', None, _('show local revision number')),
3863 3860 ('i', 'id', None, _('show global revision id')),
3864 3861 ('b', 'branch', None, _('show branch')),
3865 3862 ('t', 'tags', None, _('show tags')),
3866 3863 ('B', 'bookmarks', None, _('show bookmarks')),
3867 3864 ] + remoteopts,
3868 3865 _('[-nibtB] [-r REV] [SOURCE]'),
3869 3866 optionalrepo=True)
3870 3867 def identify(ui, repo, source=None, rev=None,
3871 3868 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
3872 3869 """identify the working copy or specified revision
3873 3870
3874 3871 Print a summary identifying the repository state at REV using one or
3875 3872 two parent hash identifiers, followed by a "+" if the working
3876 3873 directory has uncommitted changes, the branch name (if not default),
3877 3874 a list of tags, and a list of bookmarks.
3878 3875
3879 3876 When REV is not given, print a summary of the current state of the
3880 3877 repository.
3881 3878
3882 3879 Specifying a path to a repository root or Mercurial bundle will
3883 3880 cause lookup to operate on that repository/bundle.
3884 3881
3885 3882 .. container:: verbose
3886 3883
3887 3884 Examples:
3888 3885
3889 3886 - generate a build identifier for the working directory::
3890 3887
3891 3888 hg id --id > build-id.dat
3892 3889
3893 3890 - find the revision corresponding to a tag::
3894 3891
3895 3892 hg id -n -r 1.3
3896 3893
3897 3894 - check the most recent revision of a remote repository::
3898 3895
3899 3896 hg id -r tip http://selenic.com/hg/
3900 3897
3901 3898 Returns 0 if successful.
3902 3899 """
3903 3900
3904 3901 if not repo and not source:
3905 3902 raise util.Abort(_("there is no Mercurial repository here "
3906 3903 "(.hg not found)"))
3907 3904
3908 3905 hexfunc = ui.debugflag and hex or short
3909 3906 default = not (num or id or branch or tags or bookmarks)
3910 3907 output = []
3911 3908 revs = []
3912 3909
3913 3910 if source:
3914 3911 source, branches = hg.parseurl(ui.expandpath(source))
3915 3912 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
3916 3913 repo = peer.local()
3917 3914 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
3918 3915
3919 3916 if not repo:
3920 3917 if num or branch or tags:
3921 3918 raise util.Abort(
3922 3919 _("can't query remote revision number, branch, or tags"))
3923 3920 if not rev and revs:
3924 3921 rev = revs[0]
3925 3922 if not rev:
3926 3923 rev = "tip"
3927 3924
3928 3925 remoterev = peer.lookup(rev)
3929 3926 if default or id:
3930 3927 output = [hexfunc(remoterev)]
3931 3928
3932 3929 def getbms():
3933 3930 bms = []
3934 3931
3935 3932 if 'bookmarks' in peer.listkeys('namespaces'):
3936 3933 hexremoterev = hex(remoterev)
3937 3934 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
3938 3935 if bmr == hexremoterev]
3939 3936
3940 3937 return sorted(bms)
3941 3938
3942 3939 if bookmarks:
3943 3940 output.extend(getbms())
3944 3941 elif default and not ui.quiet:
3945 3942 # multiple bookmarks for a single parent separated by '/'
3946 3943 bm = '/'.join(getbms())
3947 3944 if bm:
3948 3945 output.append(bm)
3949 3946 else:
3950 3947 if not rev:
3951 3948 ctx = repo[None]
3952 3949 parents = ctx.parents()
3953 3950 changed = ""
3954 3951 if default or id or num:
3955 3952 if (util.any(repo.status())
3956 3953 or util.any(ctx.sub(s).dirty() for s in ctx.substate)):
3957 3954 changed = '+'
3958 3955 if default or id:
3959 3956 output = ["%s%s" %
3960 3957 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
3961 3958 if num:
3962 3959 output.append("%s%s" %
3963 3960 ('+'.join([str(p.rev()) for p in parents]), changed))
3964 3961 else:
3965 3962 ctx = scmutil.revsingle(repo, rev)
3966 3963 if default or id:
3967 3964 output = [hexfunc(ctx.node())]
3968 3965 if num:
3969 3966 output.append(str(ctx.rev()))
3970 3967
3971 3968 if default and not ui.quiet:
3972 3969 b = ctx.branch()
3973 3970 if b != 'default':
3974 3971 output.append("(%s)" % b)
3975 3972
3976 3973 # multiple tags for a single parent separated by '/'
3977 3974 t = '/'.join(ctx.tags())
3978 3975 if t:
3979 3976 output.append(t)
3980 3977
3981 3978 # multiple bookmarks for a single parent separated by '/'
3982 3979 bm = '/'.join(ctx.bookmarks())
3983 3980 if bm:
3984 3981 output.append(bm)
3985 3982 else:
3986 3983 if branch:
3987 3984 output.append(ctx.branch())
3988 3985
3989 3986 if tags:
3990 3987 output.extend(ctx.tags())
3991 3988
3992 3989 if bookmarks:
3993 3990 output.extend(ctx.bookmarks())
3994 3991
3995 3992 ui.write("%s\n" % ' '.join(output))
3996 3993
3997 3994 @command('import|patch',
3998 3995 [('p', 'strip', 1,
3999 3996 _('directory strip option for patch. This has the same '
4000 3997 'meaning as the corresponding patch option'), _('NUM')),
4001 3998 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
4002 3999 ('e', 'edit', False, _('invoke editor on commit messages')),
4003 4000 ('f', 'force', None,
4004 4001 _('skip check for outstanding uncommitted changes (DEPRECATED)')),
4005 4002 ('', 'no-commit', None,
4006 4003 _("don't commit, just update the working directory")),
4007 4004 ('', 'bypass', None,
4008 4005 _("apply patch without touching the working directory")),
4009 4006 ('', 'partial', None,
4010 4007 _('commit even if some hunks fail')),
4011 4008 ('', 'exact', None,
4012 4009 _('apply patch to the nodes from which it was generated')),
4013 4010 ('', 'import-branch', None,
4014 4011 _('use any branch information in patch (implied by --exact)'))] +
4015 4012 commitopts + commitopts2 + similarityopts,
4016 4013 _('[OPTION]... PATCH...'))
4017 4014 def import_(ui, repo, patch1=None, *patches, **opts):
4018 4015 """import an ordered set of patches
4019 4016
4020 4017 Import a list of patches and commit them individually (unless
4021 4018 --no-commit is specified).
4022 4019
4023 4020 Because import first applies changes to the working directory,
4024 4021 import will abort if there are outstanding changes.
4025 4022
4026 4023 You can import a patch straight from a mail message. Even patches
4027 4024 as attachments work (to use the body part, it must have type
4028 4025 text/plain or text/x-patch). From and Subject headers of email
4029 4026 message are used as default committer and commit message. All
4030 4027 text/plain body parts before first diff are added to commit
4031 4028 message.
4032 4029
4033 4030 If the imported patch was generated by :hg:`export`, user and
4034 4031 description from patch override values from message headers and
4035 4032 body. Values given on command line with -m/--message and -u/--user
4036 4033 override these.
4037 4034
4038 4035 If --exact is specified, import will set the working directory to
4039 4036 the parent of each patch before applying it, and will abort if the
4040 4037 resulting changeset has a different ID than the one recorded in
4041 4038 the patch. This may happen due to character set problems or other
4042 4039 deficiencies in the text patch format.
4043 4040
4044 4041 Use --bypass to apply and commit patches directly to the
4045 4042 repository, not touching the working directory. Without --exact,
4046 4043 patches will be applied on top of the working directory parent
4047 4044 revision.
4048 4045
4049 4046 With -s/--similarity, hg will attempt to discover renames and
4050 4047 copies in the patch in the same way as :hg:`addremove`.
4051 4048
4052 4049 Use --partial to ensure a changeset will be created from the patch
4053 4050 even if some hunks fail to apply. Hunks that fail to apply will be
4054 4051 written to a <target-file>.rej file. Conflicts can then be resolved
4055 4052 by hand before :hg:`commit --amend` is run to update the created
4056 4053 changeset. This flag exists to let people import patches that
4057 4054 partially apply without losing the associated metadata (author,
4058 4055 date, description, ...). Note that when none of the hunk applies
4059 4056 cleanly, :hg:`import --partial` will create an empty changeset,
4060 4057 importing only the patch metadata.
4061 4058
4062 4059 To read a patch from standard input, use "-" as the patch name. If
4063 4060 a URL is specified, the patch will be downloaded from it.
4064 4061 See :hg:`help dates` for a list of formats valid for -d/--date.
4065 4062
4066 4063 .. container:: verbose
4067 4064
4068 4065 Examples:
4069 4066
4070 4067 - import a traditional patch from a website and detect renames::
4071 4068
4072 4069 hg import -s 80 http://example.com/bugfix.patch
4073 4070
4074 4071 - import a changeset from an hgweb server::
4075 4072
4076 4073 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
4077 4074
4078 4075 - import all the patches in an Unix-style mbox::
4079 4076
4080 4077 hg import incoming-patches.mbox
4081 4078
4082 4079 - attempt to exactly restore an exported changeset (not always
4083 4080 possible)::
4084 4081
4085 4082 hg import --exact proposed-fix.patch
4086 4083
4087 4084 Returns 0 on success, 1 on partial success (see --partial).
4088 4085 """
4089 4086
4090 4087 if not patch1:
4091 4088 raise util.Abort(_('need at least one patch to import'))
4092 4089
4093 4090 patches = (patch1,) + patches
4094 4091
4095 4092 date = opts.get('date')
4096 4093 if date:
4097 4094 opts['date'] = util.parsedate(date)
4098 4095
4099 4096 update = not opts.get('bypass')
4100 4097 if not update and opts.get('no_commit'):
4101 4098 raise util.Abort(_('cannot use --no-commit with --bypass'))
4102 4099 try:
4103 4100 sim = float(opts.get('similarity') or 0)
4104 4101 except ValueError:
4105 4102 raise util.Abort(_('similarity must be a number'))
4106 4103 if sim < 0 or sim > 100:
4107 4104 raise util.Abort(_('similarity must be between 0 and 100'))
4108 4105 if sim and not update:
4109 4106 raise util.Abort(_('cannot use --similarity with --bypass'))
4110 4107 if opts.get('exact') and opts.get('edit'):
4111 4108 raise util.Abort(_('cannot use --exact with --edit'))
4112 4109
4113 4110 if update:
4114 4111 cmdutil.checkunfinished(repo)
4115 4112 if (opts.get('exact') or not opts.get('force')) and update:
4116 4113 cmdutil.bailifchanged(repo)
4117 4114
4118 4115 base = opts["base"]
4119 4116 wlock = lock = tr = None
4120 4117 msgs = []
4121 4118 ret = 0
4122 4119
4123 4120
4124 4121 try:
4125 4122 try:
4126 4123 wlock = repo.wlock()
4127 4124 repo.dirstate.beginparentchange()
4128 4125 if not opts.get('no_commit'):
4129 4126 lock = repo.lock()
4130 4127 tr = repo.transaction('import')
4131 4128 parents = repo.parents()
4132 4129 for patchurl in patches:
4133 4130 if patchurl == '-':
4134 4131 ui.status(_('applying patch from stdin\n'))
4135 4132 patchfile = ui.fin
4136 4133 patchurl = 'stdin' # for error message
4137 4134 else:
4138 4135 patchurl = os.path.join(base, patchurl)
4139 4136 ui.status(_('applying %s\n') % patchurl)
4140 4137 patchfile = hg.openpath(ui, patchurl)
4141 4138
4142 4139 haspatch = False
4143 4140 for hunk in patch.split(patchfile):
4144 4141 (msg, node, rej) = cmdutil.tryimportone(ui, repo, hunk,
4145 4142 parents, opts,
4146 4143 msgs, hg.clean)
4147 4144 if msg:
4148 4145 haspatch = True
4149 4146 ui.note(msg + '\n')
4150 4147 if update or opts.get('exact'):
4151 4148 parents = repo.parents()
4152 4149 else:
4153 4150 parents = [repo[node]]
4154 4151 if rej:
4155 4152 ui.write_err(_("patch applied partially\n"))
4156 4153 ui.write_err(_("(fix the .rej files and run "
4157 4154 "`hg commit --amend`)\n"))
4158 4155 ret = 1
4159 4156 break
4160 4157
4161 4158 if not haspatch:
4162 4159 raise util.Abort(_('%s: no diffs found') % patchurl)
4163 4160
4164 4161 if tr:
4165 4162 tr.close()
4166 4163 if msgs:
4167 4164 repo.savecommitmessage('\n* * *\n'.join(msgs))
4168 4165 repo.dirstate.endparentchange()
4169 4166 return ret
4170 4167 except: # re-raises
4171 4168 # wlock.release() indirectly calls dirstate.write(): since
4172 4169 # we're crashing, we do not want to change the working dir
4173 4170 # parent after all, so make sure it writes nothing
4174 4171 repo.dirstate.invalidate()
4175 4172 raise
4176 4173 finally:
4177 4174 if tr:
4178 4175 tr.release()
4179 4176 release(lock, wlock)
4180 4177
4181 4178 @command('incoming|in',
4182 4179 [('f', 'force', None,
4183 4180 _('run even if remote repository is unrelated')),
4184 4181 ('n', 'newest-first', None, _('show newest record first')),
4185 4182 ('', 'bundle', '',
4186 4183 _('file to store the bundles into'), _('FILE')),
4187 4184 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4188 4185 ('B', 'bookmarks', False, _("compare bookmarks")),
4189 4186 ('b', 'branch', [],
4190 4187 _('a specific branch you would like to pull'), _('BRANCH')),
4191 4188 ] + logopts + remoteopts + subrepoopts,
4192 4189 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
4193 4190 def incoming(ui, repo, source="default", **opts):
4194 4191 """show new changesets found in source
4195 4192
4196 4193 Show new changesets found in the specified path/URL or the default
4197 4194 pull location. These are the changesets that would have been pulled
4198 4195 if a pull at the time you issued this command.
4199 4196
4200 4197 For remote repository, using --bundle avoids downloading the
4201 4198 changesets twice if the incoming is followed by a pull.
4202 4199
4203 4200 See pull for valid source format details.
4204 4201
4205 4202 .. container:: verbose
4206 4203
4207 4204 Examples:
4208 4205
4209 4206 - show incoming changes with patches and full description::
4210 4207
4211 4208 hg incoming -vp
4212 4209
4213 4210 - show incoming changes excluding merges, store a bundle::
4214 4211
4215 4212 hg in -vpM --bundle incoming.hg
4216 4213 hg pull incoming.hg
4217 4214
4218 4215 - briefly list changes inside a bundle::
4219 4216
4220 4217 hg in changes.hg -T "{desc|firstline}\\n"
4221 4218
4222 4219 Returns 0 if there are incoming changes, 1 otherwise.
4223 4220 """
4224 4221 if opts.get('graph'):
4225 4222 cmdutil.checkunsupportedgraphflags([], opts)
4226 4223 def display(other, chlist, displayer):
4227 4224 revdag = cmdutil.graphrevs(other, chlist, opts)
4228 4225 showparents = [ctx.node() for ctx in repo[None].parents()]
4229 4226 cmdutil.displaygraph(ui, revdag, displayer, showparents,
4230 4227 graphmod.asciiedges)
4231 4228
4232 4229 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
4233 4230 return 0
4234 4231
4235 4232 if opts.get('bundle') and opts.get('subrepos'):
4236 4233 raise util.Abort(_('cannot combine --bundle and --subrepos'))
4237 4234
4238 4235 if opts.get('bookmarks'):
4239 4236 source, branches = hg.parseurl(ui.expandpath(source),
4240 4237 opts.get('branch'))
4241 4238 other = hg.peer(repo, opts, source)
4242 4239 if 'bookmarks' not in other.listkeys('namespaces'):
4243 4240 ui.warn(_("remote doesn't support bookmarks\n"))
4244 4241 return 0
4245 4242 ui.status(_('comparing with %s\n') % util.hidepassword(source))
4246 4243 return bookmarks.diff(ui, repo, other)
4247 4244
4248 4245 repo._subtoppath = ui.expandpath(source)
4249 4246 try:
4250 4247 return hg.incoming(ui, repo, source, opts)
4251 4248 finally:
4252 4249 del repo._subtoppath
4253 4250
4254 4251
4255 4252 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'),
4256 4253 norepo=True)
4257 4254 def init(ui, dest=".", **opts):
4258 4255 """create a new repository in the given directory
4259 4256
4260 4257 Initialize a new repository in the given directory. If the given
4261 4258 directory does not exist, it will be created.
4262 4259
4263 4260 If no directory is given, the current directory is used.
4264 4261
4265 4262 It is possible to specify an ``ssh://`` URL as the destination.
4266 4263 See :hg:`help urls` for more information.
4267 4264
4268 4265 Returns 0 on success.
4269 4266 """
4270 4267 hg.peer(ui, opts, ui.expandpath(dest), create=True)
4271 4268
4272 4269 @command('locate',
4273 4270 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
4274 4271 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4275 4272 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
4276 4273 ] + walkopts,
4277 4274 _('[OPTION]... [PATTERN]...'))
4278 4275 def locate(ui, repo, *pats, **opts):
4279 4276 """locate files matching specific patterns (DEPRECATED)
4280 4277
4281 4278 Print files under Mercurial control in the working directory whose
4282 4279 names match the given patterns.
4283 4280
4284 4281 By default, this command searches all directories in the working
4285 4282 directory. To search just the current directory and its
4286 4283 subdirectories, use "--include .".
4287 4284
4288 4285 If no patterns are given to match, this command prints the names
4289 4286 of all files under Mercurial control in the working directory.
4290 4287
4291 4288 If you want to feed the output of this command into the "xargs"
4292 4289 command, use the -0 option to both this command and "xargs". This
4293 4290 will avoid the problem of "xargs" treating single filenames that
4294 4291 contain whitespace as multiple filenames.
4295 4292
4296 4293 See :hg:`help files` for a more versatile command.
4297 4294
4298 4295 Returns 0 if a match is found, 1 otherwise.
4299 4296 """
4300 4297 end = opts.get('print0') and '\0' or '\n'
4301 4298 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
4302 4299
4303 4300 ret = 1
4304 4301 ctx = repo[rev]
4305 4302 m = scmutil.match(ctx, pats, opts, default='relglob')
4306 4303 m.bad = lambda x, y: False
4307 4304
4308 4305 for abs in ctx.matches(m):
4309 4306 if opts.get('fullpath'):
4310 4307 ui.write(repo.wjoin(abs), end)
4311 4308 else:
4312 4309 ui.write(((pats and m.rel(abs)) or abs), end)
4313 4310 ret = 0
4314 4311
4315 4312 return ret
4316 4313
4317 4314 @command('^log|history',
4318 4315 [('f', 'follow', None,
4319 4316 _('follow changeset history, or file history across copies and renames')),
4320 4317 ('', 'follow-first', None,
4321 4318 _('only follow the first parent of merge changesets (DEPRECATED)')),
4322 4319 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
4323 4320 ('C', 'copies', None, _('show copied files')),
4324 4321 ('k', 'keyword', [],
4325 4322 _('do case-insensitive search for a given text'), _('TEXT')),
4326 4323 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
4327 4324 ('', 'removed', None, _('include revisions where files were removed')),
4328 4325 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
4329 4326 ('u', 'user', [], _('revisions committed by user'), _('USER')),
4330 4327 ('', 'only-branch', [],
4331 4328 _('show only changesets within the given named branch (DEPRECATED)'),
4332 4329 _('BRANCH')),
4333 4330 ('b', 'branch', [],
4334 4331 _('show changesets within the given named branch'), _('BRANCH')),
4335 4332 ('P', 'prune', [],
4336 4333 _('do not display revision or any of its ancestors'), _('REV')),
4337 4334 ] + logopts + walkopts,
4338 4335 _('[OPTION]... [FILE]'),
4339 4336 inferrepo=True)
4340 4337 def log(ui, repo, *pats, **opts):
4341 4338 """show revision history of entire repository or files
4342 4339
4343 4340 Print the revision history of the specified files or the entire
4344 4341 project.
4345 4342
4346 4343 If no revision range is specified, the default is ``tip:0`` unless
4347 4344 --follow is set, in which case the working directory parent is
4348 4345 used as the starting revision.
4349 4346
4350 4347 File history is shown without following rename or copy history of
4351 4348 files. Use -f/--follow with a filename to follow history across
4352 4349 renames and copies. --follow without a filename will only show
4353 4350 ancestors or descendants of the starting revision.
4354 4351
4355 4352 By default this command prints revision number and changeset id,
4356 4353 tags, non-trivial parents, user, date and time, and a summary for
4357 4354 each commit. When the -v/--verbose switch is used, the list of
4358 4355 changed files and full commit message are shown.
4359 4356
4360 4357 With --graph the revisions are shown as an ASCII art DAG with the most
4361 4358 recent changeset at the top.
4362 4359 'o' is a changeset, '@' is a working directory parent, 'x' is obsolete,
4363 4360 and '+' represents a fork where the changeset from the lines below is a
4364 4361 parent of the 'o' merge on the same line.
4365 4362
4366 4363 .. note::
4367 4364
4368 4365 log -p/--patch may generate unexpected diff output for merge
4369 4366 changesets, as it will only compare the merge changeset against
4370 4367 its first parent. Also, only files different from BOTH parents
4371 4368 will appear in files:.
4372 4369
4373 4370 .. note::
4374 4371
4375 4372 for performance reasons, log FILE may omit duplicate changes
4376 4373 made on branches and will not show removals or mode changes. To
4377 4374 see all such changes, use the --removed switch.
4378 4375
4379 4376 .. container:: verbose
4380 4377
4381 4378 Some examples:
4382 4379
4383 4380 - changesets with full descriptions and file lists::
4384 4381
4385 4382 hg log -v
4386 4383
4387 4384 - changesets ancestral to the working directory::
4388 4385
4389 4386 hg log -f
4390 4387
4391 4388 - last 10 commits on the current branch::
4392 4389
4393 4390 hg log -l 10 -b .
4394 4391
4395 4392 - changesets showing all modifications of a file, including removals::
4396 4393
4397 4394 hg log --removed file.c
4398 4395
4399 4396 - all changesets that touch a directory, with diffs, excluding merges::
4400 4397
4401 4398 hg log -Mp lib/
4402 4399
4403 4400 - all revision numbers that match a keyword::
4404 4401
4405 4402 hg log -k bug --template "{rev}\\n"
4406 4403
4407 4404 - list available log templates::
4408 4405
4409 4406 hg log -T list
4410 4407
4411 4408 - check if a given changeset is included in a tagged release::
4412 4409
4413 4410 hg log -r "a21ccf and ancestor(1.9)"
4414 4411
4415 4412 - find all changesets by some user in a date range::
4416 4413
4417 4414 hg log -k alice -d "may 2008 to jul 2008"
4418 4415
4419 4416 - summary of all changesets after the last tag::
4420 4417
4421 4418 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
4422 4419
4423 4420 See :hg:`help dates` for a list of formats valid for -d/--date.
4424 4421
4425 4422 See :hg:`help revisions` and :hg:`help revsets` for more about
4426 4423 specifying revisions.
4427 4424
4428 4425 See :hg:`help templates` for more about pre-packaged styles and
4429 4426 specifying custom templates.
4430 4427
4431 4428 Returns 0 on success.
4432 4429
4433 4430 """
4434 4431 if opts.get('graph'):
4435 4432 return cmdutil.graphlog(ui, repo, *pats, **opts)
4436 4433
4437 4434 revs, expr, filematcher = cmdutil.getlogrevs(repo, pats, opts)
4438 4435 limit = cmdutil.loglimit(opts)
4439 4436 count = 0
4440 4437
4441 4438 getrenamed = None
4442 4439 if opts.get('copies'):
4443 4440 endrev = None
4444 4441 if opts.get('rev'):
4445 4442 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
4446 4443 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
4447 4444
4448 4445 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
4449 4446 for rev in revs:
4450 4447 if count == limit:
4451 4448 break
4452 4449 ctx = repo[rev]
4453 4450 copies = None
4454 4451 if getrenamed is not None and rev:
4455 4452 copies = []
4456 4453 for fn in ctx.files():
4457 4454 rename = getrenamed(fn, rev)
4458 4455 if rename:
4459 4456 copies.append((fn, rename[0]))
4460 4457 revmatchfn = filematcher and filematcher(ctx.rev()) or None
4461 4458 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
4462 4459 if displayer.flush(rev):
4463 4460 count += 1
4464 4461
4465 4462 displayer.close()
4466 4463
4467 4464 @command('manifest',
4468 4465 [('r', 'rev', '', _('revision to display'), _('REV')),
4469 4466 ('', 'all', False, _("list files from all revisions"))]
4470 4467 + formatteropts,
4471 4468 _('[-r REV]'))
4472 4469 def manifest(ui, repo, node=None, rev=None, **opts):
4473 4470 """output the current or given revision of the project manifest
4474 4471
4475 4472 Print a list of version controlled files for the given revision.
4476 4473 If no revision is given, the first parent of the working directory
4477 4474 is used, or the null revision if no revision is checked out.
4478 4475
4479 4476 With -v, print file permissions, symlink and executable bits.
4480 4477 With --debug, print file revision hashes.
4481 4478
4482 4479 If option --all is specified, the list of all files from all revisions
4483 4480 is printed. This includes deleted and renamed files.
4484 4481
4485 4482 Returns 0 on success.
4486 4483 """
4487 4484
4488 4485 fm = ui.formatter('manifest', opts)
4489 4486
4490 4487 if opts.get('all'):
4491 4488 if rev or node:
4492 4489 raise util.Abort(_("can't specify a revision with --all"))
4493 4490
4494 4491 res = []
4495 4492 prefix = "data/"
4496 4493 suffix = ".i"
4497 4494 plen = len(prefix)
4498 4495 slen = len(suffix)
4499 4496 lock = repo.lock()
4500 4497 try:
4501 4498 for fn, b, size in repo.store.datafiles():
4502 4499 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
4503 4500 res.append(fn[plen:-slen])
4504 4501 finally:
4505 4502 lock.release()
4506 4503 for f in res:
4507 4504 fm.startitem()
4508 4505 fm.write("path", '%s\n', f)
4509 4506 fm.end()
4510 4507 return
4511 4508
4512 4509 if rev and node:
4513 4510 raise util.Abort(_("please specify just one revision"))
4514 4511
4515 4512 if not node:
4516 4513 node = rev
4517 4514
4518 4515 char = {'l': '@', 'x': '*', '': ''}
4519 4516 mode = {'l': '644', 'x': '755', '': '644'}
4520 4517 ctx = scmutil.revsingle(repo, node)
4521 4518 mf = ctx.manifest()
4522 4519 for f in ctx:
4523 4520 fm.startitem()
4524 4521 fl = ctx[f].flags()
4525 4522 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
4526 4523 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
4527 4524 fm.write('path', '%s\n', f)
4528 4525 fm.end()
4529 4526
4530 4527 @command('^merge',
4531 4528 [('f', 'force', None,
4532 4529 _('force a merge including outstanding changes (DEPRECATED)')),
4533 4530 ('r', 'rev', '', _('revision to merge'), _('REV')),
4534 4531 ('P', 'preview', None,
4535 4532 _('review revisions to merge (no merge is performed)'))
4536 4533 ] + mergetoolopts,
4537 4534 _('[-P] [-f] [[-r] REV]'))
4538 4535 def merge(ui, repo, node=None, **opts):
4539 4536 """merge working directory with another revision
4540 4537
4541 4538 The current working directory is updated with all changes made in
4542 4539 the requested revision since the last common predecessor revision.
4543 4540
4544 4541 Files that changed between either parent are marked as changed for
4545 4542 the next commit and a commit must be performed before any further
4546 4543 updates to the repository are allowed. The next commit will have
4547 4544 two parents.
4548 4545
4549 4546 ``--tool`` can be used to specify the merge tool used for file
4550 4547 merges. It overrides the HGMERGE environment variable and your
4551 4548 configuration files. See :hg:`help merge-tools` for options.
4552 4549
4553 4550 If no revision is specified, the working directory's parent is a
4554 4551 head revision, and the current branch contains exactly one other
4555 4552 head, the other head is merged with by default. Otherwise, an
4556 4553 explicit revision with which to merge with must be provided.
4557 4554
4558 4555 :hg:`resolve` must be used to resolve unresolved files.
4559 4556
4560 4557 To undo an uncommitted merge, use :hg:`update --clean .` which
4561 4558 will check out a clean copy of the original merge parent, losing
4562 4559 all changes.
4563 4560
4564 4561 Returns 0 on success, 1 if there are unresolved files.
4565 4562 """
4566 4563
4567 4564 if opts.get('rev') and node:
4568 4565 raise util.Abort(_("please specify just one revision"))
4569 4566 if not node:
4570 4567 node = opts.get('rev')
4571 4568
4572 4569 if node:
4573 4570 node = scmutil.revsingle(repo, node).node()
4574 4571
4575 4572 if not node and repo._bookmarkcurrent:
4576 4573 bmheads = repo.bookmarkheads(repo._bookmarkcurrent)
4577 4574 curhead = repo[repo._bookmarkcurrent].node()
4578 4575 if len(bmheads) == 2:
4579 4576 if curhead == bmheads[0]:
4580 4577 node = bmheads[1]
4581 4578 else:
4582 4579 node = bmheads[0]
4583 4580 elif len(bmheads) > 2:
4584 4581 raise util.Abort(_("multiple matching bookmarks to merge - "
4585 4582 "please merge with an explicit rev or bookmark"),
4586 4583 hint=_("run 'hg heads' to see all heads"))
4587 4584 elif len(bmheads) <= 1:
4588 4585 raise util.Abort(_("no matching bookmark to merge - "
4589 4586 "please merge with an explicit rev or bookmark"),
4590 4587 hint=_("run 'hg heads' to see all heads"))
4591 4588
4592 4589 if not node and not repo._bookmarkcurrent:
4593 4590 branch = repo[None].branch()
4594 4591 bheads = repo.branchheads(branch)
4595 4592 nbhs = [bh for bh in bheads if not repo[bh].bookmarks()]
4596 4593
4597 4594 if len(nbhs) > 2:
4598 4595 raise util.Abort(_("branch '%s' has %d heads - "
4599 4596 "please merge with an explicit rev")
4600 4597 % (branch, len(bheads)),
4601 4598 hint=_("run 'hg heads .' to see heads"))
4602 4599
4603 4600 parent = repo.dirstate.p1()
4604 4601 if len(nbhs) <= 1:
4605 4602 if len(bheads) > 1:
4606 4603 raise util.Abort(_("heads are bookmarked - "
4607 4604 "please merge with an explicit rev"),
4608 4605 hint=_("run 'hg heads' to see all heads"))
4609 4606 if len(repo.heads()) > 1:
4610 4607 raise util.Abort(_("branch '%s' has one head - "
4611 4608 "please merge with an explicit rev")
4612 4609 % branch,
4613 4610 hint=_("run 'hg heads' to see all heads"))
4614 4611 msg, hint = _('nothing to merge'), None
4615 4612 if parent != repo.lookup(branch):
4616 4613 hint = _("use 'hg update' instead")
4617 4614 raise util.Abort(msg, hint=hint)
4618 4615
4619 4616 if parent not in bheads:
4620 4617 raise util.Abort(_('working directory not at a head revision'),
4621 4618 hint=_("use 'hg update' or merge with an "
4622 4619 "explicit revision"))
4623 4620 if parent == nbhs[0]:
4624 4621 node = nbhs[-1]
4625 4622 else:
4626 4623 node = nbhs[0]
4627 4624
4628 4625 if opts.get('preview'):
4629 4626 # find nodes that are ancestors of p2 but not of p1
4630 4627 p1 = repo.lookup('.')
4631 4628 p2 = repo.lookup(node)
4632 4629 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4633 4630
4634 4631 displayer = cmdutil.show_changeset(ui, repo, opts)
4635 4632 for node in nodes:
4636 4633 displayer.show(repo[node])
4637 4634 displayer.close()
4638 4635 return 0
4639 4636
4640 4637 try:
4641 4638 # ui.forcemerge is an internal variable, do not document
4642 4639 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''), 'merge')
4643 4640 return hg.merge(repo, node, force=opts.get('force'))
4644 4641 finally:
4645 4642 ui.setconfig('ui', 'forcemerge', '', 'merge')
4646 4643
4647 4644 @command('outgoing|out',
4648 4645 [('f', 'force', None, _('run even when the destination is unrelated')),
4649 4646 ('r', 'rev', [],
4650 4647 _('a changeset intended to be included in the destination'), _('REV')),
4651 4648 ('n', 'newest-first', None, _('show newest record first')),
4652 4649 ('B', 'bookmarks', False, _('compare bookmarks')),
4653 4650 ('b', 'branch', [], _('a specific branch you would like to push'),
4654 4651 _('BRANCH')),
4655 4652 ] + logopts + remoteopts + subrepoopts,
4656 4653 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
4657 4654 def outgoing(ui, repo, dest=None, **opts):
4658 4655 """show changesets not found in the destination
4659 4656
4660 4657 Show changesets not found in the specified destination repository
4661 4658 or the default push location. These are the changesets that would
4662 4659 be pushed if a push was requested.
4663 4660
4664 4661 See pull for details of valid destination formats.
4665 4662
4666 4663 Returns 0 if there are outgoing changes, 1 otherwise.
4667 4664 """
4668 4665 if opts.get('graph'):
4669 4666 cmdutil.checkunsupportedgraphflags([], opts)
4670 4667 o, other = hg._outgoing(ui, repo, dest, opts)
4671 4668 if not o:
4672 4669 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4673 4670 return
4674 4671
4675 4672 revdag = cmdutil.graphrevs(repo, o, opts)
4676 4673 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
4677 4674 showparents = [ctx.node() for ctx in repo[None].parents()]
4678 4675 cmdutil.displaygraph(ui, revdag, displayer, showparents,
4679 4676 graphmod.asciiedges)
4680 4677 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4681 4678 return 0
4682 4679
4683 4680 if opts.get('bookmarks'):
4684 4681 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4685 4682 dest, branches = hg.parseurl(dest, opts.get('branch'))
4686 4683 other = hg.peer(repo, opts, dest)
4687 4684 if 'bookmarks' not in other.listkeys('namespaces'):
4688 4685 ui.warn(_("remote doesn't support bookmarks\n"))
4689 4686 return 0
4690 4687 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
4691 4688 return bookmarks.diff(ui, other, repo)
4692 4689
4693 4690 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
4694 4691 try:
4695 4692 return hg.outgoing(ui, repo, dest, opts)
4696 4693 finally:
4697 4694 del repo._subtoppath
4698 4695
4699 4696 @command('parents',
4700 4697 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
4701 4698 ] + templateopts,
4702 4699 _('[-r REV] [FILE]'),
4703 4700 inferrepo=True)
4704 4701 def parents(ui, repo, file_=None, **opts):
4705 4702 """show the parents of the working directory or revision (DEPRECATED)
4706 4703
4707 4704 Print the working directory's parent revisions. If a revision is
4708 4705 given via -r/--rev, the parent of that revision will be printed.
4709 4706 If a file argument is given, the revision in which the file was
4710 4707 last changed (before the working directory revision or the
4711 4708 argument to --rev if given) is printed.
4712 4709
4713 4710 See :hg:`summary` and :hg:`help revsets` for related information.
4714 4711
4715 4712 Returns 0 on success.
4716 4713 """
4717 4714
4718 4715 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
4719 4716
4720 4717 if file_:
4721 4718 m = scmutil.match(ctx, (file_,), opts)
4722 4719 if m.anypats() or len(m.files()) != 1:
4723 4720 raise util.Abort(_('can only specify an explicit filename'))
4724 4721 file_ = m.files()[0]
4725 4722 filenodes = []
4726 4723 for cp in ctx.parents():
4727 4724 if not cp:
4728 4725 continue
4729 4726 try:
4730 4727 filenodes.append(cp.filenode(file_))
4731 4728 except error.LookupError:
4732 4729 pass
4733 4730 if not filenodes:
4734 4731 raise util.Abort(_("'%s' not found in manifest!") % file_)
4735 4732 p = []
4736 4733 for fn in filenodes:
4737 4734 fctx = repo.filectx(file_, fileid=fn)
4738 4735 p.append(fctx.node())
4739 4736 else:
4740 4737 p = [cp.node() for cp in ctx.parents()]
4741 4738
4742 4739 displayer = cmdutil.show_changeset(ui, repo, opts)
4743 4740 for n in p:
4744 4741 if n != nullid:
4745 4742 displayer.show(repo[n])
4746 4743 displayer.close()
4747 4744
4748 4745 @command('paths', [], _('[NAME]'), optionalrepo=True)
4749 4746 def paths(ui, repo, search=None):
4750 4747 """show aliases for remote repositories
4751 4748
4752 4749 Show definition of symbolic path name NAME. If no name is given,
4753 4750 show definition of all available names.
4754 4751
4755 4752 Option -q/--quiet suppresses all output when searching for NAME
4756 4753 and shows only the path names when listing all definitions.
4757 4754
4758 4755 Path names are defined in the [paths] section of your
4759 4756 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
4760 4757 repository, ``.hg/hgrc`` is used, too.
4761 4758
4762 4759 The path names ``default`` and ``default-push`` have a special
4763 4760 meaning. When performing a push or pull operation, they are used
4764 4761 as fallbacks if no location is specified on the command-line.
4765 4762 When ``default-push`` is set, it will be used for push and
4766 4763 ``default`` will be used for pull; otherwise ``default`` is used
4767 4764 as the fallback for both. When cloning a repository, the clone
4768 4765 source is written as ``default`` in ``.hg/hgrc``. Note that
4769 4766 ``default`` and ``default-push`` apply to all inbound (e.g.
4770 4767 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
4771 4768 :hg:`bundle`) operations.
4772 4769
4773 4770 See :hg:`help urls` for more information.
4774 4771
4775 4772 Returns 0 on success.
4776 4773 """
4777 4774 if search:
4778 4775 for name, path in ui.configitems("paths"):
4779 4776 if name == search:
4780 4777 ui.status("%s\n" % util.hidepassword(path))
4781 4778 return
4782 4779 if not ui.quiet:
4783 4780 ui.warn(_("not found!\n"))
4784 4781 return 1
4785 4782 else:
4786 4783 for name, path in ui.configitems("paths"):
4787 4784 if ui.quiet:
4788 4785 ui.write("%s\n" % name)
4789 4786 else:
4790 4787 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
4791 4788
4792 4789 @command('phase',
4793 4790 [('p', 'public', False, _('set changeset phase to public')),
4794 4791 ('d', 'draft', False, _('set changeset phase to draft')),
4795 4792 ('s', 'secret', False, _('set changeset phase to secret')),
4796 4793 ('f', 'force', False, _('allow to move boundary backward')),
4797 4794 ('r', 'rev', [], _('target revision'), _('REV')),
4798 4795 ],
4799 4796 _('[-p|-d|-s] [-f] [-r] REV...'))
4800 4797 def phase(ui, repo, *revs, **opts):
4801 4798 """set or show the current phase name
4802 4799
4803 4800 With no argument, show the phase name of specified revisions.
4804 4801
4805 4802 With one of -p/--public, -d/--draft or -s/--secret, change the
4806 4803 phase value of the specified revisions.
4807 4804
4808 4805 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
4809 4806 lower phase to an higher phase. Phases are ordered as follows::
4810 4807
4811 4808 public < draft < secret
4812 4809
4813 4810 Returns 0 on success, 1 if no phases were changed or some could not
4814 4811 be changed.
4815 4812 """
4816 4813 # search for a unique phase argument
4817 4814 targetphase = None
4818 4815 for idx, name in enumerate(phases.phasenames):
4819 4816 if opts[name]:
4820 4817 if targetphase is not None:
4821 4818 raise util.Abort(_('only one phase can be specified'))
4822 4819 targetphase = idx
4823 4820
4824 4821 # look for specified revision
4825 4822 revs = list(revs)
4826 4823 revs.extend(opts['rev'])
4827 4824 if not revs:
4828 4825 raise util.Abort(_('no revisions specified'))
4829 4826
4830 4827 revs = scmutil.revrange(repo, revs)
4831 4828
4832 4829 lock = None
4833 4830 ret = 0
4834 4831 if targetphase is None:
4835 4832 # display
4836 4833 for r in revs:
4837 4834 ctx = repo[r]
4838 4835 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
4839 4836 else:
4840 4837 tr = None
4841 4838 lock = repo.lock()
4842 4839 try:
4843 4840 tr = repo.transaction("phase")
4844 4841 # set phase
4845 4842 if not revs:
4846 4843 raise util.Abort(_('empty revision set'))
4847 4844 nodes = [repo[r].node() for r in revs]
4848 4845 olddata = repo._phasecache.getphaserevs(repo)[:]
4849 4846 phases.advanceboundary(repo, tr, targetphase, nodes)
4850 4847 if opts['force']:
4851 4848 phases.retractboundary(repo, tr, targetphase, nodes)
4852 4849 tr.close()
4853 4850 finally:
4854 4851 if tr is not None:
4855 4852 tr.release()
4856 4853 lock.release()
4857 4854 # moving revision from public to draft may hide them
4858 4855 # We have to check result on an unfiltered repository
4859 4856 unfi = repo.unfiltered()
4860 4857 newdata = repo._phasecache.getphaserevs(unfi)
4861 4858 changes = sum(o != newdata[i] for i, o in enumerate(olddata))
4862 4859 cl = unfi.changelog
4863 4860 rejected = [n for n in nodes
4864 4861 if newdata[cl.rev(n)] < targetphase]
4865 4862 if rejected:
4866 4863 ui.warn(_('cannot move %i changesets to a higher '
4867 4864 'phase, use --force\n') % len(rejected))
4868 4865 ret = 1
4869 4866 if changes:
4870 4867 msg = _('phase changed for %i changesets\n') % changes
4871 4868 if ret:
4872 4869 ui.status(msg)
4873 4870 else:
4874 4871 ui.note(msg)
4875 4872 else:
4876 4873 ui.warn(_('no phases changed\n'))
4877 4874 ret = 1
4878 4875 return ret
4879 4876
4880 4877 def postincoming(ui, repo, modheads, optupdate, checkout):
4881 4878 if modheads == 0:
4882 4879 return
4883 4880 if optupdate:
4884 4881 checkout, movemarkfrom = bookmarks.calculateupdate(ui, repo, checkout)
4885 4882 try:
4886 4883 ret = hg.update(repo, checkout)
4887 4884 except util.Abort, inst:
4888 4885 ui.warn(_("not updating: %s\n") % str(inst))
4889 4886 if inst.hint:
4890 4887 ui.warn(_("(%s)\n") % inst.hint)
4891 4888 return 0
4892 4889 if not ret and not checkout:
4893 4890 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
4894 4891 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
4895 4892 return ret
4896 4893 if modheads > 1:
4897 4894 currentbranchheads = len(repo.branchheads())
4898 4895 if currentbranchheads == modheads:
4899 4896 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
4900 4897 elif currentbranchheads > 1:
4901 4898 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
4902 4899 "merge)\n"))
4903 4900 else:
4904 4901 ui.status(_("(run 'hg heads' to see heads)\n"))
4905 4902 else:
4906 4903 ui.status(_("(run 'hg update' to get a working copy)\n"))
4907 4904
4908 4905 @command('^pull',
4909 4906 [('u', 'update', None,
4910 4907 _('update to new branch head if changesets were pulled')),
4911 4908 ('f', 'force', None, _('run even when remote repository is unrelated')),
4912 4909 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4913 4910 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
4914 4911 ('b', 'branch', [], _('a specific branch you would like to pull'),
4915 4912 _('BRANCH')),
4916 4913 ] + remoteopts,
4917 4914 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
4918 4915 def pull(ui, repo, source="default", **opts):
4919 4916 """pull changes from the specified source
4920 4917
4921 4918 Pull changes from a remote repository to a local one.
4922 4919
4923 4920 This finds all changes from the repository at the specified path
4924 4921 or URL and adds them to a local repository (the current one unless
4925 4922 -R is specified). By default, this does not update the copy of the
4926 4923 project in the working directory.
4927 4924
4928 4925 Use :hg:`incoming` if you want to see what would have been added
4929 4926 by a pull at the time you issued this command. If you then decide
4930 4927 to add those changes to the repository, you should use :hg:`pull
4931 4928 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4932 4929
4933 4930 If SOURCE is omitted, the 'default' path will be used.
4934 4931 See :hg:`help urls` for more information.
4935 4932
4936 4933 Returns 0 on success, 1 if an update had unresolved files.
4937 4934 """
4938 4935 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4939 4936 other = hg.peer(repo, opts, source)
4940 4937 try:
4941 4938 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4942 4939 revs, checkout = hg.addbranchrevs(repo, other, branches,
4943 4940 opts.get('rev'))
4944 4941
4945 4942 remotebookmarks = other.listkeys('bookmarks')
4946 4943
4947 4944 if opts.get('bookmark'):
4948 4945 if not revs:
4949 4946 revs = []
4950 4947 for b in opts['bookmark']:
4951 4948 if b not in remotebookmarks:
4952 4949 raise util.Abort(_('remote bookmark %s not found!') % b)
4953 4950 revs.append(remotebookmarks[b])
4954 4951
4955 4952 if revs:
4956 4953 try:
4957 4954 revs = [other.lookup(rev) for rev in revs]
4958 4955 except error.CapabilityError:
4959 4956 err = _("other repository doesn't support revision lookup, "
4960 4957 "so a rev cannot be specified.")
4961 4958 raise util.Abort(err)
4962 4959
4963 4960 modheads = exchange.pull(repo, other, heads=revs,
4964 4961 force=opts.get('force'),
4965 4962 bookmarks=opts.get('bookmark', ())).cgresult
4966 4963 if checkout:
4967 4964 checkout = str(repo.changelog.rev(other.lookup(checkout)))
4968 4965 repo._subtoppath = source
4969 4966 try:
4970 4967 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
4971 4968
4972 4969 finally:
4973 4970 del repo._subtoppath
4974 4971
4975 4972 finally:
4976 4973 other.close()
4977 4974 return ret
4978 4975
4979 4976 @command('^push',
4980 4977 [('f', 'force', None, _('force push')),
4981 4978 ('r', 'rev', [],
4982 4979 _('a changeset intended to be included in the destination'),
4983 4980 _('REV')),
4984 4981 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4985 4982 ('b', 'branch', [],
4986 4983 _('a specific branch you would like to push'), _('BRANCH')),
4987 4984 ('', 'new-branch', False, _('allow pushing a new branch')),
4988 4985 ] + remoteopts,
4989 4986 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4990 4987 def push(ui, repo, dest=None, **opts):
4991 4988 """push changes to the specified destination
4992 4989
4993 4990 Push changesets from the local repository to the specified
4994 4991 destination.
4995 4992
4996 4993 This operation is symmetrical to pull: it is identical to a pull
4997 4994 in the destination repository from the current one.
4998 4995
4999 4996 By default, push will not allow creation of new heads at the
5000 4997 destination, since multiple heads would make it unclear which head
5001 4998 to use. In this situation, it is recommended to pull and merge
5002 4999 before pushing.
5003 5000
5004 5001 Use --new-branch if you want to allow push to create a new named
5005 5002 branch that is not present at the destination. This allows you to
5006 5003 only create a new branch without forcing other changes.
5007 5004
5008 5005 .. note::
5009 5006
5010 5007 Extra care should be taken with the -f/--force option,
5011 5008 which will push all new heads on all branches, an action which will
5012 5009 almost always cause confusion for collaborators.
5013 5010
5014 5011 If -r/--rev is used, the specified revision and all its ancestors
5015 5012 will be pushed to the remote repository.
5016 5013
5017 5014 If -B/--bookmark is used, the specified bookmarked revision, its
5018 5015 ancestors, and the bookmark will be pushed to the remote
5019 5016 repository.
5020 5017
5021 5018 Please see :hg:`help urls` for important details about ``ssh://``
5022 5019 URLs. If DESTINATION is omitted, a default path will be used.
5023 5020
5024 5021 Returns 0 if push was successful, 1 if nothing to push.
5025 5022 """
5026 5023
5027 5024 if opts.get('bookmark'):
5028 5025 ui.setconfig('bookmarks', 'pushing', opts['bookmark'], 'push')
5029 5026 for b in opts['bookmark']:
5030 5027 # translate -B options to -r so changesets get pushed
5031 5028 if b in repo._bookmarks:
5032 5029 opts.setdefault('rev', []).append(b)
5033 5030 else:
5034 5031 # if we try to push a deleted bookmark, translate it to null
5035 5032 # this lets simultaneous -r, -b options continue working
5036 5033 opts.setdefault('rev', []).append("null")
5037 5034
5038 5035 dest = ui.expandpath(dest or 'default-push', dest or 'default')
5039 5036 dest, branches = hg.parseurl(dest, opts.get('branch'))
5040 5037 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
5041 5038 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
5042 5039 try:
5043 5040 other = hg.peer(repo, opts, dest)
5044 5041 except error.RepoError:
5045 5042 if dest == "default-push":
5046 5043 raise util.Abort(_("default repository not configured!"),
5047 5044 hint=_('see the "path" section in "hg help config"'))
5048 5045 else:
5049 5046 raise
5050 5047
5051 5048 if revs:
5052 5049 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
5053 5050
5054 5051 repo._subtoppath = dest
5055 5052 try:
5056 5053 # push subrepos depth-first for coherent ordering
5057 5054 c = repo['']
5058 5055 subs = c.substate # only repos that are committed
5059 5056 for s in sorted(subs):
5060 5057 result = c.sub(s).push(opts)
5061 5058 if result == 0:
5062 5059 return not result
5063 5060 finally:
5064 5061 del repo._subtoppath
5065 5062 pushop = exchange.push(repo, other, opts.get('force'), revs=revs,
5066 5063 newbranch=opts.get('new_branch'),
5067 5064 bookmarks=opts.get('bookmark', ()))
5068 5065
5069 5066 result = not pushop.cgresult
5070 5067
5071 5068 if pushop.bkresult is not None:
5072 5069 if pushop.bkresult == 2:
5073 5070 result = 2
5074 5071 elif not result and pushop.bkresult:
5075 5072 result = 2
5076 5073
5077 5074 return result
5078 5075
5079 5076 @command('recover', [])
5080 5077 def recover(ui, repo):
5081 5078 """roll back an interrupted transaction
5082 5079
5083 5080 Recover from an interrupted commit or pull.
5084 5081
5085 5082 This command tries to fix the repository status after an
5086 5083 interrupted operation. It should only be necessary when Mercurial
5087 5084 suggests it.
5088 5085
5089 5086 Returns 0 if successful, 1 if nothing to recover or verify fails.
5090 5087 """
5091 5088 if repo.recover():
5092 5089 return hg.verify(repo)
5093 5090 return 1
5094 5091
5095 5092 @command('^remove|rm',
5096 5093 [('A', 'after', None, _('record delete for missing files')),
5097 5094 ('f', 'force', None,
5098 5095 _('remove (and delete) file even if added or modified')),
5099 5096 ] + walkopts,
5100 5097 _('[OPTION]... FILE...'),
5101 5098 inferrepo=True)
5102 5099 def remove(ui, repo, *pats, **opts):
5103 5100 """remove the specified files on the next commit
5104 5101
5105 5102 Schedule the indicated files for removal from the current branch.
5106 5103
5107 5104 This command schedules the files to be removed at the next commit.
5108 5105 To undo a remove before that, see :hg:`revert`. To undo added
5109 5106 files, see :hg:`forget`.
5110 5107
5111 5108 .. container:: verbose
5112 5109
5113 5110 -A/--after can be used to remove only files that have already
5114 5111 been deleted, -f/--force can be used to force deletion, and -Af
5115 5112 can be used to remove files from the next revision without
5116 5113 deleting them from the working directory.
5117 5114
5118 5115 The following table details the behavior of remove for different
5119 5116 file states (columns) and option combinations (rows). The file
5120 5117 states are Added [A], Clean [C], Modified [M] and Missing [!]
5121 5118 (as reported by :hg:`status`). The actions are Warn, Remove
5122 5119 (from branch) and Delete (from disk):
5123 5120
5124 5121 ========= == == == ==
5125 5122 opt/state A C M !
5126 5123 ========= == == == ==
5127 5124 none W RD W R
5128 5125 -f R RD RD R
5129 5126 -A W W W R
5130 5127 -Af R R R R
5131 5128 ========= == == == ==
5132 5129
5133 5130 Note that remove never deletes files in Added [A] state from the
5134 5131 working directory, not even if option --force is specified.
5135 5132
5136 5133 Returns 0 on success, 1 if any warnings encountered.
5137 5134 """
5138 5135
5139 5136 ret = 0
5140 5137 after, force = opts.get('after'), opts.get('force')
5141 5138 if not pats and not after:
5142 5139 raise util.Abort(_('no files specified'))
5143 5140
5144 5141 m = scmutil.match(repo[None], pats, opts)
5145 5142 s = repo.status(match=m, clean=True)
5146 5143 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
5147 5144
5148 5145 # warn about failure to delete explicit files/dirs
5149 5146 wctx = repo[None]
5150 5147 for f in m.files():
5151 5148 if f in repo.dirstate or f in wctx.dirs():
5152 5149 continue
5153 5150 if os.path.exists(m.rel(f)):
5154 5151 if os.path.isdir(m.rel(f)):
5155 5152 ui.warn(_('not removing %s: no tracked files\n') % m.rel(f))
5156 5153 else:
5157 5154 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
5158 5155 # missing files will generate a warning elsewhere
5159 5156 ret = 1
5160 5157
5161 5158 if force:
5162 5159 list = modified + deleted + clean + added
5163 5160 elif after:
5164 5161 list = deleted
5165 5162 for f in modified + added + clean:
5166 5163 ui.warn(_('not removing %s: file still exists\n') % m.rel(f))
5167 5164 ret = 1
5168 5165 else:
5169 5166 list = deleted + clean
5170 5167 for f in modified:
5171 5168 ui.warn(_('not removing %s: file is modified (use -f'
5172 5169 ' to force removal)\n') % m.rel(f))
5173 5170 ret = 1
5174 5171 for f in added:
5175 5172 ui.warn(_('not removing %s: file has been marked for add'
5176 5173 ' (use forget to undo)\n') % m.rel(f))
5177 5174 ret = 1
5178 5175
5179 5176 for f in sorted(list):
5180 5177 if ui.verbose or not m.exact(f):
5181 5178 ui.status(_('removing %s\n') % m.rel(f))
5182 5179
5183 5180 wlock = repo.wlock()
5184 5181 try:
5185 5182 if not after:
5186 5183 for f in list:
5187 5184 if f in added:
5188 5185 continue # we never unlink added files on remove
5189 5186 util.unlinkpath(repo.wjoin(f), ignoremissing=True)
5190 5187 repo[None].forget(list)
5191 5188 finally:
5192 5189 wlock.release()
5193 5190
5194 5191 return ret
5195 5192
5196 5193 @command('rename|move|mv',
5197 5194 [('A', 'after', None, _('record a rename that has already occurred')),
5198 5195 ('f', 'force', None, _('forcibly copy over an existing managed file')),
5199 5196 ] + walkopts + dryrunopts,
5200 5197 _('[OPTION]... SOURCE... DEST'))
5201 5198 def rename(ui, repo, *pats, **opts):
5202 5199 """rename files; equivalent of copy + remove
5203 5200
5204 5201 Mark dest as copies of sources; mark sources for deletion. If dest
5205 5202 is a directory, copies are put in that directory. If dest is a
5206 5203 file, there can only be one source.
5207 5204
5208 5205 By default, this command copies the contents of files as they
5209 5206 exist in the working directory. If invoked with -A/--after, the
5210 5207 operation is recorded, but no copying is performed.
5211 5208
5212 5209 This command takes effect at the next commit. To undo a rename
5213 5210 before that, see :hg:`revert`.
5214 5211
5215 5212 Returns 0 on success, 1 if errors are encountered.
5216 5213 """
5217 5214 wlock = repo.wlock(False)
5218 5215 try:
5219 5216 return cmdutil.copy(ui, repo, pats, opts, rename=True)
5220 5217 finally:
5221 5218 wlock.release()
5222 5219
5223 5220 @command('resolve',
5224 5221 [('a', 'all', None, _('select all unresolved files')),
5225 5222 ('l', 'list', None, _('list state of files needing merge')),
5226 5223 ('m', 'mark', None, _('mark files as resolved')),
5227 5224 ('u', 'unmark', None, _('mark files as unresolved')),
5228 5225 ('n', 'no-status', None, _('hide status prefix'))]
5229 5226 + mergetoolopts + walkopts,
5230 5227 _('[OPTION]... [FILE]...'),
5231 5228 inferrepo=True)
5232 5229 def resolve(ui, repo, *pats, **opts):
5233 5230 """redo merges or set/view the merge status of files
5234 5231
5235 5232 Merges with unresolved conflicts are often the result of
5236 5233 non-interactive merging using the ``internal:merge`` configuration
5237 5234 setting, or a command-line merge tool like ``diff3``. The resolve
5238 5235 command is used to manage the files involved in a merge, after
5239 5236 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
5240 5237 working directory must have two parents). See :hg:`help
5241 5238 merge-tools` for information on configuring merge tools.
5242 5239
5243 5240 The resolve command can be used in the following ways:
5244 5241
5245 5242 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
5246 5243 files, discarding any previous merge attempts. Re-merging is not
5247 5244 performed for files already marked as resolved. Use ``--all/-a``
5248 5245 to select all unresolved files. ``--tool`` can be used to specify
5249 5246 the merge tool used for the given files. It overrides the HGMERGE
5250 5247 environment variable and your configuration files. Previous file
5251 5248 contents are saved with a ``.orig`` suffix.
5252 5249
5253 5250 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
5254 5251 (e.g. after having manually fixed-up the files). The default is
5255 5252 to mark all unresolved files.
5256 5253
5257 5254 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
5258 5255 default is to mark all resolved files.
5259 5256
5260 5257 - :hg:`resolve -l`: list files which had or still have conflicts.
5261 5258 In the printed list, ``U`` = unresolved and ``R`` = resolved.
5262 5259
5263 5260 Note that Mercurial will not let you commit files with unresolved
5264 5261 merge conflicts. You must use :hg:`resolve -m ...` before you can
5265 5262 commit after a conflicting merge.
5266 5263
5267 5264 Returns 0 on success, 1 if any files fail a resolve attempt.
5268 5265 """
5269 5266
5270 5267 all, mark, unmark, show, nostatus = \
5271 5268 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
5272 5269
5273 5270 if (show and (mark or unmark)) or (mark and unmark):
5274 5271 raise util.Abort(_("too many options specified"))
5275 5272 if pats and all:
5276 5273 raise util.Abort(_("can't specify --all and patterns"))
5277 5274 if not (all or pats or show or mark or unmark):
5278 5275 raise util.Abort(_('no files or directories specified'),
5279 5276 hint=('use --all to remerge all files'))
5280 5277
5281 5278 wlock = repo.wlock()
5282 5279 try:
5283 5280 ms = mergemod.mergestate(repo)
5284 5281
5285 5282 if not ms.active() and not show:
5286 5283 raise util.Abort(
5287 5284 _('resolve command not applicable when not merging'))
5288 5285
5289 5286 m = scmutil.match(repo[None], pats, opts)
5290 5287 ret = 0
5291 5288 didwork = False
5292 5289
5293 5290 for f in ms:
5294 5291 if not m(f):
5295 5292 continue
5296 5293
5297 5294 didwork = True
5298 5295
5299 5296 if show:
5300 5297 if nostatus:
5301 5298 ui.write("%s\n" % f)
5302 5299 else:
5303 5300 ui.write("%s %s\n" % (ms[f].upper(), f),
5304 5301 label='resolve.' +
5305 5302 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
5306 5303 elif mark:
5307 5304 ms.mark(f, "r")
5308 5305 elif unmark:
5309 5306 ms.mark(f, "u")
5310 5307 else:
5311 5308 wctx = repo[None]
5312 5309
5313 5310 # backup pre-resolve (merge uses .orig for its own purposes)
5314 5311 a = repo.wjoin(f)
5315 5312 util.copyfile(a, a + ".resolve")
5316 5313
5317 5314 try:
5318 5315 # resolve file
5319 5316 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
5320 5317 'resolve')
5321 5318 if ms.resolve(f, wctx):
5322 5319 ret = 1
5323 5320 finally:
5324 5321 ui.setconfig('ui', 'forcemerge', '', 'resolve')
5325 5322 ms.commit()
5326 5323
5327 5324 # replace filemerge's .orig file with our resolve file
5328 5325 util.rename(a + ".resolve", a + ".orig")
5329 5326
5330 5327 ms.commit()
5331 5328
5332 5329 if not didwork and pats:
5333 5330 ui.warn(_("arguments do not match paths that need resolving\n"))
5334 5331
5335 5332 finally:
5336 5333 wlock.release()
5337 5334
5338 5335 # Nudge users into finishing an unfinished operation. We don't print
5339 5336 # this with the list/show operation because we want list/show to remain
5340 5337 # machine readable.
5341 5338 if not list(ms.unresolved()) and not show:
5342 5339 ui.status(_('(no more unresolved files)\n'))
5343 5340
5344 5341 return ret
5345 5342
5346 5343 @command('revert',
5347 5344 [('a', 'all', None, _('revert all changes when no arguments given')),
5348 5345 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5349 5346 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
5350 5347 ('C', 'no-backup', None, _('do not save backup copies of files')),
5351 5348 ] + walkopts + dryrunopts,
5352 5349 _('[OPTION]... [-r REV] [NAME]...'))
5353 5350 def revert(ui, repo, *pats, **opts):
5354 5351 """restore files to their checkout state
5355 5352
5356 5353 .. note::
5357 5354
5358 5355 To check out earlier revisions, you should use :hg:`update REV`.
5359 5356 To cancel an uncommitted merge (and lose your changes),
5360 5357 use :hg:`update --clean .`.
5361 5358
5362 5359 With no revision specified, revert the specified files or directories
5363 5360 to the contents they had in the parent of the working directory.
5364 5361 This restores the contents of files to an unmodified
5365 5362 state and unschedules adds, removes, copies, and renames. If the
5366 5363 working directory has two parents, you must explicitly specify a
5367 5364 revision.
5368 5365
5369 5366 Using the -r/--rev or -d/--date options, revert the given files or
5370 5367 directories to their states as of a specific revision. Because
5371 5368 revert does not change the working directory parents, this will
5372 5369 cause these files to appear modified. This can be helpful to "back
5373 5370 out" some or all of an earlier change. See :hg:`backout` for a
5374 5371 related method.
5375 5372
5376 5373 Modified files are saved with a .orig suffix before reverting.
5377 5374 To disable these backups, use --no-backup.
5378 5375
5379 5376 See :hg:`help dates` for a list of formats valid for -d/--date.
5380 5377
5381 5378 Returns 0 on success.
5382 5379 """
5383 5380
5384 5381 if opts.get("date"):
5385 5382 if opts.get("rev"):
5386 5383 raise util.Abort(_("you can't specify a revision and a date"))
5387 5384 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
5388 5385
5389 5386 parent, p2 = repo.dirstate.parents()
5390 5387 if not opts.get('rev') and p2 != nullid:
5391 5388 # revert after merge is a trap for new users (issue2915)
5392 5389 raise util.Abort(_('uncommitted merge with no revision specified'),
5393 5390 hint=_('use "hg update" or see "hg help revert"'))
5394 5391
5395 5392 ctx = scmutil.revsingle(repo, opts.get('rev'))
5396 5393
5397 5394 if not pats and not opts.get('all'):
5398 5395 msg = _("no files or directories specified")
5399 5396 if p2 != nullid:
5400 5397 hint = _("uncommitted merge, use --all to discard all changes,"
5401 5398 " or 'hg update -C .' to abort the merge")
5402 5399 raise util.Abort(msg, hint=hint)
5403 5400 dirty = util.any(repo.status())
5404 5401 node = ctx.node()
5405 5402 if node != parent:
5406 5403 if dirty:
5407 5404 hint = _("uncommitted changes, use --all to discard all"
5408 5405 " changes, or 'hg update %s' to update") % ctx.rev()
5409 5406 else:
5410 5407 hint = _("use --all to revert all files,"
5411 5408 " or 'hg update %s' to update") % ctx.rev()
5412 5409 elif dirty:
5413 5410 hint = _("uncommitted changes, use --all to discard all changes")
5414 5411 else:
5415 5412 hint = _("use --all to revert all files")
5416 5413 raise util.Abort(msg, hint=hint)
5417 5414
5418 5415 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
5419 5416
5420 5417 @command('rollback', dryrunopts +
5421 5418 [('f', 'force', False, _('ignore safety measures'))])
5422 5419 def rollback(ui, repo, **opts):
5423 5420 """roll back the last transaction (DANGEROUS) (DEPRECATED)
5424 5421
5425 5422 Please use :hg:`commit --amend` instead of rollback to correct
5426 5423 mistakes in the last commit.
5427 5424
5428 5425 This command should be used with care. There is only one level of
5429 5426 rollback, and there is no way to undo a rollback. It will also
5430 5427 restore the dirstate at the time of the last transaction, losing
5431 5428 any dirstate changes since that time. This command does not alter
5432 5429 the working directory.
5433 5430
5434 5431 Transactions are used to encapsulate the effects of all commands
5435 5432 that create new changesets or propagate existing changesets into a
5436 5433 repository.
5437 5434
5438 5435 .. container:: verbose
5439 5436
5440 5437 For example, the following commands are transactional, and their
5441 5438 effects can be rolled back:
5442 5439
5443 5440 - commit
5444 5441 - import
5445 5442 - pull
5446 5443 - push (with this repository as the destination)
5447 5444 - unbundle
5448 5445
5449 5446 To avoid permanent data loss, rollback will refuse to rollback a
5450 5447 commit transaction if it isn't checked out. Use --force to
5451 5448 override this protection.
5452 5449
5453 5450 This command is not intended for use on public repositories. Once
5454 5451 changes are visible for pull by other users, rolling a transaction
5455 5452 back locally is ineffective (someone else may already have pulled
5456 5453 the changes). Furthermore, a race is possible with readers of the
5457 5454 repository; for example an in-progress pull from the repository
5458 5455 may fail if a rollback is performed.
5459 5456
5460 5457 Returns 0 on success, 1 if no rollback data is available.
5461 5458 """
5462 5459 return repo.rollback(dryrun=opts.get('dry_run'),
5463 5460 force=opts.get('force'))
5464 5461
5465 5462 @command('root', [])
5466 5463 def root(ui, repo):
5467 5464 """print the root (top) of the current working directory
5468 5465
5469 5466 Print the root directory of the current repository.
5470 5467
5471 5468 Returns 0 on success.
5472 5469 """
5473 5470 ui.write(repo.root + "\n")
5474 5471
5475 5472 @command('^serve',
5476 5473 [('A', 'accesslog', '', _('name of access log file to write to'),
5477 5474 _('FILE')),
5478 5475 ('d', 'daemon', None, _('run server in background')),
5479 5476 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
5480 5477 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
5481 5478 # use string type, then we can check if something was passed
5482 5479 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
5483 5480 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
5484 5481 _('ADDR')),
5485 5482 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
5486 5483 _('PREFIX')),
5487 5484 ('n', 'name', '',
5488 5485 _('name to show in web pages (default: working directory)'), _('NAME')),
5489 5486 ('', 'web-conf', '',
5490 5487 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
5491 5488 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
5492 5489 _('FILE')),
5493 5490 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
5494 5491 ('', 'stdio', None, _('for remote clients')),
5495 5492 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
5496 5493 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
5497 5494 ('', 'style', '', _('template style to use'), _('STYLE')),
5498 5495 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
5499 5496 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
5500 5497 _('[OPTION]...'),
5501 5498 optionalrepo=True)
5502 5499 def serve(ui, repo, **opts):
5503 5500 """start stand-alone webserver
5504 5501
5505 5502 Start a local HTTP repository browser and pull server. You can use
5506 5503 this for ad-hoc sharing and browsing of repositories. It is
5507 5504 recommended to use a real web server to serve a repository for
5508 5505 longer periods of time.
5509 5506
5510 5507 Please note that the server does not implement access control.
5511 5508 This means that, by default, anybody can read from the server and
5512 5509 nobody can write to it by default. Set the ``web.allow_push``
5513 5510 option to ``*`` to allow everybody to push to the server. You
5514 5511 should use a real web server if you need to authenticate users.
5515 5512
5516 5513 By default, the server logs accesses to stdout and errors to
5517 5514 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
5518 5515 files.
5519 5516
5520 5517 To have the server choose a free port number to listen on, specify
5521 5518 a port number of 0; in this case, the server will print the port
5522 5519 number it uses.
5523 5520
5524 5521 Returns 0 on success.
5525 5522 """
5526 5523
5527 5524 if opts["stdio"] and opts["cmdserver"]:
5528 5525 raise util.Abort(_("cannot use --stdio with --cmdserver"))
5529 5526
5530 5527 if opts["stdio"]:
5531 5528 if repo is None:
5532 5529 raise error.RepoError(_("there is no Mercurial repository here"
5533 5530 " (.hg not found)"))
5534 5531 s = sshserver.sshserver(ui, repo)
5535 5532 s.serve_forever()
5536 5533
5537 5534 if opts["cmdserver"]:
5538 5535 s = commandserver.server(ui, repo, opts["cmdserver"])
5539 5536 return s.serve()
5540 5537
5541 5538 # this way we can check if something was given in the command-line
5542 5539 if opts.get('port'):
5543 5540 opts['port'] = util.getport(opts.get('port'))
5544 5541
5545 5542 baseui = repo and repo.baseui or ui
5546 5543 optlist = ("name templates style address port prefix ipv6"
5547 5544 " accesslog errorlog certificate encoding")
5548 5545 for o in optlist.split():
5549 5546 val = opts.get(o, '')
5550 5547 if val in (None, ''): # should check against default options instead
5551 5548 continue
5552 5549 baseui.setconfig("web", o, val, 'serve')
5553 5550 if repo and repo.ui != baseui:
5554 5551 repo.ui.setconfig("web", o, val, 'serve')
5555 5552
5556 5553 o = opts.get('web_conf') or opts.get('webdir_conf')
5557 5554 if not o:
5558 5555 if not repo:
5559 5556 raise error.RepoError(_("there is no Mercurial repository"
5560 5557 " here (.hg not found)"))
5561 5558 o = repo
5562 5559
5563 5560 app = hgweb.hgweb(o, baseui=baseui)
5564 5561 service = httpservice(ui, app, opts)
5565 5562 cmdutil.service(opts, initfn=service.init, runfn=service.run)
5566 5563
5567 5564 class httpservice(object):
5568 5565 def __init__(self, ui, app, opts):
5569 5566 self.ui = ui
5570 5567 self.app = app
5571 5568 self.opts = opts
5572 5569
5573 5570 def init(self):
5574 5571 util.setsignalhandler()
5575 5572 self.httpd = hgweb_server.create_server(self.ui, self.app)
5576 5573
5577 5574 if self.opts['port'] and not self.ui.verbose:
5578 5575 return
5579 5576
5580 5577 if self.httpd.prefix:
5581 5578 prefix = self.httpd.prefix.strip('/') + '/'
5582 5579 else:
5583 5580 prefix = ''
5584 5581
5585 5582 port = ':%d' % self.httpd.port
5586 5583 if port == ':80':
5587 5584 port = ''
5588 5585
5589 5586 bindaddr = self.httpd.addr
5590 5587 if bindaddr == '0.0.0.0':
5591 5588 bindaddr = '*'
5592 5589 elif ':' in bindaddr: # IPv6
5593 5590 bindaddr = '[%s]' % bindaddr
5594 5591
5595 5592 fqaddr = self.httpd.fqaddr
5596 5593 if ':' in fqaddr:
5597 5594 fqaddr = '[%s]' % fqaddr
5598 5595 if self.opts['port']:
5599 5596 write = self.ui.status
5600 5597 else:
5601 5598 write = self.ui.write
5602 5599 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
5603 5600 (fqaddr, port, prefix, bindaddr, self.httpd.port))
5604 5601 self.ui.flush() # avoid buffering of status message
5605 5602
5606 5603 def run(self):
5607 5604 self.httpd.serve_forever()
5608 5605
5609 5606
5610 5607 @command('^status|st',
5611 5608 [('A', 'all', None, _('show status of all files')),
5612 5609 ('m', 'modified', None, _('show only modified files')),
5613 5610 ('a', 'added', None, _('show only added files')),
5614 5611 ('r', 'removed', None, _('show only removed files')),
5615 5612 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
5616 5613 ('c', 'clean', None, _('show only files without changes')),
5617 5614 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
5618 5615 ('i', 'ignored', None, _('show only ignored files')),
5619 5616 ('n', 'no-status', None, _('hide status prefix')),
5620 5617 ('C', 'copies', None, _('show source of copied files')),
5621 5618 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
5622 5619 ('', 'rev', [], _('show difference from revision'), _('REV')),
5623 5620 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
5624 5621 ] + walkopts + subrepoopts + formatteropts,
5625 5622 _('[OPTION]... [FILE]...'),
5626 5623 inferrepo=True)
5627 5624 def status(ui, repo, *pats, **opts):
5628 5625 """show changed files in the working directory
5629 5626
5630 5627 Show status of files in the repository. If names are given, only
5631 5628 files that match are shown. Files that are clean or ignored or
5632 5629 the source of a copy/move operation, are not listed unless
5633 5630 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
5634 5631 Unless options described with "show only ..." are given, the
5635 5632 options -mardu are used.
5636 5633
5637 5634 Option -q/--quiet hides untracked (unknown and ignored) files
5638 5635 unless explicitly requested with -u/--unknown or -i/--ignored.
5639 5636
5640 5637 .. note::
5641 5638
5642 5639 status may appear to disagree with diff if permissions have
5643 5640 changed or a merge has occurred. The standard diff format does
5644 5641 not report permission changes and diff only reports changes
5645 5642 relative to one merge parent.
5646 5643
5647 5644 If one revision is given, it is used as the base revision.
5648 5645 If two revisions are given, the differences between them are
5649 5646 shown. The --change option can also be used as a shortcut to list
5650 5647 the changed files of a revision from its first parent.
5651 5648
5652 5649 The codes used to show the status of files are::
5653 5650
5654 5651 M = modified
5655 5652 A = added
5656 5653 R = removed
5657 5654 C = clean
5658 5655 ! = missing (deleted by non-hg command, but still tracked)
5659 5656 ? = not tracked
5660 5657 I = ignored
5661 5658 = origin of the previous file (with --copies)
5662 5659
5663 5660 .. container:: verbose
5664 5661
5665 5662 Examples:
5666 5663
5667 5664 - show changes in the working directory relative to a
5668 5665 changeset::
5669 5666
5670 5667 hg status --rev 9353
5671 5668
5672 5669 - show all changes including copies in an existing changeset::
5673 5670
5674 5671 hg status --copies --change 9353
5675 5672
5676 5673 - get a NUL separated list of added files, suitable for xargs::
5677 5674
5678 5675 hg status -an0
5679 5676
5680 5677 Returns 0 on success.
5681 5678 """
5682 5679
5683 5680 revs = opts.get('rev')
5684 5681 change = opts.get('change')
5685 5682
5686 5683 if revs and change:
5687 5684 msg = _('cannot specify --rev and --change at the same time')
5688 5685 raise util.Abort(msg)
5689 5686 elif change:
5690 5687 node2 = scmutil.revsingle(repo, change, None).node()
5691 5688 node1 = repo[node2].p1().node()
5692 5689 else:
5693 5690 node1, node2 = scmutil.revpair(repo, revs)
5694 5691
5695 5692 cwd = (pats and repo.getcwd()) or ''
5696 5693 end = opts.get('print0') and '\0' or '\n'
5697 5694 copy = {}
5698 5695 states = 'modified added removed deleted unknown ignored clean'.split()
5699 5696 show = [k for k in states if opts.get(k)]
5700 5697 if opts.get('all'):
5701 5698 show += ui.quiet and (states[:4] + ['clean']) or states
5702 5699 if not show:
5703 5700 show = ui.quiet and states[:4] or states[:5]
5704 5701
5705 5702 stat = repo.status(node1, node2, scmutil.match(repo[node2], pats, opts),
5706 5703 'ignored' in show, 'clean' in show, 'unknown' in show,
5707 5704 opts.get('subrepos'))
5708 5705 changestates = zip(states, 'MAR!?IC', stat)
5709 5706
5710 5707 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
5711 5708 copy = copies.pathcopies(repo[node1], repo[node2])
5712 5709
5713 5710 fm = ui.formatter('status', opts)
5714 5711 fmt = '%s' + end
5715 5712 showchar = not opts.get('no_status')
5716 5713
5717 5714 for state, char, files in changestates:
5718 5715 if state in show:
5719 5716 label = 'status.' + state
5720 5717 for f in files:
5721 5718 fm.startitem()
5722 5719 fm.condwrite(showchar, 'status', '%s ', char, label=label)
5723 5720 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
5724 5721 if f in copy:
5725 5722 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
5726 5723 label='status.copied')
5727 5724 fm.end()
5728 5725
5729 5726 @command('^summary|sum',
5730 5727 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
5731 5728 def summary(ui, repo, **opts):
5732 5729 """summarize working directory state
5733 5730
5734 5731 This generates a brief summary of the working directory state,
5735 5732 including parents, branch, commit status, and available updates.
5736 5733
5737 5734 With the --remote option, this will check the default paths for
5738 5735 incoming and outgoing changes. This can be time-consuming.
5739 5736
5740 5737 Returns 0 on success.
5741 5738 """
5742 5739
5743 5740 ctx = repo[None]
5744 5741 parents = ctx.parents()
5745 5742 pnode = parents[0].node()
5746 5743 marks = []
5747 5744
5748 5745 for p in parents:
5749 5746 # label with log.changeset (instead of log.parent) since this
5750 5747 # shows a working directory parent *changeset*:
5751 5748 # i18n: column positioning for "hg summary"
5752 5749 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
5753 5750 label='log.changeset changeset.%s' % p.phasestr())
5754 5751 ui.write(' '.join(p.tags()), label='log.tag')
5755 5752 if p.bookmarks():
5756 5753 marks.extend(p.bookmarks())
5757 5754 if p.rev() == -1:
5758 5755 if not len(repo):
5759 5756 ui.write(_(' (empty repository)'))
5760 5757 else:
5761 5758 ui.write(_(' (no revision checked out)'))
5762 5759 ui.write('\n')
5763 5760 if p.description():
5764 5761 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5765 5762 label='log.summary')
5766 5763
5767 5764 branch = ctx.branch()
5768 5765 bheads = repo.branchheads(branch)
5769 5766 # i18n: column positioning for "hg summary"
5770 5767 m = _('branch: %s\n') % branch
5771 5768 if branch != 'default':
5772 5769 ui.write(m, label='log.branch')
5773 5770 else:
5774 5771 ui.status(m, label='log.branch')
5775 5772
5776 5773 if marks:
5777 5774 current = repo._bookmarkcurrent
5778 5775 # i18n: column positioning for "hg summary"
5779 5776 ui.write(_('bookmarks:'), label='log.bookmark')
5780 5777 if current is not None:
5781 5778 if current in marks:
5782 5779 ui.write(' *' + current, label='bookmarks.current')
5783 5780 marks.remove(current)
5784 5781 else:
5785 5782 ui.write(' [%s]' % current, label='bookmarks.current')
5786 5783 for m in marks:
5787 5784 ui.write(' ' + m, label='log.bookmark')
5788 5785 ui.write('\n', label='log.bookmark')
5789 5786
5790 5787 st = list(repo.status(unknown=True))[:5]
5791 5788
5792 5789 c = repo.dirstate.copies()
5793 5790 copied, renamed = [], []
5794 5791 for d, s in c.iteritems():
5795 5792 if s in st[2]:
5796 5793 st[2].remove(s)
5797 5794 renamed.append(d)
5798 5795 else:
5799 5796 copied.append(d)
5800 5797 if d in st[1]:
5801 5798 st[1].remove(d)
5802 5799 st.insert(3, renamed)
5803 5800 st.insert(4, copied)
5804 5801
5805 5802 ms = mergemod.mergestate(repo)
5806 5803 st.append([f for f in ms if ms[f] == 'u'])
5807 5804
5808 5805 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5809 5806 st.append(subs)
5810 5807
5811 5808 labels = [ui.label(_('%d modified'), 'status.modified'),
5812 5809 ui.label(_('%d added'), 'status.added'),
5813 5810 ui.label(_('%d removed'), 'status.removed'),
5814 5811 ui.label(_('%d renamed'), 'status.copied'),
5815 5812 ui.label(_('%d copied'), 'status.copied'),
5816 5813 ui.label(_('%d deleted'), 'status.deleted'),
5817 5814 ui.label(_('%d unknown'), 'status.unknown'),
5818 5815 ui.label(_('%d unresolved'), 'resolve.unresolved'),
5819 5816 ui.label(_('%d subrepos'), 'status.modified')]
5820 5817 t = []
5821 5818 for s, l in zip(st, labels):
5822 5819 if s:
5823 5820 t.append(l % len(s))
5824 5821
5825 5822 t = ', '.join(t)
5826 5823 cleanworkdir = False
5827 5824
5828 5825 if repo.vfs.exists('updatestate'):
5829 5826 t += _(' (interrupted update)')
5830 5827 elif len(parents) > 1:
5831 5828 t += _(' (merge)')
5832 5829 elif branch != parents[0].branch():
5833 5830 t += _(' (new branch)')
5834 5831 elif (parents[0].closesbranch() and
5835 5832 pnode in repo.branchheads(branch, closed=True)):
5836 5833 t += _(' (head closed)')
5837 5834 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[8]):
5838 5835 t += _(' (clean)')
5839 5836 cleanworkdir = True
5840 5837 elif pnode not in bheads:
5841 5838 t += _(' (new branch head)')
5842 5839
5843 5840 if cleanworkdir:
5844 5841 # i18n: column positioning for "hg summary"
5845 5842 ui.status(_('commit: %s\n') % t.strip())
5846 5843 else:
5847 5844 # i18n: column positioning for "hg summary"
5848 5845 ui.write(_('commit: %s\n') % t.strip())
5849 5846
5850 5847 # all ancestors of branch heads - all ancestors of parent = new csets
5851 5848 new = len(repo.changelog.findmissing([pctx.node() for pctx in parents],
5852 5849 bheads))
5853 5850
5854 5851 if new == 0:
5855 5852 # i18n: column positioning for "hg summary"
5856 5853 ui.status(_('update: (current)\n'))
5857 5854 elif pnode not in bheads:
5858 5855 # i18n: column positioning for "hg summary"
5859 5856 ui.write(_('update: %d new changesets (update)\n') % new)
5860 5857 else:
5861 5858 # i18n: column positioning for "hg summary"
5862 5859 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5863 5860 (new, len(bheads)))
5864 5861
5865 5862 cmdutil.summaryhooks(ui, repo)
5866 5863
5867 5864 if opts.get('remote'):
5868 5865 needsincoming, needsoutgoing = True, True
5869 5866 else:
5870 5867 needsincoming, needsoutgoing = False, False
5871 5868 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
5872 5869 if i:
5873 5870 needsincoming = True
5874 5871 if o:
5875 5872 needsoutgoing = True
5876 5873 if not needsincoming and not needsoutgoing:
5877 5874 return
5878 5875
5879 5876 def getincoming():
5880 5877 source, branches = hg.parseurl(ui.expandpath('default'))
5881 5878 sbranch = branches[0]
5882 5879 try:
5883 5880 other = hg.peer(repo, {}, source)
5884 5881 except error.RepoError:
5885 5882 if opts.get('remote'):
5886 5883 raise
5887 5884 return source, sbranch, None, None, None
5888 5885 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
5889 5886 if revs:
5890 5887 revs = [other.lookup(rev) for rev in revs]
5891 5888 ui.debug('comparing with %s\n' % util.hidepassword(source))
5892 5889 repo.ui.pushbuffer()
5893 5890 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
5894 5891 repo.ui.popbuffer()
5895 5892 return source, sbranch, other, commoninc, commoninc[1]
5896 5893
5897 5894 if needsincoming:
5898 5895 source, sbranch, sother, commoninc, incoming = getincoming()
5899 5896 else:
5900 5897 source = sbranch = sother = commoninc = incoming = None
5901 5898
5902 5899 def getoutgoing():
5903 5900 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5904 5901 dbranch = branches[0]
5905 5902 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5906 5903 if source != dest:
5907 5904 try:
5908 5905 dother = hg.peer(repo, {}, dest)
5909 5906 except error.RepoError:
5910 5907 if opts.get('remote'):
5911 5908 raise
5912 5909 return dest, dbranch, None, None
5913 5910 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5914 5911 elif sother is None:
5915 5912 # there is no explicit destination peer, but source one is invalid
5916 5913 return dest, dbranch, None, None
5917 5914 else:
5918 5915 dother = sother
5919 5916 if (source != dest or (sbranch is not None and sbranch != dbranch)):
5920 5917 common = None
5921 5918 else:
5922 5919 common = commoninc
5923 5920 if revs:
5924 5921 revs = [repo.lookup(rev) for rev in revs]
5925 5922 repo.ui.pushbuffer()
5926 5923 outgoing = discovery.findcommonoutgoing(repo, dother, onlyheads=revs,
5927 5924 commoninc=common)
5928 5925 repo.ui.popbuffer()
5929 5926 return dest, dbranch, dother, outgoing
5930 5927
5931 5928 if needsoutgoing:
5932 5929 dest, dbranch, dother, outgoing = getoutgoing()
5933 5930 else:
5934 5931 dest = dbranch = dother = outgoing = None
5935 5932
5936 5933 if opts.get('remote'):
5937 5934 t = []
5938 5935 if incoming:
5939 5936 t.append(_('1 or more incoming'))
5940 5937 o = outgoing.missing
5941 5938 if o:
5942 5939 t.append(_('%d outgoing') % len(o))
5943 5940 other = dother or sother
5944 5941 if 'bookmarks' in other.listkeys('namespaces'):
5945 5942 lmarks = repo.listkeys('bookmarks')
5946 5943 rmarks = other.listkeys('bookmarks')
5947 5944 diff = set(rmarks) - set(lmarks)
5948 5945 if len(diff) > 0:
5949 5946 t.append(_('%d incoming bookmarks') % len(diff))
5950 5947 diff = set(lmarks) - set(rmarks)
5951 5948 if len(diff) > 0:
5952 5949 t.append(_('%d outgoing bookmarks') % len(diff))
5953 5950
5954 5951 if t:
5955 5952 # i18n: column positioning for "hg summary"
5956 5953 ui.write(_('remote: %s\n') % (', '.join(t)))
5957 5954 else:
5958 5955 # i18n: column positioning for "hg summary"
5959 5956 ui.status(_('remote: (synced)\n'))
5960 5957
5961 5958 cmdutil.summaryremotehooks(ui, repo, opts,
5962 5959 ((source, sbranch, sother, commoninc),
5963 5960 (dest, dbranch, dother, outgoing)))
5964 5961
5965 5962 @command('tag',
5966 5963 [('f', 'force', None, _('force tag')),
5967 5964 ('l', 'local', None, _('make the tag local')),
5968 5965 ('r', 'rev', '', _('revision to tag'), _('REV')),
5969 5966 ('', 'remove', None, _('remove a tag')),
5970 5967 # -l/--local is already there, commitopts cannot be used
5971 5968 ('e', 'edit', None, _('invoke editor on commit messages')),
5972 5969 ('m', 'message', '', _('use text as commit message'), _('TEXT')),
5973 5970 ] + commitopts2,
5974 5971 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5975 5972 def tag(ui, repo, name1, *names, **opts):
5976 5973 """add one or more tags for the current or given revision
5977 5974
5978 5975 Name a particular revision using <name>.
5979 5976
5980 5977 Tags are used to name particular revisions of the repository and are
5981 5978 very useful to compare different revisions, to go back to significant
5982 5979 earlier versions or to mark branch points as releases, etc. Changing
5983 5980 an existing tag is normally disallowed; use -f/--force to override.
5984 5981
5985 5982 If no revision is given, the parent of the working directory is
5986 5983 used.
5987 5984
5988 5985 To facilitate version control, distribution, and merging of tags,
5989 5986 they are stored as a file named ".hgtags" which is managed similarly
5990 5987 to other project files and can be hand-edited if necessary. This
5991 5988 also means that tagging creates a new commit. The file
5992 5989 ".hg/localtags" is used for local tags (not shared among
5993 5990 repositories).
5994 5991
5995 5992 Tag commits are usually made at the head of a branch. If the parent
5996 5993 of the working directory is not a branch head, :hg:`tag` aborts; use
5997 5994 -f/--force to force the tag commit to be based on a non-head
5998 5995 changeset.
5999 5996
6000 5997 See :hg:`help dates` for a list of formats valid for -d/--date.
6001 5998
6002 5999 Since tag names have priority over branch names during revision
6003 6000 lookup, using an existing branch name as a tag name is discouraged.
6004 6001
6005 6002 Returns 0 on success.
6006 6003 """
6007 6004 wlock = lock = None
6008 6005 try:
6009 6006 wlock = repo.wlock()
6010 6007 lock = repo.lock()
6011 6008 rev_ = "."
6012 6009 names = [t.strip() for t in (name1,) + names]
6013 6010 if len(names) != len(set(names)):
6014 6011 raise util.Abort(_('tag names must be unique'))
6015 6012 for n in names:
6016 6013 scmutil.checknewlabel(repo, n, 'tag')
6017 6014 if not n:
6018 6015 raise util.Abort(_('tag names cannot consist entirely of '
6019 6016 'whitespace'))
6020 6017 if opts.get('rev') and opts.get('remove'):
6021 6018 raise util.Abort(_("--rev and --remove are incompatible"))
6022 6019 if opts.get('rev'):
6023 6020 rev_ = opts['rev']
6024 6021 message = opts.get('message')
6025 6022 if opts.get('remove'):
6026 6023 expectedtype = opts.get('local') and 'local' or 'global'
6027 6024 for n in names:
6028 6025 if not repo.tagtype(n):
6029 6026 raise util.Abort(_("tag '%s' does not exist") % n)
6030 6027 if repo.tagtype(n) != expectedtype:
6031 6028 if expectedtype == 'global':
6032 6029 raise util.Abort(_("tag '%s' is not a global tag") % n)
6033 6030 else:
6034 6031 raise util.Abort(_("tag '%s' is not a local tag") % n)
6035 6032 rev_ = nullid
6036 6033 if not message:
6037 6034 # we don't translate commit messages
6038 6035 message = 'Removed tag %s' % ', '.join(names)
6039 6036 elif not opts.get('force'):
6040 6037 for n in names:
6041 6038 if n in repo.tags():
6042 6039 raise util.Abort(_("tag '%s' already exists "
6043 6040 "(use -f to force)") % n)
6044 6041 if not opts.get('local'):
6045 6042 p1, p2 = repo.dirstate.parents()
6046 6043 if p2 != nullid:
6047 6044 raise util.Abort(_('uncommitted merge'))
6048 6045 bheads = repo.branchheads()
6049 6046 if not opts.get('force') and bheads and p1 not in bheads:
6050 6047 raise util.Abort(_('not at a branch head (use -f to force)'))
6051 6048 r = scmutil.revsingle(repo, rev_).node()
6052 6049
6053 6050 if not message:
6054 6051 # we don't translate commit messages
6055 6052 message = ('Added tag %s for changeset %s' %
6056 6053 (', '.join(names), short(r)))
6057 6054
6058 6055 date = opts.get('date')
6059 6056 if date:
6060 6057 date = util.parsedate(date)
6061 6058
6062 6059 if opts.get('remove'):
6063 6060 editform = 'tag.remove'
6064 6061 else:
6065 6062 editform = 'tag.add'
6066 6063 editor = cmdutil.getcommiteditor(editform=editform, **opts)
6067 6064
6068 6065 # don't allow tagging the null rev
6069 6066 if (not opts.get('remove') and
6070 6067 scmutil.revsingle(repo, rev_).rev() == nullrev):
6071 6068 raise util.Abort(_("cannot tag null revision"))
6072 6069
6073 6070 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date,
6074 6071 editor=editor)
6075 6072 finally:
6076 6073 release(lock, wlock)
6077 6074
6078 6075 @command('tags', formatteropts, '')
6079 6076 def tags(ui, repo, **opts):
6080 6077 """list repository tags
6081 6078
6082 6079 This lists both regular and local tags. When the -v/--verbose
6083 6080 switch is used, a third column "local" is printed for local tags.
6084 6081
6085 6082 Returns 0 on success.
6086 6083 """
6087 6084
6088 6085 fm = ui.formatter('tags', opts)
6089 if fm or ui.debugflag:
6090 hexfunc = hex
6091 else:
6092 hexfunc = short
6086 hexfunc = fm.hexfunc
6093 6087 tagtype = ""
6094 6088
6095 6089 for t, n in reversed(repo.tagslist()):
6096 6090 hn = hexfunc(n)
6097 6091 label = 'tags.normal'
6098 6092 tagtype = ''
6099 6093 if repo.tagtype(t) == 'local':
6100 6094 label = 'tags.local'
6101 6095 tagtype = 'local'
6102 6096
6103 6097 fm.startitem()
6104 6098 fm.write('tag', '%s', t, label=label)
6105 6099 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
6106 6100 fm.condwrite(not ui.quiet, 'rev node', fmt,
6107 6101 repo.changelog.rev(n), hn, label=label)
6108 6102 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
6109 6103 tagtype, label=label)
6110 6104 fm.plain('\n')
6111 6105 fm.end()
6112 6106
6113 6107 @command('tip',
6114 6108 [('p', 'patch', None, _('show patch')),
6115 6109 ('g', 'git', None, _('use git extended diff format')),
6116 6110 ] + templateopts,
6117 6111 _('[-p] [-g]'))
6118 6112 def tip(ui, repo, **opts):
6119 6113 """show the tip revision (DEPRECATED)
6120 6114
6121 6115 The tip revision (usually just called the tip) is the changeset
6122 6116 most recently added to the repository (and therefore the most
6123 6117 recently changed head).
6124 6118
6125 6119 If you have just made a commit, that commit will be the tip. If
6126 6120 you have just pulled changes from another repository, the tip of
6127 6121 that repository becomes the current tip. The "tip" tag is special
6128 6122 and cannot be renamed or assigned to a different changeset.
6129 6123
6130 6124 This command is deprecated, please use :hg:`heads` instead.
6131 6125
6132 6126 Returns 0 on success.
6133 6127 """
6134 6128 displayer = cmdutil.show_changeset(ui, repo, opts)
6135 6129 displayer.show(repo['tip'])
6136 6130 displayer.close()
6137 6131
6138 6132 @command('unbundle',
6139 6133 [('u', 'update', None,
6140 6134 _('update to new branch head if changesets were unbundled'))],
6141 6135 _('[-u] FILE...'))
6142 6136 def unbundle(ui, repo, fname1, *fnames, **opts):
6143 6137 """apply one or more changegroup files
6144 6138
6145 6139 Apply one or more compressed changegroup files generated by the
6146 6140 bundle command.
6147 6141
6148 6142 Returns 0 on success, 1 if an update has unresolved files.
6149 6143 """
6150 6144 fnames = (fname1,) + fnames
6151 6145
6152 6146 lock = repo.lock()
6153 6147 try:
6154 6148 for fname in fnames:
6155 6149 f = hg.openpath(ui, fname)
6156 6150 gen = exchange.readbundle(ui, f, fname)
6157 6151 modheads = changegroup.addchangegroup(repo, gen, 'unbundle',
6158 6152 'bundle:' + fname)
6159 6153 finally:
6160 6154 lock.release()
6161 6155
6162 6156 return postincoming(ui, repo, modheads, opts.get('update'), None)
6163 6157
6164 6158 @command('^update|up|checkout|co',
6165 6159 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
6166 6160 ('c', 'check', None,
6167 6161 _('update across branches if no uncommitted changes')),
6168 6162 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
6169 6163 ('r', 'rev', '', _('revision'), _('REV'))
6170 6164 ] + mergetoolopts,
6171 6165 _('[-c] [-C] [-d DATE] [[-r] REV]'))
6172 6166 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False,
6173 6167 tool=None):
6174 6168 """update working directory (or switch revisions)
6175 6169
6176 6170 Update the repository's working directory to the specified
6177 6171 changeset. If no changeset is specified, update to the tip of the
6178 6172 current named branch and move the current bookmark (see :hg:`help
6179 6173 bookmarks`).
6180 6174
6181 6175 Update sets the working directory's parent revision to the specified
6182 6176 changeset (see :hg:`help parents`).
6183 6177
6184 6178 If the changeset is not a descendant or ancestor of the working
6185 6179 directory's parent, the update is aborted. With the -c/--check
6186 6180 option, the working directory is checked for uncommitted changes; if
6187 6181 none are found, the working directory is updated to the specified
6188 6182 changeset.
6189 6183
6190 6184 .. container:: verbose
6191 6185
6192 6186 The following rules apply when the working directory contains
6193 6187 uncommitted changes:
6194 6188
6195 6189 1. If neither -c/--check nor -C/--clean is specified, and if
6196 6190 the requested changeset is an ancestor or descendant of
6197 6191 the working directory's parent, the uncommitted changes
6198 6192 are merged into the requested changeset and the merged
6199 6193 result is left uncommitted. If the requested changeset is
6200 6194 not an ancestor or descendant (that is, it is on another
6201 6195 branch), the update is aborted and the uncommitted changes
6202 6196 are preserved.
6203 6197
6204 6198 2. With the -c/--check option, the update is aborted and the
6205 6199 uncommitted changes are preserved.
6206 6200
6207 6201 3. With the -C/--clean option, uncommitted changes are discarded and
6208 6202 the working directory is updated to the requested changeset.
6209 6203
6210 6204 To cancel an uncommitted merge (and lose your changes), use
6211 6205 :hg:`update --clean .`.
6212 6206
6213 6207 Use null as the changeset to remove the working directory (like
6214 6208 :hg:`clone -U`).
6215 6209
6216 6210 If you want to revert just one file to an older revision, use
6217 6211 :hg:`revert [-r REV] NAME`.
6218 6212
6219 6213 See :hg:`help dates` for a list of formats valid for -d/--date.
6220 6214
6221 6215 Returns 0 on success, 1 if there are unresolved files.
6222 6216 """
6223 6217 if rev and node:
6224 6218 raise util.Abort(_("please specify just one revision"))
6225 6219
6226 6220 if rev is None or rev == '':
6227 6221 rev = node
6228 6222
6229 6223 cmdutil.clearunfinished(repo)
6230 6224
6231 6225 # with no argument, we also move the current bookmark, if any
6232 6226 rev, movemarkfrom = bookmarks.calculateupdate(ui, repo, rev)
6233 6227
6234 6228 # if we defined a bookmark, we have to remember the original bookmark name
6235 6229 brev = rev
6236 6230 rev = scmutil.revsingle(repo, rev, rev).rev()
6237 6231
6238 6232 if check and clean:
6239 6233 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
6240 6234
6241 6235 if date:
6242 6236 if rev is not None:
6243 6237 raise util.Abort(_("you can't specify a revision and a date"))
6244 6238 rev = cmdutil.finddate(ui, repo, date)
6245 6239
6246 6240 if check:
6247 6241 c = repo[None]
6248 6242 if c.dirty(merge=False, branch=False, missing=True):
6249 6243 raise util.Abort(_("uncommitted changes"))
6250 6244 if rev is None:
6251 6245 rev = repo[repo[None].branch()].rev()
6252 6246 mergemod._checkunknown(repo, repo[None], repo[rev])
6253 6247
6254 6248 repo.ui.setconfig('ui', 'forcemerge', tool, 'update')
6255 6249
6256 6250 if clean:
6257 6251 ret = hg.clean(repo, rev)
6258 6252 else:
6259 6253 ret = hg.update(repo, rev)
6260 6254
6261 6255 if not ret and movemarkfrom:
6262 6256 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
6263 6257 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
6264 6258 elif brev in repo._bookmarks:
6265 6259 bookmarks.setcurrent(repo, brev)
6266 6260 ui.status(_("(activating bookmark %s)\n") % brev)
6267 6261 elif brev:
6268 6262 if repo._bookmarkcurrent:
6269 6263 ui.status(_("(leaving bookmark %s)\n") %
6270 6264 repo._bookmarkcurrent)
6271 6265 bookmarks.unsetcurrent(repo)
6272 6266
6273 6267 return ret
6274 6268
6275 6269 @command('verify', [])
6276 6270 def verify(ui, repo):
6277 6271 """verify the integrity of the repository
6278 6272
6279 6273 Verify the integrity of the current repository.
6280 6274
6281 6275 This will perform an extensive check of the repository's
6282 6276 integrity, validating the hashes and checksums of each entry in
6283 6277 the changelog, manifest, and tracked files, as well as the
6284 6278 integrity of their crosslinks and indices.
6285 6279
6286 6280 Please see http://mercurial.selenic.com/wiki/RepositoryCorruption
6287 6281 for more information about recovery from corruption of the
6288 6282 repository.
6289 6283
6290 6284 Returns 0 on success, 1 if errors are encountered.
6291 6285 """
6292 6286 return hg.verify(repo)
6293 6287
6294 6288 @command('version', [], norepo=True)
6295 6289 def version_(ui):
6296 6290 """output version and copyright information"""
6297 6291 ui.write(_("Mercurial Distributed SCM (version %s)\n")
6298 6292 % util.version())
6299 6293 ui.status(_(
6300 6294 "(see http://mercurial.selenic.com for more information)\n"
6301 6295 "\nCopyright (C) 2005-2014 Matt Mackall and others\n"
6302 6296 "This is free software; see the source for copying conditions. "
6303 6297 "There is NO\nwarranty; "
6304 6298 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
6305 6299 ))
6306 6300
6307 6301 ui.note(_("\nEnabled extensions:\n\n"))
6308 6302 if ui.verbose:
6309 6303 # format names and versions into columns
6310 6304 names = []
6311 6305 vers = []
6312 6306 for name, module in extensions.extensions():
6313 6307 names.append(name)
6314 6308 vers.append(extensions.moduleversion(module))
6315 6309 if names:
6316 6310 maxnamelen = max(len(n) for n in names)
6317 6311 for i, name in enumerate(names):
6318 6312 ui.write(" %-*s %s\n" % (maxnamelen, name, vers[i]))
@@ -1,141 +1,148 b''
1 1 # formatter.py - generic output formatting for mercurial
2 2 #
3 3 # Copyright 2012 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 cPickle
9 from node import hex, short
9 10 from i18n import _
10 11 import encoding, util
11 12
12 13 class baseformatter(object):
13 14 def __init__(self, ui, topic, opts):
14 15 self._ui = ui
15 16 self._topic = topic
16 17 self._style = opts.get("style")
17 18 self._template = opts.get("template")
18 19 self._item = None
20 # function to convert node to string suitable for this output
21 self.hexfunc = hex
19 22 def __nonzero__(self):
20 23 '''return False if we're not doing real templating so we can
21 24 skip extra work'''
22 25 return True
23 26 def _showitem(self):
24 27 '''show a formatted item once all data is collected'''
25 28 pass
26 29 def startitem(self):
27 30 '''begin an item in the format list'''
28 31 if self._item is not None:
29 32 self._showitem()
30 33 self._item = {}
31 34 def data(self, **data):
32 35 '''insert data into item that's not shown in default output'''
33 36 self._item.update(data)
34 37 def write(self, fields, deftext, *fielddata, **opts):
35 38 '''do default text output while assigning data to item'''
36 39 for k, v in zip(fields.split(), fielddata):
37 40 self._item[k] = v
38 41 def condwrite(self, cond, fields, deftext, *fielddata, **opts):
39 42 '''do conditional write (primarily for plain formatter)'''
40 43 for k, v in zip(fields.split(), fielddata):
41 44 self._item[k] = v
42 45 def plain(self, text, **opts):
43 46 '''show raw text for non-templated mode'''
44 47 pass
45 48 def end(self):
46 49 '''end output for the formatter'''
47 50 if self._item is not None:
48 51 self._showitem()
49 52
50 53 class plainformatter(baseformatter):
51 54 '''the default text output scheme'''
52 55 def __init__(self, ui, topic, opts):
53 56 baseformatter.__init__(self, ui, topic, opts)
57 if ui.debugflag:
58 self.hexfunc = hex
59 else:
60 self.hexfunc = short
54 61 def __nonzero__(self):
55 62 return False
56 63 def startitem(self):
57 64 pass
58 65 def data(self, **data):
59 66 pass
60 67 def write(self, fields, deftext, *fielddata, **opts):
61 68 self._ui.write(deftext % fielddata, **opts)
62 69 def condwrite(self, cond, fields, deftext, *fielddata, **opts):
63 70 '''do conditional write'''
64 71 if cond:
65 72 self._ui.write(deftext % fielddata, **opts)
66 73 def plain(self, text, **opts):
67 74 self._ui.write(text, **opts)
68 75 def end(self):
69 76 pass
70 77
71 78 class debugformatter(baseformatter):
72 79 def __init__(self, ui, topic, opts):
73 80 baseformatter.__init__(self, ui, topic, opts)
74 81 self._ui.write("%s = [\n" % self._topic)
75 82 def _showitem(self):
76 83 self._ui.write(" " + repr(self._item) + ",\n")
77 84 def end(self):
78 85 baseformatter.end(self)
79 86 self._ui.write("]\n")
80 87
81 88 class pickleformatter(baseformatter):
82 89 def __init__(self, ui, topic, opts):
83 90 baseformatter.__init__(self, ui, topic, opts)
84 91 self._data = []
85 92 def _showitem(self):
86 93 self._data.append(self._item)
87 94 def end(self):
88 95 baseformatter.end(self)
89 96 self._ui.write(cPickle.dumps(self._data))
90 97
91 98 def _jsonifyobj(v):
92 99 if isinstance(v, tuple):
93 100 return '[' + ', '.join(_jsonifyobj(e) for e in v) + ']'
94 101 elif v is True:
95 102 return 'true'
96 103 elif v is False:
97 104 return 'false'
98 105 elif isinstance(v, (int, float)):
99 106 return str(v)
100 107 else:
101 108 return '"%s"' % encoding.jsonescape(v)
102 109
103 110 class jsonformatter(baseformatter):
104 111 def __init__(self, ui, topic, opts):
105 112 baseformatter.__init__(self, ui, topic, opts)
106 113 self._ui.write("[")
107 114 self._ui._first = True
108 115 def _showitem(self):
109 116 if self._ui._first:
110 117 self._ui._first = False
111 118 else:
112 119 self._ui.write(",")
113 120
114 121 self._ui.write("\n {\n")
115 122 first = True
116 123 for k, v in sorted(self._item.items()):
117 124 if first:
118 125 first = False
119 126 else:
120 127 self._ui.write(",\n")
121 128 self._ui.write(' "%s": %s' % (k, _jsonifyobj(v)))
122 129 self._ui.write("\n }")
123 130 def end(self):
124 131 baseformatter.end(self)
125 132 self._ui.write("\n]\n")
126 133
127 134 def formatter(ui, topic, opts):
128 135 template = opts.get("template", "")
129 136 if template == "json":
130 137 return jsonformatter(ui, topic, opts)
131 138 elif template == "pickle":
132 139 return pickleformatter(ui, topic, opts)
133 140 elif template == "debug":
134 141 return debugformatter(ui, topic, opts)
135 142 elif template != "":
136 143 raise util.Abort(_("custom templates not yet supported"))
137 144 elif ui.configbool('ui', 'formatdebug'):
138 145 return debugformatter(ui, topic, opts)
139 146 elif ui.configbool('ui', 'formatjson'):
140 147 return jsonformatter(ui, topic, opts)
141 148 return plainformatter(ui, topic, opts)
General Comments 0
You need to be logged in to leave comments. Login now