##// END OF EJS Templates
httpservice: move sys.exit() out of serve_forever()...
Martin von Zweigbergk -
r46422:b7b8a153 default
parent child Browse files
Show More
@@ -1,7677 +1,7678 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 errno
11 11 import os
12 12 import re
13 13 import sys
14 14
15 15 from .i18n import _
16 16 from .node import (
17 17 hex,
18 18 nullid,
19 19 nullrev,
20 20 short,
21 21 wdirhex,
22 22 wdirrev,
23 23 )
24 24 from .pycompat import open
25 25 from . import (
26 26 archival,
27 27 bookmarks,
28 28 bundle2,
29 29 bundlecaches,
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 grep as grepmod,
45 45 hbisect,
46 46 help,
47 47 hg,
48 48 logcmdutil,
49 49 merge as mergemod,
50 50 mergestate as mergestatemod,
51 51 narrowspec,
52 52 obsolete,
53 53 obsutil,
54 54 patch,
55 55 phases,
56 56 pycompat,
57 57 rcutil,
58 58 registrar,
59 59 requirements,
60 60 revsetlang,
61 61 rewriteutil,
62 62 scmutil,
63 63 server,
64 64 shelve as shelvemod,
65 65 state as statemod,
66 66 streamclone,
67 67 tags as tagsmod,
68 68 ui as uimod,
69 69 util,
70 70 verify as verifymod,
71 71 vfs as vfsmod,
72 72 wireprotoserver,
73 73 )
74 74 from .utils import (
75 75 dateutil,
76 76 stringutil,
77 77 )
78 78
79 79 table = {}
80 80 table.update(debugcommandsmod.command._table)
81 81
82 82 command = registrar.command(table)
83 83 INTENT_READONLY = registrar.INTENT_READONLY
84 84
85 85 # common command options
86 86
87 87 globalopts = [
88 88 (
89 89 b'R',
90 90 b'repository',
91 91 b'',
92 92 _(b'repository root directory or name of overlay bundle file'),
93 93 _(b'REPO'),
94 94 ),
95 95 (b'', b'cwd', b'', _(b'change working directory'), _(b'DIR')),
96 96 (
97 97 b'y',
98 98 b'noninteractive',
99 99 None,
100 100 _(
101 101 b'do not prompt, automatically pick the first choice for all prompts'
102 102 ),
103 103 ),
104 104 (b'q', b'quiet', None, _(b'suppress output')),
105 105 (b'v', b'verbose', None, _(b'enable additional output')),
106 106 (
107 107 b'',
108 108 b'color',
109 109 b'',
110 110 # i18n: 'always', 'auto', 'never', and 'debug' are keywords
111 111 # and should not be translated
112 112 _(b"when to colorize (boolean, always, auto, never, or debug)"),
113 113 _(b'TYPE'),
114 114 ),
115 115 (
116 116 b'',
117 117 b'config',
118 118 [],
119 119 _(b'set/override config option (use \'section.name=value\')'),
120 120 _(b'CONFIG'),
121 121 ),
122 122 (b'', b'debug', None, _(b'enable debugging output')),
123 123 (b'', b'debugger', None, _(b'start debugger')),
124 124 (
125 125 b'',
126 126 b'encoding',
127 127 encoding.encoding,
128 128 _(b'set the charset encoding'),
129 129 _(b'ENCODE'),
130 130 ),
131 131 (
132 132 b'',
133 133 b'encodingmode',
134 134 encoding.encodingmode,
135 135 _(b'set the charset encoding mode'),
136 136 _(b'MODE'),
137 137 ),
138 138 (b'', b'traceback', None, _(b'always print a traceback on exception')),
139 139 (b'', b'time', None, _(b'time how long the command takes')),
140 140 (b'', b'profile', None, _(b'print command execution profile')),
141 141 (b'', b'version', None, _(b'output version information and exit')),
142 142 (b'h', b'help', None, _(b'display help and exit')),
143 143 (b'', b'hidden', False, _(b'consider hidden changesets')),
144 144 (
145 145 b'',
146 146 b'pager',
147 147 b'auto',
148 148 _(b"when to paginate (boolean, always, auto, or never)"),
149 149 _(b'TYPE'),
150 150 ),
151 151 ]
152 152
153 153 dryrunopts = cmdutil.dryrunopts
154 154 remoteopts = cmdutil.remoteopts
155 155 walkopts = cmdutil.walkopts
156 156 commitopts = cmdutil.commitopts
157 157 commitopts2 = cmdutil.commitopts2
158 158 commitopts3 = cmdutil.commitopts3
159 159 formatteropts = cmdutil.formatteropts
160 160 templateopts = cmdutil.templateopts
161 161 logopts = cmdutil.logopts
162 162 diffopts = cmdutil.diffopts
163 163 diffwsopts = cmdutil.diffwsopts
164 164 diffopts2 = cmdutil.diffopts2
165 165 mergetoolopts = cmdutil.mergetoolopts
166 166 similarityopts = cmdutil.similarityopts
167 167 subrepoopts = cmdutil.subrepoopts
168 168 debugrevlogopts = cmdutil.debugrevlogopts
169 169
170 170 # Commands start here, listed alphabetically
171 171
172 172
173 173 @command(
174 174 b'abort',
175 175 dryrunopts,
176 176 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
177 177 helpbasic=True,
178 178 )
179 179 def abort(ui, repo, **opts):
180 180 """abort an unfinished operation (EXPERIMENTAL)
181 181
182 182 Aborts a multistep operation like graft, histedit, rebase, merge,
183 183 and unshelve if they are in an unfinished state.
184 184
185 185 use --dry-run/-n to dry run the command.
186 186 """
187 187 dryrun = opts.get('dry_run')
188 188 abortstate = cmdutil.getunfinishedstate(repo)
189 189 if not abortstate:
190 190 raise error.Abort(_(b'no operation in progress'))
191 191 if not abortstate.abortfunc:
192 192 raise error.Abort(
193 193 (
194 194 _(b"%s in progress but does not support 'hg abort'")
195 195 % (abortstate._opname)
196 196 ),
197 197 hint=abortstate.hint(),
198 198 )
199 199 if dryrun:
200 200 ui.status(
201 201 _(b'%s in progress, will be aborted\n') % (abortstate._opname)
202 202 )
203 203 return
204 204 return abortstate.abortfunc(ui, repo)
205 205
206 206
207 207 @command(
208 208 b'add',
209 209 walkopts + subrepoopts + dryrunopts,
210 210 _(b'[OPTION]... [FILE]...'),
211 211 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
212 212 helpbasic=True,
213 213 inferrepo=True,
214 214 )
215 215 def add(ui, repo, *pats, **opts):
216 216 """add the specified files on the next commit
217 217
218 218 Schedule files to be version controlled and added to the
219 219 repository.
220 220
221 221 The files will be added to the repository at the next commit. To
222 222 undo an add before that, see :hg:`forget`.
223 223
224 224 If no names are given, add all files to the repository (except
225 225 files matching ``.hgignore``).
226 226
227 227 .. container:: verbose
228 228
229 229 Examples:
230 230
231 231 - New (unknown) files are added
232 232 automatically by :hg:`add`::
233 233
234 234 $ ls
235 235 foo.c
236 236 $ hg status
237 237 ? foo.c
238 238 $ hg add
239 239 adding foo.c
240 240 $ hg status
241 241 A foo.c
242 242
243 243 - Specific files to be added can be specified::
244 244
245 245 $ ls
246 246 bar.c foo.c
247 247 $ hg status
248 248 ? bar.c
249 249 ? foo.c
250 250 $ hg add bar.c
251 251 $ hg status
252 252 A bar.c
253 253 ? foo.c
254 254
255 255 Returns 0 if all files are successfully added.
256 256 """
257 257
258 258 m = scmutil.match(repo[None], pats, pycompat.byteskwargs(opts))
259 259 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
260 260 rejected = cmdutil.add(ui, repo, m, b"", uipathfn, False, **opts)
261 261 return rejected and 1 or 0
262 262
263 263
264 264 @command(
265 265 b'addremove',
266 266 similarityopts + subrepoopts + walkopts + dryrunopts,
267 267 _(b'[OPTION]... [FILE]...'),
268 268 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
269 269 inferrepo=True,
270 270 )
271 271 def addremove(ui, repo, *pats, **opts):
272 272 """add all new files, delete all missing files
273 273
274 274 Add all new files and remove all missing files from the
275 275 repository.
276 276
277 277 Unless names are given, new files are ignored if they match any of
278 278 the patterns in ``.hgignore``. As with add, these changes take
279 279 effect at the next commit.
280 280
281 281 Use the -s/--similarity option to detect renamed files. This
282 282 option takes a percentage between 0 (disabled) and 100 (files must
283 283 be identical) as its parameter. With a parameter greater than 0,
284 284 this compares every removed file with every added file and records
285 285 those similar enough as renames. Detecting renamed files this way
286 286 can be expensive. After using this option, :hg:`status -C` can be
287 287 used to check which files were identified as moved or renamed. If
288 288 not specified, -s/--similarity defaults to 100 and only renames of
289 289 identical files are detected.
290 290
291 291 .. container:: verbose
292 292
293 293 Examples:
294 294
295 295 - A number of files (bar.c and foo.c) are new,
296 296 while foobar.c has been removed (without using :hg:`remove`)
297 297 from the repository::
298 298
299 299 $ ls
300 300 bar.c foo.c
301 301 $ hg status
302 302 ! foobar.c
303 303 ? bar.c
304 304 ? foo.c
305 305 $ hg addremove
306 306 adding bar.c
307 307 adding foo.c
308 308 removing foobar.c
309 309 $ hg status
310 310 A bar.c
311 311 A foo.c
312 312 R foobar.c
313 313
314 314 - A file foobar.c was moved to foo.c without using :hg:`rename`.
315 315 Afterwards, it was edited slightly::
316 316
317 317 $ ls
318 318 foo.c
319 319 $ hg status
320 320 ! foobar.c
321 321 ? foo.c
322 322 $ hg addremove --similarity 90
323 323 removing foobar.c
324 324 adding foo.c
325 325 recording removal of foobar.c as rename to foo.c (94% similar)
326 326 $ hg status -C
327 327 A foo.c
328 328 foobar.c
329 329 R foobar.c
330 330
331 331 Returns 0 if all files are successfully added.
332 332 """
333 333 opts = pycompat.byteskwargs(opts)
334 334 if not opts.get(b'similarity'):
335 335 opts[b'similarity'] = b'100'
336 336 matcher = scmutil.match(repo[None], pats, opts)
337 337 relative = scmutil.anypats(pats, opts)
338 338 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=relative)
339 339 return scmutil.addremove(repo, matcher, b"", uipathfn, opts)
340 340
341 341
342 342 @command(
343 343 b'annotate|blame',
344 344 [
345 345 (b'r', b'rev', b'', _(b'annotate the specified revision'), _(b'REV')),
346 346 (
347 347 b'',
348 348 b'follow',
349 349 None,
350 350 _(b'follow copies/renames and list the filename (DEPRECATED)'),
351 351 ),
352 352 (b'', b'no-follow', None, _(b"don't follow copies and renames")),
353 353 (b'a', b'text', None, _(b'treat all files as text')),
354 354 (b'u', b'user', None, _(b'list the author (long with -v)')),
355 355 (b'f', b'file', None, _(b'list the filename')),
356 356 (b'd', b'date', None, _(b'list the date (short with -q)')),
357 357 (b'n', b'number', None, _(b'list the revision number (default)')),
358 358 (b'c', b'changeset', None, _(b'list the changeset')),
359 359 (
360 360 b'l',
361 361 b'line-number',
362 362 None,
363 363 _(b'show line number at the first appearance'),
364 364 ),
365 365 (
366 366 b'',
367 367 b'skip',
368 368 [],
369 369 _(b'revset to not display (EXPERIMENTAL)'),
370 370 _(b'REV'),
371 371 ),
372 372 ]
373 373 + diffwsopts
374 374 + walkopts
375 375 + formatteropts,
376 376 _(b'[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
377 377 helpcategory=command.CATEGORY_FILE_CONTENTS,
378 378 helpbasic=True,
379 379 inferrepo=True,
380 380 )
381 381 def annotate(ui, repo, *pats, **opts):
382 382 """show changeset information by line for each file
383 383
384 384 List changes in files, showing the revision id responsible for
385 385 each line.
386 386
387 387 This command is useful for discovering when a change was made and
388 388 by whom.
389 389
390 390 If you include --file, --user, or --date, the revision number is
391 391 suppressed unless you also include --number.
392 392
393 393 Without the -a/--text option, annotate will avoid processing files
394 394 it detects as binary. With -a, annotate will annotate the file
395 395 anyway, although the results will probably be neither useful
396 396 nor desirable.
397 397
398 398 .. container:: verbose
399 399
400 400 Template:
401 401
402 402 The following keywords are supported in addition to the common template
403 403 keywords and functions. See also :hg:`help templates`.
404 404
405 405 :lines: List of lines with annotation data.
406 406 :path: String. Repository-absolute path of the specified file.
407 407
408 408 And each entry of ``{lines}`` provides the following sub-keywords in
409 409 addition to ``{date}``, ``{node}``, ``{rev}``, ``{user}``, etc.
410 410
411 411 :line: String. Line content.
412 412 :lineno: Integer. Line number at that revision.
413 413 :path: String. Repository-absolute path of the file at that revision.
414 414
415 415 See :hg:`help templates.operators` for the list expansion syntax.
416 416
417 417 Returns 0 on success.
418 418 """
419 419 opts = pycompat.byteskwargs(opts)
420 420 if not pats:
421 421 raise error.Abort(_(b'at least one filename or pattern is required'))
422 422
423 423 if opts.get(b'follow'):
424 424 # --follow is deprecated and now just an alias for -f/--file
425 425 # to mimic the behavior of Mercurial before version 1.5
426 426 opts[b'file'] = True
427 427
428 428 if (
429 429 not opts.get(b'user')
430 430 and not opts.get(b'changeset')
431 431 and not opts.get(b'date')
432 432 and not opts.get(b'file')
433 433 ):
434 434 opts[b'number'] = True
435 435
436 436 linenumber = opts.get(b'line_number') is not None
437 437 if (
438 438 linenumber
439 439 and (not opts.get(b'changeset'))
440 440 and (not opts.get(b'number'))
441 441 ):
442 442 raise error.Abort(_(b'at least one of -n/-c is required for -l'))
443 443
444 444 rev = opts.get(b'rev')
445 445 if rev:
446 446 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
447 447 ctx = scmutil.revsingle(repo, rev)
448 448
449 449 ui.pager(b'annotate')
450 450 rootfm = ui.formatter(b'annotate', opts)
451 451 if ui.debugflag:
452 452 shorthex = pycompat.identity
453 453 else:
454 454
455 455 def shorthex(h):
456 456 return h[:12]
457 457
458 458 if ui.quiet:
459 459 datefunc = dateutil.shortdate
460 460 else:
461 461 datefunc = dateutil.datestr
462 462 if ctx.rev() is None:
463 463 if opts.get(b'changeset'):
464 464 # omit "+" suffix which is appended to node hex
465 465 def formatrev(rev):
466 466 if rev == wdirrev:
467 467 return b'%d' % ctx.p1().rev()
468 468 else:
469 469 return b'%d' % rev
470 470
471 471 else:
472 472
473 473 def formatrev(rev):
474 474 if rev == wdirrev:
475 475 return b'%d+' % ctx.p1().rev()
476 476 else:
477 477 return b'%d ' % rev
478 478
479 479 def formathex(h):
480 480 if h == wdirhex:
481 481 return b'%s+' % shorthex(hex(ctx.p1().node()))
482 482 else:
483 483 return b'%s ' % shorthex(h)
484 484
485 485 else:
486 486 formatrev = b'%d'.__mod__
487 487 formathex = shorthex
488 488
489 489 opmap = [
490 490 (b'user', b' ', lambda x: x.fctx.user(), ui.shortuser),
491 491 (b'rev', b' ', lambda x: scmutil.intrev(x.fctx), formatrev),
492 492 (b'node', b' ', lambda x: hex(scmutil.binnode(x.fctx)), formathex),
493 493 (b'date', b' ', lambda x: x.fctx.date(), util.cachefunc(datefunc)),
494 494 (b'path', b' ', lambda x: x.fctx.path(), pycompat.bytestr),
495 495 (b'lineno', b':', lambda x: x.lineno, pycompat.bytestr),
496 496 ]
497 497 opnamemap = {
498 498 b'rev': b'number',
499 499 b'node': b'changeset',
500 500 b'path': b'file',
501 501 b'lineno': b'line_number',
502 502 }
503 503
504 504 if rootfm.isplain():
505 505
506 506 def makefunc(get, fmt):
507 507 return lambda x: fmt(get(x))
508 508
509 509 else:
510 510
511 511 def makefunc(get, fmt):
512 512 return get
513 513
514 514 datahint = rootfm.datahint()
515 515 funcmap = [
516 516 (makefunc(get, fmt), sep)
517 517 for fn, sep, get, fmt in opmap
518 518 if opts.get(opnamemap.get(fn, fn)) or fn in datahint
519 519 ]
520 520 funcmap[0] = (funcmap[0][0], b'') # no separator in front of first column
521 521 fields = b' '.join(
522 522 fn
523 523 for fn, sep, get, fmt in opmap
524 524 if opts.get(opnamemap.get(fn, fn)) or fn in datahint
525 525 )
526 526
527 527 def bad(x, y):
528 528 raise error.Abort(b"%s: %s" % (x, y))
529 529
530 530 m = scmutil.match(ctx, pats, opts, badfn=bad)
531 531
532 532 follow = not opts.get(b'no_follow')
533 533 diffopts = patch.difffeatureopts(
534 534 ui, opts, section=b'annotate', whitespace=True
535 535 )
536 536 skiprevs = opts.get(b'skip')
537 537 if skiprevs:
538 538 skiprevs = scmutil.revrange(repo, skiprevs)
539 539
540 540 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
541 541 for abs in ctx.walk(m):
542 542 fctx = ctx[abs]
543 543 rootfm.startitem()
544 544 rootfm.data(path=abs)
545 545 if not opts.get(b'text') and fctx.isbinary():
546 546 rootfm.plain(_(b"%s: binary file\n") % uipathfn(abs))
547 547 continue
548 548
549 549 fm = rootfm.nested(b'lines', tmpl=b'{rev}: {line}')
550 550 lines = fctx.annotate(
551 551 follow=follow, skiprevs=skiprevs, diffopts=diffopts
552 552 )
553 553 if not lines:
554 554 fm.end()
555 555 continue
556 556 formats = []
557 557 pieces = []
558 558
559 559 for f, sep in funcmap:
560 560 l = [f(n) for n in lines]
561 561 if fm.isplain():
562 562 sizes = [encoding.colwidth(x) for x in l]
563 563 ml = max(sizes)
564 564 formats.append([sep + b' ' * (ml - w) + b'%s' for w in sizes])
565 565 else:
566 566 formats.append([b'%s'] * len(l))
567 567 pieces.append(l)
568 568
569 569 for f, p, n in zip(zip(*formats), zip(*pieces), lines):
570 570 fm.startitem()
571 571 fm.context(fctx=n.fctx)
572 572 fm.write(fields, b"".join(f), *p)
573 573 if n.skip:
574 574 fmt = b"* %s"
575 575 else:
576 576 fmt = b": %s"
577 577 fm.write(b'line', fmt, n.text)
578 578
579 579 if not lines[-1].text.endswith(b'\n'):
580 580 fm.plain(b'\n')
581 581 fm.end()
582 582
583 583 rootfm.end()
584 584
585 585
586 586 @command(
587 587 b'archive',
588 588 [
589 589 (b'', b'no-decode', None, _(b'do not pass files through decoders')),
590 590 (
591 591 b'p',
592 592 b'prefix',
593 593 b'',
594 594 _(b'directory prefix for files in archive'),
595 595 _(b'PREFIX'),
596 596 ),
597 597 (b'r', b'rev', b'', _(b'revision to distribute'), _(b'REV')),
598 598 (b't', b'type', b'', _(b'type of distribution to create'), _(b'TYPE')),
599 599 ]
600 600 + subrepoopts
601 601 + walkopts,
602 602 _(b'[OPTION]... DEST'),
603 603 helpcategory=command.CATEGORY_IMPORT_EXPORT,
604 604 )
605 605 def archive(ui, repo, dest, **opts):
606 606 '''create an unversioned archive of a repository revision
607 607
608 608 By default, the revision used is the parent of the working
609 609 directory; use -r/--rev to specify a different revision.
610 610
611 611 The archive type is automatically detected based on file
612 612 extension (to override, use -t/--type).
613 613
614 614 .. container:: verbose
615 615
616 616 Examples:
617 617
618 618 - create a zip file containing the 1.0 release::
619 619
620 620 hg archive -r 1.0 project-1.0.zip
621 621
622 622 - create a tarball excluding .hg files::
623 623
624 624 hg archive project.tar.gz -X ".hg*"
625 625
626 626 Valid types are:
627 627
628 628 :``files``: a directory full of files (default)
629 629 :``tar``: tar archive, uncompressed
630 630 :``tbz2``: tar archive, compressed using bzip2
631 631 :``tgz``: tar archive, compressed using gzip
632 632 :``txz``: tar archive, compressed using lzma (only in Python 3)
633 633 :``uzip``: zip archive, uncompressed
634 634 :``zip``: zip archive, compressed using deflate
635 635
636 636 The exact name of the destination archive or directory is given
637 637 using a format string; see :hg:`help export` for details.
638 638
639 639 Each member added to an archive file has a directory prefix
640 640 prepended. Use -p/--prefix to specify a format string for the
641 641 prefix. The default is the basename of the archive, with suffixes
642 642 removed.
643 643
644 644 Returns 0 on success.
645 645 '''
646 646
647 647 opts = pycompat.byteskwargs(opts)
648 648 rev = opts.get(b'rev')
649 649 if rev:
650 650 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
651 651 ctx = scmutil.revsingle(repo, rev)
652 652 if not ctx:
653 653 raise error.Abort(_(b'no working directory: please specify a revision'))
654 654 node = ctx.node()
655 655 dest = cmdutil.makefilename(ctx, dest)
656 656 if os.path.realpath(dest) == repo.root:
657 657 raise error.Abort(_(b'repository root cannot be destination'))
658 658
659 659 kind = opts.get(b'type') or archival.guesskind(dest) or b'files'
660 660 prefix = opts.get(b'prefix')
661 661
662 662 if dest == b'-':
663 663 if kind == b'files':
664 664 raise error.Abort(_(b'cannot archive plain files to stdout'))
665 665 dest = cmdutil.makefileobj(ctx, dest)
666 666 if not prefix:
667 667 prefix = os.path.basename(repo.root) + b'-%h'
668 668
669 669 prefix = cmdutil.makefilename(ctx, prefix)
670 670 match = scmutil.match(ctx, [], opts)
671 671 archival.archive(
672 672 repo,
673 673 dest,
674 674 node,
675 675 kind,
676 676 not opts.get(b'no_decode'),
677 677 match,
678 678 prefix,
679 679 subrepos=opts.get(b'subrepos'),
680 680 )
681 681
682 682
683 683 @command(
684 684 b'backout',
685 685 [
686 686 (
687 687 b'',
688 688 b'merge',
689 689 None,
690 690 _(b'merge with old dirstate parent after backout'),
691 691 ),
692 692 (
693 693 b'',
694 694 b'commit',
695 695 None,
696 696 _(b'commit if no conflicts were encountered (DEPRECATED)'),
697 697 ),
698 698 (b'', b'no-commit', None, _(b'do not commit')),
699 699 (
700 700 b'',
701 701 b'parent',
702 702 b'',
703 703 _(b'parent to choose when backing out merge (DEPRECATED)'),
704 704 _(b'REV'),
705 705 ),
706 706 (b'r', b'rev', b'', _(b'revision to backout'), _(b'REV')),
707 707 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
708 708 ]
709 709 + mergetoolopts
710 710 + walkopts
711 711 + commitopts
712 712 + commitopts2,
713 713 _(b'[OPTION]... [-r] REV'),
714 714 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
715 715 )
716 716 def backout(ui, repo, node=None, rev=None, **opts):
717 717 '''reverse effect of earlier changeset
718 718
719 719 Prepare a new changeset with the effect of REV undone in the
720 720 current working directory. If no conflicts were encountered,
721 721 it will be committed immediately.
722 722
723 723 If REV is the parent of the working directory, then this new changeset
724 724 is committed automatically (unless --no-commit is specified).
725 725
726 726 .. note::
727 727
728 728 :hg:`backout` cannot be used to fix either an unwanted or
729 729 incorrect merge.
730 730
731 731 .. container:: verbose
732 732
733 733 Examples:
734 734
735 735 - Reverse the effect of the parent of the working directory.
736 736 This backout will be committed immediately::
737 737
738 738 hg backout -r .
739 739
740 740 - Reverse the effect of previous bad revision 23::
741 741
742 742 hg backout -r 23
743 743
744 744 - Reverse the effect of previous bad revision 23 and
745 745 leave changes uncommitted::
746 746
747 747 hg backout -r 23 --no-commit
748 748 hg commit -m "Backout revision 23"
749 749
750 750 By default, the pending changeset will have one parent,
751 751 maintaining a linear history. With --merge, the pending
752 752 changeset will instead have two parents: the old parent of the
753 753 working directory and a new child of REV that simply undoes REV.
754 754
755 755 Before version 1.7, the behavior without --merge was equivalent
756 756 to specifying --merge followed by :hg:`update --clean .` to
757 757 cancel the merge and leave the child of REV as a head to be
758 758 merged separately.
759 759
760 760 See :hg:`help dates` for a list of formats valid for -d/--date.
761 761
762 762 See :hg:`help revert` for a way to restore files to the state
763 763 of another revision.
764 764
765 765 Returns 0 on success, 1 if nothing to backout or there are unresolved
766 766 files.
767 767 '''
768 768 with repo.wlock(), repo.lock():
769 769 return _dobackout(ui, repo, node, rev, **opts)
770 770
771 771
772 772 def _dobackout(ui, repo, node=None, rev=None, **opts):
773 773 cmdutil.check_incompatible_arguments(opts, 'no_commit', ['commit', 'merge'])
774 774 opts = pycompat.byteskwargs(opts)
775 775
776 776 if rev and node:
777 777 raise error.Abort(_(b"please specify just one revision"))
778 778
779 779 if not rev:
780 780 rev = node
781 781
782 782 if not rev:
783 783 raise error.Abort(_(b"please specify a revision to backout"))
784 784
785 785 date = opts.get(b'date')
786 786 if date:
787 787 opts[b'date'] = dateutil.parsedate(date)
788 788
789 789 cmdutil.checkunfinished(repo)
790 790 cmdutil.bailifchanged(repo)
791 791 ctx = scmutil.revsingle(repo, rev)
792 792 node = ctx.node()
793 793
794 794 op1, op2 = repo.dirstate.parents()
795 795 if not repo.changelog.isancestor(node, op1):
796 796 raise error.Abort(_(b'cannot backout change that is not an ancestor'))
797 797
798 798 p1, p2 = repo.changelog.parents(node)
799 799 if p1 == nullid:
800 800 raise error.Abort(_(b'cannot backout a change with no parents'))
801 801 if p2 != nullid:
802 802 if not opts.get(b'parent'):
803 803 raise error.Abort(_(b'cannot backout a merge changeset'))
804 804 p = repo.lookup(opts[b'parent'])
805 805 if p not in (p1, p2):
806 806 raise error.Abort(
807 807 _(b'%s is not a parent of %s') % (short(p), short(node))
808 808 )
809 809 parent = p
810 810 else:
811 811 if opts.get(b'parent'):
812 812 raise error.Abort(_(b'cannot use --parent on non-merge changeset'))
813 813 parent = p1
814 814
815 815 # the backout should appear on the same branch
816 816 branch = repo.dirstate.branch()
817 817 bheads = repo.branchheads(branch)
818 818 rctx = scmutil.revsingle(repo, hex(parent))
819 819 if not opts.get(b'merge') and op1 != node:
820 820 with dirstateguard.dirstateguard(repo, b'backout'):
821 821 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
822 822 with ui.configoverride(overrides, b'backout'):
823 823 stats = mergemod.back_out(ctx, parent=repo[parent])
824 824 repo.setparents(op1, op2)
825 825 hg._showstats(repo, stats)
826 826 if stats.unresolvedcount:
827 827 repo.ui.status(
828 828 _(b"use 'hg resolve' to retry unresolved file merges\n")
829 829 )
830 830 return 1
831 831 else:
832 832 hg.clean(repo, node, show_stats=False)
833 833 repo.dirstate.setbranch(branch)
834 834 cmdutil.revert(ui, repo, rctx)
835 835
836 836 if opts.get(b'no_commit'):
837 837 msg = _(b"changeset %s backed out, don't forget to commit.\n")
838 838 ui.status(msg % short(node))
839 839 return 0
840 840
841 841 def commitfunc(ui, repo, message, match, opts):
842 842 editform = b'backout'
843 843 e = cmdutil.getcommiteditor(
844 844 editform=editform, **pycompat.strkwargs(opts)
845 845 )
846 846 if not message:
847 847 # we don't translate commit messages
848 848 message = b"Backed out changeset %s" % short(node)
849 849 e = cmdutil.getcommiteditor(edit=True, editform=editform)
850 850 return repo.commit(
851 851 message, opts.get(b'user'), opts.get(b'date'), match, editor=e
852 852 )
853 853
854 854 # save to detect changes
855 855 tip = repo.changelog.tip()
856 856
857 857 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
858 858 if not newnode:
859 859 ui.status(_(b"nothing changed\n"))
860 860 return 1
861 861 cmdutil.commitstatus(repo, newnode, branch, bheads, tip)
862 862
863 863 def nice(node):
864 864 return b'%d:%s' % (repo.changelog.rev(node), short(node))
865 865
866 866 ui.status(
867 867 _(b'changeset %s backs out changeset %s\n')
868 868 % (nice(newnode), nice(node))
869 869 )
870 870 if opts.get(b'merge') and op1 != node:
871 871 hg.clean(repo, op1, show_stats=False)
872 872 ui.status(_(b'merging with changeset %s\n') % nice(newnode))
873 873 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
874 874 with ui.configoverride(overrides, b'backout'):
875 875 return hg.merge(repo[b'tip'])
876 876 return 0
877 877
878 878
879 879 @command(
880 880 b'bisect',
881 881 [
882 882 (b'r', b'reset', False, _(b'reset bisect state')),
883 883 (b'g', b'good', False, _(b'mark changeset good')),
884 884 (b'b', b'bad', False, _(b'mark changeset bad')),
885 885 (b's', b'skip', False, _(b'skip testing changeset')),
886 886 (b'e', b'extend', False, _(b'extend the bisect range')),
887 887 (
888 888 b'c',
889 889 b'command',
890 890 b'',
891 891 _(b'use command to check changeset state'),
892 892 _(b'CMD'),
893 893 ),
894 894 (b'U', b'noupdate', False, _(b'do not update to target')),
895 895 ],
896 896 _(b"[-gbsr] [-U] [-c CMD] [REV]"),
897 897 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
898 898 )
899 899 def bisect(
900 900 ui,
901 901 repo,
902 902 rev=None,
903 903 extra=None,
904 904 command=None,
905 905 reset=None,
906 906 good=None,
907 907 bad=None,
908 908 skip=None,
909 909 extend=None,
910 910 noupdate=None,
911 911 ):
912 912 """subdivision search of changesets
913 913
914 914 This command helps to find changesets which introduce problems. To
915 915 use, mark the earliest changeset you know exhibits the problem as
916 916 bad, then mark the latest changeset which is free from the problem
917 917 as good. Bisect will update your working directory to a revision
918 918 for testing (unless the -U/--noupdate option is specified). Once
919 919 you have performed tests, mark the working directory as good or
920 920 bad, and bisect will either update to another candidate changeset
921 921 or announce that it has found the bad revision.
922 922
923 923 As a shortcut, you can also use the revision argument to mark a
924 924 revision as good or bad without checking it out first.
925 925
926 926 If you supply a command, it will be used for automatic bisection.
927 927 The environment variable HG_NODE will contain the ID of the
928 928 changeset being tested. The exit status of the command will be
929 929 used to mark revisions as good or bad: status 0 means good, 125
930 930 means to skip the revision, 127 (command not found) will abort the
931 931 bisection, and any other non-zero exit status means the revision
932 932 is bad.
933 933
934 934 .. container:: verbose
935 935
936 936 Some examples:
937 937
938 938 - start a bisection with known bad revision 34, and good revision 12::
939 939
940 940 hg bisect --bad 34
941 941 hg bisect --good 12
942 942
943 943 - advance the current bisection by marking current revision as good or
944 944 bad::
945 945
946 946 hg bisect --good
947 947 hg bisect --bad
948 948
949 949 - mark the current revision, or a known revision, to be skipped (e.g. if
950 950 that revision is not usable because of another issue)::
951 951
952 952 hg bisect --skip
953 953 hg bisect --skip 23
954 954
955 955 - skip all revisions that do not touch directories ``foo`` or ``bar``::
956 956
957 957 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
958 958
959 959 - forget the current bisection::
960 960
961 961 hg bisect --reset
962 962
963 963 - use 'make && make tests' to automatically find the first broken
964 964 revision::
965 965
966 966 hg bisect --reset
967 967 hg bisect --bad 34
968 968 hg bisect --good 12
969 969 hg bisect --command "make && make tests"
970 970
971 971 - see all changesets whose states are already known in the current
972 972 bisection::
973 973
974 974 hg log -r "bisect(pruned)"
975 975
976 976 - see the changeset currently being bisected (especially useful
977 977 if running with -U/--noupdate)::
978 978
979 979 hg log -r "bisect(current)"
980 980
981 981 - see all changesets that took part in the current bisection::
982 982
983 983 hg log -r "bisect(range)"
984 984
985 985 - you can even get a nice graph::
986 986
987 987 hg log --graph -r "bisect(range)"
988 988
989 989 See :hg:`help revisions.bisect` for more about the `bisect()` predicate.
990 990
991 991 Returns 0 on success.
992 992 """
993 993 # backward compatibility
994 994 if rev in b"good bad reset init".split():
995 995 ui.warn(_(b"(use of 'hg bisect <cmd>' is deprecated)\n"))
996 996 cmd, rev, extra = rev, extra, None
997 997 if cmd == b"good":
998 998 good = True
999 999 elif cmd == b"bad":
1000 1000 bad = True
1001 1001 else:
1002 1002 reset = True
1003 1003 elif extra:
1004 1004 raise error.Abort(_(b'incompatible arguments'))
1005 1005
1006 1006 incompatibles = {
1007 1007 b'--bad': bad,
1008 1008 b'--command': bool(command),
1009 1009 b'--extend': extend,
1010 1010 b'--good': good,
1011 1011 b'--reset': reset,
1012 1012 b'--skip': skip,
1013 1013 }
1014 1014
1015 1015 enabled = [x for x in incompatibles if incompatibles[x]]
1016 1016
1017 1017 if len(enabled) > 1:
1018 1018 raise error.Abort(
1019 1019 _(b'%s and %s are incompatible') % tuple(sorted(enabled)[0:2])
1020 1020 )
1021 1021
1022 1022 if reset:
1023 1023 hbisect.resetstate(repo)
1024 1024 return
1025 1025
1026 1026 state = hbisect.load_state(repo)
1027 1027
1028 1028 # update state
1029 1029 if good or bad or skip:
1030 1030 if rev:
1031 1031 nodes = [repo[i].node() for i in scmutil.revrange(repo, [rev])]
1032 1032 else:
1033 1033 nodes = [repo.lookup(b'.')]
1034 1034 if good:
1035 1035 state[b'good'] += nodes
1036 1036 elif bad:
1037 1037 state[b'bad'] += nodes
1038 1038 elif skip:
1039 1039 state[b'skip'] += nodes
1040 1040 hbisect.save_state(repo, state)
1041 1041 if not (state[b'good'] and state[b'bad']):
1042 1042 return
1043 1043
1044 1044 def mayupdate(repo, node, show_stats=True):
1045 1045 """common used update sequence"""
1046 1046 if noupdate:
1047 1047 return
1048 1048 cmdutil.checkunfinished(repo)
1049 1049 cmdutil.bailifchanged(repo)
1050 1050 return hg.clean(repo, node, show_stats=show_stats)
1051 1051
1052 1052 displayer = logcmdutil.changesetdisplayer(ui, repo, {})
1053 1053
1054 1054 if command:
1055 1055 changesets = 1
1056 1056 if noupdate:
1057 1057 try:
1058 1058 node = state[b'current'][0]
1059 1059 except LookupError:
1060 1060 raise error.Abort(
1061 1061 _(
1062 1062 b'current bisect revision is unknown - '
1063 1063 b'start a new bisect to fix'
1064 1064 )
1065 1065 )
1066 1066 else:
1067 1067 node, p2 = repo.dirstate.parents()
1068 1068 if p2 != nullid:
1069 1069 raise error.Abort(_(b'current bisect revision is a merge'))
1070 1070 if rev:
1071 1071 node = repo[scmutil.revsingle(repo, rev, node)].node()
1072 1072 with hbisect.restore_state(repo, state, node):
1073 1073 while changesets:
1074 1074 # update state
1075 1075 state[b'current'] = [node]
1076 1076 hbisect.save_state(repo, state)
1077 1077 status = ui.system(
1078 1078 command,
1079 1079 environ={b'HG_NODE': hex(node)},
1080 1080 blockedtag=b'bisect_check',
1081 1081 )
1082 1082 if status == 125:
1083 1083 transition = b"skip"
1084 1084 elif status == 0:
1085 1085 transition = b"good"
1086 1086 # status < 0 means process was killed
1087 1087 elif status == 127:
1088 1088 raise error.Abort(_(b"failed to execute %s") % command)
1089 1089 elif status < 0:
1090 1090 raise error.Abort(_(b"%s killed") % command)
1091 1091 else:
1092 1092 transition = b"bad"
1093 1093 state[transition].append(node)
1094 1094 ctx = repo[node]
1095 1095 ui.status(
1096 1096 _(b'changeset %d:%s: %s\n') % (ctx.rev(), ctx, transition)
1097 1097 )
1098 1098 hbisect.checkstate(state)
1099 1099 # bisect
1100 1100 nodes, changesets, bgood = hbisect.bisect(repo, state)
1101 1101 # update to next check
1102 1102 node = nodes[0]
1103 1103 mayupdate(repo, node, show_stats=False)
1104 1104 hbisect.printresult(ui, repo, state, displayer, nodes, bgood)
1105 1105 return
1106 1106
1107 1107 hbisect.checkstate(state)
1108 1108
1109 1109 # actually bisect
1110 1110 nodes, changesets, good = hbisect.bisect(repo, state)
1111 1111 if extend:
1112 1112 if not changesets:
1113 1113 extendnode = hbisect.extendrange(repo, state, nodes, good)
1114 1114 if extendnode is not None:
1115 1115 ui.write(
1116 1116 _(b"Extending search to changeset %d:%s\n")
1117 1117 % (extendnode.rev(), extendnode)
1118 1118 )
1119 1119 state[b'current'] = [extendnode.node()]
1120 1120 hbisect.save_state(repo, state)
1121 1121 return mayupdate(repo, extendnode.node())
1122 1122 raise error.Abort(_(b"nothing to extend"))
1123 1123
1124 1124 if changesets == 0:
1125 1125 hbisect.printresult(ui, repo, state, displayer, nodes, good)
1126 1126 else:
1127 1127 assert len(nodes) == 1 # only a single node can be tested next
1128 1128 node = nodes[0]
1129 1129 # compute the approximate number of remaining tests
1130 1130 tests, size = 0, 2
1131 1131 while size <= changesets:
1132 1132 tests, size = tests + 1, size * 2
1133 1133 rev = repo.changelog.rev(node)
1134 1134 ui.write(
1135 1135 _(
1136 1136 b"Testing changeset %d:%s "
1137 1137 b"(%d changesets remaining, ~%d tests)\n"
1138 1138 )
1139 1139 % (rev, short(node), changesets, tests)
1140 1140 )
1141 1141 state[b'current'] = [node]
1142 1142 hbisect.save_state(repo, state)
1143 1143 return mayupdate(repo, node)
1144 1144
1145 1145
1146 1146 @command(
1147 1147 b'bookmarks|bookmark',
1148 1148 [
1149 1149 (b'f', b'force', False, _(b'force')),
1150 1150 (b'r', b'rev', b'', _(b'revision for bookmark action'), _(b'REV')),
1151 1151 (b'd', b'delete', False, _(b'delete a given bookmark')),
1152 1152 (b'm', b'rename', b'', _(b'rename a given bookmark'), _(b'OLD')),
1153 1153 (b'i', b'inactive', False, _(b'mark a bookmark inactive')),
1154 1154 (b'l', b'list', False, _(b'list existing bookmarks')),
1155 1155 ]
1156 1156 + formatteropts,
1157 1157 _(b'hg bookmarks [OPTIONS]... [NAME]...'),
1158 1158 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
1159 1159 )
1160 1160 def bookmark(ui, repo, *names, **opts):
1161 1161 '''create a new bookmark or list existing bookmarks
1162 1162
1163 1163 Bookmarks are labels on changesets to help track lines of development.
1164 1164 Bookmarks are unversioned and can be moved, renamed and deleted.
1165 1165 Deleting or moving a bookmark has no effect on the associated changesets.
1166 1166
1167 1167 Creating or updating to a bookmark causes it to be marked as 'active'.
1168 1168 The active bookmark is indicated with a '*'.
1169 1169 When a commit is made, the active bookmark will advance to the new commit.
1170 1170 A plain :hg:`update` will also advance an active bookmark, if possible.
1171 1171 Updating away from a bookmark will cause it to be deactivated.
1172 1172
1173 1173 Bookmarks can be pushed and pulled between repositories (see
1174 1174 :hg:`help push` and :hg:`help pull`). If a shared bookmark has
1175 1175 diverged, a new 'divergent bookmark' of the form 'name@path' will
1176 1176 be created. Using :hg:`merge` will resolve the divergence.
1177 1177
1178 1178 Specifying bookmark as '.' to -m/-d/-l options is equivalent to specifying
1179 1179 the active bookmark's name.
1180 1180
1181 1181 A bookmark named '@' has the special property that :hg:`clone` will
1182 1182 check it out by default if it exists.
1183 1183
1184 1184 .. container:: verbose
1185 1185
1186 1186 Template:
1187 1187
1188 1188 The following keywords are supported in addition to the common template
1189 1189 keywords and functions such as ``{bookmark}``. See also
1190 1190 :hg:`help templates`.
1191 1191
1192 1192 :active: Boolean. True if the bookmark is active.
1193 1193
1194 1194 Examples:
1195 1195
1196 1196 - create an active bookmark for a new line of development::
1197 1197
1198 1198 hg book new-feature
1199 1199
1200 1200 - create an inactive bookmark as a place marker::
1201 1201
1202 1202 hg book -i reviewed
1203 1203
1204 1204 - create an inactive bookmark on another changeset::
1205 1205
1206 1206 hg book -r .^ tested
1207 1207
1208 1208 - rename bookmark turkey to dinner::
1209 1209
1210 1210 hg book -m turkey dinner
1211 1211
1212 1212 - move the '@' bookmark from another branch::
1213 1213
1214 1214 hg book -f @
1215 1215
1216 1216 - print only the active bookmark name::
1217 1217
1218 1218 hg book -ql .
1219 1219 '''
1220 1220 opts = pycompat.byteskwargs(opts)
1221 1221 force = opts.get(b'force')
1222 1222 rev = opts.get(b'rev')
1223 1223 inactive = opts.get(b'inactive') # meaning add/rename to inactive bookmark
1224 1224
1225 1225 action = cmdutil.check_at_most_one_arg(opts, b'delete', b'rename', b'list')
1226 1226 if action:
1227 1227 cmdutil.check_incompatible_arguments(opts, action, [b'rev'])
1228 1228 elif names or rev:
1229 1229 action = b'add'
1230 1230 elif inactive:
1231 1231 action = b'inactive' # meaning deactivate
1232 1232 else:
1233 1233 action = b'list'
1234 1234
1235 1235 cmdutil.check_incompatible_arguments(
1236 1236 opts, b'inactive', [b'delete', b'list']
1237 1237 )
1238 1238 if not names and action in {b'add', b'delete'}:
1239 1239 raise error.Abort(_(b"bookmark name required"))
1240 1240
1241 1241 if action in {b'add', b'delete', b'rename', b'inactive'}:
1242 1242 with repo.wlock(), repo.lock(), repo.transaction(b'bookmark') as tr:
1243 1243 if action == b'delete':
1244 1244 names = pycompat.maplist(repo._bookmarks.expandname, names)
1245 1245 bookmarks.delete(repo, tr, names)
1246 1246 elif action == b'rename':
1247 1247 if not names:
1248 1248 raise error.Abort(_(b"new bookmark name required"))
1249 1249 elif len(names) > 1:
1250 1250 raise error.Abort(_(b"only one new bookmark name allowed"))
1251 1251 oldname = repo._bookmarks.expandname(opts[b'rename'])
1252 1252 bookmarks.rename(repo, tr, oldname, names[0], force, inactive)
1253 1253 elif action == b'add':
1254 1254 bookmarks.addbookmarks(repo, tr, names, rev, force, inactive)
1255 1255 elif action == b'inactive':
1256 1256 if len(repo._bookmarks) == 0:
1257 1257 ui.status(_(b"no bookmarks set\n"))
1258 1258 elif not repo._activebookmark:
1259 1259 ui.status(_(b"no active bookmark\n"))
1260 1260 else:
1261 1261 bookmarks.deactivate(repo)
1262 1262 elif action == b'list':
1263 1263 names = pycompat.maplist(repo._bookmarks.expandname, names)
1264 1264 with ui.formatter(b'bookmarks', opts) as fm:
1265 1265 bookmarks.printbookmarks(ui, repo, fm, names)
1266 1266 else:
1267 1267 raise error.ProgrammingError(b'invalid action: %s' % action)
1268 1268
1269 1269
1270 1270 @command(
1271 1271 b'branch',
1272 1272 [
1273 1273 (
1274 1274 b'f',
1275 1275 b'force',
1276 1276 None,
1277 1277 _(b'set branch name even if it shadows an existing branch'),
1278 1278 ),
1279 1279 (b'C', b'clean', None, _(b'reset branch name to parent branch name')),
1280 1280 (
1281 1281 b'r',
1282 1282 b'rev',
1283 1283 [],
1284 1284 _(b'change branches of the given revs (EXPERIMENTAL)'),
1285 1285 ),
1286 1286 ],
1287 1287 _(b'[-fC] [NAME]'),
1288 1288 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
1289 1289 )
1290 1290 def branch(ui, repo, label=None, **opts):
1291 1291 """set or show the current branch name
1292 1292
1293 1293 .. note::
1294 1294
1295 1295 Branch names are permanent and global. Use :hg:`bookmark` to create a
1296 1296 light-weight bookmark instead. See :hg:`help glossary` for more
1297 1297 information about named branches and bookmarks.
1298 1298
1299 1299 With no argument, show the current branch name. With one argument,
1300 1300 set the working directory branch name (the branch will not exist
1301 1301 in the repository until the next commit). Standard practice
1302 1302 recommends that primary development take place on the 'default'
1303 1303 branch.
1304 1304
1305 1305 Unless -f/--force is specified, branch will not let you set a
1306 1306 branch name that already exists.
1307 1307
1308 1308 Use -C/--clean to reset the working directory branch to that of
1309 1309 the parent of the working directory, negating a previous branch
1310 1310 change.
1311 1311
1312 1312 Use the command :hg:`update` to switch to an existing branch. Use
1313 1313 :hg:`commit --close-branch` to mark this branch head as closed.
1314 1314 When all heads of a branch are closed, the branch will be
1315 1315 considered closed.
1316 1316
1317 1317 Returns 0 on success.
1318 1318 """
1319 1319 opts = pycompat.byteskwargs(opts)
1320 1320 revs = opts.get(b'rev')
1321 1321 if label:
1322 1322 label = label.strip()
1323 1323
1324 1324 if not opts.get(b'clean') and not label:
1325 1325 if revs:
1326 1326 raise error.Abort(_(b"no branch name specified for the revisions"))
1327 1327 ui.write(b"%s\n" % repo.dirstate.branch())
1328 1328 return
1329 1329
1330 1330 with repo.wlock():
1331 1331 if opts.get(b'clean'):
1332 1332 label = repo[b'.'].branch()
1333 1333 repo.dirstate.setbranch(label)
1334 1334 ui.status(_(b'reset working directory to branch %s\n') % label)
1335 1335 elif label:
1336 1336
1337 1337 scmutil.checknewlabel(repo, label, b'branch')
1338 1338 if revs:
1339 1339 return cmdutil.changebranch(ui, repo, revs, label, opts)
1340 1340
1341 1341 if not opts.get(b'force') and label in repo.branchmap():
1342 1342 if label not in [p.branch() for p in repo[None].parents()]:
1343 1343 raise error.Abort(
1344 1344 _(b'a branch of the same name already exists'),
1345 1345 # i18n: "it" refers to an existing branch
1346 1346 hint=_(b"use 'hg update' to switch to it"),
1347 1347 )
1348 1348
1349 1349 repo.dirstate.setbranch(label)
1350 1350 ui.status(_(b'marked working directory as branch %s\n') % label)
1351 1351
1352 1352 # find any open named branches aside from default
1353 1353 for n, h, t, c in repo.branchmap().iterbranches():
1354 1354 if n != b"default" and not c:
1355 1355 return 0
1356 1356 ui.status(
1357 1357 _(
1358 1358 b'(branches are permanent and global, '
1359 1359 b'did you want a bookmark?)\n'
1360 1360 )
1361 1361 )
1362 1362
1363 1363
1364 1364 @command(
1365 1365 b'branches',
1366 1366 [
1367 1367 (
1368 1368 b'a',
1369 1369 b'active',
1370 1370 False,
1371 1371 _(b'show only branches that have unmerged heads (DEPRECATED)'),
1372 1372 ),
1373 1373 (b'c', b'closed', False, _(b'show normal and closed branches')),
1374 1374 (b'r', b'rev', [], _(b'show branch name(s) of the given rev')),
1375 1375 ]
1376 1376 + formatteropts,
1377 1377 _(b'[-c]'),
1378 1378 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
1379 1379 intents={INTENT_READONLY},
1380 1380 )
1381 1381 def branches(ui, repo, active=False, closed=False, **opts):
1382 1382 """list repository named branches
1383 1383
1384 1384 List the repository's named branches, indicating which ones are
1385 1385 inactive. If -c/--closed is specified, also list branches which have
1386 1386 been marked closed (see :hg:`commit --close-branch`).
1387 1387
1388 1388 Use the command :hg:`update` to switch to an existing branch.
1389 1389
1390 1390 .. container:: verbose
1391 1391
1392 1392 Template:
1393 1393
1394 1394 The following keywords are supported in addition to the common template
1395 1395 keywords and functions such as ``{branch}``. See also
1396 1396 :hg:`help templates`.
1397 1397
1398 1398 :active: Boolean. True if the branch is active.
1399 1399 :closed: Boolean. True if the branch is closed.
1400 1400 :current: Boolean. True if it is the current branch.
1401 1401
1402 1402 Returns 0.
1403 1403 """
1404 1404
1405 1405 opts = pycompat.byteskwargs(opts)
1406 1406 revs = opts.get(b'rev')
1407 1407 selectedbranches = None
1408 1408 if revs:
1409 1409 revs = scmutil.revrange(repo, revs)
1410 1410 getbi = repo.revbranchcache().branchinfo
1411 1411 selectedbranches = {getbi(r)[0] for r in revs}
1412 1412
1413 1413 ui.pager(b'branches')
1414 1414 fm = ui.formatter(b'branches', opts)
1415 1415 hexfunc = fm.hexfunc
1416 1416
1417 1417 allheads = set(repo.heads())
1418 1418 branches = []
1419 1419 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1420 1420 if selectedbranches is not None and tag not in selectedbranches:
1421 1421 continue
1422 1422 isactive = False
1423 1423 if not isclosed:
1424 1424 openheads = set(repo.branchmap().iteropen(heads))
1425 1425 isactive = bool(openheads & allheads)
1426 1426 branches.append((tag, repo[tip], isactive, not isclosed))
1427 1427 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]), reverse=True)
1428 1428
1429 1429 for tag, ctx, isactive, isopen in branches:
1430 1430 if active and not isactive:
1431 1431 continue
1432 1432 if isactive:
1433 1433 label = b'branches.active'
1434 1434 notice = b''
1435 1435 elif not isopen:
1436 1436 if not closed:
1437 1437 continue
1438 1438 label = b'branches.closed'
1439 1439 notice = _(b' (closed)')
1440 1440 else:
1441 1441 label = b'branches.inactive'
1442 1442 notice = _(b' (inactive)')
1443 1443 current = tag == repo.dirstate.branch()
1444 1444 if current:
1445 1445 label = b'branches.current'
1446 1446
1447 1447 fm.startitem()
1448 1448 fm.write(b'branch', b'%s', tag, label=label)
1449 1449 rev = ctx.rev()
1450 1450 padsize = max(31 - len(b"%d" % rev) - encoding.colwidth(tag), 0)
1451 1451 fmt = b' ' * padsize + b' %d:%s'
1452 1452 fm.condwrite(
1453 1453 not ui.quiet,
1454 1454 b'rev node',
1455 1455 fmt,
1456 1456 rev,
1457 1457 hexfunc(ctx.node()),
1458 1458 label=b'log.changeset changeset.%s' % ctx.phasestr(),
1459 1459 )
1460 1460 fm.context(ctx=ctx)
1461 1461 fm.data(active=isactive, closed=not isopen, current=current)
1462 1462 if not ui.quiet:
1463 1463 fm.plain(notice)
1464 1464 fm.plain(b'\n')
1465 1465 fm.end()
1466 1466
1467 1467
1468 1468 @command(
1469 1469 b'bundle',
1470 1470 [
1471 1471 (
1472 1472 b'f',
1473 1473 b'force',
1474 1474 None,
1475 1475 _(b'run even when the destination is unrelated'),
1476 1476 ),
1477 1477 (
1478 1478 b'r',
1479 1479 b'rev',
1480 1480 [],
1481 1481 _(b'a changeset intended to be added to the destination'),
1482 1482 _(b'REV'),
1483 1483 ),
1484 1484 (
1485 1485 b'b',
1486 1486 b'branch',
1487 1487 [],
1488 1488 _(b'a specific branch you would like to bundle'),
1489 1489 _(b'BRANCH'),
1490 1490 ),
1491 1491 (
1492 1492 b'',
1493 1493 b'base',
1494 1494 [],
1495 1495 _(b'a base changeset assumed to be available at the destination'),
1496 1496 _(b'REV'),
1497 1497 ),
1498 1498 (b'a', b'all', None, _(b'bundle all changesets in the repository')),
1499 1499 (
1500 1500 b't',
1501 1501 b'type',
1502 1502 b'bzip2',
1503 1503 _(b'bundle compression type to use'),
1504 1504 _(b'TYPE'),
1505 1505 ),
1506 1506 ]
1507 1507 + remoteopts,
1508 1508 _(b'[-f] [-t BUNDLESPEC] [-a] [-r REV]... [--base REV]... FILE [DEST]'),
1509 1509 helpcategory=command.CATEGORY_IMPORT_EXPORT,
1510 1510 )
1511 1511 def bundle(ui, repo, fname, dest=None, **opts):
1512 1512 """create a bundle file
1513 1513
1514 1514 Generate a bundle file containing data to be transferred to another
1515 1515 repository.
1516 1516
1517 1517 To create a bundle containing all changesets, use -a/--all
1518 1518 (or --base null). Otherwise, hg assumes the destination will have
1519 1519 all the nodes you specify with --base parameters. Otherwise, hg
1520 1520 will assume the repository has all the nodes in destination, or
1521 1521 default-push/default if no destination is specified, where destination
1522 1522 is the repository you provide through DEST option.
1523 1523
1524 1524 You can change bundle format with the -t/--type option. See
1525 1525 :hg:`help bundlespec` for documentation on this format. By default,
1526 1526 the most appropriate format is used and compression defaults to
1527 1527 bzip2.
1528 1528
1529 1529 The bundle file can then be transferred using conventional means
1530 1530 and applied to another repository with the unbundle or pull
1531 1531 command. This is useful when direct push and pull are not
1532 1532 available or when exporting an entire repository is undesirable.
1533 1533
1534 1534 Applying bundles preserves all changeset contents including
1535 1535 permissions, copy/rename information, and revision history.
1536 1536
1537 1537 Returns 0 on success, 1 if no changes found.
1538 1538 """
1539 1539 opts = pycompat.byteskwargs(opts)
1540 1540 revs = None
1541 1541 if b'rev' in opts:
1542 1542 revstrings = opts[b'rev']
1543 1543 revs = scmutil.revrange(repo, revstrings)
1544 1544 if revstrings and not revs:
1545 1545 raise error.Abort(_(b'no commits to bundle'))
1546 1546
1547 1547 bundletype = opts.get(b'type', b'bzip2').lower()
1548 1548 try:
1549 1549 bundlespec = bundlecaches.parsebundlespec(
1550 1550 repo, bundletype, strict=False
1551 1551 )
1552 1552 except error.UnsupportedBundleSpecification as e:
1553 1553 raise error.Abort(
1554 1554 pycompat.bytestr(e),
1555 1555 hint=_(b"see 'hg help bundlespec' for supported values for --type"),
1556 1556 )
1557 1557 cgversion = bundlespec.contentopts[b"cg.version"]
1558 1558
1559 1559 # Packed bundles are a pseudo bundle format for now.
1560 1560 if cgversion == b's1':
1561 1561 raise error.Abort(
1562 1562 _(b'packed bundles cannot be produced by "hg bundle"'),
1563 1563 hint=_(b"use 'hg debugcreatestreamclonebundle'"),
1564 1564 )
1565 1565
1566 1566 if opts.get(b'all'):
1567 1567 if dest:
1568 1568 raise error.Abort(
1569 1569 _(b"--all is incompatible with specifying a destination")
1570 1570 )
1571 1571 if opts.get(b'base'):
1572 1572 ui.warn(_(b"ignoring --base because --all was specified\n"))
1573 1573 base = [nullrev]
1574 1574 else:
1575 1575 base = scmutil.revrange(repo, opts.get(b'base'))
1576 1576 if cgversion not in changegroup.supportedoutgoingversions(repo):
1577 1577 raise error.Abort(
1578 1578 _(b"repository does not support bundle version %s") % cgversion
1579 1579 )
1580 1580
1581 1581 if base:
1582 1582 if dest:
1583 1583 raise error.Abort(
1584 1584 _(b"--base is incompatible with specifying a destination")
1585 1585 )
1586 1586 common = [repo[rev].node() for rev in base]
1587 1587 heads = [repo[r].node() for r in revs] if revs else None
1588 1588 outgoing = discovery.outgoing(repo, common, heads)
1589 1589 else:
1590 1590 dest = ui.expandpath(dest or b'default-push', dest or b'default')
1591 1591 dest, branches = hg.parseurl(dest, opts.get(b'branch'))
1592 1592 other = hg.peer(repo, opts, dest)
1593 1593 revs = [repo[r].hex() for r in revs]
1594 1594 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1595 1595 heads = revs and pycompat.maplist(repo.lookup, revs) or revs
1596 1596 outgoing = discovery.findcommonoutgoing(
1597 1597 repo,
1598 1598 other,
1599 1599 onlyheads=heads,
1600 1600 force=opts.get(b'force'),
1601 1601 portable=True,
1602 1602 )
1603 1603
1604 1604 if not outgoing.missing:
1605 1605 scmutil.nochangesfound(ui, repo, not base and outgoing.excluded)
1606 1606 return 1
1607 1607
1608 1608 if cgversion == b'01': # bundle1
1609 1609 bversion = b'HG10' + bundlespec.wirecompression
1610 1610 bcompression = None
1611 1611 elif cgversion in (b'02', b'03'):
1612 1612 bversion = b'HG20'
1613 1613 bcompression = bundlespec.wirecompression
1614 1614 else:
1615 1615 raise error.ProgrammingError(
1616 1616 b'bundle: unexpected changegroup version %s' % cgversion
1617 1617 )
1618 1618
1619 1619 # TODO compression options should be derived from bundlespec parsing.
1620 1620 # This is a temporary hack to allow adjusting bundle compression
1621 1621 # level without a) formalizing the bundlespec changes to declare it
1622 1622 # b) introducing a command flag.
1623 1623 compopts = {}
1624 1624 complevel = ui.configint(
1625 1625 b'experimental', b'bundlecomplevel.' + bundlespec.compression
1626 1626 )
1627 1627 if complevel is None:
1628 1628 complevel = ui.configint(b'experimental', b'bundlecomplevel')
1629 1629 if complevel is not None:
1630 1630 compopts[b'level'] = complevel
1631 1631
1632 1632 # Allow overriding the bundling of obsmarker in phases through
1633 1633 # configuration while we don't have a bundle version that include them
1634 1634 if repo.ui.configbool(b'experimental', b'evolution.bundle-obsmarker'):
1635 1635 bundlespec.contentopts[b'obsolescence'] = True
1636 1636 if repo.ui.configbool(b'experimental', b'bundle-phases'):
1637 1637 bundlespec.contentopts[b'phases'] = True
1638 1638
1639 1639 bundle2.writenewbundle(
1640 1640 ui,
1641 1641 repo,
1642 1642 b'bundle',
1643 1643 fname,
1644 1644 bversion,
1645 1645 outgoing,
1646 1646 bundlespec.contentopts,
1647 1647 compression=bcompression,
1648 1648 compopts=compopts,
1649 1649 )
1650 1650
1651 1651
1652 1652 @command(
1653 1653 b'cat',
1654 1654 [
1655 1655 (
1656 1656 b'o',
1657 1657 b'output',
1658 1658 b'',
1659 1659 _(b'print output to file with formatted name'),
1660 1660 _(b'FORMAT'),
1661 1661 ),
1662 1662 (b'r', b'rev', b'', _(b'print the given revision'), _(b'REV')),
1663 1663 (b'', b'decode', None, _(b'apply any matching decode filter')),
1664 1664 ]
1665 1665 + walkopts
1666 1666 + formatteropts,
1667 1667 _(b'[OPTION]... FILE...'),
1668 1668 helpcategory=command.CATEGORY_FILE_CONTENTS,
1669 1669 inferrepo=True,
1670 1670 intents={INTENT_READONLY},
1671 1671 )
1672 1672 def cat(ui, repo, file1, *pats, **opts):
1673 1673 """output the current or given revision of files
1674 1674
1675 1675 Print the specified files as they were at the given revision. If
1676 1676 no revision is given, the parent of the working directory is used.
1677 1677
1678 1678 Output may be to a file, in which case the name of the file is
1679 1679 given using a template string. See :hg:`help templates`. In addition
1680 1680 to the common template keywords, the following formatting rules are
1681 1681 supported:
1682 1682
1683 1683 :``%%``: literal "%" character
1684 1684 :``%s``: basename of file being printed
1685 1685 :``%d``: dirname of file being printed, or '.' if in repository root
1686 1686 :``%p``: root-relative path name of file being printed
1687 1687 :``%H``: changeset hash (40 hexadecimal digits)
1688 1688 :``%R``: changeset revision number
1689 1689 :``%h``: short-form changeset hash (12 hexadecimal digits)
1690 1690 :``%r``: zero-padded changeset revision number
1691 1691 :``%b``: basename of the exporting repository
1692 1692 :``\\``: literal "\\" character
1693 1693
1694 1694 .. container:: verbose
1695 1695
1696 1696 Template:
1697 1697
1698 1698 The following keywords are supported in addition to the common template
1699 1699 keywords and functions. See also :hg:`help templates`.
1700 1700
1701 1701 :data: String. File content.
1702 1702 :path: String. Repository-absolute path of the file.
1703 1703
1704 1704 Returns 0 on success.
1705 1705 """
1706 1706 opts = pycompat.byteskwargs(opts)
1707 1707 rev = opts.get(b'rev')
1708 1708 if rev:
1709 1709 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
1710 1710 ctx = scmutil.revsingle(repo, rev)
1711 1711 m = scmutil.match(ctx, (file1,) + pats, opts)
1712 1712 fntemplate = opts.pop(b'output', b'')
1713 1713 if cmdutil.isstdiofilename(fntemplate):
1714 1714 fntemplate = b''
1715 1715
1716 1716 if fntemplate:
1717 1717 fm = formatter.nullformatter(ui, b'cat', opts)
1718 1718 else:
1719 1719 ui.pager(b'cat')
1720 1720 fm = ui.formatter(b'cat', opts)
1721 1721 with fm:
1722 1722 return cmdutil.cat(
1723 1723 ui, repo, ctx, m, fm, fntemplate, b'', **pycompat.strkwargs(opts)
1724 1724 )
1725 1725
1726 1726
1727 1727 @command(
1728 1728 b'clone',
1729 1729 [
1730 1730 (
1731 1731 b'U',
1732 1732 b'noupdate',
1733 1733 None,
1734 1734 _(
1735 1735 b'the clone will include an empty working '
1736 1736 b'directory (only a repository)'
1737 1737 ),
1738 1738 ),
1739 1739 (
1740 1740 b'u',
1741 1741 b'updaterev',
1742 1742 b'',
1743 1743 _(b'revision, tag, or branch to check out'),
1744 1744 _(b'REV'),
1745 1745 ),
1746 1746 (
1747 1747 b'r',
1748 1748 b'rev',
1749 1749 [],
1750 1750 _(
1751 1751 b'do not clone everything, but include this changeset'
1752 1752 b' and its ancestors'
1753 1753 ),
1754 1754 _(b'REV'),
1755 1755 ),
1756 1756 (
1757 1757 b'b',
1758 1758 b'branch',
1759 1759 [],
1760 1760 _(
1761 1761 b'do not clone everything, but include this branch\'s'
1762 1762 b' changesets and their ancestors'
1763 1763 ),
1764 1764 _(b'BRANCH'),
1765 1765 ),
1766 1766 (b'', b'pull', None, _(b'use pull protocol to copy metadata')),
1767 1767 (b'', b'uncompressed', None, _(b'an alias to --stream (DEPRECATED)')),
1768 1768 (b'', b'stream', None, _(b'clone with minimal data processing')),
1769 1769 ]
1770 1770 + remoteopts,
1771 1771 _(b'[OPTION]... SOURCE [DEST]'),
1772 1772 helpcategory=command.CATEGORY_REPO_CREATION,
1773 1773 helpbasic=True,
1774 1774 norepo=True,
1775 1775 )
1776 1776 def clone(ui, source, dest=None, **opts):
1777 1777 """make a copy of an existing repository
1778 1778
1779 1779 Create a copy of an existing repository in a new directory.
1780 1780
1781 1781 If no destination directory name is specified, it defaults to the
1782 1782 basename of the source.
1783 1783
1784 1784 The location of the source is added to the new repository's
1785 1785 ``.hg/hgrc`` file, as the default to be used for future pulls.
1786 1786
1787 1787 Only local paths and ``ssh://`` URLs are supported as
1788 1788 destinations. For ``ssh://`` destinations, no working directory or
1789 1789 ``.hg/hgrc`` will be created on the remote side.
1790 1790
1791 1791 If the source repository has a bookmark called '@' set, that
1792 1792 revision will be checked out in the new repository by default.
1793 1793
1794 1794 To check out a particular version, use -u/--update, or
1795 1795 -U/--noupdate to create a clone with no working directory.
1796 1796
1797 1797 To pull only a subset of changesets, specify one or more revisions
1798 1798 identifiers with -r/--rev or branches with -b/--branch. The
1799 1799 resulting clone will contain only the specified changesets and
1800 1800 their ancestors. These options (or 'clone src#rev dest') imply
1801 1801 --pull, even for local source repositories.
1802 1802
1803 1803 In normal clone mode, the remote normalizes repository data into a common
1804 1804 exchange format and the receiving end translates this data into its local
1805 1805 storage format. --stream activates a different clone mode that essentially
1806 1806 copies repository files from the remote with minimal data processing. This
1807 1807 significantly reduces the CPU cost of a clone both remotely and locally.
1808 1808 However, it often increases the transferred data size by 30-40%. This can
1809 1809 result in substantially faster clones where I/O throughput is plentiful,
1810 1810 especially for larger repositories. A side-effect of --stream clones is
1811 1811 that storage settings and requirements on the remote are applied locally:
1812 1812 a modern client may inherit legacy or inefficient storage used by the
1813 1813 remote or a legacy Mercurial client may not be able to clone from a
1814 1814 modern Mercurial remote.
1815 1815
1816 1816 .. note::
1817 1817
1818 1818 Specifying a tag will include the tagged changeset but not the
1819 1819 changeset containing the tag.
1820 1820
1821 1821 .. container:: verbose
1822 1822
1823 1823 For efficiency, hardlinks are used for cloning whenever the
1824 1824 source and destination are on the same filesystem (note this
1825 1825 applies only to the repository data, not to the working
1826 1826 directory). Some filesystems, such as AFS, implement hardlinking
1827 1827 incorrectly, but do not report errors. In these cases, use the
1828 1828 --pull option to avoid hardlinking.
1829 1829
1830 1830 Mercurial will update the working directory to the first applicable
1831 1831 revision from this list:
1832 1832
1833 1833 a) null if -U or the source repository has no changesets
1834 1834 b) if -u . and the source repository is local, the first parent of
1835 1835 the source repository's working directory
1836 1836 c) the changeset specified with -u (if a branch name, this means the
1837 1837 latest head of that branch)
1838 1838 d) the changeset specified with -r
1839 1839 e) the tipmost head specified with -b
1840 1840 f) the tipmost head specified with the url#branch source syntax
1841 1841 g) the revision marked with the '@' bookmark, if present
1842 1842 h) the tipmost head of the default branch
1843 1843 i) tip
1844 1844
1845 1845 When cloning from servers that support it, Mercurial may fetch
1846 1846 pre-generated data from a server-advertised URL or inline from the
1847 1847 same stream. When this is done, hooks operating on incoming changesets
1848 1848 and changegroups may fire more than once, once for each pre-generated
1849 1849 bundle and as well as for any additional remaining data. In addition,
1850 1850 if an error occurs, the repository may be rolled back to a partial
1851 1851 clone. This behavior may change in future releases.
1852 1852 See :hg:`help -e clonebundles` for more.
1853 1853
1854 1854 Examples:
1855 1855
1856 1856 - clone a remote repository to a new directory named hg/::
1857 1857
1858 1858 hg clone https://www.mercurial-scm.org/repo/hg/
1859 1859
1860 1860 - create a lightweight local clone::
1861 1861
1862 1862 hg clone project/ project-feature/
1863 1863
1864 1864 - clone from an absolute path on an ssh server (note double-slash)::
1865 1865
1866 1866 hg clone ssh://user@server//home/projects/alpha/
1867 1867
1868 1868 - do a streaming clone while checking out a specified version::
1869 1869
1870 1870 hg clone --stream http://server/repo -u 1.5
1871 1871
1872 1872 - create a repository without changesets after a particular revision::
1873 1873
1874 1874 hg clone -r 04e544 experimental/ good/
1875 1875
1876 1876 - clone (and track) a particular named branch::
1877 1877
1878 1878 hg clone https://www.mercurial-scm.org/repo/hg/#stable
1879 1879
1880 1880 See :hg:`help urls` for details on specifying URLs.
1881 1881
1882 1882 Returns 0 on success.
1883 1883 """
1884 1884 opts = pycompat.byteskwargs(opts)
1885 1885 cmdutil.check_at_most_one_arg(opts, b'noupdate', b'updaterev')
1886 1886
1887 1887 # --include/--exclude can come from narrow or sparse.
1888 1888 includepats, excludepats = None, None
1889 1889
1890 1890 # hg.clone() differentiates between None and an empty set. So make sure
1891 1891 # patterns are sets if narrow is requested without patterns.
1892 1892 if opts.get(b'narrow'):
1893 1893 includepats = set()
1894 1894 excludepats = set()
1895 1895
1896 1896 if opts.get(b'include'):
1897 1897 includepats = narrowspec.parsepatterns(opts.get(b'include'))
1898 1898 if opts.get(b'exclude'):
1899 1899 excludepats = narrowspec.parsepatterns(opts.get(b'exclude'))
1900 1900
1901 1901 r = hg.clone(
1902 1902 ui,
1903 1903 opts,
1904 1904 source,
1905 1905 dest,
1906 1906 pull=opts.get(b'pull'),
1907 1907 stream=opts.get(b'stream') or opts.get(b'uncompressed'),
1908 1908 revs=opts.get(b'rev'),
1909 1909 update=opts.get(b'updaterev') or not opts.get(b'noupdate'),
1910 1910 branch=opts.get(b'branch'),
1911 1911 shareopts=opts.get(b'shareopts'),
1912 1912 storeincludepats=includepats,
1913 1913 storeexcludepats=excludepats,
1914 1914 depth=opts.get(b'depth') or None,
1915 1915 )
1916 1916
1917 1917 return r is None
1918 1918
1919 1919
1920 1920 @command(
1921 1921 b'commit|ci',
1922 1922 [
1923 1923 (
1924 1924 b'A',
1925 1925 b'addremove',
1926 1926 None,
1927 1927 _(b'mark new/missing files as added/removed before committing'),
1928 1928 ),
1929 1929 (b'', b'close-branch', None, _(b'mark a branch head as closed')),
1930 1930 (b'', b'amend', None, _(b'amend the parent of the working directory')),
1931 1931 (b's', b'secret', None, _(b'use the secret phase for committing')),
1932 1932 (b'e', b'edit', None, _(b'invoke editor on commit messages')),
1933 1933 (
1934 1934 b'',
1935 1935 b'force-close-branch',
1936 1936 None,
1937 1937 _(b'forcibly close branch from a non-head changeset (ADVANCED)'),
1938 1938 ),
1939 1939 (b'i', b'interactive', None, _(b'use interactive mode')),
1940 1940 ]
1941 1941 + walkopts
1942 1942 + commitopts
1943 1943 + commitopts2
1944 1944 + subrepoopts,
1945 1945 _(b'[OPTION]... [FILE]...'),
1946 1946 helpcategory=command.CATEGORY_COMMITTING,
1947 1947 helpbasic=True,
1948 1948 inferrepo=True,
1949 1949 )
1950 1950 def commit(ui, repo, *pats, **opts):
1951 1951 """commit the specified files or all outstanding changes
1952 1952
1953 1953 Commit changes to the given files into the repository. Unlike a
1954 1954 centralized SCM, this operation is a local operation. See
1955 1955 :hg:`push` for a way to actively distribute your changes.
1956 1956
1957 1957 If a list of files is omitted, all changes reported by :hg:`status`
1958 1958 will be committed.
1959 1959
1960 1960 If you are committing the result of a merge, do not provide any
1961 1961 filenames or -I/-X filters.
1962 1962
1963 1963 If no commit message is specified, Mercurial starts your
1964 1964 configured editor where you can enter a message. In case your
1965 1965 commit fails, you will find a backup of your message in
1966 1966 ``.hg/last-message.txt``.
1967 1967
1968 1968 The --close-branch flag can be used to mark the current branch
1969 1969 head closed. When all heads of a branch are closed, the branch
1970 1970 will be considered closed and no longer listed.
1971 1971
1972 1972 The --amend flag can be used to amend the parent of the
1973 1973 working directory with a new commit that contains the changes
1974 1974 in the parent in addition to those currently reported by :hg:`status`,
1975 1975 if there are any. The old commit is stored in a backup bundle in
1976 1976 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1977 1977 on how to restore it).
1978 1978
1979 1979 Message, user and date are taken from the amended commit unless
1980 1980 specified. When a message isn't specified on the command line,
1981 1981 the editor will open with the message of the amended commit.
1982 1982
1983 1983 It is not possible to amend public changesets (see :hg:`help phases`)
1984 1984 or changesets that have children.
1985 1985
1986 1986 See :hg:`help dates` for a list of formats valid for -d/--date.
1987 1987
1988 1988 Returns 0 on success, 1 if nothing changed.
1989 1989
1990 1990 .. container:: verbose
1991 1991
1992 1992 Examples:
1993 1993
1994 1994 - commit all files ending in .py::
1995 1995
1996 1996 hg commit --include "set:**.py"
1997 1997
1998 1998 - commit all non-binary files::
1999 1999
2000 2000 hg commit --exclude "set:binary()"
2001 2001
2002 2002 - amend the current commit and set the date to now::
2003 2003
2004 2004 hg commit --amend --date now
2005 2005 """
2006 2006 with repo.wlock(), repo.lock():
2007 2007 return _docommit(ui, repo, *pats, **opts)
2008 2008
2009 2009
2010 2010 def _docommit(ui, repo, *pats, **opts):
2011 2011 if opts.get('interactive'):
2012 2012 opts.pop('interactive')
2013 2013 ret = cmdutil.dorecord(
2014 2014 ui, repo, commit, None, False, cmdutil.recordfilter, *pats, **opts
2015 2015 )
2016 2016 # ret can be 0 (no changes to record) or the value returned by
2017 2017 # commit(), 1 if nothing changed or None on success.
2018 2018 return 1 if ret == 0 else ret
2019 2019
2020 2020 opts = pycompat.byteskwargs(opts)
2021 2021 if opts.get(b'subrepos'):
2022 2022 cmdutil.check_incompatible_arguments(opts, b'subrepos', [b'amend'])
2023 2023 # Let --subrepos on the command line override config setting.
2024 2024 ui.setconfig(b'ui', b'commitsubrepos', True, b'commit')
2025 2025
2026 2026 cmdutil.checkunfinished(repo, commit=True)
2027 2027
2028 2028 branch = repo[None].branch()
2029 2029 bheads = repo.branchheads(branch)
2030 2030 tip = repo.changelog.tip()
2031 2031
2032 2032 extra = {}
2033 2033 if opts.get(b'close_branch') or opts.get(b'force_close_branch'):
2034 2034 extra[b'close'] = b'1'
2035 2035
2036 2036 if repo[b'.'].closesbranch():
2037 2037 raise error.Abort(
2038 2038 _(b'current revision is already a branch closing head')
2039 2039 )
2040 2040 elif not bheads:
2041 2041 raise error.Abort(_(b'branch "%s" has no heads to close') % branch)
2042 2042 elif (
2043 2043 branch == repo[b'.'].branch()
2044 2044 and repo[b'.'].node() not in bheads
2045 2045 and not opts.get(b'force_close_branch')
2046 2046 ):
2047 2047 hint = _(
2048 2048 b'use --force-close-branch to close branch from a non-head'
2049 2049 b' changeset'
2050 2050 )
2051 2051 raise error.Abort(_(b'can only close branch heads'), hint=hint)
2052 2052 elif opts.get(b'amend'):
2053 2053 if (
2054 2054 repo[b'.'].p1().branch() != branch
2055 2055 and repo[b'.'].p2().branch() != branch
2056 2056 ):
2057 2057 raise error.Abort(_(b'can only close branch heads'))
2058 2058
2059 2059 if opts.get(b'amend'):
2060 2060 if ui.configbool(b'ui', b'commitsubrepos'):
2061 2061 raise error.Abort(_(b'cannot amend with ui.commitsubrepos enabled'))
2062 2062
2063 2063 old = repo[b'.']
2064 2064 rewriteutil.precheck(repo, [old.rev()], b'amend')
2065 2065
2066 2066 # Currently histedit gets confused if an amend happens while histedit
2067 2067 # is in progress. Since we have a checkunfinished command, we are
2068 2068 # temporarily honoring it.
2069 2069 #
2070 2070 # Note: eventually this guard will be removed. Please do not expect
2071 2071 # this behavior to remain.
2072 2072 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
2073 2073 cmdutil.checkunfinished(repo)
2074 2074
2075 2075 node = cmdutil.amend(ui, repo, old, extra, pats, opts)
2076 2076 if node == old.node():
2077 2077 ui.status(_(b"nothing changed\n"))
2078 2078 return 1
2079 2079 else:
2080 2080
2081 2081 def commitfunc(ui, repo, message, match, opts):
2082 2082 overrides = {}
2083 2083 if opts.get(b'secret'):
2084 2084 overrides[(b'phases', b'new-commit')] = b'secret'
2085 2085
2086 2086 baseui = repo.baseui
2087 2087 with baseui.configoverride(overrides, b'commit'):
2088 2088 with ui.configoverride(overrides, b'commit'):
2089 2089 editform = cmdutil.mergeeditform(
2090 2090 repo[None], b'commit.normal'
2091 2091 )
2092 2092 editor = cmdutil.getcommiteditor(
2093 2093 editform=editform, **pycompat.strkwargs(opts)
2094 2094 )
2095 2095 return repo.commit(
2096 2096 message,
2097 2097 opts.get(b'user'),
2098 2098 opts.get(b'date'),
2099 2099 match,
2100 2100 editor=editor,
2101 2101 extra=extra,
2102 2102 )
2103 2103
2104 2104 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
2105 2105
2106 2106 if not node:
2107 2107 stat = cmdutil.postcommitstatus(repo, pats, opts)
2108 2108 if stat.deleted:
2109 2109 ui.status(
2110 2110 _(
2111 2111 b"nothing changed (%d missing files, see "
2112 2112 b"'hg status')\n"
2113 2113 )
2114 2114 % len(stat.deleted)
2115 2115 )
2116 2116 else:
2117 2117 ui.status(_(b"nothing changed\n"))
2118 2118 return 1
2119 2119
2120 2120 cmdutil.commitstatus(repo, node, branch, bheads, tip, opts)
2121 2121
2122 2122 if not ui.quiet and ui.configbool(b'commands', b'commit.post-status'):
2123 2123 status(
2124 2124 ui,
2125 2125 repo,
2126 2126 modified=True,
2127 2127 added=True,
2128 2128 removed=True,
2129 2129 deleted=True,
2130 2130 unknown=True,
2131 2131 subrepos=opts.get(b'subrepos'),
2132 2132 )
2133 2133
2134 2134
2135 2135 @command(
2136 2136 b'config|showconfig|debugconfig',
2137 2137 [
2138 2138 (b'u', b'untrusted', None, _(b'show untrusted configuration options')),
2139 2139 (b'e', b'edit', None, _(b'edit user config')),
2140 2140 (b'l', b'local', None, _(b'edit repository config')),
2141 2141 (
2142 2142 b'',
2143 2143 b'shared',
2144 2144 None,
2145 2145 _(b'edit shared source repository config (EXPERIMENTAL)'),
2146 2146 ),
2147 2147 (b'', b'non-shared', None, _(b'edit non shared config (EXPERIMENTAL)')),
2148 2148 (b'g', b'global', None, _(b'edit global config')),
2149 2149 ]
2150 2150 + formatteropts,
2151 2151 _(b'[-u] [NAME]...'),
2152 2152 helpcategory=command.CATEGORY_HELP,
2153 2153 optionalrepo=True,
2154 2154 intents={INTENT_READONLY},
2155 2155 )
2156 2156 def config(ui, repo, *values, **opts):
2157 2157 """show combined config settings from all hgrc files
2158 2158
2159 2159 With no arguments, print names and values of all config items.
2160 2160
2161 2161 With one argument of the form section.name, print just the value
2162 2162 of that config item.
2163 2163
2164 2164 With multiple arguments, print names and values of all config
2165 2165 items with matching section names or section.names.
2166 2166
2167 2167 With --edit, start an editor on the user-level config file. With
2168 2168 --global, edit the system-wide config file. With --local, edit the
2169 2169 repository-level config file.
2170 2170
2171 2171 With --debug, the source (filename and line number) is printed
2172 2172 for each config item.
2173 2173
2174 2174 See :hg:`help config` for more information about config files.
2175 2175
2176 2176 .. container:: verbose
2177 2177
2178 2178 --non-shared flag is used to edit `.hg/hgrc-not-shared` config file.
2179 2179 This file is not shared across shares when in share-safe mode.
2180 2180
2181 2181 Template:
2182 2182
2183 2183 The following keywords are supported. See also :hg:`help templates`.
2184 2184
2185 2185 :name: String. Config name.
2186 2186 :source: String. Filename and line number where the item is defined.
2187 2187 :value: String. Config value.
2188 2188
2189 2189 The --shared flag can be used to edit the config file of shared source
2190 2190 repository. It only works when you have shared using the experimental
2191 2191 share safe feature.
2192 2192
2193 2193 Returns 0 on success, 1 if NAME does not exist.
2194 2194
2195 2195 """
2196 2196
2197 2197 opts = pycompat.byteskwargs(opts)
2198 2198 editopts = (b'edit', b'local', b'global', b'shared', b'non_shared')
2199 2199 if any(opts.get(o) for o in editopts):
2200 2200 cmdutil.check_at_most_one_arg(opts, *editopts[1:])
2201 2201 if opts.get(b'local'):
2202 2202 if not repo:
2203 2203 raise error.Abort(_(b"can't use --local outside a repository"))
2204 2204 paths = [repo.vfs.join(b'hgrc')]
2205 2205 elif opts.get(b'global'):
2206 2206 paths = rcutil.systemrcpath()
2207 2207 elif opts.get(b'shared'):
2208 2208 if not repo.shared():
2209 2209 raise error.Abort(
2210 2210 _(b"repository is not shared; can't use --shared")
2211 2211 )
2212 2212 if requirements.SHARESAFE_REQUIREMENT not in repo.requirements:
2213 2213 raise error.Abort(
2214 2214 _(
2215 2215 b"share safe feature not unabled; "
2216 2216 b"unable to edit shared source repository config"
2217 2217 )
2218 2218 )
2219 2219 paths = [vfsmod.vfs(repo.sharedpath).join(b'hgrc')]
2220 2220 elif opts.get(b'non_shared'):
2221 2221 paths = [repo.vfs.join(b'hgrc-not-shared')]
2222 2222 else:
2223 2223 paths = rcutil.userrcpath()
2224 2224
2225 2225 for f in paths:
2226 2226 if os.path.exists(f):
2227 2227 break
2228 2228 else:
2229 2229 if opts.get(b'global'):
2230 2230 samplehgrc = uimod.samplehgrcs[b'global']
2231 2231 elif opts.get(b'local'):
2232 2232 samplehgrc = uimod.samplehgrcs[b'local']
2233 2233 else:
2234 2234 samplehgrc = uimod.samplehgrcs[b'user']
2235 2235
2236 2236 f = paths[0]
2237 2237 fp = open(f, b"wb")
2238 2238 fp.write(util.tonativeeol(samplehgrc))
2239 2239 fp.close()
2240 2240
2241 2241 editor = ui.geteditor()
2242 2242 ui.system(
2243 2243 b"%s \"%s\"" % (editor, f),
2244 2244 onerr=error.Abort,
2245 2245 errprefix=_(b"edit failed"),
2246 2246 blockedtag=b'config_edit',
2247 2247 )
2248 2248 return
2249 2249 ui.pager(b'config')
2250 2250 fm = ui.formatter(b'config', opts)
2251 2251 for t, f in rcutil.rccomponents():
2252 2252 if t == b'path':
2253 2253 ui.debug(b'read config from: %s\n' % f)
2254 2254 elif t == b'resource':
2255 2255 ui.debug(b'read config from: resource:%s.%s\n' % (f[0], f[1]))
2256 2256 elif t == b'items':
2257 2257 # Don't print anything for 'items'.
2258 2258 pass
2259 2259 else:
2260 2260 raise error.ProgrammingError(b'unknown rctype: %s' % t)
2261 2261 untrusted = bool(opts.get(b'untrusted'))
2262 2262
2263 2263 selsections = selentries = []
2264 2264 if values:
2265 2265 selsections = [v for v in values if b'.' not in v]
2266 2266 selentries = [v for v in values if b'.' in v]
2267 2267 uniquesel = len(selentries) == 1 and not selsections
2268 2268 selsections = set(selsections)
2269 2269 selentries = set(selentries)
2270 2270
2271 2271 matched = False
2272 2272 for section, name, value in ui.walkconfig(untrusted=untrusted):
2273 2273 source = ui.configsource(section, name, untrusted)
2274 2274 value = pycompat.bytestr(value)
2275 2275 defaultvalue = ui.configdefault(section, name)
2276 2276 if fm.isplain():
2277 2277 source = source or b'none'
2278 2278 value = value.replace(b'\n', b'\\n')
2279 2279 entryname = section + b'.' + name
2280 2280 if values and not (section in selsections or entryname in selentries):
2281 2281 continue
2282 2282 fm.startitem()
2283 2283 fm.condwrite(ui.debugflag, b'source', b'%s: ', source)
2284 2284 if uniquesel:
2285 2285 fm.data(name=entryname)
2286 2286 fm.write(b'value', b'%s\n', value)
2287 2287 else:
2288 2288 fm.write(b'name value', b'%s=%s\n', entryname, value)
2289 2289 if formatter.isprintable(defaultvalue):
2290 2290 fm.data(defaultvalue=defaultvalue)
2291 2291 elif isinstance(defaultvalue, list) and all(
2292 2292 formatter.isprintable(e) for e in defaultvalue
2293 2293 ):
2294 2294 fm.data(defaultvalue=fm.formatlist(defaultvalue, name=b'value'))
2295 2295 # TODO: no idea how to process unsupported defaultvalue types
2296 2296 matched = True
2297 2297 fm.end()
2298 2298 if matched:
2299 2299 return 0
2300 2300 return 1
2301 2301
2302 2302
2303 2303 @command(
2304 2304 b'continue',
2305 2305 dryrunopts,
2306 2306 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
2307 2307 helpbasic=True,
2308 2308 )
2309 2309 def continuecmd(ui, repo, **opts):
2310 2310 """resumes an interrupted operation (EXPERIMENTAL)
2311 2311
2312 2312 Finishes a multistep operation like graft, histedit, rebase, merge,
2313 2313 and unshelve if they are in an interrupted state.
2314 2314
2315 2315 use --dry-run/-n to dry run the command.
2316 2316 """
2317 2317 dryrun = opts.get('dry_run')
2318 2318 contstate = cmdutil.getunfinishedstate(repo)
2319 2319 if not contstate:
2320 2320 raise error.Abort(_(b'no operation in progress'))
2321 2321 if not contstate.continuefunc:
2322 2322 raise error.Abort(
2323 2323 (
2324 2324 _(b"%s in progress but does not support 'hg continue'")
2325 2325 % (contstate._opname)
2326 2326 ),
2327 2327 hint=contstate.continuemsg(),
2328 2328 )
2329 2329 if dryrun:
2330 2330 ui.status(_(b'%s in progress, will be resumed\n') % (contstate._opname))
2331 2331 return
2332 2332 return contstate.continuefunc(ui, repo)
2333 2333
2334 2334
2335 2335 @command(
2336 2336 b'copy|cp',
2337 2337 [
2338 2338 (b'', b'forget', None, _(b'unmark a destination file as copied')),
2339 2339 (b'A', b'after', None, _(b'record a copy that has already occurred')),
2340 2340 (
2341 2341 b'',
2342 2342 b'at-rev',
2343 2343 b'',
2344 2344 _(b'(un)mark copies in the given revision (EXPERIMENTAL)'),
2345 2345 _(b'REV'),
2346 2346 ),
2347 2347 (
2348 2348 b'f',
2349 2349 b'force',
2350 2350 None,
2351 2351 _(b'forcibly copy over an existing managed file'),
2352 2352 ),
2353 2353 ]
2354 2354 + walkopts
2355 2355 + dryrunopts,
2356 2356 _(b'[OPTION]... (SOURCE... DEST | --forget DEST...)'),
2357 2357 helpcategory=command.CATEGORY_FILE_CONTENTS,
2358 2358 )
2359 2359 def copy(ui, repo, *pats, **opts):
2360 2360 """mark files as copied for the next commit
2361 2361
2362 2362 Mark dest as having copies of source files. If dest is a
2363 2363 directory, copies are put in that directory. If dest is a file,
2364 2364 the source must be a single file.
2365 2365
2366 2366 By default, this command copies the contents of files as they
2367 2367 exist in the working directory. If invoked with -A/--after, the
2368 2368 operation is recorded, but no copying is performed.
2369 2369
2370 2370 To undo marking a destination file as copied, use --forget. With that
2371 2371 option, all given (positional) arguments are unmarked as copies. The
2372 2372 destination file(s) will be left in place (still tracked).
2373 2373
2374 2374 This command takes effect with the next commit by default.
2375 2375
2376 2376 Returns 0 on success, 1 if errors are encountered.
2377 2377 """
2378 2378 opts = pycompat.byteskwargs(opts)
2379 2379 with repo.wlock():
2380 2380 return cmdutil.copy(ui, repo, pats, opts)
2381 2381
2382 2382
2383 2383 @command(
2384 2384 b'debugcommands',
2385 2385 [],
2386 2386 _(b'[COMMAND]'),
2387 2387 helpcategory=command.CATEGORY_HELP,
2388 2388 norepo=True,
2389 2389 )
2390 2390 def debugcommands(ui, cmd=b'', *args):
2391 2391 """list all available commands and options"""
2392 2392 for cmd, vals in sorted(pycompat.iteritems(table)):
2393 2393 cmd = cmd.split(b'|')[0]
2394 2394 opts = b', '.join([i[1] for i in vals[1]])
2395 2395 ui.write(b'%s: %s\n' % (cmd, opts))
2396 2396
2397 2397
2398 2398 @command(
2399 2399 b'debugcomplete',
2400 2400 [(b'o', b'options', None, _(b'show the command options'))],
2401 2401 _(b'[-o] CMD'),
2402 2402 helpcategory=command.CATEGORY_HELP,
2403 2403 norepo=True,
2404 2404 )
2405 2405 def debugcomplete(ui, cmd=b'', **opts):
2406 2406 """returns the completion list associated with the given command"""
2407 2407
2408 2408 if opts.get('options'):
2409 2409 options = []
2410 2410 otables = [globalopts]
2411 2411 if cmd:
2412 2412 aliases, entry = cmdutil.findcmd(cmd, table, False)
2413 2413 otables.append(entry[1])
2414 2414 for t in otables:
2415 2415 for o in t:
2416 2416 if b"(DEPRECATED)" in o[3]:
2417 2417 continue
2418 2418 if o[0]:
2419 2419 options.append(b'-%s' % o[0])
2420 2420 options.append(b'--%s' % o[1])
2421 2421 ui.write(b"%s\n" % b"\n".join(options))
2422 2422 return
2423 2423
2424 2424 cmdlist, unused_allcmds = cmdutil.findpossible(cmd, table)
2425 2425 if ui.verbose:
2426 2426 cmdlist = [b' '.join(c[0]) for c in cmdlist.values()]
2427 2427 ui.write(b"%s\n" % b"\n".join(sorted(cmdlist)))
2428 2428
2429 2429
2430 2430 @command(
2431 2431 b'diff',
2432 2432 [
2433 2433 (b'r', b'rev', [], _(b'revision'), _(b'REV')),
2434 2434 (b'c', b'change', b'', _(b'change made by revision'), _(b'REV')),
2435 2435 ]
2436 2436 + diffopts
2437 2437 + diffopts2
2438 2438 + walkopts
2439 2439 + subrepoopts,
2440 2440 _(b'[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'),
2441 2441 helpcategory=command.CATEGORY_FILE_CONTENTS,
2442 2442 helpbasic=True,
2443 2443 inferrepo=True,
2444 2444 intents={INTENT_READONLY},
2445 2445 )
2446 2446 def diff(ui, repo, *pats, **opts):
2447 2447 """diff repository (or selected files)
2448 2448
2449 2449 Show differences between revisions for the specified files.
2450 2450
2451 2451 Differences between files are shown using the unified diff format.
2452 2452
2453 2453 .. note::
2454 2454
2455 2455 :hg:`diff` may generate unexpected results for merges, as it will
2456 2456 default to comparing against the working directory's first
2457 2457 parent changeset if no revisions are specified.
2458 2458
2459 2459 When two revision arguments are given, then changes are shown
2460 2460 between those revisions. If only one revision is specified then
2461 2461 that revision is compared to the working directory, and, when no
2462 2462 revisions are specified, the working directory files are compared
2463 2463 to its first parent.
2464 2464
2465 2465 Alternatively you can specify -c/--change with a revision to see
2466 2466 the changes in that changeset relative to its first parent.
2467 2467
2468 2468 Without the -a/--text option, diff will avoid generating diffs of
2469 2469 files it detects as binary. With -a, diff will generate a diff
2470 2470 anyway, probably with undesirable results.
2471 2471
2472 2472 Use the -g/--git option to generate diffs in the git extended diff
2473 2473 format. For more information, read :hg:`help diffs`.
2474 2474
2475 2475 .. container:: verbose
2476 2476
2477 2477 Examples:
2478 2478
2479 2479 - compare a file in the current working directory to its parent::
2480 2480
2481 2481 hg diff foo.c
2482 2482
2483 2483 - compare two historical versions of a directory, with rename info::
2484 2484
2485 2485 hg diff --git -r 1.0:1.2 lib/
2486 2486
2487 2487 - get change stats relative to the last change on some date::
2488 2488
2489 2489 hg diff --stat -r "date('may 2')"
2490 2490
2491 2491 - diff all newly-added files that contain a keyword::
2492 2492
2493 2493 hg diff "set:added() and grep(GNU)"
2494 2494
2495 2495 - compare a revision and its parents::
2496 2496
2497 2497 hg diff -c 9353 # compare against first parent
2498 2498 hg diff -r 9353^:9353 # same using revset syntax
2499 2499 hg diff -r 9353^2:9353 # compare against the second parent
2500 2500
2501 2501 Returns 0 on success.
2502 2502 """
2503 2503
2504 2504 cmdutil.check_at_most_one_arg(opts, 'rev', 'change')
2505 2505 opts = pycompat.byteskwargs(opts)
2506 2506 revs = opts.get(b'rev')
2507 2507 change = opts.get(b'change')
2508 2508 stat = opts.get(b'stat')
2509 2509 reverse = opts.get(b'reverse')
2510 2510
2511 2511 if change:
2512 2512 repo = scmutil.unhidehashlikerevs(repo, [change], b'nowarn')
2513 2513 ctx2 = scmutil.revsingle(repo, change, None)
2514 2514 ctx1 = ctx2.p1()
2515 2515 else:
2516 2516 repo = scmutil.unhidehashlikerevs(repo, revs, b'nowarn')
2517 2517 ctx1, ctx2 = scmutil.revpair(repo, revs)
2518 2518
2519 2519 if reverse:
2520 2520 ctxleft = ctx2
2521 2521 ctxright = ctx1
2522 2522 else:
2523 2523 ctxleft = ctx1
2524 2524 ctxright = ctx2
2525 2525
2526 2526 diffopts = patch.diffallopts(ui, opts)
2527 2527 m = scmutil.match(ctx2, pats, opts)
2528 2528 m = repo.narrowmatch(m)
2529 2529 ui.pager(b'diff')
2530 2530 logcmdutil.diffordiffstat(
2531 2531 ui,
2532 2532 repo,
2533 2533 diffopts,
2534 2534 ctxleft,
2535 2535 ctxright,
2536 2536 m,
2537 2537 stat=stat,
2538 2538 listsubrepos=opts.get(b'subrepos'),
2539 2539 root=opts.get(b'root'),
2540 2540 )
2541 2541
2542 2542
2543 2543 @command(
2544 2544 b'export',
2545 2545 [
2546 2546 (
2547 2547 b'B',
2548 2548 b'bookmark',
2549 2549 b'',
2550 2550 _(b'export changes only reachable by given bookmark'),
2551 2551 _(b'BOOKMARK'),
2552 2552 ),
2553 2553 (
2554 2554 b'o',
2555 2555 b'output',
2556 2556 b'',
2557 2557 _(b'print output to file with formatted name'),
2558 2558 _(b'FORMAT'),
2559 2559 ),
2560 2560 (b'', b'switch-parent', None, _(b'diff against the second parent')),
2561 2561 (b'r', b'rev', [], _(b'revisions to export'), _(b'REV')),
2562 2562 ]
2563 2563 + diffopts
2564 2564 + formatteropts,
2565 2565 _(b'[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'),
2566 2566 helpcategory=command.CATEGORY_IMPORT_EXPORT,
2567 2567 helpbasic=True,
2568 2568 intents={INTENT_READONLY},
2569 2569 )
2570 2570 def export(ui, repo, *changesets, **opts):
2571 2571 """dump the header and diffs for one or more changesets
2572 2572
2573 2573 Print the changeset header and diffs for one or more revisions.
2574 2574 If no revision is given, the parent of the working directory is used.
2575 2575
2576 2576 The information shown in the changeset header is: author, date,
2577 2577 branch name (if non-default), changeset hash, parent(s) and commit
2578 2578 comment.
2579 2579
2580 2580 .. note::
2581 2581
2582 2582 :hg:`export` may generate unexpected diff output for merge
2583 2583 changesets, as it will compare the merge changeset against its
2584 2584 first parent only.
2585 2585
2586 2586 Output may be to a file, in which case the name of the file is
2587 2587 given using a template string. See :hg:`help templates`. In addition
2588 2588 to the common template keywords, the following formatting rules are
2589 2589 supported:
2590 2590
2591 2591 :``%%``: literal "%" character
2592 2592 :``%H``: changeset hash (40 hexadecimal digits)
2593 2593 :``%N``: number of patches being generated
2594 2594 :``%R``: changeset revision number
2595 2595 :``%b``: basename of the exporting repository
2596 2596 :``%h``: short-form changeset hash (12 hexadecimal digits)
2597 2597 :``%m``: first line of the commit message (only alphanumeric characters)
2598 2598 :``%n``: zero-padded sequence number, starting at 1
2599 2599 :``%r``: zero-padded changeset revision number
2600 2600 :``\\``: literal "\\" character
2601 2601
2602 2602 Without the -a/--text option, export will avoid generating diffs
2603 2603 of files it detects as binary. With -a, export will generate a
2604 2604 diff anyway, probably with undesirable results.
2605 2605
2606 2606 With -B/--bookmark changesets reachable by the given bookmark are
2607 2607 selected.
2608 2608
2609 2609 Use the -g/--git option to generate diffs in the git extended diff
2610 2610 format. See :hg:`help diffs` for more information.
2611 2611
2612 2612 With the --switch-parent option, the diff will be against the
2613 2613 second parent. It can be useful to review a merge.
2614 2614
2615 2615 .. container:: verbose
2616 2616
2617 2617 Template:
2618 2618
2619 2619 The following keywords are supported in addition to the common template
2620 2620 keywords and functions. See also :hg:`help templates`.
2621 2621
2622 2622 :diff: String. Diff content.
2623 2623 :parents: List of strings. Parent nodes of the changeset.
2624 2624
2625 2625 Examples:
2626 2626
2627 2627 - use export and import to transplant a bugfix to the current
2628 2628 branch::
2629 2629
2630 2630 hg export -r 9353 | hg import -
2631 2631
2632 2632 - export all the changesets between two revisions to a file with
2633 2633 rename information::
2634 2634
2635 2635 hg export --git -r 123:150 > changes.txt
2636 2636
2637 2637 - split outgoing changes into a series of patches with
2638 2638 descriptive names::
2639 2639
2640 2640 hg export -r "outgoing()" -o "%n-%m.patch"
2641 2641
2642 2642 Returns 0 on success.
2643 2643 """
2644 2644 opts = pycompat.byteskwargs(opts)
2645 2645 bookmark = opts.get(b'bookmark')
2646 2646 changesets += tuple(opts.get(b'rev', []))
2647 2647
2648 2648 cmdutil.check_at_most_one_arg(opts, b'rev', b'bookmark')
2649 2649
2650 2650 if bookmark:
2651 2651 if bookmark not in repo._bookmarks:
2652 2652 raise error.Abort(_(b"bookmark '%s' not found") % bookmark)
2653 2653
2654 2654 revs = scmutil.bookmarkrevs(repo, bookmark)
2655 2655 else:
2656 2656 if not changesets:
2657 2657 changesets = [b'.']
2658 2658
2659 2659 repo = scmutil.unhidehashlikerevs(repo, changesets, b'nowarn')
2660 2660 revs = scmutil.revrange(repo, changesets)
2661 2661
2662 2662 if not revs:
2663 2663 raise error.Abort(_(b"export requires at least one changeset"))
2664 2664 if len(revs) > 1:
2665 2665 ui.note(_(b'exporting patches:\n'))
2666 2666 else:
2667 2667 ui.note(_(b'exporting patch:\n'))
2668 2668
2669 2669 fntemplate = opts.get(b'output')
2670 2670 if cmdutil.isstdiofilename(fntemplate):
2671 2671 fntemplate = b''
2672 2672
2673 2673 if fntemplate:
2674 2674 fm = formatter.nullformatter(ui, b'export', opts)
2675 2675 else:
2676 2676 ui.pager(b'export')
2677 2677 fm = ui.formatter(b'export', opts)
2678 2678 with fm:
2679 2679 cmdutil.export(
2680 2680 repo,
2681 2681 revs,
2682 2682 fm,
2683 2683 fntemplate=fntemplate,
2684 2684 switch_parent=opts.get(b'switch_parent'),
2685 2685 opts=patch.diffallopts(ui, opts),
2686 2686 )
2687 2687
2688 2688
2689 2689 @command(
2690 2690 b'files',
2691 2691 [
2692 2692 (
2693 2693 b'r',
2694 2694 b'rev',
2695 2695 b'',
2696 2696 _(b'search the repository as it is in REV'),
2697 2697 _(b'REV'),
2698 2698 ),
2699 2699 (
2700 2700 b'0',
2701 2701 b'print0',
2702 2702 None,
2703 2703 _(b'end filenames with NUL, for use with xargs'),
2704 2704 ),
2705 2705 ]
2706 2706 + walkopts
2707 2707 + formatteropts
2708 2708 + subrepoopts,
2709 2709 _(b'[OPTION]... [FILE]...'),
2710 2710 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
2711 2711 intents={INTENT_READONLY},
2712 2712 )
2713 2713 def files(ui, repo, *pats, **opts):
2714 2714 """list tracked files
2715 2715
2716 2716 Print files under Mercurial control in the working directory or
2717 2717 specified revision for given files (excluding removed files).
2718 2718 Files can be specified as filenames or filesets.
2719 2719
2720 2720 If no files are given to match, this command prints the names
2721 2721 of all files under Mercurial control.
2722 2722
2723 2723 .. container:: verbose
2724 2724
2725 2725 Template:
2726 2726
2727 2727 The following keywords are supported in addition to the common template
2728 2728 keywords and functions. See also :hg:`help templates`.
2729 2729
2730 2730 :flags: String. Character denoting file's symlink and executable bits.
2731 2731 :path: String. Repository-absolute path of the file.
2732 2732 :size: Integer. Size of the file in bytes.
2733 2733
2734 2734 Examples:
2735 2735
2736 2736 - list all files under the current directory::
2737 2737
2738 2738 hg files .
2739 2739
2740 2740 - shows sizes and flags for current revision::
2741 2741
2742 2742 hg files -vr .
2743 2743
2744 2744 - list all files named README::
2745 2745
2746 2746 hg files -I "**/README"
2747 2747
2748 2748 - list all binary files::
2749 2749
2750 2750 hg files "set:binary()"
2751 2751
2752 2752 - find files containing a regular expression::
2753 2753
2754 2754 hg files "set:grep('bob')"
2755 2755
2756 2756 - search tracked file contents with xargs and grep::
2757 2757
2758 2758 hg files -0 | xargs -0 grep foo
2759 2759
2760 2760 See :hg:`help patterns` and :hg:`help filesets` for more information
2761 2761 on specifying file patterns.
2762 2762
2763 2763 Returns 0 if a match is found, 1 otherwise.
2764 2764
2765 2765 """
2766 2766
2767 2767 opts = pycompat.byteskwargs(opts)
2768 2768 rev = opts.get(b'rev')
2769 2769 if rev:
2770 2770 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
2771 2771 ctx = scmutil.revsingle(repo, rev, None)
2772 2772
2773 2773 end = b'\n'
2774 2774 if opts.get(b'print0'):
2775 2775 end = b'\0'
2776 2776 fmt = b'%s' + end
2777 2777
2778 2778 m = scmutil.match(ctx, pats, opts)
2779 2779 ui.pager(b'files')
2780 2780 uipathfn = scmutil.getuipathfn(ctx.repo(), legacyrelativevalue=True)
2781 2781 with ui.formatter(b'files', opts) as fm:
2782 2782 return cmdutil.files(
2783 2783 ui, ctx, m, uipathfn, fm, fmt, opts.get(b'subrepos')
2784 2784 )
2785 2785
2786 2786
2787 2787 @command(
2788 2788 b'forget',
2789 2789 [(b'i', b'interactive', None, _(b'use interactive mode')),]
2790 2790 + walkopts
2791 2791 + dryrunopts,
2792 2792 _(b'[OPTION]... FILE...'),
2793 2793 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
2794 2794 helpbasic=True,
2795 2795 inferrepo=True,
2796 2796 )
2797 2797 def forget(ui, repo, *pats, **opts):
2798 2798 """forget the specified files on the next commit
2799 2799
2800 2800 Mark the specified files so they will no longer be tracked
2801 2801 after the next commit.
2802 2802
2803 2803 This only removes files from the current branch, not from the
2804 2804 entire project history, and it does not delete them from the
2805 2805 working directory.
2806 2806
2807 2807 To delete the file from the working directory, see :hg:`remove`.
2808 2808
2809 2809 To undo a forget before the next commit, see :hg:`add`.
2810 2810
2811 2811 .. container:: verbose
2812 2812
2813 2813 Examples:
2814 2814
2815 2815 - forget newly-added binary files::
2816 2816
2817 2817 hg forget "set:added() and binary()"
2818 2818
2819 2819 - forget files that would be excluded by .hgignore::
2820 2820
2821 2821 hg forget "set:hgignore()"
2822 2822
2823 2823 Returns 0 on success.
2824 2824 """
2825 2825
2826 2826 opts = pycompat.byteskwargs(opts)
2827 2827 if not pats:
2828 2828 raise error.Abort(_(b'no files specified'))
2829 2829
2830 2830 m = scmutil.match(repo[None], pats, opts)
2831 2831 dryrun, interactive = opts.get(b'dry_run'), opts.get(b'interactive')
2832 2832 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
2833 2833 rejected = cmdutil.forget(
2834 2834 ui,
2835 2835 repo,
2836 2836 m,
2837 2837 prefix=b"",
2838 2838 uipathfn=uipathfn,
2839 2839 explicitonly=False,
2840 2840 dryrun=dryrun,
2841 2841 interactive=interactive,
2842 2842 )[0]
2843 2843 return rejected and 1 or 0
2844 2844
2845 2845
2846 2846 @command(
2847 2847 b'graft',
2848 2848 [
2849 2849 (b'r', b'rev', [], _(b'revisions to graft'), _(b'REV')),
2850 2850 (
2851 2851 b'',
2852 2852 b'base',
2853 2853 b'',
2854 2854 _(b'base revision when doing the graft merge (ADVANCED)'),
2855 2855 _(b'REV'),
2856 2856 ),
2857 2857 (b'c', b'continue', False, _(b'resume interrupted graft')),
2858 2858 (b'', b'stop', False, _(b'stop interrupted graft')),
2859 2859 (b'', b'abort', False, _(b'abort interrupted graft')),
2860 2860 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
2861 2861 (b'', b'log', None, _(b'append graft info to log message')),
2862 2862 (
2863 2863 b'',
2864 2864 b'no-commit',
2865 2865 None,
2866 2866 _(b"don't commit, just apply the changes in working directory"),
2867 2867 ),
2868 2868 (b'f', b'force', False, _(b'force graft')),
2869 2869 (
2870 2870 b'D',
2871 2871 b'currentdate',
2872 2872 False,
2873 2873 _(b'record the current date as commit date'),
2874 2874 ),
2875 2875 (
2876 2876 b'U',
2877 2877 b'currentuser',
2878 2878 False,
2879 2879 _(b'record the current user as committer'),
2880 2880 ),
2881 2881 ]
2882 2882 + commitopts2
2883 2883 + mergetoolopts
2884 2884 + dryrunopts,
2885 2885 _(b'[OPTION]... [-r REV]... REV...'),
2886 2886 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
2887 2887 )
2888 2888 def graft(ui, repo, *revs, **opts):
2889 2889 '''copy changes from other branches onto the current branch
2890 2890
2891 2891 This command uses Mercurial's merge logic to copy individual
2892 2892 changes from other branches without merging branches in the
2893 2893 history graph. This is sometimes known as 'backporting' or
2894 2894 'cherry-picking'. By default, graft will copy user, date, and
2895 2895 description from the source changesets.
2896 2896
2897 2897 Changesets that are ancestors of the current revision, that have
2898 2898 already been grafted, or that are merges will be skipped.
2899 2899
2900 2900 If --log is specified, log messages will have a comment appended
2901 2901 of the form::
2902 2902
2903 2903 (grafted from CHANGESETHASH)
2904 2904
2905 2905 If --force is specified, revisions will be grafted even if they
2906 2906 are already ancestors of, or have been grafted to, the destination.
2907 2907 This is useful when the revisions have since been backed out.
2908 2908
2909 2909 If a graft merge results in conflicts, the graft process is
2910 2910 interrupted so that the current merge can be manually resolved.
2911 2911 Once all conflicts are addressed, the graft process can be
2912 2912 continued with the -c/--continue option.
2913 2913
2914 2914 The -c/--continue option reapplies all the earlier options.
2915 2915
2916 2916 .. container:: verbose
2917 2917
2918 2918 The --base option exposes more of how graft internally uses merge with a
2919 2919 custom base revision. --base can be used to specify another ancestor than
2920 2920 the first and only parent.
2921 2921
2922 2922 The command::
2923 2923
2924 2924 hg graft -r 345 --base 234
2925 2925
2926 2926 is thus pretty much the same as::
2927 2927
2928 2928 hg diff -r 234 -r 345 | hg import
2929 2929
2930 2930 but using merge to resolve conflicts and track moved files.
2931 2931
2932 2932 The result of a merge can thus be backported as a single commit by
2933 2933 specifying one of the merge parents as base, and thus effectively
2934 2934 grafting the changes from the other side.
2935 2935
2936 2936 It is also possible to collapse multiple changesets and clean up history
2937 2937 by specifying another ancestor as base, much like rebase --collapse
2938 2938 --keep.
2939 2939
2940 2940 The commit message can be tweaked after the fact using commit --amend .
2941 2941
2942 2942 For using non-ancestors as the base to backout changes, see the backout
2943 2943 command and the hidden --parent option.
2944 2944
2945 2945 .. container:: verbose
2946 2946
2947 2947 Examples:
2948 2948
2949 2949 - copy a single change to the stable branch and edit its description::
2950 2950
2951 2951 hg update stable
2952 2952 hg graft --edit 9393
2953 2953
2954 2954 - graft a range of changesets with one exception, updating dates::
2955 2955
2956 2956 hg graft -D "2085::2093 and not 2091"
2957 2957
2958 2958 - continue a graft after resolving conflicts::
2959 2959
2960 2960 hg graft -c
2961 2961
2962 2962 - show the source of a grafted changeset::
2963 2963
2964 2964 hg log --debug -r .
2965 2965
2966 2966 - show revisions sorted by date::
2967 2967
2968 2968 hg log -r "sort(all(), date)"
2969 2969
2970 2970 - backport the result of a merge as a single commit::
2971 2971
2972 2972 hg graft -r 123 --base 123^
2973 2973
2974 2974 - land a feature branch as one changeset::
2975 2975
2976 2976 hg up -cr default
2977 2977 hg graft -r featureX --base "ancestor('featureX', 'default')"
2978 2978
2979 2979 See :hg:`help revisions` for more about specifying revisions.
2980 2980
2981 2981 Returns 0 on successful completion, 1 if there are unresolved files.
2982 2982 '''
2983 2983 with repo.wlock():
2984 2984 return _dograft(ui, repo, *revs, **opts)
2985 2985
2986 2986
2987 2987 def _dograft(ui, repo, *revs, **opts):
2988 2988 opts = pycompat.byteskwargs(opts)
2989 2989 if revs and opts.get(b'rev'):
2990 2990 ui.warn(
2991 2991 _(
2992 2992 b'warning: inconsistent use of --rev might give unexpected '
2993 2993 b'revision ordering!\n'
2994 2994 )
2995 2995 )
2996 2996
2997 2997 revs = list(revs)
2998 2998 revs.extend(opts.get(b'rev'))
2999 2999 # a dict of data to be stored in state file
3000 3000 statedata = {}
3001 3001 # list of new nodes created by ongoing graft
3002 3002 statedata[b'newnodes'] = []
3003 3003
3004 3004 cmdutil.resolvecommitoptions(ui, opts)
3005 3005
3006 3006 editor = cmdutil.getcommiteditor(
3007 3007 editform=b'graft', **pycompat.strkwargs(opts)
3008 3008 )
3009 3009
3010 3010 cmdutil.check_at_most_one_arg(opts, b'abort', b'stop', b'continue')
3011 3011
3012 3012 cont = False
3013 3013 if opts.get(b'no_commit'):
3014 3014 cmdutil.check_incompatible_arguments(
3015 3015 opts,
3016 3016 b'no_commit',
3017 3017 [b'edit', b'currentuser', b'currentdate', b'log'],
3018 3018 )
3019 3019
3020 3020 graftstate = statemod.cmdstate(repo, b'graftstate')
3021 3021
3022 3022 if opts.get(b'stop'):
3023 3023 cmdutil.check_incompatible_arguments(
3024 3024 opts,
3025 3025 b'stop',
3026 3026 [
3027 3027 b'edit',
3028 3028 b'log',
3029 3029 b'user',
3030 3030 b'date',
3031 3031 b'currentdate',
3032 3032 b'currentuser',
3033 3033 b'rev',
3034 3034 ],
3035 3035 )
3036 3036 return _stopgraft(ui, repo, graftstate)
3037 3037 elif opts.get(b'abort'):
3038 3038 cmdutil.check_incompatible_arguments(
3039 3039 opts,
3040 3040 b'abort',
3041 3041 [
3042 3042 b'edit',
3043 3043 b'log',
3044 3044 b'user',
3045 3045 b'date',
3046 3046 b'currentdate',
3047 3047 b'currentuser',
3048 3048 b'rev',
3049 3049 ],
3050 3050 )
3051 3051 return cmdutil.abortgraft(ui, repo, graftstate)
3052 3052 elif opts.get(b'continue'):
3053 3053 cont = True
3054 3054 if revs:
3055 3055 raise error.Abort(_(b"can't specify --continue and revisions"))
3056 3056 # read in unfinished revisions
3057 3057 if graftstate.exists():
3058 3058 statedata = cmdutil.readgraftstate(repo, graftstate)
3059 3059 if statedata.get(b'date'):
3060 3060 opts[b'date'] = statedata[b'date']
3061 3061 if statedata.get(b'user'):
3062 3062 opts[b'user'] = statedata[b'user']
3063 3063 if statedata.get(b'log'):
3064 3064 opts[b'log'] = True
3065 3065 if statedata.get(b'no_commit'):
3066 3066 opts[b'no_commit'] = statedata.get(b'no_commit')
3067 3067 if statedata.get(b'base'):
3068 3068 opts[b'base'] = statedata.get(b'base')
3069 3069 nodes = statedata[b'nodes']
3070 3070 revs = [repo[node].rev() for node in nodes]
3071 3071 else:
3072 3072 cmdutil.wrongtooltocontinue(repo, _(b'graft'))
3073 3073 else:
3074 3074 if not revs:
3075 3075 raise error.Abort(_(b'no revisions specified'))
3076 3076 cmdutil.checkunfinished(repo)
3077 3077 cmdutil.bailifchanged(repo)
3078 3078 revs = scmutil.revrange(repo, revs)
3079 3079
3080 3080 skipped = set()
3081 3081 basectx = None
3082 3082 if opts.get(b'base'):
3083 3083 basectx = scmutil.revsingle(repo, opts[b'base'], None)
3084 3084 if basectx is None:
3085 3085 # check for merges
3086 3086 for rev in repo.revs(b'%ld and merge()', revs):
3087 3087 ui.warn(_(b'skipping ungraftable merge revision %d\n') % rev)
3088 3088 skipped.add(rev)
3089 3089 revs = [r for r in revs if r not in skipped]
3090 3090 if not revs:
3091 3091 return -1
3092 3092 if basectx is not None and len(revs) != 1:
3093 3093 raise error.Abort(_(b'only one revision allowed with --base '))
3094 3094
3095 3095 # Don't check in the --continue case, in effect retaining --force across
3096 3096 # --continues. That's because without --force, any revisions we decided to
3097 3097 # skip would have been filtered out here, so they wouldn't have made their
3098 3098 # way to the graftstate. With --force, any revisions we would have otherwise
3099 3099 # skipped would not have been filtered out, and if they hadn't been applied
3100 3100 # already, they'd have been in the graftstate.
3101 3101 if not (cont or opts.get(b'force')) and basectx is None:
3102 3102 # check for ancestors of dest branch
3103 3103 ancestors = repo.revs(b'%ld & (::.)', revs)
3104 3104 for rev in ancestors:
3105 3105 ui.warn(_(b'skipping ancestor revision %d:%s\n') % (rev, repo[rev]))
3106 3106
3107 3107 revs = [r for r in revs if r not in ancestors]
3108 3108
3109 3109 if not revs:
3110 3110 return -1
3111 3111
3112 3112 # analyze revs for earlier grafts
3113 3113 ids = {}
3114 3114 for ctx in repo.set(b"%ld", revs):
3115 3115 ids[ctx.hex()] = ctx.rev()
3116 3116 n = ctx.extra().get(b'source')
3117 3117 if n:
3118 3118 ids[n] = ctx.rev()
3119 3119
3120 3120 # check ancestors for earlier grafts
3121 3121 ui.debug(b'scanning for duplicate grafts\n')
3122 3122
3123 3123 # The only changesets we can be sure doesn't contain grafts of any
3124 3124 # revs, are the ones that are common ancestors of *all* revs:
3125 3125 for rev in repo.revs(b'only(%d,ancestor(%ld))', repo[b'.'].rev(), revs):
3126 3126 ctx = repo[rev]
3127 3127 n = ctx.extra().get(b'source')
3128 3128 if n in ids:
3129 3129 try:
3130 3130 r = repo[n].rev()
3131 3131 except error.RepoLookupError:
3132 3132 r = None
3133 3133 if r in revs:
3134 3134 ui.warn(
3135 3135 _(
3136 3136 b'skipping revision %d:%s '
3137 3137 b'(already grafted to %d:%s)\n'
3138 3138 )
3139 3139 % (r, repo[r], rev, ctx)
3140 3140 )
3141 3141 revs.remove(r)
3142 3142 elif ids[n] in revs:
3143 3143 if r is None:
3144 3144 ui.warn(
3145 3145 _(
3146 3146 b'skipping already grafted revision %d:%s '
3147 3147 b'(%d:%s also has unknown origin %s)\n'
3148 3148 )
3149 3149 % (ids[n], repo[ids[n]], rev, ctx, n[:12])
3150 3150 )
3151 3151 else:
3152 3152 ui.warn(
3153 3153 _(
3154 3154 b'skipping already grafted revision %d:%s '
3155 3155 b'(%d:%s also has origin %d:%s)\n'
3156 3156 )
3157 3157 % (ids[n], repo[ids[n]], rev, ctx, r, n[:12])
3158 3158 )
3159 3159 revs.remove(ids[n])
3160 3160 elif ctx.hex() in ids:
3161 3161 r = ids[ctx.hex()]
3162 3162 if r in revs:
3163 3163 ui.warn(
3164 3164 _(
3165 3165 b'skipping already grafted revision %d:%s '
3166 3166 b'(was grafted from %d:%s)\n'
3167 3167 )
3168 3168 % (r, repo[r], rev, ctx)
3169 3169 )
3170 3170 revs.remove(r)
3171 3171 if not revs:
3172 3172 return -1
3173 3173
3174 3174 if opts.get(b'no_commit'):
3175 3175 statedata[b'no_commit'] = True
3176 3176 if opts.get(b'base'):
3177 3177 statedata[b'base'] = opts[b'base']
3178 3178 for pos, ctx in enumerate(repo.set(b"%ld", revs)):
3179 3179 desc = b'%d:%s "%s"' % (
3180 3180 ctx.rev(),
3181 3181 ctx,
3182 3182 ctx.description().split(b'\n', 1)[0],
3183 3183 )
3184 3184 names = repo.nodetags(ctx.node()) + repo.nodebookmarks(ctx.node())
3185 3185 if names:
3186 3186 desc += b' (%s)' % b' '.join(names)
3187 3187 ui.status(_(b'grafting %s\n') % desc)
3188 3188 if opts.get(b'dry_run'):
3189 3189 continue
3190 3190
3191 3191 source = ctx.extra().get(b'source')
3192 3192 extra = {}
3193 3193 if source:
3194 3194 extra[b'source'] = source
3195 3195 extra[b'intermediate-source'] = ctx.hex()
3196 3196 else:
3197 3197 extra[b'source'] = ctx.hex()
3198 3198 user = ctx.user()
3199 3199 if opts.get(b'user'):
3200 3200 user = opts[b'user']
3201 3201 statedata[b'user'] = user
3202 3202 date = ctx.date()
3203 3203 if opts.get(b'date'):
3204 3204 date = opts[b'date']
3205 3205 statedata[b'date'] = date
3206 3206 message = ctx.description()
3207 3207 if opts.get(b'log'):
3208 3208 message += b'\n(grafted from %s)' % ctx.hex()
3209 3209 statedata[b'log'] = True
3210 3210
3211 3211 # we don't merge the first commit when continuing
3212 3212 if not cont:
3213 3213 # perform the graft merge with p1(rev) as 'ancestor'
3214 3214 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
3215 3215 base = ctx.p1() if basectx is None else basectx
3216 3216 with ui.configoverride(overrides, b'graft'):
3217 3217 stats = mergemod.graft(repo, ctx, base, [b'local', b'graft'])
3218 3218 # report any conflicts
3219 3219 if stats.unresolvedcount > 0:
3220 3220 # write out state for --continue
3221 3221 nodes = [repo[rev].hex() for rev in revs[pos:]]
3222 3222 statedata[b'nodes'] = nodes
3223 3223 stateversion = 1
3224 3224 graftstate.save(stateversion, statedata)
3225 3225 ui.error(_(b"abort: unresolved conflicts, can't continue\n"))
3226 3226 ui.error(_(b"(use 'hg resolve' and 'hg graft --continue')\n"))
3227 3227 return 1
3228 3228 else:
3229 3229 cont = False
3230 3230
3231 3231 # commit if --no-commit is false
3232 3232 if not opts.get(b'no_commit'):
3233 3233 node = repo.commit(
3234 3234 text=message, user=user, date=date, extra=extra, editor=editor
3235 3235 )
3236 3236 if node is None:
3237 3237 ui.warn(
3238 3238 _(b'note: graft of %d:%s created no changes to commit\n')
3239 3239 % (ctx.rev(), ctx)
3240 3240 )
3241 3241 # checking that newnodes exist because old state files won't have it
3242 3242 elif statedata.get(b'newnodes') is not None:
3243 3243 statedata[b'newnodes'].append(node)
3244 3244
3245 3245 # remove state when we complete successfully
3246 3246 if not opts.get(b'dry_run'):
3247 3247 graftstate.delete()
3248 3248
3249 3249 return 0
3250 3250
3251 3251
3252 3252 def _stopgraft(ui, repo, graftstate):
3253 3253 """stop the interrupted graft"""
3254 3254 if not graftstate.exists():
3255 3255 raise error.Abort(_(b"no interrupted graft found"))
3256 3256 pctx = repo[b'.']
3257 3257 mergemod.clean_update(pctx)
3258 3258 graftstate.delete()
3259 3259 ui.status(_(b"stopped the interrupted graft\n"))
3260 3260 ui.status(_(b"working directory is now at %s\n") % pctx.hex()[:12])
3261 3261 return 0
3262 3262
3263 3263
3264 3264 statemod.addunfinished(
3265 3265 b'graft',
3266 3266 fname=b'graftstate',
3267 3267 clearable=True,
3268 3268 stopflag=True,
3269 3269 continueflag=True,
3270 3270 abortfunc=cmdutil.hgabortgraft,
3271 3271 cmdhint=_(b"use 'hg graft --continue' or 'hg graft --stop' to stop"),
3272 3272 )
3273 3273
3274 3274
3275 3275 @command(
3276 3276 b'grep',
3277 3277 [
3278 3278 (b'0', b'print0', None, _(b'end fields with NUL')),
3279 3279 (b'', b'all', None, _(b'an alias to --diff (DEPRECATED)')),
3280 3280 (
3281 3281 b'',
3282 3282 b'diff',
3283 3283 None,
3284 3284 _(
3285 3285 b'search revision differences for when the pattern was added '
3286 3286 b'or removed'
3287 3287 ),
3288 3288 ),
3289 3289 (b'a', b'text', None, _(b'treat all files as text')),
3290 3290 (
3291 3291 b'f',
3292 3292 b'follow',
3293 3293 None,
3294 3294 _(
3295 3295 b'follow changeset history,'
3296 3296 b' or file history across copies and renames'
3297 3297 ),
3298 3298 ),
3299 3299 (b'i', b'ignore-case', None, _(b'ignore case when matching')),
3300 3300 (
3301 3301 b'l',
3302 3302 b'files-with-matches',
3303 3303 None,
3304 3304 _(b'print only filenames and revisions that match'),
3305 3305 ),
3306 3306 (b'n', b'line-number', None, _(b'print matching line numbers')),
3307 3307 (
3308 3308 b'r',
3309 3309 b'rev',
3310 3310 [],
3311 3311 _(b'search files changed within revision range'),
3312 3312 _(b'REV'),
3313 3313 ),
3314 3314 (
3315 3315 b'',
3316 3316 b'all-files',
3317 3317 None,
3318 3318 _(
3319 3319 b'include all files in the changeset while grepping (DEPRECATED)'
3320 3320 ),
3321 3321 ),
3322 3322 (b'u', b'user', None, _(b'list the author (long with -v)')),
3323 3323 (b'd', b'date', None, _(b'list the date (short with -q)')),
3324 3324 ]
3325 3325 + formatteropts
3326 3326 + walkopts,
3327 3327 _(b'[--diff] [OPTION]... PATTERN [FILE]...'),
3328 3328 helpcategory=command.CATEGORY_FILE_CONTENTS,
3329 3329 inferrepo=True,
3330 3330 intents={INTENT_READONLY},
3331 3331 )
3332 3332 def grep(ui, repo, pattern, *pats, **opts):
3333 3333 """search for a pattern in specified files
3334 3334
3335 3335 Search the working directory or revision history for a regular
3336 3336 expression in the specified files for the entire repository.
3337 3337
3338 3338 By default, grep searches the repository files in the working
3339 3339 directory and prints the files where it finds a match. To specify
3340 3340 historical revisions instead of the working directory, use the
3341 3341 --rev flag.
3342 3342
3343 3343 To search instead historical revision differences that contains a
3344 3344 change in match status ("-" for a match that becomes a non-match,
3345 3345 or "+" for a non-match that becomes a match), use the --diff flag.
3346 3346
3347 3347 PATTERN can be any Python (roughly Perl-compatible) regular
3348 3348 expression.
3349 3349
3350 3350 If no FILEs are specified and the --rev flag isn't supplied, all
3351 3351 files in the working directory are searched. When using the --rev
3352 3352 flag and specifying FILEs, use the --follow argument to also
3353 3353 follow the specified FILEs across renames and copies.
3354 3354
3355 3355 .. container:: verbose
3356 3356
3357 3357 Template:
3358 3358
3359 3359 The following keywords are supported in addition to the common template
3360 3360 keywords and functions. See also :hg:`help templates`.
3361 3361
3362 3362 :change: String. Character denoting insertion ``+`` or removal ``-``.
3363 3363 Available if ``--diff`` is specified.
3364 3364 :lineno: Integer. Line number of the match.
3365 3365 :path: String. Repository-absolute path of the file.
3366 3366 :texts: List of text chunks.
3367 3367
3368 3368 And each entry of ``{texts}`` provides the following sub-keywords.
3369 3369
3370 3370 :matched: Boolean. True if the chunk matches the specified pattern.
3371 3371 :text: String. Chunk content.
3372 3372
3373 3373 See :hg:`help templates.operators` for the list expansion syntax.
3374 3374
3375 3375 Returns 0 if a match is found, 1 otherwise.
3376 3376
3377 3377 """
3378 3378 cmdutil.check_incompatible_arguments(opts, 'all_files', ['all', 'diff'])
3379 3379 opts = pycompat.byteskwargs(opts)
3380 3380 diff = opts.get(b'all') or opts.get(b'diff')
3381 3381 follow = opts.get(b'follow')
3382 3382 if opts.get(b'all_files') is None and not diff:
3383 3383 opts[b'all_files'] = True
3384 3384 plaingrep = (
3385 3385 opts.get(b'all_files')
3386 3386 and not opts.get(b'rev')
3387 3387 and not opts.get(b'follow')
3388 3388 )
3389 3389 all_files = opts.get(b'all_files')
3390 3390 if plaingrep:
3391 3391 opts[b'rev'] = [b'wdir()']
3392 3392
3393 3393 reflags = re.M
3394 3394 if opts.get(b'ignore_case'):
3395 3395 reflags |= re.I
3396 3396 try:
3397 3397 regexp = util.re.compile(pattern, reflags)
3398 3398 except re.error as inst:
3399 3399 ui.warn(
3400 3400 _(b"grep: invalid match pattern: %s\n") % pycompat.bytestr(inst)
3401 3401 )
3402 3402 return 1
3403 3403 sep, eol = b':', b'\n'
3404 3404 if opts.get(b'print0'):
3405 3405 sep = eol = b'\0'
3406 3406
3407 3407 searcher = grepmod.grepsearcher(
3408 3408 ui, repo, regexp, all_files=all_files, diff=diff, follow=follow
3409 3409 )
3410 3410
3411 3411 getfile = searcher._getfile
3412 3412
3413 3413 uipathfn = scmutil.getuipathfn(repo)
3414 3414
3415 3415 def display(fm, fn, ctx, pstates, states):
3416 3416 rev = scmutil.intrev(ctx)
3417 3417 if fm.isplain():
3418 3418 formatuser = ui.shortuser
3419 3419 else:
3420 3420 formatuser = pycompat.bytestr
3421 3421 if ui.quiet:
3422 3422 datefmt = b'%Y-%m-%d'
3423 3423 else:
3424 3424 datefmt = b'%a %b %d %H:%M:%S %Y %1%2'
3425 3425 found = False
3426 3426
3427 3427 @util.cachefunc
3428 3428 def binary():
3429 3429 flog = getfile(fn)
3430 3430 try:
3431 3431 return stringutil.binary(flog.read(ctx.filenode(fn)))
3432 3432 except error.WdirUnsupported:
3433 3433 return ctx[fn].isbinary()
3434 3434
3435 3435 fieldnamemap = {b'linenumber': b'lineno'}
3436 3436 if diff:
3437 3437 iter = grepmod.difflinestates(pstates, states)
3438 3438 else:
3439 3439 iter = [(b'', l) for l in states]
3440 3440 for change, l in iter:
3441 3441 fm.startitem()
3442 3442 fm.context(ctx=ctx)
3443 3443 fm.data(node=fm.hexfunc(scmutil.binnode(ctx)), path=fn)
3444 3444 fm.plain(uipathfn(fn), label=b'grep.filename')
3445 3445
3446 3446 cols = [
3447 3447 (b'rev', b'%d', rev, not plaingrep, b''),
3448 3448 (
3449 3449 b'linenumber',
3450 3450 b'%d',
3451 3451 l.linenum,
3452 3452 opts.get(b'line_number'),
3453 3453 b'',
3454 3454 ),
3455 3455 ]
3456 3456 if diff:
3457 3457 cols.append(
3458 3458 (
3459 3459 b'change',
3460 3460 b'%s',
3461 3461 change,
3462 3462 True,
3463 3463 b'grep.inserted '
3464 3464 if change == b'+'
3465 3465 else b'grep.deleted ',
3466 3466 )
3467 3467 )
3468 3468 cols.extend(
3469 3469 [
3470 3470 (
3471 3471 b'user',
3472 3472 b'%s',
3473 3473 formatuser(ctx.user()),
3474 3474 opts.get(b'user'),
3475 3475 b'',
3476 3476 ),
3477 3477 (
3478 3478 b'date',
3479 3479 b'%s',
3480 3480 fm.formatdate(ctx.date(), datefmt),
3481 3481 opts.get(b'date'),
3482 3482 b'',
3483 3483 ),
3484 3484 ]
3485 3485 )
3486 3486 for name, fmt, data, cond, extra_label in cols:
3487 3487 if cond:
3488 3488 fm.plain(sep, label=b'grep.sep')
3489 3489 field = fieldnamemap.get(name, name)
3490 3490 label = extra_label + (b'grep.%s' % name)
3491 3491 fm.condwrite(cond, field, fmt, data, label=label)
3492 3492 if not opts.get(b'files_with_matches'):
3493 3493 fm.plain(sep, label=b'grep.sep')
3494 3494 if not opts.get(b'text') and binary():
3495 3495 fm.plain(_(b" Binary file matches"))
3496 3496 else:
3497 3497 displaymatches(fm.nested(b'texts', tmpl=b'{text}'), l)
3498 3498 fm.plain(eol)
3499 3499 found = True
3500 3500 if opts.get(b'files_with_matches'):
3501 3501 break
3502 3502 return found
3503 3503
3504 3504 def displaymatches(fm, l):
3505 3505 p = 0
3506 3506 for s, e in l.findpos(regexp):
3507 3507 if p < s:
3508 3508 fm.startitem()
3509 3509 fm.write(b'text', b'%s', l.line[p:s])
3510 3510 fm.data(matched=False)
3511 3511 fm.startitem()
3512 3512 fm.write(b'text', b'%s', l.line[s:e], label=b'grep.match')
3513 3513 fm.data(matched=True)
3514 3514 p = e
3515 3515 if p < len(l.line):
3516 3516 fm.startitem()
3517 3517 fm.write(b'text', b'%s', l.line[p:])
3518 3518 fm.data(matched=False)
3519 3519 fm.end()
3520 3520
3521 3521 found = False
3522 3522
3523 3523 wopts = logcmdutil.walkopts(
3524 3524 pats=pats,
3525 3525 opts=opts,
3526 3526 revspec=opts[b'rev'],
3527 3527 include_pats=opts[b'include'],
3528 3528 exclude_pats=opts[b'exclude'],
3529 3529 follow=follow,
3530 3530 force_changelog_traversal=all_files,
3531 3531 filter_revisions_by_pats=not all_files,
3532 3532 )
3533 3533 revs, makefilematcher = logcmdutil.makewalker(repo, wopts)
3534 3534
3535 3535 ui.pager(b'grep')
3536 3536 fm = ui.formatter(b'grep', opts)
3537 3537 for fn, ctx, pstates, states in searcher.searchfiles(revs, makefilematcher):
3538 3538 r = display(fm, fn, ctx, pstates, states)
3539 3539 found = found or r
3540 3540 if r and not diff and not all_files:
3541 3541 searcher.skipfile(fn, ctx.rev())
3542 3542 fm.end()
3543 3543
3544 3544 return not found
3545 3545
3546 3546
3547 3547 @command(
3548 3548 b'heads',
3549 3549 [
3550 3550 (
3551 3551 b'r',
3552 3552 b'rev',
3553 3553 b'',
3554 3554 _(b'show only heads which are descendants of STARTREV'),
3555 3555 _(b'STARTREV'),
3556 3556 ),
3557 3557 (b't', b'topo', False, _(b'show topological heads only')),
3558 3558 (
3559 3559 b'a',
3560 3560 b'active',
3561 3561 False,
3562 3562 _(b'show active branchheads only (DEPRECATED)'),
3563 3563 ),
3564 3564 (b'c', b'closed', False, _(b'show normal and closed branch heads')),
3565 3565 ]
3566 3566 + templateopts,
3567 3567 _(b'[-ct] [-r STARTREV] [REV]...'),
3568 3568 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
3569 3569 intents={INTENT_READONLY},
3570 3570 )
3571 3571 def heads(ui, repo, *branchrevs, **opts):
3572 3572 """show branch heads
3573 3573
3574 3574 With no arguments, show all open branch heads in the repository.
3575 3575 Branch heads are changesets that have no descendants on the
3576 3576 same branch. They are where development generally takes place and
3577 3577 are the usual targets for update and merge operations.
3578 3578
3579 3579 If one or more REVs are given, only open branch heads on the
3580 3580 branches associated with the specified changesets are shown. This
3581 3581 means that you can use :hg:`heads .` to see the heads on the
3582 3582 currently checked-out branch.
3583 3583
3584 3584 If -c/--closed is specified, also show branch heads marked closed
3585 3585 (see :hg:`commit --close-branch`).
3586 3586
3587 3587 If STARTREV is specified, only those heads that are descendants of
3588 3588 STARTREV will be displayed.
3589 3589
3590 3590 If -t/--topo is specified, named branch mechanics will be ignored and only
3591 3591 topological heads (changesets with no children) will be shown.
3592 3592
3593 3593 Returns 0 if matching heads are found, 1 if not.
3594 3594 """
3595 3595
3596 3596 opts = pycompat.byteskwargs(opts)
3597 3597 start = None
3598 3598 rev = opts.get(b'rev')
3599 3599 if rev:
3600 3600 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
3601 3601 start = scmutil.revsingle(repo, rev, None).node()
3602 3602
3603 3603 if opts.get(b'topo'):
3604 3604 heads = [repo[h] for h in repo.heads(start)]
3605 3605 else:
3606 3606 heads = []
3607 3607 for branch in repo.branchmap():
3608 3608 heads += repo.branchheads(branch, start, opts.get(b'closed'))
3609 3609 heads = [repo[h] for h in heads]
3610 3610
3611 3611 if branchrevs:
3612 3612 branches = {
3613 3613 repo[r].branch() for r in scmutil.revrange(repo, branchrevs)
3614 3614 }
3615 3615 heads = [h for h in heads if h.branch() in branches]
3616 3616
3617 3617 if opts.get(b'active') and branchrevs:
3618 3618 dagheads = repo.heads(start)
3619 3619 heads = [h for h in heads if h.node() in dagheads]
3620 3620
3621 3621 if branchrevs:
3622 3622 haveheads = {h.branch() for h in heads}
3623 3623 if branches - haveheads:
3624 3624 headless = b', '.join(b for b in branches - haveheads)
3625 3625 msg = _(b'no open branch heads found on branches %s')
3626 3626 if opts.get(b'rev'):
3627 3627 msg += _(b' (started at %s)') % opts[b'rev']
3628 3628 ui.warn((msg + b'\n') % headless)
3629 3629
3630 3630 if not heads:
3631 3631 return 1
3632 3632
3633 3633 ui.pager(b'heads')
3634 3634 heads = sorted(heads, key=lambda x: -(x.rev()))
3635 3635 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
3636 3636 for ctx in heads:
3637 3637 displayer.show(ctx)
3638 3638 displayer.close()
3639 3639
3640 3640
3641 3641 @command(
3642 3642 b'help',
3643 3643 [
3644 3644 (b'e', b'extension', None, _(b'show only help for extensions')),
3645 3645 (b'c', b'command', None, _(b'show only help for commands')),
3646 3646 (b'k', b'keyword', None, _(b'show topics matching keyword')),
3647 3647 (
3648 3648 b's',
3649 3649 b'system',
3650 3650 [],
3651 3651 _(b'show help for specific platform(s)'),
3652 3652 _(b'PLATFORM'),
3653 3653 ),
3654 3654 ],
3655 3655 _(b'[-eck] [-s PLATFORM] [TOPIC]'),
3656 3656 helpcategory=command.CATEGORY_HELP,
3657 3657 norepo=True,
3658 3658 intents={INTENT_READONLY},
3659 3659 )
3660 3660 def help_(ui, name=None, **opts):
3661 3661 """show help for a given topic or a help overview
3662 3662
3663 3663 With no arguments, print a list of commands with short help messages.
3664 3664
3665 3665 Given a topic, extension, or command name, print help for that
3666 3666 topic.
3667 3667
3668 3668 Returns 0 if successful.
3669 3669 """
3670 3670
3671 3671 keep = opts.get('system') or []
3672 3672 if len(keep) == 0:
3673 3673 if pycompat.sysplatform.startswith(b'win'):
3674 3674 keep.append(b'windows')
3675 3675 elif pycompat.sysplatform == b'OpenVMS':
3676 3676 keep.append(b'vms')
3677 3677 elif pycompat.sysplatform == b'plan9':
3678 3678 keep.append(b'plan9')
3679 3679 else:
3680 3680 keep.append(b'unix')
3681 3681 keep.append(pycompat.sysplatform.lower())
3682 3682 if ui.verbose:
3683 3683 keep.append(b'verbose')
3684 3684
3685 3685 commands = sys.modules[__name__]
3686 3686 formatted = help.formattedhelp(ui, commands, name, keep=keep, **opts)
3687 3687 ui.pager(b'help')
3688 3688 ui.write(formatted)
3689 3689
3690 3690
3691 3691 @command(
3692 3692 b'identify|id',
3693 3693 [
3694 3694 (b'r', b'rev', b'', _(b'identify the specified revision'), _(b'REV')),
3695 3695 (b'n', b'num', None, _(b'show local revision number')),
3696 3696 (b'i', b'id', None, _(b'show global revision id')),
3697 3697 (b'b', b'branch', None, _(b'show branch')),
3698 3698 (b't', b'tags', None, _(b'show tags')),
3699 3699 (b'B', b'bookmarks', None, _(b'show bookmarks')),
3700 3700 ]
3701 3701 + remoteopts
3702 3702 + formatteropts,
3703 3703 _(b'[-nibtB] [-r REV] [SOURCE]'),
3704 3704 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
3705 3705 optionalrepo=True,
3706 3706 intents={INTENT_READONLY},
3707 3707 )
3708 3708 def identify(
3709 3709 ui,
3710 3710 repo,
3711 3711 source=None,
3712 3712 rev=None,
3713 3713 num=None,
3714 3714 id=None,
3715 3715 branch=None,
3716 3716 tags=None,
3717 3717 bookmarks=None,
3718 3718 **opts
3719 3719 ):
3720 3720 """identify the working directory or specified revision
3721 3721
3722 3722 Print a summary identifying the repository state at REV using one or
3723 3723 two parent hash identifiers, followed by a "+" if the working
3724 3724 directory has uncommitted changes, the branch name (if not default),
3725 3725 a list of tags, and a list of bookmarks.
3726 3726
3727 3727 When REV is not given, print a summary of the current state of the
3728 3728 repository including the working directory. Specify -r. to get information
3729 3729 of the working directory parent without scanning uncommitted changes.
3730 3730
3731 3731 Specifying a path to a repository root or Mercurial bundle will
3732 3732 cause lookup to operate on that repository/bundle.
3733 3733
3734 3734 .. container:: verbose
3735 3735
3736 3736 Template:
3737 3737
3738 3738 The following keywords are supported in addition to the common template
3739 3739 keywords and functions. See also :hg:`help templates`.
3740 3740
3741 3741 :dirty: String. Character ``+`` denoting if the working directory has
3742 3742 uncommitted changes.
3743 3743 :id: String. One or two nodes, optionally followed by ``+``.
3744 3744 :parents: List of strings. Parent nodes of the changeset.
3745 3745
3746 3746 Examples:
3747 3747
3748 3748 - generate a build identifier for the working directory::
3749 3749
3750 3750 hg id --id > build-id.dat
3751 3751
3752 3752 - find the revision corresponding to a tag::
3753 3753
3754 3754 hg id -n -r 1.3
3755 3755
3756 3756 - check the most recent revision of a remote repository::
3757 3757
3758 3758 hg id -r tip https://www.mercurial-scm.org/repo/hg/
3759 3759
3760 3760 See :hg:`log` for generating more information about specific revisions,
3761 3761 including full hash identifiers.
3762 3762
3763 3763 Returns 0 if successful.
3764 3764 """
3765 3765
3766 3766 opts = pycompat.byteskwargs(opts)
3767 3767 if not repo and not source:
3768 3768 raise error.Abort(
3769 3769 _(b"there is no Mercurial repository here (.hg not found)")
3770 3770 )
3771 3771
3772 3772 default = not (num or id or branch or tags or bookmarks)
3773 3773 output = []
3774 3774 revs = []
3775 3775
3776 3776 if source:
3777 3777 source, branches = hg.parseurl(ui.expandpath(source))
3778 3778 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
3779 3779 repo = peer.local()
3780 3780 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
3781 3781
3782 3782 fm = ui.formatter(b'identify', opts)
3783 3783 fm.startitem()
3784 3784
3785 3785 if not repo:
3786 3786 if num or branch or tags:
3787 3787 raise error.Abort(
3788 3788 _(b"can't query remote revision number, branch, or tags")
3789 3789 )
3790 3790 if not rev and revs:
3791 3791 rev = revs[0]
3792 3792 if not rev:
3793 3793 rev = b"tip"
3794 3794
3795 3795 remoterev = peer.lookup(rev)
3796 3796 hexrev = fm.hexfunc(remoterev)
3797 3797 if default or id:
3798 3798 output = [hexrev]
3799 3799 fm.data(id=hexrev)
3800 3800
3801 3801 @util.cachefunc
3802 3802 def getbms():
3803 3803 bms = []
3804 3804
3805 3805 if b'bookmarks' in peer.listkeys(b'namespaces'):
3806 3806 hexremoterev = hex(remoterev)
3807 3807 bms = [
3808 3808 bm
3809 3809 for bm, bmr in pycompat.iteritems(
3810 3810 peer.listkeys(b'bookmarks')
3811 3811 )
3812 3812 if bmr == hexremoterev
3813 3813 ]
3814 3814
3815 3815 return sorted(bms)
3816 3816
3817 3817 if fm.isplain():
3818 3818 if bookmarks:
3819 3819 output.extend(getbms())
3820 3820 elif default and not ui.quiet:
3821 3821 # multiple bookmarks for a single parent separated by '/'
3822 3822 bm = b'/'.join(getbms())
3823 3823 if bm:
3824 3824 output.append(bm)
3825 3825 else:
3826 3826 fm.data(node=hex(remoterev))
3827 3827 if bookmarks or b'bookmarks' in fm.datahint():
3828 3828 fm.data(bookmarks=fm.formatlist(getbms(), name=b'bookmark'))
3829 3829 else:
3830 3830 if rev:
3831 3831 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
3832 3832 ctx = scmutil.revsingle(repo, rev, None)
3833 3833
3834 3834 if ctx.rev() is None:
3835 3835 ctx = repo[None]
3836 3836 parents = ctx.parents()
3837 3837 taglist = []
3838 3838 for p in parents:
3839 3839 taglist.extend(p.tags())
3840 3840
3841 3841 dirty = b""
3842 3842 if ctx.dirty(missing=True, merge=False, branch=False):
3843 3843 dirty = b'+'
3844 3844 fm.data(dirty=dirty)
3845 3845
3846 3846 hexoutput = [fm.hexfunc(p.node()) for p in parents]
3847 3847 if default or id:
3848 3848 output = [b"%s%s" % (b'+'.join(hexoutput), dirty)]
3849 3849 fm.data(id=b"%s%s" % (b'+'.join(hexoutput), dirty))
3850 3850
3851 3851 if num:
3852 3852 numoutput = [b"%d" % p.rev() for p in parents]
3853 3853 output.append(b"%s%s" % (b'+'.join(numoutput), dirty))
3854 3854
3855 3855 fm.data(
3856 3856 parents=fm.formatlist(
3857 3857 [fm.hexfunc(p.node()) for p in parents], name=b'node'
3858 3858 )
3859 3859 )
3860 3860 else:
3861 3861 hexoutput = fm.hexfunc(ctx.node())
3862 3862 if default or id:
3863 3863 output = [hexoutput]
3864 3864 fm.data(id=hexoutput)
3865 3865
3866 3866 if num:
3867 3867 output.append(pycompat.bytestr(ctx.rev()))
3868 3868 taglist = ctx.tags()
3869 3869
3870 3870 if default and not ui.quiet:
3871 3871 b = ctx.branch()
3872 3872 if b != b'default':
3873 3873 output.append(b"(%s)" % b)
3874 3874
3875 3875 # multiple tags for a single parent separated by '/'
3876 3876 t = b'/'.join(taglist)
3877 3877 if t:
3878 3878 output.append(t)
3879 3879
3880 3880 # multiple bookmarks for a single parent separated by '/'
3881 3881 bm = b'/'.join(ctx.bookmarks())
3882 3882 if bm:
3883 3883 output.append(bm)
3884 3884 else:
3885 3885 if branch:
3886 3886 output.append(ctx.branch())
3887 3887
3888 3888 if tags:
3889 3889 output.extend(taglist)
3890 3890
3891 3891 if bookmarks:
3892 3892 output.extend(ctx.bookmarks())
3893 3893
3894 3894 fm.data(node=ctx.hex())
3895 3895 fm.data(branch=ctx.branch())
3896 3896 fm.data(tags=fm.formatlist(taglist, name=b'tag', sep=b':'))
3897 3897 fm.data(bookmarks=fm.formatlist(ctx.bookmarks(), name=b'bookmark'))
3898 3898 fm.context(ctx=ctx)
3899 3899
3900 3900 fm.plain(b"%s\n" % b' '.join(output))
3901 3901 fm.end()
3902 3902
3903 3903
3904 3904 @command(
3905 3905 b'import|patch',
3906 3906 [
3907 3907 (
3908 3908 b'p',
3909 3909 b'strip',
3910 3910 1,
3911 3911 _(
3912 3912 b'directory strip option for patch. This has the same '
3913 3913 b'meaning as the corresponding patch option'
3914 3914 ),
3915 3915 _(b'NUM'),
3916 3916 ),
3917 3917 (b'b', b'base', b'', _(b'base path (DEPRECATED)'), _(b'PATH')),
3918 3918 (b'', b'secret', None, _(b'use the secret phase for committing')),
3919 3919 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
3920 3920 (
3921 3921 b'f',
3922 3922 b'force',
3923 3923 None,
3924 3924 _(b'skip check for outstanding uncommitted changes (DEPRECATED)'),
3925 3925 ),
3926 3926 (
3927 3927 b'',
3928 3928 b'no-commit',
3929 3929 None,
3930 3930 _(b"don't commit, just update the working directory"),
3931 3931 ),
3932 3932 (
3933 3933 b'',
3934 3934 b'bypass',
3935 3935 None,
3936 3936 _(b"apply patch without touching the working directory"),
3937 3937 ),
3938 3938 (b'', b'partial', None, _(b'commit even if some hunks fail')),
3939 3939 (b'', b'exact', None, _(b'abort if patch would apply lossily')),
3940 3940 (b'', b'prefix', b'', _(b'apply patch to subdirectory'), _(b'DIR')),
3941 3941 (
3942 3942 b'',
3943 3943 b'import-branch',
3944 3944 None,
3945 3945 _(b'use any branch information in patch (implied by --exact)'),
3946 3946 ),
3947 3947 ]
3948 3948 + commitopts
3949 3949 + commitopts2
3950 3950 + similarityopts,
3951 3951 _(b'[OPTION]... PATCH...'),
3952 3952 helpcategory=command.CATEGORY_IMPORT_EXPORT,
3953 3953 )
3954 3954 def import_(ui, repo, patch1=None, *patches, **opts):
3955 3955 """import an ordered set of patches
3956 3956
3957 3957 Import a list of patches and commit them individually (unless
3958 3958 --no-commit is specified).
3959 3959
3960 3960 To read a patch from standard input (stdin), use "-" as the patch
3961 3961 name. If a URL is specified, the patch will be downloaded from
3962 3962 there.
3963 3963
3964 3964 Import first applies changes to the working directory (unless
3965 3965 --bypass is specified), import will abort if there are outstanding
3966 3966 changes.
3967 3967
3968 3968 Use --bypass to apply and commit patches directly to the
3969 3969 repository, without affecting the working directory. Without
3970 3970 --exact, patches will be applied on top of the working directory
3971 3971 parent revision.
3972 3972
3973 3973 You can import a patch straight from a mail message. Even patches
3974 3974 as attachments work (to use the body part, it must have type
3975 3975 text/plain or text/x-patch). From and Subject headers of email
3976 3976 message are used as default committer and commit message. All
3977 3977 text/plain body parts before first diff are added to the commit
3978 3978 message.
3979 3979
3980 3980 If the imported patch was generated by :hg:`export`, user and
3981 3981 description from patch override values from message headers and
3982 3982 body. Values given on command line with -m/--message and -u/--user
3983 3983 override these.
3984 3984
3985 3985 If --exact is specified, import will set the working directory to
3986 3986 the parent of each patch before applying it, and will abort if the
3987 3987 resulting changeset has a different ID than the one recorded in
3988 3988 the patch. This will guard against various ways that portable
3989 3989 patch formats and mail systems might fail to transfer Mercurial
3990 3990 data or metadata. See :hg:`bundle` for lossless transmission.
3991 3991
3992 3992 Use --partial to ensure a changeset will be created from the patch
3993 3993 even if some hunks fail to apply. Hunks that fail to apply will be
3994 3994 written to a <target-file>.rej file. Conflicts can then be resolved
3995 3995 by hand before :hg:`commit --amend` is run to update the created
3996 3996 changeset. This flag exists to let people import patches that
3997 3997 partially apply without losing the associated metadata (author,
3998 3998 date, description, ...).
3999 3999
4000 4000 .. note::
4001 4001
4002 4002 When no hunks apply cleanly, :hg:`import --partial` will create
4003 4003 an empty changeset, importing only the patch metadata.
4004 4004
4005 4005 With -s/--similarity, hg will attempt to discover renames and
4006 4006 copies in the patch in the same way as :hg:`addremove`.
4007 4007
4008 4008 It is possible to use external patch programs to perform the patch
4009 4009 by setting the ``ui.patch`` configuration option. For the default
4010 4010 internal tool, the fuzz can also be configured via ``patch.fuzz``.
4011 4011 See :hg:`help config` for more information about configuration
4012 4012 files and how to use these options.
4013 4013
4014 4014 See :hg:`help dates` for a list of formats valid for -d/--date.
4015 4015
4016 4016 .. container:: verbose
4017 4017
4018 4018 Examples:
4019 4019
4020 4020 - import a traditional patch from a website and detect renames::
4021 4021
4022 4022 hg import -s 80 http://example.com/bugfix.patch
4023 4023
4024 4024 - import a changeset from an hgweb server::
4025 4025
4026 4026 hg import https://www.mercurial-scm.org/repo/hg/rev/5ca8c111e9aa
4027 4027
4028 4028 - import all the patches in an Unix-style mbox::
4029 4029
4030 4030 hg import incoming-patches.mbox
4031 4031
4032 4032 - import patches from stdin::
4033 4033
4034 4034 hg import -
4035 4035
4036 4036 - attempt to exactly restore an exported changeset (not always
4037 4037 possible)::
4038 4038
4039 4039 hg import --exact proposed-fix.patch
4040 4040
4041 4041 - use an external tool to apply a patch which is too fuzzy for
4042 4042 the default internal tool.
4043 4043
4044 4044 hg import --config ui.patch="patch --merge" fuzzy.patch
4045 4045
4046 4046 - change the default fuzzing from 2 to a less strict 7
4047 4047
4048 4048 hg import --config ui.fuzz=7 fuzz.patch
4049 4049
4050 4050 Returns 0 on success, 1 on partial success (see --partial).
4051 4051 """
4052 4052
4053 4053 cmdutil.check_incompatible_arguments(
4054 4054 opts, 'no_commit', ['bypass', 'secret']
4055 4055 )
4056 4056 cmdutil.check_incompatible_arguments(opts, 'exact', ['edit', 'prefix'])
4057 4057 opts = pycompat.byteskwargs(opts)
4058 4058 if not patch1:
4059 4059 raise error.Abort(_(b'need at least one patch to import'))
4060 4060
4061 4061 patches = (patch1,) + patches
4062 4062
4063 4063 date = opts.get(b'date')
4064 4064 if date:
4065 4065 opts[b'date'] = dateutil.parsedate(date)
4066 4066
4067 4067 exact = opts.get(b'exact')
4068 4068 update = not opts.get(b'bypass')
4069 4069 try:
4070 4070 sim = float(opts.get(b'similarity') or 0)
4071 4071 except ValueError:
4072 4072 raise error.Abort(_(b'similarity must be a number'))
4073 4073 if sim < 0 or sim > 100:
4074 4074 raise error.Abort(_(b'similarity must be between 0 and 100'))
4075 4075 if sim and not update:
4076 4076 raise error.Abort(_(b'cannot use --similarity with --bypass'))
4077 4077
4078 4078 base = opts[b"base"]
4079 4079 msgs = []
4080 4080 ret = 0
4081 4081
4082 4082 with repo.wlock():
4083 4083 if update:
4084 4084 cmdutil.checkunfinished(repo)
4085 4085 if exact or not opts.get(b'force'):
4086 4086 cmdutil.bailifchanged(repo)
4087 4087
4088 4088 if not opts.get(b'no_commit'):
4089 4089 lock = repo.lock
4090 4090 tr = lambda: repo.transaction(b'import')
4091 4091 dsguard = util.nullcontextmanager
4092 4092 else:
4093 4093 lock = util.nullcontextmanager
4094 4094 tr = util.nullcontextmanager
4095 4095 dsguard = lambda: dirstateguard.dirstateguard(repo, b'import')
4096 4096 with lock(), tr(), dsguard():
4097 4097 parents = repo[None].parents()
4098 4098 for patchurl in patches:
4099 4099 if patchurl == b'-':
4100 4100 ui.status(_(b'applying patch from stdin\n'))
4101 4101 patchfile = ui.fin
4102 4102 patchurl = b'stdin' # for error message
4103 4103 else:
4104 4104 patchurl = os.path.join(base, patchurl)
4105 4105 ui.status(_(b'applying %s\n') % patchurl)
4106 4106 patchfile = hg.openpath(ui, patchurl, sendaccept=False)
4107 4107
4108 4108 haspatch = False
4109 4109 for hunk in patch.split(patchfile):
4110 4110 with patch.extract(ui, hunk) as patchdata:
4111 4111 msg, node, rej = cmdutil.tryimportone(
4112 4112 ui, repo, patchdata, parents, opts, msgs, hg.clean
4113 4113 )
4114 4114 if msg:
4115 4115 haspatch = True
4116 4116 ui.note(msg + b'\n')
4117 4117 if update or exact:
4118 4118 parents = repo[None].parents()
4119 4119 else:
4120 4120 parents = [repo[node]]
4121 4121 if rej:
4122 4122 ui.write_err(_(b"patch applied partially\n"))
4123 4123 ui.write_err(
4124 4124 _(
4125 4125 b"(fix the .rej files and run "
4126 4126 b"`hg commit --amend`)\n"
4127 4127 )
4128 4128 )
4129 4129 ret = 1
4130 4130 break
4131 4131
4132 4132 if not haspatch:
4133 4133 raise error.Abort(_(b'%s: no diffs found') % patchurl)
4134 4134
4135 4135 if msgs:
4136 4136 repo.savecommitmessage(b'\n* * *\n'.join(msgs))
4137 4137 return ret
4138 4138
4139 4139
4140 4140 @command(
4141 4141 b'incoming|in',
4142 4142 [
4143 4143 (
4144 4144 b'f',
4145 4145 b'force',
4146 4146 None,
4147 4147 _(b'run even if remote repository is unrelated'),
4148 4148 ),
4149 4149 (b'n', b'newest-first', None, _(b'show newest record first')),
4150 4150 (b'', b'bundle', b'', _(b'file to store the bundles into'), _(b'FILE')),
4151 4151 (
4152 4152 b'r',
4153 4153 b'rev',
4154 4154 [],
4155 4155 _(b'a remote changeset intended to be added'),
4156 4156 _(b'REV'),
4157 4157 ),
4158 4158 (b'B', b'bookmarks', False, _(b"compare bookmarks")),
4159 4159 (
4160 4160 b'b',
4161 4161 b'branch',
4162 4162 [],
4163 4163 _(b'a specific branch you would like to pull'),
4164 4164 _(b'BRANCH'),
4165 4165 ),
4166 4166 ]
4167 4167 + logopts
4168 4168 + remoteopts
4169 4169 + subrepoopts,
4170 4170 _(b'[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'),
4171 4171 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
4172 4172 )
4173 4173 def incoming(ui, repo, source=b"default", **opts):
4174 4174 """show new changesets found in source
4175 4175
4176 4176 Show new changesets found in the specified path/URL or the default
4177 4177 pull location. These are the changesets that would have been pulled
4178 4178 by :hg:`pull` at the time you issued this command.
4179 4179
4180 4180 See pull for valid source format details.
4181 4181
4182 4182 .. container:: verbose
4183 4183
4184 4184 With -B/--bookmarks, the result of bookmark comparison between
4185 4185 local and remote repositories is displayed. With -v/--verbose,
4186 4186 status is also displayed for each bookmark like below::
4187 4187
4188 4188 BM1 01234567890a added
4189 4189 BM2 1234567890ab advanced
4190 4190 BM3 234567890abc diverged
4191 4191 BM4 34567890abcd changed
4192 4192
4193 4193 The action taken locally when pulling depends on the
4194 4194 status of each bookmark:
4195 4195
4196 4196 :``added``: pull will create it
4197 4197 :``advanced``: pull will update it
4198 4198 :``diverged``: pull will create a divergent bookmark
4199 4199 :``changed``: result depends on remote changesets
4200 4200
4201 4201 From the point of view of pulling behavior, bookmark
4202 4202 existing only in the remote repository are treated as ``added``,
4203 4203 even if it is in fact locally deleted.
4204 4204
4205 4205 .. container:: verbose
4206 4206
4207 4207 For remote repository, using --bundle avoids downloading the
4208 4208 changesets twice if the incoming is followed by a pull.
4209 4209
4210 4210 Examples:
4211 4211
4212 4212 - show incoming changes with patches and full description::
4213 4213
4214 4214 hg incoming -vp
4215 4215
4216 4216 - show incoming changes excluding merges, store a bundle::
4217 4217
4218 4218 hg in -vpM --bundle incoming.hg
4219 4219 hg pull incoming.hg
4220 4220
4221 4221 - briefly list changes inside a bundle::
4222 4222
4223 4223 hg in changes.hg -T "{desc|firstline}\\n"
4224 4224
4225 4225 Returns 0 if there are incoming changes, 1 otherwise.
4226 4226 """
4227 4227 opts = pycompat.byteskwargs(opts)
4228 4228 if opts.get(b'graph'):
4229 4229 logcmdutil.checkunsupportedgraphflags([], opts)
4230 4230
4231 4231 def display(other, chlist, displayer):
4232 4232 revdag = logcmdutil.graphrevs(other, chlist, opts)
4233 4233 logcmdutil.displaygraph(
4234 4234 ui, repo, revdag, displayer, graphmod.asciiedges
4235 4235 )
4236 4236
4237 4237 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
4238 4238 return 0
4239 4239
4240 4240 cmdutil.check_incompatible_arguments(opts, b'subrepos', [b'bundle'])
4241 4241
4242 4242 if opts.get(b'bookmarks'):
4243 4243 source, branches = hg.parseurl(
4244 4244 ui.expandpath(source), opts.get(b'branch')
4245 4245 )
4246 4246 other = hg.peer(repo, opts, source)
4247 4247 if b'bookmarks' not in other.listkeys(b'namespaces'):
4248 4248 ui.warn(_(b"remote doesn't support bookmarks\n"))
4249 4249 return 0
4250 4250 ui.pager(b'incoming')
4251 4251 ui.status(_(b'comparing with %s\n') % util.hidepassword(source))
4252 4252 return bookmarks.incoming(ui, repo, other)
4253 4253
4254 4254 repo._subtoppath = ui.expandpath(source)
4255 4255 try:
4256 4256 return hg.incoming(ui, repo, source, opts)
4257 4257 finally:
4258 4258 del repo._subtoppath
4259 4259
4260 4260
4261 4261 @command(
4262 4262 b'init',
4263 4263 remoteopts,
4264 4264 _(b'[-e CMD] [--remotecmd CMD] [DEST]'),
4265 4265 helpcategory=command.CATEGORY_REPO_CREATION,
4266 4266 helpbasic=True,
4267 4267 norepo=True,
4268 4268 )
4269 4269 def init(ui, dest=b".", **opts):
4270 4270 """create a new repository in the given directory
4271 4271
4272 4272 Initialize a new repository in the given directory. If the given
4273 4273 directory does not exist, it will be created.
4274 4274
4275 4275 If no directory is given, the current directory is used.
4276 4276
4277 4277 It is possible to specify an ``ssh://`` URL as the destination.
4278 4278 See :hg:`help urls` for more information.
4279 4279
4280 4280 Returns 0 on success.
4281 4281 """
4282 4282 opts = pycompat.byteskwargs(opts)
4283 4283 hg.peer(ui, opts, ui.expandpath(dest), create=True)
4284 4284
4285 4285
4286 4286 @command(
4287 4287 b'locate',
4288 4288 [
4289 4289 (
4290 4290 b'r',
4291 4291 b'rev',
4292 4292 b'',
4293 4293 _(b'search the repository as it is in REV'),
4294 4294 _(b'REV'),
4295 4295 ),
4296 4296 (
4297 4297 b'0',
4298 4298 b'print0',
4299 4299 None,
4300 4300 _(b'end filenames with NUL, for use with xargs'),
4301 4301 ),
4302 4302 (
4303 4303 b'f',
4304 4304 b'fullpath',
4305 4305 None,
4306 4306 _(b'print complete paths from the filesystem root'),
4307 4307 ),
4308 4308 ]
4309 4309 + walkopts,
4310 4310 _(b'[OPTION]... [PATTERN]...'),
4311 4311 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
4312 4312 )
4313 4313 def locate(ui, repo, *pats, **opts):
4314 4314 """locate files matching specific patterns (DEPRECATED)
4315 4315
4316 4316 Print files under Mercurial control in the working directory whose
4317 4317 names match the given patterns.
4318 4318
4319 4319 By default, this command searches all directories in the working
4320 4320 directory. To search just the current directory and its
4321 4321 subdirectories, use "--include .".
4322 4322
4323 4323 If no patterns are given to match, this command prints the names
4324 4324 of all files under Mercurial control in the working directory.
4325 4325
4326 4326 If you want to feed the output of this command into the "xargs"
4327 4327 command, use the -0 option to both this command and "xargs". This
4328 4328 will avoid the problem of "xargs" treating single filenames that
4329 4329 contain whitespace as multiple filenames.
4330 4330
4331 4331 See :hg:`help files` for a more versatile command.
4332 4332
4333 4333 Returns 0 if a match is found, 1 otherwise.
4334 4334 """
4335 4335 opts = pycompat.byteskwargs(opts)
4336 4336 if opts.get(b'print0'):
4337 4337 end = b'\0'
4338 4338 else:
4339 4339 end = b'\n'
4340 4340 ctx = scmutil.revsingle(repo, opts.get(b'rev'), None)
4341 4341
4342 4342 ret = 1
4343 4343 m = scmutil.match(
4344 4344 ctx, pats, opts, default=b'relglob', badfn=lambda x, y: False
4345 4345 )
4346 4346
4347 4347 ui.pager(b'locate')
4348 4348 if ctx.rev() is None:
4349 4349 # When run on the working copy, "locate" includes removed files, so
4350 4350 # we get the list of files from the dirstate.
4351 4351 filesgen = sorted(repo.dirstate.matches(m))
4352 4352 else:
4353 4353 filesgen = ctx.matches(m)
4354 4354 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=bool(pats))
4355 4355 for abs in filesgen:
4356 4356 if opts.get(b'fullpath'):
4357 4357 ui.write(repo.wjoin(abs), end)
4358 4358 else:
4359 4359 ui.write(uipathfn(abs), end)
4360 4360 ret = 0
4361 4361
4362 4362 return ret
4363 4363
4364 4364
4365 4365 @command(
4366 4366 b'log|history',
4367 4367 [
4368 4368 (
4369 4369 b'f',
4370 4370 b'follow',
4371 4371 None,
4372 4372 _(
4373 4373 b'follow changeset history, or file history across copies and renames'
4374 4374 ),
4375 4375 ),
4376 4376 (
4377 4377 b'',
4378 4378 b'follow-first',
4379 4379 None,
4380 4380 _(b'only follow the first parent of merge changesets (DEPRECATED)'),
4381 4381 ),
4382 4382 (
4383 4383 b'd',
4384 4384 b'date',
4385 4385 b'',
4386 4386 _(b'show revisions matching date spec'),
4387 4387 _(b'DATE'),
4388 4388 ),
4389 4389 (b'C', b'copies', None, _(b'show copied files')),
4390 4390 (
4391 4391 b'k',
4392 4392 b'keyword',
4393 4393 [],
4394 4394 _(b'do case-insensitive search for a given text'),
4395 4395 _(b'TEXT'),
4396 4396 ),
4397 4397 (
4398 4398 b'r',
4399 4399 b'rev',
4400 4400 [],
4401 4401 _(b'show the specified revision or revset'),
4402 4402 _(b'REV'),
4403 4403 ),
4404 4404 (
4405 4405 b'L',
4406 4406 b'line-range',
4407 4407 [],
4408 4408 _(b'follow line range of specified file (EXPERIMENTAL)'),
4409 4409 _(b'FILE,RANGE'),
4410 4410 ),
4411 4411 (
4412 4412 b'',
4413 4413 b'removed',
4414 4414 None,
4415 4415 _(b'include revisions where files were removed'),
4416 4416 ),
4417 4417 (
4418 4418 b'm',
4419 4419 b'only-merges',
4420 4420 None,
4421 4421 _(b'show only merges (DEPRECATED) (use -r "merge()" instead)'),
4422 4422 ),
4423 4423 (b'u', b'user', [], _(b'revisions committed by user'), _(b'USER')),
4424 4424 (
4425 4425 b'',
4426 4426 b'only-branch',
4427 4427 [],
4428 4428 _(
4429 4429 b'show only changesets within the given named branch (DEPRECATED)'
4430 4430 ),
4431 4431 _(b'BRANCH'),
4432 4432 ),
4433 4433 (
4434 4434 b'b',
4435 4435 b'branch',
4436 4436 [],
4437 4437 _(b'show changesets within the given named branch'),
4438 4438 _(b'BRANCH'),
4439 4439 ),
4440 4440 (
4441 4441 b'P',
4442 4442 b'prune',
4443 4443 [],
4444 4444 _(b'do not display revision or any of its ancestors'),
4445 4445 _(b'REV'),
4446 4446 ),
4447 4447 ]
4448 4448 + logopts
4449 4449 + walkopts,
4450 4450 _(b'[OPTION]... [FILE]'),
4451 4451 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
4452 4452 helpbasic=True,
4453 4453 inferrepo=True,
4454 4454 intents={INTENT_READONLY},
4455 4455 )
4456 4456 def log(ui, repo, *pats, **opts):
4457 4457 """show revision history of entire repository or files
4458 4458
4459 4459 Print the revision history of the specified files or the entire
4460 4460 project.
4461 4461
4462 4462 If no revision range is specified, the default is ``tip:0`` unless
4463 4463 --follow is set, in which case the working directory parent is
4464 4464 used as the starting revision.
4465 4465
4466 4466 File history is shown without following rename or copy history of
4467 4467 files. Use -f/--follow with a filename to follow history across
4468 4468 renames and copies. --follow without a filename will only show
4469 4469 ancestors of the starting revision.
4470 4470
4471 4471 By default this command prints revision number and changeset id,
4472 4472 tags, non-trivial parents, user, date and time, and a summary for
4473 4473 each commit. When the -v/--verbose switch is used, the list of
4474 4474 changed files and full commit message are shown.
4475 4475
4476 4476 With --graph the revisions are shown as an ASCII art DAG with the most
4477 4477 recent changeset at the top.
4478 4478 'o' is a changeset, '@' is a working directory parent, '%' is a changeset
4479 4479 involved in an unresolved merge conflict, '_' closes a branch,
4480 4480 'x' is obsolete, '*' is unstable, and '+' represents a fork where the
4481 4481 changeset from the lines below is a parent of the 'o' merge on the same
4482 4482 line.
4483 4483 Paths in the DAG are represented with '|', '/' and so forth. ':' in place
4484 4484 of a '|' indicates one or more revisions in a path are omitted.
4485 4485
4486 4486 .. container:: verbose
4487 4487
4488 4488 Use -L/--line-range FILE,M:N options to follow the history of lines
4489 4489 from M to N in FILE. With -p/--patch only diff hunks affecting
4490 4490 specified line range will be shown. This option requires --follow;
4491 4491 it can be specified multiple times. Currently, this option is not
4492 4492 compatible with --graph. This option is experimental.
4493 4493
4494 4494 .. note::
4495 4495
4496 4496 :hg:`log --patch` may generate unexpected diff output for merge
4497 4497 changesets, as it will only compare the merge changeset against
4498 4498 its first parent. Also, only files different from BOTH parents
4499 4499 will appear in files:.
4500 4500
4501 4501 .. note::
4502 4502
4503 4503 For performance reasons, :hg:`log FILE` may omit duplicate changes
4504 4504 made on branches and will not show removals or mode changes. To
4505 4505 see all such changes, use the --removed switch.
4506 4506
4507 4507 .. container:: verbose
4508 4508
4509 4509 .. note::
4510 4510
4511 4511 The history resulting from -L/--line-range options depends on diff
4512 4512 options; for instance if white-spaces are ignored, respective changes
4513 4513 with only white-spaces in specified line range will not be listed.
4514 4514
4515 4515 .. container:: verbose
4516 4516
4517 4517 Some examples:
4518 4518
4519 4519 - changesets with full descriptions and file lists::
4520 4520
4521 4521 hg log -v
4522 4522
4523 4523 - changesets ancestral to the working directory::
4524 4524
4525 4525 hg log -f
4526 4526
4527 4527 - last 10 commits on the current branch::
4528 4528
4529 4529 hg log -l 10 -b .
4530 4530
4531 4531 - changesets showing all modifications of a file, including removals::
4532 4532
4533 4533 hg log --removed file.c
4534 4534
4535 4535 - all changesets that touch a directory, with diffs, excluding merges::
4536 4536
4537 4537 hg log -Mp lib/
4538 4538
4539 4539 - all revision numbers that match a keyword::
4540 4540
4541 4541 hg log -k bug --template "{rev}\\n"
4542 4542
4543 4543 - the full hash identifier of the working directory parent::
4544 4544
4545 4545 hg log -r . --template "{node}\\n"
4546 4546
4547 4547 - list available log templates::
4548 4548
4549 4549 hg log -T list
4550 4550
4551 4551 - check if a given changeset is included in a tagged release::
4552 4552
4553 4553 hg log -r "a21ccf and ancestor(1.9)"
4554 4554
4555 4555 - find all changesets by some user in a date range::
4556 4556
4557 4557 hg log -k alice -d "may 2008 to jul 2008"
4558 4558
4559 4559 - summary of all changesets after the last tag::
4560 4560
4561 4561 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
4562 4562
4563 4563 - changesets touching lines 13 to 23 for file.c::
4564 4564
4565 4565 hg log -L file.c,13:23
4566 4566
4567 4567 - changesets touching lines 13 to 23 for file.c and lines 2 to 6 of
4568 4568 main.c with patch::
4569 4569
4570 4570 hg log -L file.c,13:23 -L main.c,2:6 -p
4571 4571
4572 4572 See :hg:`help dates` for a list of formats valid for -d/--date.
4573 4573
4574 4574 See :hg:`help revisions` for more about specifying and ordering
4575 4575 revisions.
4576 4576
4577 4577 See :hg:`help templates` for more about pre-packaged styles and
4578 4578 specifying custom templates. The default template used by the log
4579 4579 command can be customized via the ``command-templates.log`` configuration
4580 4580 setting.
4581 4581
4582 4582 Returns 0 on success.
4583 4583
4584 4584 """
4585 4585 opts = pycompat.byteskwargs(opts)
4586 4586 linerange = opts.get(b'line_range')
4587 4587
4588 4588 if linerange and not opts.get(b'follow'):
4589 4589 raise error.Abort(_(b'--line-range requires --follow'))
4590 4590
4591 4591 if linerange and pats:
4592 4592 # TODO: take pats as patterns with no line-range filter
4593 4593 raise error.Abort(
4594 4594 _(b'FILE arguments are not compatible with --line-range option')
4595 4595 )
4596 4596
4597 4597 repo = scmutil.unhidehashlikerevs(repo, opts.get(b'rev'), b'nowarn')
4598 4598 revs, differ = logcmdutil.getrevs(
4599 4599 repo, logcmdutil.parseopts(ui, pats, opts)
4600 4600 )
4601 4601 if linerange:
4602 4602 # TODO: should follow file history from logcmdutil._initialrevs(),
4603 4603 # then filter the result by logcmdutil._makerevset() and --limit
4604 4604 revs, differ = logcmdutil.getlinerangerevs(repo, revs, opts)
4605 4605
4606 4606 getcopies = None
4607 4607 if opts.get(b'copies'):
4608 4608 endrev = None
4609 4609 if revs:
4610 4610 endrev = revs.max() + 1
4611 4611 getcopies = scmutil.getcopiesfn(repo, endrev=endrev)
4612 4612
4613 4613 ui.pager(b'log')
4614 4614 displayer = logcmdutil.changesetdisplayer(
4615 4615 ui, repo, opts, differ, buffered=True
4616 4616 )
4617 4617 if opts.get(b'graph'):
4618 4618 displayfn = logcmdutil.displaygraphrevs
4619 4619 else:
4620 4620 displayfn = logcmdutil.displayrevs
4621 4621 displayfn(ui, repo, revs, displayer, getcopies)
4622 4622
4623 4623
4624 4624 @command(
4625 4625 b'manifest',
4626 4626 [
4627 4627 (b'r', b'rev', b'', _(b'revision to display'), _(b'REV')),
4628 4628 (b'', b'all', False, _(b"list files from all revisions")),
4629 4629 ]
4630 4630 + formatteropts,
4631 4631 _(b'[-r REV]'),
4632 4632 helpcategory=command.CATEGORY_MAINTENANCE,
4633 4633 intents={INTENT_READONLY},
4634 4634 )
4635 4635 def manifest(ui, repo, node=None, rev=None, **opts):
4636 4636 """output the current or given revision of the project manifest
4637 4637
4638 4638 Print a list of version controlled files for the given revision.
4639 4639 If no revision is given, the first parent of the working directory
4640 4640 is used, or the null revision if no revision is checked out.
4641 4641
4642 4642 With -v, print file permissions, symlink and executable bits.
4643 4643 With --debug, print file revision hashes.
4644 4644
4645 4645 If option --all is specified, the list of all files from all revisions
4646 4646 is printed. This includes deleted and renamed files.
4647 4647
4648 4648 Returns 0 on success.
4649 4649 """
4650 4650 opts = pycompat.byteskwargs(opts)
4651 4651 fm = ui.formatter(b'manifest', opts)
4652 4652
4653 4653 if opts.get(b'all'):
4654 4654 if rev or node:
4655 4655 raise error.Abort(_(b"can't specify a revision with --all"))
4656 4656
4657 4657 res = set()
4658 4658 for rev in repo:
4659 4659 ctx = repo[rev]
4660 4660 res |= set(ctx.files())
4661 4661
4662 4662 ui.pager(b'manifest')
4663 4663 for f in sorted(res):
4664 4664 fm.startitem()
4665 4665 fm.write(b"path", b'%s\n', f)
4666 4666 fm.end()
4667 4667 return
4668 4668
4669 4669 if rev and node:
4670 4670 raise error.Abort(_(b"please specify just one revision"))
4671 4671
4672 4672 if not node:
4673 4673 node = rev
4674 4674
4675 4675 char = {b'l': b'@', b'x': b'*', b'': b'', b't': b'd'}
4676 4676 mode = {b'l': b'644', b'x': b'755', b'': b'644', b't': b'755'}
4677 4677 if node:
4678 4678 repo = scmutil.unhidehashlikerevs(repo, [node], b'nowarn')
4679 4679 ctx = scmutil.revsingle(repo, node)
4680 4680 mf = ctx.manifest()
4681 4681 ui.pager(b'manifest')
4682 4682 for f in ctx:
4683 4683 fm.startitem()
4684 4684 fm.context(ctx=ctx)
4685 4685 fl = ctx[f].flags()
4686 4686 fm.condwrite(ui.debugflag, b'hash', b'%s ', hex(mf[f]))
4687 4687 fm.condwrite(ui.verbose, b'mode type', b'%s %1s ', mode[fl], char[fl])
4688 4688 fm.write(b'path', b'%s\n', f)
4689 4689 fm.end()
4690 4690
4691 4691
4692 4692 @command(
4693 4693 b'merge',
4694 4694 [
4695 4695 (
4696 4696 b'f',
4697 4697 b'force',
4698 4698 None,
4699 4699 _(b'force a merge including outstanding changes (DEPRECATED)'),
4700 4700 ),
4701 4701 (b'r', b'rev', b'', _(b'revision to merge'), _(b'REV')),
4702 4702 (
4703 4703 b'P',
4704 4704 b'preview',
4705 4705 None,
4706 4706 _(b'review revisions to merge (no merge is performed)'),
4707 4707 ),
4708 4708 (b'', b'abort', None, _(b'abort the ongoing merge')),
4709 4709 ]
4710 4710 + mergetoolopts,
4711 4711 _(b'[-P] [[-r] REV]'),
4712 4712 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
4713 4713 helpbasic=True,
4714 4714 )
4715 4715 def merge(ui, repo, node=None, **opts):
4716 4716 """merge another revision into working directory
4717 4717
4718 4718 The current working directory is updated with all changes made in
4719 4719 the requested revision since the last common predecessor revision.
4720 4720
4721 4721 Files that changed between either parent are marked as changed for
4722 4722 the next commit and a commit must be performed before any further
4723 4723 updates to the repository are allowed. The next commit will have
4724 4724 two parents.
4725 4725
4726 4726 ``--tool`` can be used to specify the merge tool used for file
4727 4727 merges. It overrides the HGMERGE environment variable and your
4728 4728 configuration files. See :hg:`help merge-tools` for options.
4729 4729
4730 4730 If no revision is specified, the working directory's parent is a
4731 4731 head revision, and the current branch contains exactly one other
4732 4732 head, the other head is merged with by default. Otherwise, an
4733 4733 explicit revision with which to merge must be provided.
4734 4734
4735 4735 See :hg:`help resolve` for information on handling file conflicts.
4736 4736
4737 4737 To undo an uncommitted merge, use :hg:`merge --abort` which
4738 4738 will check out a clean copy of the original merge parent, losing
4739 4739 all changes.
4740 4740
4741 4741 Returns 0 on success, 1 if there are unresolved files.
4742 4742 """
4743 4743
4744 4744 opts = pycompat.byteskwargs(opts)
4745 4745 abort = opts.get(b'abort')
4746 4746 if abort and repo.dirstate.p2() == nullid:
4747 4747 cmdutil.wrongtooltocontinue(repo, _(b'merge'))
4748 4748 cmdutil.check_incompatible_arguments(opts, b'abort', [b'rev', b'preview'])
4749 4749 if abort:
4750 4750 state = cmdutil.getunfinishedstate(repo)
4751 4751 if state and state._opname != b'merge':
4752 4752 raise error.Abort(
4753 4753 _(b'cannot abort merge with %s in progress') % (state._opname),
4754 4754 hint=state.hint(),
4755 4755 )
4756 4756 if node:
4757 4757 raise error.Abort(_(b"cannot specify a node with --abort"))
4758 4758 return hg.abortmerge(repo.ui, repo)
4759 4759
4760 4760 if opts.get(b'rev') and node:
4761 4761 raise error.Abort(_(b"please specify just one revision"))
4762 4762 if not node:
4763 4763 node = opts.get(b'rev')
4764 4764
4765 4765 if node:
4766 4766 ctx = scmutil.revsingle(repo, node)
4767 4767 else:
4768 4768 if ui.configbool(b'commands', b'merge.require-rev'):
4769 4769 raise error.Abort(
4770 4770 _(
4771 4771 b'configuration requires specifying revision to merge '
4772 4772 b'with'
4773 4773 )
4774 4774 )
4775 4775 ctx = repo[destutil.destmerge(repo)]
4776 4776
4777 4777 if ctx.node() is None:
4778 4778 raise error.Abort(_(b'merging with the working copy has no effect'))
4779 4779
4780 4780 if opts.get(b'preview'):
4781 4781 # find nodes that are ancestors of p2 but not of p1
4782 4782 p1 = repo[b'.'].node()
4783 4783 p2 = ctx.node()
4784 4784 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4785 4785
4786 4786 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
4787 4787 for node in nodes:
4788 4788 displayer.show(repo[node])
4789 4789 displayer.close()
4790 4790 return 0
4791 4791
4792 4792 # ui.forcemerge is an internal variable, do not document
4793 4793 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
4794 4794 with ui.configoverride(overrides, b'merge'):
4795 4795 force = opts.get(b'force')
4796 4796 labels = [b'working copy', b'merge rev']
4797 4797 return hg.merge(ctx, force=force, labels=labels)
4798 4798
4799 4799
4800 4800 statemod.addunfinished(
4801 4801 b'merge',
4802 4802 fname=None,
4803 4803 clearable=True,
4804 4804 allowcommit=True,
4805 4805 cmdmsg=_(b'outstanding uncommitted merge'),
4806 4806 abortfunc=hg.abortmerge,
4807 4807 statushint=_(
4808 4808 b'To continue: hg commit\nTo abort: hg merge --abort'
4809 4809 ),
4810 4810 cmdhint=_(b"use 'hg commit' or 'hg merge --abort'"),
4811 4811 )
4812 4812
4813 4813
4814 4814 @command(
4815 4815 b'outgoing|out',
4816 4816 [
4817 4817 (
4818 4818 b'f',
4819 4819 b'force',
4820 4820 None,
4821 4821 _(b'run even when the destination is unrelated'),
4822 4822 ),
4823 4823 (
4824 4824 b'r',
4825 4825 b'rev',
4826 4826 [],
4827 4827 _(b'a changeset intended to be included in the destination'),
4828 4828 _(b'REV'),
4829 4829 ),
4830 4830 (b'n', b'newest-first', None, _(b'show newest record first')),
4831 4831 (b'B', b'bookmarks', False, _(b'compare bookmarks')),
4832 4832 (
4833 4833 b'b',
4834 4834 b'branch',
4835 4835 [],
4836 4836 _(b'a specific branch you would like to push'),
4837 4837 _(b'BRANCH'),
4838 4838 ),
4839 4839 ]
4840 4840 + logopts
4841 4841 + remoteopts
4842 4842 + subrepoopts,
4843 4843 _(b'[-M] [-p] [-n] [-f] [-r REV]... [DEST]'),
4844 4844 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
4845 4845 )
4846 4846 def outgoing(ui, repo, dest=None, **opts):
4847 4847 """show changesets not found in the destination
4848 4848
4849 4849 Show changesets not found in the specified destination repository
4850 4850 or the default push location. These are the changesets that would
4851 4851 be pushed if a push was requested.
4852 4852
4853 4853 See pull for details of valid destination formats.
4854 4854
4855 4855 .. container:: verbose
4856 4856
4857 4857 With -B/--bookmarks, the result of bookmark comparison between
4858 4858 local and remote repositories is displayed. With -v/--verbose,
4859 4859 status is also displayed for each bookmark like below::
4860 4860
4861 4861 BM1 01234567890a added
4862 4862 BM2 deleted
4863 4863 BM3 234567890abc advanced
4864 4864 BM4 34567890abcd diverged
4865 4865 BM5 4567890abcde changed
4866 4866
4867 4867 The action taken when pushing depends on the
4868 4868 status of each bookmark:
4869 4869
4870 4870 :``added``: push with ``-B`` will create it
4871 4871 :``deleted``: push with ``-B`` will delete it
4872 4872 :``advanced``: push will update it
4873 4873 :``diverged``: push with ``-B`` will update it
4874 4874 :``changed``: push with ``-B`` will update it
4875 4875
4876 4876 From the point of view of pushing behavior, bookmarks
4877 4877 existing only in the remote repository are treated as
4878 4878 ``deleted``, even if it is in fact added remotely.
4879 4879
4880 4880 Returns 0 if there are outgoing changes, 1 otherwise.
4881 4881 """
4882 4882 # hg._outgoing() needs to re-resolve the path in order to handle #branch
4883 4883 # style URLs, so don't overwrite dest.
4884 4884 path = ui.paths.getpath(dest, default=(b'default-push', b'default'))
4885 4885 if not path:
4886 4886 raise error.Abort(
4887 4887 _(b'default repository not configured!'),
4888 4888 hint=_(b"see 'hg help config.paths'"),
4889 4889 )
4890 4890
4891 4891 opts = pycompat.byteskwargs(opts)
4892 4892 if opts.get(b'graph'):
4893 4893 logcmdutil.checkunsupportedgraphflags([], opts)
4894 4894 o, other = hg._outgoing(ui, repo, dest, opts)
4895 4895 if not o:
4896 4896 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4897 4897 return
4898 4898
4899 4899 revdag = logcmdutil.graphrevs(repo, o, opts)
4900 4900 ui.pager(b'outgoing')
4901 4901 displayer = logcmdutil.changesetdisplayer(ui, repo, opts, buffered=True)
4902 4902 logcmdutil.displaygraph(
4903 4903 ui, repo, revdag, displayer, graphmod.asciiedges
4904 4904 )
4905 4905 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4906 4906 return 0
4907 4907
4908 4908 if opts.get(b'bookmarks'):
4909 4909 dest = path.pushloc or path.loc
4910 4910 other = hg.peer(repo, opts, dest)
4911 4911 if b'bookmarks' not in other.listkeys(b'namespaces'):
4912 4912 ui.warn(_(b"remote doesn't support bookmarks\n"))
4913 4913 return 0
4914 4914 ui.status(_(b'comparing with %s\n') % util.hidepassword(dest))
4915 4915 ui.pager(b'outgoing')
4916 4916 return bookmarks.outgoing(ui, repo, other)
4917 4917
4918 4918 repo._subtoppath = path.pushloc or path.loc
4919 4919 try:
4920 4920 return hg.outgoing(ui, repo, dest, opts)
4921 4921 finally:
4922 4922 del repo._subtoppath
4923 4923
4924 4924
4925 4925 @command(
4926 4926 b'parents',
4927 4927 [
4928 4928 (
4929 4929 b'r',
4930 4930 b'rev',
4931 4931 b'',
4932 4932 _(b'show parents of the specified revision'),
4933 4933 _(b'REV'),
4934 4934 ),
4935 4935 ]
4936 4936 + templateopts,
4937 4937 _(b'[-r REV] [FILE]'),
4938 4938 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
4939 4939 inferrepo=True,
4940 4940 )
4941 4941 def parents(ui, repo, file_=None, **opts):
4942 4942 """show the parents of the working directory or revision (DEPRECATED)
4943 4943
4944 4944 Print the working directory's parent revisions. If a revision is
4945 4945 given via -r/--rev, the parent of that revision will be printed.
4946 4946 If a file argument is given, the revision in which the file was
4947 4947 last changed (before the working directory revision or the
4948 4948 argument to --rev if given) is printed.
4949 4949
4950 4950 This command is equivalent to::
4951 4951
4952 4952 hg log -r "p1()+p2()" or
4953 4953 hg log -r "p1(REV)+p2(REV)" or
4954 4954 hg log -r "max(::p1() and file(FILE))+max(::p2() and file(FILE))" or
4955 4955 hg log -r "max(::p1(REV) and file(FILE))+max(::p2(REV) and file(FILE))"
4956 4956
4957 4957 See :hg:`summary` and :hg:`help revsets` for related information.
4958 4958
4959 4959 Returns 0 on success.
4960 4960 """
4961 4961
4962 4962 opts = pycompat.byteskwargs(opts)
4963 4963 rev = opts.get(b'rev')
4964 4964 if rev:
4965 4965 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
4966 4966 ctx = scmutil.revsingle(repo, rev, None)
4967 4967
4968 4968 if file_:
4969 4969 m = scmutil.match(ctx, (file_,), opts)
4970 4970 if m.anypats() or len(m.files()) != 1:
4971 4971 raise error.Abort(_(b'can only specify an explicit filename'))
4972 4972 file_ = m.files()[0]
4973 4973 filenodes = []
4974 4974 for cp in ctx.parents():
4975 4975 if not cp:
4976 4976 continue
4977 4977 try:
4978 4978 filenodes.append(cp.filenode(file_))
4979 4979 except error.LookupError:
4980 4980 pass
4981 4981 if not filenodes:
4982 4982 raise error.Abort(_(b"'%s' not found in manifest!") % file_)
4983 4983 p = []
4984 4984 for fn in filenodes:
4985 4985 fctx = repo.filectx(file_, fileid=fn)
4986 4986 p.append(fctx.node())
4987 4987 else:
4988 4988 p = [cp.node() for cp in ctx.parents()]
4989 4989
4990 4990 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
4991 4991 for n in p:
4992 4992 if n != nullid:
4993 4993 displayer.show(repo[n])
4994 4994 displayer.close()
4995 4995
4996 4996
4997 4997 @command(
4998 4998 b'paths',
4999 4999 formatteropts,
5000 5000 _(b'[NAME]'),
5001 5001 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
5002 5002 optionalrepo=True,
5003 5003 intents={INTENT_READONLY},
5004 5004 )
5005 5005 def paths(ui, repo, search=None, **opts):
5006 5006 """show aliases for remote repositories
5007 5007
5008 5008 Show definition of symbolic path name NAME. If no name is given,
5009 5009 show definition of all available names.
5010 5010
5011 5011 Option -q/--quiet suppresses all output when searching for NAME
5012 5012 and shows only the path names when listing all definitions.
5013 5013
5014 5014 Path names are defined in the [paths] section of your
5015 5015 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
5016 5016 repository, ``.hg/hgrc`` is used, too.
5017 5017
5018 5018 The path names ``default`` and ``default-push`` have a special
5019 5019 meaning. When performing a push or pull operation, they are used
5020 5020 as fallbacks if no location is specified on the command-line.
5021 5021 When ``default-push`` is set, it will be used for push and
5022 5022 ``default`` will be used for pull; otherwise ``default`` is used
5023 5023 as the fallback for both. When cloning a repository, the clone
5024 5024 source is written as ``default`` in ``.hg/hgrc``.
5025 5025
5026 5026 .. note::
5027 5027
5028 5028 ``default`` and ``default-push`` apply to all inbound (e.g.
5029 5029 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email`
5030 5030 and :hg:`bundle`) operations.
5031 5031
5032 5032 See :hg:`help urls` for more information.
5033 5033
5034 5034 .. container:: verbose
5035 5035
5036 5036 Template:
5037 5037
5038 5038 The following keywords are supported. See also :hg:`help templates`.
5039 5039
5040 5040 :name: String. Symbolic name of the path alias.
5041 5041 :pushurl: String. URL for push operations.
5042 5042 :url: String. URL or directory path for the other operations.
5043 5043
5044 5044 Returns 0 on success.
5045 5045 """
5046 5046
5047 5047 opts = pycompat.byteskwargs(opts)
5048 5048 ui.pager(b'paths')
5049 5049 if search:
5050 5050 pathitems = [
5051 5051 (name, path)
5052 5052 for name, path in pycompat.iteritems(ui.paths)
5053 5053 if name == search
5054 5054 ]
5055 5055 else:
5056 5056 pathitems = sorted(pycompat.iteritems(ui.paths))
5057 5057
5058 5058 fm = ui.formatter(b'paths', opts)
5059 5059 if fm.isplain():
5060 5060 hidepassword = util.hidepassword
5061 5061 else:
5062 5062 hidepassword = bytes
5063 5063 if ui.quiet:
5064 5064 namefmt = b'%s\n'
5065 5065 else:
5066 5066 namefmt = b'%s = '
5067 5067 showsubopts = not search and not ui.quiet
5068 5068
5069 5069 for name, path in pathitems:
5070 5070 fm.startitem()
5071 5071 fm.condwrite(not search, b'name', namefmt, name)
5072 5072 fm.condwrite(not ui.quiet, b'url', b'%s\n', hidepassword(path.rawloc))
5073 5073 for subopt, value in sorted(path.suboptions.items()):
5074 5074 assert subopt not in (b'name', b'url')
5075 5075 if showsubopts:
5076 5076 fm.plain(b'%s:%s = ' % (name, subopt))
5077 5077 fm.condwrite(showsubopts, subopt, b'%s\n', value)
5078 5078
5079 5079 fm.end()
5080 5080
5081 5081 if search and not pathitems:
5082 5082 if not ui.quiet:
5083 5083 ui.warn(_(b"not found!\n"))
5084 5084 return 1
5085 5085 else:
5086 5086 return 0
5087 5087
5088 5088
5089 5089 @command(
5090 5090 b'phase',
5091 5091 [
5092 5092 (b'p', b'public', False, _(b'set changeset phase to public')),
5093 5093 (b'd', b'draft', False, _(b'set changeset phase to draft')),
5094 5094 (b's', b'secret', False, _(b'set changeset phase to secret')),
5095 5095 (b'f', b'force', False, _(b'allow to move boundary backward')),
5096 5096 (b'r', b'rev', [], _(b'target revision'), _(b'REV')),
5097 5097 ],
5098 5098 _(b'[-p|-d|-s] [-f] [-r] [REV...]'),
5099 5099 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
5100 5100 )
5101 5101 def phase(ui, repo, *revs, **opts):
5102 5102 """set or show the current phase name
5103 5103
5104 5104 With no argument, show the phase name of the current revision(s).
5105 5105
5106 5106 With one of -p/--public, -d/--draft or -s/--secret, change the
5107 5107 phase value of the specified revisions.
5108 5108
5109 5109 Unless -f/--force is specified, :hg:`phase` won't move changesets from a
5110 5110 lower phase to a higher phase. Phases are ordered as follows::
5111 5111
5112 5112 public < draft < secret
5113 5113
5114 5114 Returns 0 on success, 1 if some phases could not be changed.
5115 5115
5116 5116 (For more information about the phases concept, see :hg:`help phases`.)
5117 5117 """
5118 5118 opts = pycompat.byteskwargs(opts)
5119 5119 # search for a unique phase argument
5120 5120 targetphase = None
5121 5121 for idx, name in enumerate(phases.cmdphasenames):
5122 5122 if opts[name]:
5123 5123 if targetphase is not None:
5124 5124 raise error.Abort(_(b'only one phase can be specified'))
5125 5125 targetphase = idx
5126 5126
5127 5127 # look for specified revision
5128 5128 revs = list(revs)
5129 5129 revs.extend(opts[b'rev'])
5130 5130 if not revs:
5131 5131 # display both parents as the second parent phase can influence
5132 5132 # the phase of a merge commit
5133 5133 revs = [c.rev() for c in repo[None].parents()]
5134 5134
5135 5135 revs = scmutil.revrange(repo, revs)
5136 5136
5137 5137 ret = 0
5138 5138 if targetphase is None:
5139 5139 # display
5140 5140 for r in revs:
5141 5141 ctx = repo[r]
5142 5142 ui.write(b'%i: %s\n' % (ctx.rev(), ctx.phasestr()))
5143 5143 else:
5144 5144 with repo.lock(), repo.transaction(b"phase") as tr:
5145 5145 # set phase
5146 5146 if not revs:
5147 5147 raise error.Abort(_(b'empty revision set'))
5148 5148 nodes = [repo[r].node() for r in revs]
5149 5149 # moving revision from public to draft may hide them
5150 5150 # We have to check result on an unfiltered repository
5151 5151 unfi = repo.unfiltered()
5152 5152 getphase = unfi._phasecache.phase
5153 5153 olddata = [getphase(unfi, r) for r in unfi]
5154 5154 phases.advanceboundary(repo, tr, targetphase, nodes)
5155 5155 if opts[b'force']:
5156 5156 phases.retractboundary(repo, tr, targetphase, nodes)
5157 5157 getphase = unfi._phasecache.phase
5158 5158 newdata = [getphase(unfi, r) for r in unfi]
5159 5159 changes = sum(newdata[r] != olddata[r] for r in unfi)
5160 5160 cl = unfi.changelog
5161 5161 rejected = [n for n in nodes if newdata[cl.rev(n)] < targetphase]
5162 5162 if rejected:
5163 5163 ui.warn(
5164 5164 _(
5165 5165 b'cannot move %i changesets to a higher '
5166 5166 b'phase, use --force\n'
5167 5167 )
5168 5168 % len(rejected)
5169 5169 )
5170 5170 ret = 1
5171 5171 if changes:
5172 5172 msg = _(b'phase changed for %i changesets\n') % changes
5173 5173 if ret:
5174 5174 ui.status(msg)
5175 5175 else:
5176 5176 ui.note(msg)
5177 5177 else:
5178 5178 ui.warn(_(b'no phases changed\n'))
5179 5179 return ret
5180 5180
5181 5181
5182 5182 def postincoming(ui, repo, modheads, optupdate, checkout, brev):
5183 5183 """Run after a changegroup has been added via pull/unbundle
5184 5184
5185 5185 This takes arguments below:
5186 5186
5187 5187 :modheads: change of heads by pull/unbundle
5188 5188 :optupdate: updating working directory is needed or not
5189 5189 :checkout: update destination revision (or None to default destination)
5190 5190 :brev: a name, which might be a bookmark to be activated after updating
5191 5191 """
5192 5192 if modheads == 0:
5193 5193 return
5194 5194 if optupdate:
5195 5195 try:
5196 5196 return hg.updatetotally(ui, repo, checkout, brev)
5197 5197 except error.UpdateAbort as inst:
5198 5198 msg = _(b"not updating: %s") % stringutil.forcebytestr(inst)
5199 5199 hint = inst.hint
5200 5200 raise error.UpdateAbort(msg, hint=hint)
5201 5201 if modheads is not None and modheads > 1:
5202 5202 currentbranchheads = len(repo.branchheads())
5203 5203 if currentbranchheads == modheads:
5204 5204 ui.status(
5205 5205 _(b"(run 'hg heads' to see heads, 'hg merge' to merge)\n")
5206 5206 )
5207 5207 elif currentbranchheads > 1:
5208 5208 ui.status(
5209 5209 _(b"(run 'hg heads .' to see heads, 'hg merge' to merge)\n")
5210 5210 )
5211 5211 else:
5212 5212 ui.status(_(b"(run 'hg heads' to see heads)\n"))
5213 5213 elif not ui.configbool(b'commands', b'update.requiredest'):
5214 5214 ui.status(_(b"(run 'hg update' to get a working copy)\n"))
5215 5215
5216 5216
5217 5217 @command(
5218 5218 b'pull',
5219 5219 [
5220 5220 (
5221 5221 b'u',
5222 5222 b'update',
5223 5223 None,
5224 5224 _(b'update to new branch head if new descendants were pulled'),
5225 5225 ),
5226 5226 (
5227 5227 b'f',
5228 5228 b'force',
5229 5229 None,
5230 5230 _(b'run even when remote repository is unrelated'),
5231 5231 ),
5232 5232 (b'', b'confirm', None, _(b'confirm pull before applying changes'),),
5233 5233 (
5234 5234 b'r',
5235 5235 b'rev',
5236 5236 [],
5237 5237 _(b'a remote changeset intended to be added'),
5238 5238 _(b'REV'),
5239 5239 ),
5240 5240 (b'B', b'bookmark', [], _(b"bookmark to pull"), _(b'BOOKMARK')),
5241 5241 (
5242 5242 b'b',
5243 5243 b'branch',
5244 5244 [],
5245 5245 _(b'a specific branch you would like to pull'),
5246 5246 _(b'BRANCH'),
5247 5247 ),
5248 5248 ]
5249 5249 + remoteopts,
5250 5250 _(b'[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'),
5251 5251 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
5252 5252 helpbasic=True,
5253 5253 )
5254 5254 def pull(ui, repo, source=b"default", **opts):
5255 5255 """pull changes from the specified source
5256 5256
5257 5257 Pull changes from a remote repository to a local one.
5258 5258
5259 5259 This finds all changes from the repository at the specified path
5260 5260 or URL and adds them to a local repository (the current one unless
5261 5261 -R is specified). By default, this does not update the copy of the
5262 5262 project in the working directory.
5263 5263
5264 5264 When cloning from servers that support it, Mercurial may fetch
5265 5265 pre-generated data. When this is done, hooks operating on incoming
5266 5266 changesets and changegroups may fire more than once, once for each
5267 5267 pre-generated bundle and as well as for any additional remaining
5268 5268 data. See :hg:`help -e clonebundles` for more.
5269 5269
5270 5270 Use :hg:`incoming` if you want to see what would have been added
5271 5271 by a pull at the time you issued this command. If you then decide
5272 5272 to add those changes to the repository, you should use :hg:`pull
5273 5273 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
5274 5274
5275 5275 If SOURCE is omitted, the 'default' path will be used.
5276 5276 See :hg:`help urls` for more information.
5277 5277
5278 5278 Specifying bookmark as ``.`` is equivalent to specifying the active
5279 5279 bookmark's name.
5280 5280
5281 5281 Returns 0 on success, 1 if an update had unresolved files.
5282 5282 """
5283 5283
5284 5284 opts = pycompat.byteskwargs(opts)
5285 5285 if ui.configbool(b'commands', b'update.requiredest') and opts.get(
5286 5286 b'update'
5287 5287 ):
5288 5288 msg = _(b'update destination required by configuration')
5289 5289 hint = _(b'use hg pull followed by hg update DEST')
5290 5290 raise error.Abort(msg, hint=hint)
5291 5291
5292 5292 source, branches = hg.parseurl(ui.expandpath(source), opts.get(b'branch'))
5293 5293 ui.status(_(b'pulling from %s\n') % util.hidepassword(source))
5294 5294 other = hg.peer(repo, opts, source)
5295 5295 try:
5296 5296 revs, checkout = hg.addbranchrevs(
5297 5297 repo, other, branches, opts.get(b'rev')
5298 5298 )
5299 5299
5300 5300 pullopargs = {}
5301 5301
5302 5302 nodes = None
5303 5303 if opts.get(b'bookmark') or revs:
5304 5304 # The list of bookmark used here is the same used to actually update
5305 5305 # the bookmark names, to avoid the race from issue 4689 and we do
5306 5306 # all lookup and bookmark queries in one go so they see the same
5307 5307 # version of the server state (issue 4700).
5308 5308 nodes = []
5309 5309 fnodes = []
5310 5310 revs = revs or []
5311 5311 if revs and not other.capable(b'lookup'):
5312 5312 err = _(
5313 5313 b"other repository doesn't support revision lookup, "
5314 5314 b"so a rev cannot be specified."
5315 5315 )
5316 5316 raise error.Abort(err)
5317 5317 with other.commandexecutor() as e:
5318 5318 fremotebookmarks = e.callcommand(
5319 5319 b'listkeys', {b'namespace': b'bookmarks'}
5320 5320 )
5321 5321 for r in revs:
5322 5322 fnodes.append(e.callcommand(b'lookup', {b'key': r}))
5323 5323 remotebookmarks = fremotebookmarks.result()
5324 5324 remotebookmarks = bookmarks.unhexlifybookmarks(remotebookmarks)
5325 5325 pullopargs[b'remotebookmarks'] = remotebookmarks
5326 5326 for b in opts.get(b'bookmark', []):
5327 5327 b = repo._bookmarks.expandname(b)
5328 5328 if b not in remotebookmarks:
5329 5329 raise error.Abort(_(b'remote bookmark %s not found!') % b)
5330 5330 nodes.append(remotebookmarks[b])
5331 5331 for i, rev in enumerate(revs):
5332 5332 node = fnodes[i].result()
5333 5333 nodes.append(node)
5334 5334 if rev == checkout:
5335 5335 checkout = node
5336 5336
5337 5337 wlock = util.nullcontextmanager()
5338 5338 if opts.get(b'update'):
5339 5339 wlock = repo.wlock()
5340 5340 with wlock:
5341 5341 pullopargs.update(opts.get(b'opargs', {}))
5342 5342 modheads = exchange.pull(
5343 5343 repo,
5344 5344 other,
5345 5345 heads=nodes,
5346 5346 force=opts.get(b'force'),
5347 5347 bookmarks=opts.get(b'bookmark', ()),
5348 5348 opargs=pullopargs,
5349 5349 confirm=opts.get(b'confirm'),
5350 5350 ).cgresult
5351 5351
5352 5352 # brev is a name, which might be a bookmark to be activated at
5353 5353 # the end of the update. In other words, it is an explicit
5354 5354 # destination of the update
5355 5355 brev = None
5356 5356
5357 5357 if checkout:
5358 5358 checkout = repo.unfiltered().changelog.rev(checkout)
5359 5359
5360 5360 # order below depends on implementation of
5361 5361 # hg.addbranchrevs(). opts['bookmark'] is ignored,
5362 5362 # because 'checkout' is determined without it.
5363 5363 if opts.get(b'rev'):
5364 5364 brev = opts[b'rev'][0]
5365 5365 elif opts.get(b'branch'):
5366 5366 brev = opts[b'branch'][0]
5367 5367 else:
5368 5368 brev = branches[0]
5369 5369 repo._subtoppath = source
5370 5370 try:
5371 5371 ret = postincoming(
5372 5372 ui, repo, modheads, opts.get(b'update'), checkout, brev
5373 5373 )
5374 5374 except error.FilteredRepoLookupError as exc:
5375 5375 msg = _(b'cannot update to target: %s') % exc.args[0]
5376 5376 exc.args = (msg,) + exc.args[1:]
5377 5377 raise
5378 5378 finally:
5379 5379 del repo._subtoppath
5380 5380
5381 5381 finally:
5382 5382 other.close()
5383 5383 return ret
5384 5384
5385 5385
5386 5386 @command(
5387 5387 b'push',
5388 5388 [
5389 5389 (b'f', b'force', None, _(b'force push')),
5390 5390 (
5391 5391 b'r',
5392 5392 b'rev',
5393 5393 [],
5394 5394 _(b'a changeset intended to be included in the destination'),
5395 5395 _(b'REV'),
5396 5396 ),
5397 5397 (b'B', b'bookmark', [], _(b"bookmark to push"), _(b'BOOKMARK')),
5398 5398 (b'', b'all-bookmarks', None, _(b"push all bookmarks (EXPERIMENTAL)")),
5399 5399 (
5400 5400 b'b',
5401 5401 b'branch',
5402 5402 [],
5403 5403 _(b'a specific branch you would like to push'),
5404 5404 _(b'BRANCH'),
5405 5405 ),
5406 5406 (b'', b'new-branch', False, _(b'allow pushing a new branch')),
5407 5407 (
5408 5408 b'',
5409 5409 b'pushvars',
5410 5410 [],
5411 5411 _(b'variables that can be sent to server (ADVANCED)'),
5412 5412 ),
5413 5413 (
5414 5414 b'',
5415 5415 b'publish',
5416 5416 False,
5417 5417 _(b'push the changeset as public (EXPERIMENTAL)'),
5418 5418 ),
5419 5419 ]
5420 5420 + remoteopts,
5421 5421 _(b'[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'),
5422 5422 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
5423 5423 helpbasic=True,
5424 5424 )
5425 5425 def push(ui, repo, dest=None, **opts):
5426 5426 """push changes to the specified destination
5427 5427
5428 5428 Push changesets from the local repository to the specified
5429 5429 destination.
5430 5430
5431 5431 This operation is symmetrical to pull: it is identical to a pull
5432 5432 in the destination repository from the current one.
5433 5433
5434 5434 By default, push will not allow creation of new heads at the
5435 5435 destination, since multiple heads would make it unclear which head
5436 5436 to use. In this situation, it is recommended to pull and merge
5437 5437 before pushing.
5438 5438
5439 5439 Use --new-branch if you want to allow push to create a new named
5440 5440 branch that is not present at the destination. This allows you to
5441 5441 only create a new branch without forcing other changes.
5442 5442
5443 5443 .. note::
5444 5444
5445 5445 Extra care should be taken with the -f/--force option,
5446 5446 which will push all new heads on all branches, an action which will
5447 5447 almost always cause confusion for collaborators.
5448 5448
5449 5449 If -r/--rev is used, the specified revision and all its ancestors
5450 5450 will be pushed to the remote repository.
5451 5451
5452 5452 If -B/--bookmark is used, the specified bookmarked revision, its
5453 5453 ancestors, and the bookmark will be pushed to the remote
5454 5454 repository. Specifying ``.`` is equivalent to specifying the active
5455 5455 bookmark's name. Use the --all-bookmarks option for pushing all
5456 5456 current bookmarks.
5457 5457
5458 5458 Please see :hg:`help urls` for important details about ``ssh://``
5459 5459 URLs. If DESTINATION is omitted, a default path will be used.
5460 5460
5461 5461 .. container:: verbose
5462 5462
5463 5463 The --pushvars option sends strings to the server that become
5464 5464 environment variables prepended with ``HG_USERVAR_``. For example,
5465 5465 ``--pushvars ENABLE_FEATURE=true``, provides the server side hooks with
5466 5466 ``HG_USERVAR_ENABLE_FEATURE=true`` as part of their environment.
5467 5467
5468 5468 pushvars can provide for user-overridable hooks as well as set debug
5469 5469 levels. One example is having a hook that blocks commits containing
5470 5470 conflict markers, but enables the user to override the hook if the file
5471 5471 is using conflict markers for testing purposes or the file format has
5472 5472 strings that look like conflict markers.
5473 5473
5474 5474 By default, servers will ignore `--pushvars`. To enable it add the
5475 5475 following to your configuration file::
5476 5476
5477 5477 [push]
5478 5478 pushvars.server = true
5479 5479
5480 5480 Returns 0 if push was successful, 1 if nothing to push.
5481 5481 """
5482 5482
5483 5483 opts = pycompat.byteskwargs(opts)
5484 5484
5485 5485 if opts.get(b'all_bookmarks'):
5486 5486 cmdutil.check_incompatible_arguments(
5487 5487 opts, b'all_bookmarks', [b'bookmark', b'rev'],
5488 5488 )
5489 5489 opts[b'bookmark'] = list(repo._bookmarks)
5490 5490
5491 5491 if opts.get(b'bookmark'):
5492 5492 ui.setconfig(b'bookmarks', b'pushing', opts[b'bookmark'], b'push')
5493 5493 for b in opts[b'bookmark']:
5494 5494 # translate -B options to -r so changesets get pushed
5495 5495 b = repo._bookmarks.expandname(b)
5496 5496 if b in repo._bookmarks:
5497 5497 opts.setdefault(b'rev', []).append(b)
5498 5498 else:
5499 5499 # if we try to push a deleted bookmark, translate it to null
5500 5500 # this lets simultaneous -r, -b options continue working
5501 5501 opts.setdefault(b'rev', []).append(b"null")
5502 5502
5503 5503 path = ui.paths.getpath(dest, default=(b'default-push', b'default'))
5504 5504 if not path:
5505 5505 raise error.Abort(
5506 5506 _(b'default repository not configured!'),
5507 5507 hint=_(b"see 'hg help config.paths'"),
5508 5508 )
5509 5509 dest = path.pushloc or path.loc
5510 5510 branches = (path.branch, opts.get(b'branch') or [])
5511 5511 ui.status(_(b'pushing to %s\n') % util.hidepassword(dest))
5512 5512 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get(b'rev'))
5513 5513 other = hg.peer(repo, opts, dest)
5514 5514
5515 5515 if revs:
5516 5516 revs = [repo[r].node() for r in scmutil.revrange(repo, revs)]
5517 5517 if not revs:
5518 5518 raise error.Abort(
5519 5519 _(b"specified revisions evaluate to an empty set"),
5520 5520 hint=_(b"use different revision arguments"),
5521 5521 )
5522 5522 elif path.pushrev:
5523 5523 # It doesn't make any sense to specify ancestor revisions. So limit
5524 5524 # to DAG heads to make discovery simpler.
5525 5525 expr = revsetlang.formatspec(b'heads(%r)', path.pushrev)
5526 5526 revs = scmutil.revrange(repo, [expr])
5527 5527 revs = [repo[rev].node() for rev in revs]
5528 5528 if not revs:
5529 5529 raise error.Abort(
5530 5530 _(b'default push revset for path evaluates to an empty set')
5531 5531 )
5532 5532 elif ui.configbool(b'commands', b'push.require-revs'):
5533 5533 raise error.Abort(
5534 5534 _(b'no revisions specified to push'),
5535 5535 hint=_(b'did you mean "hg push -r ."?'),
5536 5536 )
5537 5537
5538 5538 repo._subtoppath = dest
5539 5539 try:
5540 5540 # push subrepos depth-first for coherent ordering
5541 5541 c = repo[b'.']
5542 5542 subs = c.substate # only repos that are committed
5543 5543 for s in sorted(subs):
5544 5544 result = c.sub(s).push(opts)
5545 5545 if result == 0:
5546 5546 return not result
5547 5547 finally:
5548 5548 del repo._subtoppath
5549 5549
5550 5550 opargs = dict(opts.get(b'opargs', {})) # copy opargs since we may mutate it
5551 5551 opargs.setdefault(b'pushvars', []).extend(opts.get(b'pushvars', []))
5552 5552
5553 5553 pushop = exchange.push(
5554 5554 repo,
5555 5555 other,
5556 5556 opts.get(b'force'),
5557 5557 revs=revs,
5558 5558 newbranch=opts.get(b'new_branch'),
5559 5559 bookmarks=opts.get(b'bookmark', ()),
5560 5560 publish=opts.get(b'publish'),
5561 5561 opargs=opargs,
5562 5562 )
5563 5563
5564 5564 result = not pushop.cgresult
5565 5565
5566 5566 if pushop.bkresult is not None:
5567 5567 if pushop.bkresult == 2:
5568 5568 result = 2
5569 5569 elif not result and pushop.bkresult:
5570 5570 result = 2
5571 5571
5572 5572 return result
5573 5573
5574 5574
5575 5575 @command(
5576 5576 b'recover',
5577 5577 [(b'', b'verify', False, b"run `hg verify` after successful recover"),],
5578 5578 helpcategory=command.CATEGORY_MAINTENANCE,
5579 5579 )
5580 5580 def recover(ui, repo, **opts):
5581 5581 """roll back an interrupted transaction
5582 5582
5583 5583 Recover from an interrupted commit or pull.
5584 5584
5585 5585 This command tries to fix the repository status after an
5586 5586 interrupted operation. It should only be necessary when Mercurial
5587 5587 suggests it.
5588 5588
5589 5589 Returns 0 if successful, 1 if nothing to recover or verify fails.
5590 5590 """
5591 5591 ret = repo.recover()
5592 5592 if ret:
5593 5593 if opts['verify']:
5594 5594 return hg.verify(repo)
5595 5595 else:
5596 5596 msg = _(
5597 5597 b"(verify step skipped, run `hg verify` to check your "
5598 5598 b"repository content)\n"
5599 5599 )
5600 5600 ui.warn(msg)
5601 5601 return 0
5602 5602 return 1
5603 5603
5604 5604
5605 5605 @command(
5606 5606 b'remove|rm',
5607 5607 [
5608 5608 (b'A', b'after', None, _(b'record delete for missing files')),
5609 5609 (b'f', b'force', None, _(b'forget added files, delete modified files')),
5610 5610 ]
5611 5611 + subrepoopts
5612 5612 + walkopts
5613 5613 + dryrunopts,
5614 5614 _(b'[OPTION]... FILE...'),
5615 5615 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5616 5616 helpbasic=True,
5617 5617 inferrepo=True,
5618 5618 )
5619 5619 def remove(ui, repo, *pats, **opts):
5620 5620 """remove the specified files on the next commit
5621 5621
5622 5622 Schedule the indicated files for removal from the current branch.
5623 5623
5624 5624 This command schedules the files to be removed at the next commit.
5625 5625 To undo a remove before that, see :hg:`revert`. To undo added
5626 5626 files, see :hg:`forget`.
5627 5627
5628 5628 .. container:: verbose
5629 5629
5630 5630 -A/--after can be used to remove only files that have already
5631 5631 been deleted, -f/--force can be used to force deletion, and -Af
5632 5632 can be used to remove files from the next revision without
5633 5633 deleting them from the working directory.
5634 5634
5635 5635 The following table details the behavior of remove for different
5636 5636 file states (columns) and option combinations (rows). The file
5637 5637 states are Added [A], Clean [C], Modified [M] and Missing [!]
5638 5638 (as reported by :hg:`status`). The actions are Warn, Remove
5639 5639 (from branch) and Delete (from disk):
5640 5640
5641 5641 ========= == == == ==
5642 5642 opt/state A C M !
5643 5643 ========= == == == ==
5644 5644 none W RD W R
5645 5645 -f R RD RD R
5646 5646 -A W W W R
5647 5647 -Af R R R R
5648 5648 ========= == == == ==
5649 5649
5650 5650 .. note::
5651 5651
5652 5652 :hg:`remove` never deletes files in Added [A] state from the
5653 5653 working directory, not even if ``--force`` is specified.
5654 5654
5655 5655 Returns 0 on success, 1 if any warnings encountered.
5656 5656 """
5657 5657
5658 5658 opts = pycompat.byteskwargs(opts)
5659 5659 after, force = opts.get(b'after'), opts.get(b'force')
5660 5660 dryrun = opts.get(b'dry_run')
5661 5661 if not pats and not after:
5662 5662 raise error.Abort(_(b'no files specified'))
5663 5663
5664 5664 m = scmutil.match(repo[None], pats, opts)
5665 5665 subrepos = opts.get(b'subrepos')
5666 5666 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
5667 5667 return cmdutil.remove(
5668 5668 ui, repo, m, b"", uipathfn, after, force, subrepos, dryrun=dryrun
5669 5669 )
5670 5670
5671 5671
5672 5672 @command(
5673 5673 b'rename|move|mv',
5674 5674 [
5675 5675 (b'A', b'after', None, _(b'record a rename that has already occurred')),
5676 5676 (
5677 5677 b'',
5678 5678 b'at-rev',
5679 5679 b'',
5680 5680 _(b'(un)mark renames in the given revision (EXPERIMENTAL)'),
5681 5681 _(b'REV'),
5682 5682 ),
5683 5683 (
5684 5684 b'f',
5685 5685 b'force',
5686 5686 None,
5687 5687 _(b'forcibly move over an existing managed file'),
5688 5688 ),
5689 5689 ]
5690 5690 + walkopts
5691 5691 + dryrunopts,
5692 5692 _(b'[OPTION]... SOURCE... DEST'),
5693 5693 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5694 5694 )
5695 5695 def rename(ui, repo, *pats, **opts):
5696 5696 """rename files; equivalent of copy + remove
5697 5697
5698 5698 Mark dest as copies of sources; mark sources for deletion. If dest
5699 5699 is a directory, copies are put in that directory. If dest is a
5700 5700 file, there can only be one source.
5701 5701
5702 5702 By default, this command copies the contents of files as they
5703 5703 exist in the working directory. If invoked with -A/--after, the
5704 5704 operation is recorded, but no copying is performed.
5705 5705
5706 5706 This command takes effect at the next commit. To undo a rename
5707 5707 before that, see :hg:`revert`.
5708 5708
5709 5709 Returns 0 on success, 1 if errors are encountered.
5710 5710 """
5711 5711 opts = pycompat.byteskwargs(opts)
5712 5712 with repo.wlock():
5713 5713 return cmdutil.copy(ui, repo, pats, opts, rename=True)
5714 5714
5715 5715
5716 5716 @command(
5717 5717 b'resolve',
5718 5718 [
5719 5719 (b'a', b'all', None, _(b'select all unresolved files')),
5720 5720 (b'l', b'list', None, _(b'list state of files needing merge')),
5721 5721 (b'm', b'mark', None, _(b'mark files as resolved')),
5722 5722 (b'u', b'unmark', None, _(b'mark files as unresolved')),
5723 5723 (b'n', b'no-status', None, _(b'hide status prefix')),
5724 5724 (b'', b're-merge', None, _(b're-merge files')),
5725 5725 ]
5726 5726 + mergetoolopts
5727 5727 + walkopts
5728 5728 + formatteropts,
5729 5729 _(b'[OPTION]... [FILE]...'),
5730 5730 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5731 5731 inferrepo=True,
5732 5732 )
5733 5733 def resolve(ui, repo, *pats, **opts):
5734 5734 """redo merges or set/view the merge status of files
5735 5735
5736 5736 Merges with unresolved conflicts are often the result of
5737 5737 non-interactive merging using the ``internal:merge`` configuration
5738 5738 setting, or a command-line merge tool like ``diff3``. The resolve
5739 5739 command is used to manage the files involved in a merge, after
5740 5740 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
5741 5741 working directory must have two parents). See :hg:`help
5742 5742 merge-tools` for information on configuring merge tools.
5743 5743
5744 5744 The resolve command can be used in the following ways:
5745 5745
5746 5746 - :hg:`resolve [--re-merge] [--tool TOOL] FILE...`: attempt to re-merge
5747 5747 the specified files, discarding any previous merge attempts. Re-merging
5748 5748 is not performed for files already marked as resolved. Use ``--all/-a``
5749 5749 to select all unresolved files. ``--tool`` can be used to specify
5750 5750 the merge tool used for the given files. It overrides the HGMERGE
5751 5751 environment variable and your configuration files. Previous file
5752 5752 contents are saved with a ``.orig`` suffix.
5753 5753
5754 5754 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
5755 5755 (e.g. after having manually fixed-up the files). The default is
5756 5756 to mark all unresolved files.
5757 5757
5758 5758 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
5759 5759 default is to mark all resolved files.
5760 5760
5761 5761 - :hg:`resolve -l`: list files which had or still have conflicts.
5762 5762 In the printed list, ``U`` = unresolved and ``R`` = resolved.
5763 5763 You can use ``set:unresolved()`` or ``set:resolved()`` to filter
5764 5764 the list. See :hg:`help filesets` for details.
5765 5765
5766 5766 .. note::
5767 5767
5768 5768 Mercurial will not let you commit files with unresolved merge
5769 5769 conflicts. You must use :hg:`resolve -m ...` before you can
5770 5770 commit after a conflicting merge.
5771 5771
5772 5772 .. container:: verbose
5773 5773
5774 5774 Template:
5775 5775
5776 5776 The following keywords are supported in addition to the common template
5777 5777 keywords and functions. See also :hg:`help templates`.
5778 5778
5779 5779 :mergestatus: String. Character denoting merge conflicts, ``U`` or ``R``.
5780 5780 :path: String. Repository-absolute path of the file.
5781 5781
5782 5782 Returns 0 on success, 1 if any files fail a resolve attempt.
5783 5783 """
5784 5784
5785 5785 opts = pycompat.byteskwargs(opts)
5786 5786 confirm = ui.configbool(b'commands', b'resolve.confirm')
5787 5787 flaglist = b'all mark unmark list no_status re_merge'.split()
5788 5788 all, mark, unmark, show, nostatus, remerge = [opts.get(o) for o in flaglist]
5789 5789
5790 5790 actioncount = len(list(filter(None, [show, mark, unmark, remerge])))
5791 5791 if actioncount > 1:
5792 5792 raise error.Abort(_(b"too many actions specified"))
5793 5793 elif actioncount == 0 and ui.configbool(
5794 5794 b'commands', b'resolve.explicit-re-merge'
5795 5795 ):
5796 5796 hint = _(b'use --mark, --unmark, --list or --re-merge')
5797 5797 raise error.Abort(_(b'no action specified'), hint=hint)
5798 5798 if pats and all:
5799 5799 raise error.Abort(_(b"can't specify --all and patterns"))
5800 5800 if not (all or pats or show or mark or unmark):
5801 5801 raise error.Abort(
5802 5802 _(b'no files or directories specified'),
5803 5803 hint=b'use --all to re-merge all unresolved files',
5804 5804 )
5805 5805
5806 5806 if confirm:
5807 5807 if all:
5808 5808 if ui.promptchoice(
5809 5809 _(b're-merge all unresolved files (yn)?$$ &Yes $$ &No')
5810 5810 ):
5811 5811 raise error.Abort(_(b'user quit'))
5812 5812 if mark and not pats:
5813 5813 if ui.promptchoice(
5814 5814 _(
5815 5815 b'mark all unresolved files as resolved (yn)?'
5816 5816 b'$$ &Yes $$ &No'
5817 5817 )
5818 5818 ):
5819 5819 raise error.Abort(_(b'user quit'))
5820 5820 if unmark and not pats:
5821 5821 if ui.promptchoice(
5822 5822 _(
5823 5823 b'mark all resolved files as unresolved (yn)?'
5824 5824 b'$$ &Yes $$ &No'
5825 5825 )
5826 5826 ):
5827 5827 raise error.Abort(_(b'user quit'))
5828 5828
5829 5829 uipathfn = scmutil.getuipathfn(repo)
5830 5830
5831 5831 if show:
5832 5832 ui.pager(b'resolve')
5833 5833 fm = ui.formatter(b'resolve', opts)
5834 5834 ms = mergestatemod.mergestate.read(repo)
5835 5835 wctx = repo[None]
5836 5836 m = scmutil.match(wctx, pats, opts)
5837 5837
5838 5838 # Labels and keys based on merge state. Unresolved path conflicts show
5839 5839 # as 'P'. Resolved path conflicts show as 'R', the same as normal
5840 5840 # resolved conflicts.
5841 5841 mergestateinfo = {
5842 5842 mergestatemod.MERGE_RECORD_UNRESOLVED: (
5843 5843 b'resolve.unresolved',
5844 5844 b'U',
5845 5845 ),
5846 5846 mergestatemod.MERGE_RECORD_RESOLVED: (b'resolve.resolved', b'R'),
5847 5847 mergestatemod.MERGE_RECORD_UNRESOLVED_PATH: (
5848 5848 b'resolve.unresolved',
5849 5849 b'P',
5850 5850 ),
5851 5851 mergestatemod.MERGE_RECORD_RESOLVED_PATH: (
5852 5852 b'resolve.resolved',
5853 5853 b'R',
5854 5854 ),
5855 5855 }
5856 5856
5857 5857 for f in ms:
5858 5858 if not m(f):
5859 5859 continue
5860 5860
5861 5861 label, key = mergestateinfo[ms[f]]
5862 5862 fm.startitem()
5863 5863 fm.context(ctx=wctx)
5864 5864 fm.condwrite(not nostatus, b'mergestatus', b'%s ', key, label=label)
5865 5865 fm.data(path=f)
5866 5866 fm.plain(b'%s\n' % uipathfn(f), label=label)
5867 5867 fm.end()
5868 5868 return 0
5869 5869
5870 5870 with repo.wlock():
5871 5871 ms = mergestatemod.mergestate.read(repo)
5872 5872
5873 5873 if not (ms.active() or repo.dirstate.p2() != nullid):
5874 5874 raise error.Abort(
5875 5875 _(b'resolve command not applicable when not merging')
5876 5876 )
5877 5877
5878 5878 wctx = repo[None]
5879 5879 m = scmutil.match(wctx, pats, opts)
5880 5880 ret = 0
5881 5881 didwork = False
5882 5882
5883 5883 tocomplete = []
5884 5884 hasconflictmarkers = []
5885 5885 if mark:
5886 5886 markcheck = ui.config(b'commands', b'resolve.mark-check')
5887 5887 if markcheck not in [b'warn', b'abort']:
5888 5888 # Treat all invalid / unrecognized values as 'none'.
5889 5889 markcheck = False
5890 5890 for f in ms:
5891 5891 if not m(f):
5892 5892 continue
5893 5893
5894 5894 didwork = True
5895 5895
5896 5896 # path conflicts must be resolved manually
5897 5897 if ms[f] in (
5898 5898 mergestatemod.MERGE_RECORD_UNRESOLVED_PATH,
5899 5899 mergestatemod.MERGE_RECORD_RESOLVED_PATH,
5900 5900 ):
5901 5901 if mark:
5902 5902 ms.mark(f, mergestatemod.MERGE_RECORD_RESOLVED_PATH)
5903 5903 elif unmark:
5904 5904 ms.mark(f, mergestatemod.MERGE_RECORD_UNRESOLVED_PATH)
5905 5905 elif ms[f] == mergestatemod.MERGE_RECORD_UNRESOLVED_PATH:
5906 5906 ui.warn(
5907 5907 _(b'%s: path conflict must be resolved manually\n')
5908 5908 % uipathfn(f)
5909 5909 )
5910 5910 continue
5911 5911
5912 5912 if mark:
5913 5913 if markcheck:
5914 5914 fdata = repo.wvfs.tryread(f)
5915 5915 if (
5916 5916 filemerge.hasconflictmarkers(fdata)
5917 5917 and ms[f] != mergestatemod.MERGE_RECORD_RESOLVED
5918 5918 ):
5919 5919 hasconflictmarkers.append(f)
5920 5920 ms.mark(f, mergestatemod.MERGE_RECORD_RESOLVED)
5921 5921 elif unmark:
5922 5922 ms.mark(f, mergestatemod.MERGE_RECORD_UNRESOLVED)
5923 5923 else:
5924 5924 # backup pre-resolve (merge uses .orig for its own purposes)
5925 5925 a = repo.wjoin(f)
5926 5926 try:
5927 5927 util.copyfile(a, a + b".resolve")
5928 5928 except (IOError, OSError) as inst:
5929 5929 if inst.errno != errno.ENOENT:
5930 5930 raise
5931 5931
5932 5932 try:
5933 5933 # preresolve file
5934 5934 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
5935 5935 with ui.configoverride(overrides, b'resolve'):
5936 5936 complete, r = ms.preresolve(f, wctx)
5937 5937 if not complete:
5938 5938 tocomplete.append(f)
5939 5939 elif r:
5940 5940 ret = 1
5941 5941 finally:
5942 5942 ms.commit()
5943 5943
5944 5944 # replace filemerge's .orig file with our resolve file, but only
5945 5945 # for merges that are complete
5946 5946 if complete:
5947 5947 try:
5948 5948 util.rename(
5949 5949 a + b".resolve", scmutil.backuppath(ui, repo, f)
5950 5950 )
5951 5951 except OSError as inst:
5952 5952 if inst.errno != errno.ENOENT:
5953 5953 raise
5954 5954
5955 5955 if hasconflictmarkers:
5956 5956 ui.warn(
5957 5957 _(
5958 5958 b'warning: the following files still have conflict '
5959 5959 b'markers:\n'
5960 5960 )
5961 5961 + b''.join(
5962 5962 b' ' + uipathfn(f) + b'\n' for f in hasconflictmarkers
5963 5963 )
5964 5964 )
5965 5965 if markcheck == b'abort' and not all and not pats:
5966 5966 raise error.Abort(
5967 5967 _(b'conflict markers detected'),
5968 5968 hint=_(b'use --all to mark anyway'),
5969 5969 )
5970 5970
5971 5971 for f in tocomplete:
5972 5972 try:
5973 5973 # resolve file
5974 5974 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
5975 5975 with ui.configoverride(overrides, b'resolve'):
5976 5976 r = ms.resolve(f, wctx)
5977 5977 if r:
5978 5978 ret = 1
5979 5979 finally:
5980 5980 ms.commit()
5981 5981
5982 5982 # replace filemerge's .orig file with our resolve file
5983 5983 a = repo.wjoin(f)
5984 5984 try:
5985 5985 util.rename(a + b".resolve", scmutil.backuppath(ui, repo, f))
5986 5986 except OSError as inst:
5987 5987 if inst.errno != errno.ENOENT:
5988 5988 raise
5989 5989
5990 5990 ms.commit()
5991 5991 branchmerge = repo.dirstate.p2() != nullid
5992 5992 mergestatemod.recordupdates(repo, ms.actions(), branchmerge, None)
5993 5993
5994 5994 if not didwork and pats:
5995 5995 hint = None
5996 5996 if not any([p for p in pats if p.find(b':') >= 0]):
5997 5997 pats = [b'path:%s' % p for p in pats]
5998 5998 m = scmutil.match(wctx, pats, opts)
5999 5999 for f in ms:
6000 6000 if not m(f):
6001 6001 continue
6002 6002
6003 6003 def flag(o):
6004 6004 if o == b're_merge':
6005 6005 return b'--re-merge '
6006 6006 return b'-%s ' % o[0:1]
6007 6007
6008 6008 flags = b''.join([flag(o) for o in flaglist if opts.get(o)])
6009 6009 hint = _(b"(try: hg resolve %s%s)\n") % (
6010 6010 flags,
6011 6011 b' '.join(pats),
6012 6012 )
6013 6013 break
6014 6014 ui.warn(_(b"arguments do not match paths that need resolving\n"))
6015 6015 if hint:
6016 6016 ui.warn(hint)
6017 6017
6018 6018 unresolvedf = list(ms.unresolved())
6019 6019 if not unresolvedf:
6020 6020 ui.status(_(b'(no more unresolved files)\n'))
6021 6021 cmdutil.checkafterresolved(repo)
6022 6022
6023 6023 return ret
6024 6024
6025 6025
6026 6026 @command(
6027 6027 b'revert',
6028 6028 [
6029 6029 (b'a', b'all', None, _(b'revert all changes when no arguments given')),
6030 6030 (b'd', b'date', b'', _(b'tipmost revision matching date'), _(b'DATE')),
6031 6031 (b'r', b'rev', b'', _(b'revert to the specified revision'), _(b'REV')),
6032 6032 (b'C', b'no-backup', None, _(b'do not save backup copies of files')),
6033 6033 (b'i', b'interactive', None, _(b'interactively select the changes')),
6034 6034 ]
6035 6035 + walkopts
6036 6036 + dryrunopts,
6037 6037 _(b'[OPTION]... [-r REV] [NAME]...'),
6038 6038 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6039 6039 )
6040 6040 def revert(ui, repo, *pats, **opts):
6041 6041 """restore files to their checkout state
6042 6042
6043 6043 .. note::
6044 6044
6045 6045 To check out earlier revisions, you should use :hg:`update REV`.
6046 6046 To cancel an uncommitted merge (and lose your changes),
6047 6047 use :hg:`merge --abort`.
6048 6048
6049 6049 With no revision specified, revert the specified files or directories
6050 6050 to the contents they had in the parent of the working directory.
6051 6051 This restores the contents of files to an unmodified
6052 6052 state and unschedules adds, removes, copies, and renames. If the
6053 6053 working directory has two parents, you must explicitly specify a
6054 6054 revision.
6055 6055
6056 6056 Using the -r/--rev or -d/--date options, revert the given files or
6057 6057 directories to their states as of a specific revision. Because
6058 6058 revert does not change the working directory parents, this will
6059 6059 cause these files to appear modified. This can be helpful to "back
6060 6060 out" some or all of an earlier change. See :hg:`backout` for a
6061 6061 related method.
6062 6062
6063 6063 Modified files are saved with a .orig suffix before reverting.
6064 6064 To disable these backups, use --no-backup. It is possible to store
6065 6065 the backup files in a custom directory relative to the root of the
6066 6066 repository by setting the ``ui.origbackuppath`` configuration
6067 6067 option.
6068 6068
6069 6069 See :hg:`help dates` for a list of formats valid for -d/--date.
6070 6070
6071 6071 See :hg:`help backout` for a way to reverse the effect of an
6072 6072 earlier changeset.
6073 6073
6074 6074 Returns 0 on success.
6075 6075 """
6076 6076
6077 6077 opts = pycompat.byteskwargs(opts)
6078 6078 if opts.get(b"date"):
6079 6079 cmdutil.check_incompatible_arguments(opts, b'date', [b'rev'])
6080 6080 opts[b"rev"] = cmdutil.finddate(ui, repo, opts[b"date"])
6081 6081
6082 6082 parent, p2 = repo.dirstate.parents()
6083 6083 if not opts.get(b'rev') and p2 != nullid:
6084 6084 # revert after merge is a trap for new users (issue2915)
6085 6085 raise error.Abort(
6086 6086 _(b'uncommitted merge with no revision specified'),
6087 6087 hint=_(b"use 'hg update' or see 'hg help revert'"),
6088 6088 )
6089 6089
6090 6090 rev = opts.get(b'rev')
6091 6091 if rev:
6092 6092 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
6093 6093 ctx = scmutil.revsingle(repo, rev)
6094 6094
6095 6095 if not (
6096 6096 pats
6097 6097 or opts.get(b'include')
6098 6098 or opts.get(b'exclude')
6099 6099 or opts.get(b'all')
6100 6100 or opts.get(b'interactive')
6101 6101 ):
6102 6102 msg = _(b"no files or directories specified")
6103 6103 if p2 != nullid:
6104 6104 hint = _(
6105 6105 b"uncommitted merge, use --all to discard all changes,"
6106 6106 b" or 'hg update -C .' to abort the merge"
6107 6107 )
6108 6108 raise error.Abort(msg, hint=hint)
6109 6109 dirty = any(repo.status())
6110 6110 node = ctx.node()
6111 6111 if node != parent:
6112 6112 if dirty:
6113 6113 hint = (
6114 6114 _(
6115 6115 b"uncommitted changes, use --all to discard all"
6116 6116 b" changes, or 'hg update %d' to update"
6117 6117 )
6118 6118 % ctx.rev()
6119 6119 )
6120 6120 else:
6121 6121 hint = (
6122 6122 _(
6123 6123 b"use --all to revert all files,"
6124 6124 b" or 'hg update %d' to update"
6125 6125 )
6126 6126 % ctx.rev()
6127 6127 )
6128 6128 elif dirty:
6129 6129 hint = _(b"uncommitted changes, use --all to discard all changes")
6130 6130 else:
6131 6131 hint = _(b"use --all to revert all files")
6132 6132 raise error.Abort(msg, hint=hint)
6133 6133
6134 6134 return cmdutil.revert(ui, repo, ctx, *pats, **pycompat.strkwargs(opts))
6135 6135
6136 6136
6137 6137 @command(
6138 6138 b'rollback',
6139 6139 dryrunopts + [(b'f', b'force', False, _(b'ignore safety measures'))],
6140 6140 helpcategory=command.CATEGORY_MAINTENANCE,
6141 6141 )
6142 6142 def rollback(ui, repo, **opts):
6143 6143 """roll back the last transaction (DANGEROUS) (DEPRECATED)
6144 6144
6145 6145 Please use :hg:`commit --amend` instead of rollback to correct
6146 6146 mistakes in the last commit.
6147 6147
6148 6148 This command should be used with care. There is only one level of
6149 6149 rollback, and there is no way to undo a rollback. It will also
6150 6150 restore the dirstate at the time of the last transaction, losing
6151 6151 any dirstate changes since that time. This command does not alter
6152 6152 the working directory.
6153 6153
6154 6154 Transactions are used to encapsulate the effects of all commands
6155 6155 that create new changesets or propagate existing changesets into a
6156 6156 repository.
6157 6157
6158 6158 .. container:: verbose
6159 6159
6160 6160 For example, the following commands are transactional, and their
6161 6161 effects can be rolled back:
6162 6162
6163 6163 - commit
6164 6164 - import
6165 6165 - pull
6166 6166 - push (with this repository as the destination)
6167 6167 - unbundle
6168 6168
6169 6169 To avoid permanent data loss, rollback will refuse to rollback a
6170 6170 commit transaction if it isn't checked out. Use --force to
6171 6171 override this protection.
6172 6172
6173 6173 The rollback command can be entirely disabled by setting the
6174 6174 ``ui.rollback`` configuration setting to false. If you're here
6175 6175 because you want to use rollback and it's disabled, you can
6176 6176 re-enable the command by setting ``ui.rollback`` to true.
6177 6177
6178 6178 This command is not intended for use on public repositories. Once
6179 6179 changes are visible for pull by other users, rolling a transaction
6180 6180 back locally is ineffective (someone else may already have pulled
6181 6181 the changes). Furthermore, a race is possible with readers of the
6182 6182 repository; for example an in-progress pull from the repository
6183 6183 may fail if a rollback is performed.
6184 6184
6185 6185 Returns 0 on success, 1 if no rollback data is available.
6186 6186 """
6187 6187 if not ui.configbool(b'ui', b'rollback'):
6188 6188 raise error.Abort(
6189 6189 _(b'rollback is disabled because it is unsafe'),
6190 6190 hint=b'see `hg help -v rollback` for information',
6191 6191 )
6192 6192 return repo.rollback(dryrun=opts.get('dry_run'), force=opts.get('force'))
6193 6193
6194 6194
6195 6195 @command(
6196 6196 b'root',
6197 6197 [] + formatteropts,
6198 6198 intents={INTENT_READONLY},
6199 6199 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6200 6200 )
6201 6201 def root(ui, repo, **opts):
6202 6202 """print the root (top) of the current working directory
6203 6203
6204 6204 Print the root directory of the current repository.
6205 6205
6206 6206 .. container:: verbose
6207 6207
6208 6208 Template:
6209 6209
6210 6210 The following keywords are supported in addition to the common template
6211 6211 keywords and functions. See also :hg:`help templates`.
6212 6212
6213 6213 :hgpath: String. Path to the .hg directory.
6214 6214 :storepath: String. Path to the directory holding versioned data.
6215 6215
6216 6216 Returns 0 on success.
6217 6217 """
6218 6218 opts = pycompat.byteskwargs(opts)
6219 6219 with ui.formatter(b'root', opts) as fm:
6220 6220 fm.startitem()
6221 6221 fm.write(b'reporoot', b'%s\n', repo.root)
6222 6222 fm.data(hgpath=repo.path, storepath=repo.spath)
6223 6223
6224 6224
6225 6225 @command(
6226 6226 b'serve',
6227 6227 [
6228 6228 (
6229 6229 b'A',
6230 6230 b'accesslog',
6231 6231 b'',
6232 6232 _(b'name of access log file to write to'),
6233 6233 _(b'FILE'),
6234 6234 ),
6235 6235 (b'd', b'daemon', None, _(b'run server in background')),
6236 6236 (b'', b'daemon-postexec', [], _(b'used internally by daemon mode')),
6237 6237 (
6238 6238 b'E',
6239 6239 b'errorlog',
6240 6240 b'',
6241 6241 _(b'name of error log file to write to'),
6242 6242 _(b'FILE'),
6243 6243 ),
6244 6244 # use string type, then we can check if something was passed
6245 6245 (
6246 6246 b'p',
6247 6247 b'port',
6248 6248 b'',
6249 6249 _(b'port to listen on (default: 8000)'),
6250 6250 _(b'PORT'),
6251 6251 ),
6252 6252 (
6253 6253 b'a',
6254 6254 b'address',
6255 6255 b'',
6256 6256 _(b'address to listen on (default: all interfaces)'),
6257 6257 _(b'ADDR'),
6258 6258 ),
6259 6259 (
6260 6260 b'',
6261 6261 b'prefix',
6262 6262 b'',
6263 6263 _(b'prefix path to serve from (default: server root)'),
6264 6264 _(b'PREFIX'),
6265 6265 ),
6266 6266 (
6267 6267 b'n',
6268 6268 b'name',
6269 6269 b'',
6270 6270 _(b'name to show in web pages (default: working directory)'),
6271 6271 _(b'NAME'),
6272 6272 ),
6273 6273 (
6274 6274 b'',
6275 6275 b'web-conf',
6276 6276 b'',
6277 6277 _(b"name of the hgweb config file (see 'hg help hgweb')"),
6278 6278 _(b'FILE'),
6279 6279 ),
6280 6280 (
6281 6281 b'',
6282 6282 b'webdir-conf',
6283 6283 b'',
6284 6284 _(b'name of the hgweb config file (DEPRECATED)'),
6285 6285 _(b'FILE'),
6286 6286 ),
6287 6287 (
6288 6288 b'',
6289 6289 b'pid-file',
6290 6290 b'',
6291 6291 _(b'name of file to write process ID to'),
6292 6292 _(b'FILE'),
6293 6293 ),
6294 6294 (b'', b'stdio', None, _(b'for remote clients (ADVANCED)')),
6295 6295 (
6296 6296 b'',
6297 6297 b'cmdserver',
6298 6298 b'',
6299 6299 _(b'for remote clients (ADVANCED)'),
6300 6300 _(b'MODE'),
6301 6301 ),
6302 6302 (b't', b'templates', b'', _(b'web templates to use'), _(b'TEMPLATE')),
6303 6303 (b'', b'style', b'', _(b'template style to use'), _(b'STYLE')),
6304 6304 (b'6', b'ipv6', None, _(b'use IPv6 in addition to IPv4')),
6305 6305 (b'', b'certificate', b'', _(b'SSL certificate file'), _(b'FILE')),
6306 6306 (b'', b'print-url', None, _(b'start and print only the URL')),
6307 6307 ]
6308 6308 + subrepoopts,
6309 6309 _(b'[OPTION]...'),
6310 6310 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
6311 6311 helpbasic=True,
6312 6312 optionalrepo=True,
6313 6313 )
6314 6314 def serve(ui, repo, **opts):
6315 6315 """start stand-alone webserver
6316 6316
6317 6317 Start a local HTTP repository browser and pull server. You can use
6318 6318 this for ad-hoc sharing and browsing of repositories. It is
6319 6319 recommended to use a real web server to serve a repository for
6320 6320 longer periods of time.
6321 6321
6322 6322 Please note that the server does not implement access control.
6323 6323 This means that, by default, anybody can read from the server and
6324 6324 nobody can write to it by default. Set the ``web.allow-push``
6325 6325 option to ``*`` to allow everybody to push to the server. You
6326 6326 should use a real web server if you need to authenticate users.
6327 6327
6328 6328 By default, the server logs accesses to stdout and errors to
6329 6329 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
6330 6330 files.
6331 6331
6332 6332 To have the server choose a free port number to listen on, specify
6333 6333 a port number of 0; in this case, the server will print the port
6334 6334 number it uses.
6335 6335
6336 6336 Returns 0 on success.
6337 6337 """
6338 6338
6339 6339 cmdutil.check_incompatible_arguments(opts, 'stdio', ['cmdserver'])
6340 6340 opts = pycompat.byteskwargs(opts)
6341 6341 if opts[b"print_url"] and ui.verbose:
6342 6342 raise error.Abort(_(b"cannot use --print-url with --verbose"))
6343 6343
6344 6344 if opts[b"stdio"]:
6345 6345 if repo is None:
6346 6346 raise error.RepoError(
6347 6347 _(b"there is no Mercurial repository here (.hg not found)")
6348 6348 )
6349 6349 s = wireprotoserver.sshserver(ui, repo)
6350 6350 s.serve_forever()
6351 sys.exit(0)
6351 6352
6352 6353 service = server.createservice(ui, repo, opts)
6353 6354 return server.runservice(opts, initfn=service.init, runfn=service.run)
6354 6355
6355 6356
6356 6357 @command(
6357 6358 b'shelve',
6358 6359 [
6359 6360 (
6360 6361 b'A',
6361 6362 b'addremove',
6362 6363 None,
6363 6364 _(b'mark new/missing files as added/removed before shelving'),
6364 6365 ),
6365 6366 (b'u', b'unknown', None, _(b'store unknown files in the shelve')),
6366 6367 (b'', b'cleanup', None, _(b'delete all shelved changes')),
6367 6368 (
6368 6369 b'',
6369 6370 b'date',
6370 6371 b'',
6371 6372 _(b'shelve with the specified commit date'),
6372 6373 _(b'DATE'),
6373 6374 ),
6374 6375 (b'd', b'delete', None, _(b'delete the named shelved change(s)')),
6375 6376 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
6376 6377 (
6377 6378 b'k',
6378 6379 b'keep',
6379 6380 False,
6380 6381 _(b'shelve, but keep changes in the working directory'),
6381 6382 ),
6382 6383 (b'l', b'list', None, _(b'list current shelves')),
6383 6384 (b'm', b'message', b'', _(b'use text as shelve message'), _(b'TEXT')),
6384 6385 (
6385 6386 b'n',
6386 6387 b'name',
6387 6388 b'',
6388 6389 _(b'use the given name for the shelved commit'),
6389 6390 _(b'NAME'),
6390 6391 ),
6391 6392 (
6392 6393 b'p',
6393 6394 b'patch',
6394 6395 None,
6395 6396 _(
6396 6397 b'output patches for changes (provide the names of the shelved '
6397 6398 b'changes as positional arguments)'
6398 6399 ),
6399 6400 ),
6400 6401 (b'i', b'interactive', None, _(b'interactive mode')),
6401 6402 (
6402 6403 b'',
6403 6404 b'stat',
6404 6405 None,
6405 6406 _(
6406 6407 b'output diffstat-style summary of changes (provide the names of '
6407 6408 b'the shelved changes as positional arguments)'
6408 6409 ),
6409 6410 ),
6410 6411 ]
6411 6412 + cmdutil.walkopts,
6412 6413 _(b'hg shelve [OPTION]... [FILE]...'),
6413 6414 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6414 6415 )
6415 6416 def shelve(ui, repo, *pats, **opts):
6416 6417 '''save and set aside changes from the working directory
6417 6418
6418 6419 Shelving takes files that "hg status" reports as not clean, saves
6419 6420 the modifications to a bundle (a shelved change), and reverts the
6420 6421 files so that their state in the working directory becomes clean.
6421 6422
6422 6423 To restore these changes to the working directory, using "hg
6423 6424 unshelve"; this will work even if you switch to a different
6424 6425 commit.
6425 6426
6426 6427 When no files are specified, "hg shelve" saves all not-clean
6427 6428 files. If specific files or directories are named, only changes to
6428 6429 those files are shelved.
6429 6430
6430 6431 In bare shelve (when no files are specified, without interactive,
6431 6432 include and exclude option), shelving remembers information if the
6432 6433 working directory was on newly created branch, in other words working
6433 6434 directory was on different branch than its first parent. In this
6434 6435 situation unshelving restores branch information to the working directory.
6435 6436
6436 6437 Each shelved change has a name that makes it easier to find later.
6437 6438 The name of a shelved change defaults to being based on the active
6438 6439 bookmark, or if there is no active bookmark, the current named
6439 6440 branch. To specify a different name, use ``--name``.
6440 6441
6441 6442 To see a list of existing shelved changes, use the ``--list``
6442 6443 option. For each shelved change, this will print its name, age,
6443 6444 and description; use ``--patch`` or ``--stat`` for more details.
6444 6445
6445 6446 To delete specific shelved changes, use ``--delete``. To delete
6446 6447 all shelved changes, use ``--cleanup``.
6447 6448 '''
6448 6449 opts = pycompat.byteskwargs(opts)
6449 6450 allowables = [
6450 6451 (b'addremove', {b'create'}), # 'create' is pseudo action
6451 6452 (b'unknown', {b'create'}),
6452 6453 (b'cleanup', {b'cleanup'}),
6453 6454 # ('date', {'create'}), # ignored for passing '--date "0 0"' in tests
6454 6455 (b'delete', {b'delete'}),
6455 6456 (b'edit', {b'create'}),
6456 6457 (b'keep', {b'create'}),
6457 6458 (b'list', {b'list'}),
6458 6459 (b'message', {b'create'}),
6459 6460 (b'name', {b'create'}),
6460 6461 (b'patch', {b'patch', b'list'}),
6461 6462 (b'stat', {b'stat', b'list'}),
6462 6463 ]
6463 6464
6464 6465 def checkopt(opt):
6465 6466 if opts.get(opt):
6466 6467 for i, allowable in allowables:
6467 6468 if opts[i] and opt not in allowable:
6468 6469 raise error.Abort(
6469 6470 _(
6470 6471 b"options '--%s' and '--%s' may not be "
6471 6472 b"used together"
6472 6473 )
6473 6474 % (opt, i)
6474 6475 )
6475 6476 return True
6476 6477
6477 6478 if checkopt(b'cleanup'):
6478 6479 if pats:
6479 6480 raise error.Abort(_(b"cannot specify names when using '--cleanup'"))
6480 6481 return shelvemod.cleanupcmd(ui, repo)
6481 6482 elif checkopt(b'delete'):
6482 6483 return shelvemod.deletecmd(ui, repo, pats)
6483 6484 elif checkopt(b'list'):
6484 6485 return shelvemod.listcmd(ui, repo, pats, opts)
6485 6486 elif checkopt(b'patch') or checkopt(b'stat'):
6486 6487 return shelvemod.patchcmds(ui, repo, pats, opts)
6487 6488 else:
6488 6489 return shelvemod.createcmd(ui, repo, pats, opts)
6489 6490
6490 6491
6491 6492 _NOTTERSE = b'nothing'
6492 6493
6493 6494
6494 6495 @command(
6495 6496 b'status|st',
6496 6497 [
6497 6498 (b'A', b'all', None, _(b'show status of all files')),
6498 6499 (b'm', b'modified', None, _(b'show only modified files')),
6499 6500 (b'a', b'added', None, _(b'show only added files')),
6500 6501 (b'r', b'removed', None, _(b'show only removed files')),
6501 6502 (b'd', b'deleted', None, _(b'show only missing files')),
6502 6503 (b'c', b'clean', None, _(b'show only files without changes')),
6503 6504 (b'u', b'unknown', None, _(b'show only unknown (not tracked) files')),
6504 6505 (b'i', b'ignored', None, _(b'show only ignored files')),
6505 6506 (b'n', b'no-status', None, _(b'hide status prefix')),
6506 6507 (b't', b'terse', _NOTTERSE, _(b'show the terse output (EXPERIMENTAL)')),
6507 6508 (
6508 6509 b'C',
6509 6510 b'copies',
6510 6511 None,
6511 6512 _(b'show source of copied files (DEFAULT: ui.statuscopies)'),
6512 6513 ),
6513 6514 (
6514 6515 b'0',
6515 6516 b'print0',
6516 6517 None,
6517 6518 _(b'end filenames with NUL, for use with xargs'),
6518 6519 ),
6519 6520 (b'', b'rev', [], _(b'show difference from revision'), _(b'REV')),
6520 6521 (
6521 6522 b'',
6522 6523 b'change',
6523 6524 b'',
6524 6525 _(b'list the changed files of a revision'),
6525 6526 _(b'REV'),
6526 6527 ),
6527 6528 ]
6528 6529 + walkopts
6529 6530 + subrepoopts
6530 6531 + formatteropts,
6531 6532 _(b'[OPTION]... [FILE]...'),
6532 6533 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6533 6534 helpbasic=True,
6534 6535 inferrepo=True,
6535 6536 intents={INTENT_READONLY},
6536 6537 )
6537 6538 def status(ui, repo, *pats, **opts):
6538 6539 """show changed files in the working directory
6539 6540
6540 6541 Show status of files in the repository. If names are given, only
6541 6542 files that match are shown. Files that are clean or ignored or
6542 6543 the source of a copy/move operation, are not listed unless
6543 6544 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
6544 6545 Unless options described with "show only ..." are given, the
6545 6546 options -mardu are used.
6546 6547
6547 6548 Option -q/--quiet hides untracked (unknown and ignored) files
6548 6549 unless explicitly requested with -u/--unknown or -i/--ignored.
6549 6550
6550 6551 .. note::
6551 6552
6552 6553 :hg:`status` may appear to disagree with diff if permissions have
6553 6554 changed or a merge has occurred. The standard diff format does
6554 6555 not report permission changes and diff only reports changes
6555 6556 relative to one merge parent.
6556 6557
6557 6558 If one revision is given, it is used as the base revision.
6558 6559 If two revisions are given, the differences between them are
6559 6560 shown. The --change option can also be used as a shortcut to list
6560 6561 the changed files of a revision from its first parent.
6561 6562
6562 6563 The codes used to show the status of files are::
6563 6564
6564 6565 M = modified
6565 6566 A = added
6566 6567 R = removed
6567 6568 C = clean
6568 6569 ! = missing (deleted by non-hg command, but still tracked)
6569 6570 ? = not tracked
6570 6571 I = ignored
6571 6572 = origin of the previous file (with --copies)
6572 6573
6573 6574 .. container:: verbose
6574 6575
6575 6576 The -t/--terse option abbreviates the output by showing only the directory
6576 6577 name if all the files in it share the same status. The option takes an
6577 6578 argument indicating the statuses to abbreviate: 'm' for 'modified', 'a'
6578 6579 for 'added', 'r' for 'removed', 'd' for 'deleted', 'u' for 'unknown', 'i'
6579 6580 for 'ignored' and 'c' for clean.
6580 6581
6581 6582 It abbreviates only those statuses which are passed. Note that clean and
6582 6583 ignored files are not displayed with '--terse ic' unless the -c/--clean
6583 6584 and -i/--ignored options are also used.
6584 6585
6585 6586 The -v/--verbose option shows information when the repository is in an
6586 6587 unfinished merge, shelve, rebase state etc. You can have this behavior
6587 6588 turned on by default by enabling the ``commands.status.verbose`` option.
6588 6589
6589 6590 You can skip displaying some of these states by setting
6590 6591 ``commands.status.skipstates`` to one or more of: 'bisect', 'graft',
6591 6592 'histedit', 'merge', 'rebase', or 'unshelve'.
6592 6593
6593 6594 Template:
6594 6595
6595 6596 The following keywords are supported in addition to the common template
6596 6597 keywords and functions. See also :hg:`help templates`.
6597 6598
6598 6599 :path: String. Repository-absolute path of the file.
6599 6600 :source: String. Repository-absolute path of the file originated from.
6600 6601 Available if ``--copies`` is specified.
6601 6602 :status: String. Character denoting file's status.
6602 6603
6603 6604 Examples:
6604 6605
6605 6606 - show changes in the working directory relative to a
6606 6607 changeset::
6607 6608
6608 6609 hg status --rev 9353
6609 6610
6610 6611 - show changes in the working directory relative to the
6611 6612 current directory (see :hg:`help patterns` for more information)::
6612 6613
6613 6614 hg status re:
6614 6615
6615 6616 - show all changes including copies in an existing changeset::
6616 6617
6617 6618 hg status --copies --change 9353
6618 6619
6619 6620 - get a NUL separated list of added files, suitable for xargs::
6620 6621
6621 6622 hg status -an0
6622 6623
6623 6624 - show more information about the repository status, abbreviating
6624 6625 added, removed, modified, deleted, and untracked paths::
6625 6626
6626 6627 hg status -v -t mardu
6627 6628
6628 6629 Returns 0 on success.
6629 6630
6630 6631 """
6631 6632
6632 6633 cmdutil.check_at_most_one_arg(opts, 'rev', 'change')
6633 6634 opts = pycompat.byteskwargs(opts)
6634 6635 revs = opts.get(b'rev')
6635 6636 change = opts.get(b'change')
6636 6637 terse = opts.get(b'terse')
6637 6638 if terse is _NOTTERSE:
6638 6639 if revs:
6639 6640 terse = b''
6640 6641 else:
6641 6642 terse = ui.config(b'commands', b'status.terse')
6642 6643
6643 6644 if revs and terse:
6644 6645 msg = _(b'cannot use --terse with --rev')
6645 6646 raise error.Abort(msg)
6646 6647 elif change:
6647 6648 repo = scmutil.unhidehashlikerevs(repo, [change], b'nowarn')
6648 6649 ctx2 = scmutil.revsingle(repo, change, None)
6649 6650 ctx1 = ctx2.p1()
6650 6651 else:
6651 6652 repo = scmutil.unhidehashlikerevs(repo, revs, b'nowarn')
6652 6653 ctx1, ctx2 = scmutil.revpair(repo, revs)
6653 6654
6654 6655 forcerelativevalue = None
6655 6656 if ui.hasconfig(b'commands', b'status.relative'):
6656 6657 forcerelativevalue = ui.configbool(b'commands', b'status.relative')
6657 6658 uipathfn = scmutil.getuipathfn(
6658 6659 repo,
6659 6660 legacyrelativevalue=bool(pats),
6660 6661 forcerelativevalue=forcerelativevalue,
6661 6662 )
6662 6663
6663 6664 if opts.get(b'print0'):
6664 6665 end = b'\0'
6665 6666 else:
6666 6667 end = b'\n'
6667 6668 states = b'modified added removed deleted unknown ignored clean'.split()
6668 6669 show = [k for k in states if opts.get(k)]
6669 6670 if opts.get(b'all'):
6670 6671 show += ui.quiet and (states[:4] + [b'clean']) or states
6671 6672
6672 6673 if not show:
6673 6674 if ui.quiet:
6674 6675 show = states[:4]
6675 6676 else:
6676 6677 show = states[:5]
6677 6678
6678 6679 m = scmutil.match(ctx2, pats, opts)
6679 6680 if terse:
6680 6681 # we need to compute clean and unknown to terse
6681 6682 stat = repo.status(
6682 6683 ctx1.node(),
6683 6684 ctx2.node(),
6684 6685 m,
6685 6686 b'ignored' in show or b'i' in terse,
6686 6687 clean=True,
6687 6688 unknown=True,
6688 6689 listsubrepos=opts.get(b'subrepos'),
6689 6690 )
6690 6691
6691 6692 stat = cmdutil.tersedir(stat, terse)
6692 6693 else:
6693 6694 stat = repo.status(
6694 6695 ctx1.node(),
6695 6696 ctx2.node(),
6696 6697 m,
6697 6698 b'ignored' in show,
6698 6699 b'clean' in show,
6699 6700 b'unknown' in show,
6700 6701 opts.get(b'subrepos'),
6701 6702 )
6702 6703
6703 6704 changestates = zip(
6704 6705 states,
6705 6706 pycompat.iterbytestr(b'MAR!?IC'),
6706 6707 [getattr(stat, s.decode('utf8')) for s in states],
6707 6708 )
6708 6709
6709 6710 copy = {}
6710 6711 if (
6711 6712 opts.get(b'all')
6712 6713 or opts.get(b'copies')
6713 6714 or ui.configbool(b'ui', b'statuscopies')
6714 6715 ) and not opts.get(b'no_status'):
6715 6716 copy = copies.pathcopies(ctx1, ctx2, m)
6716 6717
6717 6718 morestatus = None
6718 6719 if (
6719 6720 ui.verbose or ui.configbool(b'commands', b'status.verbose')
6720 6721 ) and not ui.plain():
6721 6722 morestatus = cmdutil.readmorestatus(repo)
6722 6723
6723 6724 ui.pager(b'status')
6724 6725 fm = ui.formatter(b'status', opts)
6725 6726 fmt = b'%s' + end
6726 6727 showchar = not opts.get(b'no_status')
6727 6728
6728 6729 for state, char, files in changestates:
6729 6730 if state in show:
6730 6731 label = b'status.' + state
6731 6732 for f in files:
6732 6733 fm.startitem()
6733 6734 fm.context(ctx=ctx2)
6734 6735 fm.data(itemtype=b'file', path=f)
6735 6736 fm.condwrite(showchar, b'status', b'%s ', char, label=label)
6736 6737 fm.plain(fmt % uipathfn(f), label=label)
6737 6738 if f in copy:
6738 6739 fm.data(source=copy[f])
6739 6740 fm.plain(
6740 6741 (b' %s' + end) % uipathfn(copy[f]),
6741 6742 label=b'status.copied',
6742 6743 )
6743 6744 if morestatus:
6744 6745 morestatus.formatfile(f, fm)
6745 6746
6746 6747 if morestatus:
6747 6748 morestatus.formatfooter(fm)
6748 6749 fm.end()
6749 6750
6750 6751
6751 6752 @command(
6752 6753 b'summary|sum',
6753 6754 [(b'', b'remote', None, _(b'check for push and pull'))],
6754 6755 b'[--remote]',
6755 6756 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6756 6757 helpbasic=True,
6757 6758 intents={INTENT_READONLY},
6758 6759 )
6759 6760 def summary(ui, repo, **opts):
6760 6761 """summarize working directory state
6761 6762
6762 6763 This generates a brief summary of the working directory state,
6763 6764 including parents, branch, commit status, phase and available updates.
6764 6765
6765 6766 With the --remote option, this will check the default paths for
6766 6767 incoming and outgoing changes. This can be time-consuming.
6767 6768
6768 6769 Returns 0 on success.
6769 6770 """
6770 6771
6771 6772 opts = pycompat.byteskwargs(opts)
6772 6773 ui.pager(b'summary')
6773 6774 ctx = repo[None]
6774 6775 parents = ctx.parents()
6775 6776 pnode = parents[0].node()
6776 6777 marks = []
6777 6778
6778 6779 try:
6779 6780 ms = mergestatemod.mergestate.read(repo)
6780 6781 except error.UnsupportedMergeRecords as e:
6781 6782 s = b' '.join(e.recordtypes)
6782 6783 ui.warn(
6783 6784 _(b'warning: merge state has unsupported record types: %s\n') % s
6784 6785 )
6785 6786 unresolved = []
6786 6787 else:
6787 6788 unresolved = list(ms.unresolved())
6788 6789
6789 6790 for p in parents:
6790 6791 # label with log.changeset (instead of log.parent) since this
6791 6792 # shows a working directory parent *changeset*:
6792 6793 # i18n: column positioning for "hg summary"
6793 6794 ui.write(
6794 6795 _(b'parent: %d:%s ') % (p.rev(), p),
6795 6796 label=logcmdutil.changesetlabels(p),
6796 6797 )
6797 6798 ui.write(b' '.join(p.tags()), label=b'log.tag')
6798 6799 if p.bookmarks():
6799 6800 marks.extend(p.bookmarks())
6800 6801 if p.rev() == -1:
6801 6802 if not len(repo):
6802 6803 ui.write(_(b' (empty repository)'))
6803 6804 else:
6804 6805 ui.write(_(b' (no revision checked out)'))
6805 6806 if p.obsolete():
6806 6807 ui.write(_(b' (obsolete)'))
6807 6808 if p.isunstable():
6808 6809 instabilities = (
6809 6810 ui.label(instability, b'trouble.%s' % instability)
6810 6811 for instability in p.instabilities()
6811 6812 )
6812 6813 ui.write(b' (' + b', '.join(instabilities) + b')')
6813 6814 ui.write(b'\n')
6814 6815 if p.description():
6815 6816 ui.status(
6816 6817 b' ' + p.description().splitlines()[0].strip() + b'\n',
6817 6818 label=b'log.summary',
6818 6819 )
6819 6820
6820 6821 branch = ctx.branch()
6821 6822 bheads = repo.branchheads(branch)
6822 6823 # i18n: column positioning for "hg summary"
6823 6824 m = _(b'branch: %s\n') % branch
6824 6825 if branch != b'default':
6825 6826 ui.write(m, label=b'log.branch')
6826 6827 else:
6827 6828 ui.status(m, label=b'log.branch')
6828 6829
6829 6830 if marks:
6830 6831 active = repo._activebookmark
6831 6832 # i18n: column positioning for "hg summary"
6832 6833 ui.write(_(b'bookmarks:'), label=b'log.bookmark')
6833 6834 if active is not None:
6834 6835 if active in marks:
6835 6836 ui.write(b' *' + active, label=bookmarks.activebookmarklabel)
6836 6837 marks.remove(active)
6837 6838 else:
6838 6839 ui.write(b' [%s]' % active, label=bookmarks.activebookmarklabel)
6839 6840 for m in marks:
6840 6841 ui.write(b' ' + m, label=b'log.bookmark')
6841 6842 ui.write(b'\n', label=b'log.bookmark')
6842 6843
6843 6844 status = repo.status(unknown=True)
6844 6845
6845 6846 c = repo.dirstate.copies()
6846 6847 copied, renamed = [], []
6847 6848 for d, s in pycompat.iteritems(c):
6848 6849 if s in status.removed:
6849 6850 status.removed.remove(s)
6850 6851 renamed.append(d)
6851 6852 else:
6852 6853 copied.append(d)
6853 6854 if d in status.added:
6854 6855 status.added.remove(d)
6855 6856
6856 6857 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
6857 6858
6858 6859 labels = [
6859 6860 (ui.label(_(b'%d modified'), b'status.modified'), status.modified),
6860 6861 (ui.label(_(b'%d added'), b'status.added'), status.added),
6861 6862 (ui.label(_(b'%d removed'), b'status.removed'), status.removed),
6862 6863 (ui.label(_(b'%d renamed'), b'status.copied'), renamed),
6863 6864 (ui.label(_(b'%d copied'), b'status.copied'), copied),
6864 6865 (ui.label(_(b'%d deleted'), b'status.deleted'), status.deleted),
6865 6866 (ui.label(_(b'%d unknown'), b'status.unknown'), status.unknown),
6866 6867 (ui.label(_(b'%d unresolved'), b'resolve.unresolved'), unresolved),
6867 6868 (ui.label(_(b'%d subrepos'), b'status.modified'), subs),
6868 6869 ]
6869 6870 t = []
6870 6871 for l, s in labels:
6871 6872 if s:
6872 6873 t.append(l % len(s))
6873 6874
6874 6875 t = b', '.join(t)
6875 6876 cleanworkdir = False
6876 6877
6877 6878 if repo.vfs.exists(b'graftstate'):
6878 6879 t += _(b' (graft in progress)')
6879 6880 if repo.vfs.exists(b'updatestate'):
6880 6881 t += _(b' (interrupted update)')
6881 6882 elif len(parents) > 1:
6882 6883 t += _(b' (merge)')
6883 6884 elif branch != parents[0].branch():
6884 6885 t += _(b' (new branch)')
6885 6886 elif parents[0].closesbranch() and pnode in repo.branchheads(
6886 6887 branch, closed=True
6887 6888 ):
6888 6889 t += _(b' (head closed)')
6889 6890 elif not (
6890 6891 status.modified
6891 6892 or status.added
6892 6893 or status.removed
6893 6894 or renamed
6894 6895 or copied
6895 6896 or subs
6896 6897 ):
6897 6898 t += _(b' (clean)')
6898 6899 cleanworkdir = True
6899 6900 elif pnode not in bheads:
6900 6901 t += _(b' (new branch head)')
6901 6902
6902 6903 if parents:
6903 6904 pendingphase = max(p.phase() for p in parents)
6904 6905 else:
6905 6906 pendingphase = phases.public
6906 6907
6907 6908 if pendingphase > phases.newcommitphase(ui):
6908 6909 t += b' (%s)' % phases.phasenames[pendingphase]
6909 6910
6910 6911 if cleanworkdir:
6911 6912 # i18n: column positioning for "hg summary"
6912 6913 ui.status(_(b'commit: %s\n') % t.strip())
6913 6914 else:
6914 6915 # i18n: column positioning for "hg summary"
6915 6916 ui.write(_(b'commit: %s\n') % t.strip())
6916 6917
6917 6918 # all ancestors of branch heads - all ancestors of parent = new csets
6918 6919 new = len(
6919 6920 repo.changelog.findmissing([pctx.node() for pctx in parents], bheads)
6920 6921 )
6921 6922
6922 6923 if new == 0:
6923 6924 # i18n: column positioning for "hg summary"
6924 6925 ui.status(_(b'update: (current)\n'))
6925 6926 elif pnode not in bheads:
6926 6927 # i18n: column positioning for "hg summary"
6927 6928 ui.write(_(b'update: %d new changesets (update)\n') % new)
6928 6929 else:
6929 6930 # i18n: column positioning for "hg summary"
6930 6931 ui.write(
6931 6932 _(b'update: %d new changesets, %d branch heads (merge)\n')
6932 6933 % (new, len(bheads))
6933 6934 )
6934 6935
6935 6936 t = []
6936 6937 draft = len(repo.revs(b'draft()'))
6937 6938 if draft:
6938 6939 t.append(_(b'%d draft') % draft)
6939 6940 secret = len(repo.revs(b'secret()'))
6940 6941 if secret:
6941 6942 t.append(_(b'%d secret') % secret)
6942 6943
6943 6944 if draft or secret:
6944 6945 ui.status(_(b'phases: %s\n') % b', '.join(t))
6945 6946
6946 6947 if obsolete.isenabled(repo, obsolete.createmarkersopt):
6947 6948 for trouble in (b"orphan", b"contentdivergent", b"phasedivergent"):
6948 6949 numtrouble = len(repo.revs(trouble + b"()"))
6949 6950 # We write all the possibilities to ease translation
6950 6951 troublemsg = {
6951 6952 b"orphan": _(b"orphan: %d changesets"),
6952 6953 b"contentdivergent": _(b"content-divergent: %d changesets"),
6953 6954 b"phasedivergent": _(b"phase-divergent: %d changesets"),
6954 6955 }
6955 6956 if numtrouble > 0:
6956 6957 ui.status(troublemsg[trouble] % numtrouble + b"\n")
6957 6958
6958 6959 cmdutil.summaryhooks(ui, repo)
6959 6960
6960 6961 if opts.get(b'remote'):
6961 6962 needsincoming, needsoutgoing = True, True
6962 6963 else:
6963 6964 needsincoming, needsoutgoing = False, False
6964 6965 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
6965 6966 if i:
6966 6967 needsincoming = True
6967 6968 if o:
6968 6969 needsoutgoing = True
6969 6970 if not needsincoming and not needsoutgoing:
6970 6971 return
6971 6972
6972 6973 def getincoming():
6973 6974 source, branches = hg.parseurl(ui.expandpath(b'default'))
6974 6975 sbranch = branches[0]
6975 6976 try:
6976 6977 other = hg.peer(repo, {}, source)
6977 6978 except error.RepoError:
6978 6979 if opts.get(b'remote'):
6979 6980 raise
6980 6981 return source, sbranch, None, None, None
6981 6982 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
6982 6983 if revs:
6983 6984 revs = [other.lookup(rev) for rev in revs]
6984 6985 ui.debug(b'comparing with %s\n' % util.hidepassword(source))
6985 6986 repo.ui.pushbuffer()
6986 6987 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
6987 6988 repo.ui.popbuffer()
6988 6989 return source, sbranch, other, commoninc, commoninc[1]
6989 6990
6990 6991 if needsincoming:
6991 6992 source, sbranch, sother, commoninc, incoming = getincoming()
6992 6993 else:
6993 6994 source = sbranch = sother = commoninc = incoming = None
6994 6995
6995 6996 def getoutgoing():
6996 6997 dest, branches = hg.parseurl(ui.expandpath(b'default-push', b'default'))
6997 6998 dbranch = branches[0]
6998 6999 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
6999 7000 if source != dest:
7000 7001 try:
7001 7002 dother = hg.peer(repo, {}, dest)
7002 7003 except error.RepoError:
7003 7004 if opts.get(b'remote'):
7004 7005 raise
7005 7006 return dest, dbranch, None, None
7006 7007 ui.debug(b'comparing with %s\n' % util.hidepassword(dest))
7007 7008 elif sother is None:
7008 7009 # there is no explicit destination peer, but source one is invalid
7009 7010 return dest, dbranch, None, None
7010 7011 else:
7011 7012 dother = sother
7012 7013 if source != dest or (sbranch is not None and sbranch != dbranch):
7013 7014 common = None
7014 7015 else:
7015 7016 common = commoninc
7016 7017 if revs:
7017 7018 revs = [repo.lookup(rev) for rev in revs]
7018 7019 repo.ui.pushbuffer()
7019 7020 outgoing = discovery.findcommonoutgoing(
7020 7021 repo, dother, onlyheads=revs, commoninc=common
7021 7022 )
7022 7023 repo.ui.popbuffer()
7023 7024 return dest, dbranch, dother, outgoing
7024 7025
7025 7026 if needsoutgoing:
7026 7027 dest, dbranch, dother, outgoing = getoutgoing()
7027 7028 else:
7028 7029 dest = dbranch = dother = outgoing = None
7029 7030
7030 7031 if opts.get(b'remote'):
7031 7032 t = []
7032 7033 if incoming:
7033 7034 t.append(_(b'1 or more incoming'))
7034 7035 o = outgoing.missing
7035 7036 if o:
7036 7037 t.append(_(b'%d outgoing') % len(o))
7037 7038 other = dother or sother
7038 7039 if b'bookmarks' in other.listkeys(b'namespaces'):
7039 7040 counts = bookmarks.summary(repo, other)
7040 7041 if counts[0] > 0:
7041 7042 t.append(_(b'%d incoming bookmarks') % counts[0])
7042 7043 if counts[1] > 0:
7043 7044 t.append(_(b'%d outgoing bookmarks') % counts[1])
7044 7045
7045 7046 if t:
7046 7047 # i18n: column positioning for "hg summary"
7047 7048 ui.write(_(b'remote: %s\n') % (b', '.join(t)))
7048 7049 else:
7049 7050 # i18n: column positioning for "hg summary"
7050 7051 ui.status(_(b'remote: (synced)\n'))
7051 7052
7052 7053 cmdutil.summaryremotehooks(
7053 7054 ui,
7054 7055 repo,
7055 7056 opts,
7056 7057 (
7057 7058 (source, sbranch, sother, commoninc),
7058 7059 (dest, dbranch, dother, outgoing),
7059 7060 ),
7060 7061 )
7061 7062
7062 7063
7063 7064 @command(
7064 7065 b'tag',
7065 7066 [
7066 7067 (b'f', b'force', None, _(b'force tag')),
7067 7068 (b'l', b'local', None, _(b'make the tag local')),
7068 7069 (b'r', b'rev', b'', _(b'revision to tag'), _(b'REV')),
7069 7070 (b'', b'remove', None, _(b'remove a tag')),
7070 7071 # -l/--local is already there, commitopts cannot be used
7071 7072 (b'e', b'edit', None, _(b'invoke editor on commit messages')),
7072 7073 (b'm', b'message', b'', _(b'use text as commit message'), _(b'TEXT')),
7073 7074 ]
7074 7075 + commitopts2,
7075 7076 _(b'[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'),
7076 7077 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
7077 7078 )
7078 7079 def tag(ui, repo, name1, *names, **opts):
7079 7080 """add one or more tags for the current or given revision
7080 7081
7081 7082 Name a particular revision using <name>.
7082 7083
7083 7084 Tags are used to name particular revisions of the repository and are
7084 7085 very useful to compare different revisions, to go back to significant
7085 7086 earlier versions or to mark branch points as releases, etc. Changing
7086 7087 an existing tag is normally disallowed; use -f/--force to override.
7087 7088
7088 7089 If no revision is given, the parent of the working directory is
7089 7090 used.
7090 7091
7091 7092 To facilitate version control, distribution, and merging of tags,
7092 7093 they are stored as a file named ".hgtags" which is managed similarly
7093 7094 to other project files and can be hand-edited if necessary. This
7094 7095 also means that tagging creates a new commit. The file
7095 7096 ".hg/localtags" is used for local tags (not shared among
7096 7097 repositories).
7097 7098
7098 7099 Tag commits are usually made at the head of a branch. If the parent
7099 7100 of the working directory is not a branch head, :hg:`tag` aborts; use
7100 7101 -f/--force to force the tag commit to be based on a non-head
7101 7102 changeset.
7102 7103
7103 7104 See :hg:`help dates` for a list of formats valid for -d/--date.
7104 7105
7105 7106 Since tag names have priority over branch names during revision
7106 7107 lookup, using an existing branch name as a tag name is discouraged.
7107 7108
7108 7109 Returns 0 on success.
7109 7110 """
7110 7111 cmdutil.check_incompatible_arguments(opts, 'remove', ['rev'])
7111 7112 opts = pycompat.byteskwargs(opts)
7112 7113 with repo.wlock(), repo.lock():
7113 7114 rev_ = b"."
7114 7115 names = [t.strip() for t in (name1,) + names]
7115 7116 if len(names) != len(set(names)):
7116 7117 raise error.Abort(_(b'tag names must be unique'))
7117 7118 for n in names:
7118 7119 scmutil.checknewlabel(repo, n, b'tag')
7119 7120 if not n:
7120 7121 raise error.Abort(
7121 7122 _(b'tag names cannot consist entirely of whitespace')
7122 7123 )
7123 7124 if opts.get(b'rev'):
7124 7125 rev_ = opts[b'rev']
7125 7126 message = opts.get(b'message')
7126 7127 if opts.get(b'remove'):
7127 7128 if opts.get(b'local'):
7128 7129 expectedtype = b'local'
7129 7130 else:
7130 7131 expectedtype = b'global'
7131 7132
7132 7133 for n in names:
7133 7134 if repo.tagtype(n) == b'global':
7134 7135 alltags = tagsmod.findglobaltags(ui, repo)
7135 7136 if alltags[n][0] == nullid:
7136 7137 raise error.Abort(_(b"tag '%s' is already removed") % n)
7137 7138 if not repo.tagtype(n):
7138 7139 raise error.Abort(_(b"tag '%s' does not exist") % n)
7139 7140 if repo.tagtype(n) != expectedtype:
7140 7141 if expectedtype == b'global':
7141 7142 raise error.Abort(
7142 7143 _(b"tag '%s' is not a global tag") % n
7143 7144 )
7144 7145 else:
7145 7146 raise error.Abort(_(b"tag '%s' is not a local tag") % n)
7146 7147 rev_ = b'null'
7147 7148 if not message:
7148 7149 # we don't translate commit messages
7149 7150 message = b'Removed tag %s' % b', '.join(names)
7150 7151 elif not opts.get(b'force'):
7151 7152 for n in names:
7152 7153 if n in repo.tags():
7153 7154 raise error.Abort(
7154 7155 _(b"tag '%s' already exists (use -f to force)") % n
7155 7156 )
7156 7157 if not opts.get(b'local'):
7157 7158 p1, p2 = repo.dirstate.parents()
7158 7159 if p2 != nullid:
7159 7160 raise error.Abort(_(b'uncommitted merge'))
7160 7161 bheads = repo.branchheads()
7161 7162 if not opts.get(b'force') and bheads and p1 not in bheads:
7162 7163 raise error.Abort(
7163 7164 _(
7164 7165 b'working directory is not at a branch head '
7165 7166 b'(use -f to force)'
7166 7167 )
7167 7168 )
7168 7169 node = scmutil.revsingle(repo, rev_).node()
7169 7170
7170 7171 if not message:
7171 7172 # we don't translate commit messages
7172 7173 message = b'Added tag %s for changeset %s' % (
7173 7174 b', '.join(names),
7174 7175 short(node),
7175 7176 )
7176 7177
7177 7178 date = opts.get(b'date')
7178 7179 if date:
7179 7180 date = dateutil.parsedate(date)
7180 7181
7181 7182 if opts.get(b'remove'):
7182 7183 editform = b'tag.remove'
7183 7184 else:
7184 7185 editform = b'tag.add'
7185 7186 editor = cmdutil.getcommiteditor(
7186 7187 editform=editform, **pycompat.strkwargs(opts)
7187 7188 )
7188 7189
7189 7190 # don't allow tagging the null rev
7190 7191 if (
7191 7192 not opts.get(b'remove')
7192 7193 and scmutil.revsingle(repo, rev_).rev() == nullrev
7193 7194 ):
7194 7195 raise error.Abort(_(b"cannot tag null revision"))
7195 7196
7196 7197 tagsmod.tag(
7197 7198 repo,
7198 7199 names,
7199 7200 node,
7200 7201 message,
7201 7202 opts.get(b'local'),
7202 7203 opts.get(b'user'),
7203 7204 date,
7204 7205 editor=editor,
7205 7206 )
7206 7207
7207 7208
7208 7209 @command(
7209 7210 b'tags',
7210 7211 formatteropts,
7211 7212 b'',
7212 7213 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
7213 7214 intents={INTENT_READONLY},
7214 7215 )
7215 7216 def tags(ui, repo, **opts):
7216 7217 """list repository tags
7217 7218
7218 7219 This lists both regular and local tags. When the -v/--verbose
7219 7220 switch is used, a third column "local" is printed for local tags.
7220 7221 When the -q/--quiet switch is used, only the tag name is printed.
7221 7222
7222 7223 .. container:: verbose
7223 7224
7224 7225 Template:
7225 7226
7226 7227 The following keywords are supported in addition to the common template
7227 7228 keywords and functions such as ``{tag}``. See also
7228 7229 :hg:`help templates`.
7229 7230
7230 7231 :type: String. ``local`` for local tags.
7231 7232
7232 7233 Returns 0 on success.
7233 7234 """
7234 7235
7235 7236 opts = pycompat.byteskwargs(opts)
7236 7237 ui.pager(b'tags')
7237 7238 fm = ui.formatter(b'tags', opts)
7238 7239 hexfunc = fm.hexfunc
7239 7240
7240 7241 for t, n in reversed(repo.tagslist()):
7241 7242 hn = hexfunc(n)
7242 7243 label = b'tags.normal'
7243 7244 tagtype = b''
7244 7245 if repo.tagtype(t) == b'local':
7245 7246 label = b'tags.local'
7246 7247 tagtype = b'local'
7247 7248
7248 7249 fm.startitem()
7249 7250 fm.context(repo=repo)
7250 7251 fm.write(b'tag', b'%s', t, label=label)
7251 7252 fmt = b" " * (30 - encoding.colwidth(t)) + b' %5d:%s'
7252 7253 fm.condwrite(
7253 7254 not ui.quiet,
7254 7255 b'rev node',
7255 7256 fmt,
7256 7257 repo.changelog.rev(n),
7257 7258 hn,
7258 7259 label=label,
7259 7260 )
7260 7261 fm.condwrite(
7261 7262 ui.verbose and tagtype, b'type', b' %s', tagtype, label=label
7262 7263 )
7263 7264 fm.plain(b'\n')
7264 7265 fm.end()
7265 7266
7266 7267
7267 7268 @command(
7268 7269 b'tip',
7269 7270 [
7270 7271 (b'p', b'patch', None, _(b'show patch')),
7271 7272 (b'g', b'git', None, _(b'use git extended diff format')),
7272 7273 ]
7273 7274 + templateopts,
7274 7275 _(b'[-p] [-g]'),
7275 7276 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
7276 7277 )
7277 7278 def tip(ui, repo, **opts):
7278 7279 """show the tip revision (DEPRECATED)
7279 7280
7280 7281 The tip revision (usually just called the tip) is the changeset
7281 7282 most recently added to the repository (and therefore the most
7282 7283 recently changed head).
7283 7284
7284 7285 If you have just made a commit, that commit will be the tip. If
7285 7286 you have just pulled changes from another repository, the tip of
7286 7287 that repository becomes the current tip. The "tip" tag is special
7287 7288 and cannot be renamed or assigned to a different changeset.
7288 7289
7289 7290 This command is deprecated, please use :hg:`heads` instead.
7290 7291
7291 7292 Returns 0 on success.
7292 7293 """
7293 7294 opts = pycompat.byteskwargs(opts)
7294 7295 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
7295 7296 displayer.show(repo[b'tip'])
7296 7297 displayer.close()
7297 7298
7298 7299
7299 7300 @command(
7300 7301 b'unbundle',
7301 7302 [
7302 7303 (
7303 7304 b'u',
7304 7305 b'update',
7305 7306 None,
7306 7307 _(b'update to new branch head if changesets were unbundled'),
7307 7308 )
7308 7309 ],
7309 7310 _(b'[-u] FILE...'),
7310 7311 helpcategory=command.CATEGORY_IMPORT_EXPORT,
7311 7312 )
7312 7313 def unbundle(ui, repo, fname1, *fnames, **opts):
7313 7314 """apply one or more bundle files
7314 7315
7315 7316 Apply one or more bundle files generated by :hg:`bundle`.
7316 7317
7317 7318 Returns 0 on success, 1 if an update has unresolved files.
7318 7319 """
7319 7320 fnames = (fname1,) + fnames
7320 7321
7321 7322 with repo.lock():
7322 7323 for fname in fnames:
7323 7324 f = hg.openpath(ui, fname)
7324 7325 gen = exchange.readbundle(ui, f, fname)
7325 7326 if isinstance(gen, streamclone.streamcloneapplier):
7326 7327 raise error.Abort(
7327 7328 _(
7328 7329 b'packed bundles cannot be applied with '
7329 7330 b'"hg unbundle"'
7330 7331 ),
7331 7332 hint=_(b'use "hg debugapplystreamclonebundle"'),
7332 7333 )
7333 7334 url = b'bundle:' + fname
7334 7335 try:
7335 7336 txnname = b'unbundle'
7336 7337 if not isinstance(gen, bundle2.unbundle20):
7337 7338 txnname = b'unbundle\n%s' % util.hidepassword(url)
7338 7339 with repo.transaction(txnname) as tr:
7339 7340 op = bundle2.applybundle(
7340 7341 repo, gen, tr, source=b'unbundle', url=url
7341 7342 )
7342 7343 except error.BundleUnknownFeatureError as exc:
7343 7344 raise error.Abort(
7344 7345 _(b'%s: unknown bundle feature, %s') % (fname, exc),
7345 7346 hint=_(
7346 7347 b"see https://mercurial-scm.org/"
7347 7348 b"wiki/BundleFeature for more "
7348 7349 b"information"
7349 7350 ),
7350 7351 )
7351 7352 modheads = bundle2.combinechangegroupresults(op)
7352 7353
7353 7354 return postincoming(ui, repo, modheads, opts.get('update'), None, None)
7354 7355
7355 7356
7356 7357 @command(
7357 7358 b'unshelve',
7358 7359 [
7359 7360 (b'a', b'abort', None, _(b'abort an incomplete unshelve operation')),
7360 7361 (
7361 7362 b'c',
7362 7363 b'continue',
7363 7364 None,
7364 7365 _(b'continue an incomplete unshelve operation'),
7365 7366 ),
7366 7367 (b'i', b'interactive', None, _(b'use interactive mode (EXPERIMENTAL)')),
7367 7368 (b'k', b'keep', None, _(b'keep shelve after unshelving')),
7368 7369 (
7369 7370 b'n',
7370 7371 b'name',
7371 7372 b'',
7372 7373 _(b'restore shelved change with given name'),
7373 7374 _(b'NAME'),
7374 7375 ),
7375 7376 (b't', b'tool', b'', _(b'specify merge tool')),
7376 7377 (
7377 7378 b'',
7378 7379 b'date',
7379 7380 b'',
7380 7381 _(b'set date for temporary commits (DEPRECATED)'),
7381 7382 _(b'DATE'),
7382 7383 ),
7383 7384 ],
7384 7385 _(b'hg unshelve [OPTION]... [[-n] SHELVED]'),
7385 7386 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
7386 7387 )
7387 7388 def unshelve(ui, repo, *shelved, **opts):
7388 7389 """restore a shelved change to the working directory
7389 7390
7390 7391 This command accepts an optional name of a shelved change to
7391 7392 restore. If none is given, the most recent shelved change is used.
7392 7393
7393 7394 If a shelved change is applied successfully, the bundle that
7394 7395 contains the shelved changes is moved to a backup location
7395 7396 (.hg/shelve-backup).
7396 7397
7397 7398 Since you can restore a shelved change on top of an arbitrary
7398 7399 commit, it is possible that unshelving will result in a conflict
7399 7400 between your changes and the commits you are unshelving onto. If
7400 7401 this occurs, you must resolve the conflict, then use
7401 7402 ``--continue`` to complete the unshelve operation. (The bundle
7402 7403 will not be moved until you successfully complete the unshelve.)
7403 7404
7404 7405 (Alternatively, you can use ``--abort`` to abandon an unshelve
7405 7406 that causes a conflict. This reverts the unshelved changes, and
7406 7407 leaves the bundle in place.)
7407 7408
7408 7409 If bare shelved change (without interactive, include and exclude
7409 7410 option) was done on newly created branch it would restore branch
7410 7411 information to the working directory.
7411 7412
7412 7413 After a successful unshelve, the shelved changes are stored in a
7413 7414 backup directory. Only the N most recent backups are kept. N
7414 7415 defaults to 10 but can be overridden using the ``shelve.maxbackups``
7415 7416 configuration option.
7416 7417
7417 7418 .. container:: verbose
7418 7419
7419 7420 Timestamp in seconds is used to decide order of backups. More
7420 7421 than ``maxbackups`` backups are kept, if same timestamp
7421 7422 prevents from deciding exact order of them, for safety.
7422 7423
7423 7424 Selected changes can be unshelved with ``--interactive`` flag.
7424 7425 The working directory is updated with the selected changes, and
7425 7426 only the unselected changes remain shelved.
7426 7427 Note: The whole shelve is applied to working directory first before
7427 7428 running interactively. So, this will bring up all the conflicts between
7428 7429 working directory and the shelve, irrespective of which changes will be
7429 7430 unshelved.
7430 7431 """
7431 7432 with repo.wlock():
7432 7433 return shelvemod.unshelvecmd(ui, repo, *shelved, **opts)
7433 7434
7434 7435
7435 7436 statemod.addunfinished(
7436 7437 b'unshelve',
7437 7438 fname=b'shelvedstate',
7438 7439 continueflag=True,
7439 7440 abortfunc=shelvemod.hgabortunshelve,
7440 7441 continuefunc=shelvemod.hgcontinueunshelve,
7441 7442 cmdmsg=_(b'unshelve already in progress'),
7442 7443 )
7443 7444
7444 7445
7445 7446 @command(
7446 7447 b'update|up|checkout|co',
7447 7448 [
7448 7449 (b'C', b'clean', None, _(b'discard uncommitted changes (no backup)')),
7449 7450 (b'c', b'check', None, _(b'require clean working directory')),
7450 7451 (b'm', b'merge', None, _(b'merge uncommitted changes')),
7451 7452 (b'd', b'date', b'', _(b'tipmost revision matching date'), _(b'DATE')),
7452 7453 (b'r', b'rev', b'', _(b'revision'), _(b'REV')),
7453 7454 ]
7454 7455 + mergetoolopts,
7455 7456 _(b'[-C|-c|-m] [-d DATE] [[-r] REV]'),
7456 7457 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
7457 7458 helpbasic=True,
7458 7459 )
7459 7460 def update(ui, repo, node=None, **opts):
7460 7461 """update working directory (or switch revisions)
7461 7462
7462 7463 Update the repository's working directory to the specified
7463 7464 changeset. If no changeset is specified, update to the tip of the
7464 7465 current named branch and move the active bookmark (see :hg:`help
7465 7466 bookmarks`).
7466 7467
7467 7468 Update sets the working directory's parent revision to the specified
7468 7469 changeset (see :hg:`help parents`).
7469 7470
7470 7471 If the changeset is not a descendant or ancestor of the working
7471 7472 directory's parent and there are uncommitted changes, the update is
7472 7473 aborted. With the -c/--check option, the working directory is checked
7473 7474 for uncommitted changes; if none are found, the working directory is
7474 7475 updated to the specified changeset.
7475 7476
7476 7477 .. container:: verbose
7477 7478
7478 7479 The -C/--clean, -c/--check, and -m/--merge options control what
7479 7480 happens if the working directory contains uncommitted changes.
7480 7481 At most of one of them can be specified.
7481 7482
7482 7483 1. If no option is specified, and if
7483 7484 the requested changeset is an ancestor or descendant of
7484 7485 the working directory's parent, the uncommitted changes
7485 7486 are merged into the requested changeset and the merged
7486 7487 result is left uncommitted. If the requested changeset is
7487 7488 not an ancestor or descendant (that is, it is on another
7488 7489 branch), the update is aborted and the uncommitted changes
7489 7490 are preserved.
7490 7491
7491 7492 2. With the -m/--merge option, the update is allowed even if the
7492 7493 requested changeset is not an ancestor or descendant of
7493 7494 the working directory's parent.
7494 7495
7495 7496 3. With the -c/--check option, the update is aborted and the
7496 7497 uncommitted changes are preserved.
7497 7498
7498 7499 4. With the -C/--clean option, uncommitted changes are discarded and
7499 7500 the working directory is updated to the requested changeset.
7500 7501
7501 7502 To cancel an uncommitted merge (and lose your changes), use
7502 7503 :hg:`merge --abort`.
7503 7504
7504 7505 Use null as the changeset to remove the working directory (like
7505 7506 :hg:`clone -U`).
7506 7507
7507 7508 If you want to revert just one file to an older revision, use
7508 7509 :hg:`revert [-r REV] NAME`.
7509 7510
7510 7511 See :hg:`help dates` for a list of formats valid for -d/--date.
7511 7512
7512 7513 Returns 0 on success, 1 if there are unresolved files.
7513 7514 """
7514 7515 cmdutil.check_at_most_one_arg(opts, 'clean', 'check', 'merge')
7515 7516 rev = opts.get('rev')
7516 7517 date = opts.get('date')
7517 7518 clean = opts.get('clean')
7518 7519 check = opts.get('check')
7519 7520 merge = opts.get('merge')
7520 7521 if rev and node:
7521 7522 raise error.Abort(_(b"please specify just one revision"))
7522 7523
7523 7524 if ui.configbool(b'commands', b'update.requiredest'):
7524 7525 if not node and not rev and not date:
7525 7526 raise error.Abort(
7526 7527 _(b'you must specify a destination'),
7527 7528 hint=_(b'for example: hg update ".::"'),
7528 7529 )
7529 7530
7530 7531 if rev is None or rev == b'':
7531 7532 rev = node
7532 7533
7533 7534 if date and rev is not None:
7534 7535 raise error.Abort(_(b"you can't specify a revision and a date"))
7535 7536
7536 7537 updatecheck = None
7537 7538 if check:
7538 7539 updatecheck = b'abort'
7539 7540 elif merge:
7540 7541 updatecheck = b'none'
7541 7542
7542 7543 with repo.wlock():
7543 7544 cmdutil.clearunfinished(repo)
7544 7545 if date:
7545 7546 rev = cmdutil.finddate(ui, repo, date)
7546 7547
7547 7548 # if we defined a bookmark, we have to remember the original name
7548 7549 brev = rev
7549 7550 if rev:
7550 7551 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
7551 7552 ctx = scmutil.revsingle(repo, rev, default=None)
7552 7553 rev = ctx.rev()
7553 7554 hidden = ctx.hidden()
7554 7555 overrides = {(b'ui', b'forcemerge'): opts.get('tool', b'')}
7555 7556 with ui.configoverride(overrides, b'update'):
7556 7557 ret = hg.updatetotally(
7557 7558 ui, repo, rev, brev, clean=clean, updatecheck=updatecheck
7558 7559 )
7559 7560 if hidden:
7560 7561 ctxstr = ctx.hex()[:12]
7561 7562 ui.warn(_(b"updated to hidden changeset %s\n") % ctxstr)
7562 7563
7563 7564 if ctx.obsolete():
7564 7565 obsfatemsg = obsutil._getfilteredreason(repo, ctxstr, ctx)
7565 7566 ui.warn(b"(%s)\n" % obsfatemsg)
7566 7567 return ret
7567 7568
7568 7569
7569 7570 @command(
7570 7571 b'verify',
7571 7572 [(b'', b'full', False, b'perform more checks (EXPERIMENTAL)')],
7572 7573 helpcategory=command.CATEGORY_MAINTENANCE,
7573 7574 )
7574 7575 def verify(ui, repo, **opts):
7575 7576 """verify the integrity of the repository
7576 7577
7577 7578 Verify the integrity of the current repository.
7578 7579
7579 7580 This will perform an extensive check of the repository's
7580 7581 integrity, validating the hashes and checksums of each entry in
7581 7582 the changelog, manifest, and tracked files, as well as the
7582 7583 integrity of their crosslinks and indices.
7583 7584
7584 7585 Please see https://mercurial-scm.org/wiki/RepositoryCorruption
7585 7586 for more information about recovery from corruption of the
7586 7587 repository.
7587 7588
7588 7589 Returns 0 on success, 1 if errors are encountered.
7589 7590 """
7590 7591 opts = pycompat.byteskwargs(opts)
7591 7592
7592 7593 level = None
7593 7594 if opts[b'full']:
7594 7595 level = verifymod.VERIFY_FULL
7595 7596 return hg.verify(repo, level)
7596 7597
7597 7598
7598 7599 @command(
7599 7600 b'version',
7600 7601 [] + formatteropts,
7601 7602 helpcategory=command.CATEGORY_HELP,
7602 7603 norepo=True,
7603 7604 intents={INTENT_READONLY},
7604 7605 )
7605 7606 def version_(ui, **opts):
7606 7607 """output version and copyright information
7607 7608
7608 7609 .. container:: verbose
7609 7610
7610 7611 Template:
7611 7612
7612 7613 The following keywords are supported. See also :hg:`help templates`.
7613 7614
7614 7615 :extensions: List of extensions.
7615 7616 :ver: String. Version number.
7616 7617
7617 7618 And each entry of ``{extensions}`` provides the following sub-keywords
7618 7619 in addition to ``{ver}``.
7619 7620
7620 7621 :bundled: Boolean. True if included in the release.
7621 7622 :name: String. Extension name.
7622 7623 """
7623 7624 opts = pycompat.byteskwargs(opts)
7624 7625 if ui.verbose:
7625 7626 ui.pager(b'version')
7626 7627 fm = ui.formatter(b"version", opts)
7627 7628 fm.startitem()
7628 7629 fm.write(
7629 7630 b"ver", _(b"Mercurial Distributed SCM (version %s)\n"), util.version()
7630 7631 )
7631 7632 license = _(
7632 7633 b"(see https://mercurial-scm.org for more information)\n"
7633 7634 b"\nCopyright (C) 2005-2020 Matt Mackall and others\n"
7634 7635 b"This is free software; see the source for copying conditions. "
7635 7636 b"There is NO\nwarranty; "
7636 7637 b"not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
7637 7638 )
7638 7639 if not ui.quiet:
7639 7640 fm.plain(license)
7640 7641
7641 7642 if ui.verbose:
7642 7643 fm.plain(_(b"\nEnabled extensions:\n\n"))
7643 7644 # format names and versions into columns
7644 7645 names = []
7645 7646 vers = []
7646 7647 isinternals = []
7647 7648 for name, module in sorted(extensions.extensions()):
7648 7649 names.append(name)
7649 7650 vers.append(extensions.moduleversion(module) or None)
7650 7651 isinternals.append(extensions.ismoduleinternal(module))
7651 7652 fn = fm.nested(b"extensions", tmpl=b'{name}\n')
7652 7653 if names:
7653 7654 namefmt = b" %%-%ds " % max(len(n) for n in names)
7654 7655 places = [_(b"external"), _(b"internal")]
7655 7656 for n, v, p in zip(names, vers, isinternals):
7656 7657 fn.startitem()
7657 7658 fn.condwrite(ui.verbose, b"name", namefmt, n)
7658 7659 if ui.verbose:
7659 7660 fn.plain(b"%s " % places[p])
7660 7661 fn.data(bundled=p)
7661 7662 fn.condwrite(ui.verbose and v, b"ver", b"%s", v)
7662 7663 if ui.verbose:
7663 7664 fn.plain(b"\n")
7664 7665 fn.end()
7665 7666 fm.end()
7666 7667
7667 7668
7668 7669 def loadcmdtable(ui, name, cmdtable):
7669 7670 """Load command functions from specified cmdtable
7670 7671 """
7671 7672 overrides = [cmd for cmd in cmdtable if cmd in table]
7672 7673 if overrides:
7673 7674 ui.warn(
7674 7675 _(b"extension '%s' overrides commands: %s\n")
7675 7676 % (name, b" ".join(overrides))
7676 7677 )
7677 7678 table.update(cmdtable)
@@ -1,4578 +1,4579 b''
1 1 # debugcommands.py - command processing for debug* commands
2 2 #
3 3 # Copyright 2005-2016 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 from __future__ import absolute_import
9 9
10 10 import codecs
11 11 import collections
12 12 import difflib
13 13 import errno
14 14 import glob
15 15 import operator
16 16 import os
17 17 import platform
18 18 import random
19 19 import re
20 20 import socket
21 21 import ssl
22 22 import stat
23 23 import string
24 24 import subprocess
25 25 import sys
26 26 import time
27 27
28 28 from .i18n import _
29 29 from .node import (
30 30 bin,
31 31 hex,
32 32 nullid,
33 33 nullrev,
34 34 short,
35 35 )
36 36 from .pycompat import (
37 37 getattr,
38 38 open,
39 39 )
40 40 from . import (
41 41 bundle2,
42 42 bundlerepo,
43 43 changegroup,
44 44 cmdutil,
45 45 color,
46 46 context,
47 47 copies,
48 48 dagparser,
49 49 encoding,
50 50 error,
51 51 exchange,
52 52 extensions,
53 53 filemerge,
54 54 filesetlang,
55 55 formatter,
56 56 hg,
57 57 httppeer,
58 58 localrepo,
59 59 lock as lockmod,
60 60 logcmdutil,
61 61 mergestate as mergestatemod,
62 62 metadata,
63 63 obsolete,
64 64 obsutil,
65 65 pathutil,
66 66 phases,
67 67 policy,
68 68 pvec,
69 69 pycompat,
70 70 registrar,
71 71 repair,
72 72 revlog,
73 73 revset,
74 74 revsetlang,
75 75 scmutil,
76 76 setdiscovery,
77 77 simplemerge,
78 78 sshpeer,
79 79 sslutil,
80 80 streamclone,
81 81 tags as tagsmod,
82 82 templater,
83 83 treediscovery,
84 84 upgrade,
85 85 url as urlmod,
86 86 util,
87 87 vfs as vfsmod,
88 88 wireprotoframing,
89 89 wireprotoserver,
90 90 wireprotov2peer,
91 91 )
92 92 from .utils import (
93 93 cborutil,
94 94 compression,
95 95 dateutil,
96 96 procutil,
97 97 stringutil,
98 98 )
99 99
100 100 from .revlogutils import (
101 101 deltas as deltautil,
102 102 nodemap,
103 103 sidedata,
104 104 )
105 105
106 106 release = lockmod.release
107 107
108 108 command = registrar.command()
109 109
110 110
111 111 @command(b'debugancestor', [], _(b'[INDEX] REV1 REV2'), optionalrepo=True)
112 112 def debugancestor(ui, repo, *args):
113 113 """find the ancestor revision of two revisions in a given index"""
114 114 if len(args) == 3:
115 115 index, rev1, rev2 = args
116 116 r = revlog.revlog(vfsmod.vfs(encoding.getcwd(), audit=False), index)
117 117 lookup = r.lookup
118 118 elif len(args) == 2:
119 119 if not repo:
120 120 raise error.Abort(
121 121 _(b'there is no Mercurial repository here (.hg not found)')
122 122 )
123 123 rev1, rev2 = args
124 124 r = repo.changelog
125 125 lookup = repo.lookup
126 126 else:
127 127 raise error.Abort(_(b'either two or three arguments required'))
128 128 a = r.ancestor(lookup(rev1), lookup(rev2))
129 129 ui.write(b'%d:%s\n' % (r.rev(a), hex(a)))
130 130
131 131
132 132 @command(b'debugantivirusrunning', [])
133 133 def debugantivirusrunning(ui, repo):
134 134 """attempt to trigger an antivirus scanner to see if one is active"""
135 135 with repo.cachevfs.open('eicar-test-file.com', b'wb') as f:
136 136 f.write(
137 137 util.b85decode(
138 138 # This is a base85-armored version of the EICAR test file. See
139 139 # https://en.wikipedia.org/wiki/EICAR_test_file for details.
140 140 b'ST#=}P$fV?P+K%yP+C|uG$>GBDK|qyDK~v2MM*<JQY}+dK~6+LQba95P'
141 141 b'E<)&Nm5l)EmTEQR4qnHOhq9iNGnJx'
142 142 )
143 143 )
144 144 # Give an AV engine time to scan the file.
145 145 time.sleep(2)
146 146 util.unlink(repo.cachevfs.join('eicar-test-file.com'))
147 147
148 148
149 149 @command(b'debugapplystreamclonebundle', [], b'FILE')
150 150 def debugapplystreamclonebundle(ui, repo, fname):
151 151 """apply a stream clone bundle file"""
152 152 f = hg.openpath(ui, fname)
153 153 gen = exchange.readbundle(ui, f, fname)
154 154 gen.apply(repo)
155 155
156 156
157 157 @command(
158 158 b'debugbuilddag',
159 159 [
160 160 (
161 161 b'm',
162 162 b'mergeable-file',
163 163 None,
164 164 _(b'add single file mergeable changes'),
165 165 ),
166 166 (
167 167 b'o',
168 168 b'overwritten-file',
169 169 None,
170 170 _(b'add single file all revs overwrite'),
171 171 ),
172 172 (b'n', b'new-file', None, _(b'add new file at each rev')),
173 173 ],
174 174 _(b'[OPTION]... [TEXT]'),
175 175 )
176 176 def debugbuilddag(
177 177 ui,
178 178 repo,
179 179 text=None,
180 180 mergeable_file=False,
181 181 overwritten_file=False,
182 182 new_file=False,
183 183 ):
184 184 """builds a repo with a given DAG from scratch in the current empty repo
185 185
186 186 The description of the DAG is read from stdin if not given on the
187 187 command line.
188 188
189 189 Elements:
190 190
191 191 - "+n" is a linear run of n nodes based on the current default parent
192 192 - "." is a single node based on the current default parent
193 193 - "$" resets the default parent to null (implied at the start);
194 194 otherwise the default parent is always the last node created
195 195 - "<p" sets the default parent to the backref p
196 196 - "*p" is a fork at parent p, which is a backref
197 197 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
198 198 - "/p2" is a merge of the preceding node and p2
199 199 - ":tag" defines a local tag for the preceding node
200 200 - "@branch" sets the named branch for subsequent nodes
201 201 - "#...\\n" is a comment up to the end of the line
202 202
203 203 Whitespace between the above elements is ignored.
204 204
205 205 A backref is either
206 206
207 207 - a number n, which references the node curr-n, where curr is the current
208 208 node, or
209 209 - the name of a local tag you placed earlier using ":tag", or
210 210 - empty to denote the default parent.
211 211
212 212 All string valued-elements are either strictly alphanumeric, or must
213 213 be enclosed in double quotes ("..."), with "\\" as escape character.
214 214 """
215 215
216 216 if text is None:
217 217 ui.status(_(b"reading DAG from stdin\n"))
218 218 text = ui.fin.read()
219 219
220 220 cl = repo.changelog
221 221 if len(cl) > 0:
222 222 raise error.Abort(_(b'repository is not empty'))
223 223
224 224 # determine number of revs in DAG
225 225 total = 0
226 226 for type, data in dagparser.parsedag(text):
227 227 if type == b'n':
228 228 total += 1
229 229
230 230 if mergeable_file:
231 231 linesperrev = 2
232 232 # make a file with k lines per rev
233 233 initialmergedlines = [
234 234 b'%d' % i for i in pycompat.xrange(0, total * linesperrev)
235 235 ]
236 236 initialmergedlines.append(b"")
237 237
238 238 tags = []
239 239 progress = ui.makeprogress(
240 240 _(b'building'), unit=_(b'revisions'), total=total
241 241 )
242 242 with progress, repo.wlock(), repo.lock(), repo.transaction(b"builddag"):
243 243 at = -1
244 244 atbranch = b'default'
245 245 nodeids = []
246 246 id = 0
247 247 progress.update(id)
248 248 for type, data in dagparser.parsedag(text):
249 249 if type == b'n':
250 250 ui.note((b'node %s\n' % pycompat.bytestr(data)))
251 251 id, ps = data
252 252
253 253 files = []
254 254 filecontent = {}
255 255
256 256 p2 = None
257 257 if mergeable_file:
258 258 fn = b"mf"
259 259 p1 = repo[ps[0]]
260 260 if len(ps) > 1:
261 261 p2 = repo[ps[1]]
262 262 pa = p1.ancestor(p2)
263 263 base, local, other = [
264 264 x[fn].data() for x in (pa, p1, p2)
265 265 ]
266 266 m3 = simplemerge.Merge3Text(base, local, other)
267 267 ml = [l.strip() for l in m3.merge_lines()]
268 268 ml.append(b"")
269 269 elif at > 0:
270 270 ml = p1[fn].data().split(b"\n")
271 271 else:
272 272 ml = initialmergedlines
273 273 ml[id * linesperrev] += b" r%i" % id
274 274 mergedtext = b"\n".join(ml)
275 275 files.append(fn)
276 276 filecontent[fn] = mergedtext
277 277
278 278 if overwritten_file:
279 279 fn = b"of"
280 280 files.append(fn)
281 281 filecontent[fn] = b"r%i\n" % id
282 282
283 283 if new_file:
284 284 fn = b"nf%i" % id
285 285 files.append(fn)
286 286 filecontent[fn] = b"r%i\n" % id
287 287 if len(ps) > 1:
288 288 if not p2:
289 289 p2 = repo[ps[1]]
290 290 for fn in p2:
291 291 if fn.startswith(b"nf"):
292 292 files.append(fn)
293 293 filecontent[fn] = p2[fn].data()
294 294
295 295 def fctxfn(repo, cx, path):
296 296 if path in filecontent:
297 297 return context.memfilectx(
298 298 repo, cx, path, filecontent[path]
299 299 )
300 300 return None
301 301
302 302 if len(ps) == 0 or ps[0] < 0:
303 303 pars = [None, None]
304 304 elif len(ps) == 1:
305 305 pars = [nodeids[ps[0]], None]
306 306 else:
307 307 pars = [nodeids[p] for p in ps]
308 308 cx = context.memctx(
309 309 repo,
310 310 pars,
311 311 b"r%i" % id,
312 312 files,
313 313 fctxfn,
314 314 date=(id, 0),
315 315 user=b"debugbuilddag",
316 316 extra={b'branch': atbranch},
317 317 )
318 318 nodeid = repo.commitctx(cx)
319 319 nodeids.append(nodeid)
320 320 at = id
321 321 elif type == b'l':
322 322 id, name = data
323 323 ui.note((b'tag %s\n' % name))
324 324 tags.append(b"%s %s\n" % (hex(repo.changelog.node(id)), name))
325 325 elif type == b'a':
326 326 ui.note((b'branch %s\n' % data))
327 327 atbranch = data
328 328 progress.update(id)
329 329
330 330 if tags:
331 331 repo.vfs.write(b"localtags", b"".join(tags))
332 332
333 333
334 334 def _debugchangegroup(ui, gen, all=None, indent=0, **opts):
335 335 indent_string = b' ' * indent
336 336 if all:
337 337 ui.writenoi18n(
338 338 b"%sformat: id, p1, p2, cset, delta base, len(delta)\n"
339 339 % indent_string
340 340 )
341 341
342 342 def showchunks(named):
343 343 ui.write(b"\n%s%s\n" % (indent_string, named))
344 344 for deltadata in gen.deltaiter():
345 345 node, p1, p2, cs, deltabase, delta, flags = deltadata
346 346 ui.write(
347 347 b"%s%s %s %s %s %s %d\n"
348 348 % (
349 349 indent_string,
350 350 hex(node),
351 351 hex(p1),
352 352 hex(p2),
353 353 hex(cs),
354 354 hex(deltabase),
355 355 len(delta),
356 356 )
357 357 )
358 358
359 359 gen.changelogheader()
360 360 showchunks(b"changelog")
361 361 gen.manifestheader()
362 362 showchunks(b"manifest")
363 363 for chunkdata in iter(gen.filelogheader, {}):
364 364 fname = chunkdata[b'filename']
365 365 showchunks(fname)
366 366 else:
367 367 if isinstance(gen, bundle2.unbundle20):
368 368 raise error.Abort(_(b'use debugbundle2 for this file'))
369 369 gen.changelogheader()
370 370 for deltadata in gen.deltaiter():
371 371 node, p1, p2, cs, deltabase, delta, flags = deltadata
372 372 ui.write(b"%s%s\n" % (indent_string, hex(node)))
373 373
374 374
375 375 def _debugobsmarkers(ui, part, indent=0, **opts):
376 376 """display version and markers contained in 'data'"""
377 377 opts = pycompat.byteskwargs(opts)
378 378 data = part.read()
379 379 indent_string = b' ' * indent
380 380 try:
381 381 version, markers = obsolete._readmarkers(data)
382 382 except error.UnknownVersion as exc:
383 383 msg = b"%sunsupported version: %s (%d bytes)\n"
384 384 msg %= indent_string, exc.version, len(data)
385 385 ui.write(msg)
386 386 else:
387 387 msg = b"%sversion: %d (%d bytes)\n"
388 388 msg %= indent_string, version, len(data)
389 389 ui.write(msg)
390 390 fm = ui.formatter(b'debugobsolete', opts)
391 391 for rawmarker in sorted(markers):
392 392 m = obsutil.marker(None, rawmarker)
393 393 fm.startitem()
394 394 fm.plain(indent_string)
395 395 cmdutil.showmarker(fm, m)
396 396 fm.end()
397 397
398 398
399 399 def _debugphaseheads(ui, data, indent=0):
400 400 """display version and markers contained in 'data'"""
401 401 indent_string = b' ' * indent
402 402 headsbyphase = phases.binarydecode(data)
403 403 for phase in phases.allphases:
404 404 for head in headsbyphase[phase]:
405 405 ui.write(indent_string)
406 406 ui.write(b'%s %s\n' % (hex(head), phases.phasenames[phase]))
407 407
408 408
409 409 def _quasirepr(thing):
410 410 if isinstance(thing, (dict, util.sortdict, collections.OrderedDict)):
411 411 return b'{%s}' % (
412 412 b', '.join(b'%s: %s' % (k, thing[k]) for k in sorted(thing))
413 413 )
414 414 return pycompat.bytestr(repr(thing))
415 415
416 416
417 417 def _debugbundle2(ui, gen, all=None, **opts):
418 418 """lists the contents of a bundle2"""
419 419 if not isinstance(gen, bundle2.unbundle20):
420 420 raise error.Abort(_(b'not a bundle2 file'))
421 421 ui.write((b'Stream params: %s\n' % _quasirepr(gen.params)))
422 422 parttypes = opts.get('part_type', [])
423 423 for part in gen.iterparts():
424 424 if parttypes and part.type not in parttypes:
425 425 continue
426 426 msg = b'%s -- %s (mandatory: %r)\n'
427 427 ui.write((msg % (part.type, _quasirepr(part.params), part.mandatory)))
428 428 if part.type == b'changegroup':
429 429 version = part.params.get(b'version', b'01')
430 430 cg = changegroup.getunbundler(version, part, b'UN')
431 431 if not ui.quiet:
432 432 _debugchangegroup(ui, cg, all=all, indent=4, **opts)
433 433 if part.type == b'obsmarkers':
434 434 if not ui.quiet:
435 435 _debugobsmarkers(ui, part, indent=4, **opts)
436 436 if part.type == b'phase-heads':
437 437 if not ui.quiet:
438 438 _debugphaseheads(ui, part, indent=4)
439 439
440 440
441 441 @command(
442 442 b'debugbundle',
443 443 [
444 444 (b'a', b'all', None, _(b'show all details')),
445 445 (b'', b'part-type', [], _(b'show only the named part type')),
446 446 (b'', b'spec', None, _(b'print the bundlespec of the bundle')),
447 447 ],
448 448 _(b'FILE'),
449 449 norepo=True,
450 450 )
451 451 def debugbundle(ui, bundlepath, all=None, spec=None, **opts):
452 452 """lists the contents of a bundle"""
453 453 with hg.openpath(ui, bundlepath) as f:
454 454 if spec:
455 455 spec = exchange.getbundlespec(ui, f)
456 456 ui.write(b'%s\n' % spec)
457 457 return
458 458
459 459 gen = exchange.readbundle(ui, f, bundlepath)
460 460 if isinstance(gen, bundle2.unbundle20):
461 461 return _debugbundle2(ui, gen, all=all, **opts)
462 462 _debugchangegroup(ui, gen, all=all, **opts)
463 463
464 464
465 465 @command(b'debugcapabilities', [], _(b'PATH'), norepo=True)
466 466 def debugcapabilities(ui, path, **opts):
467 467 """lists the capabilities of a remote peer"""
468 468 opts = pycompat.byteskwargs(opts)
469 469 peer = hg.peer(ui, opts, path)
470 470 caps = peer.capabilities()
471 471 ui.writenoi18n(b'Main capabilities:\n')
472 472 for c in sorted(caps):
473 473 ui.write(b' %s\n' % c)
474 474 b2caps = bundle2.bundle2caps(peer)
475 475 if b2caps:
476 476 ui.writenoi18n(b'Bundle2 capabilities:\n')
477 477 for key, values in sorted(pycompat.iteritems(b2caps)):
478 478 ui.write(b' %s\n' % key)
479 479 for v in values:
480 480 ui.write(b' %s\n' % v)
481 481
482 482
483 483 @command(b'debugchangedfiles', [], b'REV')
484 484 def debugchangedfiles(ui, repo, rev):
485 485 """list the stored files changes for a revision"""
486 486 ctx = scmutil.revsingle(repo, rev, None)
487 487 sd = repo.changelog.sidedata(ctx.rev())
488 488 files_block = sd.get(sidedata.SD_FILES)
489 489 if files_block is not None:
490 490 files = metadata.decode_files_sidedata(sd)
491 491 for f in sorted(files.touched):
492 492 if f in files.added:
493 493 action = b"added"
494 494 elif f in files.removed:
495 495 action = b"removed"
496 496 elif f in files.merged:
497 497 action = b"merged"
498 498 elif f in files.salvaged:
499 499 action = b"salvaged"
500 500 else:
501 501 action = b"touched"
502 502
503 503 copy_parent = b""
504 504 copy_source = b""
505 505 if f in files.copied_from_p1:
506 506 copy_parent = b"p1"
507 507 copy_source = files.copied_from_p1[f]
508 508 elif f in files.copied_from_p2:
509 509 copy_parent = b"p2"
510 510 copy_source = files.copied_from_p2[f]
511 511
512 512 data = (action, copy_parent, f, copy_source)
513 513 template = b"%-8s %2s: %s, %s;\n"
514 514 ui.write(template % data)
515 515
516 516
517 517 @command(b'debugcheckstate', [], b'')
518 518 def debugcheckstate(ui, repo):
519 519 """validate the correctness of the current dirstate"""
520 520 parent1, parent2 = repo.dirstate.parents()
521 521 m1 = repo[parent1].manifest()
522 522 m2 = repo[parent2].manifest()
523 523 errors = 0
524 524 for f in repo.dirstate:
525 525 state = repo.dirstate[f]
526 526 if state in b"nr" and f not in m1:
527 527 ui.warn(_(b"%s in state %s, but not in manifest1\n") % (f, state))
528 528 errors += 1
529 529 if state in b"a" and f in m1:
530 530 ui.warn(_(b"%s in state %s, but also in manifest1\n") % (f, state))
531 531 errors += 1
532 532 if state in b"m" and f not in m1 and f not in m2:
533 533 ui.warn(
534 534 _(b"%s in state %s, but not in either manifest\n") % (f, state)
535 535 )
536 536 errors += 1
537 537 for f in m1:
538 538 state = repo.dirstate[f]
539 539 if state not in b"nrm":
540 540 ui.warn(_(b"%s in manifest1, but listed as state %s") % (f, state))
541 541 errors += 1
542 542 if errors:
543 543 errstr = _(b".hg/dirstate inconsistent with current parent's manifest")
544 544 raise error.Abort(errstr)
545 545
546 546
547 547 @command(
548 548 b'debugcolor',
549 549 [(b'', b'style', None, _(b'show all configured styles'))],
550 550 b'hg debugcolor',
551 551 )
552 552 def debugcolor(ui, repo, **opts):
553 553 """show available color, effects or style"""
554 554 ui.writenoi18n(b'color mode: %s\n' % stringutil.pprint(ui._colormode))
555 555 if opts.get('style'):
556 556 return _debugdisplaystyle(ui)
557 557 else:
558 558 return _debugdisplaycolor(ui)
559 559
560 560
561 561 def _debugdisplaycolor(ui):
562 562 ui = ui.copy()
563 563 ui._styles.clear()
564 564 for effect in color._activeeffects(ui).keys():
565 565 ui._styles[effect] = effect
566 566 if ui._terminfoparams:
567 567 for k, v in ui.configitems(b'color'):
568 568 if k.startswith(b'color.'):
569 569 ui._styles[k] = k[6:]
570 570 elif k.startswith(b'terminfo.'):
571 571 ui._styles[k] = k[9:]
572 572 ui.write(_(b'available colors:\n'))
573 573 # sort label with a '_' after the other to group '_background' entry.
574 574 items = sorted(ui._styles.items(), key=lambda i: (b'_' in i[0], i[0], i[1]))
575 575 for colorname, label in items:
576 576 ui.write(b'%s\n' % colorname, label=label)
577 577
578 578
579 579 def _debugdisplaystyle(ui):
580 580 ui.write(_(b'available style:\n'))
581 581 if not ui._styles:
582 582 return
583 583 width = max(len(s) for s in ui._styles)
584 584 for label, effects in sorted(ui._styles.items()):
585 585 ui.write(b'%s' % label, label=label)
586 586 if effects:
587 587 # 50
588 588 ui.write(b': ')
589 589 ui.write(b' ' * (max(0, width - len(label))))
590 590 ui.write(b', '.join(ui.label(e, e) for e in effects.split()))
591 591 ui.write(b'\n')
592 592
593 593
594 594 @command(b'debugcreatestreamclonebundle', [], b'FILE')
595 595 def debugcreatestreamclonebundle(ui, repo, fname):
596 596 """create a stream clone bundle file
597 597
598 598 Stream bundles are special bundles that are essentially archives of
599 599 revlog files. They are commonly used for cloning very quickly.
600 600 """
601 601 # TODO we may want to turn this into an abort when this functionality
602 602 # is moved into `hg bundle`.
603 603 if phases.hassecret(repo):
604 604 ui.warn(
605 605 _(
606 606 b'(warning: stream clone bundle will contain secret '
607 607 b'revisions)\n'
608 608 )
609 609 )
610 610
611 611 requirements, gen = streamclone.generatebundlev1(repo)
612 612 changegroup.writechunks(ui, gen, fname)
613 613
614 614 ui.write(_(b'bundle requirements: %s\n') % b', '.join(sorted(requirements)))
615 615
616 616
617 617 @command(
618 618 b'debugdag',
619 619 [
620 620 (b't', b'tags', None, _(b'use tags as labels')),
621 621 (b'b', b'branches', None, _(b'annotate with branch names')),
622 622 (b'', b'dots', None, _(b'use dots for runs')),
623 623 (b's', b'spaces', None, _(b'separate elements by spaces')),
624 624 ],
625 625 _(b'[OPTION]... [FILE [REV]...]'),
626 626 optionalrepo=True,
627 627 )
628 628 def debugdag(ui, repo, file_=None, *revs, **opts):
629 629 """format the changelog or an index DAG as a concise textual description
630 630
631 631 If you pass a revlog index, the revlog's DAG is emitted. If you list
632 632 revision numbers, they get labeled in the output as rN.
633 633
634 634 Otherwise, the changelog DAG of the current repo is emitted.
635 635 """
636 636 spaces = opts.get('spaces')
637 637 dots = opts.get('dots')
638 638 if file_:
639 639 rlog = revlog.revlog(vfsmod.vfs(encoding.getcwd(), audit=False), file_)
640 640 revs = {int(r) for r in revs}
641 641
642 642 def events():
643 643 for r in rlog:
644 644 yield b'n', (r, list(p for p in rlog.parentrevs(r) if p != -1))
645 645 if r in revs:
646 646 yield b'l', (r, b"r%i" % r)
647 647
648 648 elif repo:
649 649 cl = repo.changelog
650 650 tags = opts.get('tags')
651 651 branches = opts.get('branches')
652 652 if tags:
653 653 labels = {}
654 654 for l, n in repo.tags().items():
655 655 labels.setdefault(cl.rev(n), []).append(l)
656 656
657 657 def events():
658 658 b = b"default"
659 659 for r in cl:
660 660 if branches:
661 661 newb = cl.read(cl.node(r))[5][b'branch']
662 662 if newb != b:
663 663 yield b'a', newb
664 664 b = newb
665 665 yield b'n', (r, list(p for p in cl.parentrevs(r) if p != -1))
666 666 if tags:
667 667 ls = labels.get(r)
668 668 if ls:
669 669 for l in ls:
670 670 yield b'l', (r, l)
671 671
672 672 else:
673 673 raise error.Abort(_(b'need repo for changelog dag'))
674 674
675 675 for line in dagparser.dagtextlines(
676 676 events(),
677 677 addspaces=spaces,
678 678 wraplabels=True,
679 679 wrapannotations=True,
680 680 wrapnonlinear=dots,
681 681 usedots=dots,
682 682 maxlinewidth=70,
683 683 ):
684 684 ui.write(line)
685 685 ui.write(b"\n")
686 686
687 687
688 688 @command(b'debugdata', cmdutil.debugrevlogopts, _(b'-c|-m|FILE REV'))
689 689 def debugdata(ui, repo, file_, rev=None, **opts):
690 690 """dump the contents of a data file revision"""
691 691 opts = pycompat.byteskwargs(opts)
692 692 if opts.get(b'changelog') or opts.get(b'manifest') or opts.get(b'dir'):
693 693 if rev is not None:
694 694 raise error.CommandError(b'debugdata', _(b'invalid arguments'))
695 695 file_, rev = None, file_
696 696 elif rev is None:
697 697 raise error.CommandError(b'debugdata', _(b'invalid arguments'))
698 698 r = cmdutil.openstorage(repo, b'debugdata', file_, opts)
699 699 try:
700 700 ui.write(r.rawdata(r.lookup(rev)))
701 701 except KeyError:
702 702 raise error.Abort(_(b'invalid revision identifier %s') % rev)
703 703
704 704
705 705 @command(
706 706 b'debugdate',
707 707 [(b'e', b'extended', None, _(b'try extended date formats'))],
708 708 _(b'[-e] DATE [RANGE]'),
709 709 norepo=True,
710 710 optionalrepo=True,
711 711 )
712 712 def debugdate(ui, date, range=None, **opts):
713 713 """parse and display a date"""
714 714 if opts["extended"]:
715 715 d = dateutil.parsedate(date, dateutil.extendeddateformats)
716 716 else:
717 717 d = dateutil.parsedate(date)
718 718 ui.writenoi18n(b"internal: %d %d\n" % d)
719 719 ui.writenoi18n(b"standard: %s\n" % dateutil.datestr(d))
720 720 if range:
721 721 m = dateutil.matchdate(range)
722 722 ui.writenoi18n(b"match: %s\n" % m(d[0]))
723 723
724 724
725 725 @command(
726 726 b'debugdeltachain',
727 727 cmdutil.debugrevlogopts + cmdutil.formatteropts,
728 728 _(b'-c|-m|FILE'),
729 729 optionalrepo=True,
730 730 )
731 731 def debugdeltachain(ui, repo, file_=None, **opts):
732 732 """dump information about delta chains in a revlog
733 733
734 734 Output can be templatized. Available template keywords are:
735 735
736 736 :``rev``: revision number
737 737 :``chainid``: delta chain identifier (numbered by unique base)
738 738 :``chainlen``: delta chain length to this revision
739 739 :``prevrev``: previous revision in delta chain
740 740 :``deltatype``: role of delta / how it was computed
741 741 :``compsize``: compressed size of revision
742 742 :``uncompsize``: uncompressed size of revision
743 743 :``chainsize``: total size of compressed revisions in chain
744 744 :``chainratio``: total chain size divided by uncompressed revision size
745 745 (new delta chains typically start at ratio 2.00)
746 746 :``lindist``: linear distance from base revision in delta chain to end
747 747 of this revision
748 748 :``extradist``: total size of revisions not part of this delta chain from
749 749 base of delta chain to end of this revision; a measurement
750 750 of how much extra data we need to read/seek across to read
751 751 the delta chain for this revision
752 752 :``extraratio``: extradist divided by chainsize; another representation of
753 753 how much unrelated data is needed to load this delta chain
754 754
755 755 If the repository is configured to use the sparse read, additional keywords
756 756 are available:
757 757
758 758 :``readsize``: total size of data read from the disk for a revision
759 759 (sum of the sizes of all the blocks)
760 760 :``largestblock``: size of the largest block of data read from the disk
761 761 :``readdensity``: density of useful bytes in the data read from the disk
762 762 :``srchunks``: in how many data hunks the whole revision would be read
763 763
764 764 The sparse read can be enabled with experimental.sparse-read = True
765 765 """
766 766 opts = pycompat.byteskwargs(opts)
767 767 r = cmdutil.openrevlog(repo, b'debugdeltachain', file_, opts)
768 768 index = r.index
769 769 start = r.start
770 770 length = r.length
771 771 generaldelta = r.version & revlog.FLAG_GENERALDELTA
772 772 withsparseread = getattr(r, '_withsparseread', False)
773 773
774 774 def revinfo(rev):
775 775 e = index[rev]
776 776 compsize = e[1]
777 777 uncompsize = e[2]
778 778 chainsize = 0
779 779
780 780 if generaldelta:
781 781 if e[3] == e[5]:
782 782 deltatype = b'p1'
783 783 elif e[3] == e[6]:
784 784 deltatype = b'p2'
785 785 elif e[3] == rev - 1:
786 786 deltatype = b'prev'
787 787 elif e[3] == rev:
788 788 deltatype = b'base'
789 789 else:
790 790 deltatype = b'other'
791 791 else:
792 792 if e[3] == rev:
793 793 deltatype = b'base'
794 794 else:
795 795 deltatype = b'prev'
796 796
797 797 chain = r._deltachain(rev)[0]
798 798 for iterrev in chain:
799 799 e = index[iterrev]
800 800 chainsize += e[1]
801 801
802 802 return compsize, uncompsize, deltatype, chain, chainsize
803 803
804 804 fm = ui.formatter(b'debugdeltachain', opts)
805 805
806 806 fm.plain(
807 807 b' rev chain# chainlen prev delta '
808 808 b'size rawsize chainsize ratio lindist extradist '
809 809 b'extraratio'
810 810 )
811 811 if withsparseread:
812 812 fm.plain(b' readsize largestblk rddensity srchunks')
813 813 fm.plain(b'\n')
814 814
815 815 chainbases = {}
816 816 for rev in r:
817 817 comp, uncomp, deltatype, chain, chainsize = revinfo(rev)
818 818 chainbase = chain[0]
819 819 chainid = chainbases.setdefault(chainbase, len(chainbases) + 1)
820 820 basestart = start(chainbase)
821 821 revstart = start(rev)
822 822 lineardist = revstart + comp - basestart
823 823 extradist = lineardist - chainsize
824 824 try:
825 825 prevrev = chain[-2]
826 826 except IndexError:
827 827 prevrev = -1
828 828
829 829 if uncomp != 0:
830 830 chainratio = float(chainsize) / float(uncomp)
831 831 else:
832 832 chainratio = chainsize
833 833
834 834 if chainsize != 0:
835 835 extraratio = float(extradist) / float(chainsize)
836 836 else:
837 837 extraratio = extradist
838 838
839 839 fm.startitem()
840 840 fm.write(
841 841 b'rev chainid chainlen prevrev deltatype compsize '
842 842 b'uncompsize chainsize chainratio lindist extradist '
843 843 b'extraratio',
844 844 b'%7d %7d %8d %8d %7s %10d %10d %10d %9.5f %9d %9d %10.5f',
845 845 rev,
846 846 chainid,
847 847 len(chain),
848 848 prevrev,
849 849 deltatype,
850 850 comp,
851 851 uncomp,
852 852 chainsize,
853 853 chainratio,
854 854 lineardist,
855 855 extradist,
856 856 extraratio,
857 857 rev=rev,
858 858 chainid=chainid,
859 859 chainlen=len(chain),
860 860 prevrev=prevrev,
861 861 deltatype=deltatype,
862 862 compsize=comp,
863 863 uncompsize=uncomp,
864 864 chainsize=chainsize,
865 865 chainratio=chainratio,
866 866 lindist=lineardist,
867 867 extradist=extradist,
868 868 extraratio=extraratio,
869 869 )
870 870 if withsparseread:
871 871 readsize = 0
872 872 largestblock = 0
873 873 srchunks = 0
874 874
875 875 for revschunk in deltautil.slicechunk(r, chain):
876 876 srchunks += 1
877 877 blkend = start(revschunk[-1]) + length(revschunk[-1])
878 878 blksize = blkend - start(revschunk[0])
879 879
880 880 readsize += blksize
881 881 if largestblock < blksize:
882 882 largestblock = blksize
883 883
884 884 if readsize:
885 885 readdensity = float(chainsize) / float(readsize)
886 886 else:
887 887 readdensity = 1
888 888
889 889 fm.write(
890 890 b'readsize largestblock readdensity srchunks',
891 891 b' %10d %10d %9.5f %8d',
892 892 readsize,
893 893 largestblock,
894 894 readdensity,
895 895 srchunks,
896 896 readsize=readsize,
897 897 largestblock=largestblock,
898 898 readdensity=readdensity,
899 899 srchunks=srchunks,
900 900 )
901 901
902 902 fm.plain(b'\n')
903 903
904 904 fm.end()
905 905
906 906
907 907 @command(
908 908 b'debugdirstate|debugstate',
909 909 [
910 910 (
911 911 b'',
912 912 b'nodates',
913 913 None,
914 914 _(b'do not display the saved mtime (DEPRECATED)'),
915 915 ),
916 916 (b'', b'dates', True, _(b'display the saved mtime')),
917 917 (b'', b'datesort', None, _(b'sort by saved mtime')),
918 918 ],
919 919 _(b'[OPTION]...'),
920 920 )
921 921 def debugstate(ui, repo, **opts):
922 922 """show the contents of the current dirstate"""
923 923
924 924 nodates = not opts['dates']
925 925 if opts.get('nodates') is not None:
926 926 nodates = True
927 927 datesort = opts.get('datesort')
928 928
929 929 if datesort:
930 930 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
931 931 else:
932 932 keyfunc = None # sort by filename
933 933 for file_, ent in sorted(pycompat.iteritems(repo.dirstate), key=keyfunc):
934 934 if ent[3] == -1:
935 935 timestr = b'unset '
936 936 elif nodates:
937 937 timestr = b'set '
938 938 else:
939 939 timestr = time.strftime(
940 940 "%Y-%m-%d %H:%M:%S ", time.localtime(ent[3])
941 941 )
942 942 timestr = encoding.strtolocal(timestr)
943 943 if ent[1] & 0o20000:
944 944 mode = b'lnk'
945 945 else:
946 946 mode = b'%3o' % (ent[1] & 0o777 & ~util.umask)
947 947 ui.write(b"%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
948 948 for f in repo.dirstate.copies():
949 949 ui.write(_(b"copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
950 950
951 951
952 952 @command(
953 953 b'debugdiscovery',
954 954 [
955 955 (b'', b'old', None, _(b'use old-style discovery')),
956 956 (
957 957 b'',
958 958 b'nonheads',
959 959 None,
960 960 _(b'use old-style discovery with non-heads included'),
961 961 ),
962 962 (b'', b'rev', [], b'restrict discovery to this set of revs'),
963 963 (b'', b'seed', b'12323', b'specify the random seed use for discovery'),
964 964 ]
965 965 + cmdutil.remoteopts,
966 966 _(b'[--rev REV] [OTHER]'),
967 967 )
968 968 def debugdiscovery(ui, repo, remoteurl=b"default", **opts):
969 969 """runs the changeset discovery protocol in isolation"""
970 970 opts = pycompat.byteskwargs(opts)
971 971 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl))
972 972 remote = hg.peer(repo, opts, remoteurl)
973 973 ui.status(_(b'comparing with %s\n') % util.hidepassword(remoteurl))
974 974
975 975 # make sure tests are repeatable
976 976 random.seed(int(opts[b'seed']))
977 977
978 978 if opts.get(b'old'):
979 979
980 980 def doit(pushedrevs, remoteheads, remote=remote):
981 981 if not util.safehasattr(remote, b'branches'):
982 982 # enable in-client legacy support
983 983 remote = localrepo.locallegacypeer(remote.local())
984 984 common, _in, hds = treediscovery.findcommonincoming(
985 985 repo, remote, force=True
986 986 )
987 987 common = set(common)
988 988 if not opts.get(b'nonheads'):
989 989 ui.writenoi18n(
990 990 b"unpruned common: %s\n"
991 991 % b" ".join(sorted(short(n) for n in common))
992 992 )
993 993
994 994 clnode = repo.changelog.node
995 995 common = repo.revs(b'heads(::%ln)', common)
996 996 common = {clnode(r) for r in common}
997 997 return common, hds
998 998
999 999 else:
1000 1000
1001 1001 def doit(pushedrevs, remoteheads, remote=remote):
1002 1002 nodes = None
1003 1003 if pushedrevs:
1004 1004 revs = scmutil.revrange(repo, pushedrevs)
1005 1005 nodes = [repo[r].node() for r in revs]
1006 1006 common, any, hds = setdiscovery.findcommonheads(
1007 1007 ui, repo, remote, ancestorsof=nodes
1008 1008 )
1009 1009 return common, hds
1010 1010
1011 1011 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches, revs=None)
1012 1012 localrevs = opts[b'rev']
1013 1013 with util.timedcm('debug-discovery') as t:
1014 1014 common, hds = doit(localrevs, remoterevs)
1015 1015
1016 1016 # compute all statistics
1017 1017 common = set(common)
1018 1018 rheads = set(hds)
1019 1019 lheads = set(repo.heads())
1020 1020
1021 1021 data = {}
1022 1022 data[b'elapsed'] = t.elapsed
1023 1023 data[b'nb-common'] = len(common)
1024 1024 data[b'nb-common-local'] = len(common & lheads)
1025 1025 data[b'nb-common-remote'] = len(common & rheads)
1026 1026 data[b'nb-common-both'] = len(common & rheads & lheads)
1027 1027 data[b'nb-local'] = len(lheads)
1028 1028 data[b'nb-local-missing'] = data[b'nb-local'] - data[b'nb-common-local']
1029 1029 data[b'nb-remote'] = len(rheads)
1030 1030 data[b'nb-remote-unknown'] = data[b'nb-remote'] - data[b'nb-common-remote']
1031 1031 data[b'nb-revs'] = len(repo.revs(b'all()'))
1032 1032 data[b'nb-revs-common'] = len(repo.revs(b'::%ln', common))
1033 1033 data[b'nb-revs-missing'] = data[b'nb-revs'] - data[b'nb-revs-common']
1034 1034
1035 1035 # display discovery summary
1036 1036 ui.writenoi18n(b"elapsed time: %(elapsed)f seconds\n" % data)
1037 1037 ui.writenoi18n(b"heads summary:\n")
1038 1038 ui.writenoi18n(b" total common heads: %(nb-common)9d\n" % data)
1039 1039 ui.writenoi18n(b" also local heads: %(nb-common-local)9d\n" % data)
1040 1040 ui.writenoi18n(b" also remote heads: %(nb-common-remote)9d\n" % data)
1041 1041 ui.writenoi18n(b" both: %(nb-common-both)9d\n" % data)
1042 1042 ui.writenoi18n(b" local heads: %(nb-local)9d\n" % data)
1043 1043 ui.writenoi18n(b" common: %(nb-common-local)9d\n" % data)
1044 1044 ui.writenoi18n(b" missing: %(nb-local-missing)9d\n" % data)
1045 1045 ui.writenoi18n(b" remote heads: %(nb-remote)9d\n" % data)
1046 1046 ui.writenoi18n(b" common: %(nb-common-remote)9d\n" % data)
1047 1047 ui.writenoi18n(b" unknown: %(nb-remote-unknown)9d\n" % data)
1048 1048 ui.writenoi18n(b"local changesets: %(nb-revs)9d\n" % data)
1049 1049 ui.writenoi18n(b" common: %(nb-revs-common)9d\n" % data)
1050 1050 ui.writenoi18n(b" missing: %(nb-revs-missing)9d\n" % data)
1051 1051
1052 1052 if ui.verbose:
1053 1053 ui.writenoi18n(
1054 1054 b"common heads: %s\n" % b" ".join(sorted(short(n) for n in common))
1055 1055 )
1056 1056
1057 1057
1058 1058 _chunksize = 4 << 10
1059 1059
1060 1060
1061 1061 @command(
1062 1062 b'debugdownload', [(b'o', b'output', b'', _(b'path')),], optionalrepo=True
1063 1063 )
1064 1064 def debugdownload(ui, repo, url, output=None, **opts):
1065 1065 """download a resource using Mercurial logic and config
1066 1066 """
1067 1067 fh = urlmod.open(ui, url, output)
1068 1068
1069 1069 dest = ui
1070 1070 if output:
1071 1071 dest = open(output, b"wb", _chunksize)
1072 1072 try:
1073 1073 data = fh.read(_chunksize)
1074 1074 while data:
1075 1075 dest.write(data)
1076 1076 data = fh.read(_chunksize)
1077 1077 finally:
1078 1078 if output:
1079 1079 dest.close()
1080 1080
1081 1081
1082 1082 @command(b'debugextensions', cmdutil.formatteropts, [], optionalrepo=True)
1083 1083 def debugextensions(ui, repo, **opts):
1084 1084 '''show information about active extensions'''
1085 1085 opts = pycompat.byteskwargs(opts)
1086 1086 exts = extensions.extensions(ui)
1087 1087 hgver = util.version()
1088 1088 fm = ui.formatter(b'debugextensions', opts)
1089 1089 for extname, extmod in sorted(exts, key=operator.itemgetter(0)):
1090 1090 isinternal = extensions.ismoduleinternal(extmod)
1091 1091 extsource = None
1092 1092
1093 1093 if util.safehasattr(extmod, '__file__'):
1094 1094 extsource = pycompat.fsencode(extmod.__file__)
1095 1095 elif getattr(sys, 'oxidized', False):
1096 1096 extsource = pycompat.sysexecutable
1097 1097 if isinternal:
1098 1098 exttestedwith = [] # never expose magic string to users
1099 1099 else:
1100 1100 exttestedwith = getattr(extmod, 'testedwith', b'').split()
1101 1101 extbuglink = getattr(extmod, 'buglink', None)
1102 1102
1103 1103 fm.startitem()
1104 1104
1105 1105 if ui.quiet or ui.verbose:
1106 1106 fm.write(b'name', b'%s\n', extname)
1107 1107 else:
1108 1108 fm.write(b'name', b'%s', extname)
1109 1109 if isinternal or hgver in exttestedwith:
1110 1110 fm.plain(b'\n')
1111 1111 elif not exttestedwith:
1112 1112 fm.plain(_(b' (untested!)\n'))
1113 1113 else:
1114 1114 lasttestedversion = exttestedwith[-1]
1115 1115 fm.plain(b' (%s!)\n' % lasttestedversion)
1116 1116
1117 1117 fm.condwrite(
1118 1118 ui.verbose and extsource,
1119 1119 b'source',
1120 1120 _(b' location: %s\n'),
1121 1121 extsource or b"",
1122 1122 )
1123 1123
1124 1124 if ui.verbose:
1125 1125 fm.plain(_(b' bundled: %s\n') % [b'no', b'yes'][isinternal])
1126 1126 fm.data(bundled=isinternal)
1127 1127
1128 1128 fm.condwrite(
1129 1129 ui.verbose and exttestedwith,
1130 1130 b'testedwith',
1131 1131 _(b' tested with: %s\n'),
1132 1132 fm.formatlist(exttestedwith, name=b'ver'),
1133 1133 )
1134 1134
1135 1135 fm.condwrite(
1136 1136 ui.verbose and extbuglink,
1137 1137 b'buglink',
1138 1138 _(b' bug reporting: %s\n'),
1139 1139 extbuglink or b"",
1140 1140 )
1141 1141
1142 1142 fm.end()
1143 1143
1144 1144
1145 1145 @command(
1146 1146 b'debugfileset',
1147 1147 [
1148 1148 (
1149 1149 b'r',
1150 1150 b'rev',
1151 1151 b'',
1152 1152 _(b'apply the filespec on this revision'),
1153 1153 _(b'REV'),
1154 1154 ),
1155 1155 (
1156 1156 b'',
1157 1157 b'all-files',
1158 1158 False,
1159 1159 _(b'test files from all revisions and working directory'),
1160 1160 ),
1161 1161 (
1162 1162 b's',
1163 1163 b'show-matcher',
1164 1164 None,
1165 1165 _(b'print internal representation of matcher'),
1166 1166 ),
1167 1167 (
1168 1168 b'p',
1169 1169 b'show-stage',
1170 1170 [],
1171 1171 _(b'print parsed tree at the given stage'),
1172 1172 _(b'NAME'),
1173 1173 ),
1174 1174 ],
1175 1175 _(b'[-r REV] [--all-files] [OPTION]... FILESPEC'),
1176 1176 )
1177 1177 def debugfileset(ui, repo, expr, **opts):
1178 1178 '''parse and apply a fileset specification'''
1179 1179 from . import fileset
1180 1180
1181 1181 fileset.symbols # force import of fileset so we have predicates to optimize
1182 1182 opts = pycompat.byteskwargs(opts)
1183 1183 ctx = scmutil.revsingle(repo, opts.get(b'rev'), None)
1184 1184
1185 1185 stages = [
1186 1186 (b'parsed', pycompat.identity),
1187 1187 (b'analyzed', filesetlang.analyze),
1188 1188 (b'optimized', filesetlang.optimize),
1189 1189 ]
1190 1190 stagenames = {n for n, f in stages}
1191 1191
1192 1192 showalways = set()
1193 1193 if ui.verbose and not opts[b'show_stage']:
1194 1194 # show parsed tree by --verbose (deprecated)
1195 1195 showalways.add(b'parsed')
1196 1196 if opts[b'show_stage'] == [b'all']:
1197 1197 showalways.update(stagenames)
1198 1198 else:
1199 1199 for n in opts[b'show_stage']:
1200 1200 if n not in stagenames:
1201 1201 raise error.Abort(_(b'invalid stage name: %s') % n)
1202 1202 showalways.update(opts[b'show_stage'])
1203 1203
1204 1204 tree = filesetlang.parse(expr)
1205 1205 for n, f in stages:
1206 1206 tree = f(tree)
1207 1207 if n in showalways:
1208 1208 if opts[b'show_stage'] or n != b'parsed':
1209 1209 ui.write(b"* %s:\n" % n)
1210 1210 ui.write(filesetlang.prettyformat(tree), b"\n")
1211 1211
1212 1212 files = set()
1213 1213 if opts[b'all_files']:
1214 1214 for r in repo:
1215 1215 c = repo[r]
1216 1216 files.update(c.files())
1217 1217 files.update(c.substate)
1218 1218 if opts[b'all_files'] or ctx.rev() is None:
1219 1219 wctx = repo[None]
1220 1220 files.update(
1221 1221 repo.dirstate.walk(
1222 1222 scmutil.matchall(repo),
1223 1223 subrepos=list(wctx.substate),
1224 1224 unknown=True,
1225 1225 ignored=True,
1226 1226 )
1227 1227 )
1228 1228 files.update(wctx.substate)
1229 1229 else:
1230 1230 files.update(ctx.files())
1231 1231 files.update(ctx.substate)
1232 1232
1233 1233 m = ctx.matchfileset(repo.getcwd(), expr)
1234 1234 if opts[b'show_matcher'] or (opts[b'show_matcher'] is None and ui.verbose):
1235 1235 ui.writenoi18n(b'* matcher:\n', stringutil.prettyrepr(m), b'\n')
1236 1236 for f in sorted(files):
1237 1237 if not m(f):
1238 1238 continue
1239 1239 ui.write(b"%s\n" % f)
1240 1240
1241 1241
1242 1242 @command(b'debugformat', [] + cmdutil.formatteropts)
1243 1243 def debugformat(ui, repo, **opts):
1244 1244 """display format information about the current repository
1245 1245
1246 1246 Use --verbose to get extra information about current config value and
1247 1247 Mercurial default."""
1248 1248 opts = pycompat.byteskwargs(opts)
1249 1249 maxvariantlength = max(len(fv.name) for fv in upgrade.allformatvariant)
1250 1250 maxvariantlength = max(len(b'format-variant'), maxvariantlength)
1251 1251
1252 1252 def makeformatname(name):
1253 1253 return b'%s:' + (b' ' * (maxvariantlength - len(name)))
1254 1254
1255 1255 fm = ui.formatter(b'debugformat', opts)
1256 1256 if fm.isplain():
1257 1257
1258 1258 def formatvalue(value):
1259 1259 if util.safehasattr(value, b'startswith'):
1260 1260 return value
1261 1261 if value:
1262 1262 return b'yes'
1263 1263 else:
1264 1264 return b'no'
1265 1265
1266 1266 else:
1267 1267 formatvalue = pycompat.identity
1268 1268
1269 1269 fm.plain(b'format-variant')
1270 1270 fm.plain(b' ' * (maxvariantlength - len(b'format-variant')))
1271 1271 fm.plain(b' repo')
1272 1272 if ui.verbose:
1273 1273 fm.plain(b' config default')
1274 1274 fm.plain(b'\n')
1275 1275 for fv in upgrade.allformatvariant:
1276 1276 fm.startitem()
1277 1277 repovalue = fv.fromrepo(repo)
1278 1278 configvalue = fv.fromconfig(repo)
1279 1279
1280 1280 if repovalue != configvalue:
1281 1281 namelabel = b'formatvariant.name.mismatchconfig'
1282 1282 repolabel = b'formatvariant.repo.mismatchconfig'
1283 1283 elif repovalue != fv.default:
1284 1284 namelabel = b'formatvariant.name.mismatchdefault'
1285 1285 repolabel = b'formatvariant.repo.mismatchdefault'
1286 1286 else:
1287 1287 namelabel = b'formatvariant.name.uptodate'
1288 1288 repolabel = b'formatvariant.repo.uptodate'
1289 1289
1290 1290 fm.write(b'name', makeformatname(fv.name), fv.name, label=namelabel)
1291 1291 fm.write(b'repo', b' %3s', formatvalue(repovalue), label=repolabel)
1292 1292 if fv.default != configvalue:
1293 1293 configlabel = b'formatvariant.config.special'
1294 1294 else:
1295 1295 configlabel = b'formatvariant.config.default'
1296 1296 fm.condwrite(
1297 1297 ui.verbose,
1298 1298 b'config',
1299 1299 b' %6s',
1300 1300 formatvalue(configvalue),
1301 1301 label=configlabel,
1302 1302 )
1303 1303 fm.condwrite(
1304 1304 ui.verbose,
1305 1305 b'default',
1306 1306 b' %7s',
1307 1307 formatvalue(fv.default),
1308 1308 label=b'formatvariant.default',
1309 1309 )
1310 1310 fm.plain(b'\n')
1311 1311 fm.end()
1312 1312
1313 1313
1314 1314 @command(b'debugfsinfo', [], _(b'[PATH]'), norepo=True)
1315 1315 def debugfsinfo(ui, path=b"."):
1316 1316 """show information detected about current filesystem"""
1317 1317 ui.writenoi18n(b'path: %s\n' % path)
1318 1318 ui.writenoi18n(
1319 1319 b'mounted on: %s\n' % (util.getfsmountpoint(path) or b'(unknown)')
1320 1320 )
1321 1321 ui.writenoi18n(b'exec: %s\n' % (util.checkexec(path) and b'yes' or b'no'))
1322 1322 ui.writenoi18n(b'fstype: %s\n' % (util.getfstype(path) or b'(unknown)'))
1323 1323 ui.writenoi18n(
1324 1324 b'symlink: %s\n' % (util.checklink(path) and b'yes' or b'no')
1325 1325 )
1326 1326 ui.writenoi18n(
1327 1327 b'hardlink: %s\n' % (util.checknlink(path) and b'yes' or b'no')
1328 1328 )
1329 1329 casesensitive = b'(unknown)'
1330 1330 try:
1331 1331 with pycompat.namedtempfile(prefix=b'.debugfsinfo', dir=path) as f:
1332 1332 casesensitive = util.fscasesensitive(f.name) and b'yes' or b'no'
1333 1333 except OSError:
1334 1334 pass
1335 1335 ui.writenoi18n(b'case-sensitive: %s\n' % casesensitive)
1336 1336
1337 1337
1338 1338 @command(
1339 1339 b'debuggetbundle',
1340 1340 [
1341 1341 (b'H', b'head', [], _(b'id of head node'), _(b'ID')),
1342 1342 (b'C', b'common', [], _(b'id of common node'), _(b'ID')),
1343 1343 (
1344 1344 b't',
1345 1345 b'type',
1346 1346 b'bzip2',
1347 1347 _(b'bundle compression type to use'),
1348 1348 _(b'TYPE'),
1349 1349 ),
1350 1350 ],
1351 1351 _(b'REPO FILE [-H|-C ID]...'),
1352 1352 norepo=True,
1353 1353 )
1354 1354 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1355 1355 """retrieves a bundle from a repo
1356 1356
1357 1357 Every ID must be a full-length hex node id string. Saves the bundle to the
1358 1358 given file.
1359 1359 """
1360 1360 opts = pycompat.byteskwargs(opts)
1361 1361 repo = hg.peer(ui, opts, repopath)
1362 1362 if not repo.capable(b'getbundle'):
1363 1363 raise error.Abort(b"getbundle() not supported by target repository")
1364 1364 args = {}
1365 1365 if common:
1366 1366 args['common'] = [bin(s) for s in common]
1367 1367 if head:
1368 1368 args['heads'] = [bin(s) for s in head]
1369 1369 # TODO: get desired bundlecaps from command line.
1370 1370 args['bundlecaps'] = None
1371 1371 bundle = repo.getbundle(b'debug', **args)
1372 1372
1373 1373 bundletype = opts.get(b'type', b'bzip2').lower()
1374 1374 btypes = {
1375 1375 b'none': b'HG10UN',
1376 1376 b'bzip2': b'HG10BZ',
1377 1377 b'gzip': b'HG10GZ',
1378 1378 b'bundle2': b'HG20',
1379 1379 }
1380 1380 bundletype = btypes.get(bundletype)
1381 1381 if bundletype not in bundle2.bundletypes:
1382 1382 raise error.Abort(_(b'unknown bundle type specified with --type'))
1383 1383 bundle2.writebundle(ui, bundle, bundlepath, bundletype)
1384 1384
1385 1385
1386 1386 @command(b'debugignore', [], b'[FILE]')
1387 1387 def debugignore(ui, repo, *files, **opts):
1388 1388 """display the combined ignore pattern and information about ignored files
1389 1389
1390 1390 With no argument display the combined ignore pattern.
1391 1391
1392 1392 Given space separated file names, shows if the given file is ignored and
1393 1393 if so, show the ignore rule (file and line number) that matched it.
1394 1394 """
1395 1395 ignore = repo.dirstate._ignore
1396 1396 if not files:
1397 1397 # Show all the patterns
1398 1398 ui.write(b"%s\n" % pycompat.byterepr(ignore))
1399 1399 else:
1400 1400 m = scmutil.match(repo[None], pats=files)
1401 1401 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
1402 1402 for f in m.files():
1403 1403 nf = util.normpath(f)
1404 1404 ignored = None
1405 1405 ignoredata = None
1406 1406 if nf != b'.':
1407 1407 if ignore(nf):
1408 1408 ignored = nf
1409 1409 ignoredata = repo.dirstate._ignorefileandline(nf)
1410 1410 else:
1411 1411 for p in pathutil.finddirs(nf):
1412 1412 if ignore(p):
1413 1413 ignored = p
1414 1414 ignoredata = repo.dirstate._ignorefileandline(p)
1415 1415 break
1416 1416 if ignored:
1417 1417 if ignored == nf:
1418 1418 ui.write(_(b"%s is ignored\n") % uipathfn(f))
1419 1419 else:
1420 1420 ui.write(
1421 1421 _(
1422 1422 b"%s is ignored because of "
1423 1423 b"containing directory %s\n"
1424 1424 )
1425 1425 % (uipathfn(f), ignored)
1426 1426 )
1427 1427 ignorefile, lineno, line = ignoredata
1428 1428 ui.write(
1429 1429 _(b"(ignore rule in %s, line %d: '%s')\n")
1430 1430 % (ignorefile, lineno, line)
1431 1431 )
1432 1432 else:
1433 1433 ui.write(_(b"%s is not ignored\n") % uipathfn(f))
1434 1434
1435 1435
1436 1436 @command(
1437 1437 b'debugindex',
1438 1438 cmdutil.debugrevlogopts + cmdutil.formatteropts,
1439 1439 _(b'-c|-m|FILE'),
1440 1440 )
1441 1441 def debugindex(ui, repo, file_=None, **opts):
1442 1442 """dump index data for a storage primitive"""
1443 1443 opts = pycompat.byteskwargs(opts)
1444 1444 store = cmdutil.openstorage(repo, b'debugindex', file_, opts)
1445 1445
1446 1446 if ui.debugflag:
1447 1447 shortfn = hex
1448 1448 else:
1449 1449 shortfn = short
1450 1450
1451 1451 idlen = 12
1452 1452 for i in store:
1453 1453 idlen = len(shortfn(store.node(i)))
1454 1454 break
1455 1455
1456 1456 fm = ui.formatter(b'debugindex', opts)
1457 1457 fm.plain(
1458 1458 b' rev linkrev %s %s p2\n'
1459 1459 % (b'nodeid'.ljust(idlen), b'p1'.ljust(idlen))
1460 1460 )
1461 1461
1462 1462 for rev in store:
1463 1463 node = store.node(rev)
1464 1464 parents = store.parents(node)
1465 1465
1466 1466 fm.startitem()
1467 1467 fm.write(b'rev', b'%6d ', rev)
1468 1468 fm.write(b'linkrev', b'%7d ', store.linkrev(rev))
1469 1469 fm.write(b'node', b'%s ', shortfn(node))
1470 1470 fm.write(b'p1', b'%s ', shortfn(parents[0]))
1471 1471 fm.write(b'p2', b'%s', shortfn(parents[1]))
1472 1472 fm.plain(b'\n')
1473 1473
1474 1474 fm.end()
1475 1475
1476 1476
1477 1477 @command(
1478 1478 b'debugindexdot',
1479 1479 cmdutil.debugrevlogopts,
1480 1480 _(b'-c|-m|FILE'),
1481 1481 optionalrepo=True,
1482 1482 )
1483 1483 def debugindexdot(ui, repo, file_=None, **opts):
1484 1484 """dump an index DAG as a graphviz dot file"""
1485 1485 opts = pycompat.byteskwargs(opts)
1486 1486 r = cmdutil.openstorage(repo, b'debugindexdot', file_, opts)
1487 1487 ui.writenoi18n(b"digraph G {\n")
1488 1488 for i in r:
1489 1489 node = r.node(i)
1490 1490 pp = r.parents(node)
1491 1491 ui.write(b"\t%d -> %d\n" % (r.rev(pp[0]), i))
1492 1492 if pp[1] != nullid:
1493 1493 ui.write(b"\t%d -> %d\n" % (r.rev(pp[1]), i))
1494 1494 ui.write(b"}\n")
1495 1495
1496 1496
1497 1497 @command(b'debugindexstats', [])
1498 1498 def debugindexstats(ui, repo):
1499 1499 """show stats related to the changelog index"""
1500 1500 repo.changelog.shortest(nullid, 1)
1501 1501 index = repo.changelog.index
1502 1502 if not util.safehasattr(index, b'stats'):
1503 1503 raise error.Abort(_(b'debugindexstats only works with native code'))
1504 1504 for k, v in sorted(index.stats().items()):
1505 1505 ui.write(b'%s: %d\n' % (k, v))
1506 1506
1507 1507
1508 1508 @command(b'debuginstall', [] + cmdutil.formatteropts, b'', norepo=True)
1509 1509 def debuginstall(ui, **opts):
1510 1510 '''test Mercurial installation
1511 1511
1512 1512 Returns 0 on success.
1513 1513 '''
1514 1514 opts = pycompat.byteskwargs(opts)
1515 1515
1516 1516 problems = 0
1517 1517
1518 1518 fm = ui.formatter(b'debuginstall', opts)
1519 1519 fm.startitem()
1520 1520
1521 1521 # encoding might be unknown or wrong. don't translate these messages.
1522 1522 fm.write(b'encoding', b"checking encoding (%s)...\n", encoding.encoding)
1523 1523 err = None
1524 1524 try:
1525 1525 codecs.lookup(pycompat.sysstr(encoding.encoding))
1526 1526 except LookupError as inst:
1527 1527 err = stringutil.forcebytestr(inst)
1528 1528 problems += 1
1529 1529 fm.condwrite(
1530 1530 err,
1531 1531 b'encodingerror',
1532 1532 b" %s\n (check that your locale is properly set)\n",
1533 1533 err,
1534 1534 )
1535 1535
1536 1536 # Python
1537 1537 pythonlib = None
1538 1538 if util.safehasattr(os, '__file__'):
1539 1539 pythonlib = os.path.dirname(pycompat.fsencode(os.__file__))
1540 1540 elif getattr(sys, 'oxidized', False):
1541 1541 pythonlib = pycompat.sysexecutable
1542 1542
1543 1543 fm.write(
1544 1544 b'pythonexe',
1545 1545 _(b"checking Python executable (%s)\n"),
1546 1546 pycompat.sysexecutable or _(b"unknown"),
1547 1547 )
1548 1548 fm.write(
1549 1549 b'pythonimplementation',
1550 1550 _(b"checking Python implementation (%s)\n"),
1551 1551 pycompat.sysbytes(platform.python_implementation()),
1552 1552 )
1553 1553 fm.write(
1554 1554 b'pythonver',
1555 1555 _(b"checking Python version (%s)\n"),
1556 1556 (b"%d.%d.%d" % sys.version_info[:3]),
1557 1557 )
1558 1558 fm.write(
1559 1559 b'pythonlib',
1560 1560 _(b"checking Python lib (%s)...\n"),
1561 1561 pythonlib or _(b"unknown"),
1562 1562 )
1563 1563
1564 1564 try:
1565 1565 from . import rustext
1566 1566
1567 1567 rustext.__doc__ # trigger lazy import
1568 1568 except ImportError:
1569 1569 rustext = None
1570 1570
1571 1571 security = set(sslutil.supportedprotocols)
1572 1572 if sslutil.hassni:
1573 1573 security.add(b'sni')
1574 1574
1575 1575 fm.write(
1576 1576 b'pythonsecurity',
1577 1577 _(b"checking Python security support (%s)\n"),
1578 1578 fm.formatlist(sorted(security), name=b'protocol', fmt=b'%s', sep=b','),
1579 1579 )
1580 1580
1581 1581 # These are warnings, not errors. So don't increment problem count. This
1582 1582 # may change in the future.
1583 1583 if b'tls1.2' not in security:
1584 1584 fm.plain(
1585 1585 _(
1586 1586 b' TLS 1.2 not supported by Python install; '
1587 1587 b'network connections lack modern security\n'
1588 1588 )
1589 1589 )
1590 1590 if b'sni' not in security:
1591 1591 fm.plain(
1592 1592 _(
1593 1593 b' SNI not supported by Python install; may have '
1594 1594 b'connectivity issues with some servers\n'
1595 1595 )
1596 1596 )
1597 1597
1598 1598 fm.plain(
1599 1599 _(
1600 1600 b"checking Rust extensions (%s)\n"
1601 1601 % (b'missing' if rustext is None else b'installed')
1602 1602 ),
1603 1603 )
1604 1604
1605 1605 # TODO print CA cert info
1606 1606
1607 1607 # hg version
1608 1608 hgver = util.version()
1609 1609 fm.write(
1610 1610 b'hgver', _(b"checking Mercurial version (%s)\n"), hgver.split(b'+')[0]
1611 1611 )
1612 1612 fm.write(
1613 1613 b'hgverextra',
1614 1614 _(b"checking Mercurial custom build (%s)\n"),
1615 1615 b'+'.join(hgver.split(b'+')[1:]),
1616 1616 )
1617 1617
1618 1618 # compiled modules
1619 1619 hgmodules = None
1620 1620 if util.safehasattr(sys.modules[__name__], '__file__'):
1621 1621 hgmodules = os.path.dirname(pycompat.fsencode(__file__))
1622 1622 elif getattr(sys, 'oxidized', False):
1623 1623 hgmodules = pycompat.sysexecutable
1624 1624
1625 1625 fm.write(
1626 1626 b'hgmodulepolicy', _(b"checking module policy (%s)\n"), policy.policy
1627 1627 )
1628 1628 fm.write(
1629 1629 b'hgmodules',
1630 1630 _(b"checking installed modules (%s)...\n"),
1631 1631 hgmodules or _(b"unknown"),
1632 1632 )
1633 1633
1634 1634 rustandc = policy.policy in (b'rust+c', b'rust+c-allow')
1635 1635 rustext = rustandc # for now, that's the only case
1636 1636 cext = policy.policy in (b'c', b'allow') or rustandc
1637 1637 nopure = cext or rustext
1638 1638 if nopure:
1639 1639 err = None
1640 1640 try:
1641 1641 if cext:
1642 1642 from .cext import ( # pytype: disable=import-error
1643 1643 base85,
1644 1644 bdiff,
1645 1645 mpatch,
1646 1646 osutil,
1647 1647 )
1648 1648
1649 1649 # quiet pyflakes
1650 1650 dir(bdiff), dir(mpatch), dir(base85), dir(osutil)
1651 1651 if rustext:
1652 1652 from .rustext import ( # pytype: disable=import-error
1653 1653 ancestor,
1654 1654 dirstate,
1655 1655 )
1656 1656
1657 1657 dir(ancestor), dir(dirstate) # quiet pyflakes
1658 1658 except Exception as inst:
1659 1659 err = stringutil.forcebytestr(inst)
1660 1660 problems += 1
1661 1661 fm.condwrite(err, b'extensionserror', b" %s\n", err)
1662 1662
1663 1663 compengines = util.compengines._engines.values()
1664 1664 fm.write(
1665 1665 b'compengines',
1666 1666 _(b'checking registered compression engines (%s)\n'),
1667 1667 fm.formatlist(
1668 1668 sorted(e.name() for e in compengines),
1669 1669 name=b'compengine',
1670 1670 fmt=b'%s',
1671 1671 sep=b', ',
1672 1672 ),
1673 1673 )
1674 1674 fm.write(
1675 1675 b'compenginesavail',
1676 1676 _(b'checking available compression engines (%s)\n'),
1677 1677 fm.formatlist(
1678 1678 sorted(e.name() for e in compengines if e.available()),
1679 1679 name=b'compengine',
1680 1680 fmt=b'%s',
1681 1681 sep=b', ',
1682 1682 ),
1683 1683 )
1684 1684 wirecompengines = compression.compengines.supportedwireengines(
1685 1685 compression.SERVERROLE
1686 1686 )
1687 1687 fm.write(
1688 1688 b'compenginesserver',
1689 1689 _(
1690 1690 b'checking available compression engines '
1691 1691 b'for wire protocol (%s)\n'
1692 1692 ),
1693 1693 fm.formatlist(
1694 1694 [e.name() for e in wirecompengines if e.wireprotosupport()],
1695 1695 name=b'compengine',
1696 1696 fmt=b'%s',
1697 1697 sep=b', ',
1698 1698 ),
1699 1699 )
1700 1700 re2 = b'missing'
1701 1701 if util._re2:
1702 1702 re2 = b'available'
1703 1703 fm.plain(_(b'checking "re2" regexp engine (%s)\n') % re2)
1704 1704 fm.data(re2=bool(util._re2))
1705 1705
1706 1706 # templates
1707 1707 p = templater.templatedir()
1708 1708 fm.write(b'templatedirs', b'checking templates (%s)...\n', p or b'')
1709 1709 fm.condwrite(not p, b'', _(b" no template directories found\n"))
1710 1710 if p:
1711 1711 (m, fp) = templater.try_open_template(b"map-cmdline.default")
1712 1712 if m:
1713 1713 # template found, check if it is working
1714 1714 err = None
1715 1715 try:
1716 1716 templater.templater.frommapfile(m)
1717 1717 except Exception as inst:
1718 1718 err = stringutil.forcebytestr(inst)
1719 1719 p = None
1720 1720 fm.condwrite(err, b'defaulttemplateerror', b" %s\n", err)
1721 1721 else:
1722 1722 p = None
1723 1723 fm.condwrite(
1724 1724 p, b'defaulttemplate', _(b"checking default template (%s)\n"), m
1725 1725 )
1726 1726 fm.condwrite(
1727 1727 not m,
1728 1728 b'defaulttemplatenotfound',
1729 1729 _(b" template '%s' not found\n"),
1730 1730 b"default",
1731 1731 )
1732 1732 if not p:
1733 1733 problems += 1
1734 1734 fm.condwrite(
1735 1735 not p, b'', _(b" (templates seem to have been installed incorrectly)\n")
1736 1736 )
1737 1737
1738 1738 # editor
1739 1739 editor = ui.geteditor()
1740 1740 editor = util.expandpath(editor)
1741 1741 editorbin = procutil.shellsplit(editor)[0]
1742 1742 fm.write(b'editor', _(b"checking commit editor... (%s)\n"), editorbin)
1743 1743 cmdpath = procutil.findexe(editorbin)
1744 1744 fm.condwrite(
1745 1745 not cmdpath and editor == b'vi',
1746 1746 b'vinotfound',
1747 1747 _(
1748 1748 b" No commit editor set and can't find %s in PATH\n"
1749 1749 b" (specify a commit editor in your configuration"
1750 1750 b" file)\n"
1751 1751 ),
1752 1752 not cmdpath and editor == b'vi' and editorbin,
1753 1753 )
1754 1754 fm.condwrite(
1755 1755 not cmdpath and editor != b'vi',
1756 1756 b'editornotfound',
1757 1757 _(
1758 1758 b" Can't find editor '%s' in PATH\n"
1759 1759 b" (specify a commit editor in your configuration"
1760 1760 b" file)\n"
1761 1761 ),
1762 1762 not cmdpath and editorbin,
1763 1763 )
1764 1764 if not cmdpath and editor != b'vi':
1765 1765 problems += 1
1766 1766
1767 1767 # check username
1768 1768 username = None
1769 1769 err = None
1770 1770 try:
1771 1771 username = ui.username()
1772 1772 except error.Abort as e:
1773 1773 err = e.message
1774 1774 problems += 1
1775 1775
1776 1776 fm.condwrite(
1777 1777 username, b'username', _(b"checking username (%s)\n"), username
1778 1778 )
1779 1779 fm.condwrite(
1780 1780 err,
1781 1781 b'usernameerror',
1782 1782 _(
1783 1783 b"checking username...\n %s\n"
1784 1784 b" (specify a username in your configuration file)\n"
1785 1785 ),
1786 1786 err,
1787 1787 )
1788 1788
1789 1789 for name, mod in extensions.extensions():
1790 1790 handler = getattr(mod, 'debuginstall', None)
1791 1791 if handler is not None:
1792 1792 problems += handler(ui, fm)
1793 1793
1794 1794 fm.condwrite(not problems, b'', _(b"no problems detected\n"))
1795 1795 if not problems:
1796 1796 fm.data(problems=problems)
1797 1797 fm.condwrite(
1798 1798 problems,
1799 1799 b'problems',
1800 1800 _(b"%d problems detected, please check your install!\n"),
1801 1801 problems,
1802 1802 )
1803 1803 fm.end()
1804 1804
1805 1805 return problems
1806 1806
1807 1807
1808 1808 @command(b'debugknown', [], _(b'REPO ID...'), norepo=True)
1809 1809 def debugknown(ui, repopath, *ids, **opts):
1810 1810 """test whether node ids are known to a repo
1811 1811
1812 1812 Every ID must be a full-length hex node id string. Returns a list of 0s
1813 1813 and 1s indicating unknown/known.
1814 1814 """
1815 1815 opts = pycompat.byteskwargs(opts)
1816 1816 repo = hg.peer(ui, opts, repopath)
1817 1817 if not repo.capable(b'known'):
1818 1818 raise error.Abort(b"known() not supported by target repository")
1819 1819 flags = repo.known([bin(s) for s in ids])
1820 1820 ui.write(b"%s\n" % (b"".join([f and b"1" or b"0" for f in flags])))
1821 1821
1822 1822
1823 1823 @command(b'debuglabelcomplete', [], _(b'LABEL...'))
1824 1824 def debuglabelcomplete(ui, repo, *args):
1825 1825 '''backwards compatibility with old bash completion scripts (DEPRECATED)'''
1826 1826 debugnamecomplete(ui, repo, *args)
1827 1827
1828 1828
1829 1829 @command(
1830 1830 b'debuglocks',
1831 1831 [
1832 1832 (b'L', b'force-lock', None, _(b'free the store lock (DANGEROUS)')),
1833 1833 (
1834 1834 b'W',
1835 1835 b'force-wlock',
1836 1836 None,
1837 1837 _(b'free the working state lock (DANGEROUS)'),
1838 1838 ),
1839 1839 (b's', b'set-lock', None, _(b'set the store lock until stopped')),
1840 1840 (
1841 1841 b'S',
1842 1842 b'set-wlock',
1843 1843 None,
1844 1844 _(b'set the working state lock until stopped'),
1845 1845 ),
1846 1846 ],
1847 1847 _(b'[OPTION]...'),
1848 1848 )
1849 1849 def debuglocks(ui, repo, **opts):
1850 1850 """show or modify state of locks
1851 1851
1852 1852 By default, this command will show which locks are held. This
1853 1853 includes the user and process holding the lock, the amount of time
1854 1854 the lock has been held, and the machine name where the process is
1855 1855 running if it's not local.
1856 1856
1857 1857 Locks protect the integrity of Mercurial's data, so should be
1858 1858 treated with care. System crashes or other interruptions may cause
1859 1859 locks to not be properly released, though Mercurial will usually
1860 1860 detect and remove such stale locks automatically.
1861 1861
1862 1862 However, detecting stale locks may not always be possible (for
1863 1863 instance, on a shared filesystem). Removing locks may also be
1864 1864 blocked by filesystem permissions.
1865 1865
1866 1866 Setting a lock will prevent other commands from changing the data.
1867 1867 The command will wait until an interruption (SIGINT, SIGTERM, ...) occurs.
1868 1868 The set locks are removed when the command exits.
1869 1869
1870 1870 Returns 0 if no locks are held.
1871 1871
1872 1872 """
1873 1873
1874 1874 if opts.get('force_lock'):
1875 1875 repo.svfs.unlink(b'lock')
1876 1876 if opts.get('force_wlock'):
1877 1877 repo.vfs.unlink(b'wlock')
1878 1878 if opts.get('force_lock') or opts.get('force_wlock'):
1879 1879 return 0
1880 1880
1881 1881 locks = []
1882 1882 try:
1883 1883 if opts.get('set_wlock'):
1884 1884 try:
1885 1885 locks.append(repo.wlock(False))
1886 1886 except error.LockHeld:
1887 1887 raise error.Abort(_(b'wlock is already held'))
1888 1888 if opts.get('set_lock'):
1889 1889 try:
1890 1890 locks.append(repo.lock(False))
1891 1891 except error.LockHeld:
1892 1892 raise error.Abort(_(b'lock is already held'))
1893 1893 if len(locks):
1894 1894 ui.promptchoice(_(b"ready to release the lock (y)? $$ &Yes"))
1895 1895 return 0
1896 1896 finally:
1897 1897 release(*locks)
1898 1898
1899 1899 now = time.time()
1900 1900 held = 0
1901 1901
1902 1902 def report(vfs, name, method):
1903 1903 # this causes stale locks to get reaped for more accurate reporting
1904 1904 try:
1905 1905 l = method(False)
1906 1906 except error.LockHeld:
1907 1907 l = None
1908 1908
1909 1909 if l:
1910 1910 l.release()
1911 1911 else:
1912 1912 try:
1913 1913 st = vfs.lstat(name)
1914 1914 age = now - st[stat.ST_MTIME]
1915 1915 user = util.username(st.st_uid)
1916 1916 locker = vfs.readlock(name)
1917 1917 if b":" in locker:
1918 1918 host, pid = locker.split(b':')
1919 1919 if host == socket.gethostname():
1920 1920 locker = b'user %s, process %s' % (user or b'None', pid)
1921 1921 else:
1922 1922 locker = b'user %s, process %s, host %s' % (
1923 1923 user or b'None',
1924 1924 pid,
1925 1925 host,
1926 1926 )
1927 1927 ui.writenoi18n(b"%-6s %s (%ds)\n" % (name + b":", locker, age))
1928 1928 return 1
1929 1929 except OSError as e:
1930 1930 if e.errno != errno.ENOENT:
1931 1931 raise
1932 1932
1933 1933 ui.writenoi18n(b"%-6s free\n" % (name + b":"))
1934 1934 return 0
1935 1935
1936 1936 held += report(repo.svfs, b"lock", repo.lock)
1937 1937 held += report(repo.vfs, b"wlock", repo.wlock)
1938 1938
1939 1939 return held
1940 1940
1941 1941
1942 1942 @command(
1943 1943 b'debugmanifestfulltextcache',
1944 1944 [
1945 1945 (b'', b'clear', False, _(b'clear the cache')),
1946 1946 (
1947 1947 b'a',
1948 1948 b'add',
1949 1949 [],
1950 1950 _(b'add the given manifest nodes to the cache'),
1951 1951 _(b'NODE'),
1952 1952 ),
1953 1953 ],
1954 1954 b'',
1955 1955 )
1956 1956 def debugmanifestfulltextcache(ui, repo, add=(), **opts):
1957 1957 """show, clear or amend the contents of the manifest fulltext cache"""
1958 1958
1959 1959 def getcache():
1960 1960 r = repo.manifestlog.getstorage(b'')
1961 1961 try:
1962 1962 return r._fulltextcache
1963 1963 except AttributeError:
1964 1964 msg = _(
1965 1965 b"Current revlog implementation doesn't appear to have a "
1966 1966 b"manifest fulltext cache\n"
1967 1967 )
1968 1968 raise error.Abort(msg)
1969 1969
1970 1970 if opts.get('clear'):
1971 1971 with repo.wlock():
1972 1972 cache = getcache()
1973 1973 cache.clear(clear_persisted_data=True)
1974 1974 return
1975 1975
1976 1976 if add:
1977 1977 with repo.wlock():
1978 1978 m = repo.manifestlog
1979 1979 store = m.getstorage(b'')
1980 1980 for n in add:
1981 1981 try:
1982 1982 manifest = m[store.lookup(n)]
1983 1983 except error.LookupError as e:
1984 1984 raise error.Abort(e, hint=b"Check your manifest node id")
1985 1985 manifest.read() # stores revisision in cache too
1986 1986 return
1987 1987
1988 1988 cache = getcache()
1989 1989 if not len(cache):
1990 1990 ui.write(_(b'cache empty\n'))
1991 1991 else:
1992 1992 ui.write(
1993 1993 _(
1994 1994 b'cache contains %d manifest entries, in order of most to '
1995 1995 b'least recent:\n'
1996 1996 )
1997 1997 % (len(cache),)
1998 1998 )
1999 1999 totalsize = 0
2000 2000 for nodeid in cache:
2001 2001 # Use cache.get to not update the LRU order
2002 2002 data = cache.peek(nodeid)
2003 2003 size = len(data)
2004 2004 totalsize += size + 24 # 20 bytes nodeid, 4 bytes size
2005 2005 ui.write(
2006 2006 _(b'id: %s, size %s\n') % (hex(nodeid), util.bytecount(size))
2007 2007 )
2008 2008 ondisk = cache._opener.stat(b'manifestfulltextcache').st_size
2009 2009 ui.write(
2010 2010 _(b'total cache data size %s, on-disk %s\n')
2011 2011 % (util.bytecount(totalsize), util.bytecount(ondisk))
2012 2012 )
2013 2013
2014 2014
2015 2015 @command(b'debugmergestate', [] + cmdutil.templateopts, b'')
2016 2016 def debugmergestate(ui, repo, *args, **opts):
2017 2017 """print merge state
2018 2018
2019 2019 Use --verbose to print out information about whether v1 or v2 merge state
2020 2020 was chosen."""
2021 2021
2022 2022 if ui.verbose:
2023 2023 ms = mergestatemod.mergestate(repo)
2024 2024
2025 2025 # sort so that reasonable information is on top
2026 2026 v1records = ms._readrecordsv1()
2027 2027 v2records = ms._readrecordsv2()
2028 2028
2029 2029 if not v1records and not v2records:
2030 2030 pass
2031 2031 elif not v2records:
2032 2032 ui.writenoi18n(b'no version 2 merge state\n')
2033 2033 elif ms._v1v2match(v1records, v2records):
2034 2034 ui.writenoi18n(b'v1 and v2 states match: using v2\n')
2035 2035 else:
2036 2036 ui.writenoi18n(b'v1 and v2 states mismatch: using v1\n')
2037 2037
2038 2038 opts = pycompat.byteskwargs(opts)
2039 2039 if not opts[b'template']:
2040 2040 opts[b'template'] = (
2041 2041 b'{if(commits, "", "no merge state found\n")}'
2042 2042 b'{commits % "{name}{if(label, " ({label})")}: {node}\n"}'
2043 2043 b'{files % "file: {path} (state \\"{state}\\")\n'
2044 2044 b'{if(local_path, "'
2045 2045 b' local path: {local_path} (hash {local_key}, flags \\"{local_flags}\\")\n'
2046 2046 b' ancestor path: {ancestor_path} (node {ancestor_node})\n'
2047 2047 b' other path: {other_path} (node {other_node})\n'
2048 2048 b'")}'
2049 2049 b'{if(rename_side, "'
2050 2050 b' rename side: {rename_side}\n'
2051 2051 b' renamed path: {renamed_path}\n'
2052 2052 b'")}'
2053 2053 b'{extras % " extra: {key} = {value}\n"}'
2054 2054 b'"}'
2055 2055 b'{extras % "extra: {file} ({key} = {value})\n"}'
2056 2056 )
2057 2057
2058 2058 ms = mergestatemod.mergestate.read(repo)
2059 2059
2060 2060 fm = ui.formatter(b'debugmergestate', opts)
2061 2061 fm.startitem()
2062 2062
2063 2063 fm_commits = fm.nested(b'commits')
2064 2064 if ms.active():
2065 2065 for name, node, label_index in (
2066 2066 (b'local', ms.local, 0),
2067 2067 (b'other', ms.other, 1),
2068 2068 ):
2069 2069 fm_commits.startitem()
2070 2070 fm_commits.data(name=name)
2071 2071 fm_commits.data(node=hex(node))
2072 2072 if ms._labels and len(ms._labels) > label_index:
2073 2073 fm_commits.data(label=ms._labels[label_index])
2074 2074 fm_commits.end()
2075 2075
2076 2076 fm_files = fm.nested(b'files')
2077 2077 if ms.active():
2078 2078 for f in ms:
2079 2079 fm_files.startitem()
2080 2080 fm_files.data(path=f)
2081 2081 state = ms._state[f]
2082 2082 fm_files.data(state=state[0])
2083 2083 if state[0] in (
2084 2084 mergestatemod.MERGE_RECORD_UNRESOLVED,
2085 2085 mergestatemod.MERGE_RECORD_RESOLVED,
2086 2086 ):
2087 2087 fm_files.data(local_key=state[1])
2088 2088 fm_files.data(local_path=state[2])
2089 2089 fm_files.data(ancestor_path=state[3])
2090 2090 fm_files.data(ancestor_node=state[4])
2091 2091 fm_files.data(other_path=state[5])
2092 2092 fm_files.data(other_node=state[6])
2093 2093 fm_files.data(local_flags=state[7])
2094 2094 elif state[0] in (
2095 2095 mergestatemod.MERGE_RECORD_UNRESOLVED_PATH,
2096 2096 mergestatemod.MERGE_RECORD_RESOLVED_PATH,
2097 2097 ):
2098 2098 fm_files.data(renamed_path=state[1])
2099 2099 fm_files.data(rename_side=state[2])
2100 2100 fm_extras = fm_files.nested(b'extras')
2101 2101 for k, v in sorted(ms.extras(f).items()):
2102 2102 fm_extras.startitem()
2103 2103 fm_extras.data(key=k)
2104 2104 fm_extras.data(value=v)
2105 2105 fm_extras.end()
2106 2106
2107 2107 fm_files.end()
2108 2108
2109 2109 fm_extras = fm.nested(b'extras')
2110 2110 for f, d in sorted(pycompat.iteritems(ms.allextras())):
2111 2111 if f in ms:
2112 2112 # If file is in mergestate, we have already processed it's extras
2113 2113 continue
2114 2114 for k, v in pycompat.iteritems(d):
2115 2115 fm_extras.startitem()
2116 2116 fm_extras.data(file=f)
2117 2117 fm_extras.data(key=k)
2118 2118 fm_extras.data(value=v)
2119 2119 fm_extras.end()
2120 2120
2121 2121 fm.end()
2122 2122
2123 2123
2124 2124 @command(b'debugnamecomplete', [], _(b'NAME...'))
2125 2125 def debugnamecomplete(ui, repo, *args):
2126 2126 '''complete "names" - tags, open branch names, bookmark names'''
2127 2127
2128 2128 names = set()
2129 2129 # since we previously only listed open branches, we will handle that
2130 2130 # specially (after this for loop)
2131 2131 for name, ns in pycompat.iteritems(repo.names):
2132 2132 if name != b'branches':
2133 2133 names.update(ns.listnames(repo))
2134 2134 names.update(
2135 2135 tag
2136 2136 for (tag, heads, tip, closed) in repo.branchmap().iterbranches()
2137 2137 if not closed
2138 2138 )
2139 2139 completions = set()
2140 2140 if not args:
2141 2141 args = [b'']
2142 2142 for a in args:
2143 2143 completions.update(n for n in names if n.startswith(a))
2144 2144 ui.write(b'\n'.join(sorted(completions)))
2145 2145 ui.write(b'\n')
2146 2146
2147 2147
2148 2148 @command(
2149 2149 b'debugnodemap',
2150 2150 [
2151 2151 (
2152 2152 b'',
2153 2153 b'dump-new',
2154 2154 False,
2155 2155 _(b'write a (new) persistent binary nodemap on stdin'),
2156 2156 ),
2157 2157 (b'', b'dump-disk', False, _(b'dump on-disk data on stdin')),
2158 2158 (
2159 2159 b'',
2160 2160 b'check',
2161 2161 False,
2162 2162 _(b'check that the data on disk data are correct.'),
2163 2163 ),
2164 2164 (
2165 2165 b'',
2166 2166 b'metadata',
2167 2167 False,
2168 2168 _(b'display the on disk meta data for the nodemap'),
2169 2169 ),
2170 2170 ],
2171 2171 )
2172 2172 def debugnodemap(ui, repo, **opts):
2173 2173 """write and inspect on disk nodemap
2174 2174 """
2175 2175 if opts['dump_new']:
2176 2176 unfi = repo.unfiltered()
2177 2177 cl = unfi.changelog
2178 2178 if util.safehasattr(cl.index, "nodemap_data_all"):
2179 2179 data = cl.index.nodemap_data_all()
2180 2180 else:
2181 2181 data = nodemap.persistent_data(cl.index)
2182 2182 ui.write(data)
2183 2183 elif opts['dump_disk']:
2184 2184 unfi = repo.unfiltered()
2185 2185 cl = unfi.changelog
2186 2186 nm_data = nodemap.persisted_data(cl)
2187 2187 if nm_data is not None:
2188 2188 docket, data = nm_data
2189 2189 ui.write(data[:])
2190 2190 elif opts['check']:
2191 2191 unfi = repo.unfiltered()
2192 2192 cl = unfi.changelog
2193 2193 nm_data = nodemap.persisted_data(cl)
2194 2194 if nm_data is not None:
2195 2195 docket, data = nm_data
2196 2196 return nodemap.check_data(ui, cl.index, data)
2197 2197 elif opts['metadata']:
2198 2198 unfi = repo.unfiltered()
2199 2199 cl = unfi.changelog
2200 2200 nm_data = nodemap.persisted_data(cl)
2201 2201 if nm_data is not None:
2202 2202 docket, data = nm_data
2203 2203 ui.write((b"uid: %s\n") % docket.uid)
2204 2204 ui.write((b"tip-rev: %d\n") % docket.tip_rev)
2205 2205 ui.write((b"tip-node: %s\n") % hex(docket.tip_node))
2206 2206 ui.write((b"data-length: %d\n") % docket.data_length)
2207 2207 ui.write((b"data-unused: %d\n") % docket.data_unused)
2208 2208 unused_perc = docket.data_unused * 100.0 / docket.data_length
2209 2209 ui.write((b"data-unused: %2.3f%%\n") % unused_perc)
2210 2210
2211 2211
2212 2212 @command(
2213 2213 b'debugobsolete',
2214 2214 [
2215 2215 (b'', b'flags', 0, _(b'markers flag')),
2216 2216 (
2217 2217 b'',
2218 2218 b'record-parents',
2219 2219 False,
2220 2220 _(b'record parent information for the precursor'),
2221 2221 ),
2222 2222 (b'r', b'rev', [], _(b'display markers relevant to REV')),
2223 2223 (
2224 2224 b'',
2225 2225 b'exclusive',
2226 2226 False,
2227 2227 _(b'restrict display to markers only relevant to REV'),
2228 2228 ),
2229 2229 (b'', b'index', False, _(b'display index of the marker')),
2230 2230 (b'', b'delete', [], _(b'delete markers specified by indices')),
2231 2231 ]
2232 2232 + cmdutil.commitopts2
2233 2233 + cmdutil.formatteropts,
2234 2234 _(b'[OBSOLETED [REPLACEMENT ...]]'),
2235 2235 )
2236 2236 def debugobsolete(ui, repo, precursor=None, *successors, **opts):
2237 2237 """create arbitrary obsolete marker
2238 2238
2239 2239 With no arguments, displays the list of obsolescence markers."""
2240 2240
2241 2241 opts = pycompat.byteskwargs(opts)
2242 2242
2243 2243 def parsenodeid(s):
2244 2244 try:
2245 2245 # We do not use revsingle/revrange functions here to accept
2246 2246 # arbitrary node identifiers, possibly not present in the
2247 2247 # local repository.
2248 2248 n = bin(s)
2249 2249 if len(n) != len(nullid):
2250 2250 raise TypeError()
2251 2251 return n
2252 2252 except TypeError:
2253 2253 raise error.Abort(
2254 2254 b'changeset references must be full hexadecimal '
2255 2255 b'node identifiers'
2256 2256 )
2257 2257
2258 2258 if opts.get(b'delete'):
2259 2259 indices = []
2260 2260 for v in opts.get(b'delete'):
2261 2261 try:
2262 2262 indices.append(int(v))
2263 2263 except ValueError:
2264 2264 raise error.Abort(
2265 2265 _(b'invalid index value: %r') % v,
2266 2266 hint=_(b'use integers for indices'),
2267 2267 )
2268 2268
2269 2269 if repo.currenttransaction():
2270 2270 raise error.Abort(
2271 2271 _(b'cannot delete obsmarkers in the middle of transaction.')
2272 2272 )
2273 2273
2274 2274 with repo.lock():
2275 2275 n = repair.deleteobsmarkers(repo.obsstore, indices)
2276 2276 ui.write(_(b'deleted %i obsolescence markers\n') % n)
2277 2277
2278 2278 return
2279 2279
2280 2280 if precursor is not None:
2281 2281 if opts[b'rev']:
2282 2282 raise error.Abort(b'cannot select revision when creating marker')
2283 2283 metadata = {}
2284 2284 metadata[b'user'] = encoding.fromlocal(opts[b'user'] or ui.username())
2285 2285 succs = tuple(parsenodeid(succ) for succ in successors)
2286 2286 l = repo.lock()
2287 2287 try:
2288 2288 tr = repo.transaction(b'debugobsolete')
2289 2289 try:
2290 2290 date = opts.get(b'date')
2291 2291 if date:
2292 2292 date = dateutil.parsedate(date)
2293 2293 else:
2294 2294 date = None
2295 2295 prec = parsenodeid(precursor)
2296 2296 parents = None
2297 2297 if opts[b'record_parents']:
2298 2298 if prec not in repo.unfiltered():
2299 2299 raise error.Abort(
2300 2300 b'cannot used --record-parents on '
2301 2301 b'unknown changesets'
2302 2302 )
2303 2303 parents = repo.unfiltered()[prec].parents()
2304 2304 parents = tuple(p.node() for p in parents)
2305 2305 repo.obsstore.create(
2306 2306 tr,
2307 2307 prec,
2308 2308 succs,
2309 2309 opts[b'flags'],
2310 2310 parents=parents,
2311 2311 date=date,
2312 2312 metadata=metadata,
2313 2313 ui=ui,
2314 2314 )
2315 2315 tr.close()
2316 2316 except ValueError as exc:
2317 2317 raise error.Abort(
2318 2318 _(b'bad obsmarker input: %s') % pycompat.bytestr(exc)
2319 2319 )
2320 2320 finally:
2321 2321 tr.release()
2322 2322 finally:
2323 2323 l.release()
2324 2324 else:
2325 2325 if opts[b'rev']:
2326 2326 revs = scmutil.revrange(repo, opts[b'rev'])
2327 2327 nodes = [repo[r].node() for r in revs]
2328 2328 markers = list(
2329 2329 obsutil.getmarkers(
2330 2330 repo, nodes=nodes, exclusive=opts[b'exclusive']
2331 2331 )
2332 2332 )
2333 2333 markers.sort(key=lambda x: x._data)
2334 2334 else:
2335 2335 markers = obsutil.getmarkers(repo)
2336 2336
2337 2337 markerstoiter = markers
2338 2338 isrelevant = lambda m: True
2339 2339 if opts.get(b'rev') and opts.get(b'index'):
2340 2340 markerstoiter = obsutil.getmarkers(repo)
2341 2341 markerset = set(markers)
2342 2342 isrelevant = lambda m: m in markerset
2343 2343
2344 2344 fm = ui.formatter(b'debugobsolete', opts)
2345 2345 for i, m in enumerate(markerstoiter):
2346 2346 if not isrelevant(m):
2347 2347 # marker can be irrelevant when we're iterating over a set
2348 2348 # of markers (markerstoiter) which is bigger than the set
2349 2349 # of markers we want to display (markers)
2350 2350 # this can happen if both --index and --rev options are
2351 2351 # provided and thus we need to iterate over all of the markers
2352 2352 # to get the correct indices, but only display the ones that
2353 2353 # are relevant to --rev value
2354 2354 continue
2355 2355 fm.startitem()
2356 2356 ind = i if opts.get(b'index') else None
2357 2357 cmdutil.showmarker(fm, m, index=ind)
2358 2358 fm.end()
2359 2359
2360 2360
2361 2361 @command(
2362 2362 b'debugp1copies',
2363 2363 [(b'r', b'rev', b'', _(b'revision to debug'), _(b'REV'))],
2364 2364 _(b'[-r REV]'),
2365 2365 )
2366 2366 def debugp1copies(ui, repo, **opts):
2367 2367 """dump copy information compared to p1"""
2368 2368
2369 2369 opts = pycompat.byteskwargs(opts)
2370 2370 ctx = scmutil.revsingle(repo, opts.get(b'rev'), default=None)
2371 2371 for dst, src in ctx.p1copies().items():
2372 2372 ui.write(b'%s -> %s\n' % (src, dst))
2373 2373
2374 2374
2375 2375 @command(
2376 2376 b'debugp2copies',
2377 2377 [(b'r', b'rev', b'', _(b'revision to debug'), _(b'REV'))],
2378 2378 _(b'[-r REV]'),
2379 2379 )
2380 2380 def debugp1copies(ui, repo, **opts):
2381 2381 """dump copy information compared to p2"""
2382 2382
2383 2383 opts = pycompat.byteskwargs(opts)
2384 2384 ctx = scmutil.revsingle(repo, opts.get(b'rev'), default=None)
2385 2385 for dst, src in ctx.p2copies().items():
2386 2386 ui.write(b'%s -> %s\n' % (src, dst))
2387 2387
2388 2388
2389 2389 @command(
2390 2390 b'debugpathcomplete',
2391 2391 [
2392 2392 (b'f', b'full', None, _(b'complete an entire path')),
2393 2393 (b'n', b'normal', None, _(b'show only normal files')),
2394 2394 (b'a', b'added', None, _(b'show only added files')),
2395 2395 (b'r', b'removed', None, _(b'show only removed files')),
2396 2396 ],
2397 2397 _(b'FILESPEC...'),
2398 2398 )
2399 2399 def debugpathcomplete(ui, repo, *specs, **opts):
2400 2400 '''complete part or all of a tracked path
2401 2401
2402 2402 This command supports shells that offer path name completion. It
2403 2403 currently completes only files already known to the dirstate.
2404 2404
2405 2405 Completion extends only to the next path segment unless
2406 2406 --full is specified, in which case entire paths are used.'''
2407 2407
2408 2408 def complete(path, acceptable):
2409 2409 dirstate = repo.dirstate
2410 2410 spec = os.path.normpath(os.path.join(encoding.getcwd(), path))
2411 2411 rootdir = repo.root + pycompat.ossep
2412 2412 if spec != repo.root and not spec.startswith(rootdir):
2413 2413 return [], []
2414 2414 if os.path.isdir(spec):
2415 2415 spec += b'/'
2416 2416 spec = spec[len(rootdir) :]
2417 2417 fixpaths = pycompat.ossep != b'/'
2418 2418 if fixpaths:
2419 2419 spec = spec.replace(pycompat.ossep, b'/')
2420 2420 speclen = len(spec)
2421 2421 fullpaths = opts['full']
2422 2422 files, dirs = set(), set()
2423 2423 adddir, addfile = dirs.add, files.add
2424 2424 for f, st in pycompat.iteritems(dirstate):
2425 2425 if f.startswith(spec) and st[0] in acceptable:
2426 2426 if fixpaths:
2427 2427 f = f.replace(b'/', pycompat.ossep)
2428 2428 if fullpaths:
2429 2429 addfile(f)
2430 2430 continue
2431 2431 s = f.find(pycompat.ossep, speclen)
2432 2432 if s >= 0:
2433 2433 adddir(f[:s])
2434 2434 else:
2435 2435 addfile(f)
2436 2436 return files, dirs
2437 2437
2438 2438 acceptable = b''
2439 2439 if opts['normal']:
2440 2440 acceptable += b'nm'
2441 2441 if opts['added']:
2442 2442 acceptable += b'a'
2443 2443 if opts['removed']:
2444 2444 acceptable += b'r'
2445 2445 cwd = repo.getcwd()
2446 2446 if not specs:
2447 2447 specs = [b'.']
2448 2448
2449 2449 files, dirs = set(), set()
2450 2450 for spec in specs:
2451 2451 f, d = complete(spec, acceptable or b'nmar')
2452 2452 files.update(f)
2453 2453 dirs.update(d)
2454 2454 files.update(dirs)
2455 2455 ui.write(b'\n'.join(repo.pathto(p, cwd) for p in sorted(files)))
2456 2456 ui.write(b'\n')
2457 2457
2458 2458
2459 2459 @command(
2460 2460 b'debugpathcopies',
2461 2461 cmdutil.walkopts,
2462 2462 b'hg debugpathcopies REV1 REV2 [FILE]',
2463 2463 inferrepo=True,
2464 2464 )
2465 2465 def debugpathcopies(ui, repo, rev1, rev2, *pats, **opts):
2466 2466 """show copies between two revisions"""
2467 2467 ctx1 = scmutil.revsingle(repo, rev1)
2468 2468 ctx2 = scmutil.revsingle(repo, rev2)
2469 2469 m = scmutil.match(ctx1, pats, opts)
2470 2470 for dst, src in sorted(copies.pathcopies(ctx1, ctx2, m).items()):
2471 2471 ui.write(b'%s -> %s\n' % (src, dst))
2472 2472
2473 2473
2474 2474 @command(b'debugpeer', [], _(b'PATH'), norepo=True)
2475 2475 def debugpeer(ui, path):
2476 2476 """establish a connection to a peer repository"""
2477 2477 # Always enable peer request logging. Requires --debug to display
2478 2478 # though.
2479 2479 overrides = {
2480 2480 (b'devel', b'debug.peer-request'): True,
2481 2481 }
2482 2482
2483 2483 with ui.configoverride(overrides):
2484 2484 peer = hg.peer(ui, {}, path)
2485 2485
2486 2486 local = peer.local() is not None
2487 2487 canpush = peer.canpush()
2488 2488
2489 2489 ui.write(_(b'url: %s\n') % peer.url())
2490 2490 ui.write(_(b'local: %s\n') % (_(b'yes') if local else _(b'no')))
2491 2491 ui.write(_(b'pushable: %s\n') % (_(b'yes') if canpush else _(b'no')))
2492 2492
2493 2493
2494 2494 @command(
2495 2495 b'debugpickmergetool',
2496 2496 [
2497 2497 (b'r', b'rev', b'', _(b'check for files in this revision'), _(b'REV')),
2498 2498 (b'', b'changedelete', None, _(b'emulate merging change and delete')),
2499 2499 ]
2500 2500 + cmdutil.walkopts
2501 2501 + cmdutil.mergetoolopts,
2502 2502 _(b'[PATTERN]...'),
2503 2503 inferrepo=True,
2504 2504 )
2505 2505 def debugpickmergetool(ui, repo, *pats, **opts):
2506 2506 """examine which merge tool is chosen for specified file
2507 2507
2508 2508 As described in :hg:`help merge-tools`, Mercurial examines
2509 2509 configurations below in this order to decide which merge tool is
2510 2510 chosen for specified file.
2511 2511
2512 2512 1. ``--tool`` option
2513 2513 2. ``HGMERGE`` environment variable
2514 2514 3. configurations in ``merge-patterns`` section
2515 2515 4. configuration of ``ui.merge``
2516 2516 5. configurations in ``merge-tools`` section
2517 2517 6. ``hgmerge`` tool (for historical reason only)
2518 2518 7. default tool for fallback (``:merge`` or ``:prompt``)
2519 2519
2520 2520 This command writes out examination result in the style below::
2521 2521
2522 2522 FILE = MERGETOOL
2523 2523
2524 2524 By default, all files known in the first parent context of the
2525 2525 working directory are examined. Use file patterns and/or -I/-X
2526 2526 options to limit target files. -r/--rev is also useful to examine
2527 2527 files in another context without actual updating to it.
2528 2528
2529 2529 With --debug, this command shows warning messages while matching
2530 2530 against ``merge-patterns`` and so on, too. It is recommended to
2531 2531 use this option with explicit file patterns and/or -I/-X options,
2532 2532 because this option increases amount of output per file according
2533 2533 to configurations in hgrc.
2534 2534
2535 2535 With -v/--verbose, this command shows configurations below at
2536 2536 first (only if specified).
2537 2537
2538 2538 - ``--tool`` option
2539 2539 - ``HGMERGE`` environment variable
2540 2540 - configuration of ``ui.merge``
2541 2541
2542 2542 If merge tool is chosen before matching against
2543 2543 ``merge-patterns``, this command can't show any helpful
2544 2544 information, even with --debug. In such case, information above is
2545 2545 useful to know why a merge tool is chosen.
2546 2546 """
2547 2547 opts = pycompat.byteskwargs(opts)
2548 2548 overrides = {}
2549 2549 if opts[b'tool']:
2550 2550 overrides[(b'ui', b'forcemerge')] = opts[b'tool']
2551 2551 ui.notenoi18n(b'with --tool %r\n' % (pycompat.bytestr(opts[b'tool'])))
2552 2552
2553 2553 with ui.configoverride(overrides, b'debugmergepatterns'):
2554 2554 hgmerge = encoding.environ.get(b"HGMERGE")
2555 2555 if hgmerge is not None:
2556 2556 ui.notenoi18n(b'with HGMERGE=%r\n' % (pycompat.bytestr(hgmerge)))
2557 2557 uimerge = ui.config(b"ui", b"merge")
2558 2558 if uimerge:
2559 2559 ui.notenoi18n(b'with ui.merge=%r\n' % (pycompat.bytestr(uimerge)))
2560 2560
2561 2561 ctx = scmutil.revsingle(repo, opts.get(b'rev'))
2562 2562 m = scmutil.match(ctx, pats, opts)
2563 2563 changedelete = opts[b'changedelete']
2564 2564 for path in ctx.walk(m):
2565 2565 fctx = ctx[path]
2566 2566 try:
2567 2567 if not ui.debugflag:
2568 2568 ui.pushbuffer(error=True)
2569 2569 tool, toolpath = filemerge._picktool(
2570 2570 repo,
2571 2571 ui,
2572 2572 path,
2573 2573 fctx.isbinary(),
2574 2574 b'l' in fctx.flags(),
2575 2575 changedelete,
2576 2576 )
2577 2577 finally:
2578 2578 if not ui.debugflag:
2579 2579 ui.popbuffer()
2580 2580 ui.write(b'%s = %s\n' % (path, tool))
2581 2581
2582 2582
2583 2583 @command(b'debugpushkey', [], _(b'REPO NAMESPACE [KEY OLD NEW]'), norepo=True)
2584 2584 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
2585 2585 '''access the pushkey key/value protocol
2586 2586
2587 2587 With two args, list the keys in the given namespace.
2588 2588
2589 2589 With five args, set a key to new if it currently is set to old.
2590 2590 Reports success or failure.
2591 2591 '''
2592 2592
2593 2593 target = hg.peer(ui, {}, repopath)
2594 2594 if keyinfo:
2595 2595 key, old, new = keyinfo
2596 2596 with target.commandexecutor() as e:
2597 2597 r = e.callcommand(
2598 2598 b'pushkey',
2599 2599 {
2600 2600 b'namespace': namespace,
2601 2601 b'key': key,
2602 2602 b'old': old,
2603 2603 b'new': new,
2604 2604 },
2605 2605 ).result()
2606 2606
2607 2607 ui.status(pycompat.bytestr(r) + b'\n')
2608 2608 return not r
2609 2609 else:
2610 2610 for k, v in sorted(pycompat.iteritems(target.listkeys(namespace))):
2611 2611 ui.write(
2612 2612 b"%s\t%s\n" % (stringutil.escapestr(k), stringutil.escapestr(v))
2613 2613 )
2614 2614
2615 2615
2616 2616 @command(b'debugpvec', [], _(b'A B'))
2617 2617 def debugpvec(ui, repo, a, b=None):
2618 2618 ca = scmutil.revsingle(repo, a)
2619 2619 cb = scmutil.revsingle(repo, b)
2620 2620 pa = pvec.ctxpvec(ca)
2621 2621 pb = pvec.ctxpvec(cb)
2622 2622 if pa == pb:
2623 2623 rel = b"="
2624 2624 elif pa > pb:
2625 2625 rel = b">"
2626 2626 elif pa < pb:
2627 2627 rel = b"<"
2628 2628 elif pa | pb:
2629 2629 rel = b"|"
2630 2630 ui.write(_(b"a: %s\n") % pa)
2631 2631 ui.write(_(b"b: %s\n") % pb)
2632 2632 ui.write(_(b"depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
2633 2633 ui.write(
2634 2634 _(b"delta: %d hdist: %d distance: %d relation: %s\n")
2635 2635 % (
2636 2636 abs(pa._depth - pb._depth),
2637 2637 pvec._hamming(pa._vec, pb._vec),
2638 2638 pa.distance(pb),
2639 2639 rel,
2640 2640 )
2641 2641 )
2642 2642
2643 2643
2644 2644 @command(
2645 2645 b'debugrebuilddirstate|debugrebuildstate',
2646 2646 [
2647 2647 (b'r', b'rev', b'', _(b'revision to rebuild to'), _(b'REV')),
2648 2648 (
2649 2649 b'',
2650 2650 b'minimal',
2651 2651 None,
2652 2652 _(
2653 2653 b'only rebuild files that are inconsistent with '
2654 2654 b'the working copy parent'
2655 2655 ),
2656 2656 ),
2657 2657 ],
2658 2658 _(b'[-r REV]'),
2659 2659 )
2660 2660 def debugrebuilddirstate(ui, repo, rev, **opts):
2661 2661 """rebuild the dirstate as it would look like for the given revision
2662 2662
2663 2663 If no revision is specified the first current parent will be used.
2664 2664
2665 2665 The dirstate will be set to the files of the given revision.
2666 2666 The actual working directory content or existing dirstate
2667 2667 information such as adds or removes is not considered.
2668 2668
2669 2669 ``minimal`` will only rebuild the dirstate status for files that claim to be
2670 2670 tracked but are not in the parent manifest, or that exist in the parent
2671 2671 manifest but are not in the dirstate. It will not change adds, removes, or
2672 2672 modified files that are in the working copy parent.
2673 2673
2674 2674 One use of this command is to make the next :hg:`status` invocation
2675 2675 check the actual file content.
2676 2676 """
2677 2677 ctx = scmutil.revsingle(repo, rev)
2678 2678 with repo.wlock():
2679 2679 dirstate = repo.dirstate
2680 2680 changedfiles = None
2681 2681 # See command doc for what minimal does.
2682 2682 if opts.get('minimal'):
2683 2683 manifestfiles = set(ctx.manifest().keys())
2684 2684 dirstatefiles = set(dirstate)
2685 2685 manifestonly = manifestfiles - dirstatefiles
2686 2686 dsonly = dirstatefiles - manifestfiles
2687 2687 dsnotadded = {f for f in dsonly if dirstate[f] != b'a'}
2688 2688 changedfiles = manifestonly | dsnotadded
2689 2689
2690 2690 dirstate.rebuild(ctx.node(), ctx.manifest(), changedfiles)
2691 2691
2692 2692
2693 2693 @command(b'debugrebuildfncache', [], b'')
2694 2694 def debugrebuildfncache(ui, repo):
2695 2695 """rebuild the fncache file"""
2696 2696 repair.rebuildfncache(ui, repo)
2697 2697
2698 2698
2699 2699 @command(
2700 2700 b'debugrename',
2701 2701 [(b'r', b'rev', b'', _(b'revision to debug'), _(b'REV'))],
2702 2702 _(b'[-r REV] [FILE]...'),
2703 2703 )
2704 2704 def debugrename(ui, repo, *pats, **opts):
2705 2705 """dump rename information"""
2706 2706
2707 2707 opts = pycompat.byteskwargs(opts)
2708 2708 ctx = scmutil.revsingle(repo, opts.get(b'rev'))
2709 2709 m = scmutil.match(ctx, pats, opts)
2710 2710 for abs in ctx.walk(m):
2711 2711 fctx = ctx[abs]
2712 2712 o = fctx.filelog().renamed(fctx.filenode())
2713 2713 rel = repo.pathto(abs)
2714 2714 if o:
2715 2715 ui.write(_(b"%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
2716 2716 else:
2717 2717 ui.write(_(b"%s not renamed\n") % rel)
2718 2718
2719 2719
2720 2720 @command(b'debugrequires|debugrequirements', [], b'')
2721 2721 def debugrequirements(ui, repo):
2722 2722 """ print the current repo requirements """
2723 2723 for r in sorted(repo.requirements):
2724 2724 ui.write(b"%s\n" % r)
2725 2725
2726 2726
2727 2727 @command(
2728 2728 b'debugrevlog',
2729 2729 cmdutil.debugrevlogopts + [(b'd', b'dump', False, _(b'dump index data'))],
2730 2730 _(b'-c|-m|FILE'),
2731 2731 optionalrepo=True,
2732 2732 )
2733 2733 def debugrevlog(ui, repo, file_=None, **opts):
2734 2734 """show data and statistics about a revlog"""
2735 2735 opts = pycompat.byteskwargs(opts)
2736 2736 r = cmdutil.openrevlog(repo, b'debugrevlog', file_, opts)
2737 2737
2738 2738 if opts.get(b"dump"):
2739 2739 numrevs = len(r)
2740 2740 ui.write(
2741 2741 (
2742 2742 b"# rev p1rev p2rev start end deltastart base p1 p2"
2743 2743 b" rawsize totalsize compression heads chainlen\n"
2744 2744 )
2745 2745 )
2746 2746 ts = 0
2747 2747 heads = set()
2748 2748
2749 2749 for rev in pycompat.xrange(numrevs):
2750 2750 dbase = r.deltaparent(rev)
2751 2751 if dbase == -1:
2752 2752 dbase = rev
2753 2753 cbase = r.chainbase(rev)
2754 2754 clen = r.chainlen(rev)
2755 2755 p1, p2 = r.parentrevs(rev)
2756 2756 rs = r.rawsize(rev)
2757 2757 ts = ts + rs
2758 2758 heads -= set(r.parentrevs(rev))
2759 2759 heads.add(rev)
2760 2760 try:
2761 2761 compression = ts / r.end(rev)
2762 2762 except ZeroDivisionError:
2763 2763 compression = 0
2764 2764 ui.write(
2765 2765 b"%5d %5d %5d %5d %5d %10d %4d %4d %4d %7d %9d "
2766 2766 b"%11d %5d %8d\n"
2767 2767 % (
2768 2768 rev,
2769 2769 p1,
2770 2770 p2,
2771 2771 r.start(rev),
2772 2772 r.end(rev),
2773 2773 r.start(dbase),
2774 2774 r.start(cbase),
2775 2775 r.start(p1),
2776 2776 r.start(p2),
2777 2777 rs,
2778 2778 ts,
2779 2779 compression,
2780 2780 len(heads),
2781 2781 clen,
2782 2782 )
2783 2783 )
2784 2784 return 0
2785 2785
2786 2786 v = r.version
2787 2787 format = v & 0xFFFF
2788 2788 flags = []
2789 2789 gdelta = False
2790 2790 if v & revlog.FLAG_INLINE_DATA:
2791 2791 flags.append(b'inline')
2792 2792 if v & revlog.FLAG_GENERALDELTA:
2793 2793 gdelta = True
2794 2794 flags.append(b'generaldelta')
2795 2795 if not flags:
2796 2796 flags = [b'(none)']
2797 2797
2798 2798 ### tracks merge vs single parent
2799 2799 nummerges = 0
2800 2800
2801 2801 ### tracks ways the "delta" are build
2802 2802 # nodelta
2803 2803 numempty = 0
2804 2804 numemptytext = 0
2805 2805 numemptydelta = 0
2806 2806 # full file content
2807 2807 numfull = 0
2808 2808 # intermediate snapshot against a prior snapshot
2809 2809 numsemi = 0
2810 2810 # snapshot count per depth
2811 2811 numsnapdepth = collections.defaultdict(lambda: 0)
2812 2812 # delta against previous revision
2813 2813 numprev = 0
2814 2814 # delta against first or second parent (not prev)
2815 2815 nump1 = 0
2816 2816 nump2 = 0
2817 2817 # delta against neither prev nor parents
2818 2818 numother = 0
2819 2819 # delta against prev that are also first or second parent
2820 2820 # (details of `numprev`)
2821 2821 nump1prev = 0
2822 2822 nump2prev = 0
2823 2823
2824 2824 # data about delta chain of each revs
2825 2825 chainlengths = []
2826 2826 chainbases = []
2827 2827 chainspans = []
2828 2828
2829 2829 # data about each revision
2830 2830 datasize = [None, 0, 0]
2831 2831 fullsize = [None, 0, 0]
2832 2832 semisize = [None, 0, 0]
2833 2833 # snapshot count per depth
2834 2834 snapsizedepth = collections.defaultdict(lambda: [None, 0, 0])
2835 2835 deltasize = [None, 0, 0]
2836 2836 chunktypecounts = {}
2837 2837 chunktypesizes = {}
2838 2838
2839 2839 def addsize(size, l):
2840 2840 if l[0] is None or size < l[0]:
2841 2841 l[0] = size
2842 2842 if size > l[1]:
2843 2843 l[1] = size
2844 2844 l[2] += size
2845 2845
2846 2846 numrevs = len(r)
2847 2847 for rev in pycompat.xrange(numrevs):
2848 2848 p1, p2 = r.parentrevs(rev)
2849 2849 delta = r.deltaparent(rev)
2850 2850 if format > 0:
2851 2851 addsize(r.rawsize(rev), datasize)
2852 2852 if p2 != nullrev:
2853 2853 nummerges += 1
2854 2854 size = r.length(rev)
2855 2855 if delta == nullrev:
2856 2856 chainlengths.append(0)
2857 2857 chainbases.append(r.start(rev))
2858 2858 chainspans.append(size)
2859 2859 if size == 0:
2860 2860 numempty += 1
2861 2861 numemptytext += 1
2862 2862 else:
2863 2863 numfull += 1
2864 2864 numsnapdepth[0] += 1
2865 2865 addsize(size, fullsize)
2866 2866 addsize(size, snapsizedepth[0])
2867 2867 else:
2868 2868 chainlengths.append(chainlengths[delta] + 1)
2869 2869 baseaddr = chainbases[delta]
2870 2870 revaddr = r.start(rev)
2871 2871 chainbases.append(baseaddr)
2872 2872 chainspans.append((revaddr - baseaddr) + size)
2873 2873 if size == 0:
2874 2874 numempty += 1
2875 2875 numemptydelta += 1
2876 2876 elif r.issnapshot(rev):
2877 2877 addsize(size, semisize)
2878 2878 numsemi += 1
2879 2879 depth = r.snapshotdepth(rev)
2880 2880 numsnapdepth[depth] += 1
2881 2881 addsize(size, snapsizedepth[depth])
2882 2882 else:
2883 2883 addsize(size, deltasize)
2884 2884 if delta == rev - 1:
2885 2885 numprev += 1
2886 2886 if delta == p1:
2887 2887 nump1prev += 1
2888 2888 elif delta == p2:
2889 2889 nump2prev += 1
2890 2890 elif delta == p1:
2891 2891 nump1 += 1
2892 2892 elif delta == p2:
2893 2893 nump2 += 1
2894 2894 elif delta != nullrev:
2895 2895 numother += 1
2896 2896
2897 2897 # Obtain data on the raw chunks in the revlog.
2898 2898 if util.safehasattr(r, b'_getsegmentforrevs'):
2899 2899 segment = r._getsegmentforrevs(rev, rev)[1]
2900 2900 else:
2901 2901 segment = r._revlog._getsegmentforrevs(rev, rev)[1]
2902 2902 if segment:
2903 2903 chunktype = bytes(segment[0:1])
2904 2904 else:
2905 2905 chunktype = b'empty'
2906 2906
2907 2907 if chunktype not in chunktypecounts:
2908 2908 chunktypecounts[chunktype] = 0
2909 2909 chunktypesizes[chunktype] = 0
2910 2910
2911 2911 chunktypecounts[chunktype] += 1
2912 2912 chunktypesizes[chunktype] += size
2913 2913
2914 2914 # Adjust size min value for empty cases
2915 2915 for size in (datasize, fullsize, semisize, deltasize):
2916 2916 if size[0] is None:
2917 2917 size[0] = 0
2918 2918
2919 2919 numdeltas = numrevs - numfull - numempty - numsemi
2920 2920 numoprev = numprev - nump1prev - nump2prev
2921 2921 totalrawsize = datasize[2]
2922 2922 datasize[2] /= numrevs
2923 2923 fulltotal = fullsize[2]
2924 2924 if numfull == 0:
2925 2925 fullsize[2] = 0
2926 2926 else:
2927 2927 fullsize[2] /= numfull
2928 2928 semitotal = semisize[2]
2929 2929 snaptotal = {}
2930 2930 if numsemi > 0:
2931 2931 semisize[2] /= numsemi
2932 2932 for depth in snapsizedepth:
2933 2933 snaptotal[depth] = snapsizedepth[depth][2]
2934 2934 snapsizedepth[depth][2] /= numsnapdepth[depth]
2935 2935
2936 2936 deltatotal = deltasize[2]
2937 2937 if numdeltas > 0:
2938 2938 deltasize[2] /= numdeltas
2939 2939 totalsize = fulltotal + semitotal + deltatotal
2940 2940 avgchainlen = sum(chainlengths) / numrevs
2941 2941 maxchainlen = max(chainlengths)
2942 2942 maxchainspan = max(chainspans)
2943 2943 compratio = 1
2944 2944 if totalsize:
2945 2945 compratio = totalrawsize / totalsize
2946 2946
2947 2947 basedfmtstr = b'%%%dd\n'
2948 2948 basepcfmtstr = b'%%%dd %s(%%5.2f%%%%)\n'
2949 2949
2950 2950 def dfmtstr(max):
2951 2951 return basedfmtstr % len(str(max))
2952 2952
2953 2953 def pcfmtstr(max, padding=0):
2954 2954 return basepcfmtstr % (len(str(max)), b' ' * padding)
2955 2955
2956 2956 def pcfmt(value, total):
2957 2957 if total:
2958 2958 return (value, 100 * float(value) / total)
2959 2959 else:
2960 2960 return value, 100.0
2961 2961
2962 2962 ui.writenoi18n(b'format : %d\n' % format)
2963 2963 ui.writenoi18n(b'flags : %s\n' % b', '.join(flags))
2964 2964
2965 2965 ui.write(b'\n')
2966 2966 fmt = pcfmtstr(totalsize)
2967 2967 fmt2 = dfmtstr(totalsize)
2968 2968 ui.writenoi18n(b'revisions : ' + fmt2 % numrevs)
2969 2969 ui.writenoi18n(b' merges : ' + fmt % pcfmt(nummerges, numrevs))
2970 2970 ui.writenoi18n(
2971 2971 b' normal : ' + fmt % pcfmt(numrevs - nummerges, numrevs)
2972 2972 )
2973 2973 ui.writenoi18n(b'revisions : ' + fmt2 % numrevs)
2974 2974 ui.writenoi18n(b' empty : ' + fmt % pcfmt(numempty, numrevs))
2975 2975 ui.writenoi18n(
2976 2976 b' text : '
2977 2977 + fmt % pcfmt(numemptytext, numemptytext + numemptydelta)
2978 2978 )
2979 2979 ui.writenoi18n(
2980 2980 b' delta : '
2981 2981 + fmt % pcfmt(numemptydelta, numemptytext + numemptydelta)
2982 2982 )
2983 2983 ui.writenoi18n(
2984 2984 b' snapshot : ' + fmt % pcfmt(numfull + numsemi, numrevs)
2985 2985 )
2986 2986 for depth in sorted(numsnapdepth):
2987 2987 ui.write(
2988 2988 (b' lvl-%-3d : ' % depth)
2989 2989 + fmt % pcfmt(numsnapdepth[depth], numrevs)
2990 2990 )
2991 2991 ui.writenoi18n(b' deltas : ' + fmt % pcfmt(numdeltas, numrevs))
2992 2992 ui.writenoi18n(b'revision size : ' + fmt2 % totalsize)
2993 2993 ui.writenoi18n(
2994 2994 b' snapshot : ' + fmt % pcfmt(fulltotal + semitotal, totalsize)
2995 2995 )
2996 2996 for depth in sorted(numsnapdepth):
2997 2997 ui.write(
2998 2998 (b' lvl-%-3d : ' % depth)
2999 2999 + fmt % pcfmt(snaptotal[depth], totalsize)
3000 3000 )
3001 3001 ui.writenoi18n(b' deltas : ' + fmt % pcfmt(deltatotal, totalsize))
3002 3002
3003 3003 def fmtchunktype(chunktype):
3004 3004 if chunktype == b'empty':
3005 3005 return b' %s : ' % chunktype
3006 3006 elif chunktype in pycompat.bytestr(string.ascii_letters):
3007 3007 return b' 0x%s (%s) : ' % (hex(chunktype), chunktype)
3008 3008 else:
3009 3009 return b' 0x%s : ' % hex(chunktype)
3010 3010
3011 3011 ui.write(b'\n')
3012 3012 ui.writenoi18n(b'chunks : ' + fmt2 % numrevs)
3013 3013 for chunktype in sorted(chunktypecounts):
3014 3014 ui.write(fmtchunktype(chunktype))
3015 3015 ui.write(fmt % pcfmt(chunktypecounts[chunktype], numrevs))
3016 3016 ui.writenoi18n(b'chunks size : ' + fmt2 % totalsize)
3017 3017 for chunktype in sorted(chunktypecounts):
3018 3018 ui.write(fmtchunktype(chunktype))
3019 3019 ui.write(fmt % pcfmt(chunktypesizes[chunktype], totalsize))
3020 3020
3021 3021 ui.write(b'\n')
3022 3022 fmt = dfmtstr(max(avgchainlen, maxchainlen, maxchainspan, compratio))
3023 3023 ui.writenoi18n(b'avg chain length : ' + fmt % avgchainlen)
3024 3024 ui.writenoi18n(b'max chain length : ' + fmt % maxchainlen)
3025 3025 ui.writenoi18n(b'max chain reach : ' + fmt % maxchainspan)
3026 3026 ui.writenoi18n(b'compression ratio : ' + fmt % compratio)
3027 3027
3028 3028 if format > 0:
3029 3029 ui.write(b'\n')
3030 3030 ui.writenoi18n(
3031 3031 b'uncompressed data size (min/max/avg) : %d / %d / %d\n'
3032 3032 % tuple(datasize)
3033 3033 )
3034 3034 ui.writenoi18n(
3035 3035 b'full revision size (min/max/avg) : %d / %d / %d\n'
3036 3036 % tuple(fullsize)
3037 3037 )
3038 3038 ui.writenoi18n(
3039 3039 b'inter-snapshot size (min/max/avg) : %d / %d / %d\n'
3040 3040 % tuple(semisize)
3041 3041 )
3042 3042 for depth in sorted(snapsizedepth):
3043 3043 if depth == 0:
3044 3044 continue
3045 3045 ui.writenoi18n(
3046 3046 b' level-%-3d (min/max/avg) : %d / %d / %d\n'
3047 3047 % ((depth,) + tuple(snapsizedepth[depth]))
3048 3048 )
3049 3049 ui.writenoi18n(
3050 3050 b'delta size (min/max/avg) : %d / %d / %d\n'
3051 3051 % tuple(deltasize)
3052 3052 )
3053 3053
3054 3054 if numdeltas > 0:
3055 3055 ui.write(b'\n')
3056 3056 fmt = pcfmtstr(numdeltas)
3057 3057 fmt2 = pcfmtstr(numdeltas, 4)
3058 3058 ui.writenoi18n(
3059 3059 b'deltas against prev : ' + fmt % pcfmt(numprev, numdeltas)
3060 3060 )
3061 3061 if numprev > 0:
3062 3062 ui.writenoi18n(
3063 3063 b' where prev = p1 : ' + fmt2 % pcfmt(nump1prev, numprev)
3064 3064 )
3065 3065 ui.writenoi18n(
3066 3066 b' where prev = p2 : ' + fmt2 % pcfmt(nump2prev, numprev)
3067 3067 )
3068 3068 ui.writenoi18n(
3069 3069 b' other : ' + fmt2 % pcfmt(numoprev, numprev)
3070 3070 )
3071 3071 if gdelta:
3072 3072 ui.writenoi18n(
3073 3073 b'deltas against p1 : ' + fmt % pcfmt(nump1, numdeltas)
3074 3074 )
3075 3075 ui.writenoi18n(
3076 3076 b'deltas against p2 : ' + fmt % pcfmt(nump2, numdeltas)
3077 3077 )
3078 3078 ui.writenoi18n(
3079 3079 b'deltas against other : ' + fmt % pcfmt(numother, numdeltas)
3080 3080 )
3081 3081
3082 3082
3083 3083 @command(
3084 3084 b'debugrevlogindex',
3085 3085 cmdutil.debugrevlogopts
3086 3086 + [(b'f', b'format', 0, _(b'revlog format'), _(b'FORMAT'))],
3087 3087 _(b'[-f FORMAT] -c|-m|FILE'),
3088 3088 optionalrepo=True,
3089 3089 )
3090 3090 def debugrevlogindex(ui, repo, file_=None, **opts):
3091 3091 """dump the contents of a revlog index"""
3092 3092 opts = pycompat.byteskwargs(opts)
3093 3093 r = cmdutil.openrevlog(repo, b'debugrevlogindex', file_, opts)
3094 3094 format = opts.get(b'format', 0)
3095 3095 if format not in (0, 1):
3096 3096 raise error.Abort(_(b"unknown format %d") % format)
3097 3097
3098 3098 if ui.debugflag:
3099 3099 shortfn = hex
3100 3100 else:
3101 3101 shortfn = short
3102 3102
3103 3103 # There might not be anything in r, so have a sane default
3104 3104 idlen = 12
3105 3105 for i in r:
3106 3106 idlen = len(shortfn(r.node(i)))
3107 3107 break
3108 3108
3109 3109 if format == 0:
3110 3110 if ui.verbose:
3111 3111 ui.writenoi18n(
3112 3112 b" rev offset length linkrev %s %s p2\n"
3113 3113 % (b"nodeid".ljust(idlen), b"p1".ljust(idlen))
3114 3114 )
3115 3115 else:
3116 3116 ui.writenoi18n(
3117 3117 b" rev linkrev %s %s p2\n"
3118 3118 % (b"nodeid".ljust(idlen), b"p1".ljust(idlen))
3119 3119 )
3120 3120 elif format == 1:
3121 3121 if ui.verbose:
3122 3122 ui.writenoi18n(
3123 3123 (
3124 3124 b" rev flag offset length size link p1"
3125 3125 b" p2 %s\n"
3126 3126 )
3127 3127 % b"nodeid".rjust(idlen)
3128 3128 )
3129 3129 else:
3130 3130 ui.writenoi18n(
3131 3131 b" rev flag size link p1 p2 %s\n"
3132 3132 % b"nodeid".rjust(idlen)
3133 3133 )
3134 3134
3135 3135 for i in r:
3136 3136 node = r.node(i)
3137 3137 if format == 0:
3138 3138 try:
3139 3139 pp = r.parents(node)
3140 3140 except Exception:
3141 3141 pp = [nullid, nullid]
3142 3142 if ui.verbose:
3143 3143 ui.write(
3144 3144 b"% 6d % 9d % 7d % 7d %s %s %s\n"
3145 3145 % (
3146 3146 i,
3147 3147 r.start(i),
3148 3148 r.length(i),
3149 3149 r.linkrev(i),
3150 3150 shortfn(node),
3151 3151 shortfn(pp[0]),
3152 3152 shortfn(pp[1]),
3153 3153 )
3154 3154 )
3155 3155 else:
3156 3156 ui.write(
3157 3157 b"% 6d % 7d %s %s %s\n"
3158 3158 % (
3159 3159 i,
3160 3160 r.linkrev(i),
3161 3161 shortfn(node),
3162 3162 shortfn(pp[0]),
3163 3163 shortfn(pp[1]),
3164 3164 )
3165 3165 )
3166 3166 elif format == 1:
3167 3167 pr = r.parentrevs(i)
3168 3168 if ui.verbose:
3169 3169 ui.write(
3170 3170 b"% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d %s\n"
3171 3171 % (
3172 3172 i,
3173 3173 r.flags(i),
3174 3174 r.start(i),
3175 3175 r.length(i),
3176 3176 r.rawsize(i),
3177 3177 r.linkrev(i),
3178 3178 pr[0],
3179 3179 pr[1],
3180 3180 shortfn(node),
3181 3181 )
3182 3182 )
3183 3183 else:
3184 3184 ui.write(
3185 3185 b"% 6d %04x % 8d % 6d % 6d % 6d %s\n"
3186 3186 % (
3187 3187 i,
3188 3188 r.flags(i),
3189 3189 r.rawsize(i),
3190 3190 r.linkrev(i),
3191 3191 pr[0],
3192 3192 pr[1],
3193 3193 shortfn(node),
3194 3194 )
3195 3195 )
3196 3196
3197 3197
3198 3198 @command(
3199 3199 b'debugrevspec',
3200 3200 [
3201 3201 (
3202 3202 b'',
3203 3203 b'optimize',
3204 3204 None,
3205 3205 _(b'print parsed tree after optimizing (DEPRECATED)'),
3206 3206 ),
3207 3207 (
3208 3208 b'',
3209 3209 b'show-revs',
3210 3210 True,
3211 3211 _(b'print list of result revisions (default)'),
3212 3212 ),
3213 3213 (
3214 3214 b's',
3215 3215 b'show-set',
3216 3216 None,
3217 3217 _(b'print internal representation of result set'),
3218 3218 ),
3219 3219 (
3220 3220 b'p',
3221 3221 b'show-stage',
3222 3222 [],
3223 3223 _(b'print parsed tree at the given stage'),
3224 3224 _(b'NAME'),
3225 3225 ),
3226 3226 (b'', b'no-optimized', False, _(b'evaluate tree without optimization')),
3227 3227 (b'', b'verify-optimized', False, _(b'verify optimized result')),
3228 3228 ],
3229 3229 b'REVSPEC',
3230 3230 )
3231 3231 def debugrevspec(ui, repo, expr, **opts):
3232 3232 """parse and apply a revision specification
3233 3233
3234 3234 Use -p/--show-stage option to print the parsed tree at the given stages.
3235 3235 Use -p all to print tree at every stage.
3236 3236
3237 3237 Use --no-show-revs option with -s or -p to print only the set
3238 3238 representation or the parsed tree respectively.
3239 3239
3240 3240 Use --verify-optimized to compare the optimized result with the unoptimized
3241 3241 one. Returns 1 if the optimized result differs.
3242 3242 """
3243 3243 opts = pycompat.byteskwargs(opts)
3244 3244 aliases = ui.configitems(b'revsetalias')
3245 3245 stages = [
3246 3246 (b'parsed', lambda tree: tree),
3247 3247 (
3248 3248 b'expanded',
3249 3249 lambda tree: revsetlang.expandaliases(tree, aliases, ui.warn),
3250 3250 ),
3251 3251 (b'concatenated', revsetlang.foldconcat),
3252 3252 (b'analyzed', revsetlang.analyze),
3253 3253 (b'optimized', revsetlang.optimize),
3254 3254 ]
3255 3255 if opts[b'no_optimized']:
3256 3256 stages = stages[:-1]
3257 3257 if opts[b'verify_optimized'] and opts[b'no_optimized']:
3258 3258 raise error.Abort(
3259 3259 _(b'cannot use --verify-optimized with --no-optimized')
3260 3260 )
3261 3261 stagenames = {n for n, f in stages}
3262 3262
3263 3263 showalways = set()
3264 3264 showchanged = set()
3265 3265 if ui.verbose and not opts[b'show_stage']:
3266 3266 # show parsed tree by --verbose (deprecated)
3267 3267 showalways.add(b'parsed')
3268 3268 showchanged.update([b'expanded', b'concatenated'])
3269 3269 if opts[b'optimize']:
3270 3270 showalways.add(b'optimized')
3271 3271 if opts[b'show_stage'] and opts[b'optimize']:
3272 3272 raise error.Abort(_(b'cannot use --optimize with --show-stage'))
3273 3273 if opts[b'show_stage'] == [b'all']:
3274 3274 showalways.update(stagenames)
3275 3275 else:
3276 3276 for n in opts[b'show_stage']:
3277 3277 if n not in stagenames:
3278 3278 raise error.Abort(_(b'invalid stage name: %s') % n)
3279 3279 showalways.update(opts[b'show_stage'])
3280 3280
3281 3281 treebystage = {}
3282 3282 printedtree = None
3283 3283 tree = revsetlang.parse(expr, lookup=revset.lookupfn(repo))
3284 3284 for n, f in stages:
3285 3285 treebystage[n] = tree = f(tree)
3286 3286 if n in showalways or (n in showchanged and tree != printedtree):
3287 3287 if opts[b'show_stage'] or n != b'parsed':
3288 3288 ui.write(b"* %s:\n" % n)
3289 3289 ui.write(revsetlang.prettyformat(tree), b"\n")
3290 3290 printedtree = tree
3291 3291
3292 3292 if opts[b'verify_optimized']:
3293 3293 arevs = revset.makematcher(treebystage[b'analyzed'])(repo)
3294 3294 brevs = revset.makematcher(treebystage[b'optimized'])(repo)
3295 3295 if opts[b'show_set'] or (opts[b'show_set'] is None and ui.verbose):
3296 3296 ui.writenoi18n(
3297 3297 b"* analyzed set:\n", stringutil.prettyrepr(arevs), b"\n"
3298 3298 )
3299 3299 ui.writenoi18n(
3300 3300 b"* optimized set:\n", stringutil.prettyrepr(brevs), b"\n"
3301 3301 )
3302 3302 arevs = list(arevs)
3303 3303 brevs = list(brevs)
3304 3304 if arevs == brevs:
3305 3305 return 0
3306 3306 ui.writenoi18n(b'--- analyzed\n', label=b'diff.file_a')
3307 3307 ui.writenoi18n(b'+++ optimized\n', label=b'diff.file_b')
3308 3308 sm = difflib.SequenceMatcher(None, arevs, brevs)
3309 3309 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
3310 3310 if tag in ('delete', 'replace'):
3311 3311 for c in arevs[alo:ahi]:
3312 3312 ui.write(b'-%d\n' % c, label=b'diff.deleted')
3313 3313 if tag in ('insert', 'replace'):
3314 3314 for c in brevs[blo:bhi]:
3315 3315 ui.write(b'+%d\n' % c, label=b'diff.inserted')
3316 3316 if tag == 'equal':
3317 3317 for c in arevs[alo:ahi]:
3318 3318 ui.write(b' %d\n' % c)
3319 3319 return 1
3320 3320
3321 3321 func = revset.makematcher(tree)
3322 3322 revs = func(repo)
3323 3323 if opts[b'show_set'] or (opts[b'show_set'] is None and ui.verbose):
3324 3324 ui.writenoi18n(b"* set:\n", stringutil.prettyrepr(revs), b"\n")
3325 3325 if not opts[b'show_revs']:
3326 3326 return
3327 3327 for c in revs:
3328 3328 ui.write(b"%d\n" % c)
3329 3329
3330 3330
3331 3331 @command(
3332 3332 b'debugserve',
3333 3333 [
3334 3334 (
3335 3335 b'',
3336 3336 b'sshstdio',
3337 3337 False,
3338 3338 _(b'run an SSH server bound to process handles'),
3339 3339 ),
3340 3340 (b'', b'logiofd', b'', _(b'file descriptor to log server I/O to')),
3341 3341 (b'', b'logiofile', b'', _(b'file to log server I/O to')),
3342 3342 ],
3343 3343 b'',
3344 3344 )
3345 3345 def debugserve(ui, repo, **opts):
3346 3346 """run a server with advanced settings
3347 3347
3348 3348 This command is similar to :hg:`serve`. It exists partially as a
3349 3349 workaround to the fact that ``hg serve --stdio`` must have specific
3350 3350 arguments for security reasons.
3351 3351 """
3352 3352 opts = pycompat.byteskwargs(opts)
3353 3353
3354 3354 if not opts[b'sshstdio']:
3355 3355 raise error.Abort(_(b'only --sshstdio is currently supported'))
3356 3356
3357 3357 logfh = None
3358 3358
3359 3359 if opts[b'logiofd'] and opts[b'logiofile']:
3360 3360 raise error.Abort(_(b'cannot use both --logiofd and --logiofile'))
3361 3361
3362 3362 if opts[b'logiofd']:
3363 3363 # Ideally we would be line buffered. But line buffering in binary
3364 3364 # mode isn't supported and emits a warning in Python 3.8+. Disabling
3365 3365 # buffering could have performance impacts. But since this isn't
3366 3366 # performance critical code, it should be fine.
3367 3367 try:
3368 3368 logfh = os.fdopen(int(opts[b'logiofd']), 'ab', 0)
3369 3369 except OSError as e:
3370 3370 if e.errno != errno.ESPIPE:
3371 3371 raise
3372 3372 # can't seek a pipe, so `ab` mode fails on py3
3373 3373 logfh = os.fdopen(int(opts[b'logiofd']), 'wb', 0)
3374 3374 elif opts[b'logiofile']:
3375 3375 logfh = open(opts[b'logiofile'], b'ab', 0)
3376 3376
3377 3377 s = wireprotoserver.sshserver(ui, repo, logfh=logfh)
3378 3378 s.serve_forever()
3379 sys.exit(0)
3379 3380
3380 3381
3381 3382 @command(b'debugsetparents', [], _(b'REV1 [REV2]'))
3382 3383 def debugsetparents(ui, repo, rev1, rev2=None):
3383 3384 """manually set the parents of the current working directory
3384 3385
3385 3386 This is useful for writing repository conversion tools, but should
3386 3387 be used with care. For example, neither the working directory nor the
3387 3388 dirstate is updated, so file status may be incorrect after running this
3388 3389 command.
3389 3390
3390 3391 Returns 0 on success.
3391 3392 """
3392 3393
3393 3394 node1 = scmutil.revsingle(repo, rev1).node()
3394 3395 node2 = scmutil.revsingle(repo, rev2, b'null').node()
3395 3396
3396 3397 with repo.wlock():
3397 3398 repo.setparents(node1, node2)
3398 3399
3399 3400
3400 3401 @command(b'debugsidedata', cmdutil.debugrevlogopts, _(b'-c|-m|FILE REV'))
3401 3402 def debugsidedata(ui, repo, file_, rev=None, **opts):
3402 3403 """dump the side data for a cl/manifest/file revision
3403 3404
3404 3405 Use --verbose to dump the sidedata content."""
3405 3406 opts = pycompat.byteskwargs(opts)
3406 3407 if opts.get(b'changelog') or opts.get(b'manifest') or opts.get(b'dir'):
3407 3408 if rev is not None:
3408 3409 raise error.CommandError(b'debugdata', _(b'invalid arguments'))
3409 3410 file_, rev = None, file_
3410 3411 elif rev is None:
3411 3412 raise error.CommandError(b'debugdata', _(b'invalid arguments'))
3412 3413 r = cmdutil.openstorage(repo, b'debugdata', file_, opts)
3413 3414 r = getattr(r, '_revlog', r)
3414 3415 try:
3415 3416 sidedata = r.sidedata(r.lookup(rev))
3416 3417 except KeyError:
3417 3418 raise error.Abort(_(b'invalid revision identifier %s') % rev)
3418 3419 if sidedata:
3419 3420 sidedata = list(sidedata.items())
3420 3421 sidedata.sort()
3421 3422 ui.writenoi18n(b'%d sidedata entries\n' % len(sidedata))
3422 3423 for key, value in sidedata:
3423 3424 ui.writenoi18n(b' entry-%04o size %d\n' % (key, len(value)))
3424 3425 if ui.verbose:
3425 3426 ui.writenoi18n(b' %s\n' % stringutil.pprint(value))
3426 3427
3427 3428
3428 3429 @command(b'debugssl', [], b'[SOURCE]', optionalrepo=True)
3429 3430 def debugssl(ui, repo, source=None, **opts):
3430 3431 '''test a secure connection to a server
3431 3432
3432 3433 This builds the certificate chain for the server on Windows, installing the
3433 3434 missing intermediates and trusted root via Windows Update if necessary. It
3434 3435 does nothing on other platforms.
3435 3436
3436 3437 If SOURCE is omitted, the 'default' path will be used. If a URL is given,
3437 3438 that server is used. See :hg:`help urls` for more information.
3438 3439
3439 3440 If the update succeeds, retry the original operation. Otherwise, the cause
3440 3441 of the SSL error is likely another issue.
3441 3442 '''
3442 3443 if not pycompat.iswindows:
3443 3444 raise error.Abort(
3444 3445 _(b'certificate chain building is only possible on Windows')
3445 3446 )
3446 3447
3447 3448 if not source:
3448 3449 if not repo:
3449 3450 raise error.Abort(
3450 3451 _(
3451 3452 b"there is no Mercurial repository here, and no "
3452 3453 b"server specified"
3453 3454 )
3454 3455 )
3455 3456 source = b"default"
3456 3457
3457 3458 source, branches = hg.parseurl(ui.expandpath(source))
3458 3459 url = util.url(source)
3459 3460
3460 3461 defaultport = {b'https': 443, b'ssh': 22}
3461 3462 if url.scheme in defaultport:
3462 3463 try:
3463 3464 addr = (url.host, int(url.port or defaultport[url.scheme]))
3464 3465 except ValueError:
3465 3466 raise error.Abort(_(b"malformed port number in URL"))
3466 3467 else:
3467 3468 raise error.Abort(_(b"only https and ssh connections are supported"))
3468 3469
3469 3470 from . import win32
3470 3471
3471 3472 s = ssl.wrap_socket(
3472 3473 socket.socket(),
3473 3474 ssl_version=ssl.PROTOCOL_TLS,
3474 3475 cert_reqs=ssl.CERT_NONE,
3475 3476 ca_certs=None,
3476 3477 )
3477 3478
3478 3479 try:
3479 3480 s.connect(addr)
3480 3481 cert = s.getpeercert(True)
3481 3482
3482 3483 ui.status(_(b'checking the certificate chain for %s\n') % url.host)
3483 3484
3484 3485 complete = win32.checkcertificatechain(cert, build=False)
3485 3486
3486 3487 if not complete:
3487 3488 ui.status(_(b'certificate chain is incomplete, updating... '))
3488 3489
3489 3490 if not win32.checkcertificatechain(cert):
3490 3491 ui.status(_(b'failed.\n'))
3491 3492 else:
3492 3493 ui.status(_(b'done.\n'))
3493 3494 else:
3494 3495 ui.status(_(b'full certificate chain is available\n'))
3495 3496 finally:
3496 3497 s.close()
3497 3498
3498 3499
3499 3500 @command(
3500 3501 b"debugbackupbundle",
3501 3502 [
3502 3503 (
3503 3504 b"",
3504 3505 b"recover",
3505 3506 b"",
3506 3507 b"brings the specified changeset back into the repository",
3507 3508 )
3508 3509 ]
3509 3510 + cmdutil.logopts,
3510 3511 _(b"hg debugbackupbundle [--recover HASH]"),
3511 3512 )
3512 3513 def debugbackupbundle(ui, repo, *pats, **opts):
3513 3514 """lists the changesets available in backup bundles
3514 3515
3515 3516 Without any arguments, this command prints a list of the changesets in each
3516 3517 backup bundle.
3517 3518
3518 3519 --recover takes a changeset hash and unbundles the first bundle that
3519 3520 contains that hash, which puts that changeset back in your repository.
3520 3521
3521 3522 --verbose will print the entire commit message and the bundle path for that
3522 3523 backup.
3523 3524 """
3524 3525 backups = list(
3525 3526 filter(
3526 3527 os.path.isfile, glob.glob(repo.vfs.join(b"strip-backup") + b"/*.hg")
3527 3528 )
3528 3529 )
3529 3530 backups.sort(key=lambda x: os.path.getmtime(x), reverse=True)
3530 3531
3531 3532 opts = pycompat.byteskwargs(opts)
3532 3533 opts[b"bundle"] = b""
3533 3534 opts[b"force"] = None
3534 3535 limit = logcmdutil.getlimit(opts)
3535 3536
3536 3537 def display(other, chlist, displayer):
3537 3538 if opts.get(b"newest_first"):
3538 3539 chlist.reverse()
3539 3540 count = 0
3540 3541 for n in chlist:
3541 3542 if limit is not None and count >= limit:
3542 3543 break
3543 3544 parents = [True for p in other.changelog.parents(n) if p != nullid]
3544 3545 if opts.get(b"no_merges") and len(parents) == 2:
3545 3546 continue
3546 3547 count += 1
3547 3548 displayer.show(other[n])
3548 3549
3549 3550 recovernode = opts.get(b"recover")
3550 3551 if recovernode:
3551 3552 if scmutil.isrevsymbol(repo, recovernode):
3552 3553 ui.warn(_(b"%s already exists in the repo\n") % recovernode)
3553 3554 return
3554 3555 elif backups:
3555 3556 msg = _(
3556 3557 b"Recover changesets using: hg debugbackupbundle --recover "
3557 3558 b"<changeset hash>\n\nAvailable backup changesets:"
3558 3559 )
3559 3560 ui.status(msg, label=b"status.removed")
3560 3561 else:
3561 3562 ui.status(_(b"no backup changesets found\n"))
3562 3563 return
3563 3564
3564 3565 for backup in backups:
3565 3566 # Much of this is copied from the hg incoming logic
3566 3567 source = ui.expandpath(os.path.relpath(backup, encoding.getcwd()))
3567 3568 source, branches = hg.parseurl(source, opts.get(b"branch"))
3568 3569 try:
3569 3570 other = hg.peer(repo, opts, source)
3570 3571 except error.LookupError as ex:
3571 3572 msg = _(b"\nwarning: unable to open bundle %s") % source
3572 3573 hint = _(b"\n(missing parent rev %s)\n") % short(ex.name)
3573 3574 ui.warn(msg, hint=hint)
3574 3575 continue
3575 3576 revs, checkout = hg.addbranchrevs(
3576 3577 repo, other, branches, opts.get(b"rev")
3577 3578 )
3578 3579
3579 3580 if revs:
3580 3581 revs = [other.lookup(rev) for rev in revs]
3581 3582
3582 3583 quiet = ui.quiet
3583 3584 try:
3584 3585 ui.quiet = True
3585 3586 other, chlist, cleanupfn = bundlerepo.getremotechanges(
3586 3587 ui, repo, other, revs, opts[b"bundle"], opts[b"force"]
3587 3588 )
3588 3589 except error.LookupError:
3589 3590 continue
3590 3591 finally:
3591 3592 ui.quiet = quiet
3592 3593
3593 3594 try:
3594 3595 if not chlist:
3595 3596 continue
3596 3597 if recovernode:
3597 3598 with repo.lock(), repo.transaction(b"unbundle") as tr:
3598 3599 if scmutil.isrevsymbol(other, recovernode):
3599 3600 ui.status(_(b"Unbundling %s\n") % (recovernode))
3600 3601 f = hg.openpath(ui, source)
3601 3602 gen = exchange.readbundle(ui, f, source)
3602 3603 if isinstance(gen, bundle2.unbundle20):
3603 3604 bundle2.applybundle(
3604 3605 repo,
3605 3606 gen,
3606 3607 tr,
3607 3608 source=b"unbundle",
3608 3609 url=b"bundle:" + source,
3609 3610 )
3610 3611 else:
3611 3612 gen.apply(repo, b"unbundle", b"bundle:" + source)
3612 3613 break
3613 3614 else:
3614 3615 backupdate = encoding.strtolocal(
3615 3616 time.strftime(
3616 3617 "%a %H:%M, %Y-%m-%d",
3617 3618 time.localtime(os.path.getmtime(source)),
3618 3619 )
3619 3620 )
3620 3621 ui.status(b"\n%s\n" % (backupdate.ljust(50)))
3621 3622 if ui.verbose:
3622 3623 ui.status(b"%s%s\n" % (b"bundle:".ljust(13), source))
3623 3624 else:
3624 3625 opts[
3625 3626 b"template"
3626 3627 ] = b"{label('status.modified', node|short)} {desc|firstline}\n"
3627 3628 displayer = logcmdutil.changesetdisplayer(
3628 3629 ui, other, opts, False
3629 3630 )
3630 3631 display(other, chlist, displayer)
3631 3632 displayer.close()
3632 3633 finally:
3633 3634 cleanupfn()
3634 3635
3635 3636
3636 3637 @command(
3637 3638 b'debugsub',
3638 3639 [(b'r', b'rev', b'', _(b'revision to check'), _(b'REV'))],
3639 3640 _(b'[-r REV] [REV]'),
3640 3641 )
3641 3642 def debugsub(ui, repo, rev=None):
3642 3643 ctx = scmutil.revsingle(repo, rev, None)
3643 3644 for k, v in sorted(ctx.substate.items()):
3644 3645 ui.writenoi18n(b'path %s\n' % k)
3645 3646 ui.writenoi18n(b' source %s\n' % v[0])
3646 3647 ui.writenoi18n(b' revision %s\n' % v[1])
3647 3648
3648 3649
3649 3650 @command(
3650 3651 b'debugsuccessorssets',
3651 3652 [(b'', b'closest', False, _(b'return closest successors sets only'))],
3652 3653 _(b'[REV]'),
3653 3654 )
3654 3655 def debugsuccessorssets(ui, repo, *revs, **opts):
3655 3656 """show set of successors for revision
3656 3657
3657 3658 A successors set of changeset A is a consistent group of revisions that
3658 3659 succeed A. It contains non-obsolete changesets only unless closests
3659 3660 successors set is set.
3660 3661
3661 3662 In most cases a changeset A has a single successors set containing a single
3662 3663 successor (changeset A replaced by A').
3663 3664
3664 3665 A changeset that is made obsolete with no successors are called "pruned".
3665 3666 Such changesets have no successors sets at all.
3666 3667
3667 3668 A changeset that has been "split" will have a successors set containing
3668 3669 more than one successor.
3669 3670
3670 3671 A changeset that has been rewritten in multiple different ways is called
3671 3672 "divergent". Such changesets have multiple successor sets (each of which
3672 3673 may also be split, i.e. have multiple successors).
3673 3674
3674 3675 Results are displayed as follows::
3675 3676
3676 3677 <rev1>
3677 3678 <successors-1A>
3678 3679 <rev2>
3679 3680 <successors-2A>
3680 3681 <successors-2B1> <successors-2B2> <successors-2B3>
3681 3682
3682 3683 Here rev2 has two possible (i.e. divergent) successors sets. The first
3683 3684 holds one element, whereas the second holds three (i.e. the changeset has
3684 3685 been split).
3685 3686 """
3686 3687 # passed to successorssets caching computation from one call to another
3687 3688 cache = {}
3688 3689 ctx2str = bytes
3689 3690 node2str = short
3690 3691 for rev in scmutil.revrange(repo, revs):
3691 3692 ctx = repo[rev]
3692 3693 ui.write(b'%s\n' % ctx2str(ctx))
3693 3694 for succsset in obsutil.successorssets(
3694 3695 repo, ctx.node(), closest=opts['closest'], cache=cache
3695 3696 ):
3696 3697 if succsset:
3697 3698 ui.write(b' ')
3698 3699 ui.write(node2str(succsset[0]))
3699 3700 for node in succsset[1:]:
3700 3701 ui.write(b' ')
3701 3702 ui.write(node2str(node))
3702 3703 ui.write(b'\n')
3703 3704
3704 3705
3705 3706 @command(b'debugtagscache', [])
3706 3707 def debugtagscache(ui, repo):
3707 3708 """display the contents of .hg/cache/hgtagsfnodes1"""
3708 3709 cache = tagsmod.hgtagsfnodescache(repo.unfiltered())
3709 3710 for r in repo:
3710 3711 node = repo[r].node()
3711 3712 tagsnode = cache.getfnode(node, computemissing=False)
3712 3713 tagsnodedisplay = hex(tagsnode) if tagsnode else b'missing/invalid'
3713 3714 ui.write(b'%d %s %s\n' % (r, hex(node), tagsnodedisplay))
3714 3715
3715 3716
3716 3717 @command(
3717 3718 b'debugtemplate',
3718 3719 [
3719 3720 (b'r', b'rev', [], _(b'apply template on changesets'), _(b'REV')),
3720 3721 (b'D', b'define', [], _(b'define template keyword'), _(b'KEY=VALUE')),
3721 3722 ],
3722 3723 _(b'[-r REV]... [-D KEY=VALUE]... TEMPLATE'),
3723 3724 optionalrepo=True,
3724 3725 )
3725 3726 def debugtemplate(ui, repo, tmpl, **opts):
3726 3727 """parse and apply a template
3727 3728
3728 3729 If -r/--rev is given, the template is processed as a log template and
3729 3730 applied to the given changesets. Otherwise, it is processed as a generic
3730 3731 template.
3731 3732
3732 3733 Use --verbose to print the parsed tree.
3733 3734 """
3734 3735 revs = None
3735 3736 if opts['rev']:
3736 3737 if repo is None:
3737 3738 raise error.RepoError(
3738 3739 _(b'there is no Mercurial repository here (.hg not found)')
3739 3740 )
3740 3741 revs = scmutil.revrange(repo, opts['rev'])
3741 3742
3742 3743 props = {}
3743 3744 for d in opts['define']:
3744 3745 try:
3745 3746 k, v = (e.strip() for e in d.split(b'=', 1))
3746 3747 if not k or k == b'ui':
3747 3748 raise ValueError
3748 3749 props[k] = v
3749 3750 except ValueError:
3750 3751 raise error.Abort(_(b'malformed keyword definition: %s') % d)
3751 3752
3752 3753 if ui.verbose:
3753 3754 aliases = ui.configitems(b'templatealias')
3754 3755 tree = templater.parse(tmpl)
3755 3756 ui.note(templater.prettyformat(tree), b'\n')
3756 3757 newtree = templater.expandaliases(tree, aliases)
3757 3758 if newtree != tree:
3758 3759 ui.notenoi18n(
3759 3760 b"* expanded:\n", templater.prettyformat(newtree), b'\n'
3760 3761 )
3761 3762
3762 3763 if revs is None:
3763 3764 tres = formatter.templateresources(ui, repo)
3764 3765 t = formatter.maketemplater(ui, tmpl, resources=tres)
3765 3766 if ui.verbose:
3766 3767 kwds, funcs = t.symbolsuseddefault()
3767 3768 ui.writenoi18n(b"* keywords: %s\n" % b', '.join(sorted(kwds)))
3768 3769 ui.writenoi18n(b"* functions: %s\n" % b', '.join(sorted(funcs)))
3769 3770 ui.write(t.renderdefault(props))
3770 3771 else:
3771 3772 displayer = logcmdutil.maketemplater(ui, repo, tmpl)
3772 3773 if ui.verbose:
3773 3774 kwds, funcs = displayer.t.symbolsuseddefault()
3774 3775 ui.writenoi18n(b"* keywords: %s\n" % b', '.join(sorted(kwds)))
3775 3776 ui.writenoi18n(b"* functions: %s\n" % b', '.join(sorted(funcs)))
3776 3777 for r in revs:
3777 3778 displayer.show(repo[r], **pycompat.strkwargs(props))
3778 3779 displayer.close()
3779 3780
3780 3781
3781 3782 @command(
3782 3783 b'debuguigetpass',
3783 3784 [(b'p', b'prompt', b'', _(b'prompt text'), _(b'TEXT')),],
3784 3785 _(b'[-p TEXT]'),
3785 3786 norepo=True,
3786 3787 )
3787 3788 def debuguigetpass(ui, prompt=b''):
3788 3789 """show prompt to type password"""
3789 3790 r = ui.getpass(prompt)
3790 3791 ui.writenoi18n(b'response: %s\n' % r)
3791 3792
3792 3793
3793 3794 @command(
3794 3795 b'debuguiprompt',
3795 3796 [(b'p', b'prompt', b'', _(b'prompt text'), _(b'TEXT')),],
3796 3797 _(b'[-p TEXT]'),
3797 3798 norepo=True,
3798 3799 )
3799 3800 def debuguiprompt(ui, prompt=b''):
3800 3801 """show plain prompt"""
3801 3802 r = ui.prompt(prompt)
3802 3803 ui.writenoi18n(b'response: %s\n' % r)
3803 3804
3804 3805
3805 3806 @command(b'debugupdatecaches', [])
3806 3807 def debugupdatecaches(ui, repo, *pats, **opts):
3807 3808 """warm all known caches in the repository"""
3808 3809 with repo.wlock(), repo.lock():
3809 3810 repo.updatecaches(full=True)
3810 3811
3811 3812
3812 3813 @command(
3813 3814 b'debugupgraderepo',
3814 3815 [
3815 3816 (
3816 3817 b'o',
3817 3818 b'optimize',
3818 3819 [],
3819 3820 _(b'extra optimization to perform'),
3820 3821 _(b'NAME'),
3821 3822 ),
3822 3823 (b'', b'run', False, _(b'performs an upgrade')),
3823 3824 (b'', b'backup', True, _(b'keep the old repository content around')),
3824 3825 (b'', b'changelog', None, _(b'select the changelog for upgrade')),
3825 3826 (b'', b'manifest', None, _(b'select the manifest for upgrade')),
3826 3827 ],
3827 3828 )
3828 3829 def debugupgraderepo(ui, repo, run=False, optimize=None, backup=True, **opts):
3829 3830 """upgrade a repository to use different features
3830 3831
3831 3832 If no arguments are specified, the repository is evaluated for upgrade
3832 3833 and a list of problems and potential optimizations is printed.
3833 3834
3834 3835 With ``--run``, a repository upgrade is performed. Behavior of the upgrade
3835 3836 can be influenced via additional arguments. More details will be provided
3836 3837 by the command output when run without ``--run``.
3837 3838
3838 3839 During the upgrade, the repository will be locked and no writes will be
3839 3840 allowed.
3840 3841
3841 3842 At the end of the upgrade, the repository may not be readable while new
3842 3843 repository data is swapped in. This window will be as long as it takes to
3843 3844 rename some directories inside the ``.hg`` directory. On most machines, this
3844 3845 should complete almost instantaneously and the chances of a consumer being
3845 3846 unable to access the repository should be low.
3846 3847
3847 3848 By default, all revlog will be upgraded. You can restrict this using flag
3848 3849 such as `--manifest`:
3849 3850
3850 3851 * `--manifest`: only optimize the manifest
3851 3852 * `--no-manifest`: optimize all revlog but the manifest
3852 3853 * `--changelog`: optimize the changelog only
3853 3854 * `--no-changelog --no-manifest`: optimize filelogs only
3854 3855 """
3855 3856 return upgrade.upgraderepo(
3856 3857 ui, repo, run=run, optimize=optimize, backup=backup, **opts
3857 3858 )
3858 3859
3859 3860
3860 3861 @command(
3861 3862 b'debugwalk', cmdutil.walkopts, _(b'[OPTION]... [FILE]...'), inferrepo=True
3862 3863 )
3863 3864 def debugwalk(ui, repo, *pats, **opts):
3864 3865 """show how files match on given patterns"""
3865 3866 opts = pycompat.byteskwargs(opts)
3866 3867 m = scmutil.match(repo[None], pats, opts)
3867 3868 if ui.verbose:
3868 3869 ui.writenoi18n(b'* matcher:\n', stringutil.prettyrepr(m), b'\n')
3869 3870 items = list(repo[None].walk(m))
3870 3871 if not items:
3871 3872 return
3872 3873 f = lambda fn: fn
3873 3874 if ui.configbool(b'ui', b'slash') and pycompat.ossep != b'/':
3874 3875 f = lambda fn: util.normpath(fn)
3875 3876 fmt = b'f %%-%ds %%-%ds %%s' % (
3876 3877 max([len(abs) for abs in items]),
3877 3878 max([len(repo.pathto(abs)) for abs in items]),
3878 3879 )
3879 3880 for abs in items:
3880 3881 line = fmt % (
3881 3882 abs,
3882 3883 f(repo.pathto(abs)),
3883 3884 m.exact(abs) and b'exact' or b'',
3884 3885 )
3885 3886 ui.write(b"%s\n" % line.rstrip())
3886 3887
3887 3888
3888 3889 @command(b'debugwhyunstable', [], _(b'REV'))
3889 3890 def debugwhyunstable(ui, repo, rev):
3890 3891 """explain instabilities of a changeset"""
3891 3892 for entry in obsutil.whyunstable(repo, scmutil.revsingle(repo, rev)):
3892 3893 dnodes = b''
3893 3894 if entry.get(b'divergentnodes'):
3894 3895 dnodes = (
3895 3896 b' '.join(
3896 3897 b'%s (%s)' % (ctx.hex(), ctx.phasestr())
3897 3898 for ctx in entry[b'divergentnodes']
3898 3899 )
3899 3900 + b' '
3900 3901 )
3901 3902 ui.write(
3902 3903 b'%s: %s%s %s\n'
3903 3904 % (entry[b'instability'], dnodes, entry[b'reason'], entry[b'node'])
3904 3905 )
3905 3906
3906 3907
3907 3908 @command(
3908 3909 b'debugwireargs',
3909 3910 [
3910 3911 (b'', b'three', b'', b'three'),
3911 3912 (b'', b'four', b'', b'four'),
3912 3913 (b'', b'five', b'', b'five'),
3913 3914 ]
3914 3915 + cmdutil.remoteopts,
3915 3916 _(b'REPO [OPTIONS]... [ONE [TWO]]'),
3916 3917 norepo=True,
3917 3918 )
3918 3919 def debugwireargs(ui, repopath, *vals, **opts):
3919 3920 opts = pycompat.byteskwargs(opts)
3920 3921 repo = hg.peer(ui, opts, repopath)
3921 3922 for opt in cmdutil.remoteopts:
3922 3923 del opts[opt[1]]
3923 3924 args = {}
3924 3925 for k, v in pycompat.iteritems(opts):
3925 3926 if v:
3926 3927 args[k] = v
3927 3928 args = pycompat.strkwargs(args)
3928 3929 # run twice to check that we don't mess up the stream for the next command
3929 3930 res1 = repo.debugwireargs(*vals, **args)
3930 3931 res2 = repo.debugwireargs(*vals, **args)
3931 3932 ui.write(b"%s\n" % res1)
3932 3933 if res1 != res2:
3933 3934 ui.warn(b"%s\n" % res2)
3934 3935
3935 3936
3936 3937 def _parsewirelangblocks(fh):
3937 3938 activeaction = None
3938 3939 blocklines = []
3939 3940 lastindent = 0
3940 3941
3941 3942 for line in fh:
3942 3943 line = line.rstrip()
3943 3944 if not line:
3944 3945 continue
3945 3946
3946 3947 if line.startswith(b'#'):
3947 3948 continue
3948 3949
3949 3950 if not line.startswith(b' '):
3950 3951 # New block. Flush previous one.
3951 3952 if activeaction:
3952 3953 yield activeaction, blocklines
3953 3954
3954 3955 activeaction = line
3955 3956 blocklines = []
3956 3957 lastindent = 0
3957 3958 continue
3958 3959
3959 3960 # Else we start with an indent.
3960 3961
3961 3962 if not activeaction:
3962 3963 raise error.Abort(_(b'indented line outside of block'))
3963 3964
3964 3965 indent = len(line) - len(line.lstrip())
3965 3966
3966 3967 # If this line is indented more than the last line, concatenate it.
3967 3968 if indent > lastindent and blocklines:
3968 3969 blocklines[-1] += line.lstrip()
3969 3970 else:
3970 3971 blocklines.append(line)
3971 3972 lastindent = indent
3972 3973
3973 3974 # Flush last block.
3974 3975 if activeaction:
3975 3976 yield activeaction, blocklines
3976 3977
3977 3978
3978 3979 @command(
3979 3980 b'debugwireproto',
3980 3981 [
3981 3982 (b'', b'localssh', False, _(b'start an SSH server for this repo')),
3982 3983 (b'', b'peer', b'', _(b'construct a specific version of the peer')),
3983 3984 (
3984 3985 b'',
3985 3986 b'noreadstderr',
3986 3987 False,
3987 3988 _(b'do not read from stderr of the remote'),
3988 3989 ),
3989 3990 (
3990 3991 b'',
3991 3992 b'nologhandshake',
3992 3993 False,
3993 3994 _(b'do not log I/O related to the peer handshake'),
3994 3995 ),
3995 3996 ]
3996 3997 + cmdutil.remoteopts,
3997 3998 _(b'[PATH]'),
3998 3999 optionalrepo=True,
3999 4000 )
4000 4001 def debugwireproto(ui, repo, path=None, **opts):
4001 4002 """send wire protocol commands to a server
4002 4003
4003 4004 This command can be used to issue wire protocol commands to remote
4004 4005 peers and to debug the raw data being exchanged.
4005 4006
4006 4007 ``--localssh`` will start an SSH server against the current repository
4007 4008 and connect to that. By default, the connection will perform a handshake
4008 4009 and establish an appropriate peer instance.
4009 4010
4010 4011 ``--peer`` can be used to bypass the handshake protocol and construct a
4011 4012 peer instance using the specified class type. Valid values are ``raw``,
4012 4013 ``http2``, ``ssh1``, and ``ssh2``. ``raw`` instances only allow sending
4013 4014 raw data payloads and don't support higher-level command actions.
4014 4015
4015 4016 ``--noreadstderr`` can be used to disable automatic reading from stderr
4016 4017 of the peer (for SSH connections only). Disabling automatic reading of
4017 4018 stderr is useful for making output more deterministic.
4018 4019
4019 4020 Commands are issued via a mini language which is specified via stdin.
4020 4021 The language consists of individual actions to perform. An action is
4021 4022 defined by a block. A block is defined as a line with no leading
4022 4023 space followed by 0 or more lines with leading space. Blocks are
4023 4024 effectively a high-level command with additional metadata.
4024 4025
4025 4026 Lines beginning with ``#`` are ignored.
4026 4027
4027 4028 The following sections denote available actions.
4028 4029
4029 4030 raw
4030 4031 ---
4031 4032
4032 4033 Send raw data to the server.
4033 4034
4034 4035 The block payload contains the raw data to send as one atomic send
4035 4036 operation. The data may not actually be delivered in a single system
4036 4037 call: it depends on the abilities of the transport being used.
4037 4038
4038 4039 Each line in the block is de-indented and concatenated. Then, that
4039 4040 value is evaluated as a Python b'' literal. This allows the use of
4040 4041 backslash escaping, etc.
4041 4042
4042 4043 raw+
4043 4044 ----
4044 4045
4045 4046 Behaves like ``raw`` except flushes output afterwards.
4046 4047
4047 4048 command <X>
4048 4049 -----------
4049 4050
4050 4051 Send a request to run a named command, whose name follows the ``command``
4051 4052 string.
4052 4053
4053 4054 Arguments to the command are defined as lines in this block. The format of
4054 4055 each line is ``<key> <value>``. e.g.::
4055 4056
4056 4057 command listkeys
4057 4058 namespace bookmarks
4058 4059
4059 4060 If the value begins with ``eval:``, it will be interpreted as a Python
4060 4061 literal expression. Otherwise values are interpreted as Python b'' literals.
4061 4062 This allows sending complex types and encoding special byte sequences via
4062 4063 backslash escaping.
4063 4064
4064 4065 The following arguments have special meaning:
4065 4066
4066 4067 ``PUSHFILE``
4067 4068 When defined, the *push* mechanism of the peer will be used instead
4068 4069 of the static request-response mechanism and the content of the
4069 4070 file specified in the value of this argument will be sent as the
4070 4071 command payload.
4071 4072
4072 4073 This can be used to submit a local bundle file to the remote.
4073 4074
4074 4075 batchbegin
4075 4076 ----------
4076 4077
4077 4078 Instruct the peer to begin a batched send.
4078 4079
4079 4080 All ``command`` blocks are queued for execution until the next
4080 4081 ``batchsubmit`` block.
4081 4082
4082 4083 batchsubmit
4083 4084 -----------
4084 4085
4085 4086 Submit previously queued ``command`` blocks as a batch request.
4086 4087
4087 4088 This action MUST be paired with a ``batchbegin`` action.
4088 4089
4089 4090 httprequest <method> <path>
4090 4091 ---------------------------
4091 4092
4092 4093 (HTTP peer only)
4093 4094
4094 4095 Send an HTTP request to the peer.
4095 4096
4096 4097 The HTTP request line follows the ``httprequest`` action. e.g. ``GET /foo``.
4097 4098
4098 4099 Arguments of the form ``<key>: <value>`` are interpreted as HTTP request
4099 4100 headers to add to the request. e.g. ``Accept: foo``.
4100 4101
4101 4102 The following arguments are special:
4102 4103
4103 4104 ``BODYFILE``
4104 4105 The content of the file defined as the value to this argument will be
4105 4106 transferred verbatim as the HTTP request body.
4106 4107
4107 4108 ``frame <type> <flags> <payload>``
4108 4109 Send a unified protocol frame as part of the request body.
4109 4110
4110 4111 All frames will be collected and sent as the body to the HTTP
4111 4112 request.
4112 4113
4113 4114 close
4114 4115 -----
4115 4116
4116 4117 Close the connection to the server.
4117 4118
4118 4119 flush
4119 4120 -----
4120 4121
4121 4122 Flush data written to the server.
4122 4123
4123 4124 readavailable
4124 4125 -------------
4125 4126
4126 4127 Close the write end of the connection and read all available data from
4127 4128 the server.
4128 4129
4129 4130 If the connection to the server encompasses multiple pipes, we poll both
4130 4131 pipes and read available data.
4131 4132
4132 4133 readline
4133 4134 --------
4134 4135
4135 4136 Read a line of output from the server. If there are multiple output
4136 4137 pipes, reads only the main pipe.
4137 4138
4138 4139 ereadline
4139 4140 ---------
4140 4141
4141 4142 Like ``readline``, but read from the stderr pipe, if available.
4142 4143
4143 4144 read <X>
4144 4145 --------
4145 4146
4146 4147 ``read()`` N bytes from the server's main output pipe.
4147 4148
4148 4149 eread <X>
4149 4150 ---------
4150 4151
4151 4152 ``read()`` N bytes from the server's stderr pipe, if available.
4152 4153
4153 4154 Specifying Unified Frame-Based Protocol Frames
4154 4155 ----------------------------------------------
4155 4156
4156 4157 It is possible to emit a *Unified Frame-Based Protocol* by using special
4157 4158 syntax.
4158 4159
4159 4160 A frame is composed as a type, flags, and payload. These can be parsed
4160 4161 from a string of the form:
4161 4162
4162 4163 <request-id> <stream-id> <stream-flags> <type> <flags> <payload>
4163 4164
4164 4165 ``request-id`` and ``stream-id`` are integers defining the request and
4165 4166 stream identifiers.
4166 4167
4167 4168 ``type`` can be an integer value for the frame type or the string name
4168 4169 of the type. The strings are defined in ``wireprotoframing.py``. e.g.
4169 4170 ``command-name``.
4170 4171
4171 4172 ``stream-flags`` and ``flags`` are a ``|`` delimited list of flag
4172 4173 components. Each component (and there can be just one) can be an integer
4173 4174 or a flag name for stream flags or frame flags, respectively. Values are
4174 4175 resolved to integers and then bitwise OR'd together.
4175 4176
4176 4177 ``payload`` represents the raw frame payload. If it begins with
4177 4178 ``cbor:``, the following string is evaluated as Python code and the
4178 4179 resulting object is fed into a CBOR encoder. Otherwise it is interpreted
4179 4180 as a Python byte string literal.
4180 4181 """
4181 4182 opts = pycompat.byteskwargs(opts)
4182 4183
4183 4184 if opts[b'localssh'] and not repo:
4184 4185 raise error.Abort(_(b'--localssh requires a repository'))
4185 4186
4186 4187 if opts[b'peer'] and opts[b'peer'] not in (
4187 4188 b'raw',
4188 4189 b'http2',
4189 4190 b'ssh1',
4190 4191 b'ssh2',
4191 4192 ):
4192 4193 raise error.Abort(
4193 4194 _(b'invalid value for --peer'),
4194 4195 hint=_(b'valid values are "raw", "ssh1", and "ssh2"'),
4195 4196 )
4196 4197
4197 4198 if path and opts[b'localssh']:
4198 4199 raise error.Abort(_(b'cannot specify --localssh with an explicit path'))
4199 4200
4200 4201 if ui.interactive():
4201 4202 ui.write(_(b'(waiting for commands on stdin)\n'))
4202 4203
4203 4204 blocks = list(_parsewirelangblocks(ui.fin))
4204 4205
4205 4206 proc = None
4206 4207 stdin = None
4207 4208 stdout = None
4208 4209 stderr = None
4209 4210 opener = None
4210 4211
4211 4212 if opts[b'localssh']:
4212 4213 # We start the SSH server in its own process so there is process
4213 4214 # separation. This prevents a whole class of potential bugs around
4214 4215 # shared state from interfering with server operation.
4215 4216 args = procutil.hgcmd() + [
4216 4217 b'-R',
4217 4218 repo.root,
4218 4219 b'debugserve',
4219 4220 b'--sshstdio',
4220 4221 ]
4221 4222 proc = subprocess.Popen(
4222 4223 pycompat.rapply(procutil.tonativestr, args),
4223 4224 stdin=subprocess.PIPE,
4224 4225 stdout=subprocess.PIPE,
4225 4226 stderr=subprocess.PIPE,
4226 4227 bufsize=0,
4227 4228 )
4228 4229
4229 4230 stdin = proc.stdin
4230 4231 stdout = proc.stdout
4231 4232 stderr = proc.stderr
4232 4233
4233 4234 # We turn the pipes into observers so we can log I/O.
4234 4235 if ui.verbose or opts[b'peer'] == b'raw':
4235 4236 stdin = util.makeloggingfileobject(
4236 4237 ui, proc.stdin, b'i', logdata=True
4237 4238 )
4238 4239 stdout = util.makeloggingfileobject(
4239 4240 ui, proc.stdout, b'o', logdata=True
4240 4241 )
4241 4242 stderr = util.makeloggingfileobject(
4242 4243 ui, proc.stderr, b'e', logdata=True
4243 4244 )
4244 4245
4245 4246 # --localssh also implies the peer connection settings.
4246 4247
4247 4248 url = b'ssh://localserver'
4248 4249 autoreadstderr = not opts[b'noreadstderr']
4249 4250
4250 4251 if opts[b'peer'] == b'ssh1':
4251 4252 ui.write(_(b'creating ssh peer for wire protocol version 1\n'))
4252 4253 peer = sshpeer.sshv1peer(
4253 4254 ui,
4254 4255 url,
4255 4256 proc,
4256 4257 stdin,
4257 4258 stdout,
4258 4259 stderr,
4259 4260 None,
4260 4261 autoreadstderr=autoreadstderr,
4261 4262 )
4262 4263 elif opts[b'peer'] == b'ssh2':
4263 4264 ui.write(_(b'creating ssh peer for wire protocol version 2\n'))
4264 4265 peer = sshpeer.sshv2peer(
4265 4266 ui,
4266 4267 url,
4267 4268 proc,
4268 4269 stdin,
4269 4270 stdout,
4270 4271 stderr,
4271 4272 None,
4272 4273 autoreadstderr=autoreadstderr,
4273 4274 )
4274 4275 elif opts[b'peer'] == b'raw':
4275 4276 ui.write(_(b'using raw connection to peer\n'))
4276 4277 peer = None
4277 4278 else:
4278 4279 ui.write(_(b'creating ssh peer from handshake results\n'))
4279 4280 peer = sshpeer.makepeer(
4280 4281 ui,
4281 4282 url,
4282 4283 proc,
4283 4284 stdin,
4284 4285 stdout,
4285 4286 stderr,
4286 4287 autoreadstderr=autoreadstderr,
4287 4288 )
4288 4289
4289 4290 elif path:
4290 4291 # We bypass hg.peer() so we can proxy the sockets.
4291 4292 # TODO consider not doing this because we skip
4292 4293 # ``hg.wirepeersetupfuncs`` and potentially other useful functionality.
4293 4294 u = util.url(path)
4294 4295 if u.scheme != b'http':
4295 4296 raise error.Abort(_(b'only http:// paths are currently supported'))
4296 4297
4297 4298 url, authinfo = u.authinfo()
4298 4299 openerargs = {
4299 4300 'useragent': b'Mercurial debugwireproto',
4300 4301 }
4301 4302
4302 4303 # Turn pipes/sockets into observers so we can log I/O.
4303 4304 if ui.verbose:
4304 4305 openerargs.update(
4305 4306 {
4306 4307 'loggingfh': ui,
4307 4308 'loggingname': b's',
4308 4309 'loggingopts': {'logdata': True, 'logdataapis': False,},
4309 4310 }
4310 4311 )
4311 4312
4312 4313 if ui.debugflag:
4313 4314 openerargs['loggingopts']['logdataapis'] = True
4314 4315
4315 4316 # Don't send default headers when in raw mode. This allows us to
4316 4317 # bypass most of the behavior of our URL handling code so we can
4317 4318 # have near complete control over what's sent on the wire.
4318 4319 if opts[b'peer'] == b'raw':
4319 4320 openerargs['sendaccept'] = False
4320 4321
4321 4322 opener = urlmod.opener(ui, authinfo, **openerargs)
4322 4323
4323 4324 if opts[b'peer'] == b'http2':
4324 4325 ui.write(_(b'creating http peer for wire protocol version 2\n'))
4325 4326 # We go through makepeer() because we need an API descriptor for
4326 4327 # the peer instance to be useful.
4327 4328 with ui.configoverride(
4328 4329 {(b'experimental', b'httppeer.advertise-v2'): True}
4329 4330 ):
4330 4331 if opts[b'nologhandshake']:
4331 4332 ui.pushbuffer()
4332 4333
4333 4334 peer = httppeer.makepeer(ui, path, opener=opener)
4334 4335
4335 4336 if opts[b'nologhandshake']:
4336 4337 ui.popbuffer()
4337 4338
4338 4339 if not isinstance(peer, httppeer.httpv2peer):
4339 4340 raise error.Abort(
4340 4341 _(
4341 4342 b'could not instantiate HTTP peer for '
4342 4343 b'wire protocol version 2'
4343 4344 ),
4344 4345 hint=_(
4345 4346 b'the server may not have the feature '
4346 4347 b'enabled or is not allowing this '
4347 4348 b'client version'
4348 4349 ),
4349 4350 )
4350 4351
4351 4352 elif opts[b'peer'] == b'raw':
4352 4353 ui.write(_(b'using raw connection to peer\n'))
4353 4354 peer = None
4354 4355 elif opts[b'peer']:
4355 4356 raise error.Abort(
4356 4357 _(b'--peer %s not supported with HTTP peers') % opts[b'peer']
4357 4358 )
4358 4359 else:
4359 4360 peer = httppeer.makepeer(ui, path, opener=opener)
4360 4361
4361 4362 # We /could/ populate stdin/stdout with sock.makefile()...
4362 4363 else:
4363 4364 raise error.Abort(_(b'unsupported connection configuration'))
4364 4365
4365 4366 batchedcommands = None
4366 4367
4367 4368 # Now perform actions based on the parsed wire language instructions.
4368 4369 for action, lines in blocks:
4369 4370 if action in (b'raw', b'raw+'):
4370 4371 if not stdin:
4371 4372 raise error.Abort(_(b'cannot call raw/raw+ on this peer'))
4372 4373
4373 4374 # Concatenate the data together.
4374 4375 data = b''.join(l.lstrip() for l in lines)
4375 4376 data = stringutil.unescapestr(data)
4376 4377 stdin.write(data)
4377 4378
4378 4379 if action == b'raw+':
4379 4380 stdin.flush()
4380 4381 elif action == b'flush':
4381 4382 if not stdin:
4382 4383 raise error.Abort(_(b'cannot call flush on this peer'))
4383 4384 stdin.flush()
4384 4385 elif action.startswith(b'command'):
4385 4386 if not peer:
4386 4387 raise error.Abort(
4387 4388 _(
4388 4389 b'cannot send commands unless peer instance '
4389 4390 b'is available'
4390 4391 )
4391 4392 )
4392 4393
4393 4394 command = action.split(b' ', 1)[1]
4394 4395
4395 4396 args = {}
4396 4397 for line in lines:
4397 4398 # We need to allow empty values.
4398 4399 fields = line.lstrip().split(b' ', 1)
4399 4400 if len(fields) == 1:
4400 4401 key = fields[0]
4401 4402 value = b''
4402 4403 else:
4403 4404 key, value = fields
4404 4405
4405 4406 if value.startswith(b'eval:'):
4406 4407 value = stringutil.evalpythonliteral(value[5:])
4407 4408 else:
4408 4409 value = stringutil.unescapestr(value)
4409 4410
4410 4411 args[key] = value
4411 4412
4412 4413 if batchedcommands is not None:
4413 4414 batchedcommands.append((command, args))
4414 4415 continue
4415 4416
4416 4417 ui.status(_(b'sending %s command\n') % command)
4417 4418
4418 4419 if b'PUSHFILE' in args:
4419 4420 with open(args[b'PUSHFILE'], 'rb') as fh:
4420 4421 del args[b'PUSHFILE']
4421 4422 res, output = peer._callpush(
4422 4423 command, fh, **pycompat.strkwargs(args)
4423 4424 )
4424 4425 ui.status(_(b'result: %s\n') % stringutil.escapestr(res))
4425 4426 ui.status(
4426 4427 _(b'remote output: %s\n') % stringutil.escapestr(output)
4427 4428 )
4428 4429 else:
4429 4430 with peer.commandexecutor() as e:
4430 4431 res = e.callcommand(command, args).result()
4431 4432
4432 4433 if isinstance(res, wireprotov2peer.commandresponse):
4433 4434 val = res.objects()
4434 4435 ui.status(
4435 4436 _(b'response: %s\n')
4436 4437 % stringutil.pprint(val, bprefix=True, indent=2)
4437 4438 )
4438 4439 else:
4439 4440 ui.status(
4440 4441 _(b'response: %s\n')
4441 4442 % stringutil.pprint(res, bprefix=True, indent=2)
4442 4443 )
4443 4444
4444 4445 elif action == b'batchbegin':
4445 4446 if batchedcommands is not None:
4446 4447 raise error.Abort(_(b'nested batchbegin not allowed'))
4447 4448
4448 4449 batchedcommands = []
4449 4450 elif action == b'batchsubmit':
4450 4451 # There is a batching API we could go through. But it would be
4451 4452 # difficult to normalize requests into function calls. It is easier
4452 4453 # to bypass this layer and normalize to commands + args.
4453 4454 ui.status(
4454 4455 _(b'sending batch with %d sub-commands\n')
4455 4456 % len(batchedcommands)
4456 4457 )
4457 4458 assert peer is not None
4458 4459 for i, chunk in enumerate(peer._submitbatch(batchedcommands)):
4459 4460 ui.status(
4460 4461 _(b'response #%d: %s\n') % (i, stringutil.escapestr(chunk))
4461 4462 )
4462 4463
4463 4464 batchedcommands = None
4464 4465
4465 4466 elif action.startswith(b'httprequest '):
4466 4467 if not opener:
4467 4468 raise error.Abort(
4468 4469 _(b'cannot use httprequest without an HTTP peer')
4469 4470 )
4470 4471
4471 4472 request = action.split(b' ', 2)
4472 4473 if len(request) != 3:
4473 4474 raise error.Abort(
4474 4475 _(
4475 4476 b'invalid httprequest: expected format is '
4476 4477 b'"httprequest <method> <path>'
4477 4478 )
4478 4479 )
4479 4480
4480 4481 method, httppath = request[1:]
4481 4482 headers = {}
4482 4483 body = None
4483 4484 frames = []
4484 4485 for line in lines:
4485 4486 line = line.lstrip()
4486 4487 m = re.match(b'^([a-zA-Z0-9_-]+): (.*)$', line)
4487 4488 if m:
4488 4489 # Headers need to use native strings.
4489 4490 key = pycompat.strurl(m.group(1))
4490 4491 value = pycompat.strurl(m.group(2))
4491 4492 headers[key] = value
4492 4493 continue
4493 4494
4494 4495 if line.startswith(b'BODYFILE '):
4495 4496 with open(line.split(b' ', 1), b'rb') as fh:
4496 4497 body = fh.read()
4497 4498 elif line.startswith(b'frame '):
4498 4499 frame = wireprotoframing.makeframefromhumanstring(
4499 4500 line[len(b'frame ') :]
4500 4501 )
4501 4502
4502 4503 frames.append(frame)
4503 4504 else:
4504 4505 raise error.Abort(
4505 4506 _(b'unknown argument to httprequest: %s') % line
4506 4507 )
4507 4508
4508 4509 url = path + httppath
4509 4510
4510 4511 if frames:
4511 4512 body = b''.join(bytes(f) for f in frames)
4512 4513
4513 4514 req = urlmod.urlreq.request(pycompat.strurl(url), body, headers)
4514 4515
4515 4516 # urllib.Request insists on using has_data() as a proxy for
4516 4517 # determining the request method. Override that to use our
4517 4518 # explicitly requested method.
4518 4519 req.get_method = lambda: pycompat.sysstr(method)
4519 4520
4520 4521 try:
4521 4522 res = opener.open(req)
4522 4523 body = res.read()
4523 4524 except util.urlerr.urlerror as e:
4524 4525 # read() method must be called, but only exists in Python 2
4525 4526 getattr(e, 'read', lambda: None)()
4526 4527 continue
4527 4528
4528 4529 ct = res.headers.get('Content-Type')
4529 4530 if ct == 'application/mercurial-cbor':
4530 4531 ui.write(
4531 4532 _(b'cbor> %s\n')
4532 4533 % stringutil.pprint(
4533 4534 cborutil.decodeall(body), bprefix=True, indent=2
4534 4535 )
4535 4536 )
4536 4537
4537 4538 elif action == b'close':
4538 4539 assert peer is not None
4539 4540 peer.close()
4540 4541 elif action == b'readavailable':
4541 4542 if not stdout or not stderr:
4542 4543 raise error.Abort(
4543 4544 _(b'readavailable not available on this peer')
4544 4545 )
4545 4546
4546 4547 stdin.close()
4547 4548 stdout.read()
4548 4549 stderr.read()
4549 4550
4550 4551 elif action == b'readline':
4551 4552 if not stdout:
4552 4553 raise error.Abort(_(b'readline not available on this peer'))
4553 4554 stdout.readline()
4554 4555 elif action == b'ereadline':
4555 4556 if not stderr:
4556 4557 raise error.Abort(_(b'ereadline not available on this peer'))
4557 4558 stderr.readline()
4558 4559 elif action.startswith(b'read '):
4559 4560 count = int(action.split(b' ', 1)[1])
4560 4561 if not stdout:
4561 4562 raise error.Abort(_(b'read not available on this peer'))
4562 4563 stdout.read(count)
4563 4564 elif action.startswith(b'eread '):
4564 4565 count = int(action.split(b' ', 1)[1])
4565 4566 if not stderr:
4566 4567 raise error.Abort(_(b'eread not available on this peer'))
4567 4568 stderr.read(count)
4568 4569 else:
4569 4570 raise error.Abort(_(b'unknown action: %s') % action)
4570 4571
4571 4572 if batchedcommands is not None:
4572 4573 raise error.Abort(_(b'unclosed "batchbegin" request'))
4573 4574
4574 4575 if peer:
4575 4576 peer.close()
4576 4577
4577 4578 if proc:
4578 4579 proc.kill()
@@ -1,124 +1,126 b''
1 1 # hgweb/__init__.py - web interface to a mercurial repository
2 2 #
3 3 # Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net>
4 4 # Copyright 2005 Matt Mackall <mpm@selenic.com>
5 5 #
6 6 # This software may be used and distributed according to the terms of the
7 7 # GNU General Public License version 2 or any later version.
8 8
9 9 from __future__ import absolute_import
10 10
11 11 import os
12 import sys
12 13
13 14 from ..i18n import _
14 15
15 16 from .. import (
16 17 error,
17 18 pycompat,
18 19 )
19 20
20 21 from ..utils import procutil
21 22
22 23 from . import (
23 24 hgweb_mod,
24 25 hgwebdir_mod,
25 26 server,
26 27 )
27 28
28 29
29 30 def hgweb(config, name=None, baseui=None):
30 31 '''create an hgweb wsgi object
31 32
32 33 config can be one of:
33 34 - repo object (single repo view)
34 35 - path to repo (single repo view)
35 36 - path to config file (multi-repo view)
36 37 - dict of virtual:real pairs (multi-repo view)
37 38 - list of virtual:real tuples (multi-repo view)
38 39 '''
39 40
40 41 if isinstance(config, pycompat.unicode):
41 42 raise error.ProgrammingError(
42 43 b'Mercurial only supports encoded strings: %r' % config
43 44 )
44 45 if (
45 46 (isinstance(config, bytes) and not os.path.isdir(config))
46 47 or isinstance(config, dict)
47 48 or isinstance(config, list)
48 49 ):
49 50 # create a multi-dir interface
50 51 return hgwebdir_mod.hgwebdir(config, baseui=baseui)
51 52 return hgweb_mod.hgweb(config, name=name, baseui=baseui)
52 53
53 54
54 55 def hgwebdir(config, baseui=None):
55 56 return hgwebdir_mod.hgwebdir(config, baseui=baseui)
56 57
57 58
58 59 class httpservice(object):
59 60 def __init__(self, ui, app, opts):
60 61 self.ui = ui
61 62 self.app = app
62 63 self.opts = opts
63 64
64 65 def init(self):
65 66 procutil.setsignalhandler()
66 67 self.httpd = server.create_server(self.ui, self.app)
67 68
68 69 if (
69 70 self.opts[b'port']
70 71 and not self.ui.verbose
71 72 and not self.opts[b'print_url']
72 73 ):
73 74 return
74 75
75 76 if self.httpd.prefix:
76 77 prefix = self.httpd.prefix.strip(b'/') + b'/'
77 78 else:
78 79 prefix = b''
79 80
80 81 port = ':%d' % self.httpd.port
81 82 if port == ':80':
82 83 port = ''
83 84
84 85 bindaddr = self.httpd.addr
85 86 if bindaddr == '0.0.0.0':
86 87 bindaddr = '*'
87 88 elif ':' in bindaddr: # IPv6
88 89 bindaddr = '[%s]' % bindaddr
89 90
90 91 fqaddr = self.httpd.fqaddr
91 92 if ':' in fqaddr:
92 93 fqaddr = '[%s]' % fqaddr
93 94
94 95 url = b'http://%s%s/%s' % (
95 96 pycompat.sysbytes(fqaddr),
96 97 pycompat.sysbytes(port),
97 98 prefix,
98 99 )
99 100 if self.opts[b'print_url']:
100 101 self.ui.write(b'%s\n' % url)
101 102 else:
102 103 if self.opts[b'port']:
103 104 write = self.ui.status
104 105 else:
105 106 write = self.ui.write
106 107 write(
107 108 _(b'listening at %s (bound to %s:%d)\n')
108 109 % (url, pycompat.sysbytes(bindaddr), self.httpd.port)
109 110 )
110 111 self.ui.flush() # avoid buffering of status message
111 112
112 113 def run(self):
113 114 self.httpd.serve_forever()
115 sys.exit(0)
114 116
115 117
116 118 def createapp(baseui, repo, webconf):
117 119 if webconf:
118 120 return hgwebdir_mod.hgwebdir(webconf, baseui=baseui)
119 121 else:
120 122 if not repo:
121 123 raise error.RepoError(
122 124 _(b"there is no Mercurial repository here (.hg not found)")
123 125 )
124 126 return hgweb_mod.hgweb(repo, baseui=baseui)
@@ -1,858 +1,856 b''
1 1 # Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net>
2 2 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 3 #
4 4 # This software may be used and distributed according to the terms of the
5 5 # GNU General Public License version 2 or any later version.
6 6
7 7 from __future__ import absolute_import
8 8
9 9 import contextlib
10 10 import struct
11 import sys
12 11 import threading
13 12
14 13 from .i18n import _
15 14 from . import (
16 15 encoding,
17 16 error,
18 17 pycompat,
19 18 util,
20 19 wireprototypes,
21 20 wireprotov1server,
22 21 wireprotov2server,
23 22 )
24 23 from .interfaces import util as interfaceutil
25 24 from .utils import (
26 25 cborutil,
27 26 compression,
28 27 )
29 28
30 29 stringio = util.stringio
31 30
32 31 urlerr = util.urlerr
33 32 urlreq = util.urlreq
34 33
35 34 HTTP_OK = 200
36 35
37 36 HGTYPE = b'application/mercurial-0.1'
38 37 HGTYPE2 = b'application/mercurial-0.2'
39 38 HGERRTYPE = b'application/hg-error'
40 39
41 40 SSHV1 = wireprototypes.SSHV1
42 41 SSHV2 = wireprototypes.SSHV2
43 42
44 43
45 44 def decodevaluefromheaders(req, headerprefix):
46 45 """Decode a long value from multiple HTTP request headers.
47 46
48 47 Returns the value as a bytes, not a str.
49 48 """
50 49 chunks = []
51 50 i = 1
52 51 while True:
53 52 v = req.headers.get(b'%s-%d' % (headerprefix, i))
54 53 if v is None:
55 54 break
56 55 chunks.append(pycompat.bytesurl(v))
57 56 i += 1
58 57
59 58 return b''.join(chunks)
60 59
61 60
62 61 @interfaceutil.implementer(wireprototypes.baseprotocolhandler)
63 62 class httpv1protocolhandler(object):
64 63 def __init__(self, req, ui, checkperm):
65 64 self._req = req
66 65 self._ui = ui
67 66 self._checkperm = checkperm
68 67 self._protocaps = None
69 68
70 69 @property
71 70 def name(self):
72 71 return b'http-v1'
73 72
74 73 def getargs(self, args):
75 74 knownargs = self._args()
76 75 data = {}
77 76 keys = args.split()
78 77 for k in keys:
79 78 if k == b'*':
80 79 star = {}
81 80 for key in knownargs.keys():
82 81 if key != b'cmd' and key not in keys:
83 82 star[key] = knownargs[key][0]
84 83 data[b'*'] = star
85 84 else:
86 85 data[k] = knownargs[k][0]
87 86 return [data[k] for k in keys]
88 87
89 88 def _args(self):
90 89 args = self._req.qsparams.asdictoflists()
91 90 postlen = int(self._req.headers.get(b'X-HgArgs-Post', 0))
92 91 if postlen:
93 92 args.update(
94 93 urlreq.parseqs(
95 94 self._req.bodyfh.read(postlen), keep_blank_values=True
96 95 )
97 96 )
98 97 return args
99 98
100 99 argvalue = decodevaluefromheaders(self._req, b'X-HgArg')
101 100 args.update(urlreq.parseqs(argvalue, keep_blank_values=True))
102 101 return args
103 102
104 103 def getprotocaps(self):
105 104 if self._protocaps is None:
106 105 value = decodevaluefromheaders(self._req, b'X-HgProto')
107 106 self._protocaps = set(value.split(b' '))
108 107 return self._protocaps
109 108
110 109 def getpayload(self):
111 110 # Existing clients *always* send Content-Length.
112 111 length = int(self._req.headers[b'Content-Length'])
113 112
114 113 # If httppostargs is used, we need to read Content-Length
115 114 # minus the amount that was consumed by args.
116 115 length -= int(self._req.headers.get(b'X-HgArgs-Post', 0))
117 116 return util.filechunkiter(self._req.bodyfh, limit=length)
118 117
119 118 @contextlib.contextmanager
120 119 def mayberedirectstdio(self):
121 120 oldout = self._ui.fout
122 121 olderr = self._ui.ferr
123 122
124 123 out = util.stringio()
125 124
126 125 try:
127 126 self._ui.fout = out
128 127 self._ui.ferr = out
129 128 yield out
130 129 finally:
131 130 self._ui.fout = oldout
132 131 self._ui.ferr = olderr
133 132
134 133 def client(self):
135 134 return b'remote:%s:%s:%s' % (
136 135 self._req.urlscheme,
137 136 urlreq.quote(self._req.remotehost or b''),
138 137 urlreq.quote(self._req.remoteuser or b''),
139 138 )
140 139
141 140 def addcapabilities(self, repo, caps):
142 141 caps.append(b'batch')
143 142
144 143 caps.append(
145 144 b'httpheader=%d' % repo.ui.configint(b'server', b'maxhttpheaderlen')
146 145 )
147 146 if repo.ui.configbool(b'experimental', b'httppostargs'):
148 147 caps.append(b'httppostargs')
149 148
150 149 # FUTURE advertise 0.2rx once support is implemented
151 150 # FUTURE advertise minrx and mintx after consulting config option
152 151 caps.append(b'httpmediatype=0.1rx,0.1tx,0.2tx')
153 152
154 153 compengines = wireprototypes.supportedcompengines(
155 154 repo.ui, compression.SERVERROLE
156 155 )
157 156 if compengines:
158 157 comptypes = b','.join(
159 158 urlreq.quote(e.wireprotosupport().name) for e in compengines
160 159 )
161 160 caps.append(b'compression=%s' % comptypes)
162 161
163 162 return caps
164 163
165 164 def checkperm(self, perm):
166 165 return self._checkperm(perm)
167 166
168 167
169 168 # This method exists mostly so that extensions like remotefilelog can
170 169 # disable a kludgey legacy method only over http. As of early 2018,
171 170 # there are no other known users, so with any luck we can discard this
172 171 # hook if remotefilelog becomes a first-party extension.
173 172 def iscmd(cmd):
174 173 return cmd in wireprotov1server.commands
175 174
176 175
177 176 def handlewsgirequest(rctx, req, res, checkperm):
178 177 """Possibly process a wire protocol request.
179 178
180 179 If the current request is a wire protocol request, the request is
181 180 processed by this function.
182 181
183 182 ``req`` is a ``parsedrequest`` instance.
184 183 ``res`` is a ``wsgiresponse`` instance.
185 184
186 185 Returns a bool indicating if the request was serviced. If set, the caller
187 186 should stop processing the request, as a response has already been issued.
188 187 """
189 188 # Avoid cycle involving hg module.
190 189 from .hgweb import common as hgwebcommon
191 190
192 191 repo = rctx.repo
193 192
194 193 # HTTP version 1 wire protocol requests are denoted by a "cmd" query
195 194 # string parameter. If it isn't present, this isn't a wire protocol
196 195 # request.
197 196 if b'cmd' not in req.qsparams:
198 197 return False
199 198
200 199 cmd = req.qsparams[b'cmd']
201 200
202 201 # The "cmd" request parameter is used by both the wire protocol and hgweb.
203 202 # While not all wire protocol commands are available for all transports,
204 203 # if we see a "cmd" value that resembles a known wire protocol command, we
205 204 # route it to a protocol handler. This is better than routing possible
206 205 # wire protocol requests to hgweb because it prevents hgweb from using
207 206 # known wire protocol commands and it is less confusing for machine
208 207 # clients.
209 208 if not iscmd(cmd):
210 209 return False
211 210
212 211 # The "cmd" query string argument is only valid on the root path of the
213 212 # repo. e.g. ``/?cmd=foo``, ``/repo?cmd=foo``. URL paths within the repo
214 213 # like ``/blah?cmd=foo`` are not allowed. So don't recognize the request
215 214 # in this case. We send an HTTP 404 for backwards compatibility reasons.
216 215 if req.dispatchpath:
217 216 res.status = hgwebcommon.statusmessage(404)
218 217 res.headers[b'Content-Type'] = HGTYPE
219 218 # TODO This is not a good response to issue for this request. This
220 219 # is mostly for BC for now.
221 220 res.setbodybytes(b'0\n%s\n' % b'Not Found')
222 221 return True
223 222
224 223 proto = httpv1protocolhandler(
225 224 req, repo.ui, lambda perm: checkperm(rctx, req, perm)
226 225 )
227 226
228 227 # The permissions checker should be the only thing that can raise an
229 228 # ErrorResponse. It is kind of a layer violation to catch an hgweb
230 229 # exception here. So consider refactoring into a exception type that
231 230 # is associated with the wire protocol.
232 231 try:
233 232 _callhttp(repo, req, res, proto, cmd)
234 233 except hgwebcommon.ErrorResponse as e:
235 234 for k, v in e.headers:
236 235 res.headers[k] = v
237 236 res.status = hgwebcommon.statusmessage(e.code, pycompat.bytestr(e))
238 237 # TODO This response body assumes the failed command was
239 238 # "unbundle." That assumption is not always valid.
240 239 res.setbodybytes(b'0\n%s\n' % pycompat.bytestr(e))
241 240
242 241 return True
243 242
244 243
245 244 def _availableapis(repo):
246 245 apis = set()
247 246
248 247 # Registered APIs are made available via config options of the name of
249 248 # the protocol.
250 249 for k, v in API_HANDLERS.items():
251 250 section, option = v[b'config']
252 251 if repo.ui.configbool(section, option):
253 252 apis.add(k)
254 253
255 254 return apis
256 255
257 256
258 257 def handlewsgiapirequest(rctx, req, res, checkperm):
259 258 """Handle requests to /api/*."""
260 259 assert req.dispatchparts[0] == b'api'
261 260
262 261 repo = rctx.repo
263 262
264 263 # This whole URL space is experimental for now. But we want to
265 264 # reserve the URL space. So, 404 all URLs if the feature isn't enabled.
266 265 if not repo.ui.configbool(b'experimental', b'web.apiserver'):
267 266 res.status = b'404 Not Found'
268 267 res.headers[b'Content-Type'] = b'text/plain'
269 268 res.setbodybytes(_(b'Experimental API server endpoint not enabled'))
270 269 return
271 270
272 271 # The URL space is /api/<protocol>/*. The structure of URLs under varies
273 272 # by <protocol>.
274 273
275 274 availableapis = _availableapis(repo)
276 275
277 276 # Requests to /api/ list available APIs.
278 277 if req.dispatchparts == [b'api']:
279 278 res.status = b'200 OK'
280 279 res.headers[b'Content-Type'] = b'text/plain'
281 280 lines = [
282 281 _(
283 282 b'APIs can be accessed at /api/<name>, where <name> can be '
284 283 b'one of the following:\n'
285 284 )
286 285 ]
287 286 if availableapis:
288 287 lines.extend(sorted(availableapis))
289 288 else:
290 289 lines.append(_(b'(no available APIs)\n'))
291 290 res.setbodybytes(b'\n'.join(lines))
292 291 return
293 292
294 293 proto = req.dispatchparts[1]
295 294
296 295 if proto not in API_HANDLERS:
297 296 res.status = b'404 Not Found'
298 297 res.headers[b'Content-Type'] = b'text/plain'
299 298 res.setbodybytes(
300 299 _(b'Unknown API: %s\nKnown APIs: %s')
301 300 % (proto, b', '.join(sorted(availableapis)))
302 301 )
303 302 return
304 303
305 304 if proto not in availableapis:
306 305 res.status = b'404 Not Found'
307 306 res.headers[b'Content-Type'] = b'text/plain'
308 307 res.setbodybytes(_(b'API %s not enabled\n') % proto)
309 308 return
310 309
311 310 API_HANDLERS[proto][b'handler'](
312 311 rctx, req, res, checkperm, req.dispatchparts[2:]
313 312 )
314 313
315 314
316 315 # Maps API name to metadata so custom API can be registered.
317 316 # Keys are:
318 317 #
319 318 # config
320 319 # Config option that controls whether service is enabled.
321 320 # handler
322 321 # Callable receiving (rctx, req, res, checkperm, urlparts) that is called
323 322 # when a request to this API is received.
324 323 # apidescriptor
325 324 # Callable receiving (req, repo) that is called to obtain an API
326 325 # descriptor for this service. The response must be serializable to CBOR.
327 326 API_HANDLERS = {
328 327 wireprotov2server.HTTP_WIREPROTO_V2: {
329 328 b'config': (b'experimental', b'web.api.http-v2'),
330 329 b'handler': wireprotov2server.handlehttpv2request,
331 330 b'apidescriptor': wireprotov2server.httpv2apidescriptor,
332 331 },
333 332 }
334 333
335 334
336 335 def _httpresponsetype(ui, proto, prefer_uncompressed):
337 336 """Determine the appropriate response type and compression settings.
338 337
339 338 Returns a tuple of (mediatype, compengine, engineopts).
340 339 """
341 340 # Determine the response media type and compression engine based
342 341 # on the request parameters.
343 342
344 343 if b'0.2' in proto.getprotocaps():
345 344 # All clients are expected to support uncompressed data.
346 345 if prefer_uncompressed:
347 346 return HGTYPE2, compression._noopengine(), {}
348 347
349 348 # Now find an agreed upon compression format.
350 349 compformats = wireprotov1server.clientcompressionsupport(proto)
351 350 for engine in wireprototypes.supportedcompengines(
352 351 ui, compression.SERVERROLE
353 352 ):
354 353 if engine.wireprotosupport().name in compformats:
355 354 opts = {}
356 355 level = ui.configint(b'server', b'%slevel' % engine.name())
357 356 if level is not None:
358 357 opts[b'level'] = level
359 358
360 359 return HGTYPE2, engine, opts
361 360
362 361 # No mutually supported compression format. Fall back to the
363 362 # legacy protocol.
364 363
365 364 # Don't allow untrusted settings because disabling compression or
366 365 # setting a very high compression level could lead to flooding
367 366 # the server's network or CPU.
368 367 opts = {b'level': ui.configint(b'server', b'zliblevel')}
369 368 return HGTYPE, util.compengines[b'zlib'], opts
370 369
371 370
372 371 def processcapabilitieshandshake(repo, req, res, proto):
373 372 """Called during a ?cmd=capabilities request.
374 373
375 374 If the client is advertising support for a newer protocol, we send
376 375 a CBOR response with information about available services. If no
377 376 advertised services are available, we don't handle the request.
378 377 """
379 378 # Fall back to old behavior unless the API server is enabled.
380 379 if not repo.ui.configbool(b'experimental', b'web.apiserver'):
381 380 return False
382 381
383 382 clientapis = decodevaluefromheaders(req, b'X-HgUpgrade')
384 383 protocaps = decodevaluefromheaders(req, b'X-HgProto')
385 384 if not clientapis or not protocaps:
386 385 return False
387 386
388 387 # We currently only support CBOR responses.
389 388 protocaps = set(protocaps.split(b' '))
390 389 if b'cbor' not in protocaps:
391 390 return False
392 391
393 392 descriptors = {}
394 393
395 394 for api in sorted(set(clientapis.split()) & _availableapis(repo)):
396 395 handler = API_HANDLERS[api]
397 396
398 397 descriptorfn = handler.get(b'apidescriptor')
399 398 if not descriptorfn:
400 399 continue
401 400
402 401 descriptors[api] = descriptorfn(req, repo)
403 402
404 403 v1caps = wireprotov1server.dispatch(repo, proto, b'capabilities')
405 404 assert isinstance(v1caps, wireprototypes.bytesresponse)
406 405
407 406 m = {
408 407 # TODO allow this to be configurable.
409 408 b'apibase': b'api/',
410 409 b'apis': descriptors,
411 410 b'v1capabilities': v1caps.data,
412 411 }
413 412
414 413 res.status = b'200 OK'
415 414 res.headers[b'Content-Type'] = b'application/mercurial-cbor'
416 415 res.setbodybytes(b''.join(cborutil.streamencode(m)))
417 416
418 417 return True
419 418
420 419
421 420 def _callhttp(repo, req, res, proto, cmd):
422 421 # Avoid cycle involving hg module.
423 422 from .hgweb import common as hgwebcommon
424 423
425 424 def genversion2(gen, engine, engineopts):
426 425 # application/mercurial-0.2 always sends a payload header
427 426 # identifying the compression engine.
428 427 name = engine.wireprotosupport().name
429 428 assert 0 < len(name) < 256
430 429 yield struct.pack(b'B', len(name))
431 430 yield name
432 431
433 432 for chunk in gen:
434 433 yield chunk
435 434
436 435 def setresponse(code, contenttype, bodybytes=None, bodygen=None):
437 436 if code == HTTP_OK:
438 437 res.status = b'200 Script output follows'
439 438 else:
440 439 res.status = hgwebcommon.statusmessage(code)
441 440
442 441 res.headers[b'Content-Type'] = contenttype
443 442
444 443 if bodybytes is not None:
445 444 res.setbodybytes(bodybytes)
446 445 if bodygen is not None:
447 446 res.setbodygen(bodygen)
448 447
449 448 if not wireprotov1server.commands.commandavailable(cmd, proto):
450 449 setresponse(
451 450 HTTP_OK,
452 451 HGERRTYPE,
453 452 _(
454 453 b'requested wire protocol command is not available over '
455 454 b'HTTP'
456 455 ),
457 456 )
458 457 return
459 458
460 459 proto.checkperm(wireprotov1server.commands[cmd].permission)
461 460
462 461 # Possibly handle a modern client wanting to switch protocols.
463 462 if cmd == b'capabilities' and processcapabilitieshandshake(
464 463 repo, req, res, proto
465 464 ):
466 465
467 466 return
468 467
469 468 rsp = wireprotov1server.dispatch(repo, proto, cmd)
470 469
471 470 if isinstance(rsp, bytes):
472 471 setresponse(HTTP_OK, HGTYPE, bodybytes=rsp)
473 472 elif isinstance(rsp, wireprototypes.bytesresponse):
474 473 setresponse(HTTP_OK, HGTYPE, bodybytes=rsp.data)
475 474 elif isinstance(rsp, wireprototypes.streamreslegacy):
476 475 setresponse(HTTP_OK, HGTYPE, bodygen=rsp.gen)
477 476 elif isinstance(rsp, wireprototypes.streamres):
478 477 gen = rsp.gen
479 478
480 479 # This code for compression should not be streamres specific. It
481 480 # is here because we only compress streamres at the moment.
482 481 mediatype, engine, engineopts = _httpresponsetype(
483 482 repo.ui, proto, rsp.prefer_uncompressed
484 483 )
485 484 gen = engine.compressstream(gen, engineopts)
486 485
487 486 if mediatype == HGTYPE2:
488 487 gen = genversion2(gen, engine, engineopts)
489 488
490 489 setresponse(HTTP_OK, mediatype, bodygen=gen)
491 490 elif isinstance(rsp, wireprototypes.pushres):
492 491 rsp = b'%d\n%s' % (rsp.res, rsp.output)
493 492 setresponse(HTTP_OK, HGTYPE, bodybytes=rsp)
494 493 elif isinstance(rsp, wireprototypes.pusherr):
495 494 rsp = b'0\n%s\n' % rsp.res
496 495 res.drain = True
497 496 setresponse(HTTP_OK, HGTYPE, bodybytes=rsp)
498 497 elif isinstance(rsp, wireprototypes.ooberror):
499 498 setresponse(HTTP_OK, HGERRTYPE, bodybytes=rsp.message)
500 499 else:
501 500 raise error.ProgrammingError(b'hgweb.protocol internal failure', rsp)
502 501
503 502
504 503 def _sshv1respondbytes(fout, value):
505 504 """Send a bytes response for protocol version 1."""
506 505 fout.write(b'%d\n' % len(value))
507 506 fout.write(value)
508 507 fout.flush()
509 508
510 509
511 510 def _sshv1respondstream(fout, source):
512 511 write = fout.write
513 512 for chunk in source.gen:
514 513 write(chunk)
515 514 fout.flush()
516 515
517 516
518 517 def _sshv1respondooberror(fout, ferr, rsp):
519 518 ferr.write(b'%s\n-\n' % rsp)
520 519 ferr.flush()
521 520 fout.write(b'\n')
522 521 fout.flush()
523 522
524 523
525 524 @interfaceutil.implementer(wireprototypes.baseprotocolhandler)
526 525 class sshv1protocolhandler(object):
527 526 """Handler for requests services via version 1 of SSH protocol."""
528 527
529 528 def __init__(self, ui, fin, fout):
530 529 self._ui = ui
531 530 self._fin = fin
532 531 self._fout = fout
533 532 self._protocaps = set()
534 533
535 534 @property
536 535 def name(self):
537 536 return wireprototypes.SSHV1
538 537
539 538 def getargs(self, args):
540 539 data = {}
541 540 keys = args.split()
542 541 for n in pycompat.xrange(len(keys)):
543 542 argline = self._fin.readline()[:-1]
544 543 arg, l = argline.split()
545 544 if arg not in keys:
546 545 raise error.Abort(_(b"unexpected parameter %r") % arg)
547 546 if arg == b'*':
548 547 star = {}
549 548 for k in pycompat.xrange(int(l)):
550 549 argline = self._fin.readline()[:-1]
551 550 arg, l = argline.split()
552 551 val = self._fin.read(int(l))
553 552 star[arg] = val
554 553 data[b'*'] = star
555 554 else:
556 555 val = self._fin.read(int(l))
557 556 data[arg] = val
558 557 return [data[k] for k in keys]
559 558
560 559 def getprotocaps(self):
561 560 return self._protocaps
562 561
563 562 def getpayload(self):
564 563 # We initially send an empty response. This tells the client it is
565 564 # OK to start sending data. If a client sees any other response, it
566 565 # interprets it as an error.
567 566 _sshv1respondbytes(self._fout, b'')
568 567
569 568 # The file is in the form:
570 569 #
571 570 # <chunk size>\n<chunk>
572 571 # ...
573 572 # 0\n
574 573 count = int(self._fin.readline())
575 574 while count:
576 575 yield self._fin.read(count)
577 576 count = int(self._fin.readline())
578 577
579 578 @contextlib.contextmanager
580 579 def mayberedirectstdio(self):
581 580 yield None
582 581
583 582 def client(self):
584 583 client = encoding.environ.get(b'SSH_CLIENT', b'').split(b' ', 1)[0]
585 584 return b'remote:ssh:' + client
586 585
587 586 def addcapabilities(self, repo, caps):
588 587 if self.name == wireprototypes.SSHV1:
589 588 caps.append(b'protocaps')
590 589 caps.append(b'batch')
591 590 return caps
592 591
593 592 def checkperm(self, perm):
594 593 pass
595 594
596 595
597 596 class sshv2protocolhandler(sshv1protocolhandler):
598 597 """Protocol handler for version 2 of the SSH protocol."""
599 598
600 599 @property
601 600 def name(self):
602 601 return wireprototypes.SSHV2
603 602
604 603 def addcapabilities(self, repo, caps):
605 604 return caps
606 605
607 606
608 607 def _runsshserver(ui, repo, fin, fout, ev):
609 608 # This function operates like a state machine of sorts. The following
610 609 # states are defined:
611 610 #
612 611 # protov1-serving
613 612 # Server is in protocol version 1 serving mode. Commands arrive on
614 613 # new lines. These commands are processed in this state, one command
615 614 # after the other.
616 615 #
617 616 # protov2-serving
618 617 # Server is in protocol version 2 serving mode.
619 618 #
620 619 # upgrade-initial
621 620 # The server is going to process an upgrade request.
622 621 #
623 622 # upgrade-v2-filter-legacy-handshake
624 623 # The protocol is being upgraded to version 2. The server is expecting
625 624 # the legacy handshake from version 1.
626 625 #
627 626 # upgrade-v2-finish
628 627 # The upgrade to version 2 of the protocol is imminent.
629 628 #
630 629 # shutdown
631 630 # The server is shutting down, possibly in reaction to a client event.
632 631 #
633 632 # And here are their transitions:
634 633 #
635 634 # protov1-serving -> shutdown
636 635 # When server receives an empty request or encounters another
637 636 # error.
638 637 #
639 638 # protov1-serving -> upgrade-initial
640 639 # An upgrade request line was seen.
641 640 #
642 641 # upgrade-initial -> upgrade-v2-filter-legacy-handshake
643 642 # Upgrade to version 2 in progress. Server is expecting to
644 643 # process a legacy handshake.
645 644 #
646 645 # upgrade-v2-filter-legacy-handshake -> shutdown
647 646 # Client did not fulfill upgrade handshake requirements.
648 647 #
649 648 # upgrade-v2-filter-legacy-handshake -> upgrade-v2-finish
650 649 # Client fulfilled version 2 upgrade requirements. Finishing that
651 650 # upgrade.
652 651 #
653 652 # upgrade-v2-finish -> protov2-serving
654 653 # Protocol upgrade to version 2 complete. Server can now speak protocol
655 654 # version 2.
656 655 #
657 656 # protov2-serving -> protov1-serving
658 657 # Ths happens by default since protocol version 2 is the same as
659 658 # version 1 except for the handshake.
660 659
661 660 state = b'protov1-serving'
662 661 proto = sshv1protocolhandler(ui, fin, fout)
663 662 protoswitched = False
664 663
665 664 while not ev.is_set():
666 665 if state == b'protov1-serving':
667 666 # Commands are issued on new lines.
668 667 request = fin.readline()[:-1]
669 668
670 669 # Empty lines signal to terminate the connection.
671 670 if not request:
672 671 state = b'shutdown'
673 672 continue
674 673
675 674 # It looks like a protocol upgrade request. Transition state to
676 675 # handle it.
677 676 if request.startswith(b'upgrade '):
678 677 if protoswitched:
679 678 _sshv1respondooberror(
680 679 fout,
681 680 ui.ferr,
682 681 b'cannot upgrade protocols multiple times',
683 682 )
684 683 state = b'shutdown'
685 684 continue
686 685
687 686 state = b'upgrade-initial'
688 687 continue
689 688
690 689 available = wireprotov1server.commands.commandavailable(
691 690 request, proto
692 691 )
693 692
694 693 # This command isn't available. Send an empty response and go
695 694 # back to waiting for a new command.
696 695 if not available:
697 696 _sshv1respondbytes(fout, b'')
698 697 continue
699 698
700 699 rsp = wireprotov1server.dispatch(repo, proto, request)
701 700 repo.ui.fout.flush()
702 701 repo.ui.ferr.flush()
703 702
704 703 if isinstance(rsp, bytes):
705 704 _sshv1respondbytes(fout, rsp)
706 705 elif isinstance(rsp, wireprototypes.bytesresponse):
707 706 _sshv1respondbytes(fout, rsp.data)
708 707 elif isinstance(rsp, wireprototypes.streamres):
709 708 _sshv1respondstream(fout, rsp)
710 709 elif isinstance(rsp, wireprototypes.streamreslegacy):
711 710 _sshv1respondstream(fout, rsp)
712 711 elif isinstance(rsp, wireprototypes.pushres):
713 712 _sshv1respondbytes(fout, b'')
714 713 _sshv1respondbytes(fout, b'%d' % rsp.res)
715 714 elif isinstance(rsp, wireprototypes.pusherr):
716 715 _sshv1respondbytes(fout, rsp.res)
717 716 elif isinstance(rsp, wireprototypes.ooberror):
718 717 _sshv1respondooberror(fout, ui.ferr, rsp.message)
719 718 else:
720 719 raise error.ProgrammingError(
721 720 b'unhandled response type from '
722 721 b'wire protocol command: %s' % rsp
723 722 )
724 723
725 724 # For now, protocol version 2 serving just goes back to version 1.
726 725 elif state == b'protov2-serving':
727 726 state = b'protov1-serving'
728 727 continue
729 728
730 729 elif state == b'upgrade-initial':
731 730 # We should never transition into this state if we've switched
732 731 # protocols.
733 732 assert not protoswitched
734 733 assert proto.name == wireprototypes.SSHV1
735 734
736 735 # Expected: upgrade <token> <capabilities>
737 736 # If we get something else, the request is malformed. It could be
738 737 # from a future client that has altered the upgrade line content.
739 738 # We treat this as an unknown command.
740 739 try:
741 740 token, caps = request.split(b' ')[1:]
742 741 except ValueError:
743 742 _sshv1respondbytes(fout, b'')
744 743 state = b'protov1-serving'
745 744 continue
746 745
747 746 # Send empty response if we don't support upgrading protocols.
748 747 if not ui.configbool(b'experimental', b'sshserver.support-v2'):
749 748 _sshv1respondbytes(fout, b'')
750 749 state = b'protov1-serving'
751 750 continue
752 751
753 752 try:
754 753 caps = urlreq.parseqs(caps)
755 754 except ValueError:
756 755 _sshv1respondbytes(fout, b'')
757 756 state = b'protov1-serving'
758 757 continue
759 758
760 759 # We don't see an upgrade request to protocol version 2. Ignore
761 760 # the upgrade request.
762 761 wantedprotos = caps.get(b'proto', [b''])[0]
763 762 if SSHV2 not in wantedprotos:
764 763 _sshv1respondbytes(fout, b'')
765 764 state = b'protov1-serving'
766 765 continue
767 766
768 767 # It looks like we can honor this upgrade request to protocol 2.
769 768 # Filter the rest of the handshake protocol request lines.
770 769 state = b'upgrade-v2-filter-legacy-handshake'
771 770 continue
772 771
773 772 elif state == b'upgrade-v2-filter-legacy-handshake':
774 773 # Client should have sent legacy handshake after an ``upgrade``
775 774 # request. Expected lines:
776 775 #
777 776 # hello
778 777 # between
779 778 # pairs 81
780 779 # 0000...-0000...
781 780
782 781 ok = True
783 782 for line in (b'hello', b'between', b'pairs 81'):
784 783 request = fin.readline()[:-1]
785 784
786 785 if request != line:
787 786 _sshv1respondooberror(
788 787 fout,
789 788 ui.ferr,
790 789 b'malformed handshake protocol: missing %s' % line,
791 790 )
792 791 ok = False
793 792 state = b'shutdown'
794 793 break
795 794
796 795 if not ok:
797 796 continue
798 797
799 798 request = fin.read(81)
800 799 if request != b'%s-%s' % (b'0' * 40, b'0' * 40):
801 800 _sshv1respondooberror(
802 801 fout,
803 802 ui.ferr,
804 803 b'malformed handshake protocol: '
805 804 b'missing between argument value',
806 805 )
807 806 state = b'shutdown'
808 807 continue
809 808
810 809 state = b'upgrade-v2-finish'
811 810 continue
812 811
813 812 elif state == b'upgrade-v2-finish':
814 813 # Send the upgrade response.
815 814 fout.write(b'upgraded %s %s\n' % (token, SSHV2))
816 815 servercaps = wireprotov1server.capabilities(repo, proto)
817 816 rsp = b'capabilities: %s' % servercaps.data
818 817 fout.write(b'%d\n%s\n' % (len(rsp), rsp))
819 818 fout.flush()
820 819
821 820 proto = sshv2protocolhandler(ui, fin, fout)
822 821 protoswitched = True
823 822
824 823 state = b'protov2-serving'
825 824 continue
826 825
827 826 elif state == b'shutdown':
828 827 break
829 828
830 829 else:
831 830 raise error.ProgrammingError(
832 831 b'unhandled ssh server state: %s' % state
833 832 )
834 833
835 834
836 835 class sshserver(object):
837 836 def __init__(self, ui, repo, logfh=None):
838 837 self._ui = ui
839 838 self._repo = repo
840 839 self._fin, self._fout = ui.protectfinout()
841 840
842 841 # Log write I/O to stdout and stderr if configured.
843 842 if logfh:
844 843 self._fout = util.makeloggingfileobject(
845 844 logfh, self._fout, b'o', logdata=True
846 845 )
847 846 ui.ferr = util.makeloggingfileobject(
848 847 logfh, ui.ferr, b'e', logdata=True
849 848 )
850 849
851 850 def serve_forever(self):
852 851 self.serveuntil(threading.Event())
853 852 self._ui.restorefinout(self._fin, self._fout)
854 sys.exit(0)
855 853
856 854 def serveuntil(self, ev):
857 855 """Serve until a threading.Event is set."""
858 856 _runsshserver(self._ui, self._repo, self._fin, self._fout, ev)
General Comments 0
You need to be logged in to leave comments. Login now