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