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