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