##// END OF EJS Templates
commit: warn the user when a commit already exists...
Dan Villiom Podlaski Christiansen -
r46392:103929c2 stable draft
parent child Browse files
Show More
@@ -1,3872 +1,3877 b''
1 1 # cmdutil.py - help for command processing in 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 copy as copymod
11 11 import errno
12 12 import os
13 13 import re
14 14
15 15 from .i18n import _
16 16 from .node import (
17 17 hex,
18 18 nullid,
19 19 short,
20 20 )
21 21 from .pycompat import (
22 22 getattr,
23 23 open,
24 24 setattr,
25 25 )
26 26 from .thirdparty import attr
27 27
28 28 from . import (
29 29 bookmarks,
30 30 changelog,
31 31 copies,
32 32 crecord as crecordmod,
33 33 dirstateguard,
34 34 encoding,
35 35 error,
36 36 formatter,
37 37 logcmdutil,
38 38 match as matchmod,
39 39 merge as mergemod,
40 40 mergestate as mergestatemod,
41 41 mergeutil,
42 42 obsolete,
43 43 patch,
44 44 pathutil,
45 45 phases,
46 46 pycompat,
47 47 repair,
48 48 revlog,
49 49 rewriteutil,
50 50 scmutil,
51 51 state as statemod,
52 52 subrepoutil,
53 53 templatekw,
54 54 templater,
55 55 util,
56 56 vfs as vfsmod,
57 57 )
58 58
59 59 from .utils import (
60 60 dateutil,
61 61 stringutil,
62 62 )
63 63
64 64 if pycompat.TYPE_CHECKING:
65 65 from typing import (
66 66 Any,
67 67 Dict,
68 68 )
69 69
70 70 for t in (Any, Dict):
71 71 assert t
72 72
73 73 stringio = util.stringio
74 74
75 75 # templates of common command options
76 76
77 77 dryrunopts = [
78 78 (b'n', b'dry-run', None, _(b'do not perform actions, just print output')),
79 79 ]
80 80
81 81 confirmopts = [
82 82 (b'', b'confirm', None, _(b'ask before applying actions')),
83 83 ]
84 84
85 85 remoteopts = [
86 86 (b'e', b'ssh', b'', _(b'specify ssh command to use'), _(b'CMD')),
87 87 (
88 88 b'',
89 89 b'remotecmd',
90 90 b'',
91 91 _(b'specify hg command to run on the remote side'),
92 92 _(b'CMD'),
93 93 ),
94 94 (
95 95 b'',
96 96 b'insecure',
97 97 None,
98 98 _(b'do not verify server certificate (ignoring web.cacerts config)'),
99 99 ),
100 100 ]
101 101
102 102 walkopts = [
103 103 (
104 104 b'I',
105 105 b'include',
106 106 [],
107 107 _(b'include names matching the given patterns'),
108 108 _(b'PATTERN'),
109 109 ),
110 110 (
111 111 b'X',
112 112 b'exclude',
113 113 [],
114 114 _(b'exclude names matching the given patterns'),
115 115 _(b'PATTERN'),
116 116 ),
117 117 ]
118 118
119 119 commitopts = [
120 120 (b'm', b'message', b'', _(b'use text as commit message'), _(b'TEXT')),
121 121 (b'l', b'logfile', b'', _(b'read commit message from file'), _(b'FILE')),
122 122 ]
123 123
124 124 commitopts2 = [
125 125 (
126 126 b'd',
127 127 b'date',
128 128 b'',
129 129 _(b'record the specified date as commit date'),
130 130 _(b'DATE'),
131 131 ),
132 132 (
133 133 b'u',
134 134 b'user',
135 135 b'',
136 136 _(b'record the specified user as committer'),
137 137 _(b'USER'),
138 138 ),
139 139 ]
140 140
141 141 commitopts3 = [
142 142 (b'D', b'currentdate', None, _(b'record the current date as commit date')),
143 143 (b'U', b'currentuser', None, _(b'record the current user as committer')),
144 144 ]
145 145
146 146 formatteropts = [
147 147 (b'T', b'template', b'', _(b'display with template'), _(b'TEMPLATE')),
148 148 ]
149 149
150 150 templateopts = [
151 151 (
152 152 b'',
153 153 b'style',
154 154 b'',
155 155 _(b'display using template map file (DEPRECATED)'),
156 156 _(b'STYLE'),
157 157 ),
158 158 (b'T', b'template', b'', _(b'display with template'), _(b'TEMPLATE')),
159 159 ]
160 160
161 161 logopts = [
162 162 (b'p', b'patch', None, _(b'show patch')),
163 163 (b'g', b'git', None, _(b'use git extended diff format')),
164 164 (b'l', b'limit', b'', _(b'limit number of changes displayed'), _(b'NUM')),
165 165 (b'M', b'no-merges', None, _(b'do not show merges')),
166 166 (b'', b'stat', None, _(b'output diffstat-style summary of changes')),
167 167 (b'G', b'graph', None, _(b"show the revision DAG")),
168 168 ] + templateopts
169 169
170 170 diffopts = [
171 171 (b'a', b'text', None, _(b'treat all files as text')),
172 172 (
173 173 b'g',
174 174 b'git',
175 175 None,
176 176 _(b'use git extended diff format (DEFAULT: diff.git)'),
177 177 ),
178 178 (b'', b'binary', None, _(b'generate binary diffs in git mode (default)')),
179 179 (b'', b'nodates', None, _(b'omit dates from diff headers')),
180 180 ]
181 181
182 182 diffwsopts = [
183 183 (
184 184 b'w',
185 185 b'ignore-all-space',
186 186 None,
187 187 _(b'ignore white space when comparing lines'),
188 188 ),
189 189 (
190 190 b'b',
191 191 b'ignore-space-change',
192 192 None,
193 193 _(b'ignore changes in the amount of white space'),
194 194 ),
195 195 (
196 196 b'B',
197 197 b'ignore-blank-lines',
198 198 None,
199 199 _(b'ignore changes whose lines are all blank'),
200 200 ),
201 201 (
202 202 b'Z',
203 203 b'ignore-space-at-eol',
204 204 None,
205 205 _(b'ignore changes in whitespace at EOL'),
206 206 ),
207 207 ]
208 208
209 209 diffopts2 = (
210 210 [
211 211 (b'', b'noprefix', None, _(b'omit a/ and b/ prefixes from filenames')),
212 212 (
213 213 b'p',
214 214 b'show-function',
215 215 None,
216 216 _(
217 217 b'show which function each change is in (DEFAULT: diff.showfunc)'
218 218 ),
219 219 ),
220 220 (b'', b'reverse', None, _(b'produce a diff that undoes the changes')),
221 221 ]
222 222 + diffwsopts
223 223 + [
224 224 (
225 225 b'U',
226 226 b'unified',
227 227 b'',
228 228 _(b'number of lines of context to show'),
229 229 _(b'NUM'),
230 230 ),
231 231 (b'', b'stat', None, _(b'output diffstat-style summary of changes')),
232 232 (
233 233 b'',
234 234 b'root',
235 235 b'',
236 236 _(b'produce diffs relative to subdirectory'),
237 237 _(b'DIR'),
238 238 ),
239 239 ]
240 240 )
241 241
242 242 mergetoolopts = [
243 243 (b't', b'tool', b'', _(b'specify merge tool'), _(b'TOOL')),
244 244 ]
245 245
246 246 similarityopts = [
247 247 (
248 248 b's',
249 249 b'similarity',
250 250 b'',
251 251 _(b'guess renamed files by similarity (0<=s<=100)'),
252 252 _(b'SIMILARITY'),
253 253 )
254 254 ]
255 255
256 256 subrepoopts = [(b'S', b'subrepos', None, _(b'recurse into subrepositories'))]
257 257
258 258 debugrevlogopts = [
259 259 (b'c', b'changelog', False, _(b'open changelog')),
260 260 (b'm', b'manifest', False, _(b'open manifest')),
261 261 (b'', b'dir', b'', _(b'open directory manifest')),
262 262 ]
263 263
264 264 # special string such that everything below this line will be ingored in the
265 265 # editor text
266 266 _linebelow = b"^HG: ------------------------ >8 ------------------------$"
267 267
268 268
269 269 def check_at_most_one_arg(opts, *args):
270 270 """abort if more than one of the arguments are in opts
271 271
272 272 Returns the unique argument or None if none of them were specified.
273 273 """
274 274
275 275 def to_display(name):
276 276 return pycompat.sysbytes(name).replace(b'_', b'-')
277 277
278 278 previous = None
279 279 for x in args:
280 280 if opts.get(x):
281 281 if previous:
282 282 raise error.Abort(
283 283 _(b'cannot specify both --%s and --%s')
284 284 % (to_display(previous), to_display(x))
285 285 )
286 286 previous = x
287 287 return previous
288 288
289 289
290 290 def check_incompatible_arguments(opts, first, others):
291 291 """abort if the first argument is given along with any of the others
292 292
293 293 Unlike check_at_most_one_arg(), `others` are not mutually exclusive
294 294 among themselves, and they're passed as a single collection.
295 295 """
296 296 for other in others:
297 297 check_at_most_one_arg(opts, first, other)
298 298
299 299
300 300 def resolvecommitoptions(ui, opts):
301 301 """modify commit options dict to handle related options
302 302
303 303 The return value indicates that ``rewrite.update-timestamp`` is the reason
304 304 the ``date`` option is set.
305 305 """
306 306 check_at_most_one_arg(opts, b'date', b'currentdate')
307 307 check_at_most_one_arg(opts, b'user', b'currentuser')
308 308
309 309 datemaydiffer = False # date-only change should be ignored?
310 310
311 311 if opts.get(b'currentdate'):
312 312 opts[b'date'] = b'%d %d' % dateutil.makedate()
313 313 elif (
314 314 not opts.get(b'date')
315 315 and ui.configbool(b'rewrite', b'update-timestamp')
316 316 and opts.get(b'currentdate') is None
317 317 ):
318 318 opts[b'date'] = b'%d %d' % dateutil.makedate()
319 319 datemaydiffer = True
320 320
321 321 if opts.get(b'currentuser'):
322 322 opts[b'user'] = ui.username()
323 323
324 324 return datemaydiffer
325 325
326 326
327 327 def checknotesize(ui, opts):
328 328 """ make sure note is of valid format """
329 329
330 330 note = opts.get(b'note')
331 331 if not note:
332 332 return
333 333
334 334 if len(note) > 255:
335 335 raise error.Abort(_(b"cannot store a note of more than 255 bytes"))
336 336 if b'\n' in note:
337 337 raise error.Abort(_(b"note cannot contain a newline"))
338 338
339 339
340 340 def ishunk(x):
341 341 hunkclasses = (crecordmod.uihunk, patch.recordhunk)
342 342 return isinstance(x, hunkclasses)
343 343
344 344
345 345 def newandmodified(chunks, originalchunks):
346 346 newlyaddedandmodifiedfiles = set()
347 347 alsorestore = set()
348 348 for chunk in chunks:
349 349 if (
350 350 ishunk(chunk)
351 351 and chunk.header.isnewfile()
352 352 and chunk not in originalchunks
353 353 ):
354 354 newlyaddedandmodifiedfiles.add(chunk.header.filename())
355 355 alsorestore.update(
356 356 set(chunk.header.files()) - {chunk.header.filename()}
357 357 )
358 358 return newlyaddedandmodifiedfiles, alsorestore
359 359
360 360
361 361 def parsealiases(cmd):
362 362 return cmd.split(b"|")
363 363
364 364
365 365 def setupwrapcolorwrite(ui):
366 366 # wrap ui.write so diff output can be labeled/colorized
367 367 def wrapwrite(orig, *args, **kw):
368 368 label = kw.pop('label', b'')
369 369 for chunk, l in patch.difflabel(lambda: args):
370 370 orig(chunk, label=label + l)
371 371
372 372 oldwrite = ui.write
373 373
374 374 def wrap(*args, **kwargs):
375 375 return wrapwrite(oldwrite, *args, **kwargs)
376 376
377 377 setattr(ui, 'write', wrap)
378 378 return oldwrite
379 379
380 380
381 381 def filterchunks(ui, originalhunks, usecurses, testfile, match, operation=None):
382 382 try:
383 383 if usecurses:
384 384 if testfile:
385 385 recordfn = crecordmod.testdecorator(
386 386 testfile, crecordmod.testchunkselector
387 387 )
388 388 else:
389 389 recordfn = crecordmod.chunkselector
390 390
391 391 return crecordmod.filterpatch(
392 392 ui, originalhunks, recordfn, operation
393 393 )
394 394 except crecordmod.fallbackerror as e:
395 395 ui.warn(b'%s\n' % e)
396 396 ui.warn(_(b'falling back to text mode\n'))
397 397
398 398 return patch.filterpatch(ui, originalhunks, match, operation)
399 399
400 400
401 401 def recordfilter(ui, originalhunks, match, operation=None):
402 402 """ Prompts the user to filter the originalhunks and return a list of
403 403 selected hunks.
404 404 *operation* is used for to build ui messages to indicate the user what
405 405 kind of filtering they are doing: reverting, committing, shelving, etc.
406 406 (see patch.filterpatch).
407 407 """
408 408 usecurses = crecordmod.checkcurses(ui)
409 409 testfile = ui.config(b'experimental', b'crecordtest')
410 410 oldwrite = setupwrapcolorwrite(ui)
411 411 try:
412 412 newchunks, newopts = filterchunks(
413 413 ui, originalhunks, usecurses, testfile, match, operation
414 414 )
415 415 finally:
416 416 ui.write = oldwrite
417 417 return newchunks, newopts
418 418
419 419
420 420 def dorecord(
421 421 ui, repo, commitfunc, cmdsuggest, backupall, filterfn, *pats, **opts
422 422 ):
423 423 opts = pycompat.byteskwargs(opts)
424 424 if not ui.interactive():
425 425 if cmdsuggest:
426 426 msg = _(b'running non-interactively, use %s instead') % cmdsuggest
427 427 else:
428 428 msg = _(b'running non-interactively')
429 429 raise error.Abort(msg)
430 430
431 431 # make sure username is set before going interactive
432 432 if not opts.get(b'user'):
433 433 ui.username() # raise exception, username not provided
434 434
435 435 def recordfunc(ui, repo, message, match, opts):
436 436 """This is generic record driver.
437 437
438 438 Its job is to interactively filter local changes, and
439 439 accordingly prepare working directory into a state in which the
440 440 job can be delegated to a non-interactive commit command such as
441 441 'commit' or 'qrefresh'.
442 442
443 443 After the actual job is done by non-interactive command, the
444 444 working directory is restored to its original state.
445 445
446 446 In the end we'll record interesting changes, and everything else
447 447 will be left in place, so the user can continue working.
448 448 """
449 449 if not opts.get(b'interactive-unshelve'):
450 450 checkunfinished(repo, commit=True)
451 451 wctx = repo[None]
452 452 merge = len(wctx.parents()) > 1
453 453 if merge:
454 454 raise error.Abort(
455 455 _(
456 456 b'cannot partially commit a merge '
457 457 b'(use "hg commit" instead)'
458 458 )
459 459 )
460 460
461 461 def fail(f, msg):
462 462 raise error.Abort(b'%s: %s' % (f, msg))
463 463
464 464 force = opts.get(b'force')
465 465 if not force:
466 466 match = matchmod.badmatch(match, fail)
467 467
468 468 status = repo.status(match=match)
469 469
470 470 overrides = {(b'ui', b'commitsubrepos'): True}
471 471
472 472 with repo.ui.configoverride(overrides, b'record'):
473 473 # subrepoutil.precommit() modifies the status
474 474 tmpstatus = scmutil.status(
475 475 copymod.copy(status.modified),
476 476 copymod.copy(status.added),
477 477 copymod.copy(status.removed),
478 478 copymod.copy(status.deleted),
479 479 copymod.copy(status.unknown),
480 480 copymod.copy(status.ignored),
481 481 copymod.copy(status.clean), # pytype: disable=wrong-arg-count
482 482 )
483 483
484 484 # Force allows -X subrepo to skip the subrepo.
485 485 subs, commitsubs, newstate = subrepoutil.precommit(
486 486 repo.ui, wctx, tmpstatus, match, force=True
487 487 )
488 488 for s in subs:
489 489 if s in commitsubs:
490 490 dirtyreason = wctx.sub(s).dirtyreason(True)
491 491 raise error.Abort(dirtyreason)
492 492
493 493 if not force:
494 494 repo.checkcommitpatterns(wctx, match, status, fail)
495 495 diffopts = patch.difffeatureopts(
496 496 ui,
497 497 opts=opts,
498 498 whitespace=True,
499 499 section=b'commands',
500 500 configprefix=b'commit.interactive.',
501 501 )
502 502 diffopts.nodates = True
503 503 diffopts.git = True
504 504 diffopts.showfunc = True
505 505 originaldiff = patch.diff(repo, changes=status, opts=diffopts)
506 506 originalchunks = patch.parsepatch(originaldiff)
507 507 match = scmutil.match(repo[None], pats)
508 508
509 509 # 1. filter patch, since we are intending to apply subset of it
510 510 try:
511 511 chunks, newopts = filterfn(ui, originalchunks, match)
512 512 except error.PatchError as err:
513 513 raise error.Abort(_(b'error parsing patch: %s') % err)
514 514 opts.update(newopts)
515 515
516 516 # We need to keep a backup of files that have been newly added and
517 517 # modified during the recording process because there is a previous
518 518 # version without the edit in the workdir. We also will need to restore
519 519 # files that were the sources of renames so that the patch application
520 520 # works.
521 521 newlyaddedandmodifiedfiles, alsorestore = newandmodified(
522 522 chunks, originalchunks
523 523 )
524 524 contenders = set()
525 525 for h in chunks:
526 526 try:
527 527 contenders.update(set(h.files()))
528 528 except AttributeError:
529 529 pass
530 530
531 531 changed = status.modified + status.added + status.removed
532 532 newfiles = [f for f in changed if f in contenders]
533 533 if not newfiles:
534 534 ui.status(_(b'no changes to record\n'))
535 535 return 0
536 536
537 537 modified = set(status.modified)
538 538
539 539 # 2. backup changed files, so we can restore them in the end
540 540
541 541 if backupall:
542 542 tobackup = changed
543 543 else:
544 544 tobackup = [
545 545 f
546 546 for f in newfiles
547 547 if f in modified or f in newlyaddedandmodifiedfiles
548 548 ]
549 549 backups = {}
550 550 if tobackup:
551 551 backupdir = repo.vfs.join(b'record-backups')
552 552 try:
553 553 os.mkdir(backupdir)
554 554 except OSError as err:
555 555 if err.errno != errno.EEXIST:
556 556 raise
557 557 try:
558 558 # backup continues
559 559 for f in tobackup:
560 560 fd, tmpname = pycompat.mkstemp(
561 561 prefix=os.path.basename(f) + b'.', dir=backupdir
562 562 )
563 563 os.close(fd)
564 564 ui.debug(b'backup %r as %r\n' % (f, tmpname))
565 565 util.copyfile(repo.wjoin(f), tmpname, copystat=True)
566 566 backups[f] = tmpname
567 567
568 568 fp = stringio()
569 569 for c in chunks:
570 570 fname = c.filename()
571 571 if fname in backups:
572 572 c.write(fp)
573 573 dopatch = fp.tell()
574 574 fp.seek(0)
575 575
576 576 # 2.5 optionally review / modify patch in text editor
577 577 if opts.get(b'review', False):
578 578 patchtext = (
579 579 crecordmod.diffhelptext
580 580 + crecordmod.patchhelptext
581 581 + fp.read()
582 582 )
583 583 reviewedpatch = ui.edit(
584 584 patchtext, b"", action=b"diff", repopath=repo.path
585 585 )
586 586 fp.truncate(0)
587 587 fp.write(reviewedpatch)
588 588 fp.seek(0)
589 589
590 590 [os.unlink(repo.wjoin(c)) for c in newlyaddedandmodifiedfiles]
591 591 # 3a. apply filtered patch to clean repo (clean)
592 592 if backups:
593 593 m = scmutil.matchfiles(repo, set(backups.keys()) | alsorestore)
594 594 mergemod.revert_to(repo[b'.'], matcher=m)
595 595
596 596 # 3b. (apply)
597 597 if dopatch:
598 598 try:
599 599 ui.debug(b'applying patch\n')
600 600 ui.debug(fp.getvalue())
601 601 patch.internalpatch(ui, repo, fp, 1, eolmode=None)
602 602 except error.PatchError as err:
603 603 raise error.Abort(pycompat.bytestr(err))
604 604 del fp
605 605
606 606 # 4. We prepared working directory according to filtered
607 607 # patch. Now is the time to delegate the job to
608 608 # commit/qrefresh or the like!
609 609
610 610 # Make all of the pathnames absolute.
611 611 newfiles = [repo.wjoin(nf) for nf in newfiles]
612 612 return commitfunc(ui, repo, *newfiles, **pycompat.strkwargs(opts))
613 613 finally:
614 614 # 5. finally restore backed-up files
615 615 try:
616 616 dirstate = repo.dirstate
617 617 for realname, tmpname in pycompat.iteritems(backups):
618 618 ui.debug(b'restoring %r to %r\n' % (tmpname, realname))
619 619
620 620 if dirstate[realname] == b'n':
621 621 # without normallookup, restoring timestamp
622 622 # may cause partially committed files
623 623 # to be treated as unmodified
624 624 dirstate.normallookup(realname)
625 625
626 626 # copystat=True here and above are a hack to trick any
627 627 # editors that have f open that we haven't modified them.
628 628 #
629 629 # Also note that this racy as an editor could notice the
630 630 # file's mtime before we've finished writing it.
631 631 util.copyfile(tmpname, repo.wjoin(realname), copystat=True)
632 632 os.unlink(tmpname)
633 633 if tobackup:
634 634 os.rmdir(backupdir)
635 635 except OSError:
636 636 pass
637 637
638 638 def recordinwlock(ui, repo, message, match, opts):
639 639 with repo.wlock():
640 640 return recordfunc(ui, repo, message, match, opts)
641 641
642 642 return commit(ui, repo, recordinwlock, pats, opts)
643 643
644 644
645 645 class dirnode(object):
646 646 """
647 647 Represent a directory in user working copy with information required for
648 648 the purpose of tersing its status.
649 649
650 650 path is the path to the directory, without a trailing '/'
651 651
652 652 statuses is a set of statuses of all files in this directory (this includes
653 653 all the files in all the subdirectories too)
654 654
655 655 files is a list of files which are direct child of this directory
656 656
657 657 subdirs is a dictionary of sub-directory name as the key and it's own
658 658 dirnode object as the value
659 659 """
660 660
661 661 def __init__(self, dirpath):
662 662 self.path = dirpath
663 663 self.statuses = set()
664 664 self.files = []
665 665 self.subdirs = {}
666 666
667 667 def _addfileindir(self, filename, status):
668 668 """Add a file in this directory as a direct child."""
669 669 self.files.append((filename, status))
670 670
671 671 def addfile(self, filename, status):
672 672 """
673 673 Add a file to this directory or to its direct parent directory.
674 674
675 675 If the file is not direct child of this directory, we traverse to the
676 676 directory of which this file is a direct child of and add the file
677 677 there.
678 678 """
679 679
680 680 # the filename contains a path separator, it means it's not the direct
681 681 # child of this directory
682 682 if b'/' in filename:
683 683 subdir, filep = filename.split(b'/', 1)
684 684
685 685 # does the dirnode object for subdir exists
686 686 if subdir not in self.subdirs:
687 687 subdirpath = pathutil.join(self.path, subdir)
688 688 self.subdirs[subdir] = dirnode(subdirpath)
689 689
690 690 # try adding the file in subdir
691 691 self.subdirs[subdir].addfile(filep, status)
692 692
693 693 else:
694 694 self._addfileindir(filename, status)
695 695
696 696 if status not in self.statuses:
697 697 self.statuses.add(status)
698 698
699 699 def iterfilepaths(self):
700 700 """Yield (status, path) for files directly under this directory."""
701 701 for f, st in self.files:
702 702 yield st, pathutil.join(self.path, f)
703 703
704 704 def tersewalk(self, terseargs):
705 705 """
706 706 Yield (status, path) obtained by processing the status of this
707 707 dirnode.
708 708
709 709 terseargs is the string of arguments passed by the user with `--terse`
710 710 flag.
711 711
712 712 Following are the cases which can happen:
713 713
714 714 1) All the files in the directory (including all the files in its
715 715 subdirectories) share the same status and the user has asked us to terse
716 716 that status. -> yield (status, dirpath). dirpath will end in '/'.
717 717
718 718 2) Otherwise, we do following:
719 719
720 720 a) Yield (status, filepath) for all the files which are in this
721 721 directory (only the ones in this directory, not the subdirs)
722 722
723 723 b) Recurse the function on all the subdirectories of this
724 724 directory
725 725 """
726 726
727 727 if len(self.statuses) == 1:
728 728 onlyst = self.statuses.pop()
729 729
730 730 # Making sure we terse only when the status abbreviation is
731 731 # passed as terse argument
732 732 if onlyst in terseargs:
733 733 yield onlyst, self.path + b'/'
734 734 return
735 735
736 736 # add the files to status list
737 737 for st, fpath in self.iterfilepaths():
738 738 yield st, fpath
739 739
740 740 # recurse on the subdirs
741 741 for dirobj in self.subdirs.values():
742 742 for st, fpath in dirobj.tersewalk(terseargs):
743 743 yield st, fpath
744 744
745 745
746 746 def tersedir(statuslist, terseargs):
747 747 """
748 748 Terse the status if all the files in a directory shares the same status.
749 749
750 750 statuslist is scmutil.status() object which contains a list of files for
751 751 each status.
752 752 terseargs is string which is passed by the user as the argument to `--terse`
753 753 flag.
754 754
755 755 The function makes a tree of objects of dirnode class, and at each node it
756 756 stores the information required to know whether we can terse a certain
757 757 directory or not.
758 758 """
759 759 # the order matters here as that is used to produce final list
760 760 allst = (b'm', b'a', b'r', b'd', b'u', b'i', b'c')
761 761
762 762 # checking the argument validity
763 763 for s in pycompat.bytestr(terseargs):
764 764 if s not in allst:
765 765 raise error.Abort(_(b"'%s' not recognized") % s)
766 766
767 767 # creating a dirnode object for the root of the repo
768 768 rootobj = dirnode(b'')
769 769 pstatus = (
770 770 b'modified',
771 771 b'added',
772 772 b'deleted',
773 773 b'clean',
774 774 b'unknown',
775 775 b'ignored',
776 776 b'removed',
777 777 )
778 778
779 779 tersedict = {}
780 780 for attrname in pstatus:
781 781 statuschar = attrname[0:1]
782 782 for f in getattr(statuslist, attrname):
783 783 rootobj.addfile(f, statuschar)
784 784 tersedict[statuschar] = []
785 785
786 786 # we won't be tersing the root dir, so add files in it
787 787 for st, fpath in rootobj.iterfilepaths():
788 788 tersedict[st].append(fpath)
789 789
790 790 # process each sub-directory and build tersedict
791 791 for subdir in rootobj.subdirs.values():
792 792 for st, f in subdir.tersewalk(terseargs):
793 793 tersedict[st].append(f)
794 794
795 795 tersedlist = []
796 796 for st in allst:
797 797 tersedict[st].sort()
798 798 tersedlist.append(tersedict[st])
799 799
800 800 return scmutil.status(*tersedlist)
801 801
802 802
803 803 def _commentlines(raw):
804 804 '''Surround lineswith a comment char and a new line'''
805 805 lines = raw.splitlines()
806 806 commentedlines = [b'# %s' % line for line in lines]
807 807 return b'\n'.join(commentedlines) + b'\n'
808 808
809 809
810 810 @attr.s(frozen=True)
811 811 class morestatus(object):
812 812 reporoot = attr.ib()
813 813 unfinishedop = attr.ib()
814 814 unfinishedmsg = attr.ib()
815 815 activemerge = attr.ib()
816 816 unresolvedpaths = attr.ib()
817 817 _formattedpaths = attr.ib(init=False, default=set())
818 818 _label = b'status.morestatus'
819 819
820 820 def formatfile(self, path, fm):
821 821 self._formattedpaths.add(path)
822 822 if self.activemerge and path in self.unresolvedpaths:
823 823 fm.data(unresolved=True)
824 824
825 825 def formatfooter(self, fm):
826 826 if self.unfinishedop or self.unfinishedmsg:
827 827 fm.startitem()
828 828 fm.data(itemtype=b'morestatus')
829 829
830 830 if self.unfinishedop:
831 831 fm.data(unfinished=self.unfinishedop)
832 832 statemsg = (
833 833 _(b'The repository is in an unfinished *%s* state.')
834 834 % self.unfinishedop
835 835 )
836 836 fm.plain(b'%s\n' % _commentlines(statemsg), label=self._label)
837 837 if self.unfinishedmsg:
838 838 fm.data(unfinishedmsg=self.unfinishedmsg)
839 839
840 840 # May also start new data items.
841 841 self._formatconflicts(fm)
842 842
843 843 if self.unfinishedmsg:
844 844 fm.plain(
845 845 b'%s\n' % _commentlines(self.unfinishedmsg), label=self._label
846 846 )
847 847
848 848 def _formatconflicts(self, fm):
849 849 if not self.activemerge:
850 850 return
851 851
852 852 if self.unresolvedpaths:
853 853 mergeliststr = b'\n'.join(
854 854 [
855 855 b' %s'
856 856 % util.pathto(self.reporoot, encoding.getcwd(), path)
857 857 for path in self.unresolvedpaths
858 858 ]
859 859 )
860 860 msg = (
861 861 _(
862 862 '''Unresolved merge conflicts:
863 863
864 864 %s
865 865
866 866 To mark files as resolved: hg resolve --mark FILE'''
867 867 )
868 868 % mergeliststr
869 869 )
870 870
871 871 # If any paths with unresolved conflicts were not previously
872 872 # formatted, output them now.
873 873 for f in self.unresolvedpaths:
874 874 if f in self._formattedpaths:
875 875 # Already output.
876 876 continue
877 877 fm.startitem()
878 878 # We can't claim to know the status of the file - it may just
879 879 # have been in one of the states that were not requested for
880 880 # display, so it could be anything.
881 881 fm.data(itemtype=b'file', path=f, unresolved=True)
882 882
883 883 else:
884 884 msg = _(b'No unresolved merge conflicts.')
885 885
886 886 fm.plain(b'%s\n' % _commentlines(msg), label=self._label)
887 887
888 888
889 889 def readmorestatus(repo):
890 890 """Returns a morestatus object if the repo has unfinished state."""
891 891 statetuple = statemod.getrepostate(repo)
892 892 mergestate = mergestatemod.mergestate.read(repo)
893 893 activemerge = mergestate.active()
894 894 if not statetuple and not activemerge:
895 895 return None
896 896
897 897 unfinishedop = unfinishedmsg = unresolved = None
898 898 if statetuple:
899 899 unfinishedop, unfinishedmsg = statetuple
900 900 if activemerge:
901 901 unresolved = sorted(mergestate.unresolved())
902 902 return morestatus(
903 903 repo.root, unfinishedop, unfinishedmsg, activemerge, unresolved
904 904 )
905 905
906 906
907 907 def findpossible(cmd, table, strict=False):
908 908 """
909 909 Return cmd -> (aliases, command table entry)
910 910 for each matching command.
911 911 Return debug commands (or their aliases) only if no normal command matches.
912 912 """
913 913 choice = {}
914 914 debugchoice = {}
915 915
916 916 if cmd in table:
917 917 # short-circuit exact matches, "log" alias beats "log|history"
918 918 keys = [cmd]
919 919 else:
920 920 keys = table.keys()
921 921
922 922 allcmds = []
923 923 for e in keys:
924 924 aliases = parsealiases(e)
925 925 allcmds.extend(aliases)
926 926 found = None
927 927 if cmd in aliases:
928 928 found = cmd
929 929 elif not strict:
930 930 for a in aliases:
931 931 if a.startswith(cmd):
932 932 found = a
933 933 break
934 934 if found is not None:
935 935 if aliases[0].startswith(b"debug") or found.startswith(b"debug"):
936 936 debugchoice[found] = (aliases, table[e])
937 937 else:
938 938 choice[found] = (aliases, table[e])
939 939
940 940 if not choice and debugchoice:
941 941 choice = debugchoice
942 942
943 943 return choice, allcmds
944 944
945 945
946 946 def findcmd(cmd, table, strict=True):
947 947 """Return (aliases, command table entry) for command string."""
948 948 choice, allcmds = findpossible(cmd, table, strict)
949 949
950 950 if cmd in choice:
951 951 return choice[cmd]
952 952
953 953 if len(choice) > 1:
954 954 clist = sorted(choice)
955 955 raise error.AmbiguousCommand(cmd, clist)
956 956
957 957 if choice:
958 958 return list(choice.values())[0]
959 959
960 960 raise error.UnknownCommand(cmd, allcmds)
961 961
962 962
963 963 def changebranch(ui, repo, revs, label, opts):
964 964 """ Change the branch name of given revs to label """
965 965
966 966 with repo.wlock(), repo.lock(), repo.transaction(b'branches'):
967 967 # abort in case of uncommitted merge or dirty wdir
968 968 bailifchanged(repo)
969 969 revs = scmutil.revrange(repo, revs)
970 970 if not revs:
971 971 raise error.Abort(b"empty revision set")
972 972 roots = repo.revs(b'roots(%ld)', revs)
973 973 if len(roots) > 1:
974 974 raise error.Abort(
975 975 _(b"cannot change branch of non-linear revisions")
976 976 )
977 977 rewriteutil.precheck(repo, revs, b'change branch of')
978 978
979 979 root = repo[roots.first()]
980 980 rpb = {parent.branch() for parent in root.parents()}
981 981 if (
982 982 not opts.get(b'force')
983 983 and label not in rpb
984 984 and label in repo.branchmap()
985 985 ):
986 986 raise error.Abort(_(b"a branch of the same name already exists"))
987 987
988 988 if repo.revs(b'obsolete() and %ld', revs):
989 989 raise error.Abort(
990 990 _(b"cannot change branch of a obsolete changeset")
991 991 )
992 992
993 993 # make sure only topological heads
994 994 if repo.revs(b'heads(%ld) - head()', revs):
995 995 raise error.Abort(_(b"cannot change branch in middle of a stack"))
996 996
997 997 replacements = {}
998 998 # avoid import cycle mercurial.cmdutil -> mercurial.context ->
999 999 # mercurial.subrepo -> mercurial.cmdutil
1000 1000 from . import context
1001 1001
1002 1002 for rev in revs:
1003 1003 ctx = repo[rev]
1004 1004 oldbranch = ctx.branch()
1005 1005 # check if ctx has same branch
1006 1006 if oldbranch == label:
1007 1007 continue
1008 1008
1009 1009 def filectxfn(repo, newctx, path):
1010 1010 try:
1011 1011 return ctx[path]
1012 1012 except error.ManifestLookupError:
1013 1013 return None
1014 1014
1015 1015 ui.debug(
1016 1016 b"changing branch of '%s' from '%s' to '%s'\n"
1017 1017 % (hex(ctx.node()), oldbranch, label)
1018 1018 )
1019 1019 extra = ctx.extra()
1020 1020 extra[b'branch_change'] = hex(ctx.node())
1021 1021 # While changing branch of set of linear commits, make sure that
1022 1022 # we base our commits on new parent rather than old parent which
1023 1023 # was obsoleted while changing the branch
1024 1024 p1 = ctx.p1().node()
1025 1025 p2 = ctx.p2().node()
1026 1026 if p1 in replacements:
1027 1027 p1 = replacements[p1][0]
1028 1028 if p2 in replacements:
1029 1029 p2 = replacements[p2][0]
1030 1030
1031 1031 mc = context.memctx(
1032 1032 repo,
1033 1033 (p1, p2),
1034 1034 ctx.description(),
1035 1035 ctx.files(),
1036 1036 filectxfn,
1037 1037 user=ctx.user(),
1038 1038 date=ctx.date(),
1039 1039 extra=extra,
1040 1040 branch=label,
1041 1041 )
1042 1042
1043 1043 newnode = repo.commitctx(mc)
1044 1044 replacements[ctx.node()] = (newnode,)
1045 1045 ui.debug(b'new node id is %s\n' % hex(newnode))
1046 1046
1047 1047 # create obsmarkers and move bookmarks
1048 1048 scmutil.cleanupnodes(
1049 1049 repo, replacements, b'branch-change', fixphase=True
1050 1050 )
1051 1051
1052 1052 # move the working copy too
1053 1053 wctx = repo[None]
1054 1054 # in-progress merge is a bit too complex for now.
1055 1055 if len(wctx.parents()) == 1:
1056 1056 newid = replacements.get(wctx.p1().node())
1057 1057 if newid is not None:
1058 1058 # avoid import cycle mercurial.cmdutil -> mercurial.hg ->
1059 1059 # mercurial.cmdutil
1060 1060 from . import hg
1061 1061
1062 1062 hg.update(repo, newid[0], quietempty=True)
1063 1063
1064 1064 ui.status(_(b"changed branch on %d changesets\n") % len(replacements))
1065 1065
1066 1066
1067 1067 def findrepo(p):
1068 1068 while not os.path.isdir(os.path.join(p, b".hg")):
1069 1069 oldp, p = p, os.path.dirname(p)
1070 1070 if p == oldp:
1071 1071 return None
1072 1072
1073 1073 return p
1074 1074
1075 1075
1076 1076 def bailifchanged(repo, merge=True, hint=None):
1077 1077 """ enforce the precondition that working directory must be clean.
1078 1078
1079 1079 'merge' can be set to false if a pending uncommitted merge should be
1080 1080 ignored (such as when 'update --check' runs).
1081 1081
1082 1082 'hint' is the usual hint given to Abort exception.
1083 1083 """
1084 1084
1085 1085 if merge and repo.dirstate.p2() != nullid:
1086 1086 raise error.Abort(_(b'outstanding uncommitted merge'), hint=hint)
1087 1087 st = repo.status()
1088 1088 if st.modified or st.added or st.removed or st.deleted:
1089 1089 raise error.Abort(_(b'uncommitted changes'), hint=hint)
1090 1090 ctx = repo[None]
1091 1091 for s in sorted(ctx.substate):
1092 1092 ctx.sub(s).bailifchanged(hint=hint)
1093 1093
1094 1094
1095 1095 def logmessage(ui, opts):
1096 1096 """ get the log message according to -m and -l option """
1097 1097
1098 1098 check_at_most_one_arg(opts, b'message', b'logfile')
1099 1099
1100 1100 message = opts.get(b'message')
1101 1101 logfile = opts.get(b'logfile')
1102 1102
1103 1103 if not message and logfile:
1104 1104 try:
1105 1105 if isstdiofilename(logfile):
1106 1106 message = ui.fin.read()
1107 1107 else:
1108 1108 message = b'\n'.join(util.readfile(logfile).splitlines())
1109 1109 except IOError as inst:
1110 1110 raise error.Abort(
1111 1111 _(b"can't read commit message '%s': %s")
1112 1112 % (logfile, encoding.strtolocal(inst.strerror))
1113 1113 )
1114 1114 return message
1115 1115
1116 1116
1117 1117 def mergeeditform(ctxorbool, baseformname):
1118 1118 """return appropriate editform name (referencing a committemplate)
1119 1119
1120 1120 'ctxorbool' is either a ctx to be committed, or a bool indicating whether
1121 1121 merging is committed.
1122 1122
1123 1123 This returns baseformname with '.merge' appended if it is a merge,
1124 1124 otherwise '.normal' is appended.
1125 1125 """
1126 1126 if isinstance(ctxorbool, bool):
1127 1127 if ctxorbool:
1128 1128 return baseformname + b".merge"
1129 1129 elif len(ctxorbool.parents()) > 1:
1130 1130 return baseformname + b".merge"
1131 1131
1132 1132 return baseformname + b".normal"
1133 1133
1134 1134
1135 1135 def getcommiteditor(
1136 1136 edit=False, finishdesc=None, extramsg=None, editform=b'', **opts
1137 1137 ):
1138 1138 """get appropriate commit message editor according to '--edit' option
1139 1139
1140 1140 'finishdesc' is a function to be called with edited commit message
1141 1141 (= 'description' of the new changeset) just after editing, but
1142 1142 before checking empty-ness. It should return actual text to be
1143 1143 stored into history. This allows to change description before
1144 1144 storing.
1145 1145
1146 1146 'extramsg' is a extra message to be shown in the editor instead of
1147 1147 'Leave message empty to abort commit' line. 'HG: ' prefix and EOL
1148 1148 is automatically added.
1149 1149
1150 1150 'editform' is a dot-separated list of names, to distinguish
1151 1151 the purpose of commit text editing.
1152 1152
1153 1153 'getcommiteditor' returns 'commitforceeditor' regardless of
1154 1154 'edit', if one of 'finishdesc' or 'extramsg' is specified, because
1155 1155 they are specific for usage in MQ.
1156 1156 """
1157 1157 if edit or finishdesc or extramsg:
1158 1158 return lambda r, c, s: commitforceeditor(
1159 1159 r, c, s, finishdesc=finishdesc, extramsg=extramsg, editform=editform
1160 1160 )
1161 1161 elif editform:
1162 1162 return lambda r, c, s: commiteditor(r, c, s, editform=editform)
1163 1163 else:
1164 1164 return commiteditor
1165 1165
1166 1166
1167 1167 def _escapecommandtemplate(tmpl):
1168 1168 parts = []
1169 1169 for typ, start, end in templater.scantemplate(tmpl, raw=True):
1170 1170 if typ == b'string':
1171 1171 parts.append(stringutil.escapestr(tmpl[start:end]))
1172 1172 else:
1173 1173 parts.append(tmpl[start:end])
1174 1174 return b''.join(parts)
1175 1175
1176 1176
1177 1177 def rendercommandtemplate(ui, tmpl, props):
1178 1178 r"""Expand a literal template 'tmpl' in a way suitable for command line
1179 1179
1180 1180 '\' in outermost string is not taken as an escape character because it
1181 1181 is a directory separator on Windows.
1182 1182
1183 1183 >>> from . import ui as uimod
1184 1184 >>> ui = uimod.ui()
1185 1185 >>> rendercommandtemplate(ui, b'c:\\{path}', {b'path': b'foo'})
1186 1186 'c:\\foo'
1187 1187 >>> rendercommandtemplate(ui, b'{"c:\\{path}"}', {'path': b'foo'})
1188 1188 'c:{path}'
1189 1189 """
1190 1190 if not tmpl:
1191 1191 return tmpl
1192 1192 t = formatter.maketemplater(ui, _escapecommandtemplate(tmpl))
1193 1193 return t.renderdefault(props)
1194 1194
1195 1195
1196 1196 def rendertemplate(ctx, tmpl, props=None):
1197 1197 """Expand a literal template 'tmpl' byte-string against one changeset
1198 1198
1199 1199 Each props item must be a stringify-able value or a callable returning
1200 1200 such value, i.e. no bare list nor dict should be passed.
1201 1201 """
1202 1202 repo = ctx.repo()
1203 1203 tres = formatter.templateresources(repo.ui, repo)
1204 1204 t = formatter.maketemplater(
1205 1205 repo.ui, tmpl, defaults=templatekw.keywords, resources=tres
1206 1206 )
1207 1207 mapping = {b'ctx': ctx}
1208 1208 if props:
1209 1209 mapping.update(props)
1210 1210 return t.renderdefault(mapping)
1211 1211
1212 1212
1213 1213 def _buildfntemplate(pat, total=None, seqno=None, revwidth=None, pathname=None):
1214 1214 r"""Convert old-style filename format string to template string
1215 1215
1216 1216 >>> _buildfntemplate(b'foo-%b-%n.patch', seqno=0)
1217 1217 'foo-{reporoot|basename}-{seqno}.patch'
1218 1218 >>> _buildfntemplate(b'%R{tags % "{tag}"}%H')
1219 1219 '{rev}{tags % "{tag}"}{node}'
1220 1220
1221 1221 '\' in outermost strings has to be escaped because it is a directory
1222 1222 separator on Windows:
1223 1223
1224 1224 >>> _buildfntemplate(b'c:\\tmp\\%R\\%n.patch', seqno=0)
1225 1225 'c:\\\\tmp\\\\{rev}\\\\{seqno}.patch'
1226 1226 >>> _buildfntemplate(b'\\\\foo\\bar.patch')
1227 1227 '\\\\\\\\foo\\\\bar.patch'
1228 1228 >>> _buildfntemplate(b'\\{tags % "{tag}"}')
1229 1229 '\\\\{tags % "{tag}"}'
1230 1230
1231 1231 but inner strings follow the template rules (i.e. '\' is taken as an
1232 1232 escape character):
1233 1233
1234 1234 >>> _buildfntemplate(br'{"c:\tmp"}', seqno=0)
1235 1235 '{"c:\\tmp"}'
1236 1236 """
1237 1237 expander = {
1238 1238 b'H': b'{node}',
1239 1239 b'R': b'{rev}',
1240 1240 b'h': b'{node|short}',
1241 1241 b'm': br'{sub(r"[^\w]", "_", desc|firstline)}',
1242 1242 b'r': b'{if(revwidth, pad(rev, revwidth, "0", left=True), rev)}',
1243 1243 b'%': b'%',
1244 1244 b'b': b'{reporoot|basename}',
1245 1245 }
1246 1246 if total is not None:
1247 1247 expander[b'N'] = b'{total}'
1248 1248 if seqno is not None:
1249 1249 expander[b'n'] = b'{seqno}'
1250 1250 if total is not None and seqno is not None:
1251 1251 expander[b'n'] = b'{pad(seqno, total|stringify|count, "0", left=True)}'
1252 1252 if pathname is not None:
1253 1253 expander[b's'] = b'{pathname|basename}'
1254 1254 expander[b'd'] = b'{if(pathname|dirname, pathname|dirname, ".")}'
1255 1255 expander[b'p'] = b'{pathname}'
1256 1256
1257 1257 newname = []
1258 1258 for typ, start, end in templater.scantemplate(pat, raw=True):
1259 1259 if typ != b'string':
1260 1260 newname.append(pat[start:end])
1261 1261 continue
1262 1262 i = start
1263 1263 while i < end:
1264 1264 n = pat.find(b'%', i, end)
1265 1265 if n < 0:
1266 1266 newname.append(stringutil.escapestr(pat[i:end]))
1267 1267 break
1268 1268 newname.append(stringutil.escapestr(pat[i:n]))
1269 1269 if n + 2 > end:
1270 1270 raise error.Abort(
1271 1271 _(b"incomplete format spec in output filename")
1272 1272 )
1273 1273 c = pat[n + 1 : n + 2]
1274 1274 i = n + 2
1275 1275 try:
1276 1276 newname.append(expander[c])
1277 1277 except KeyError:
1278 1278 raise error.Abort(
1279 1279 _(b"invalid format spec '%%%s' in output filename") % c
1280 1280 )
1281 1281 return b''.join(newname)
1282 1282
1283 1283
1284 1284 def makefilename(ctx, pat, **props):
1285 1285 if not pat:
1286 1286 return pat
1287 1287 tmpl = _buildfntemplate(pat, **props)
1288 1288 # BUG: alias expansion shouldn't be made against template fragments
1289 1289 # rewritten from %-format strings, but we have no easy way to partially
1290 1290 # disable the expansion.
1291 1291 return rendertemplate(ctx, tmpl, pycompat.byteskwargs(props))
1292 1292
1293 1293
1294 1294 def isstdiofilename(pat):
1295 1295 """True if the given pat looks like a filename denoting stdin/stdout"""
1296 1296 return not pat or pat == b'-'
1297 1297
1298 1298
1299 1299 class _unclosablefile(object):
1300 1300 def __init__(self, fp):
1301 1301 self._fp = fp
1302 1302
1303 1303 def close(self):
1304 1304 pass
1305 1305
1306 1306 def __iter__(self):
1307 1307 return iter(self._fp)
1308 1308
1309 1309 def __getattr__(self, attr):
1310 1310 return getattr(self._fp, attr)
1311 1311
1312 1312 def __enter__(self):
1313 1313 return self
1314 1314
1315 1315 def __exit__(self, exc_type, exc_value, exc_tb):
1316 1316 pass
1317 1317
1318 1318
1319 1319 def makefileobj(ctx, pat, mode=b'wb', **props):
1320 1320 writable = mode not in (b'r', b'rb')
1321 1321
1322 1322 if isstdiofilename(pat):
1323 1323 repo = ctx.repo()
1324 1324 if writable:
1325 1325 fp = repo.ui.fout
1326 1326 else:
1327 1327 fp = repo.ui.fin
1328 1328 return _unclosablefile(fp)
1329 1329 fn = makefilename(ctx, pat, **props)
1330 1330 return open(fn, mode)
1331 1331
1332 1332
1333 1333 def openstorage(repo, cmd, file_, opts, returnrevlog=False):
1334 1334 """opens the changelog, manifest, a filelog or a given revlog"""
1335 1335 cl = opts[b'changelog']
1336 1336 mf = opts[b'manifest']
1337 1337 dir = opts[b'dir']
1338 1338 msg = None
1339 1339 if cl and mf:
1340 1340 msg = _(b'cannot specify --changelog and --manifest at the same time')
1341 1341 elif cl and dir:
1342 1342 msg = _(b'cannot specify --changelog and --dir at the same time')
1343 1343 elif cl or mf or dir:
1344 1344 if file_:
1345 1345 msg = _(b'cannot specify filename with --changelog or --manifest')
1346 1346 elif not repo:
1347 1347 msg = _(
1348 1348 b'cannot specify --changelog or --manifest or --dir '
1349 1349 b'without a repository'
1350 1350 )
1351 1351 if msg:
1352 1352 raise error.Abort(msg)
1353 1353
1354 1354 r = None
1355 1355 if repo:
1356 1356 if cl:
1357 1357 r = repo.unfiltered().changelog
1358 1358 elif dir:
1359 1359 if not scmutil.istreemanifest(repo):
1360 1360 raise error.Abort(
1361 1361 _(
1362 1362 b"--dir can only be used on repos with "
1363 1363 b"treemanifest enabled"
1364 1364 )
1365 1365 )
1366 1366 if not dir.endswith(b'/'):
1367 1367 dir = dir + b'/'
1368 1368 dirlog = repo.manifestlog.getstorage(dir)
1369 1369 if len(dirlog):
1370 1370 r = dirlog
1371 1371 elif mf:
1372 1372 r = repo.manifestlog.getstorage(b'')
1373 1373 elif file_:
1374 1374 filelog = repo.file(file_)
1375 1375 if len(filelog):
1376 1376 r = filelog
1377 1377
1378 1378 # Not all storage may be revlogs. If requested, try to return an actual
1379 1379 # revlog instance.
1380 1380 if returnrevlog:
1381 1381 if isinstance(r, revlog.revlog):
1382 1382 pass
1383 1383 elif util.safehasattr(r, b'_revlog'):
1384 1384 r = r._revlog # pytype: disable=attribute-error
1385 1385 elif r is not None:
1386 1386 raise error.Abort(_(b'%r does not appear to be a revlog') % r)
1387 1387
1388 1388 if not r:
1389 1389 if not returnrevlog:
1390 1390 raise error.Abort(_(b'cannot give path to non-revlog'))
1391 1391
1392 1392 if not file_:
1393 1393 raise error.CommandError(cmd, _(b'invalid arguments'))
1394 1394 if not os.path.isfile(file_):
1395 1395 raise error.Abort(_(b"revlog '%s' not found") % file_)
1396 1396 r = revlog.revlog(
1397 1397 vfsmod.vfs(encoding.getcwd(), audit=False), file_[:-2] + b".i"
1398 1398 )
1399 1399 return r
1400 1400
1401 1401
1402 1402 def openrevlog(repo, cmd, file_, opts):
1403 1403 """Obtain a revlog backing storage of an item.
1404 1404
1405 1405 This is similar to ``openstorage()`` except it always returns a revlog.
1406 1406
1407 1407 In most cases, a caller cares about the main storage object - not the
1408 1408 revlog backing it. Therefore, this function should only be used by code
1409 1409 that needs to examine low-level revlog implementation details. e.g. debug
1410 1410 commands.
1411 1411 """
1412 1412 return openstorage(repo, cmd, file_, opts, returnrevlog=True)
1413 1413
1414 1414
1415 1415 def copy(ui, repo, pats, opts, rename=False):
1416 1416 check_incompatible_arguments(opts, b'forget', [b'dry_run'])
1417 1417
1418 1418 # called with the repo lock held
1419 1419 #
1420 1420 # hgsep => pathname that uses "/" to separate directories
1421 1421 # ossep => pathname that uses os.sep to separate directories
1422 1422 cwd = repo.getcwd()
1423 1423 targets = {}
1424 1424 forget = opts.get(b"forget")
1425 1425 after = opts.get(b"after")
1426 1426 dryrun = opts.get(b"dry_run")
1427 1427 rev = opts.get(b'at_rev')
1428 1428 if rev:
1429 1429 if not forget and not after:
1430 1430 # TODO: Remove this restriction and make it also create the copy
1431 1431 # targets (and remove the rename source if rename==True).
1432 1432 raise error.Abort(_(b'--at-rev requires --after'))
1433 1433 ctx = scmutil.revsingle(repo, rev)
1434 1434 if len(ctx.parents()) > 1:
1435 1435 raise error.Abort(_(b'cannot mark/unmark copy in merge commit'))
1436 1436 else:
1437 1437 ctx = repo[None]
1438 1438
1439 1439 pctx = ctx.p1()
1440 1440
1441 1441 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
1442 1442
1443 1443 if forget:
1444 1444 if ctx.rev() is None:
1445 1445 new_ctx = ctx
1446 1446 else:
1447 1447 if len(ctx.parents()) > 1:
1448 1448 raise error.Abort(_(b'cannot unmark copy in merge commit'))
1449 1449 # avoid cycle context -> subrepo -> cmdutil
1450 1450 from . import context
1451 1451
1452 1452 rewriteutil.precheck(repo, [ctx.rev()], b'uncopy')
1453 1453 new_ctx = context.overlayworkingctx(repo)
1454 1454 new_ctx.setbase(ctx.p1())
1455 1455 mergemod.graft(repo, ctx, wctx=new_ctx)
1456 1456
1457 1457 match = scmutil.match(ctx, pats, opts)
1458 1458
1459 1459 current_copies = ctx.p1copies()
1460 1460 current_copies.update(ctx.p2copies())
1461 1461
1462 1462 uipathfn = scmutil.getuipathfn(repo)
1463 1463 for f in ctx.walk(match):
1464 1464 if f in current_copies:
1465 1465 new_ctx[f].markcopied(None)
1466 1466 elif match.exact(f):
1467 1467 ui.warn(
1468 1468 _(
1469 1469 b'%s: not unmarking as copy - file is not marked as copied\n'
1470 1470 )
1471 1471 % uipathfn(f)
1472 1472 )
1473 1473
1474 1474 if ctx.rev() is not None:
1475 1475 with repo.lock():
1476 1476 mem_ctx = new_ctx.tomemctx_for_amend(ctx)
1477 1477 new_node = mem_ctx.commit()
1478 1478
1479 1479 if repo.dirstate.p1() == ctx.node():
1480 1480 with repo.dirstate.parentchange():
1481 1481 scmutil.movedirstate(repo, repo[new_node])
1482 1482 replacements = {ctx.node(): [new_node]}
1483 1483 scmutil.cleanupnodes(
1484 1484 repo, replacements, b'uncopy', fixphase=True
1485 1485 )
1486 1486
1487 1487 return
1488 1488
1489 1489 pats = scmutil.expandpats(pats)
1490 1490 if not pats:
1491 1491 raise error.Abort(_(b'no source or destination specified'))
1492 1492 if len(pats) == 1:
1493 1493 raise error.Abort(_(b'no destination specified'))
1494 1494 dest = pats.pop()
1495 1495
1496 1496 def walkpat(pat):
1497 1497 srcs = []
1498 1498 # TODO: Inline and simplify the non-working-copy version of this code
1499 1499 # since it shares very little with the working-copy version of it.
1500 1500 ctx_to_walk = ctx if ctx.rev() is None else pctx
1501 1501 m = scmutil.match(ctx_to_walk, [pat], opts, globbed=True)
1502 1502 for abs in ctx_to_walk.walk(m):
1503 1503 rel = uipathfn(abs)
1504 1504 exact = m.exact(abs)
1505 1505 if abs not in ctx:
1506 1506 if abs in pctx:
1507 1507 if not after:
1508 1508 if exact:
1509 1509 ui.warn(
1510 1510 _(
1511 1511 b'%s: not copying - file has been marked '
1512 1512 b'for remove\n'
1513 1513 )
1514 1514 % rel
1515 1515 )
1516 1516 continue
1517 1517 else:
1518 1518 if exact:
1519 1519 ui.warn(
1520 1520 _(b'%s: not copying - file is not managed\n') % rel
1521 1521 )
1522 1522 continue
1523 1523
1524 1524 # abs: hgsep
1525 1525 # rel: ossep
1526 1526 srcs.append((abs, rel, exact))
1527 1527 return srcs
1528 1528
1529 1529 if ctx.rev() is not None:
1530 1530 rewriteutil.precheck(repo, [ctx.rev()], b'uncopy')
1531 1531 absdest = pathutil.canonpath(repo.root, cwd, dest)
1532 1532 if ctx.hasdir(absdest):
1533 1533 raise error.Abort(
1534 1534 _(b'%s: --at-rev does not support a directory as destination')
1535 1535 % uipathfn(absdest)
1536 1536 )
1537 1537 if absdest not in ctx:
1538 1538 raise error.Abort(
1539 1539 _(b'%s: copy destination does not exist in %s')
1540 1540 % (uipathfn(absdest), ctx)
1541 1541 )
1542 1542
1543 1543 # avoid cycle context -> subrepo -> cmdutil
1544 1544 from . import context
1545 1545
1546 1546 copylist = []
1547 1547 for pat in pats:
1548 1548 srcs = walkpat(pat)
1549 1549 if not srcs:
1550 1550 continue
1551 1551 for abs, rel, exact in srcs:
1552 1552 copylist.append(abs)
1553 1553
1554 1554 if not copylist:
1555 1555 raise error.Abort(_(b'no files to copy'))
1556 1556 # TODO: Add support for `hg cp --at-rev . foo bar dir` and
1557 1557 # `hg cp --at-rev . dir1 dir2`, preferably unifying the code with the
1558 1558 # existing functions below.
1559 1559 if len(copylist) != 1:
1560 1560 raise error.Abort(_(b'--at-rev requires a single source'))
1561 1561
1562 1562 new_ctx = context.overlayworkingctx(repo)
1563 1563 new_ctx.setbase(ctx.p1())
1564 1564 mergemod.graft(repo, ctx, wctx=new_ctx)
1565 1565
1566 1566 new_ctx.markcopied(absdest, copylist[0])
1567 1567
1568 1568 with repo.lock():
1569 1569 mem_ctx = new_ctx.tomemctx_for_amend(ctx)
1570 1570 new_node = mem_ctx.commit()
1571 1571
1572 1572 if repo.dirstate.p1() == ctx.node():
1573 1573 with repo.dirstate.parentchange():
1574 1574 scmutil.movedirstate(repo, repo[new_node])
1575 1575 replacements = {ctx.node(): [new_node]}
1576 1576 scmutil.cleanupnodes(repo, replacements, b'copy', fixphase=True)
1577 1577
1578 1578 return
1579 1579
1580 1580 # abssrc: hgsep
1581 1581 # relsrc: ossep
1582 1582 # otarget: ossep
1583 1583 def copyfile(abssrc, relsrc, otarget, exact):
1584 1584 abstarget = pathutil.canonpath(repo.root, cwd, otarget)
1585 1585 if b'/' in abstarget:
1586 1586 # We cannot normalize abstarget itself, this would prevent
1587 1587 # case only renames, like a => A.
1588 1588 abspath, absname = abstarget.rsplit(b'/', 1)
1589 1589 abstarget = repo.dirstate.normalize(abspath) + b'/' + absname
1590 1590 reltarget = repo.pathto(abstarget, cwd)
1591 1591 target = repo.wjoin(abstarget)
1592 1592 src = repo.wjoin(abssrc)
1593 1593 state = repo.dirstate[abstarget]
1594 1594
1595 1595 scmutil.checkportable(ui, abstarget)
1596 1596
1597 1597 # check for collisions
1598 1598 prevsrc = targets.get(abstarget)
1599 1599 if prevsrc is not None:
1600 1600 ui.warn(
1601 1601 _(b'%s: not overwriting - %s collides with %s\n')
1602 1602 % (
1603 1603 reltarget,
1604 1604 repo.pathto(abssrc, cwd),
1605 1605 repo.pathto(prevsrc, cwd),
1606 1606 )
1607 1607 )
1608 1608 return True # report a failure
1609 1609
1610 1610 # check for overwrites
1611 1611 exists = os.path.lexists(target)
1612 1612 samefile = False
1613 1613 if exists and abssrc != abstarget:
1614 1614 if repo.dirstate.normalize(abssrc) == repo.dirstate.normalize(
1615 1615 abstarget
1616 1616 ):
1617 1617 if not rename:
1618 1618 ui.warn(_(b"%s: can't copy - same file\n") % reltarget)
1619 1619 return True # report a failure
1620 1620 exists = False
1621 1621 samefile = True
1622 1622
1623 1623 if not after and exists or after and state in b'mn':
1624 1624 if not opts[b'force']:
1625 1625 if state in b'mn':
1626 1626 msg = _(b'%s: not overwriting - file already committed\n')
1627 1627 if after:
1628 1628 flags = b'--after --force'
1629 1629 else:
1630 1630 flags = b'--force'
1631 1631 if rename:
1632 1632 hint = (
1633 1633 _(
1634 1634 b"('hg rename %s' to replace the file by "
1635 1635 b'recording a rename)\n'
1636 1636 )
1637 1637 % flags
1638 1638 )
1639 1639 else:
1640 1640 hint = (
1641 1641 _(
1642 1642 b"('hg copy %s' to replace the file by "
1643 1643 b'recording a copy)\n'
1644 1644 )
1645 1645 % flags
1646 1646 )
1647 1647 else:
1648 1648 msg = _(b'%s: not overwriting - file exists\n')
1649 1649 if rename:
1650 1650 hint = _(
1651 1651 b"('hg rename --after' to record the rename)\n"
1652 1652 )
1653 1653 else:
1654 1654 hint = _(b"('hg copy --after' to record the copy)\n")
1655 1655 ui.warn(msg % reltarget)
1656 1656 ui.warn(hint)
1657 1657 return True # report a failure
1658 1658
1659 1659 if after:
1660 1660 if not exists:
1661 1661 if rename:
1662 1662 ui.warn(
1663 1663 _(b'%s: not recording move - %s does not exist\n')
1664 1664 % (relsrc, reltarget)
1665 1665 )
1666 1666 else:
1667 1667 ui.warn(
1668 1668 _(b'%s: not recording copy - %s does not exist\n')
1669 1669 % (relsrc, reltarget)
1670 1670 )
1671 1671 return True # report a failure
1672 1672 elif not dryrun:
1673 1673 try:
1674 1674 if exists:
1675 1675 os.unlink(target)
1676 1676 targetdir = os.path.dirname(target) or b'.'
1677 1677 if not os.path.isdir(targetdir):
1678 1678 os.makedirs(targetdir)
1679 1679 if samefile:
1680 1680 tmp = target + b"~hgrename"
1681 1681 os.rename(src, tmp)
1682 1682 os.rename(tmp, target)
1683 1683 else:
1684 1684 # Preserve stat info on renames, not on copies; this matches
1685 1685 # Linux CLI behavior.
1686 1686 util.copyfile(src, target, copystat=rename)
1687 1687 srcexists = True
1688 1688 except IOError as inst:
1689 1689 if inst.errno == errno.ENOENT:
1690 1690 ui.warn(_(b'%s: deleted in working directory\n') % relsrc)
1691 1691 srcexists = False
1692 1692 else:
1693 1693 ui.warn(
1694 1694 _(b'%s: cannot copy - %s\n')
1695 1695 % (relsrc, encoding.strtolocal(inst.strerror))
1696 1696 )
1697 1697 return True # report a failure
1698 1698
1699 1699 if ui.verbose or not exact:
1700 1700 if rename:
1701 1701 ui.status(_(b'moving %s to %s\n') % (relsrc, reltarget))
1702 1702 else:
1703 1703 ui.status(_(b'copying %s to %s\n') % (relsrc, reltarget))
1704 1704
1705 1705 targets[abstarget] = abssrc
1706 1706
1707 1707 # fix up dirstate
1708 1708 scmutil.dirstatecopy(
1709 1709 ui, repo, ctx, abssrc, abstarget, dryrun=dryrun, cwd=cwd
1710 1710 )
1711 1711 if rename and not dryrun:
1712 1712 if not after and srcexists and not samefile:
1713 1713 rmdir = repo.ui.configbool(b'experimental', b'removeemptydirs')
1714 1714 repo.wvfs.unlinkpath(abssrc, rmdir=rmdir)
1715 1715 ctx.forget([abssrc])
1716 1716
1717 1717 # pat: ossep
1718 1718 # dest ossep
1719 1719 # srcs: list of (hgsep, hgsep, ossep, bool)
1720 1720 # return: function that takes hgsep and returns ossep
1721 1721 def targetpathfn(pat, dest, srcs):
1722 1722 if os.path.isdir(pat):
1723 1723 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1724 1724 abspfx = util.localpath(abspfx)
1725 1725 if destdirexists:
1726 1726 striplen = len(os.path.split(abspfx)[0])
1727 1727 else:
1728 1728 striplen = len(abspfx)
1729 1729 if striplen:
1730 1730 striplen += len(pycompat.ossep)
1731 1731 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
1732 1732 elif destdirexists:
1733 1733 res = lambda p: os.path.join(
1734 1734 dest, os.path.basename(util.localpath(p))
1735 1735 )
1736 1736 else:
1737 1737 res = lambda p: dest
1738 1738 return res
1739 1739
1740 1740 # pat: ossep
1741 1741 # dest ossep
1742 1742 # srcs: list of (hgsep, hgsep, ossep, bool)
1743 1743 # return: function that takes hgsep and returns ossep
1744 1744 def targetpathafterfn(pat, dest, srcs):
1745 1745 if matchmod.patkind(pat):
1746 1746 # a mercurial pattern
1747 1747 res = lambda p: os.path.join(
1748 1748 dest, os.path.basename(util.localpath(p))
1749 1749 )
1750 1750 else:
1751 1751 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1752 1752 if len(abspfx) < len(srcs[0][0]):
1753 1753 # A directory. Either the target path contains the last
1754 1754 # component of the source path or it does not.
1755 1755 def evalpath(striplen):
1756 1756 score = 0
1757 1757 for s in srcs:
1758 1758 t = os.path.join(dest, util.localpath(s[0])[striplen:])
1759 1759 if os.path.lexists(t):
1760 1760 score += 1
1761 1761 return score
1762 1762
1763 1763 abspfx = util.localpath(abspfx)
1764 1764 striplen = len(abspfx)
1765 1765 if striplen:
1766 1766 striplen += len(pycompat.ossep)
1767 1767 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
1768 1768 score = evalpath(striplen)
1769 1769 striplen1 = len(os.path.split(abspfx)[0])
1770 1770 if striplen1:
1771 1771 striplen1 += len(pycompat.ossep)
1772 1772 if evalpath(striplen1) > score:
1773 1773 striplen = striplen1
1774 1774 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
1775 1775 else:
1776 1776 # a file
1777 1777 if destdirexists:
1778 1778 res = lambda p: os.path.join(
1779 1779 dest, os.path.basename(util.localpath(p))
1780 1780 )
1781 1781 else:
1782 1782 res = lambda p: dest
1783 1783 return res
1784 1784
1785 1785 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
1786 1786 if not destdirexists:
1787 1787 if len(pats) > 1 or matchmod.patkind(pats[0]):
1788 1788 raise error.Abort(
1789 1789 _(
1790 1790 b'with multiple sources, destination must be an '
1791 1791 b'existing directory'
1792 1792 )
1793 1793 )
1794 1794 if util.endswithsep(dest):
1795 1795 raise error.Abort(_(b'destination %s is not a directory') % dest)
1796 1796
1797 1797 tfn = targetpathfn
1798 1798 if after:
1799 1799 tfn = targetpathafterfn
1800 1800 copylist = []
1801 1801 for pat in pats:
1802 1802 srcs = walkpat(pat)
1803 1803 if not srcs:
1804 1804 continue
1805 1805 copylist.append((tfn(pat, dest, srcs), srcs))
1806 1806 if not copylist:
1807 1807 raise error.Abort(_(b'no files to copy'))
1808 1808
1809 1809 errors = 0
1810 1810 for targetpath, srcs in copylist:
1811 1811 for abssrc, relsrc, exact in srcs:
1812 1812 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
1813 1813 errors += 1
1814 1814
1815 1815 return errors != 0
1816 1816
1817 1817
1818 1818 ## facility to let extension process additional data into an import patch
1819 1819 # list of identifier to be executed in order
1820 1820 extrapreimport = [] # run before commit
1821 1821 extrapostimport = [] # run after commit
1822 1822 # mapping from identifier to actual import function
1823 1823 #
1824 1824 # 'preimport' are run before the commit is made and are provided the following
1825 1825 # arguments:
1826 1826 # - repo: the localrepository instance,
1827 1827 # - patchdata: data extracted from patch header (cf m.patch.patchheadermap),
1828 1828 # - extra: the future extra dictionary of the changeset, please mutate it,
1829 1829 # - opts: the import options.
1830 1830 # XXX ideally, we would just pass an ctx ready to be computed, that would allow
1831 1831 # mutation of in memory commit and more. Feel free to rework the code to get
1832 1832 # there.
1833 1833 extrapreimportmap = {}
1834 1834 # 'postimport' are run after the commit is made and are provided the following
1835 1835 # argument:
1836 1836 # - ctx: the changectx created by import.
1837 1837 extrapostimportmap = {}
1838 1838
1839 1839
1840 1840 def tryimportone(ui, repo, patchdata, parents, opts, msgs, updatefunc):
1841 1841 """Utility function used by commands.import to import a single patch
1842 1842
1843 1843 This function is explicitly defined here to help the evolve extension to
1844 1844 wrap this part of the import logic.
1845 1845
1846 1846 The API is currently a bit ugly because it a simple code translation from
1847 1847 the import command. Feel free to make it better.
1848 1848
1849 1849 :patchdata: a dictionary containing parsed patch data (such as from
1850 1850 ``patch.extract()``)
1851 1851 :parents: nodes that will be parent of the created commit
1852 1852 :opts: the full dict of option passed to the import command
1853 1853 :msgs: list to save commit message to.
1854 1854 (used in case we need to save it when failing)
1855 1855 :updatefunc: a function that update a repo to a given node
1856 1856 updatefunc(<repo>, <node>)
1857 1857 """
1858 1858 # avoid cycle context -> subrepo -> cmdutil
1859 1859 from . import context
1860 1860
1861 1861 tmpname = patchdata.get(b'filename')
1862 1862 message = patchdata.get(b'message')
1863 1863 user = opts.get(b'user') or patchdata.get(b'user')
1864 1864 date = opts.get(b'date') or patchdata.get(b'date')
1865 1865 branch = patchdata.get(b'branch')
1866 1866 nodeid = patchdata.get(b'nodeid')
1867 1867 p1 = patchdata.get(b'p1')
1868 1868 p2 = patchdata.get(b'p2')
1869 1869
1870 1870 nocommit = opts.get(b'no_commit')
1871 1871 importbranch = opts.get(b'import_branch')
1872 1872 update = not opts.get(b'bypass')
1873 1873 strip = opts[b"strip"]
1874 1874 prefix = opts[b"prefix"]
1875 1875 sim = float(opts.get(b'similarity') or 0)
1876 1876
1877 1877 if not tmpname:
1878 1878 return None, None, False
1879 1879
1880 1880 rejects = False
1881 1881
1882 1882 cmdline_message = logmessage(ui, opts)
1883 1883 if cmdline_message:
1884 1884 # pickup the cmdline msg
1885 1885 message = cmdline_message
1886 1886 elif message:
1887 1887 # pickup the patch msg
1888 1888 message = message.strip()
1889 1889 else:
1890 1890 # launch the editor
1891 1891 message = None
1892 1892 ui.debug(b'message:\n%s\n' % (message or b''))
1893 1893
1894 1894 if len(parents) == 1:
1895 1895 parents.append(repo[nullid])
1896 1896 if opts.get(b'exact'):
1897 1897 if not nodeid or not p1:
1898 1898 raise error.Abort(_(b'not a Mercurial patch'))
1899 1899 p1 = repo[p1]
1900 1900 p2 = repo[p2 or nullid]
1901 1901 elif p2:
1902 1902 try:
1903 1903 p1 = repo[p1]
1904 1904 p2 = repo[p2]
1905 1905 # Without any options, consider p2 only if the
1906 1906 # patch is being applied on top of the recorded
1907 1907 # first parent.
1908 1908 if p1 != parents[0]:
1909 1909 p1 = parents[0]
1910 1910 p2 = repo[nullid]
1911 1911 except error.RepoError:
1912 1912 p1, p2 = parents
1913 1913 if p2.node() == nullid:
1914 1914 ui.warn(
1915 1915 _(
1916 1916 b"warning: import the patch as a normal revision\n"
1917 1917 b"(use --exact to import the patch as a merge)\n"
1918 1918 )
1919 1919 )
1920 1920 else:
1921 1921 p1, p2 = parents
1922 1922
1923 1923 n = None
1924 1924 if update:
1925 1925 if p1 != parents[0]:
1926 1926 updatefunc(repo, p1.node())
1927 1927 if p2 != parents[1]:
1928 1928 repo.setparents(p1.node(), p2.node())
1929 1929
1930 1930 if opts.get(b'exact') or importbranch:
1931 1931 repo.dirstate.setbranch(branch or b'default')
1932 1932
1933 1933 partial = opts.get(b'partial', False)
1934 1934 files = set()
1935 1935 try:
1936 1936 patch.patch(
1937 1937 ui,
1938 1938 repo,
1939 1939 tmpname,
1940 1940 strip=strip,
1941 1941 prefix=prefix,
1942 1942 files=files,
1943 1943 eolmode=None,
1944 1944 similarity=sim / 100.0,
1945 1945 )
1946 1946 except error.PatchError as e:
1947 1947 if not partial:
1948 1948 raise error.Abort(pycompat.bytestr(e))
1949 1949 if partial:
1950 1950 rejects = True
1951 1951
1952 1952 files = list(files)
1953 1953 if nocommit:
1954 1954 if message:
1955 1955 msgs.append(message)
1956 1956 else:
1957 1957 if opts.get(b'exact') or p2:
1958 1958 # If you got here, you either use --force and know what
1959 1959 # you are doing or used --exact or a merge patch while
1960 1960 # being updated to its first parent.
1961 1961 m = None
1962 1962 else:
1963 1963 m = scmutil.matchfiles(repo, files or [])
1964 1964 editform = mergeeditform(repo[None], b'import.normal')
1965 1965 if opts.get(b'exact'):
1966 1966 editor = None
1967 1967 else:
1968 1968 editor = getcommiteditor(
1969 1969 editform=editform, **pycompat.strkwargs(opts)
1970 1970 )
1971 1971 extra = {}
1972 1972 for idfunc in extrapreimport:
1973 1973 extrapreimportmap[idfunc](repo, patchdata, extra, opts)
1974 1974 overrides = {}
1975 1975 if partial:
1976 1976 overrides[(b'ui', b'allowemptycommit')] = True
1977 1977 if opts.get(b'secret'):
1978 1978 overrides[(b'phases', b'new-commit')] = b'secret'
1979 1979 with repo.ui.configoverride(overrides, b'import'):
1980 1980 n = repo.commit(
1981 1981 message, user, date, match=m, editor=editor, extra=extra
1982 1982 )
1983 1983 for idfunc in extrapostimport:
1984 1984 extrapostimportmap[idfunc](repo[n])
1985 1985 else:
1986 1986 if opts.get(b'exact') or importbranch:
1987 1987 branch = branch or b'default'
1988 1988 else:
1989 1989 branch = p1.branch()
1990 1990 store = patch.filestore()
1991 1991 try:
1992 1992 files = set()
1993 1993 try:
1994 1994 patch.patchrepo(
1995 1995 ui,
1996 1996 repo,
1997 1997 p1,
1998 1998 store,
1999 1999 tmpname,
2000 2000 strip,
2001 2001 prefix,
2002 2002 files,
2003 2003 eolmode=None,
2004 2004 )
2005 2005 except error.PatchError as e:
2006 2006 raise error.Abort(stringutil.forcebytestr(e))
2007 2007 if opts.get(b'exact'):
2008 2008 editor = None
2009 2009 else:
2010 2010 editor = getcommiteditor(editform=b'import.bypass')
2011 2011 memctx = context.memctx(
2012 2012 repo,
2013 2013 (p1.node(), p2.node()),
2014 2014 message,
2015 2015 files=files,
2016 2016 filectxfn=store,
2017 2017 user=user,
2018 2018 date=date,
2019 2019 branch=branch,
2020 2020 editor=editor,
2021 2021 )
2022 2022
2023 2023 overrides = {}
2024 2024 if opts.get(b'secret'):
2025 2025 overrides[(b'phases', b'new-commit')] = b'secret'
2026 2026 with repo.ui.configoverride(overrides, b'import'):
2027 2027 n = memctx.commit()
2028 2028 finally:
2029 2029 store.close()
2030 2030 if opts.get(b'exact') and nocommit:
2031 2031 # --exact with --no-commit is still useful in that it does merge
2032 2032 # and branch bits
2033 2033 ui.warn(_(b"warning: can't check exact import with --no-commit\n"))
2034 2034 elif opts.get(b'exact') and (not n or hex(n) != nodeid):
2035 2035 raise error.Abort(_(b'patch is damaged or loses information'))
2036 2036 msg = _(b'applied to working directory')
2037 2037 if n:
2038 2038 # i18n: refers to a short changeset id
2039 2039 msg = _(b'created %s') % short(n)
2040 2040 return msg, n, rejects
2041 2041
2042 2042
2043 2043 # facility to let extensions include additional data in an exported patch
2044 2044 # list of identifiers to be executed in order
2045 2045 extraexport = []
2046 2046 # mapping from identifier to actual export function
2047 2047 # function as to return a string to be added to the header or None
2048 2048 # it is given two arguments (sequencenumber, changectx)
2049 2049 extraexportmap = {}
2050 2050
2051 2051
2052 2052 def _exportsingle(repo, ctx, fm, match, switch_parent, seqno, diffopts):
2053 2053 node = scmutil.binnode(ctx)
2054 2054 parents = [p.node() for p in ctx.parents() if p]
2055 2055 branch = ctx.branch()
2056 2056 if switch_parent:
2057 2057 parents.reverse()
2058 2058
2059 2059 if parents:
2060 2060 prev = parents[0]
2061 2061 else:
2062 2062 prev = nullid
2063 2063
2064 2064 fm.context(ctx=ctx)
2065 2065 fm.plain(b'# HG changeset patch\n')
2066 2066 fm.write(b'user', b'# User %s\n', ctx.user())
2067 2067 fm.plain(b'# Date %d %d\n' % ctx.date())
2068 2068 fm.write(b'date', b'# %s\n', fm.formatdate(ctx.date()))
2069 2069 fm.condwrite(
2070 2070 branch and branch != b'default', b'branch', b'# Branch %s\n', branch
2071 2071 )
2072 2072 fm.write(b'node', b'# Node ID %s\n', hex(node))
2073 2073 fm.plain(b'# Parent %s\n' % hex(prev))
2074 2074 if len(parents) > 1:
2075 2075 fm.plain(b'# Parent %s\n' % hex(parents[1]))
2076 2076 fm.data(parents=fm.formatlist(pycompat.maplist(hex, parents), name=b'node'))
2077 2077
2078 2078 # TODO: redesign extraexportmap function to support formatter
2079 2079 for headerid in extraexport:
2080 2080 header = extraexportmap[headerid](seqno, ctx)
2081 2081 if header is not None:
2082 2082 fm.plain(b'# %s\n' % header)
2083 2083
2084 2084 fm.write(b'desc', b'%s\n', ctx.description().rstrip())
2085 2085 fm.plain(b'\n')
2086 2086
2087 2087 if fm.isplain():
2088 2088 chunkiter = patch.diffui(repo, prev, node, match, opts=diffopts)
2089 2089 for chunk, label in chunkiter:
2090 2090 fm.plain(chunk, label=label)
2091 2091 else:
2092 2092 chunkiter = patch.diff(repo, prev, node, match, opts=diffopts)
2093 2093 # TODO: make it structured?
2094 2094 fm.data(diff=b''.join(chunkiter))
2095 2095
2096 2096
2097 2097 def _exportfile(repo, revs, fm, dest, switch_parent, diffopts, match):
2098 2098 """Export changesets to stdout or a single file"""
2099 2099 for seqno, rev in enumerate(revs, 1):
2100 2100 ctx = repo[rev]
2101 2101 if not dest.startswith(b'<'):
2102 2102 repo.ui.note(b"%s\n" % dest)
2103 2103 fm.startitem()
2104 2104 _exportsingle(repo, ctx, fm, match, switch_parent, seqno, diffopts)
2105 2105
2106 2106
2107 2107 def _exportfntemplate(
2108 2108 repo, revs, basefm, fntemplate, switch_parent, diffopts, match
2109 2109 ):
2110 2110 """Export changesets to possibly multiple files"""
2111 2111 total = len(revs)
2112 2112 revwidth = max(len(str(rev)) for rev in revs)
2113 2113 filemap = util.sortdict() # filename: [(seqno, rev), ...]
2114 2114
2115 2115 for seqno, rev in enumerate(revs, 1):
2116 2116 ctx = repo[rev]
2117 2117 dest = makefilename(
2118 2118 ctx, fntemplate, total=total, seqno=seqno, revwidth=revwidth
2119 2119 )
2120 2120 filemap.setdefault(dest, []).append((seqno, rev))
2121 2121
2122 2122 for dest in filemap:
2123 2123 with formatter.maybereopen(basefm, dest) as fm:
2124 2124 repo.ui.note(b"%s\n" % dest)
2125 2125 for seqno, rev in filemap[dest]:
2126 2126 fm.startitem()
2127 2127 ctx = repo[rev]
2128 2128 _exportsingle(
2129 2129 repo, ctx, fm, match, switch_parent, seqno, diffopts
2130 2130 )
2131 2131
2132 2132
2133 2133 def _prefetchchangedfiles(repo, revs, match):
2134 2134 allfiles = set()
2135 2135 for rev in revs:
2136 2136 for file in repo[rev].files():
2137 2137 if not match or match(file):
2138 2138 allfiles.add(file)
2139 2139 match = scmutil.matchfiles(repo, allfiles)
2140 2140 revmatches = [(rev, match) for rev in revs]
2141 2141 scmutil.prefetchfiles(repo, revmatches)
2142 2142
2143 2143
2144 2144 def export(
2145 2145 repo,
2146 2146 revs,
2147 2147 basefm,
2148 2148 fntemplate=b'hg-%h.patch',
2149 2149 switch_parent=False,
2150 2150 opts=None,
2151 2151 match=None,
2152 2152 ):
2153 2153 '''export changesets as hg patches
2154 2154
2155 2155 Args:
2156 2156 repo: The repository from which we're exporting revisions.
2157 2157 revs: A list of revisions to export as revision numbers.
2158 2158 basefm: A formatter to which patches should be written.
2159 2159 fntemplate: An optional string to use for generating patch file names.
2160 2160 switch_parent: If True, show diffs against second parent when not nullid.
2161 2161 Default is false, which always shows diff against p1.
2162 2162 opts: diff options to use for generating the patch.
2163 2163 match: If specified, only export changes to files matching this matcher.
2164 2164
2165 2165 Returns:
2166 2166 Nothing.
2167 2167
2168 2168 Side Effect:
2169 2169 "HG Changeset Patch" data is emitted to one of the following
2170 2170 destinations:
2171 2171 fntemplate specified: Each rev is written to a unique file named using
2172 2172 the given template.
2173 2173 Otherwise: All revs will be written to basefm.
2174 2174 '''
2175 2175 _prefetchchangedfiles(repo, revs, match)
2176 2176
2177 2177 if not fntemplate:
2178 2178 _exportfile(
2179 2179 repo, revs, basefm, b'<unnamed>', switch_parent, opts, match
2180 2180 )
2181 2181 else:
2182 2182 _exportfntemplate(
2183 2183 repo, revs, basefm, fntemplate, switch_parent, opts, match
2184 2184 )
2185 2185
2186 2186
2187 2187 def exportfile(repo, revs, fp, switch_parent=False, opts=None, match=None):
2188 2188 """Export changesets to the given file stream"""
2189 2189 _prefetchchangedfiles(repo, revs, match)
2190 2190
2191 2191 dest = getattr(fp, 'name', b'<unnamed>')
2192 2192 with formatter.formatter(repo.ui, fp, b'export', {}) as fm:
2193 2193 _exportfile(repo, revs, fm, dest, switch_parent, opts, match)
2194 2194
2195 2195
2196 2196 def showmarker(fm, marker, index=None):
2197 2197 """utility function to display obsolescence marker in a readable way
2198 2198
2199 2199 To be used by debug function."""
2200 2200 if index is not None:
2201 2201 fm.write(b'index', b'%i ', index)
2202 2202 fm.write(b'prednode', b'%s ', hex(marker.prednode()))
2203 2203 succs = marker.succnodes()
2204 2204 fm.condwrite(
2205 2205 succs,
2206 2206 b'succnodes',
2207 2207 b'%s ',
2208 2208 fm.formatlist(map(hex, succs), name=b'node'),
2209 2209 )
2210 2210 fm.write(b'flag', b'%X ', marker.flags())
2211 2211 parents = marker.parentnodes()
2212 2212 if parents is not None:
2213 2213 fm.write(
2214 2214 b'parentnodes',
2215 2215 b'{%s} ',
2216 2216 fm.formatlist(map(hex, parents), name=b'node', sep=b', '),
2217 2217 )
2218 2218 fm.write(b'date', b'(%s) ', fm.formatdate(marker.date()))
2219 2219 meta = marker.metadata().copy()
2220 2220 meta.pop(b'date', None)
2221 2221 smeta = pycompat.rapply(pycompat.maybebytestr, meta)
2222 2222 fm.write(
2223 2223 b'metadata', b'{%s}', fm.formatdict(smeta, fmt=b'%r: %r', sep=b', ')
2224 2224 )
2225 2225 fm.plain(b'\n')
2226 2226
2227 2227
2228 2228 def finddate(ui, repo, date):
2229 2229 """Find the tipmost changeset that matches the given date spec"""
2230 2230 mrevs = repo.revs(b'date(%s)', date)
2231 2231 try:
2232 2232 rev = mrevs.max()
2233 2233 except ValueError:
2234 2234 raise error.Abort(_(b"revision matching date not found"))
2235 2235
2236 2236 ui.status(
2237 2237 _(b"found revision %d from %s\n")
2238 2238 % (rev, dateutil.datestr(repo[rev].date()))
2239 2239 )
2240 2240 return b'%d' % rev
2241 2241
2242 2242
2243 2243 def add(ui, repo, match, prefix, uipathfn, explicitonly, **opts):
2244 2244 bad = []
2245 2245
2246 2246 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2247 2247 names = []
2248 2248 wctx = repo[None]
2249 2249 cca = None
2250 2250 abort, warn = scmutil.checkportabilityalert(ui)
2251 2251 if abort or warn:
2252 2252 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
2253 2253
2254 2254 match = repo.narrowmatch(match, includeexact=True)
2255 2255 badmatch = matchmod.badmatch(match, badfn)
2256 2256 dirstate = repo.dirstate
2257 2257 # We don't want to just call wctx.walk here, since it would return a lot of
2258 2258 # clean files, which we aren't interested in and takes time.
2259 2259 for f in sorted(
2260 2260 dirstate.walk(
2261 2261 badmatch,
2262 2262 subrepos=sorted(wctx.substate),
2263 2263 unknown=True,
2264 2264 ignored=False,
2265 2265 full=False,
2266 2266 )
2267 2267 ):
2268 2268 exact = match.exact(f)
2269 2269 if exact or not explicitonly and f not in wctx and repo.wvfs.lexists(f):
2270 2270 if cca:
2271 2271 cca(f)
2272 2272 names.append(f)
2273 2273 if ui.verbose or not exact:
2274 2274 ui.status(
2275 2275 _(b'adding %s\n') % uipathfn(f), label=b'ui.addremove.added'
2276 2276 )
2277 2277
2278 2278 for subpath in sorted(wctx.substate):
2279 2279 sub = wctx.sub(subpath)
2280 2280 try:
2281 2281 submatch = matchmod.subdirmatcher(subpath, match)
2282 2282 subprefix = repo.wvfs.reljoin(prefix, subpath)
2283 2283 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2284 2284 if opts.get('subrepos'):
2285 2285 bad.extend(
2286 2286 sub.add(ui, submatch, subprefix, subuipathfn, False, **opts)
2287 2287 )
2288 2288 else:
2289 2289 bad.extend(
2290 2290 sub.add(ui, submatch, subprefix, subuipathfn, True, **opts)
2291 2291 )
2292 2292 except error.LookupError:
2293 2293 ui.status(
2294 2294 _(b"skipping missing subrepository: %s\n") % uipathfn(subpath)
2295 2295 )
2296 2296
2297 2297 if not opts.get('dry_run'):
2298 2298 rejected = wctx.add(names, prefix)
2299 2299 bad.extend(f for f in rejected if f in match.files())
2300 2300 return bad
2301 2301
2302 2302
2303 2303 def addwebdirpath(repo, serverpath, webconf):
2304 2304 webconf[serverpath] = repo.root
2305 2305 repo.ui.debug(b'adding %s = %s\n' % (serverpath, repo.root))
2306 2306
2307 2307 for r in repo.revs(b'filelog("path:.hgsub")'):
2308 2308 ctx = repo[r]
2309 2309 for subpath in ctx.substate:
2310 2310 ctx.sub(subpath).addwebdirpath(serverpath, webconf)
2311 2311
2312 2312
2313 2313 def forget(
2314 2314 ui, repo, match, prefix, uipathfn, explicitonly, dryrun, interactive
2315 2315 ):
2316 2316 if dryrun and interactive:
2317 2317 raise error.Abort(_(b"cannot specify both --dry-run and --interactive"))
2318 2318 bad = []
2319 2319 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2320 2320 wctx = repo[None]
2321 2321 forgot = []
2322 2322
2323 2323 s = repo.status(match=matchmod.badmatch(match, badfn), clean=True)
2324 2324 forget = sorted(s.modified + s.added + s.deleted + s.clean)
2325 2325 if explicitonly:
2326 2326 forget = [f for f in forget if match.exact(f)]
2327 2327
2328 2328 for subpath in sorted(wctx.substate):
2329 2329 sub = wctx.sub(subpath)
2330 2330 submatch = matchmod.subdirmatcher(subpath, match)
2331 2331 subprefix = repo.wvfs.reljoin(prefix, subpath)
2332 2332 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2333 2333 try:
2334 2334 subbad, subforgot = sub.forget(
2335 2335 submatch,
2336 2336 subprefix,
2337 2337 subuipathfn,
2338 2338 dryrun=dryrun,
2339 2339 interactive=interactive,
2340 2340 )
2341 2341 bad.extend([subpath + b'/' + f for f in subbad])
2342 2342 forgot.extend([subpath + b'/' + f for f in subforgot])
2343 2343 except error.LookupError:
2344 2344 ui.status(
2345 2345 _(b"skipping missing subrepository: %s\n") % uipathfn(subpath)
2346 2346 )
2347 2347
2348 2348 if not explicitonly:
2349 2349 for f in match.files():
2350 2350 if f not in repo.dirstate and not repo.wvfs.isdir(f):
2351 2351 if f not in forgot:
2352 2352 if repo.wvfs.exists(f):
2353 2353 # Don't complain if the exact case match wasn't given.
2354 2354 # But don't do this until after checking 'forgot', so
2355 2355 # that subrepo files aren't normalized, and this op is
2356 2356 # purely from data cached by the status walk above.
2357 2357 if repo.dirstate.normalize(f) in repo.dirstate:
2358 2358 continue
2359 2359 ui.warn(
2360 2360 _(
2361 2361 b'not removing %s: '
2362 2362 b'file is already untracked\n'
2363 2363 )
2364 2364 % uipathfn(f)
2365 2365 )
2366 2366 bad.append(f)
2367 2367
2368 2368 if interactive:
2369 2369 responses = _(
2370 2370 b'[Ynsa?]'
2371 2371 b'$$ &Yes, forget this file'
2372 2372 b'$$ &No, skip this file'
2373 2373 b'$$ &Skip remaining files'
2374 2374 b'$$ Include &all remaining files'
2375 2375 b'$$ &? (display help)'
2376 2376 )
2377 2377 for filename in forget[:]:
2378 2378 r = ui.promptchoice(
2379 2379 _(b'forget %s %s') % (uipathfn(filename), responses)
2380 2380 )
2381 2381 if r == 4: # ?
2382 2382 while r == 4:
2383 2383 for c, t in ui.extractchoices(responses)[1]:
2384 2384 ui.write(b'%s - %s\n' % (c, encoding.lower(t)))
2385 2385 r = ui.promptchoice(
2386 2386 _(b'forget %s %s') % (uipathfn(filename), responses)
2387 2387 )
2388 2388 if r == 0: # yes
2389 2389 continue
2390 2390 elif r == 1: # no
2391 2391 forget.remove(filename)
2392 2392 elif r == 2: # Skip
2393 2393 fnindex = forget.index(filename)
2394 2394 del forget[fnindex:]
2395 2395 break
2396 2396 elif r == 3: # All
2397 2397 break
2398 2398
2399 2399 for f in forget:
2400 2400 if ui.verbose or not match.exact(f) or interactive:
2401 2401 ui.status(
2402 2402 _(b'removing %s\n') % uipathfn(f), label=b'ui.addremove.removed'
2403 2403 )
2404 2404
2405 2405 if not dryrun:
2406 2406 rejected = wctx.forget(forget, prefix)
2407 2407 bad.extend(f for f in rejected if f in match.files())
2408 2408 forgot.extend(f for f in forget if f not in rejected)
2409 2409 return bad, forgot
2410 2410
2411 2411
2412 2412 def files(ui, ctx, m, uipathfn, fm, fmt, subrepos):
2413 2413 ret = 1
2414 2414
2415 2415 needsfctx = ui.verbose or {b'size', b'flags'} & fm.datahint()
2416 2416 if fm.isplain() and not needsfctx:
2417 2417 # Fast path. The speed-up comes from skipping the formatter, and batching
2418 2418 # calls to ui.write.
2419 2419 buf = []
2420 2420 for f in ctx.matches(m):
2421 2421 buf.append(fmt % uipathfn(f))
2422 2422 if len(buf) > 100:
2423 2423 ui.write(b''.join(buf))
2424 2424 del buf[:]
2425 2425 ret = 0
2426 2426 if buf:
2427 2427 ui.write(b''.join(buf))
2428 2428 else:
2429 2429 for f in ctx.matches(m):
2430 2430 fm.startitem()
2431 2431 fm.context(ctx=ctx)
2432 2432 if needsfctx:
2433 2433 fc = ctx[f]
2434 2434 fm.write(b'size flags', b'% 10d % 1s ', fc.size(), fc.flags())
2435 2435 fm.data(path=f)
2436 2436 fm.plain(fmt % uipathfn(f))
2437 2437 ret = 0
2438 2438
2439 2439 for subpath in sorted(ctx.substate):
2440 2440 submatch = matchmod.subdirmatcher(subpath, m)
2441 2441 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2442 2442 if subrepos or m.exact(subpath) or any(submatch.files()):
2443 2443 sub = ctx.sub(subpath)
2444 2444 try:
2445 2445 recurse = m.exact(subpath) or subrepos
2446 2446 if (
2447 2447 sub.printfiles(ui, submatch, subuipathfn, fm, fmt, recurse)
2448 2448 == 0
2449 2449 ):
2450 2450 ret = 0
2451 2451 except error.LookupError:
2452 2452 ui.status(
2453 2453 _(b"skipping missing subrepository: %s\n")
2454 2454 % uipathfn(subpath)
2455 2455 )
2456 2456
2457 2457 return ret
2458 2458
2459 2459
2460 2460 def remove(
2461 2461 ui, repo, m, prefix, uipathfn, after, force, subrepos, dryrun, warnings=None
2462 2462 ):
2463 2463 ret = 0
2464 2464 s = repo.status(match=m, clean=True)
2465 2465 modified, added, deleted, clean = s.modified, s.added, s.deleted, s.clean
2466 2466
2467 2467 wctx = repo[None]
2468 2468
2469 2469 if warnings is None:
2470 2470 warnings = []
2471 2471 warn = True
2472 2472 else:
2473 2473 warn = False
2474 2474
2475 2475 subs = sorted(wctx.substate)
2476 2476 progress = ui.makeprogress(
2477 2477 _(b'searching'), total=len(subs), unit=_(b'subrepos')
2478 2478 )
2479 2479 for subpath in subs:
2480 2480 submatch = matchmod.subdirmatcher(subpath, m)
2481 2481 subprefix = repo.wvfs.reljoin(prefix, subpath)
2482 2482 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2483 2483 if subrepos or m.exact(subpath) or any(submatch.files()):
2484 2484 progress.increment()
2485 2485 sub = wctx.sub(subpath)
2486 2486 try:
2487 2487 if sub.removefiles(
2488 2488 submatch,
2489 2489 subprefix,
2490 2490 subuipathfn,
2491 2491 after,
2492 2492 force,
2493 2493 subrepos,
2494 2494 dryrun,
2495 2495 warnings,
2496 2496 ):
2497 2497 ret = 1
2498 2498 except error.LookupError:
2499 2499 warnings.append(
2500 2500 _(b"skipping missing subrepository: %s\n")
2501 2501 % uipathfn(subpath)
2502 2502 )
2503 2503 progress.complete()
2504 2504
2505 2505 # warn about failure to delete explicit files/dirs
2506 2506 deleteddirs = pathutil.dirs(deleted)
2507 2507 files = m.files()
2508 2508 progress = ui.makeprogress(
2509 2509 _(b'deleting'), total=len(files), unit=_(b'files')
2510 2510 )
2511 2511 for f in files:
2512 2512
2513 2513 def insubrepo():
2514 2514 for subpath in wctx.substate:
2515 2515 if f.startswith(subpath + b'/'):
2516 2516 return True
2517 2517 return False
2518 2518
2519 2519 progress.increment()
2520 2520 isdir = f in deleteddirs or wctx.hasdir(f)
2521 2521 if f in repo.dirstate or isdir or f == b'.' or insubrepo() or f in subs:
2522 2522 continue
2523 2523
2524 2524 if repo.wvfs.exists(f):
2525 2525 if repo.wvfs.isdir(f):
2526 2526 warnings.append(
2527 2527 _(b'not removing %s: no tracked files\n') % uipathfn(f)
2528 2528 )
2529 2529 else:
2530 2530 warnings.append(
2531 2531 _(b'not removing %s: file is untracked\n') % uipathfn(f)
2532 2532 )
2533 2533 # missing files will generate a warning elsewhere
2534 2534 ret = 1
2535 2535 progress.complete()
2536 2536
2537 2537 if force:
2538 2538 list = modified + deleted + clean + added
2539 2539 elif after:
2540 2540 list = deleted
2541 2541 remaining = modified + added + clean
2542 2542 progress = ui.makeprogress(
2543 2543 _(b'skipping'), total=len(remaining), unit=_(b'files')
2544 2544 )
2545 2545 for f in remaining:
2546 2546 progress.increment()
2547 2547 if ui.verbose or (f in files):
2548 2548 warnings.append(
2549 2549 _(b'not removing %s: file still exists\n') % uipathfn(f)
2550 2550 )
2551 2551 ret = 1
2552 2552 progress.complete()
2553 2553 else:
2554 2554 list = deleted + clean
2555 2555 progress = ui.makeprogress(
2556 2556 _(b'skipping'), total=(len(modified) + len(added)), unit=_(b'files')
2557 2557 )
2558 2558 for f in modified:
2559 2559 progress.increment()
2560 2560 warnings.append(
2561 2561 _(
2562 2562 b'not removing %s: file is modified (use -f'
2563 2563 b' to force removal)\n'
2564 2564 )
2565 2565 % uipathfn(f)
2566 2566 )
2567 2567 ret = 1
2568 2568 for f in added:
2569 2569 progress.increment()
2570 2570 warnings.append(
2571 2571 _(
2572 2572 b"not removing %s: file has been marked for add"
2573 2573 b" (use 'hg forget' to undo add)\n"
2574 2574 )
2575 2575 % uipathfn(f)
2576 2576 )
2577 2577 ret = 1
2578 2578 progress.complete()
2579 2579
2580 2580 list = sorted(list)
2581 2581 progress = ui.makeprogress(
2582 2582 _(b'deleting'), total=len(list), unit=_(b'files')
2583 2583 )
2584 2584 for f in list:
2585 2585 if ui.verbose or not m.exact(f):
2586 2586 progress.increment()
2587 2587 ui.status(
2588 2588 _(b'removing %s\n') % uipathfn(f), label=b'ui.addremove.removed'
2589 2589 )
2590 2590 progress.complete()
2591 2591
2592 2592 if not dryrun:
2593 2593 with repo.wlock():
2594 2594 if not after:
2595 2595 for f in list:
2596 2596 if f in added:
2597 2597 continue # we never unlink added files on remove
2598 2598 rmdir = repo.ui.configbool(
2599 2599 b'experimental', b'removeemptydirs'
2600 2600 )
2601 2601 repo.wvfs.unlinkpath(f, ignoremissing=True, rmdir=rmdir)
2602 2602 repo[None].forget(list)
2603 2603
2604 2604 if warn:
2605 2605 for warning in warnings:
2606 2606 ui.warn(warning)
2607 2607
2608 2608 return ret
2609 2609
2610 2610
2611 2611 def _catfmtneedsdata(fm):
2612 2612 return not fm.datahint() or b'data' in fm.datahint()
2613 2613
2614 2614
2615 2615 def _updatecatformatter(fm, ctx, matcher, path, decode):
2616 2616 """Hook for adding data to the formatter used by ``hg cat``.
2617 2617
2618 2618 Extensions (e.g., lfs) can wrap this to inject keywords/data, but must call
2619 2619 this method first."""
2620 2620
2621 2621 # data() can be expensive to fetch (e.g. lfs), so don't fetch it if it
2622 2622 # wasn't requested.
2623 2623 data = b''
2624 2624 if _catfmtneedsdata(fm):
2625 2625 data = ctx[path].data()
2626 2626 if decode:
2627 2627 data = ctx.repo().wwritedata(path, data)
2628 2628 fm.startitem()
2629 2629 fm.context(ctx=ctx)
2630 2630 fm.write(b'data', b'%s', data)
2631 2631 fm.data(path=path)
2632 2632
2633 2633
2634 2634 def cat(ui, repo, ctx, matcher, basefm, fntemplate, prefix, **opts):
2635 2635 err = 1
2636 2636 opts = pycompat.byteskwargs(opts)
2637 2637
2638 2638 def write(path):
2639 2639 filename = None
2640 2640 if fntemplate:
2641 2641 filename = makefilename(
2642 2642 ctx, fntemplate, pathname=os.path.join(prefix, path)
2643 2643 )
2644 2644 # attempt to create the directory if it does not already exist
2645 2645 try:
2646 2646 os.makedirs(os.path.dirname(filename))
2647 2647 except OSError:
2648 2648 pass
2649 2649 with formatter.maybereopen(basefm, filename) as fm:
2650 2650 _updatecatformatter(fm, ctx, matcher, path, opts.get(b'decode'))
2651 2651
2652 2652 # Automation often uses hg cat on single files, so special case it
2653 2653 # for performance to avoid the cost of parsing the manifest.
2654 2654 if len(matcher.files()) == 1 and not matcher.anypats():
2655 2655 file = matcher.files()[0]
2656 2656 mfl = repo.manifestlog
2657 2657 mfnode = ctx.manifestnode()
2658 2658 try:
2659 2659 if mfnode and mfl[mfnode].find(file)[0]:
2660 2660 if _catfmtneedsdata(basefm):
2661 2661 scmutil.prefetchfiles(repo, [(ctx.rev(), matcher)])
2662 2662 write(file)
2663 2663 return 0
2664 2664 except KeyError:
2665 2665 pass
2666 2666
2667 2667 if _catfmtneedsdata(basefm):
2668 2668 scmutil.prefetchfiles(repo, [(ctx.rev(), matcher)])
2669 2669
2670 2670 for abs in ctx.walk(matcher):
2671 2671 write(abs)
2672 2672 err = 0
2673 2673
2674 2674 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
2675 2675 for subpath in sorted(ctx.substate):
2676 2676 sub = ctx.sub(subpath)
2677 2677 try:
2678 2678 submatch = matchmod.subdirmatcher(subpath, matcher)
2679 2679 subprefix = os.path.join(prefix, subpath)
2680 2680 if not sub.cat(
2681 2681 submatch,
2682 2682 basefm,
2683 2683 fntemplate,
2684 2684 subprefix,
2685 2685 **pycompat.strkwargs(opts)
2686 2686 ):
2687 2687 err = 0
2688 2688 except error.RepoLookupError:
2689 2689 ui.status(
2690 2690 _(b"skipping missing subrepository: %s\n") % uipathfn(subpath)
2691 2691 )
2692 2692
2693 2693 return err
2694 2694
2695 2695
2696 2696 def commit(ui, repo, commitfunc, pats, opts):
2697 2697 '''commit the specified files or all outstanding changes'''
2698 2698 date = opts.get(b'date')
2699 2699 if date:
2700 2700 opts[b'date'] = dateutil.parsedate(date)
2701 2701 message = logmessage(ui, opts)
2702 2702 matcher = scmutil.match(repo[None], pats, opts)
2703 2703
2704 2704 dsguard = None
2705 2705 # extract addremove carefully -- this function can be called from a command
2706 2706 # that doesn't support addremove
2707 2707 if opts.get(b'addremove'):
2708 2708 dsguard = dirstateguard.dirstateguard(repo, b'commit')
2709 2709 with dsguard or util.nullcontextmanager():
2710 2710 if dsguard:
2711 2711 relative = scmutil.anypats(pats, opts)
2712 2712 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=relative)
2713 2713 if scmutil.addremove(repo, matcher, b"", uipathfn, opts) != 0:
2714 2714 raise error.Abort(
2715 2715 _(b"failed to mark all new/missing files as added/removed")
2716 2716 )
2717 2717
2718 2718 return commitfunc(ui, repo, message, matcher, opts)
2719 2719
2720 2720
2721 2721 def samefile(f, ctx1, ctx2):
2722 2722 if f in ctx1.manifest():
2723 2723 a = ctx1.filectx(f)
2724 2724 if f in ctx2.manifest():
2725 2725 b = ctx2.filectx(f)
2726 2726 return not a.cmp(b) and a.flags() == b.flags()
2727 2727 else:
2728 2728 return False
2729 2729 else:
2730 2730 return f not in ctx2.manifest()
2731 2731
2732 2732
2733 2733 def amend(ui, repo, old, extra, pats, opts):
2734 2734 # avoid cycle context -> subrepo -> cmdutil
2735 2735 from . import context
2736 2736
2737 2737 # amend will reuse the existing user if not specified, but the obsolete
2738 2738 # marker creation requires that the current user's name is specified.
2739 2739 if obsolete.isenabled(repo, obsolete.createmarkersopt):
2740 2740 ui.username() # raise exception if username not set
2741 2741
2742 2742 ui.note(_(b'amending changeset %s\n') % old)
2743 2743 base = old.p1()
2744 2744
2745 2745 with repo.wlock(), repo.lock(), repo.transaction(b'amend'):
2746 2746 # Participating changesets:
2747 2747 #
2748 2748 # wctx o - workingctx that contains changes from working copy
2749 2749 # | to go into amending commit
2750 2750 # |
2751 2751 # old o - changeset to amend
2752 2752 # |
2753 2753 # base o - first parent of the changeset to amend
2754 2754 wctx = repo[None]
2755 2755
2756 2756 # Copy to avoid mutating input
2757 2757 extra = extra.copy()
2758 2758 # Update extra dict from amended commit (e.g. to preserve graft
2759 2759 # source)
2760 2760 extra.update(old.extra())
2761 2761
2762 2762 # Also update it from the from the wctx
2763 2763 extra.update(wctx.extra())
2764 2764
2765 2765 # date-only change should be ignored?
2766 2766 datemaydiffer = resolvecommitoptions(ui, opts)
2767 2767
2768 2768 date = old.date()
2769 2769 if opts.get(b'date'):
2770 2770 date = dateutil.parsedate(opts.get(b'date'))
2771 2771 user = opts.get(b'user') or old.user()
2772 2772
2773 2773 if len(old.parents()) > 1:
2774 2774 # ctx.files() isn't reliable for merges, so fall back to the
2775 2775 # slower repo.status() method
2776 2776 st = base.status(old)
2777 2777 files = set(st.modified) | set(st.added) | set(st.removed)
2778 2778 else:
2779 2779 files = set(old.files())
2780 2780
2781 2781 # add/remove the files to the working copy if the "addremove" option
2782 2782 # was specified.
2783 2783 matcher = scmutil.match(wctx, pats, opts)
2784 2784 relative = scmutil.anypats(pats, opts)
2785 2785 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=relative)
2786 2786 if opts.get(b'addremove') and scmutil.addremove(
2787 2787 repo, matcher, b"", uipathfn, opts
2788 2788 ):
2789 2789 raise error.Abort(
2790 2790 _(b"failed to mark all new/missing files as added/removed")
2791 2791 )
2792 2792
2793 2793 # Check subrepos. This depends on in-place wctx._status update in
2794 2794 # subrepo.precommit(). To minimize the risk of this hack, we do
2795 2795 # nothing if .hgsub does not exist.
2796 2796 if b'.hgsub' in wctx or b'.hgsub' in old:
2797 2797 subs, commitsubs, newsubstate = subrepoutil.precommit(
2798 2798 ui, wctx, wctx._status, matcher
2799 2799 )
2800 2800 # amend should abort if commitsubrepos is enabled
2801 2801 assert not commitsubs
2802 2802 if subs:
2803 2803 subrepoutil.writestate(repo, newsubstate)
2804 2804
2805 2805 ms = mergestatemod.mergestate.read(repo)
2806 2806 mergeutil.checkunresolved(ms)
2807 2807
2808 2808 filestoamend = {f for f in wctx.files() if matcher(f)}
2809 2809
2810 2810 changes = len(filestoamend) > 0
2811 2811 if changes:
2812 2812 # Recompute copies (avoid recording a -> b -> a)
2813 2813 copied = copies.pathcopies(base, wctx, matcher)
2814 2814 if old.p2:
2815 2815 copied.update(copies.pathcopies(old.p2(), wctx, matcher))
2816 2816
2817 2817 # Prune files which were reverted by the updates: if old
2818 2818 # introduced file X and the file was renamed in the working
2819 2819 # copy, then those two files are the same and
2820 2820 # we can discard X from our list of files. Likewise if X
2821 2821 # was removed, it's no longer relevant. If X is missing (aka
2822 2822 # deleted), old X must be preserved.
2823 2823 files.update(filestoamend)
2824 2824 files = [
2825 2825 f
2826 2826 for f in files
2827 2827 if (f not in filestoamend or not samefile(f, wctx, base))
2828 2828 ]
2829 2829
2830 2830 def filectxfn(repo, ctx_, path):
2831 2831 try:
2832 2832 # If the file being considered is not amongst the files
2833 2833 # to be amended, we should return the file context from the
2834 2834 # old changeset. This avoids issues when only some files in
2835 2835 # the working copy are being amended but there are also
2836 2836 # changes to other files from the old changeset.
2837 2837 if path not in filestoamend:
2838 2838 return old.filectx(path)
2839 2839
2840 2840 # Return None for removed files.
2841 2841 if path in wctx.removed():
2842 2842 return None
2843 2843
2844 2844 fctx = wctx[path]
2845 2845 flags = fctx.flags()
2846 2846 mctx = context.memfilectx(
2847 2847 repo,
2848 2848 ctx_,
2849 2849 fctx.path(),
2850 2850 fctx.data(),
2851 2851 islink=b'l' in flags,
2852 2852 isexec=b'x' in flags,
2853 2853 copysource=copied.get(path),
2854 2854 )
2855 2855 return mctx
2856 2856 except KeyError:
2857 2857 return None
2858 2858
2859 2859 else:
2860 2860 ui.note(_(b'copying changeset %s to %s\n') % (old, base))
2861 2861
2862 2862 # Use version of files as in the old cset
2863 2863 def filectxfn(repo, ctx_, path):
2864 2864 try:
2865 2865 return old.filectx(path)
2866 2866 except KeyError:
2867 2867 return None
2868 2868
2869 2869 # See if we got a message from -m or -l, if not, open the editor with
2870 2870 # the message of the changeset to amend.
2871 2871 message = logmessage(ui, opts)
2872 2872
2873 2873 editform = mergeeditform(old, b'commit.amend')
2874 2874
2875 2875 if not message:
2876 2876 message = old.description()
2877 2877 # Default if message isn't provided and --edit is not passed is to
2878 2878 # invoke editor, but allow --no-edit. If somehow we don't have any
2879 2879 # description, let's always start the editor.
2880 2880 doedit = not message or opts.get(b'edit') in [True, None]
2881 2881 else:
2882 2882 # Default if message is provided is to not invoke editor, but allow
2883 2883 # --edit.
2884 2884 doedit = opts.get(b'edit') is True
2885 2885 editor = getcommiteditor(edit=doedit, editform=editform)
2886 2886
2887 2887 pureextra = extra.copy()
2888 2888 extra[b'amend_source'] = old.hex()
2889 2889
2890 2890 new = context.memctx(
2891 2891 repo,
2892 2892 parents=[base.node(), old.p2().node()],
2893 2893 text=message,
2894 2894 files=files,
2895 2895 filectxfn=filectxfn,
2896 2896 user=user,
2897 2897 date=date,
2898 2898 extra=extra,
2899 2899 editor=editor,
2900 2900 )
2901 2901
2902 2902 newdesc = changelog.stripdesc(new.description())
2903 2903 if (
2904 2904 (not changes)
2905 2905 and newdesc == old.description()
2906 2906 and user == old.user()
2907 2907 and (date == old.date() or datemaydiffer)
2908 2908 and pureextra == old.extra()
2909 2909 ):
2910 2910 # nothing changed. continuing here would create a new node
2911 2911 # anyway because of the amend_source noise.
2912 2912 #
2913 2913 # This not what we expect from amend.
2914 2914 return old.node()
2915 2915
2916 2916 commitphase = None
2917 2917 if opts.get(b'secret'):
2918 2918 commitphase = phases.secret
2919 2919 newid = repo.commitctx(new)
2920 2920 ms.reset()
2921 2921
2922 2922 # Reroute the working copy parent to the new changeset
2923 2923 repo.setparents(newid, nullid)
2924 2924 mapping = {old.node(): (newid,)}
2925 2925 obsmetadata = None
2926 2926 if opts.get(b'note'):
2927 2927 obsmetadata = {b'note': encoding.fromlocal(opts[b'note'])}
2928 2928 backup = ui.configbool(b'rewrite', b'backup-bundle')
2929 2929 scmutil.cleanupnodes(
2930 2930 repo,
2931 2931 mapping,
2932 2932 b'amend',
2933 2933 metadata=obsmetadata,
2934 2934 fixphase=True,
2935 2935 targetphase=commitphase,
2936 2936 backup=backup,
2937 2937 )
2938 2938
2939 2939 # Fixing the dirstate because localrepo.commitctx does not update
2940 2940 # it. This is rather convenient because we did not need to update
2941 2941 # the dirstate for all the files in the new commit which commitctx
2942 2942 # could have done if it updated the dirstate. Now, we can
2943 2943 # selectively update the dirstate only for the amended files.
2944 2944 dirstate = repo.dirstate
2945 2945
2946 2946 # Update the state of the files which were added and modified in the
2947 2947 # amend to "normal" in the dirstate. We need to use "normallookup" since
2948 2948 # the files may have changed since the command started; using "normal"
2949 2949 # would mark them as clean but with uncommitted contents.
2950 2950 normalfiles = set(wctx.modified() + wctx.added()) & filestoamend
2951 2951 for f in normalfiles:
2952 2952 dirstate.normallookup(f)
2953 2953
2954 2954 # Update the state of files which were removed in the amend
2955 2955 # to "removed" in the dirstate.
2956 2956 removedfiles = set(wctx.removed()) & filestoamend
2957 2957 for f in removedfiles:
2958 2958 dirstate.drop(f)
2959 2959
2960 2960 return newid
2961 2961
2962 2962
2963 2963 def commiteditor(repo, ctx, subs, editform=b''):
2964 2964 if ctx.description():
2965 2965 return ctx.description()
2966 2966 return commitforceeditor(
2967 2967 repo, ctx, subs, editform=editform, unchangedmessagedetection=True
2968 2968 )
2969 2969
2970 2970
2971 2971 def commitforceeditor(
2972 2972 repo,
2973 2973 ctx,
2974 2974 subs,
2975 2975 finishdesc=None,
2976 2976 extramsg=None,
2977 2977 editform=b'',
2978 2978 unchangedmessagedetection=False,
2979 2979 ):
2980 2980 if not extramsg:
2981 2981 extramsg = _(b"Leave message empty to abort commit.")
2982 2982
2983 2983 forms = [e for e in editform.split(b'.') if e]
2984 2984 forms.insert(0, b'changeset')
2985 2985 templatetext = None
2986 2986 while forms:
2987 2987 ref = b'.'.join(forms)
2988 2988 if repo.ui.config(b'committemplate', ref):
2989 2989 templatetext = committext = buildcommittemplate(
2990 2990 repo, ctx, subs, extramsg, ref
2991 2991 )
2992 2992 break
2993 2993 forms.pop()
2994 2994 else:
2995 2995 committext = buildcommittext(repo, ctx, subs, extramsg)
2996 2996
2997 2997 # run editor in the repository root
2998 2998 olddir = encoding.getcwd()
2999 2999 os.chdir(repo.root)
3000 3000
3001 3001 # make in-memory changes visible to external process
3002 3002 tr = repo.currenttransaction()
3003 3003 repo.dirstate.write(tr)
3004 3004 pending = tr and tr.writepending() and repo.root
3005 3005
3006 3006 editortext = repo.ui.edit(
3007 3007 committext,
3008 3008 ctx.user(),
3009 3009 ctx.extra(),
3010 3010 editform=editform,
3011 3011 pending=pending,
3012 3012 repopath=repo.path,
3013 3013 action=b'commit',
3014 3014 )
3015 3015 text = editortext
3016 3016
3017 3017 # strip away anything below this special string (used for editors that want
3018 3018 # to display the diff)
3019 3019 stripbelow = re.search(_linebelow, text, flags=re.MULTILINE)
3020 3020 if stripbelow:
3021 3021 text = text[: stripbelow.start()]
3022 3022
3023 3023 text = re.sub(b"(?m)^HG:.*(\n|$)", b"", text)
3024 3024 os.chdir(olddir)
3025 3025
3026 3026 if finishdesc:
3027 3027 text = finishdesc(text)
3028 3028 if not text.strip():
3029 3029 raise error.Abort(_(b"empty commit message"))
3030 3030 if unchangedmessagedetection and editortext == templatetext:
3031 3031 raise error.Abort(_(b"commit message unchanged"))
3032 3032
3033 3033 return text
3034 3034
3035 3035
3036 3036 def buildcommittemplate(repo, ctx, subs, extramsg, ref):
3037 3037 ui = repo.ui
3038 3038 spec = formatter.reference_templatespec(ref)
3039 3039 t = logcmdutil.changesettemplater(ui, repo, spec)
3040 3040 t.t.cache.update(
3041 3041 (k, templater.unquotestring(v))
3042 3042 for k, v in repo.ui.configitems(b'committemplate')
3043 3043 )
3044 3044
3045 3045 if not extramsg:
3046 3046 extramsg = b'' # ensure that extramsg is string
3047 3047
3048 3048 ui.pushbuffer()
3049 3049 t.show(ctx, extramsg=extramsg)
3050 3050 return ui.popbuffer()
3051 3051
3052 3052
3053 3053 def hgprefix(msg):
3054 3054 return b"\n".join([b"HG: %s" % a for a in msg.split(b"\n") if a])
3055 3055
3056 3056
3057 3057 def buildcommittext(repo, ctx, subs, extramsg):
3058 3058 edittext = []
3059 3059 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
3060 3060 if ctx.description():
3061 3061 edittext.append(ctx.description())
3062 3062 edittext.append(b"")
3063 3063 edittext.append(b"") # Empty line between message and comments.
3064 3064 edittext.append(
3065 3065 hgprefix(
3066 3066 _(
3067 3067 b"Enter commit message."
3068 3068 b" Lines beginning with 'HG:' are removed."
3069 3069 )
3070 3070 )
3071 3071 )
3072 3072 edittext.append(hgprefix(extramsg))
3073 3073 edittext.append(b"HG: --")
3074 3074 edittext.append(hgprefix(_(b"user: %s") % ctx.user()))
3075 3075 if ctx.p2():
3076 3076 edittext.append(hgprefix(_(b"branch merge")))
3077 3077 if ctx.branch():
3078 3078 edittext.append(hgprefix(_(b"branch '%s'") % ctx.branch()))
3079 3079 if bookmarks.isactivewdirparent(repo):
3080 3080 edittext.append(hgprefix(_(b"bookmark '%s'") % repo._activebookmark))
3081 3081 edittext.extend([hgprefix(_(b"subrepo %s") % s) for s in subs])
3082 3082 edittext.extend([hgprefix(_(b"added %s") % f) for f in added])
3083 3083 edittext.extend([hgprefix(_(b"changed %s") % f) for f in modified])
3084 3084 edittext.extend([hgprefix(_(b"removed %s") % f) for f in removed])
3085 3085 if not added and not modified and not removed:
3086 3086 edittext.append(hgprefix(_(b"no files changed")))
3087 3087 edittext.append(b"")
3088 3088
3089 3089 return b"\n".join(edittext)
3090 3090
3091 3091
3092 def commitstatus(repo, node, branch, bheads=None, opts=None):
3092 def commitstatus(repo, node, branch, bheads=None, tip=None, opts=None):
3093 3093 if opts is None:
3094 3094 opts = {}
3095 3095 ctx = repo[node]
3096 3096 parents = ctx.parents()
3097 3097
3098 if (
3098 if tip is not None and repo.changelog.tip() == tip:
3099 # avoid reporting something like "committed new head" when
3100 # recommitting old changesets, and issue a helpful warning
3101 # for most instances
3102 repo.ui.warn(_("warning: commit already existed in the repository!\n"))
3103 elif (
3099 3104 not opts.get(b'amend')
3100 3105 and bheads
3101 3106 and node not in bheads
3102 3107 and not any(
3103 3108 p.node() in bheads and p.branch() == branch for p in parents
3104 3109 )
3105 3110 ):
3106 3111 repo.ui.status(_(b'created new head\n'))
3107 3112 # The message is not printed for initial roots. For the other
3108 3113 # changesets, it is printed in the following situations:
3109 3114 #
3110 3115 # Par column: for the 2 parents with ...
3111 3116 # N: null or no parent
3112 3117 # B: parent is on another named branch
3113 3118 # C: parent is a regular non head changeset
3114 3119 # H: parent was a branch head of the current branch
3115 3120 # Msg column: whether we print "created new head" message
3116 3121 # In the following, it is assumed that there already exists some
3117 3122 # initial branch heads of the current branch, otherwise nothing is
3118 3123 # printed anyway.
3119 3124 #
3120 3125 # Par Msg Comment
3121 3126 # N N y additional topo root
3122 3127 #
3123 3128 # B N y additional branch root
3124 3129 # C N y additional topo head
3125 3130 # H N n usual case
3126 3131 #
3127 3132 # B B y weird additional branch root
3128 3133 # C B y branch merge
3129 3134 # H B n merge with named branch
3130 3135 #
3131 3136 # C C y additional head from merge
3132 3137 # C H n merge with a head
3133 3138 #
3134 3139 # H H n head merge: head count decreases
3135 3140
3136 3141 if not opts.get(b'close_branch'):
3137 3142 for r in parents:
3138 3143 if r.closesbranch() and r.branch() == branch:
3139 3144 repo.ui.status(
3140 3145 _(b'reopening closed branch head %d\n') % r.rev()
3141 3146 )
3142 3147
3143 3148 if repo.ui.debugflag:
3144 3149 repo.ui.write(
3145 3150 _(b'committed changeset %d:%s\n') % (ctx.rev(), ctx.hex())
3146 3151 )
3147 3152 elif repo.ui.verbose:
3148 3153 repo.ui.write(_(b'committed changeset %d:%s\n') % (ctx.rev(), ctx))
3149 3154
3150 3155
3151 3156 def postcommitstatus(repo, pats, opts):
3152 3157 return repo.status(match=scmutil.match(repo[None], pats, opts))
3153 3158
3154 3159
3155 3160 def revert(ui, repo, ctx, *pats, **opts):
3156 3161 opts = pycompat.byteskwargs(opts)
3157 3162 parent, p2 = repo.dirstate.parents()
3158 3163 node = ctx.node()
3159 3164
3160 3165 mf = ctx.manifest()
3161 3166 if node == p2:
3162 3167 parent = p2
3163 3168
3164 3169 # need all matching names in dirstate and manifest of target rev,
3165 3170 # so have to walk both. do not print errors if files exist in one
3166 3171 # but not other. in both cases, filesets should be evaluated against
3167 3172 # workingctx to get consistent result (issue4497). this means 'set:**'
3168 3173 # cannot be used to select missing files from target rev.
3169 3174
3170 3175 # `names` is a mapping for all elements in working copy and target revision
3171 3176 # The mapping is in the form:
3172 3177 # <abs path in repo> -> (<path from CWD>, <exactly specified by matcher?>)
3173 3178 names = {}
3174 3179 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
3175 3180
3176 3181 with repo.wlock():
3177 3182 ## filling of the `names` mapping
3178 3183 # walk dirstate to fill `names`
3179 3184
3180 3185 interactive = opts.get(b'interactive', False)
3181 3186 wctx = repo[None]
3182 3187 m = scmutil.match(wctx, pats, opts)
3183 3188
3184 3189 # we'll need this later
3185 3190 targetsubs = sorted(s for s in wctx.substate if m(s))
3186 3191
3187 3192 if not m.always():
3188 3193 matcher = matchmod.badmatch(m, lambda x, y: False)
3189 3194 for abs in wctx.walk(matcher):
3190 3195 names[abs] = m.exact(abs)
3191 3196
3192 3197 # walk target manifest to fill `names`
3193 3198
3194 3199 def badfn(path, msg):
3195 3200 if path in names:
3196 3201 return
3197 3202 if path in ctx.substate:
3198 3203 return
3199 3204 path_ = path + b'/'
3200 3205 for f in names:
3201 3206 if f.startswith(path_):
3202 3207 return
3203 3208 ui.warn(b"%s: %s\n" % (uipathfn(path), msg))
3204 3209
3205 3210 for abs in ctx.walk(matchmod.badmatch(m, badfn)):
3206 3211 if abs not in names:
3207 3212 names[abs] = m.exact(abs)
3208 3213
3209 3214 # Find status of all file in `names`.
3210 3215 m = scmutil.matchfiles(repo, names)
3211 3216
3212 3217 changes = repo.status(
3213 3218 node1=node, match=m, unknown=True, ignored=True, clean=True
3214 3219 )
3215 3220 else:
3216 3221 changes = repo.status(node1=node, match=m)
3217 3222 for kind in changes:
3218 3223 for abs in kind:
3219 3224 names[abs] = m.exact(abs)
3220 3225
3221 3226 m = scmutil.matchfiles(repo, names)
3222 3227
3223 3228 modified = set(changes.modified)
3224 3229 added = set(changes.added)
3225 3230 removed = set(changes.removed)
3226 3231 _deleted = set(changes.deleted)
3227 3232 unknown = set(changes.unknown)
3228 3233 unknown.update(changes.ignored)
3229 3234 clean = set(changes.clean)
3230 3235 modadded = set()
3231 3236
3232 3237 # We need to account for the state of the file in the dirstate,
3233 3238 # even when we revert against something else than parent. This will
3234 3239 # slightly alter the behavior of revert (doing back up or not, delete
3235 3240 # or just forget etc).
3236 3241 if parent == node:
3237 3242 dsmodified = modified
3238 3243 dsadded = added
3239 3244 dsremoved = removed
3240 3245 # store all local modifications, useful later for rename detection
3241 3246 localchanges = dsmodified | dsadded
3242 3247 modified, added, removed = set(), set(), set()
3243 3248 else:
3244 3249 changes = repo.status(node1=parent, match=m)
3245 3250 dsmodified = set(changes.modified)
3246 3251 dsadded = set(changes.added)
3247 3252 dsremoved = set(changes.removed)
3248 3253 # store all local modifications, useful later for rename detection
3249 3254 localchanges = dsmodified | dsadded
3250 3255
3251 3256 # only take into account for removes between wc and target
3252 3257 clean |= dsremoved - removed
3253 3258 dsremoved &= removed
3254 3259 # distinct between dirstate remove and other
3255 3260 removed -= dsremoved
3256 3261
3257 3262 modadded = added & dsmodified
3258 3263 added -= modadded
3259 3264
3260 3265 # tell newly modified apart.
3261 3266 dsmodified &= modified
3262 3267 dsmodified |= modified & dsadded # dirstate added may need backup
3263 3268 modified -= dsmodified
3264 3269
3265 3270 # We need to wait for some post-processing to update this set
3266 3271 # before making the distinction. The dirstate will be used for
3267 3272 # that purpose.
3268 3273 dsadded = added
3269 3274
3270 3275 # in case of merge, files that are actually added can be reported as
3271 3276 # modified, we need to post process the result
3272 3277 if p2 != nullid:
3273 3278 mergeadd = set(dsmodified)
3274 3279 for path in dsmodified:
3275 3280 if path in mf:
3276 3281 mergeadd.remove(path)
3277 3282 dsadded |= mergeadd
3278 3283 dsmodified -= mergeadd
3279 3284
3280 3285 # if f is a rename, update `names` to also revert the source
3281 3286 for f in localchanges:
3282 3287 src = repo.dirstate.copied(f)
3283 3288 # XXX should we check for rename down to target node?
3284 3289 if src and src not in names and repo.dirstate[src] == b'r':
3285 3290 dsremoved.add(src)
3286 3291 names[src] = True
3287 3292
3288 3293 # determine the exact nature of the deleted changesets
3289 3294 deladded = set(_deleted)
3290 3295 for path in _deleted:
3291 3296 if path in mf:
3292 3297 deladded.remove(path)
3293 3298 deleted = _deleted - deladded
3294 3299
3295 3300 # distinguish between file to forget and the other
3296 3301 added = set()
3297 3302 for abs in dsadded:
3298 3303 if repo.dirstate[abs] != b'a':
3299 3304 added.add(abs)
3300 3305 dsadded -= added
3301 3306
3302 3307 for abs in deladded:
3303 3308 if repo.dirstate[abs] == b'a':
3304 3309 dsadded.add(abs)
3305 3310 deladded -= dsadded
3306 3311
3307 3312 # For files marked as removed, we check if an unknown file is present at
3308 3313 # the same path. If a such file exists it may need to be backed up.
3309 3314 # Making the distinction at this stage helps have simpler backup
3310 3315 # logic.
3311 3316 removunk = set()
3312 3317 for abs in removed:
3313 3318 target = repo.wjoin(abs)
3314 3319 if os.path.lexists(target):
3315 3320 removunk.add(abs)
3316 3321 removed -= removunk
3317 3322
3318 3323 dsremovunk = set()
3319 3324 for abs in dsremoved:
3320 3325 target = repo.wjoin(abs)
3321 3326 if os.path.lexists(target):
3322 3327 dsremovunk.add(abs)
3323 3328 dsremoved -= dsremovunk
3324 3329
3325 3330 # action to be actually performed by revert
3326 3331 # (<list of file>, message>) tuple
3327 3332 actions = {
3328 3333 b'revert': ([], _(b'reverting %s\n')),
3329 3334 b'add': ([], _(b'adding %s\n')),
3330 3335 b'remove': ([], _(b'removing %s\n')),
3331 3336 b'drop': ([], _(b'removing %s\n')),
3332 3337 b'forget': ([], _(b'forgetting %s\n')),
3333 3338 b'undelete': ([], _(b'undeleting %s\n')),
3334 3339 b'noop': (None, _(b'no changes needed to %s\n')),
3335 3340 b'unknown': (None, _(b'file not managed: %s\n')),
3336 3341 }
3337 3342
3338 3343 # "constant" that convey the backup strategy.
3339 3344 # All set to `discard` if `no-backup` is set do avoid checking
3340 3345 # no_backup lower in the code.
3341 3346 # These values are ordered for comparison purposes
3342 3347 backupinteractive = 3 # do backup if interactively modified
3343 3348 backup = 2 # unconditionally do backup
3344 3349 check = 1 # check if the existing file differs from target
3345 3350 discard = 0 # never do backup
3346 3351 if opts.get(b'no_backup'):
3347 3352 backupinteractive = backup = check = discard
3348 3353 if interactive:
3349 3354 dsmodifiedbackup = backupinteractive
3350 3355 else:
3351 3356 dsmodifiedbackup = backup
3352 3357 tobackup = set()
3353 3358
3354 3359 backupanddel = actions[b'remove']
3355 3360 if not opts.get(b'no_backup'):
3356 3361 backupanddel = actions[b'drop']
3357 3362
3358 3363 disptable = (
3359 3364 # dispatch table:
3360 3365 # file state
3361 3366 # action
3362 3367 # make backup
3363 3368 ## Sets that results that will change file on disk
3364 3369 # Modified compared to target, no local change
3365 3370 (modified, actions[b'revert'], discard),
3366 3371 # Modified compared to target, but local file is deleted
3367 3372 (deleted, actions[b'revert'], discard),
3368 3373 # Modified compared to target, local change
3369 3374 (dsmodified, actions[b'revert'], dsmodifiedbackup),
3370 3375 # Added since target
3371 3376 (added, actions[b'remove'], discard),
3372 3377 # Added in working directory
3373 3378 (dsadded, actions[b'forget'], discard),
3374 3379 # Added since target, have local modification
3375 3380 (modadded, backupanddel, backup),
3376 3381 # Added since target but file is missing in working directory
3377 3382 (deladded, actions[b'drop'], discard),
3378 3383 # Removed since target, before working copy parent
3379 3384 (removed, actions[b'add'], discard),
3380 3385 # Same as `removed` but an unknown file exists at the same path
3381 3386 (removunk, actions[b'add'], check),
3382 3387 # Removed since targe, marked as such in working copy parent
3383 3388 (dsremoved, actions[b'undelete'], discard),
3384 3389 # Same as `dsremoved` but an unknown file exists at the same path
3385 3390 (dsremovunk, actions[b'undelete'], check),
3386 3391 ## the following sets does not result in any file changes
3387 3392 # File with no modification
3388 3393 (clean, actions[b'noop'], discard),
3389 3394 # Existing file, not tracked anywhere
3390 3395 (unknown, actions[b'unknown'], discard),
3391 3396 )
3392 3397
3393 3398 for abs, exact in sorted(names.items()):
3394 3399 # target file to be touch on disk (relative to cwd)
3395 3400 target = repo.wjoin(abs)
3396 3401 # search the entry in the dispatch table.
3397 3402 # if the file is in any of these sets, it was touched in the working
3398 3403 # directory parent and we are sure it needs to be reverted.
3399 3404 for table, (xlist, msg), dobackup in disptable:
3400 3405 if abs not in table:
3401 3406 continue
3402 3407 if xlist is not None:
3403 3408 xlist.append(abs)
3404 3409 if dobackup:
3405 3410 # If in interactive mode, don't automatically create
3406 3411 # .orig files (issue4793)
3407 3412 if dobackup == backupinteractive:
3408 3413 tobackup.add(abs)
3409 3414 elif backup <= dobackup or wctx[abs].cmp(ctx[abs]):
3410 3415 absbakname = scmutil.backuppath(ui, repo, abs)
3411 3416 bakname = os.path.relpath(
3412 3417 absbakname, start=repo.root
3413 3418 )
3414 3419 ui.note(
3415 3420 _(b'saving current version of %s as %s\n')
3416 3421 % (uipathfn(abs), uipathfn(bakname))
3417 3422 )
3418 3423 if not opts.get(b'dry_run'):
3419 3424 if interactive:
3420 3425 util.copyfile(target, absbakname)
3421 3426 else:
3422 3427 util.rename(target, absbakname)
3423 3428 if opts.get(b'dry_run'):
3424 3429 if ui.verbose or not exact:
3425 3430 ui.status(msg % uipathfn(abs))
3426 3431 elif exact:
3427 3432 ui.warn(msg % uipathfn(abs))
3428 3433 break
3429 3434
3430 3435 if not opts.get(b'dry_run'):
3431 3436 needdata = (b'revert', b'add', b'undelete')
3432 3437 oplist = [actions[name][0] for name in needdata]
3433 3438 prefetch = scmutil.prefetchfiles
3434 3439 matchfiles = scmutil.matchfiles(
3435 3440 repo, [f for sublist in oplist for f in sublist]
3436 3441 )
3437 3442 prefetch(
3438 3443 repo, [(ctx.rev(), matchfiles)],
3439 3444 )
3440 3445 match = scmutil.match(repo[None], pats)
3441 3446 _performrevert(
3442 3447 repo,
3443 3448 ctx,
3444 3449 names,
3445 3450 uipathfn,
3446 3451 actions,
3447 3452 match,
3448 3453 interactive,
3449 3454 tobackup,
3450 3455 )
3451 3456
3452 3457 if targetsubs:
3453 3458 # Revert the subrepos on the revert list
3454 3459 for sub in targetsubs:
3455 3460 try:
3456 3461 wctx.sub(sub).revert(
3457 3462 ctx.substate[sub], *pats, **pycompat.strkwargs(opts)
3458 3463 )
3459 3464 except KeyError:
3460 3465 raise error.Abort(
3461 3466 b"subrepository '%s' does not exist in %s!"
3462 3467 % (sub, short(ctx.node()))
3463 3468 )
3464 3469
3465 3470
3466 3471 def _performrevert(
3467 3472 repo,
3468 3473 ctx,
3469 3474 names,
3470 3475 uipathfn,
3471 3476 actions,
3472 3477 match,
3473 3478 interactive=False,
3474 3479 tobackup=None,
3475 3480 ):
3476 3481 """function that actually perform all the actions computed for revert
3477 3482
3478 3483 This is an independent function to let extension to plug in and react to
3479 3484 the imminent revert.
3480 3485
3481 3486 Make sure you have the working directory locked when calling this function.
3482 3487 """
3483 3488 parent, p2 = repo.dirstate.parents()
3484 3489 node = ctx.node()
3485 3490 excluded_files = []
3486 3491
3487 3492 def checkout(f):
3488 3493 fc = ctx[f]
3489 3494 repo.wwrite(f, fc.data(), fc.flags())
3490 3495
3491 3496 def doremove(f):
3492 3497 try:
3493 3498 rmdir = repo.ui.configbool(b'experimental', b'removeemptydirs')
3494 3499 repo.wvfs.unlinkpath(f, rmdir=rmdir)
3495 3500 except OSError:
3496 3501 pass
3497 3502 repo.dirstate.remove(f)
3498 3503
3499 3504 def prntstatusmsg(action, f):
3500 3505 exact = names[f]
3501 3506 if repo.ui.verbose or not exact:
3502 3507 repo.ui.status(actions[action][1] % uipathfn(f))
3503 3508
3504 3509 audit_path = pathutil.pathauditor(repo.root, cached=True)
3505 3510 for f in actions[b'forget'][0]:
3506 3511 if interactive:
3507 3512 choice = repo.ui.promptchoice(
3508 3513 _(b"forget added file %s (Yn)?$$ &Yes $$ &No") % uipathfn(f)
3509 3514 )
3510 3515 if choice == 0:
3511 3516 prntstatusmsg(b'forget', f)
3512 3517 repo.dirstate.drop(f)
3513 3518 else:
3514 3519 excluded_files.append(f)
3515 3520 else:
3516 3521 prntstatusmsg(b'forget', f)
3517 3522 repo.dirstate.drop(f)
3518 3523 for f in actions[b'remove'][0]:
3519 3524 audit_path(f)
3520 3525 if interactive:
3521 3526 choice = repo.ui.promptchoice(
3522 3527 _(b"remove added file %s (Yn)?$$ &Yes $$ &No") % uipathfn(f)
3523 3528 )
3524 3529 if choice == 0:
3525 3530 prntstatusmsg(b'remove', f)
3526 3531 doremove(f)
3527 3532 else:
3528 3533 excluded_files.append(f)
3529 3534 else:
3530 3535 prntstatusmsg(b'remove', f)
3531 3536 doremove(f)
3532 3537 for f in actions[b'drop'][0]:
3533 3538 audit_path(f)
3534 3539 prntstatusmsg(b'drop', f)
3535 3540 repo.dirstate.remove(f)
3536 3541
3537 3542 normal = None
3538 3543 if node == parent:
3539 3544 # We're reverting to our parent. If possible, we'd like status
3540 3545 # to report the file as clean. We have to use normallookup for
3541 3546 # merges to avoid losing information about merged/dirty files.
3542 3547 if p2 != nullid:
3543 3548 normal = repo.dirstate.normallookup
3544 3549 else:
3545 3550 normal = repo.dirstate.normal
3546 3551
3547 3552 newlyaddedandmodifiedfiles = set()
3548 3553 if interactive:
3549 3554 # Prompt the user for changes to revert
3550 3555 torevert = [f for f in actions[b'revert'][0] if f not in excluded_files]
3551 3556 m = scmutil.matchfiles(repo, torevert)
3552 3557 diffopts = patch.difffeatureopts(
3553 3558 repo.ui,
3554 3559 whitespace=True,
3555 3560 section=b'commands',
3556 3561 configprefix=b'revert.interactive.',
3557 3562 )
3558 3563 diffopts.nodates = True
3559 3564 diffopts.git = True
3560 3565 operation = b'apply'
3561 3566 if node == parent:
3562 3567 if repo.ui.configbool(
3563 3568 b'experimental', b'revert.interactive.select-to-keep'
3564 3569 ):
3565 3570 operation = b'keep'
3566 3571 else:
3567 3572 operation = b'discard'
3568 3573
3569 3574 if operation == b'apply':
3570 3575 diff = patch.diff(repo, None, ctx.node(), m, opts=diffopts)
3571 3576 else:
3572 3577 diff = patch.diff(repo, ctx.node(), None, m, opts=diffopts)
3573 3578 originalchunks = patch.parsepatch(diff)
3574 3579
3575 3580 try:
3576 3581
3577 3582 chunks, opts = recordfilter(
3578 3583 repo.ui, originalchunks, match, operation=operation
3579 3584 )
3580 3585 if operation == b'discard':
3581 3586 chunks = patch.reversehunks(chunks)
3582 3587
3583 3588 except error.PatchError as err:
3584 3589 raise error.Abort(_(b'error parsing patch: %s') % err)
3585 3590
3586 3591 # FIXME: when doing an interactive revert of a copy, there's no way of
3587 3592 # performing a partial revert of the added file, the only option is
3588 3593 # "remove added file <name> (Yn)?", so we don't need to worry about the
3589 3594 # alsorestore value. Ideally we'd be able to partially revert
3590 3595 # copied/renamed files.
3591 3596 newlyaddedandmodifiedfiles, unusedalsorestore = newandmodified(
3592 3597 chunks, originalchunks
3593 3598 )
3594 3599 if tobackup is None:
3595 3600 tobackup = set()
3596 3601 # Apply changes
3597 3602 fp = stringio()
3598 3603 # chunks are serialized per file, but files aren't sorted
3599 3604 for f in sorted({c.header.filename() for c in chunks if ishunk(c)}):
3600 3605 prntstatusmsg(b'revert', f)
3601 3606 files = set()
3602 3607 for c in chunks:
3603 3608 if ishunk(c):
3604 3609 abs = c.header.filename()
3605 3610 # Create a backup file only if this hunk should be backed up
3606 3611 if c.header.filename() in tobackup:
3607 3612 target = repo.wjoin(abs)
3608 3613 bakname = scmutil.backuppath(repo.ui, repo, abs)
3609 3614 util.copyfile(target, bakname)
3610 3615 tobackup.remove(abs)
3611 3616 if abs not in files:
3612 3617 files.add(abs)
3613 3618 if operation == b'keep':
3614 3619 checkout(abs)
3615 3620 c.write(fp)
3616 3621 dopatch = fp.tell()
3617 3622 fp.seek(0)
3618 3623 if dopatch:
3619 3624 try:
3620 3625 patch.internalpatch(repo.ui, repo, fp, 1, eolmode=None)
3621 3626 except error.PatchError as err:
3622 3627 raise error.Abort(pycompat.bytestr(err))
3623 3628 del fp
3624 3629 else:
3625 3630 for f in actions[b'revert'][0]:
3626 3631 prntstatusmsg(b'revert', f)
3627 3632 checkout(f)
3628 3633 if normal:
3629 3634 normal(f)
3630 3635
3631 3636 for f in actions[b'add'][0]:
3632 3637 # Don't checkout modified files, they are already created by the diff
3633 3638 if f not in newlyaddedandmodifiedfiles:
3634 3639 prntstatusmsg(b'add', f)
3635 3640 checkout(f)
3636 3641 repo.dirstate.add(f)
3637 3642
3638 3643 normal = repo.dirstate.normallookup
3639 3644 if node == parent and p2 == nullid:
3640 3645 normal = repo.dirstate.normal
3641 3646 for f in actions[b'undelete'][0]:
3642 3647 if interactive:
3643 3648 choice = repo.ui.promptchoice(
3644 3649 _(b"add back removed file %s (Yn)?$$ &Yes $$ &No") % f
3645 3650 )
3646 3651 if choice == 0:
3647 3652 prntstatusmsg(b'undelete', f)
3648 3653 checkout(f)
3649 3654 normal(f)
3650 3655 else:
3651 3656 excluded_files.append(f)
3652 3657 else:
3653 3658 prntstatusmsg(b'undelete', f)
3654 3659 checkout(f)
3655 3660 normal(f)
3656 3661
3657 3662 copied = copies.pathcopies(repo[parent], ctx)
3658 3663
3659 3664 for f in (
3660 3665 actions[b'add'][0] + actions[b'undelete'][0] + actions[b'revert'][0]
3661 3666 ):
3662 3667 if f in copied:
3663 3668 repo.dirstate.copy(copied[f], f)
3664 3669
3665 3670
3666 3671 # a list of (ui, repo, otherpeer, opts, missing) functions called by
3667 3672 # commands.outgoing. "missing" is "missing" of the result of
3668 3673 # "findcommonoutgoing()"
3669 3674 outgoinghooks = util.hooks()
3670 3675
3671 3676 # a list of (ui, repo) functions called by commands.summary
3672 3677 summaryhooks = util.hooks()
3673 3678
3674 3679 # a list of (ui, repo, opts, changes) functions called by commands.summary.
3675 3680 #
3676 3681 # functions should return tuple of booleans below, if 'changes' is None:
3677 3682 # (whether-incomings-are-needed, whether-outgoings-are-needed)
3678 3683 #
3679 3684 # otherwise, 'changes' is a tuple of tuples below:
3680 3685 # - (sourceurl, sourcebranch, sourcepeer, incoming)
3681 3686 # - (desturl, destbranch, destpeer, outgoing)
3682 3687 summaryremotehooks = util.hooks()
3683 3688
3684 3689
3685 3690 def checkunfinished(repo, commit=False, skipmerge=False):
3686 3691 '''Look for an unfinished multistep operation, like graft, and abort
3687 3692 if found. It's probably good to check this right before
3688 3693 bailifchanged().
3689 3694 '''
3690 3695 # Check for non-clearable states first, so things like rebase will take
3691 3696 # precedence over update.
3692 3697 for state in statemod._unfinishedstates:
3693 3698 if (
3694 3699 state._clearable
3695 3700 or (commit and state._allowcommit)
3696 3701 or state._reportonly
3697 3702 ):
3698 3703 continue
3699 3704 if state.isunfinished(repo):
3700 3705 raise error.Abort(state.msg(), hint=state.hint())
3701 3706
3702 3707 for s in statemod._unfinishedstates:
3703 3708 if (
3704 3709 not s._clearable
3705 3710 or (commit and s._allowcommit)
3706 3711 or (s._opname == b'merge' and skipmerge)
3707 3712 or s._reportonly
3708 3713 ):
3709 3714 continue
3710 3715 if s.isunfinished(repo):
3711 3716 raise error.Abort(s.msg(), hint=s.hint())
3712 3717
3713 3718
3714 3719 def clearunfinished(repo):
3715 3720 '''Check for unfinished operations (as above), and clear the ones
3716 3721 that are clearable.
3717 3722 '''
3718 3723 for state in statemod._unfinishedstates:
3719 3724 if state._reportonly:
3720 3725 continue
3721 3726 if not state._clearable and state.isunfinished(repo):
3722 3727 raise error.Abort(state.msg(), hint=state.hint())
3723 3728
3724 3729 for s in statemod._unfinishedstates:
3725 3730 if s._opname == b'merge' or state._reportonly:
3726 3731 continue
3727 3732 if s._clearable and s.isunfinished(repo):
3728 3733 util.unlink(repo.vfs.join(s._fname))
3729 3734
3730 3735
3731 3736 def getunfinishedstate(repo):
3732 3737 ''' Checks for unfinished operations and returns statecheck object
3733 3738 for it'''
3734 3739 for state in statemod._unfinishedstates:
3735 3740 if state.isunfinished(repo):
3736 3741 return state
3737 3742 return None
3738 3743
3739 3744
3740 3745 def howtocontinue(repo):
3741 3746 '''Check for an unfinished operation and return the command to finish
3742 3747 it.
3743 3748
3744 3749 statemod._unfinishedstates list is checked for an unfinished operation
3745 3750 and the corresponding message to finish it is generated if a method to
3746 3751 continue is supported by the operation.
3747 3752
3748 3753 Returns a (msg, warning) tuple. 'msg' is a string and 'warning' is
3749 3754 a boolean.
3750 3755 '''
3751 3756 contmsg = _(b"continue: %s")
3752 3757 for state in statemod._unfinishedstates:
3753 3758 if not state._continueflag:
3754 3759 continue
3755 3760 if state.isunfinished(repo):
3756 3761 return contmsg % state.continuemsg(), True
3757 3762 if repo[None].dirty(missing=True, merge=False, branch=False):
3758 3763 return contmsg % _(b"hg commit"), False
3759 3764 return None, None
3760 3765
3761 3766
3762 3767 def checkafterresolved(repo):
3763 3768 '''Inform the user about the next action after completing hg resolve
3764 3769
3765 3770 If there's a an unfinished operation that supports continue flag,
3766 3771 howtocontinue will yield repo.ui.warn as the reporter.
3767 3772
3768 3773 Otherwise, it will yield repo.ui.note.
3769 3774 '''
3770 3775 msg, warning = howtocontinue(repo)
3771 3776 if msg is not None:
3772 3777 if warning:
3773 3778 repo.ui.warn(b"%s\n" % msg)
3774 3779 else:
3775 3780 repo.ui.note(b"%s\n" % msg)
3776 3781
3777 3782
3778 3783 def wrongtooltocontinue(repo, task):
3779 3784 '''Raise an abort suggesting how to properly continue if there is an
3780 3785 active task.
3781 3786
3782 3787 Uses howtocontinue() to find the active task.
3783 3788
3784 3789 If there's no task (repo.ui.note for 'hg commit'), it does not offer
3785 3790 a hint.
3786 3791 '''
3787 3792 after = howtocontinue(repo)
3788 3793 hint = None
3789 3794 if after[1]:
3790 3795 hint = after[0]
3791 3796 raise error.Abort(_(b'no %s in progress') % task, hint=hint)
3792 3797
3793 3798
3794 3799 def abortgraft(ui, repo, graftstate):
3795 3800 """abort the interrupted graft and rollbacks to the state before interrupted
3796 3801 graft"""
3797 3802 if not graftstate.exists():
3798 3803 raise error.Abort(_(b"no interrupted graft to abort"))
3799 3804 statedata = readgraftstate(repo, graftstate)
3800 3805 newnodes = statedata.get(b'newnodes')
3801 3806 if newnodes is None:
3802 3807 # and old graft state which does not have all the data required to abort
3803 3808 # the graft
3804 3809 raise error.Abort(_(b"cannot abort using an old graftstate"))
3805 3810
3806 3811 # changeset from which graft operation was started
3807 3812 if len(newnodes) > 0:
3808 3813 startctx = repo[newnodes[0]].p1()
3809 3814 else:
3810 3815 startctx = repo[b'.']
3811 3816 # whether to strip or not
3812 3817 cleanup = False
3813 3818
3814 3819 if newnodes:
3815 3820 newnodes = [repo[r].rev() for r in newnodes]
3816 3821 cleanup = True
3817 3822 # checking that none of the newnodes turned public or is public
3818 3823 immutable = [c for c in newnodes if not repo[c].mutable()]
3819 3824 if immutable:
3820 3825 repo.ui.warn(
3821 3826 _(b"cannot clean up public changesets %s\n")
3822 3827 % b', '.join(bytes(repo[r]) for r in immutable),
3823 3828 hint=_(b"see 'hg help phases' for details"),
3824 3829 )
3825 3830 cleanup = False
3826 3831
3827 3832 # checking that no new nodes are created on top of grafted revs
3828 3833 desc = set(repo.changelog.descendants(newnodes))
3829 3834 if desc - set(newnodes):
3830 3835 repo.ui.warn(
3831 3836 _(
3832 3837 b"new changesets detected on destination "
3833 3838 b"branch, can't strip\n"
3834 3839 )
3835 3840 )
3836 3841 cleanup = False
3837 3842
3838 3843 if cleanup:
3839 3844 with repo.wlock(), repo.lock():
3840 3845 mergemod.clean_update(startctx)
3841 3846 # stripping the new nodes created
3842 3847 strippoints = [
3843 3848 c.node() for c in repo.set(b"roots(%ld)", newnodes)
3844 3849 ]
3845 3850 repair.strip(repo.ui, repo, strippoints, backup=False)
3846 3851
3847 3852 if not cleanup:
3848 3853 # we don't update to the startnode if we can't strip
3849 3854 startctx = repo[b'.']
3850 3855 mergemod.clean_update(startctx)
3851 3856
3852 3857 ui.status(_(b"graft aborted\n"))
3853 3858 ui.status(_(b"working directory is now at %s\n") % startctx.hex()[:12])
3854 3859 graftstate.delete()
3855 3860 return 0
3856 3861
3857 3862
3858 3863 def readgraftstate(repo, graftstate):
3859 3864 # type: (Any, statemod.cmdstate) -> Dict[bytes, Any]
3860 3865 """read the graft state file and return a dict of the data stored in it"""
3861 3866 try:
3862 3867 return graftstate.read()
3863 3868 except error.CorruptedState:
3864 3869 nodes = repo.vfs.read(b'graftstate').splitlines()
3865 3870 return {b'nodes': nodes}
3866 3871
3867 3872
3868 3873 def hgabortgraft(ui, repo):
3869 3874 """ abort logic for aborting graft using 'hg abort'"""
3870 3875 with repo.wlock():
3871 3876 graftstate = statemod.cmdstate(repo, b'graftstate')
3872 3877 return abortgraft(ui, repo, graftstate)
@@ -1,7656 +1,7660 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 changegroup,
30 30 cmdutil,
31 31 copies,
32 32 debugcommands as debugcommandsmod,
33 33 destutil,
34 34 dirstateguard,
35 35 discovery,
36 36 encoding,
37 37 error,
38 38 exchange,
39 39 extensions,
40 40 filemerge,
41 41 formatter,
42 42 graphmod,
43 43 grep as grepmod,
44 44 hbisect,
45 45 help,
46 46 hg,
47 47 logcmdutil,
48 48 merge as mergemod,
49 49 mergestate as mergestatemod,
50 50 narrowspec,
51 51 obsolete,
52 52 obsutil,
53 53 patch,
54 54 phases,
55 55 pycompat,
56 56 rcutil,
57 57 registrar,
58 58 requirements,
59 59 revsetlang,
60 60 rewriteutil,
61 61 scmutil,
62 62 server,
63 63 shelve as shelvemod,
64 64 state as statemod,
65 65 streamclone,
66 66 tags as tagsmod,
67 67 ui as uimod,
68 68 util,
69 69 verify as verifymod,
70 70 vfs as vfsmod,
71 71 wireprotoserver,
72 72 )
73 73 from .utils import (
74 74 dateutil,
75 75 stringutil,
76 76 )
77 77
78 78 table = {}
79 79 table.update(debugcommandsmod.command._table)
80 80
81 81 command = registrar.command(table)
82 82 INTENT_READONLY = registrar.INTENT_READONLY
83 83
84 84 # common command options
85 85
86 86 globalopts = [
87 87 (
88 88 b'R',
89 89 b'repository',
90 90 b'',
91 91 _(b'repository root directory or name of overlay bundle file'),
92 92 _(b'REPO'),
93 93 ),
94 94 (b'', b'cwd', b'', _(b'change working directory'), _(b'DIR')),
95 95 (
96 96 b'y',
97 97 b'noninteractive',
98 98 None,
99 99 _(
100 100 b'do not prompt, automatically pick the first choice for all prompts'
101 101 ),
102 102 ),
103 103 (b'q', b'quiet', None, _(b'suppress output')),
104 104 (b'v', b'verbose', None, _(b'enable additional output')),
105 105 (
106 106 b'',
107 107 b'color',
108 108 b'',
109 109 # i18n: 'always', 'auto', 'never', and 'debug' are keywords
110 110 # and should not be translated
111 111 _(b"when to colorize (boolean, always, auto, never, or debug)"),
112 112 _(b'TYPE'),
113 113 ),
114 114 (
115 115 b'',
116 116 b'config',
117 117 [],
118 118 _(b'set/override config option (use \'section.name=value\')'),
119 119 _(b'CONFIG'),
120 120 ),
121 121 (b'', b'debug', None, _(b'enable debugging output')),
122 122 (b'', b'debugger', None, _(b'start debugger')),
123 123 (
124 124 b'',
125 125 b'encoding',
126 126 encoding.encoding,
127 127 _(b'set the charset encoding'),
128 128 _(b'ENCODE'),
129 129 ),
130 130 (
131 131 b'',
132 132 b'encodingmode',
133 133 encoding.encodingmode,
134 134 _(b'set the charset encoding mode'),
135 135 _(b'MODE'),
136 136 ),
137 137 (b'', b'traceback', None, _(b'always print a traceback on exception')),
138 138 (b'', b'time', None, _(b'time how long the command takes')),
139 139 (b'', b'profile', None, _(b'print command execution profile')),
140 140 (b'', b'version', None, _(b'output version information and exit')),
141 141 (b'h', b'help', None, _(b'display help and exit')),
142 142 (b'', b'hidden', False, _(b'consider hidden changesets')),
143 143 (
144 144 b'',
145 145 b'pager',
146 146 b'auto',
147 147 _(b"when to paginate (boolean, always, auto, or never)"),
148 148 _(b'TYPE'),
149 149 ),
150 150 ]
151 151
152 152 dryrunopts = cmdutil.dryrunopts
153 153 remoteopts = cmdutil.remoteopts
154 154 walkopts = cmdutil.walkopts
155 155 commitopts = cmdutil.commitopts
156 156 commitopts2 = cmdutil.commitopts2
157 157 commitopts3 = cmdutil.commitopts3
158 158 formatteropts = cmdutil.formatteropts
159 159 templateopts = cmdutil.templateopts
160 160 logopts = cmdutil.logopts
161 161 diffopts = cmdutil.diffopts
162 162 diffwsopts = cmdutil.diffwsopts
163 163 diffopts2 = cmdutil.diffopts2
164 164 mergetoolopts = cmdutil.mergetoolopts
165 165 similarityopts = cmdutil.similarityopts
166 166 subrepoopts = cmdutil.subrepoopts
167 167 debugrevlogopts = cmdutil.debugrevlogopts
168 168
169 169 # Commands start here, listed alphabetically
170 170
171 171
172 172 @command(
173 173 b'abort',
174 174 dryrunopts,
175 175 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
176 176 helpbasic=True,
177 177 )
178 178 def abort(ui, repo, **opts):
179 179 """abort an unfinished operation (EXPERIMENTAL)
180 180
181 181 Aborts a multistep operation like graft, histedit, rebase, merge,
182 182 and unshelve if they are in an unfinished state.
183 183
184 184 use --dry-run/-n to dry run the command.
185 185 """
186 186 dryrun = opts.get('dry_run')
187 187 abortstate = cmdutil.getunfinishedstate(repo)
188 188 if not abortstate:
189 189 raise error.Abort(_(b'no operation in progress'))
190 190 if not abortstate.abortfunc:
191 191 raise error.Abort(
192 192 (
193 193 _(b"%s in progress but does not support 'hg abort'")
194 194 % (abortstate._opname)
195 195 ),
196 196 hint=abortstate.hint(),
197 197 )
198 198 if dryrun:
199 199 ui.status(
200 200 _(b'%s in progress, will be aborted\n') % (abortstate._opname)
201 201 )
202 202 return
203 203 return abortstate.abortfunc(ui, repo)
204 204
205 205
206 206 @command(
207 207 b'add',
208 208 walkopts + subrepoopts + dryrunopts,
209 209 _(b'[OPTION]... [FILE]...'),
210 210 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
211 211 helpbasic=True,
212 212 inferrepo=True,
213 213 )
214 214 def add(ui, repo, *pats, **opts):
215 215 """add the specified files on the next commit
216 216
217 217 Schedule files to be version controlled and added to the
218 218 repository.
219 219
220 220 The files will be added to the repository at the next commit. To
221 221 undo an add before that, see :hg:`forget`.
222 222
223 223 If no names are given, add all files to the repository (except
224 224 files matching ``.hgignore``).
225 225
226 226 .. container:: verbose
227 227
228 228 Examples:
229 229
230 230 - New (unknown) files are added
231 231 automatically by :hg:`add`::
232 232
233 233 $ ls
234 234 foo.c
235 235 $ hg status
236 236 ? foo.c
237 237 $ hg add
238 238 adding foo.c
239 239 $ hg status
240 240 A foo.c
241 241
242 242 - Specific files to be added can be specified::
243 243
244 244 $ ls
245 245 bar.c foo.c
246 246 $ hg status
247 247 ? bar.c
248 248 ? foo.c
249 249 $ hg add bar.c
250 250 $ hg status
251 251 A bar.c
252 252 ? foo.c
253 253
254 254 Returns 0 if all files are successfully added.
255 255 """
256 256
257 257 m = scmutil.match(repo[None], pats, pycompat.byteskwargs(opts))
258 258 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
259 259 rejected = cmdutil.add(ui, repo, m, b"", uipathfn, False, **opts)
260 260 return rejected and 1 or 0
261 261
262 262
263 263 @command(
264 264 b'addremove',
265 265 similarityopts + subrepoopts + walkopts + dryrunopts,
266 266 _(b'[OPTION]... [FILE]...'),
267 267 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
268 268 inferrepo=True,
269 269 )
270 270 def addremove(ui, repo, *pats, **opts):
271 271 """add all new files, delete all missing files
272 272
273 273 Add all new files and remove all missing files from the
274 274 repository.
275 275
276 276 Unless names are given, new files are ignored if they match any of
277 277 the patterns in ``.hgignore``. As with add, these changes take
278 278 effect at the next commit.
279 279
280 280 Use the -s/--similarity option to detect renamed files. This
281 281 option takes a percentage between 0 (disabled) and 100 (files must
282 282 be identical) as its parameter. With a parameter greater than 0,
283 283 this compares every removed file with every added file and records
284 284 those similar enough as renames. Detecting renamed files this way
285 285 can be expensive. After using this option, :hg:`status -C` can be
286 286 used to check which files were identified as moved or renamed. If
287 287 not specified, -s/--similarity defaults to 100 and only renames of
288 288 identical files are detected.
289 289
290 290 .. container:: verbose
291 291
292 292 Examples:
293 293
294 294 - A number of files (bar.c and foo.c) are new,
295 295 while foobar.c has been removed (without using :hg:`remove`)
296 296 from the repository::
297 297
298 298 $ ls
299 299 bar.c foo.c
300 300 $ hg status
301 301 ! foobar.c
302 302 ? bar.c
303 303 ? foo.c
304 304 $ hg addremove
305 305 adding bar.c
306 306 adding foo.c
307 307 removing foobar.c
308 308 $ hg status
309 309 A bar.c
310 310 A foo.c
311 311 R foobar.c
312 312
313 313 - A file foobar.c was moved to foo.c without using :hg:`rename`.
314 314 Afterwards, it was edited slightly::
315 315
316 316 $ ls
317 317 foo.c
318 318 $ hg status
319 319 ! foobar.c
320 320 ? foo.c
321 321 $ hg addremove --similarity 90
322 322 removing foobar.c
323 323 adding foo.c
324 324 recording removal of foobar.c as rename to foo.c (94% similar)
325 325 $ hg status -C
326 326 A foo.c
327 327 foobar.c
328 328 R foobar.c
329 329
330 330 Returns 0 if all files are successfully added.
331 331 """
332 332 opts = pycompat.byteskwargs(opts)
333 333 if not opts.get(b'similarity'):
334 334 opts[b'similarity'] = b'100'
335 335 matcher = scmutil.match(repo[None], pats, opts)
336 336 relative = scmutil.anypats(pats, opts)
337 337 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=relative)
338 338 return scmutil.addremove(repo, matcher, b"", uipathfn, opts)
339 339
340 340
341 341 @command(
342 342 b'annotate|blame',
343 343 [
344 344 (b'r', b'rev', b'', _(b'annotate the specified revision'), _(b'REV')),
345 345 (
346 346 b'',
347 347 b'follow',
348 348 None,
349 349 _(b'follow copies/renames and list the filename (DEPRECATED)'),
350 350 ),
351 351 (b'', b'no-follow', None, _(b"don't follow copies and renames")),
352 352 (b'a', b'text', None, _(b'treat all files as text')),
353 353 (b'u', b'user', None, _(b'list the author (long with -v)')),
354 354 (b'f', b'file', None, _(b'list the filename')),
355 355 (b'd', b'date', None, _(b'list the date (short with -q)')),
356 356 (b'n', b'number', None, _(b'list the revision number (default)')),
357 357 (b'c', b'changeset', None, _(b'list the changeset')),
358 358 (
359 359 b'l',
360 360 b'line-number',
361 361 None,
362 362 _(b'show line number at the first appearance'),
363 363 ),
364 364 (
365 365 b'',
366 366 b'skip',
367 367 [],
368 368 _(b'revset to not display (EXPERIMENTAL)'),
369 369 _(b'REV'),
370 370 ),
371 371 ]
372 372 + diffwsopts
373 373 + walkopts
374 374 + formatteropts,
375 375 _(b'[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
376 376 helpcategory=command.CATEGORY_FILE_CONTENTS,
377 377 helpbasic=True,
378 378 inferrepo=True,
379 379 )
380 380 def annotate(ui, repo, *pats, **opts):
381 381 """show changeset information by line for each file
382 382
383 383 List changes in files, showing the revision id responsible for
384 384 each line.
385 385
386 386 This command is useful for discovering when a change was made and
387 387 by whom.
388 388
389 389 If you include --file, --user, or --date, the revision number is
390 390 suppressed unless you also include --number.
391 391
392 392 Without the -a/--text option, annotate will avoid processing files
393 393 it detects as binary. With -a, annotate will annotate the file
394 394 anyway, although the results will probably be neither useful
395 395 nor desirable.
396 396
397 397 .. container:: verbose
398 398
399 399 Template:
400 400
401 401 The following keywords are supported in addition to the common template
402 402 keywords and functions. See also :hg:`help templates`.
403 403
404 404 :lines: List of lines with annotation data.
405 405 :path: String. Repository-absolute path of the specified file.
406 406
407 407 And each entry of ``{lines}`` provides the following sub-keywords in
408 408 addition to ``{date}``, ``{node}``, ``{rev}``, ``{user}``, etc.
409 409
410 410 :line: String. Line content.
411 411 :lineno: Integer. Line number at that revision.
412 412 :path: String. Repository-absolute path of the file at that revision.
413 413
414 414 See :hg:`help templates.operators` for the list expansion syntax.
415 415
416 416 Returns 0 on success.
417 417 """
418 418 opts = pycompat.byteskwargs(opts)
419 419 if not pats:
420 420 raise error.Abort(_(b'at least one filename or pattern is required'))
421 421
422 422 if opts.get(b'follow'):
423 423 # --follow is deprecated and now just an alias for -f/--file
424 424 # to mimic the behavior of Mercurial before version 1.5
425 425 opts[b'file'] = True
426 426
427 427 if (
428 428 not opts.get(b'user')
429 429 and not opts.get(b'changeset')
430 430 and not opts.get(b'date')
431 431 and not opts.get(b'file')
432 432 ):
433 433 opts[b'number'] = True
434 434
435 435 linenumber = opts.get(b'line_number') is not None
436 436 if (
437 437 linenumber
438 438 and (not opts.get(b'changeset'))
439 439 and (not opts.get(b'number'))
440 440 ):
441 441 raise error.Abort(_(b'at least one of -n/-c is required for -l'))
442 442
443 443 rev = opts.get(b'rev')
444 444 if rev:
445 445 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
446 446 ctx = scmutil.revsingle(repo, rev)
447 447
448 448 ui.pager(b'annotate')
449 449 rootfm = ui.formatter(b'annotate', opts)
450 450 if ui.debugflag:
451 451 shorthex = pycompat.identity
452 452 else:
453 453
454 454 def shorthex(h):
455 455 return h[:12]
456 456
457 457 if ui.quiet:
458 458 datefunc = dateutil.shortdate
459 459 else:
460 460 datefunc = dateutil.datestr
461 461 if ctx.rev() is None:
462 462 if opts.get(b'changeset'):
463 463 # omit "+" suffix which is appended to node hex
464 464 def formatrev(rev):
465 465 if rev == wdirrev:
466 466 return b'%d' % ctx.p1().rev()
467 467 else:
468 468 return b'%d' % rev
469 469
470 470 else:
471 471
472 472 def formatrev(rev):
473 473 if rev == wdirrev:
474 474 return b'%d+' % ctx.p1().rev()
475 475 else:
476 476 return b'%d ' % rev
477 477
478 478 def formathex(h):
479 479 if h == wdirhex:
480 480 return b'%s+' % shorthex(hex(ctx.p1().node()))
481 481 else:
482 482 return b'%s ' % shorthex(h)
483 483
484 484 else:
485 485 formatrev = b'%d'.__mod__
486 486 formathex = shorthex
487 487
488 488 opmap = [
489 489 (b'user', b' ', lambda x: x.fctx.user(), ui.shortuser),
490 490 (b'rev', b' ', lambda x: scmutil.intrev(x.fctx), formatrev),
491 491 (b'node', b' ', lambda x: hex(scmutil.binnode(x.fctx)), formathex),
492 492 (b'date', b' ', lambda x: x.fctx.date(), util.cachefunc(datefunc)),
493 493 (b'path', b' ', lambda x: x.fctx.path(), pycompat.bytestr),
494 494 (b'lineno', b':', lambda x: x.lineno, pycompat.bytestr),
495 495 ]
496 496 opnamemap = {
497 497 b'rev': b'number',
498 498 b'node': b'changeset',
499 499 b'path': b'file',
500 500 b'lineno': b'line_number',
501 501 }
502 502
503 503 if rootfm.isplain():
504 504
505 505 def makefunc(get, fmt):
506 506 return lambda x: fmt(get(x))
507 507
508 508 else:
509 509
510 510 def makefunc(get, fmt):
511 511 return get
512 512
513 513 datahint = rootfm.datahint()
514 514 funcmap = [
515 515 (makefunc(get, fmt), sep)
516 516 for fn, sep, get, fmt in opmap
517 517 if opts.get(opnamemap.get(fn, fn)) or fn in datahint
518 518 ]
519 519 funcmap[0] = (funcmap[0][0], b'') # no separator in front of first column
520 520 fields = b' '.join(
521 521 fn
522 522 for fn, sep, get, fmt in opmap
523 523 if opts.get(opnamemap.get(fn, fn)) or fn in datahint
524 524 )
525 525
526 526 def bad(x, y):
527 527 raise error.Abort(b"%s: %s" % (x, y))
528 528
529 529 m = scmutil.match(ctx, pats, opts, badfn=bad)
530 530
531 531 follow = not opts.get(b'no_follow')
532 532 diffopts = patch.difffeatureopts(
533 533 ui, opts, section=b'annotate', whitespace=True
534 534 )
535 535 skiprevs = opts.get(b'skip')
536 536 if skiprevs:
537 537 skiprevs = scmutil.revrange(repo, skiprevs)
538 538
539 539 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
540 540 for abs in ctx.walk(m):
541 541 fctx = ctx[abs]
542 542 rootfm.startitem()
543 543 rootfm.data(path=abs)
544 544 if not opts.get(b'text') and fctx.isbinary():
545 545 rootfm.plain(_(b"%s: binary file\n") % uipathfn(abs))
546 546 continue
547 547
548 548 fm = rootfm.nested(b'lines', tmpl=b'{rev}: {line}')
549 549 lines = fctx.annotate(
550 550 follow=follow, skiprevs=skiprevs, diffopts=diffopts
551 551 )
552 552 if not lines:
553 553 fm.end()
554 554 continue
555 555 formats = []
556 556 pieces = []
557 557
558 558 for f, sep in funcmap:
559 559 l = [f(n) for n in lines]
560 560 if fm.isplain():
561 561 sizes = [encoding.colwidth(x) for x in l]
562 562 ml = max(sizes)
563 563 formats.append([sep + b' ' * (ml - w) + b'%s' for w in sizes])
564 564 else:
565 565 formats.append([b'%s'] * len(l))
566 566 pieces.append(l)
567 567
568 568 for f, p, n in zip(zip(*formats), zip(*pieces), lines):
569 569 fm.startitem()
570 570 fm.context(fctx=n.fctx)
571 571 fm.write(fields, b"".join(f), *p)
572 572 if n.skip:
573 573 fmt = b"* %s"
574 574 else:
575 575 fmt = b": %s"
576 576 fm.write(b'line', fmt, n.text)
577 577
578 578 if not lines[-1].text.endswith(b'\n'):
579 579 fm.plain(b'\n')
580 580 fm.end()
581 581
582 582 rootfm.end()
583 583
584 584
585 585 @command(
586 586 b'archive',
587 587 [
588 588 (b'', b'no-decode', None, _(b'do not pass files through decoders')),
589 589 (
590 590 b'p',
591 591 b'prefix',
592 592 b'',
593 593 _(b'directory prefix for files in archive'),
594 594 _(b'PREFIX'),
595 595 ),
596 596 (b'r', b'rev', b'', _(b'revision to distribute'), _(b'REV')),
597 597 (b't', b'type', b'', _(b'type of distribution to create'), _(b'TYPE')),
598 598 ]
599 599 + subrepoopts
600 600 + walkopts,
601 601 _(b'[OPTION]... DEST'),
602 602 helpcategory=command.CATEGORY_IMPORT_EXPORT,
603 603 )
604 604 def archive(ui, repo, dest, **opts):
605 605 '''create an unversioned archive of a repository revision
606 606
607 607 By default, the revision used is the parent of the working
608 608 directory; use -r/--rev to specify a different revision.
609 609
610 610 The archive type is automatically detected based on file
611 611 extension (to override, use -t/--type).
612 612
613 613 .. container:: verbose
614 614
615 615 Examples:
616 616
617 617 - create a zip file containing the 1.0 release::
618 618
619 619 hg archive -r 1.0 project-1.0.zip
620 620
621 621 - create a tarball excluding .hg files::
622 622
623 623 hg archive project.tar.gz -X ".hg*"
624 624
625 625 Valid types are:
626 626
627 627 :``files``: a directory full of files (default)
628 628 :``tar``: tar archive, uncompressed
629 629 :``tbz2``: tar archive, compressed using bzip2
630 630 :``tgz``: tar archive, compressed using gzip
631 631 :``txz``: tar archive, compressed using lzma (only in Python 3)
632 632 :``uzip``: zip archive, uncompressed
633 633 :``zip``: zip archive, compressed using deflate
634 634
635 635 The exact name of the destination archive or directory is given
636 636 using a format string; see :hg:`help export` for details.
637 637
638 638 Each member added to an archive file has a directory prefix
639 639 prepended. Use -p/--prefix to specify a format string for the
640 640 prefix. The default is the basename of the archive, with suffixes
641 641 removed.
642 642
643 643 Returns 0 on success.
644 644 '''
645 645
646 646 opts = pycompat.byteskwargs(opts)
647 647 rev = opts.get(b'rev')
648 648 if rev:
649 649 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
650 650 ctx = scmutil.revsingle(repo, rev)
651 651 if not ctx:
652 652 raise error.Abort(_(b'no working directory: please specify a revision'))
653 653 node = ctx.node()
654 654 dest = cmdutil.makefilename(ctx, dest)
655 655 if os.path.realpath(dest) == repo.root:
656 656 raise error.Abort(_(b'repository root cannot be destination'))
657 657
658 658 kind = opts.get(b'type') or archival.guesskind(dest) or b'files'
659 659 prefix = opts.get(b'prefix')
660 660
661 661 if dest == b'-':
662 662 if kind == b'files':
663 663 raise error.Abort(_(b'cannot archive plain files to stdout'))
664 664 dest = cmdutil.makefileobj(ctx, dest)
665 665 if not prefix:
666 666 prefix = os.path.basename(repo.root) + b'-%h'
667 667
668 668 prefix = cmdutil.makefilename(ctx, prefix)
669 669 match = scmutil.match(ctx, [], opts)
670 670 archival.archive(
671 671 repo,
672 672 dest,
673 673 node,
674 674 kind,
675 675 not opts.get(b'no_decode'),
676 676 match,
677 677 prefix,
678 678 subrepos=opts.get(b'subrepos'),
679 679 )
680 680
681 681
682 682 @command(
683 683 b'backout',
684 684 [
685 685 (
686 686 b'',
687 687 b'merge',
688 688 None,
689 689 _(b'merge with old dirstate parent after backout'),
690 690 ),
691 691 (
692 692 b'',
693 693 b'commit',
694 694 None,
695 695 _(b'commit if no conflicts were encountered (DEPRECATED)'),
696 696 ),
697 697 (b'', b'no-commit', None, _(b'do not commit')),
698 698 (
699 699 b'',
700 700 b'parent',
701 701 b'',
702 702 _(b'parent to choose when backing out merge (DEPRECATED)'),
703 703 _(b'REV'),
704 704 ),
705 705 (b'r', b'rev', b'', _(b'revision to backout'), _(b'REV')),
706 706 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
707 707 ]
708 708 + mergetoolopts
709 709 + walkopts
710 710 + commitopts
711 711 + commitopts2,
712 712 _(b'[OPTION]... [-r] REV'),
713 713 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
714 714 )
715 715 def backout(ui, repo, node=None, rev=None, **opts):
716 716 '''reverse effect of earlier changeset
717 717
718 718 Prepare a new changeset with the effect of REV undone in the
719 719 current working directory. If no conflicts were encountered,
720 720 it will be committed immediately.
721 721
722 722 If REV is the parent of the working directory, then this new changeset
723 723 is committed automatically (unless --no-commit is specified).
724 724
725 725 .. note::
726 726
727 727 :hg:`backout` cannot be used to fix either an unwanted or
728 728 incorrect merge.
729 729
730 730 .. container:: verbose
731 731
732 732 Examples:
733 733
734 734 - Reverse the effect of the parent of the working directory.
735 735 This backout will be committed immediately::
736 736
737 737 hg backout -r .
738 738
739 739 - Reverse the effect of previous bad revision 23::
740 740
741 741 hg backout -r 23
742 742
743 743 - Reverse the effect of previous bad revision 23 and
744 744 leave changes uncommitted::
745 745
746 746 hg backout -r 23 --no-commit
747 747 hg commit -m "Backout revision 23"
748 748
749 749 By default, the pending changeset will have one parent,
750 750 maintaining a linear history. With --merge, the pending
751 751 changeset will instead have two parents: the old parent of the
752 752 working directory and a new child of REV that simply undoes REV.
753 753
754 754 Before version 1.7, the behavior without --merge was equivalent
755 755 to specifying --merge followed by :hg:`update --clean .` to
756 756 cancel the merge and leave the child of REV as a head to be
757 757 merged separately.
758 758
759 759 See :hg:`help dates` for a list of formats valid for -d/--date.
760 760
761 761 See :hg:`help revert` for a way to restore files to the state
762 762 of another revision.
763 763
764 764 Returns 0 on success, 1 if nothing to backout or there are unresolved
765 765 files.
766 766 '''
767 767 with repo.wlock(), repo.lock():
768 768 return _dobackout(ui, repo, node, rev, **opts)
769 769
770 770
771 771 def _dobackout(ui, repo, node=None, rev=None, **opts):
772 772 cmdutil.check_incompatible_arguments(opts, 'no_commit', ['commit', 'merge'])
773 773 opts = pycompat.byteskwargs(opts)
774 774
775 775 if rev and node:
776 776 raise error.Abort(_(b"please specify just one revision"))
777 777
778 778 if not rev:
779 779 rev = node
780 780
781 781 if not rev:
782 782 raise error.Abort(_(b"please specify a revision to backout"))
783 783
784 784 date = opts.get(b'date')
785 785 if date:
786 786 opts[b'date'] = dateutil.parsedate(date)
787 787
788 788 cmdutil.checkunfinished(repo)
789 789 cmdutil.bailifchanged(repo)
790 790 ctx = scmutil.revsingle(repo, rev)
791 791 node = ctx.node()
792 792
793 793 op1, op2 = repo.dirstate.parents()
794 794 if not repo.changelog.isancestor(node, op1):
795 795 raise error.Abort(_(b'cannot backout change that is not an ancestor'))
796 796
797 797 p1, p2 = repo.changelog.parents(node)
798 798 if p1 == nullid:
799 799 raise error.Abort(_(b'cannot backout a change with no parents'))
800 800 if p2 != nullid:
801 801 if not opts.get(b'parent'):
802 802 raise error.Abort(_(b'cannot backout a merge changeset'))
803 803 p = repo.lookup(opts[b'parent'])
804 804 if p not in (p1, p2):
805 805 raise error.Abort(
806 806 _(b'%s is not a parent of %s') % (short(p), short(node))
807 807 )
808 808 parent = p
809 809 else:
810 810 if opts.get(b'parent'):
811 811 raise error.Abort(_(b'cannot use --parent on non-merge changeset'))
812 812 parent = p1
813 813
814 814 # the backout should appear on the same branch
815 815 branch = repo.dirstate.branch()
816 816 bheads = repo.branchheads(branch)
817 817 rctx = scmutil.revsingle(repo, hex(parent))
818 818 if not opts.get(b'merge') and op1 != node:
819 819 with dirstateguard.dirstateguard(repo, b'backout'):
820 820 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
821 821 with ui.configoverride(overrides, b'backout'):
822 822 stats = mergemod.back_out(ctx, parent=repo[parent])
823 823 repo.setparents(op1, op2)
824 824 hg._showstats(repo, stats)
825 825 if stats.unresolvedcount:
826 826 repo.ui.status(
827 827 _(b"use 'hg resolve' to retry unresolved file merges\n")
828 828 )
829 829 return 1
830 830 else:
831 831 hg.clean(repo, node, show_stats=False)
832 832 repo.dirstate.setbranch(branch)
833 833 cmdutil.revert(ui, repo, rctx)
834 834
835 835 if opts.get(b'no_commit'):
836 836 msg = _(b"changeset %s backed out, don't forget to commit.\n")
837 837 ui.status(msg % short(node))
838 838 return 0
839 839
840 840 def commitfunc(ui, repo, message, match, opts):
841 841 editform = b'backout'
842 842 e = cmdutil.getcommiteditor(
843 843 editform=editform, **pycompat.strkwargs(opts)
844 844 )
845 845 if not message:
846 846 # we don't translate commit messages
847 847 message = b"Backed out changeset %s" % short(node)
848 848 e = cmdutil.getcommiteditor(edit=True, editform=editform)
849 849 return repo.commit(
850 850 message, opts.get(b'user'), opts.get(b'date'), match, editor=e
851 851 )
852 852
853 # save to detect changes
854 tip = repo.changelog.tip()
855
853 856 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
854 857 if not newnode:
855 858 ui.status(_(b"nothing changed\n"))
856 859 return 1
857 cmdutil.commitstatus(repo, newnode, branch, bheads)
860 cmdutil.commitstatus(repo, newnode, branch, bheads, tip)
858 861
859 862 def nice(node):
860 863 return b'%d:%s' % (repo.changelog.rev(node), short(node))
861 864
862 865 ui.status(
863 866 _(b'changeset %s backs out changeset %s\n')
864 867 % (nice(newnode), nice(node))
865 868 )
866 869 if opts.get(b'merge') and op1 != node:
867 870 hg.clean(repo, op1, show_stats=False)
868 871 ui.status(_(b'merging with changeset %s\n') % nice(newnode))
869 872 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
870 873 with ui.configoverride(overrides, b'backout'):
871 874 return hg.merge(repo[b'tip'])
872 875 return 0
873 876
874 877
875 878 @command(
876 879 b'bisect',
877 880 [
878 881 (b'r', b'reset', False, _(b'reset bisect state')),
879 882 (b'g', b'good', False, _(b'mark changeset good')),
880 883 (b'b', b'bad', False, _(b'mark changeset bad')),
881 884 (b's', b'skip', False, _(b'skip testing changeset')),
882 885 (b'e', b'extend', False, _(b'extend the bisect range')),
883 886 (
884 887 b'c',
885 888 b'command',
886 889 b'',
887 890 _(b'use command to check changeset state'),
888 891 _(b'CMD'),
889 892 ),
890 893 (b'U', b'noupdate', False, _(b'do not update to target')),
891 894 ],
892 895 _(b"[-gbsr] [-U] [-c CMD] [REV]"),
893 896 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
894 897 )
895 898 def bisect(
896 899 ui,
897 900 repo,
898 901 rev=None,
899 902 extra=None,
900 903 command=None,
901 904 reset=None,
902 905 good=None,
903 906 bad=None,
904 907 skip=None,
905 908 extend=None,
906 909 noupdate=None,
907 910 ):
908 911 """subdivision search of changesets
909 912
910 913 This command helps to find changesets which introduce problems. To
911 914 use, mark the earliest changeset you know exhibits the problem as
912 915 bad, then mark the latest changeset which is free from the problem
913 916 as good. Bisect will update your working directory to a revision
914 917 for testing (unless the -U/--noupdate option is specified). Once
915 918 you have performed tests, mark the working directory as good or
916 919 bad, and bisect will either update to another candidate changeset
917 920 or announce that it has found the bad revision.
918 921
919 922 As a shortcut, you can also use the revision argument to mark a
920 923 revision as good or bad without checking it out first.
921 924
922 925 If you supply a command, it will be used for automatic bisection.
923 926 The environment variable HG_NODE will contain the ID of the
924 927 changeset being tested. The exit status of the command will be
925 928 used to mark revisions as good or bad: status 0 means good, 125
926 929 means to skip the revision, 127 (command not found) will abort the
927 930 bisection, and any other non-zero exit status means the revision
928 931 is bad.
929 932
930 933 .. container:: verbose
931 934
932 935 Some examples:
933 936
934 937 - start a bisection with known bad revision 34, and good revision 12::
935 938
936 939 hg bisect --bad 34
937 940 hg bisect --good 12
938 941
939 942 - advance the current bisection by marking current revision as good or
940 943 bad::
941 944
942 945 hg bisect --good
943 946 hg bisect --bad
944 947
945 948 - mark the current revision, or a known revision, to be skipped (e.g. if
946 949 that revision is not usable because of another issue)::
947 950
948 951 hg bisect --skip
949 952 hg bisect --skip 23
950 953
951 954 - skip all revisions that do not touch directories ``foo`` or ``bar``::
952 955
953 956 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
954 957
955 958 - forget the current bisection::
956 959
957 960 hg bisect --reset
958 961
959 962 - use 'make && make tests' to automatically find the first broken
960 963 revision::
961 964
962 965 hg bisect --reset
963 966 hg bisect --bad 34
964 967 hg bisect --good 12
965 968 hg bisect --command "make && make tests"
966 969
967 970 - see all changesets whose states are already known in the current
968 971 bisection::
969 972
970 973 hg log -r "bisect(pruned)"
971 974
972 975 - see the changeset currently being bisected (especially useful
973 976 if running with -U/--noupdate)::
974 977
975 978 hg log -r "bisect(current)"
976 979
977 980 - see all changesets that took part in the current bisection::
978 981
979 982 hg log -r "bisect(range)"
980 983
981 984 - you can even get a nice graph::
982 985
983 986 hg log --graph -r "bisect(range)"
984 987
985 988 See :hg:`help revisions.bisect` for more about the `bisect()` predicate.
986 989
987 990 Returns 0 on success.
988 991 """
989 992 # backward compatibility
990 993 if rev in b"good bad reset init".split():
991 994 ui.warn(_(b"(use of 'hg bisect <cmd>' is deprecated)\n"))
992 995 cmd, rev, extra = rev, extra, None
993 996 if cmd == b"good":
994 997 good = True
995 998 elif cmd == b"bad":
996 999 bad = True
997 1000 else:
998 1001 reset = True
999 1002 elif extra:
1000 1003 raise error.Abort(_(b'incompatible arguments'))
1001 1004
1002 1005 incompatibles = {
1003 1006 b'--bad': bad,
1004 1007 b'--command': bool(command),
1005 1008 b'--extend': extend,
1006 1009 b'--good': good,
1007 1010 b'--reset': reset,
1008 1011 b'--skip': skip,
1009 1012 }
1010 1013
1011 1014 enabled = [x for x in incompatibles if incompatibles[x]]
1012 1015
1013 1016 if len(enabled) > 1:
1014 1017 raise error.Abort(
1015 1018 _(b'%s and %s are incompatible') % tuple(sorted(enabled)[0:2])
1016 1019 )
1017 1020
1018 1021 if reset:
1019 1022 hbisect.resetstate(repo)
1020 1023 return
1021 1024
1022 1025 state = hbisect.load_state(repo)
1023 1026
1024 1027 # update state
1025 1028 if good or bad or skip:
1026 1029 if rev:
1027 1030 nodes = [repo[i].node() for i in scmutil.revrange(repo, [rev])]
1028 1031 else:
1029 1032 nodes = [repo.lookup(b'.')]
1030 1033 if good:
1031 1034 state[b'good'] += nodes
1032 1035 elif bad:
1033 1036 state[b'bad'] += nodes
1034 1037 elif skip:
1035 1038 state[b'skip'] += nodes
1036 1039 hbisect.save_state(repo, state)
1037 1040 if not (state[b'good'] and state[b'bad']):
1038 1041 return
1039 1042
1040 1043 def mayupdate(repo, node, show_stats=True):
1041 1044 """common used update sequence"""
1042 1045 if noupdate:
1043 1046 return
1044 1047 cmdutil.checkunfinished(repo)
1045 1048 cmdutil.bailifchanged(repo)
1046 1049 return hg.clean(repo, node, show_stats=show_stats)
1047 1050
1048 1051 displayer = logcmdutil.changesetdisplayer(ui, repo, {})
1049 1052
1050 1053 if command:
1051 1054 changesets = 1
1052 1055 if noupdate:
1053 1056 try:
1054 1057 node = state[b'current'][0]
1055 1058 except LookupError:
1056 1059 raise error.Abort(
1057 1060 _(
1058 1061 b'current bisect revision is unknown - '
1059 1062 b'start a new bisect to fix'
1060 1063 )
1061 1064 )
1062 1065 else:
1063 1066 node, p2 = repo.dirstate.parents()
1064 1067 if p2 != nullid:
1065 1068 raise error.Abort(_(b'current bisect revision is a merge'))
1066 1069 if rev:
1067 1070 node = repo[scmutil.revsingle(repo, rev, node)].node()
1068 1071 with hbisect.restore_state(repo, state, node):
1069 1072 while changesets:
1070 1073 # update state
1071 1074 state[b'current'] = [node]
1072 1075 hbisect.save_state(repo, state)
1073 1076 status = ui.system(
1074 1077 command,
1075 1078 environ={b'HG_NODE': hex(node)},
1076 1079 blockedtag=b'bisect_check',
1077 1080 )
1078 1081 if status == 125:
1079 1082 transition = b"skip"
1080 1083 elif status == 0:
1081 1084 transition = b"good"
1082 1085 # status < 0 means process was killed
1083 1086 elif status == 127:
1084 1087 raise error.Abort(_(b"failed to execute %s") % command)
1085 1088 elif status < 0:
1086 1089 raise error.Abort(_(b"%s killed") % command)
1087 1090 else:
1088 1091 transition = b"bad"
1089 1092 state[transition].append(node)
1090 1093 ctx = repo[node]
1091 1094 ui.status(
1092 1095 _(b'changeset %d:%s: %s\n') % (ctx.rev(), ctx, transition)
1093 1096 )
1094 1097 hbisect.checkstate(state)
1095 1098 # bisect
1096 1099 nodes, changesets, bgood = hbisect.bisect(repo, state)
1097 1100 # update to next check
1098 1101 node = nodes[0]
1099 1102 mayupdate(repo, node, show_stats=False)
1100 1103 hbisect.printresult(ui, repo, state, displayer, nodes, bgood)
1101 1104 return
1102 1105
1103 1106 hbisect.checkstate(state)
1104 1107
1105 1108 # actually bisect
1106 1109 nodes, changesets, good = hbisect.bisect(repo, state)
1107 1110 if extend:
1108 1111 if not changesets:
1109 1112 extendnode = hbisect.extendrange(repo, state, nodes, good)
1110 1113 if extendnode is not None:
1111 1114 ui.write(
1112 1115 _(b"Extending search to changeset %d:%s\n")
1113 1116 % (extendnode.rev(), extendnode)
1114 1117 )
1115 1118 state[b'current'] = [extendnode.node()]
1116 1119 hbisect.save_state(repo, state)
1117 1120 return mayupdate(repo, extendnode.node())
1118 1121 raise error.Abort(_(b"nothing to extend"))
1119 1122
1120 1123 if changesets == 0:
1121 1124 hbisect.printresult(ui, repo, state, displayer, nodes, good)
1122 1125 else:
1123 1126 assert len(nodes) == 1 # only a single node can be tested next
1124 1127 node = nodes[0]
1125 1128 # compute the approximate number of remaining tests
1126 1129 tests, size = 0, 2
1127 1130 while size <= changesets:
1128 1131 tests, size = tests + 1, size * 2
1129 1132 rev = repo.changelog.rev(node)
1130 1133 ui.write(
1131 1134 _(
1132 1135 b"Testing changeset %d:%s "
1133 1136 b"(%d changesets remaining, ~%d tests)\n"
1134 1137 )
1135 1138 % (rev, short(node), changesets, tests)
1136 1139 )
1137 1140 state[b'current'] = [node]
1138 1141 hbisect.save_state(repo, state)
1139 1142 return mayupdate(repo, node)
1140 1143
1141 1144
1142 1145 @command(
1143 1146 b'bookmarks|bookmark',
1144 1147 [
1145 1148 (b'f', b'force', False, _(b'force')),
1146 1149 (b'r', b'rev', b'', _(b'revision for bookmark action'), _(b'REV')),
1147 1150 (b'd', b'delete', False, _(b'delete a given bookmark')),
1148 1151 (b'm', b'rename', b'', _(b'rename a given bookmark'), _(b'OLD')),
1149 1152 (b'i', b'inactive', False, _(b'mark a bookmark inactive')),
1150 1153 (b'l', b'list', False, _(b'list existing bookmarks')),
1151 1154 ]
1152 1155 + formatteropts,
1153 1156 _(b'hg bookmarks [OPTIONS]... [NAME]...'),
1154 1157 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
1155 1158 )
1156 1159 def bookmark(ui, repo, *names, **opts):
1157 1160 '''create a new bookmark or list existing bookmarks
1158 1161
1159 1162 Bookmarks are labels on changesets to help track lines of development.
1160 1163 Bookmarks are unversioned and can be moved, renamed and deleted.
1161 1164 Deleting or moving a bookmark has no effect on the associated changesets.
1162 1165
1163 1166 Creating or updating to a bookmark causes it to be marked as 'active'.
1164 1167 The active bookmark is indicated with a '*'.
1165 1168 When a commit is made, the active bookmark will advance to the new commit.
1166 1169 A plain :hg:`update` will also advance an active bookmark, if possible.
1167 1170 Updating away from a bookmark will cause it to be deactivated.
1168 1171
1169 1172 Bookmarks can be pushed and pulled between repositories (see
1170 1173 :hg:`help push` and :hg:`help pull`). If a shared bookmark has
1171 1174 diverged, a new 'divergent bookmark' of the form 'name@path' will
1172 1175 be created. Using :hg:`merge` will resolve the divergence.
1173 1176
1174 1177 Specifying bookmark as '.' to -m/-d/-l options is equivalent to specifying
1175 1178 the active bookmark's name.
1176 1179
1177 1180 A bookmark named '@' has the special property that :hg:`clone` will
1178 1181 check it out by default if it exists.
1179 1182
1180 1183 .. container:: verbose
1181 1184
1182 1185 Template:
1183 1186
1184 1187 The following keywords are supported in addition to the common template
1185 1188 keywords and functions such as ``{bookmark}``. See also
1186 1189 :hg:`help templates`.
1187 1190
1188 1191 :active: Boolean. True if the bookmark is active.
1189 1192
1190 1193 Examples:
1191 1194
1192 1195 - create an active bookmark for a new line of development::
1193 1196
1194 1197 hg book new-feature
1195 1198
1196 1199 - create an inactive bookmark as a place marker::
1197 1200
1198 1201 hg book -i reviewed
1199 1202
1200 1203 - create an inactive bookmark on another changeset::
1201 1204
1202 1205 hg book -r .^ tested
1203 1206
1204 1207 - rename bookmark turkey to dinner::
1205 1208
1206 1209 hg book -m turkey dinner
1207 1210
1208 1211 - move the '@' bookmark from another branch::
1209 1212
1210 1213 hg book -f @
1211 1214
1212 1215 - print only the active bookmark name::
1213 1216
1214 1217 hg book -ql .
1215 1218 '''
1216 1219 opts = pycompat.byteskwargs(opts)
1217 1220 force = opts.get(b'force')
1218 1221 rev = opts.get(b'rev')
1219 1222 inactive = opts.get(b'inactive') # meaning add/rename to inactive bookmark
1220 1223
1221 1224 action = cmdutil.check_at_most_one_arg(opts, b'delete', b'rename', b'list')
1222 1225 if action:
1223 1226 cmdutil.check_incompatible_arguments(opts, action, [b'rev'])
1224 1227 elif names or rev:
1225 1228 action = b'add'
1226 1229 elif inactive:
1227 1230 action = b'inactive' # meaning deactivate
1228 1231 else:
1229 1232 action = b'list'
1230 1233
1231 1234 cmdutil.check_incompatible_arguments(
1232 1235 opts, b'inactive', [b'delete', b'list']
1233 1236 )
1234 1237 if not names and action in {b'add', b'delete'}:
1235 1238 raise error.Abort(_(b"bookmark name required"))
1236 1239
1237 1240 if action in {b'add', b'delete', b'rename', b'inactive'}:
1238 1241 with repo.wlock(), repo.lock(), repo.transaction(b'bookmark') as tr:
1239 1242 if action == b'delete':
1240 1243 names = pycompat.maplist(repo._bookmarks.expandname, names)
1241 1244 bookmarks.delete(repo, tr, names)
1242 1245 elif action == b'rename':
1243 1246 if not names:
1244 1247 raise error.Abort(_(b"new bookmark name required"))
1245 1248 elif len(names) > 1:
1246 1249 raise error.Abort(_(b"only one new bookmark name allowed"))
1247 1250 oldname = repo._bookmarks.expandname(opts[b'rename'])
1248 1251 bookmarks.rename(repo, tr, oldname, names[0], force, inactive)
1249 1252 elif action == b'add':
1250 1253 bookmarks.addbookmarks(repo, tr, names, rev, force, inactive)
1251 1254 elif action == b'inactive':
1252 1255 if len(repo._bookmarks) == 0:
1253 1256 ui.status(_(b"no bookmarks set\n"))
1254 1257 elif not repo._activebookmark:
1255 1258 ui.status(_(b"no active bookmark\n"))
1256 1259 else:
1257 1260 bookmarks.deactivate(repo)
1258 1261 elif action == b'list':
1259 1262 names = pycompat.maplist(repo._bookmarks.expandname, names)
1260 1263 with ui.formatter(b'bookmarks', opts) as fm:
1261 1264 bookmarks.printbookmarks(ui, repo, fm, names)
1262 1265 else:
1263 1266 raise error.ProgrammingError(b'invalid action: %s' % action)
1264 1267
1265 1268
1266 1269 @command(
1267 1270 b'branch',
1268 1271 [
1269 1272 (
1270 1273 b'f',
1271 1274 b'force',
1272 1275 None,
1273 1276 _(b'set branch name even if it shadows an existing branch'),
1274 1277 ),
1275 1278 (b'C', b'clean', None, _(b'reset branch name to parent branch name')),
1276 1279 (
1277 1280 b'r',
1278 1281 b'rev',
1279 1282 [],
1280 1283 _(b'change branches of the given revs (EXPERIMENTAL)'),
1281 1284 ),
1282 1285 ],
1283 1286 _(b'[-fC] [NAME]'),
1284 1287 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
1285 1288 )
1286 1289 def branch(ui, repo, label=None, **opts):
1287 1290 """set or show the current branch name
1288 1291
1289 1292 .. note::
1290 1293
1291 1294 Branch names are permanent and global. Use :hg:`bookmark` to create a
1292 1295 light-weight bookmark instead. See :hg:`help glossary` for more
1293 1296 information about named branches and bookmarks.
1294 1297
1295 1298 With no argument, show the current branch name. With one argument,
1296 1299 set the working directory branch name (the branch will not exist
1297 1300 in the repository until the next commit). Standard practice
1298 1301 recommends that primary development take place on the 'default'
1299 1302 branch.
1300 1303
1301 1304 Unless -f/--force is specified, branch will not let you set a
1302 1305 branch name that already exists.
1303 1306
1304 1307 Use -C/--clean to reset the working directory branch to that of
1305 1308 the parent of the working directory, negating a previous branch
1306 1309 change.
1307 1310
1308 1311 Use the command :hg:`update` to switch to an existing branch. Use
1309 1312 :hg:`commit --close-branch` to mark this branch head as closed.
1310 1313 When all heads of a branch are closed, the branch will be
1311 1314 considered closed.
1312 1315
1313 1316 Returns 0 on success.
1314 1317 """
1315 1318 opts = pycompat.byteskwargs(opts)
1316 1319 revs = opts.get(b'rev')
1317 1320 if label:
1318 1321 label = label.strip()
1319 1322
1320 1323 if not opts.get(b'clean') and not label:
1321 1324 if revs:
1322 1325 raise error.Abort(_(b"no branch name specified for the revisions"))
1323 1326 ui.write(b"%s\n" % repo.dirstate.branch())
1324 1327 return
1325 1328
1326 1329 with repo.wlock():
1327 1330 if opts.get(b'clean'):
1328 1331 label = repo[b'.'].branch()
1329 1332 repo.dirstate.setbranch(label)
1330 1333 ui.status(_(b'reset working directory to branch %s\n') % label)
1331 1334 elif label:
1332 1335
1333 1336 scmutil.checknewlabel(repo, label, b'branch')
1334 1337 if revs:
1335 1338 return cmdutil.changebranch(ui, repo, revs, label, opts)
1336 1339
1337 1340 if not opts.get(b'force') and label in repo.branchmap():
1338 1341 if label not in [p.branch() for p in repo[None].parents()]:
1339 1342 raise error.Abort(
1340 1343 _(b'a branch of the same name already exists'),
1341 1344 # i18n: "it" refers to an existing branch
1342 1345 hint=_(b"use 'hg update' to switch to it"),
1343 1346 )
1344 1347
1345 1348 repo.dirstate.setbranch(label)
1346 1349 ui.status(_(b'marked working directory as branch %s\n') % label)
1347 1350
1348 1351 # find any open named branches aside from default
1349 1352 for n, h, t, c in repo.branchmap().iterbranches():
1350 1353 if n != b"default" and not c:
1351 1354 return 0
1352 1355 ui.status(
1353 1356 _(
1354 1357 b'(branches are permanent and global, '
1355 1358 b'did you want a bookmark?)\n'
1356 1359 )
1357 1360 )
1358 1361
1359 1362
1360 1363 @command(
1361 1364 b'branches',
1362 1365 [
1363 1366 (
1364 1367 b'a',
1365 1368 b'active',
1366 1369 False,
1367 1370 _(b'show only branches that have unmerged heads (DEPRECATED)'),
1368 1371 ),
1369 1372 (b'c', b'closed', False, _(b'show normal and closed branches')),
1370 1373 (b'r', b'rev', [], _(b'show branch name(s) of the given rev')),
1371 1374 ]
1372 1375 + formatteropts,
1373 1376 _(b'[-c]'),
1374 1377 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
1375 1378 intents={INTENT_READONLY},
1376 1379 )
1377 1380 def branches(ui, repo, active=False, closed=False, **opts):
1378 1381 """list repository named branches
1379 1382
1380 1383 List the repository's named branches, indicating which ones are
1381 1384 inactive. If -c/--closed is specified, also list branches which have
1382 1385 been marked closed (see :hg:`commit --close-branch`).
1383 1386
1384 1387 Use the command :hg:`update` to switch to an existing branch.
1385 1388
1386 1389 .. container:: verbose
1387 1390
1388 1391 Template:
1389 1392
1390 1393 The following keywords are supported in addition to the common template
1391 1394 keywords and functions such as ``{branch}``. See also
1392 1395 :hg:`help templates`.
1393 1396
1394 1397 :active: Boolean. True if the branch is active.
1395 1398 :closed: Boolean. True if the branch is closed.
1396 1399 :current: Boolean. True if it is the current branch.
1397 1400
1398 1401 Returns 0.
1399 1402 """
1400 1403
1401 1404 opts = pycompat.byteskwargs(opts)
1402 1405 revs = opts.get(b'rev')
1403 1406 selectedbranches = None
1404 1407 if revs:
1405 1408 revs = scmutil.revrange(repo, revs)
1406 1409 getbi = repo.revbranchcache().branchinfo
1407 1410 selectedbranches = {getbi(r)[0] for r in revs}
1408 1411
1409 1412 ui.pager(b'branches')
1410 1413 fm = ui.formatter(b'branches', opts)
1411 1414 hexfunc = fm.hexfunc
1412 1415
1413 1416 allheads = set(repo.heads())
1414 1417 branches = []
1415 1418 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1416 1419 if selectedbranches is not None and tag not in selectedbranches:
1417 1420 continue
1418 1421 isactive = False
1419 1422 if not isclosed:
1420 1423 openheads = set(repo.branchmap().iteropen(heads))
1421 1424 isactive = bool(openheads & allheads)
1422 1425 branches.append((tag, repo[tip], isactive, not isclosed))
1423 1426 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]), reverse=True)
1424 1427
1425 1428 for tag, ctx, isactive, isopen in branches:
1426 1429 if active and not isactive:
1427 1430 continue
1428 1431 if isactive:
1429 1432 label = b'branches.active'
1430 1433 notice = b''
1431 1434 elif not isopen:
1432 1435 if not closed:
1433 1436 continue
1434 1437 label = b'branches.closed'
1435 1438 notice = _(b' (closed)')
1436 1439 else:
1437 1440 label = b'branches.inactive'
1438 1441 notice = _(b' (inactive)')
1439 1442 current = tag == repo.dirstate.branch()
1440 1443 if current:
1441 1444 label = b'branches.current'
1442 1445
1443 1446 fm.startitem()
1444 1447 fm.write(b'branch', b'%s', tag, label=label)
1445 1448 rev = ctx.rev()
1446 1449 padsize = max(31 - len(b"%d" % rev) - encoding.colwidth(tag), 0)
1447 1450 fmt = b' ' * padsize + b' %d:%s'
1448 1451 fm.condwrite(
1449 1452 not ui.quiet,
1450 1453 b'rev node',
1451 1454 fmt,
1452 1455 rev,
1453 1456 hexfunc(ctx.node()),
1454 1457 label=b'log.changeset changeset.%s' % ctx.phasestr(),
1455 1458 )
1456 1459 fm.context(ctx=ctx)
1457 1460 fm.data(active=isactive, closed=not isopen, current=current)
1458 1461 if not ui.quiet:
1459 1462 fm.plain(notice)
1460 1463 fm.plain(b'\n')
1461 1464 fm.end()
1462 1465
1463 1466
1464 1467 @command(
1465 1468 b'bundle',
1466 1469 [
1467 1470 (
1468 1471 b'f',
1469 1472 b'force',
1470 1473 None,
1471 1474 _(b'run even when the destination is unrelated'),
1472 1475 ),
1473 1476 (
1474 1477 b'r',
1475 1478 b'rev',
1476 1479 [],
1477 1480 _(b'a changeset intended to be added to the destination'),
1478 1481 _(b'REV'),
1479 1482 ),
1480 1483 (
1481 1484 b'b',
1482 1485 b'branch',
1483 1486 [],
1484 1487 _(b'a specific branch you would like to bundle'),
1485 1488 _(b'BRANCH'),
1486 1489 ),
1487 1490 (
1488 1491 b'',
1489 1492 b'base',
1490 1493 [],
1491 1494 _(b'a base changeset assumed to be available at the destination'),
1492 1495 _(b'REV'),
1493 1496 ),
1494 1497 (b'a', b'all', None, _(b'bundle all changesets in the repository')),
1495 1498 (
1496 1499 b't',
1497 1500 b'type',
1498 1501 b'bzip2',
1499 1502 _(b'bundle compression type to use'),
1500 1503 _(b'TYPE'),
1501 1504 ),
1502 1505 ]
1503 1506 + remoteopts,
1504 1507 _(b'[-f] [-t BUNDLESPEC] [-a] [-r REV]... [--base REV]... FILE [DEST]'),
1505 1508 helpcategory=command.CATEGORY_IMPORT_EXPORT,
1506 1509 )
1507 1510 def bundle(ui, repo, fname, dest=None, **opts):
1508 1511 """create a bundle file
1509 1512
1510 1513 Generate a bundle file containing data to be transferred to another
1511 1514 repository.
1512 1515
1513 1516 To create a bundle containing all changesets, use -a/--all
1514 1517 (or --base null). Otherwise, hg assumes the destination will have
1515 1518 all the nodes you specify with --base parameters. Otherwise, hg
1516 1519 will assume the repository has all the nodes in destination, or
1517 1520 default-push/default if no destination is specified, where destination
1518 1521 is the repository you provide through DEST option.
1519 1522
1520 1523 You can change bundle format with the -t/--type option. See
1521 1524 :hg:`help bundlespec` for documentation on this format. By default,
1522 1525 the most appropriate format is used and compression defaults to
1523 1526 bzip2.
1524 1527
1525 1528 The bundle file can then be transferred using conventional means
1526 1529 and applied to another repository with the unbundle or pull
1527 1530 command. This is useful when direct push and pull are not
1528 1531 available or when exporting an entire repository is undesirable.
1529 1532
1530 1533 Applying bundles preserves all changeset contents including
1531 1534 permissions, copy/rename information, and revision history.
1532 1535
1533 1536 Returns 0 on success, 1 if no changes found.
1534 1537 """
1535 1538 opts = pycompat.byteskwargs(opts)
1536 1539 revs = None
1537 1540 if b'rev' in opts:
1538 1541 revstrings = opts[b'rev']
1539 1542 revs = scmutil.revrange(repo, revstrings)
1540 1543 if revstrings and not revs:
1541 1544 raise error.Abort(_(b'no commits to bundle'))
1542 1545
1543 1546 bundletype = opts.get(b'type', b'bzip2').lower()
1544 1547 try:
1545 1548 bundlespec = exchange.parsebundlespec(repo, bundletype, strict=False)
1546 1549 except error.UnsupportedBundleSpecification as e:
1547 1550 raise error.Abort(
1548 1551 pycompat.bytestr(e),
1549 1552 hint=_(b"see 'hg help bundlespec' for supported values for --type"),
1550 1553 )
1551 1554 cgversion = bundlespec.contentopts[b"cg.version"]
1552 1555
1553 1556 # Packed bundles are a pseudo bundle format for now.
1554 1557 if cgversion == b's1':
1555 1558 raise error.Abort(
1556 1559 _(b'packed bundles cannot be produced by "hg bundle"'),
1557 1560 hint=_(b"use 'hg debugcreatestreamclonebundle'"),
1558 1561 )
1559 1562
1560 1563 if opts.get(b'all'):
1561 1564 if dest:
1562 1565 raise error.Abort(
1563 1566 _(b"--all is incompatible with specifying a destination")
1564 1567 )
1565 1568 if opts.get(b'base'):
1566 1569 ui.warn(_(b"ignoring --base because --all was specified\n"))
1567 1570 base = [nullrev]
1568 1571 else:
1569 1572 base = scmutil.revrange(repo, opts.get(b'base'))
1570 1573 if cgversion not in changegroup.supportedoutgoingversions(repo):
1571 1574 raise error.Abort(
1572 1575 _(b"repository does not support bundle version %s") % cgversion
1573 1576 )
1574 1577
1575 1578 if base:
1576 1579 if dest:
1577 1580 raise error.Abort(
1578 1581 _(b"--base is incompatible with specifying a destination")
1579 1582 )
1580 1583 common = [repo[rev].node() for rev in base]
1581 1584 heads = [repo[r].node() for r in revs] if revs else None
1582 1585 outgoing = discovery.outgoing(repo, common, heads)
1583 1586 else:
1584 1587 dest = ui.expandpath(dest or b'default-push', dest or b'default')
1585 1588 dest, branches = hg.parseurl(dest, opts.get(b'branch'))
1586 1589 other = hg.peer(repo, opts, dest)
1587 1590 revs = [repo[r].hex() for r in revs]
1588 1591 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1589 1592 heads = revs and pycompat.maplist(repo.lookup, revs) or revs
1590 1593 outgoing = discovery.findcommonoutgoing(
1591 1594 repo,
1592 1595 other,
1593 1596 onlyheads=heads,
1594 1597 force=opts.get(b'force'),
1595 1598 portable=True,
1596 1599 )
1597 1600
1598 1601 if not outgoing.missing:
1599 1602 scmutil.nochangesfound(ui, repo, not base and outgoing.excluded)
1600 1603 return 1
1601 1604
1602 1605 if cgversion == b'01': # bundle1
1603 1606 bversion = b'HG10' + bundlespec.wirecompression
1604 1607 bcompression = None
1605 1608 elif cgversion in (b'02', b'03'):
1606 1609 bversion = b'HG20'
1607 1610 bcompression = bundlespec.wirecompression
1608 1611 else:
1609 1612 raise error.ProgrammingError(
1610 1613 b'bundle: unexpected changegroup version %s' % cgversion
1611 1614 )
1612 1615
1613 1616 # TODO compression options should be derived from bundlespec parsing.
1614 1617 # This is a temporary hack to allow adjusting bundle compression
1615 1618 # level without a) formalizing the bundlespec changes to declare it
1616 1619 # b) introducing a command flag.
1617 1620 compopts = {}
1618 1621 complevel = ui.configint(
1619 1622 b'experimental', b'bundlecomplevel.' + bundlespec.compression
1620 1623 )
1621 1624 if complevel is None:
1622 1625 complevel = ui.configint(b'experimental', b'bundlecomplevel')
1623 1626 if complevel is not None:
1624 1627 compopts[b'level'] = complevel
1625 1628
1626 1629 # Allow overriding the bundling of obsmarker in phases through
1627 1630 # configuration while we don't have a bundle version that include them
1628 1631 if repo.ui.configbool(b'experimental', b'evolution.bundle-obsmarker'):
1629 1632 bundlespec.contentopts[b'obsolescence'] = True
1630 1633 if repo.ui.configbool(b'experimental', b'bundle-phases'):
1631 1634 bundlespec.contentopts[b'phases'] = True
1632 1635
1633 1636 bundle2.writenewbundle(
1634 1637 ui,
1635 1638 repo,
1636 1639 b'bundle',
1637 1640 fname,
1638 1641 bversion,
1639 1642 outgoing,
1640 1643 bundlespec.contentopts,
1641 1644 compression=bcompression,
1642 1645 compopts=compopts,
1643 1646 )
1644 1647
1645 1648
1646 1649 @command(
1647 1650 b'cat',
1648 1651 [
1649 1652 (
1650 1653 b'o',
1651 1654 b'output',
1652 1655 b'',
1653 1656 _(b'print output to file with formatted name'),
1654 1657 _(b'FORMAT'),
1655 1658 ),
1656 1659 (b'r', b'rev', b'', _(b'print the given revision'), _(b'REV')),
1657 1660 (b'', b'decode', None, _(b'apply any matching decode filter')),
1658 1661 ]
1659 1662 + walkopts
1660 1663 + formatteropts,
1661 1664 _(b'[OPTION]... FILE...'),
1662 1665 helpcategory=command.CATEGORY_FILE_CONTENTS,
1663 1666 inferrepo=True,
1664 1667 intents={INTENT_READONLY},
1665 1668 )
1666 1669 def cat(ui, repo, file1, *pats, **opts):
1667 1670 """output the current or given revision of files
1668 1671
1669 1672 Print the specified files as they were at the given revision. If
1670 1673 no revision is given, the parent of the working directory is used.
1671 1674
1672 1675 Output may be to a file, in which case the name of the file is
1673 1676 given using a template string. See :hg:`help templates`. In addition
1674 1677 to the common template keywords, the following formatting rules are
1675 1678 supported:
1676 1679
1677 1680 :``%%``: literal "%" character
1678 1681 :``%s``: basename of file being printed
1679 1682 :``%d``: dirname of file being printed, or '.' if in repository root
1680 1683 :``%p``: root-relative path name of file being printed
1681 1684 :``%H``: changeset hash (40 hexadecimal digits)
1682 1685 :``%R``: changeset revision number
1683 1686 :``%h``: short-form changeset hash (12 hexadecimal digits)
1684 1687 :``%r``: zero-padded changeset revision number
1685 1688 :``%b``: basename of the exporting repository
1686 1689 :``\\``: literal "\\" character
1687 1690
1688 1691 .. container:: verbose
1689 1692
1690 1693 Template:
1691 1694
1692 1695 The following keywords are supported in addition to the common template
1693 1696 keywords and functions. See also :hg:`help templates`.
1694 1697
1695 1698 :data: String. File content.
1696 1699 :path: String. Repository-absolute path of the file.
1697 1700
1698 1701 Returns 0 on success.
1699 1702 """
1700 1703 opts = pycompat.byteskwargs(opts)
1701 1704 rev = opts.get(b'rev')
1702 1705 if rev:
1703 1706 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
1704 1707 ctx = scmutil.revsingle(repo, rev)
1705 1708 m = scmutil.match(ctx, (file1,) + pats, opts)
1706 1709 fntemplate = opts.pop(b'output', b'')
1707 1710 if cmdutil.isstdiofilename(fntemplate):
1708 1711 fntemplate = b''
1709 1712
1710 1713 if fntemplate:
1711 1714 fm = formatter.nullformatter(ui, b'cat', opts)
1712 1715 else:
1713 1716 ui.pager(b'cat')
1714 1717 fm = ui.formatter(b'cat', opts)
1715 1718 with fm:
1716 1719 return cmdutil.cat(
1717 1720 ui, repo, ctx, m, fm, fntemplate, b'', **pycompat.strkwargs(opts)
1718 1721 )
1719 1722
1720 1723
1721 1724 @command(
1722 1725 b'clone',
1723 1726 [
1724 1727 (
1725 1728 b'U',
1726 1729 b'noupdate',
1727 1730 None,
1728 1731 _(
1729 1732 b'the clone will include an empty working '
1730 1733 b'directory (only a repository)'
1731 1734 ),
1732 1735 ),
1733 1736 (
1734 1737 b'u',
1735 1738 b'updaterev',
1736 1739 b'',
1737 1740 _(b'revision, tag, or branch to check out'),
1738 1741 _(b'REV'),
1739 1742 ),
1740 1743 (
1741 1744 b'r',
1742 1745 b'rev',
1743 1746 [],
1744 1747 _(
1745 1748 b'do not clone everything, but include this changeset'
1746 1749 b' and its ancestors'
1747 1750 ),
1748 1751 _(b'REV'),
1749 1752 ),
1750 1753 (
1751 1754 b'b',
1752 1755 b'branch',
1753 1756 [],
1754 1757 _(
1755 1758 b'do not clone everything, but include this branch\'s'
1756 1759 b' changesets and their ancestors'
1757 1760 ),
1758 1761 _(b'BRANCH'),
1759 1762 ),
1760 1763 (b'', b'pull', None, _(b'use pull protocol to copy metadata')),
1761 1764 (b'', b'uncompressed', None, _(b'an alias to --stream (DEPRECATED)')),
1762 1765 (b'', b'stream', None, _(b'clone with minimal data processing')),
1763 1766 ]
1764 1767 + remoteopts,
1765 1768 _(b'[OPTION]... SOURCE [DEST]'),
1766 1769 helpcategory=command.CATEGORY_REPO_CREATION,
1767 1770 helpbasic=True,
1768 1771 norepo=True,
1769 1772 )
1770 1773 def clone(ui, source, dest=None, **opts):
1771 1774 """make a copy of an existing repository
1772 1775
1773 1776 Create a copy of an existing repository in a new directory.
1774 1777
1775 1778 If no destination directory name is specified, it defaults to the
1776 1779 basename of the source.
1777 1780
1778 1781 The location of the source is added to the new repository's
1779 1782 ``.hg/hgrc`` file, as the default to be used for future pulls.
1780 1783
1781 1784 Only local paths and ``ssh://`` URLs are supported as
1782 1785 destinations. For ``ssh://`` destinations, no working directory or
1783 1786 ``.hg/hgrc`` will be created on the remote side.
1784 1787
1785 1788 If the source repository has a bookmark called '@' set, that
1786 1789 revision will be checked out in the new repository by default.
1787 1790
1788 1791 To check out a particular version, use -u/--update, or
1789 1792 -U/--noupdate to create a clone with no working directory.
1790 1793
1791 1794 To pull only a subset of changesets, specify one or more revisions
1792 1795 identifiers with -r/--rev or branches with -b/--branch. The
1793 1796 resulting clone will contain only the specified changesets and
1794 1797 their ancestors. These options (or 'clone src#rev dest') imply
1795 1798 --pull, even for local source repositories.
1796 1799
1797 1800 In normal clone mode, the remote normalizes repository data into a common
1798 1801 exchange format and the receiving end translates this data into its local
1799 1802 storage format. --stream activates a different clone mode that essentially
1800 1803 copies repository files from the remote with minimal data processing. This
1801 1804 significantly reduces the CPU cost of a clone both remotely and locally.
1802 1805 However, it often increases the transferred data size by 30-40%. This can
1803 1806 result in substantially faster clones where I/O throughput is plentiful,
1804 1807 especially for larger repositories. A side-effect of --stream clones is
1805 1808 that storage settings and requirements on the remote are applied locally:
1806 1809 a modern client may inherit legacy or inefficient storage used by the
1807 1810 remote or a legacy Mercurial client may not be able to clone from a
1808 1811 modern Mercurial remote.
1809 1812
1810 1813 .. note::
1811 1814
1812 1815 Specifying a tag will include the tagged changeset but not the
1813 1816 changeset containing the tag.
1814 1817
1815 1818 .. container:: verbose
1816 1819
1817 1820 For efficiency, hardlinks are used for cloning whenever the
1818 1821 source and destination are on the same filesystem (note this
1819 1822 applies only to the repository data, not to the working
1820 1823 directory). Some filesystems, such as AFS, implement hardlinking
1821 1824 incorrectly, but do not report errors. In these cases, use the
1822 1825 --pull option to avoid hardlinking.
1823 1826
1824 1827 Mercurial will update the working directory to the first applicable
1825 1828 revision from this list:
1826 1829
1827 1830 a) null if -U or the source repository has no changesets
1828 1831 b) if -u . and the source repository is local, the first parent of
1829 1832 the source repository's working directory
1830 1833 c) the changeset specified with -u (if a branch name, this means the
1831 1834 latest head of that branch)
1832 1835 d) the changeset specified with -r
1833 1836 e) the tipmost head specified with -b
1834 1837 f) the tipmost head specified with the url#branch source syntax
1835 1838 g) the revision marked with the '@' bookmark, if present
1836 1839 h) the tipmost head of the default branch
1837 1840 i) tip
1838 1841
1839 1842 When cloning from servers that support it, Mercurial may fetch
1840 1843 pre-generated data from a server-advertised URL or inline from the
1841 1844 same stream. When this is done, hooks operating on incoming changesets
1842 1845 and changegroups may fire more than once, once for each pre-generated
1843 1846 bundle and as well as for any additional remaining data. In addition,
1844 1847 if an error occurs, the repository may be rolled back to a partial
1845 1848 clone. This behavior may change in future releases.
1846 1849 See :hg:`help -e clonebundles` for more.
1847 1850
1848 1851 Examples:
1849 1852
1850 1853 - clone a remote repository to a new directory named hg/::
1851 1854
1852 1855 hg clone https://www.mercurial-scm.org/repo/hg/
1853 1856
1854 1857 - create a lightweight local clone::
1855 1858
1856 1859 hg clone project/ project-feature/
1857 1860
1858 1861 - clone from an absolute path on an ssh server (note double-slash)::
1859 1862
1860 1863 hg clone ssh://user@server//home/projects/alpha/
1861 1864
1862 1865 - do a streaming clone while checking out a specified version::
1863 1866
1864 1867 hg clone --stream http://server/repo -u 1.5
1865 1868
1866 1869 - create a repository without changesets after a particular revision::
1867 1870
1868 1871 hg clone -r 04e544 experimental/ good/
1869 1872
1870 1873 - clone (and track) a particular named branch::
1871 1874
1872 1875 hg clone https://www.mercurial-scm.org/repo/hg/#stable
1873 1876
1874 1877 See :hg:`help urls` for details on specifying URLs.
1875 1878
1876 1879 Returns 0 on success.
1877 1880 """
1878 1881 opts = pycompat.byteskwargs(opts)
1879 1882 cmdutil.check_at_most_one_arg(opts, b'noupdate', b'updaterev')
1880 1883
1881 1884 # --include/--exclude can come from narrow or sparse.
1882 1885 includepats, excludepats = None, None
1883 1886
1884 1887 # hg.clone() differentiates between None and an empty set. So make sure
1885 1888 # patterns are sets if narrow is requested without patterns.
1886 1889 if opts.get(b'narrow'):
1887 1890 includepats = set()
1888 1891 excludepats = set()
1889 1892
1890 1893 if opts.get(b'include'):
1891 1894 includepats = narrowspec.parsepatterns(opts.get(b'include'))
1892 1895 if opts.get(b'exclude'):
1893 1896 excludepats = narrowspec.parsepatterns(opts.get(b'exclude'))
1894 1897
1895 1898 r = hg.clone(
1896 1899 ui,
1897 1900 opts,
1898 1901 source,
1899 1902 dest,
1900 1903 pull=opts.get(b'pull'),
1901 1904 stream=opts.get(b'stream') or opts.get(b'uncompressed'),
1902 1905 revs=opts.get(b'rev'),
1903 1906 update=opts.get(b'updaterev') or not opts.get(b'noupdate'),
1904 1907 branch=opts.get(b'branch'),
1905 1908 shareopts=opts.get(b'shareopts'),
1906 1909 storeincludepats=includepats,
1907 1910 storeexcludepats=excludepats,
1908 1911 depth=opts.get(b'depth') or None,
1909 1912 )
1910 1913
1911 1914 return r is None
1912 1915
1913 1916
1914 1917 @command(
1915 1918 b'commit|ci',
1916 1919 [
1917 1920 (
1918 1921 b'A',
1919 1922 b'addremove',
1920 1923 None,
1921 1924 _(b'mark new/missing files as added/removed before committing'),
1922 1925 ),
1923 1926 (b'', b'close-branch', None, _(b'mark a branch head as closed')),
1924 1927 (b'', b'amend', None, _(b'amend the parent of the working directory')),
1925 1928 (b's', b'secret', None, _(b'use the secret phase for committing')),
1926 1929 (b'e', b'edit', None, _(b'invoke editor on commit messages')),
1927 1930 (
1928 1931 b'',
1929 1932 b'force-close-branch',
1930 1933 None,
1931 1934 _(b'forcibly close branch from a non-head changeset (ADVANCED)'),
1932 1935 ),
1933 1936 (b'i', b'interactive', None, _(b'use interactive mode')),
1934 1937 ]
1935 1938 + walkopts
1936 1939 + commitopts
1937 1940 + commitopts2
1938 1941 + subrepoopts,
1939 1942 _(b'[OPTION]... [FILE]...'),
1940 1943 helpcategory=command.CATEGORY_COMMITTING,
1941 1944 helpbasic=True,
1942 1945 inferrepo=True,
1943 1946 )
1944 1947 def commit(ui, repo, *pats, **opts):
1945 1948 """commit the specified files or all outstanding changes
1946 1949
1947 1950 Commit changes to the given files into the repository. Unlike a
1948 1951 centralized SCM, this operation is a local operation. See
1949 1952 :hg:`push` for a way to actively distribute your changes.
1950 1953
1951 1954 If a list of files is omitted, all changes reported by :hg:`status`
1952 1955 will be committed.
1953 1956
1954 1957 If you are committing the result of a merge, do not provide any
1955 1958 filenames or -I/-X filters.
1956 1959
1957 1960 If no commit message is specified, Mercurial starts your
1958 1961 configured editor where you can enter a message. In case your
1959 1962 commit fails, you will find a backup of your message in
1960 1963 ``.hg/last-message.txt``.
1961 1964
1962 1965 The --close-branch flag can be used to mark the current branch
1963 1966 head closed. When all heads of a branch are closed, the branch
1964 1967 will be considered closed and no longer listed.
1965 1968
1966 1969 The --amend flag can be used to amend the parent of the
1967 1970 working directory with a new commit that contains the changes
1968 1971 in the parent in addition to those currently reported by :hg:`status`,
1969 1972 if there are any. The old commit is stored in a backup bundle in
1970 1973 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1971 1974 on how to restore it).
1972 1975
1973 1976 Message, user and date are taken from the amended commit unless
1974 1977 specified. When a message isn't specified on the command line,
1975 1978 the editor will open with the message of the amended commit.
1976 1979
1977 1980 It is not possible to amend public changesets (see :hg:`help phases`)
1978 1981 or changesets that have children.
1979 1982
1980 1983 See :hg:`help dates` for a list of formats valid for -d/--date.
1981 1984
1982 1985 Returns 0 on success, 1 if nothing changed.
1983 1986
1984 1987 .. container:: verbose
1985 1988
1986 1989 Examples:
1987 1990
1988 1991 - commit all files ending in .py::
1989 1992
1990 1993 hg commit --include "set:**.py"
1991 1994
1992 1995 - commit all non-binary files::
1993 1996
1994 1997 hg commit --exclude "set:binary()"
1995 1998
1996 1999 - amend the current commit and set the date to now::
1997 2000
1998 2001 hg commit --amend --date now
1999 2002 """
2000 2003 with repo.wlock(), repo.lock():
2001 2004 return _docommit(ui, repo, *pats, **opts)
2002 2005
2003 2006
2004 2007 def _docommit(ui, repo, *pats, **opts):
2005 2008 if opts.get('interactive'):
2006 2009 opts.pop('interactive')
2007 2010 ret = cmdutil.dorecord(
2008 2011 ui, repo, commit, None, False, cmdutil.recordfilter, *pats, **opts
2009 2012 )
2010 2013 # ret can be 0 (no changes to record) or the value returned by
2011 2014 # commit(), 1 if nothing changed or None on success.
2012 2015 return 1 if ret == 0 else ret
2013 2016
2014 2017 opts = pycompat.byteskwargs(opts)
2015 2018 if opts.get(b'subrepos'):
2016 2019 if opts.get(b'amend'):
2017 2020 raise error.Abort(_(b'cannot amend with --subrepos'))
2018 2021 # Let --subrepos on the command line override config setting.
2019 2022 ui.setconfig(b'ui', b'commitsubrepos', True, b'commit')
2020 2023
2021 2024 cmdutil.checkunfinished(repo, commit=True)
2022 2025
2023 2026 branch = repo[None].branch()
2024 2027 bheads = repo.branchheads(branch)
2028 tip = repo.changelog.tip()
2025 2029
2026 2030 extra = {}
2027 2031 if opts.get(b'close_branch') or opts.get(b'force_close_branch'):
2028 2032 extra[b'close'] = b'1'
2029 2033
2030 2034 if repo[b'.'].closesbranch():
2031 2035 raise error.Abort(
2032 2036 _(b'current revision is already a branch closing head')
2033 2037 )
2034 2038 elif not bheads:
2035 2039 raise error.Abort(_(b'branch "%s" has no heads to close') % branch)
2036 2040 elif (
2037 2041 branch == repo[b'.'].branch()
2038 2042 and repo[b'.'].node() not in bheads
2039 2043 and not opts.get(b'force_close_branch')
2040 2044 ):
2041 2045 hint = _(
2042 2046 b'use --force-close-branch to close branch from a non-head'
2043 2047 b' changeset'
2044 2048 )
2045 2049 raise error.Abort(_(b'can only close branch heads'), hint=hint)
2046 2050 elif opts.get(b'amend'):
2047 2051 if (
2048 2052 repo[b'.'].p1().branch() != branch
2049 2053 and repo[b'.'].p2().branch() != branch
2050 2054 ):
2051 2055 raise error.Abort(_(b'can only close branch heads'))
2052 2056
2053 2057 if opts.get(b'amend'):
2054 2058 if ui.configbool(b'ui', b'commitsubrepos'):
2055 2059 raise error.Abort(_(b'cannot amend with ui.commitsubrepos enabled'))
2056 2060
2057 2061 old = repo[b'.']
2058 2062 rewriteutil.precheck(repo, [old.rev()], b'amend')
2059 2063
2060 2064 # Currently histedit gets confused if an amend happens while histedit
2061 2065 # is in progress. Since we have a checkunfinished command, we are
2062 2066 # temporarily honoring it.
2063 2067 #
2064 2068 # Note: eventually this guard will be removed. Please do not expect
2065 2069 # this behavior to remain.
2066 2070 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
2067 2071 cmdutil.checkunfinished(repo)
2068 2072
2069 2073 node = cmdutil.amend(ui, repo, old, extra, pats, opts)
2070 2074 if node == old.node():
2071 2075 ui.status(_(b"nothing changed\n"))
2072 2076 return 1
2073 2077 else:
2074 2078
2075 2079 def commitfunc(ui, repo, message, match, opts):
2076 2080 overrides = {}
2077 2081 if opts.get(b'secret'):
2078 2082 overrides[(b'phases', b'new-commit')] = b'secret'
2079 2083
2080 2084 baseui = repo.baseui
2081 2085 with baseui.configoverride(overrides, b'commit'):
2082 2086 with ui.configoverride(overrides, b'commit'):
2083 2087 editform = cmdutil.mergeeditform(
2084 2088 repo[None], b'commit.normal'
2085 2089 )
2086 2090 editor = cmdutil.getcommiteditor(
2087 2091 editform=editform, **pycompat.strkwargs(opts)
2088 2092 )
2089 2093 return repo.commit(
2090 2094 message,
2091 2095 opts.get(b'user'),
2092 2096 opts.get(b'date'),
2093 2097 match,
2094 2098 editor=editor,
2095 2099 extra=extra,
2096 2100 )
2097 2101
2098 2102 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
2099 2103
2100 2104 if not node:
2101 2105 stat = cmdutil.postcommitstatus(repo, pats, opts)
2102 2106 if stat.deleted:
2103 2107 ui.status(
2104 2108 _(
2105 2109 b"nothing changed (%d missing files, see "
2106 2110 b"'hg status')\n"
2107 2111 )
2108 2112 % len(stat.deleted)
2109 2113 )
2110 2114 else:
2111 2115 ui.status(_(b"nothing changed\n"))
2112 2116 return 1
2113 2117
2114 cmdutil.commitstatus(repo, node, branch, bheads, opts)
2118 cmdutil.commitstatus(repo, node, branch, bheads, tip, opts)
2115 2119
2116 2120 if not ui.quiet and ui.configbool(b'commands', b'commit.post-status'):
2117 2121 status(
2118 2122 ui,
2119 2123 repo,
2120 2124 modified=True,
2121 2125 added=True,
2122 2126 removed=True,
2123 2127 deleted=True,
2124 2128 unknown=True,
2125 2129 subrepos=opts.get(b'subrepos'),
2126 2130 )
2127 2131
2128 2132
2129 2133 @command(
2130 2134 b'config|showconfig|debugconfig',
2131 2135 [
2132 2136 (b'u', b'untrusted', None, _(b'show untrusted configuration options')),
2133 2137 (b'e', b'edit', None, _(b'edit user config')),
2134 2138 (b'l', b'local', None, _(b'edit repository config')),
2135 2139 (
2136 2140 b'',
2137 2141 b'shared',
2138 2142 None,
2139 2143 _(b'edit shared source repository config (EXPERIMENTAL)'),
2140 2144 ),
2141 2145 (b'g', b'global', None, _(b'edit global config')),
2142 2146 ]
2143 2147 + formatteropts,
2144 2148 _(b'[-u] [NAME]...'),
2145 2149 helpcategory=command.CATEGORY_HELP,
2146 2150 optionalrepo=True,
2147 2151 intents={INTENT_READONLY},
2148 2152 )
2149 2153 def config(ui, repo, *values, **opts):
2150 2154 """show combined config settings from all hgrc files
2151 2155
2152 2156 With no arguments, print names and values of all config items.
2153 2157
2154 2158 With one argument of the form section.name, print just the value
2155 2159 of that config item.
2156 2160
2157 2161 With multiple arguments, print names and values of all config
2158 2162 items with matching section names or section.names.
2159 2163
2160 2164 With --edit, start an editor on the user-level config file. With
2161 2165 --global, edit the system-wide config file. With --local, edit the
2162 2166 repository-level config file.
2163 2167
2164 2168 With --debug, the source (filename and line number) is printed
2165 2169 for each config item.
2166 2170
2167 2171 See :hg:`help config` for more information about config files.
2168 2172
2169 2173 .. container:: verbose
2170 2174
2171 2175 Template:
2172 2176
2173 2177 The following keywords are supported. See also :hg:`help templates`.
2174 2178
2175 2179 :name: String. Config name.
2176 2180 :source: String. Filename and line number where the item is defined.
2177 2181 :value: String. Config value.
2178 2182
2179 2183 The --shared flag can be used to edit the config file of shared source
2180 2184 repository. It only works when you have shared using the experimental
2181 2185 share safe feature.
2182 2186
2183 2187 Returns 0 on success, 1 if NAME does not exist.
2184 2188
2185 2189 """
2186 2190
2187 2191 opts = pycompat.byteskwargs(opts)
2188 2192 editopts = (b'edit', b'local', b'global', b'shared')
2189 2193 if any(opts.get(o) for o in editopts):
2190 2194 cmdutil.check_at_most_one_arg(opts, *editopts[1:])
2191 2195 if opts.get(b'local'):
2192 2196 if not repo:
2193 2197 raise error.Abort(_(b"can't use --local outside a repository"))
2194 2198 paths = [repo.vfs.join(b'hgrc')]
2195 2199 elif opts.get(b'global'):
2196 2200 paths = rcutil.systemrcpath()
2197 2201 elif opts.get(b'shared'):
2198 2202 if not repo.shared():
2199 2203 raise error.Abort(
2200 2204 _(b"repository is not shared; can't use --shared")
2201 2205 )
2202 2206 if requirements.SHARESAFE_REQUIREMENT not in repo.requirements:
2203 2207 raise error.Abort(
2204 2208 _(
2205 2209 b"share safe feature not unabled; "
2206 2210 b"unable to edit shared source repository config"
2207 2211 )
2208 2212 )
2209 2213 paths = [vfsmod.vfs(repo.sharedpath).join(b'hgrc')]
2210 2214 else:
2211 2215 paths = rcutil.userrcpath()
2212 2216
2213 2217 for f in paths:
2214 2218 if os.path.exists(f):
2215 2219 break
2216 2220 else:
2217 2221 if opts.get(b'global'):
2218 2222 samplehgrc = uimod.samplehgrcs[b'global']
2219 2223 elif opts.get(b'local'):
2220 2224 samplehgrc = uimod.samplehgrcs[b'local']
2221 2225 else:
2222 2226 samplehgrc = uimod.samplehgrcs[b'user']
2223 2227
2224 2228 f = paths[0]
2225 2229 fp = open(f, b"wb")
2226 2230 fp.write(util.tonativeeol(samplehgrc))
2227 2231 fp.close()
2228 2232
2229 2233 editor = ui.geteditor()
2230 2234 ui.system(
2231 2235 b"%s \"%s\"" % (editor, f),
2232 2236 onerr=error.Abort,
2233 2237 errprefix=_(b"edit failed"),
2234 2238 blockedtag=b'config_edit',
2235 2239 )
2236 2240 return
2237 2241 ui.pager(b'config')
2238 2242 fm = ui.formatter(b'config', opts)
2239 2243 for t, f in rcutil.rccomponents():
2240 2244 if t == b'path':
2241 2245 ui.debug(b'read config from: %s\n' % f)
2242 2246 elif t == b'resource':
2243 2247 ui.debug(b'read config from: resource:%s.%s\n' % (f[0], f[1]))
2244 2248 elif t == b'items':
2245 2249 # Don't print anything for 'items'.
2246 2250 pass
2247 2251 else:
2248 2252 raise error.ProgrammingError(b'unknown rctype: %s' % t)
2249 2253 untrusted = bool(opts.get(b'untrusted'))
2250 2254
2251 2255 selsections = selentries = []
2252 2256 if values:
2253 2257 selsections = [v for v in values if b'.' not in v]
2254 2258 selentries = [v for v in values if b'.' in v]
2255 2259 uniquesel = len(selentries) == 1 and not selsections
2256 2260 selsections = set(selsections)
2257 2261 selentries = set(selentries)
2258 2262
2259 2263 matched = False
2260 2264 for section, name, value in ui.walkconfig(untrusted=untrusted):
2261 2265 source = ui.configsource(section, name, untrusted)
2262 2266 value = pycompat.bytestr(value)
2263 2267 defaultvalue = ui.configdefault(section, name)
2264 2268 if fm.isplain():
2265 2269 source = source or b'none'
2266 2270 value = value.replace(b'\n', b'\\n')
2267 2271 entryname = section + b'.' + name
2268 2272 if values and not (section in selsections or entryname in selentries):
2269 2273 continue
2270 2274 fm.startitem()
2271 2275 fm.condwrite(ui.debugflag, b'source', b'%s: ', source)
2272 2276 if uniquesel:
2273 2277 fm.data(name=entryname)
2274 2278 fm.write(b'value', b'%s\n', value)
2275 2279 else:
2276 2280 fm.write(b'name value', b'%s=%s\n', entryname, value)
2277 2281 if formatter.isprintable(defaultvalue):
2278 2282 fm.data(defaultvalue=defaultvalue)
2279 2283 elif isinstance(defaultvalue, list) and all(
2280 2284 formatter.isprintable(e) for e in defaultvalue
2281 2285 ):
2282 2286 fm.data(defaultvalue=fm.formatlist(defaultvalue, name=b'value'))
2283 2287 # TODO: no idea how to process unsupported defaultvalue types
2284 2288 matched = True
2285 2289 fm.end()
2286 2290 if matched:
2287 2291 return 0
2288 2292 return 1
2289 2293
2290 2294
2291 2295 @command(
2292 2296 b'continue',
2293 2297 dryrunopts,
2294 2298 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
2295 2299 helpbasic=True,
2296 2300 )
2297 2301 def continuecmd(ui, repo, **opts):
2298 2302 """resumes an interrupted operation (EXPERIMENTAL)
2299 2303
2300 2304 Finishes a multistep operation like graft, histedit, rebase, merge,
2301 2305 and unshelve if they are in an interrupted state.
2302 2306
2303 2307 use --dry-run/-n to dry run the command.
2304 2308 """
2305 2309 dryrun = opts.get('dry_run')
2306 2310 contstate = cmdutil.getunfinishedstate(repo)
2307 2311 if not contstate:
2308 2312 raise error.Abort(_(b'no operation in progress'))
2309 2313 if not contstate.continuefunc:
2310 2314 raise error.Abort(
2311 2315 (
2312 2316 _(b"%s in progress but does not support 'hg continue'")
2313 2317 % (contstate._opname)
2314 2318 ),
2315 2319 hint=contstate.continuemsg(),
2316 2320 )
2317 2321 if dryrun:
2318 2322 ui.status(_(b'%s in progress, will be resumed\n') % (contstate._opname))
2319 2323 return
2320 2324 return contstate.continuefunc(ui, repo)
2321 2325
2322 2326
2323 2327 @command(
2324 2328 b'copy|cp',
2325 2329 [
2326 2330 (b'', b'forget', None, _(b'unmark a destination file as copied')),
2327 2331 (b'A', b'after', None, _(b'record a copy that has already occurred')),
2328 2332 (
2329 2333 b'',
2330 2334 b'at-rev',
2331 2335 b'',
2332 2336 _(b'(un)mark copies in the given revision (EXPERIMENTAL)'),
2333 2337 _(b'REV'),
2334 2338 ),
2335 2339 (
2336 2340 b'f',
2337 2341 b'force',
2338 2342 None,
2339 2343 _(b'forcibly copy over an existing managed file'),
2340 2344 ),
2341 2345 ]
2342 2346 + walkopts
2343 2347 + dryrunopts,
2344 2348 _(b'[OPTION]... SOURCE... DEST'),
2345 2349 helpcategory=command.CATEGORY_FILE_CONTENTS,
2346 2350 )
2347 2351 def copy(ui, repo, *pats, **opts):
2348 2352 """mark files as copied for the next commit
2349 2353
2350 2354 Mark dest as having copies of source files. If dest is a
2351 2355 directory, copies are put in that directory. If dest is a file,
2352 2356 the source must be a single file.
2353 2357
2354 2358 By default, this command copies the contents of files as they
2355 2359 exist in the working directory. If invoked with -A/--after, the
2356 2360 operation is recorded, but no copying is performed.
2357 2361
2358 2362 To undo marking a destination file as copied, use --forget. With that
2359 2363 option, all given (positional) arguments are unmarked as copies. The
2360 2364 destination file(s) will be left in place (still tracked).
2361 2365
2362 2366 This command takes effect with the next commit by default.
2363 2367
2364 2368 Returns 0 on success, 1 if errors are encountered.
2365 2369 """
2366 2370 opts = pycompat.byteskwargs(opts)
2367 2371 with repo.wlock():
2368 2372 return cmdutil.copy(ui, repo, pats, opts)
2369 2373
2370 2374
2371 2375 @command(
2372 2376 b'debugcommands',
2373 2377 [],
2374 2378 _(b'[COMMAND]'),
2375 2379 helpcategory=command.CATEGORY_HELP,
2376 2380 norepo=True,
2377 2381 )
2378 2382 def debugcommands(ui, cmd=b'', *args):
2379 2383 """list all available commands and options"""
2380 2384 for cmd, vals in sorted(pycompat.iteritems(table)):
2381 2385 cmd = cmd.split(b'|')[0]
2382 2386 opts = b', '.join([i[1] for i in vals[1]])
2383 2387 ui.write(b'%s: %s\n' % (cmd, opts))
2384 2388
2385 2389
2386 2390 @command(
2387 2391 b'debugcomplete',
2388 2392 [(b'o', b'options', None, _(b'show the command options'))],
2389 2393 _(b'[-o] CMD'),
2390 2394 helpcategory=command.CATEGORY_HELP,
2391 2395 norepo=True,
2392 2396 )
2393 2397 def debugcomplete(ui, cmd=b'', **opts):
2394 2398 """returns the completion list associated with the given command"""
2395 2399
2396 2400 if opts.get('options'):
2397 2401 options = []
2398 2402 otables = [globalopts]
2399 2403 if cmd:
2400 2404 aliases, entry = cmdutil.findcmd(cmd, table, False)
2401 2405 otables.append(entry[1])
2402 2406 for t in otables:
2403 2407 for o in t:
2404 2408 if b"(DEPRECATED)" in o[3]:
2405 2409 continue
2406 2410 if o[0]:
2407 2411 options.append(b'-%s' % o[0])
2408 2412 options.append(b'--%s' % o[1])
2409 2413 ui.write(b"%s\n" % b"\n".join(options))
2410 2414 return
2411 2415
2412 2416 cmdlist, unused_allcmds = cmdutil.findpossible(cmd, table)
2413 2417 if ui.verbose:
2414 2418 cmdlist = [b' '.join(c[0]) for c in cmdlist.values()]
2415 2419 ui.write(b"%s\n" % b"\n".join(sorted(cmdlist)))
2416 2420
2417 2421
2418 2422 @command(
2419 2423 b'diff',
2420 2424 [
2421 2425 (b'r', b'rev', [], _(b'revision'), _(b'REV')),
2422 2426 (b'c', b'change', b'', _(b'change made by revision'), _(b'REV')),
2423 2427 ]
2424 2428 + diffopts
2425 2429 + diffopts2
2426 2430 + walkopts
2427 2431 + subrepoopts,
2428 2432 _(b'[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'),
2429 2433 helpcategory=command.CATEGORY_FILE_CONTENTS,
2430 2434 helpbasic=True,
2431 2435 inferrepo=True,
2432 2436 intents={INTENT_READONLY},
2433 2437 )
2434 2438 def diff(ui, repo, *pats, **opts):
2435 2439 """diff repository (or selected files)
2436 2440
2437 2441 Show differences between revisions for the specified files.
2438 2442
2439 2443 Differences between files are shown using the unified diff format.
2440 2444
2441 2445 .. note::
2442 2446
2443 2447 :hg:`diff` may generate unexpected results for merges, as it will
2444 2448 default to comparing against the working directory's first
2445 2449 parent changeset if no revisions are specified.
2446 2450
2447 2451 When two revision arguments are given, then changes are shown
2448 2452 between those revisions. If only one revision is specified then
2449 2453 that revision is compared to the working directory, and, when no
2450 2454 revisions are specified, the working directory files are compared
2451 2455 to its first parent.
2452 2456
2453 2457 Alternatively you can specify -c/--change with a revision to see
2454 2458 the changes in that changeset relative to its first parent.
2455 2459
2456 2460 Without the -a/--text option, diff will avoid generating diffs of
2457 2461 files it detects as binary. With -a, diff will generate a diff
2458 2462 anyway, probably with undesirable results.
2459 2463
2460 2464 Use the -g/--git option to generate diffs in the git extended diff
2461 2465 format. For more information, read :hg:`help diffs`.
2462 2466
2463 2467 .. container:: verbose
2464 2468
2465 2469 Examples:
2466 2470
2467 2471 - compare a file in the current working directory to its parent::
2468 2472
2469 2473 hg diff foo.c
2470 2474
2471 2475 - compare two historical versions of a directory, with rename info::
2472 2476
2473 2477 hg diff --git -r 1.0:1.2 lib/
2474 2478
2475 2479 - get change stats relative to the last change on some date::
2476 2480
2477 2481 hg diff --stat -r "date('may 2')"
2478 2482
2479 2483 - diff all newly-added files that contain a keyword::
2480 2484
2481 2485 hg diff "set:added() and grep(GNU)"
2482 2486
2483 2487 - compare a revision and its parents::
2484 2488
2485 2489 hg diff -c 9353 # compare against first parent
2486 2490 hg diff -r 9353^:9353 # same using revset syntax
2487 2491 hg diff -r 9353^2:9353 # compare against the second parent
2488 2492
2489 2493 Returns 0 on success.
2490 2494 """
2491 2495
2492 2496 cmdutil.check_at_most_one_arg(opts, 'rev', 'change')
2493 2497 opts = pycompat.byteskwargs(opts)
2494 2498 revs = opts.get(b'rev')
2495 2499 change = opts.get(b'change')
2496 2500 stat = opts.get(b'stat')
2497 2501 reverse = opts.get(b'reverse')
2498 2502
2499 2503 if change:
2500 2504 repo = scmutil.unhidehashlikerevs(repo, [change], b'nowarn')
2501 2505 ctx2 = scmutil.revsingle(repo, change, None)
2502 2506 ctx1 = ctx2.p1()
2503 2507 else:
2504 2508 repo = scmutil.unhidehashlikerevs(repo, revs, b'nowarn')
2505 2509 ctx1, ctx2 = scmutil.revpair(repo, revs)
2506 2510
2507 2511 if reverse:
2508 2512 ctxleft = ctx2
2509 2513 ctxright = ctx1
2510 2514 else:
2511 2515 ctxleft = ctx1
2512 2516 ctxright = ctx2
2513 2517
2514 2518 diffopts = patch.diffallopts(ui, opts)
2515 2519 m = scmutil.match(ctx2, pats, opts)
2516 2520 m = repo.narrowmatch(m)
2517 2521 ui.pager(b'diff')
2518 2522 logcmdutil.diffordiffstat(
2519 2523 ui,
2520 2524 repo,
2521 2525 diffopts,
2522 2526 ctxleft,
2523 2527 ctxright,
2524 2528 m,
2525 2529 stat=stat,
2526 2530 listsubrepos=opts.get(b'subrepos'),
2527 2531 root=opts.get(b'root'),
2528 2532 )
2529 2533
2530 2534
2531 2535 @command(
2532 2536 b'export',
2533 2537 [
2534 2538 (
2535 2539 b'B',
2536 2540 b'bookmark',
2537 2541 b'',
2538 2542 _(b'export changes only reachable by given bookmark'),
2539 2543 _(b'BOOKMARK'),
2540 2544 ),
2541 2545 (
2542 2546 b'o',
2543 2547 b'output',
2544 2548 b'',
2545 2549 _(b'print output to file with formatted name'),
2546 2550 _(b'FORMAT'),
2547 2551 ),
2548 2552 (b'', b'switch-parent', None, _(b'diff against the second parent')),
2549 2553 (b'r', b'rev', [], _(b'revisions to export'), _(b'REV')),
2550 2554 ]
2551 2555 + diffopts
2552 2556 + formatteropts,
2553 2557 _(b'[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'),
2554 2558 helpcategory=command.CATEGORY_IMPORT_EXPORT,
2555 2559 helpbasic=True,
2556 2560 intents={INTENT_READONLY},
2557 2561 )
2558 2562 def export(ui, repo, *changesets, **opts):
2559 2563 """dump the header and diffs for one or more changesets
2560 2564
2561 2565 Print the changeset header and diffs for one or more revisions.
2562 2566 If no revision is given, the parent of the working directory is used.
2563 2567
2564 2568 The information shown in the changeset header is: author, date,
2565 2569 branch name (if non-default), changeset hash, parent(s) and commit
2566 2570 comment.
2567 2571
2568 2572 .. note::
2569 2573
2570 2574 :hg:`export` may generate unexpected diff output for merge
2571 2575 changesets, as it will compare the merge changeset against its
2572 2576 first parent only.
2573 2577
2574 2578 Output may be to a file, in which case the name of the file is
2575 2579 given using a template string. See :hg:`help templates`. In addition
2576 2580 to the common template keywords, the following formatting rules are
2577 2581 supported:
2578 2582
2579 2583 :``%%``: literal "%" character
2580 2584 :``%H``: changeset hash (40 hexadecimal digits)
2581 2585 :``%N``: number of patches being generated
2582 2586 :``%R``: changeset revision number
2583 2587 :``%b``: basename of the exporting repository
2584 2588 :``%h``: short-form changeset hash (12 hexadecimal digits)
2585 2589 :``%m``: first line of the commit message (only alphanumeric characters)
2586 2590 :``%n``: zero-padded sequence number, starting at 1
2587 2591 :``%r``: zero-padded changeset revision number
2588 2592 :``\\``: literal "\\" character
2589 2593
2590 2594 Without the -a/--text option, export will avoid generating diffs
2591 2595 of files it detects as binary. With -a, export will generate a
2592 2596 diff anyway, probably with undesirable results.
2593 2597
2594 2598 With -B/--bookmark changesets reachable by the given bookmark are
2595 2599 selected.
2596 2600
2597 2601 Use the -g/--git option to generate diffs in the git extended diff
2598 2602 format. See :hg:`help diffs` for more information.
2599 2603
2600 2604 With the --switch-parent option, the diff will be against the
2601 2605 second parent. It can be useful to review a merge.
2602 2606
2603 2607 .. container:: verbose
2604 2608
2605 2609 Template:
2606 2610
2607 2611 The following keywords are supported in addition to the common template
2608 2612 keywords and functions. See also :hg:`help templates`.
2609 2613
2610 2614 :diff: String. Diff content.
2611 2615 :parents: List of strings. Parent nodes of the changeset.
2612 2616
2613 2617 Examples:
2614 2618
2615 2619 - use export and import to transplant a bugfix to the current
2616 2620 branch::
2617 2621
2618 2622 hg export -r 9353 | hg import -
2619 2623
2620 2624 - export all the changesets between two revisions to a file with
2621 2625 rename information::
2622 2626
2623 2627 hg export --git -r 123:150 > changes.txt
2624 2628
2625 2629 - split outgoing changes into a series of patches with
2626 2630 descriptive names::
2627 2631
2628 2632 hg export -r "outgoing()" -o "%n-%m.patch"
2629 2633
2630 2634 Returns 0 on success.
2631 2635 """
2632 2636 opts = pycompat.byteskwargs(opts)
2633 2637 bookmark = opts.get(b'bookmark')
2634 2638 changesets += tuple(opts.get(b'rev', []))
2635 2639
2636 2640 cmdutil.check_at_most_one_arg(opts, b'rev', b'bookmark')
2637 2641
2638 2642 if bookmark:
2639 2643 if bookmark not in repo._bookmarks:
2640 2644 raise error.Abort(_(b"bookmark '%s' not found") % bookmark)
2641 2645
2642 2646 revs = scmutil.bookmarkrevs(repo, bookmark)
2643 2647 else:
2644 2648 if not changesets:
2645 2649 changesets = [b'.']
2646 2650
2647 2651 repo = scmutil.unhidehashlikerevs(repo, changesets, b'nowarn')
2648 2652 revs = scmutil.revrange(repo, changesets)
2649 2653
2650 2654 if not revs:
2651 2655 raise error.Abort(_(b"export requires at least one changeset"))
2652 2656 if len(revs) > 1:
2653 2657 ui.note(_(b'exporting patches:\n'))
2654 2658 else:
2655 2659 ui.note(_(b'exporting patch:\n'))
2656 2660
2657 2661 fntemplate = opts.get(b'output')
2658 2662 if cmdutil.isstdiofilename(fntemplate):
2659 2663 fntemplate = b''
2660 2664
2661 2665 if fntemplate:
2662 2666 fm = formatter.nullformatter(ui, b'export', opts)
2663 2667 else:
2664 2668 ui.pager(b'export')
2665 2669 fm = ui.formatter(b'export', opts)
2666 2670 with fm:
2667 2671 cmdutil.export(
2668 2672 repo,
2669 2673 revs,
2670 2674 fm,
2671 2675 fntemplate=fntemplate,
2672 2676 switch_parent=opts.get(b'switch_parent'),
2673 2677 opts=patch.diffallopts(ui, opts),
2674 2678 )
2675 2679
2676 2680
2677 2681 @command(
2678 2682 b'files',
2679 2683 [
2680 2684 (
2681 2685 b'r',
2682 2686 b'rev',
2683 2687 b'',
2684 2688 _(b'search the repository as it is in REV'),
2685 2689 _(b'REV'),
2686 2690 ),
2687 2691 (
2688 2692 b'0',
2689 2693 b'print0',
2690 2694 None,
2691 2695 _(b'end filenames with NUL, for use with xargs'),
2692 2696 ),
2693 2697 ]
2694 2698 + walkopts
2695 2699 + formatteropts
2696 2700 + subrepoopts,
2697 2701 _(b'[OPTION]... [FILE]...'),
2698 2702 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
2699 2703 intents={INTENT_READONLY},
2700 2704 )
2701 2705 def files(ui, repo, *pats, **opts):
2702 2706 """list tracked files
2703 2707
2704 2708 Print files under Mercurial control in the working directory or
2705 2709 specified revision for given files (excluding removed files).
2706 2710 Files can be specified as filenames or filesets.
2707 2711
2708 2712 If no files are given to match, this command prints the names
2709 2713 of all files under Mercurial control.
2710 2714
2711 2715 .. container:: verbose
2712 2716
2713 2717 Template:
2714 2718
2715 2719 The following keywords are supported in addition to the common template
2716 2720 keywords and functions. See also :hg:`help templates`.
2717 2721
2718 2722 :flags: String. Character denoting file's symlink and executable bits.
2719 2723 :path: String. Repository-absolute path of the file.
2720 2724 :size: Integer. Size of the file in bytes.
2721 2725
2722 2726 Examples:
2723 2727
2724 2728 - list all files under the current directory::
2725 2729
2726 2730 hg files .
2727 2731
2728 2732 - shows sizes and flags for current revision::
2729 2733
2730 2734 hg files -vr .
2731 2735
2732 2736 - list all files named README::
2733 2737
2734 2738 hg files -I "**/README"
2735 2739
2736 2740 - list all binary files::
2737 2741
2738 2742 hg files "set:binary()"
2739 2743
2740 2744 - find files containing a regular expression::
2741 2745
2742 2746 hg files "set:grep('bob')"
2743 2747
2744 2748 - search tracked file contents with xargs and grep::
2745 2749
2746 2750 hg files -0 | xargs -0 grep foo
2747 2751
2748 2752 See :hg:`help patterns` and :hg:`help filesets` for more information
2749 2753 on specifying file patterns.
2750 2754
2751 2755 Returns 0 if a match is found, 1 otherwise.
2752 2756
2753 2757 """
2754 2758
2755 2759 opts = pycompat.byteskwargs(opts)
2756 2760 rev = opts.get(b'rev')
2757 2761 if rev:
2758 2762 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
2759 2763 ctx = scmutil.revsingle(repo, rev, None)
2760 2764
2761 2765 end = b'\n'
2762 2766 if opts.get(b'print0'):
2763 2767 end = b'\0'
2764 2768 fmt = b'%s' + end
2765 2769
2766 2770 m = scmutil.match(ctx, pats, opts)
2767 2771 ui.pager(b'files')
2768 2772 uipathfn = scmutil.getuipathfn(ctx.repo(), legacyrelativevalue=True)
2769 2773 with ui.formatter(b'files', opts) as fm:
2770 2774 return cmdutil.files(
2771 2775 ui, ctx, m, uipathfn, fm, fmt, opts.get(b'subrepos')
2772 2776 )
2773 2777
2774 2778
2775 2779 @command(
2776 2780 b'forget',
2777 2781 [(b'i', b'interactive', None, _(b'use interactive mode')),]
2778 2782 + walkopts
2779 2783 + dryrunopts,
2780 2784 _(b'[OPTION]... FILE...'),
2781 2785 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
2782 2786 helpbasic=True,
2783 2787 inferrepo=True,
2784 2788 )
2785 2789 def forget(ui, repo, *pats, **opts):
2786 2790 """forget the specified files on the next commit
2787 2791
2788 2792 Mark the specified files so they will no longer be tracked
2789 2793 after the next commit.
2790 2794
2791 2795 This only removes files from the current branch, not from the
2792 2796 entire project history, and it does not delete them from the
2793 2797 working directory.
2794 2798
2795 2799 To delete the file from the working directory, see :hg:`remove`.
2796 2800
2797 2801 To undo a forget before the next commit, see :hg:`add`.
2798 2802
2799 2803 .. container:: verbose
2800 2804
2801 2805 Examples:
2802 2806
2803 2807 - forget newly-added binary files::
2804 2808
2805 2809 hg forget "set:added() and binary()"
2806 2810
2807 2811 - forget files that would be excluded by .hgignore::
2808 2812
2809 2813 hg forget "set:hgignore()"
2810 2814
2811 2815 Returns 0 on success.
2812 2816 """
2813 2817
2814 2818 opts = pycompat.byteskwargs(opts)
2815 2819 if not pats:
2816 2820 raise error.Abort(_(b'no files specified'))
2817 2821
2818 2822 m = scmutil.match(repo[None], pats, opts)
2819 2823 dryrun, interactive = opts.get(b'dry_run'), opts.get(b'interactive')
2820 2824 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
2821 2825 rejected = cmdutil.forget(
2822 2826 ui,
2823 2827 repo,
2824 2828 m,
2825 2829 prefix=b"",
2826 2830 uipathfn=uipathfn,
2827 2831 explicitonly=False,
2828 2832 dryrun=dryrun,
2829 2833 interactive=interactive,
2830 2834 )[0]
2831 2835 return rejected and 1 or 0
2832 2836
2833 2837
2834 2838 @command(
2835 2839 b'graft',
2836 2840 [
2837 2841 (b'r', b'rev', [], _(b'revisions to graft'), _(b'REV')),
2838 2842 (
2839 2843 b'',
2840 2844 b'base',
2841 2845 b'',
2842 2846 _(b'base revision when doing the graft merge (ADVANCED)'),
2843 2847 _(b'REV'),
2844 2848 ),
2845 2849 (b'c', b'continue', False, _(b'resume interrupted graft')),
2846 2850 (b'', b'stop', False, _(b'stop interrupted graft')),
2847 2851 (b'', b'abort', False, _(b'abort interrupted graft')),
2848 2852 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
2849 2853 (b'', b'log', None, _(b'append graft info to log message')),
2850 2854 (
2851 2855 b'',
2852 2856 b'no-commit',
2853 2857 None,
2854 2858 _(b"don't commit, just apply the changes in working directory"),
2855 2859 ),
2856 2860 (b'f', b'force', False, _(b'force graft')),
2857 2861 (
2858 2862 b'D',
2859 2863 b'currentdate',
2860 2864 False,
2861 2865 _(b'record the current date as commit date'),
2862 2866 ),
2863 2867 (
2864 2868 b'U',
2865 2869 b'currentuser',
2866 2870 False,
2867 2871 _(b'record the current user as committer'),
2868 2872 ),
2869 2873 ]
2870 2874 + commitopts2
2871 2875 + mergetoolopts
2872 2876 + dryrunopts,
2873 2877 _(b'[OPTION]... [-r REV]... REV...'),
2874 2878 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
2875 2879 )
2876 2880 def graft(ui, repo, *revs, **opts):
2877 2881 '''copy changes from other branches onto the current branch
2878 2882
2879 2883 This command uses Mercurial's merge logic to copy individual
2880 2884 changes from other branches without merging branches in the
2881 2885 history graph. This is sometimes known as 'backporting' or
2882 2886 'cherry-picking'. By default, graft will copy user, date, and
2883 2887 description from the source changesets.
2884 2888
2885 2889 Changesets that are ancestors of the current revision, that have
2886 2890 already been grafted, or that are merges will be skipped.
2887 2891
2888 2892 If --log is specified, log messages will have a comment appended
2889 2893 of the form::
2890 2894
2891 2895 (grafted from CHANGESETHASH)
2892 2896
2893 2897 If --force is specified, revisions will be grafted even if they
2894 2898 are already ancestors of, or have been grafted to, the destination.
2895 2899 This is useful when the revisions have since been backed out.
2896 2900
2897 2901 If a graft merge results in conflicts, the graft process is
2898 2902 interrupted so that the current merge can be manually resolved.
2899 2903 Once all conflicts are addressed, the graft process can be
2900 2904 continued with the -c/--continue option.
2901 2905
2902 2906 The -c/--continue option reapplies all the earlier options.
2903 2907
2904 2908 .. container:: verbose
2905 2909
2906 2910 The --base option exposes more of how graft internally uses merge with a
2907 2911 custom base revision. --base can be used to specify another ancestor than
2908 2912 the first and only parent.
2909 2913
2910 2914 The command::
2911 2915
2912 2916 hg graft -r 345 --base 234
2913 2917
2914 2918 is thus pretty much the same as::
2915 2919
2916 2920 hg diff -r 234 -r 345 | hg import
2917 2921
2918 2922 but using merge to resolve conflicts and track moved files.
2919 2923
2920 2924 The result of a merge can thus be backported as a single commit by
2921 2925 specifying one of the merge parents as base, and thus effectively
2922 2926 grafting the changes from the other side.
2923 2927
2924 2928 It is also possible to collapse multiple changesets and clean up history
2925 2929 by specifying another ancestor as base, much like rebase --collapse
2926 2930 --keep.
2927 2931
2928 2932 The commit message can be tweaked after the fact using commit --amend .
2929 2933
2930 2934 For using non-ancestors as the base to backout changes, see the backout
2931 2935 command and the hidden --parent option.
2932 2936
2933 2937 .. container:: verbose
2934 2938
2935 2939 Examples:
2936 2940
2937 2941 - copy a single change to the stable branch and edit its description::
2938 2942
2939 2943 hg update stable
2940 2944 hg graft --edit 9393
2941 2945
2942 2946 - graft a range of changesets with one exception, updating dates::
2943 2947
2944 2948 hg graft -D "2085::2093 and not 2091"
2945 2949
2946 2950 - continue a graft after resolving conflicts::
2947 2951
2948 2952 hg graft -c
2949 2953
2950 2954 - show the source of a grafted changeset::
2951 2955
2952 2956 hg log --debug -r .
2953 2957
2954 2958 - show revisions sorted by date::
2955 2959
2956 2960 hg log -r "sort(all(), date)"
2957 2961
2958 2962 - backport the result of a merge as a single commit::
2959 2963
2960 2964 hg graft -r 123 --base 123^
2961 2965
2962 2966 - land a feature branch as one changeset::
2963 2967
2964 2968 hg up -cr default
2965 2969 hg graft -r featureX --base "ancestor('featureX', 'default')"
2966 2970
2967 2971 See :hg:`help revisions` for more about specifying revisions.
2968 2972
2969 2973 Returns 0 on successful completion, 1 if there are unresolved files.
2970 2974 '''
2971 2975 with repo.wlock():
2972 2976 return _dograft(ui, repo, *revs, **opts)
2973 2977
2974 2978
2975 2979 def _dograft(ui, repo, *revs, **opts):
2976 2980 opts = pycompat.byteskwargs(opts)
2977 2981 if revs and opts.get(b'rev'):
2978 2982 ui.warn(
2979 2983 _(
2980 2984 b'warning: inconsistent use of --rev might give unexpected '
2981 2985 b'revision ordering!\n'
2982 2986 )
2983 2987 )
2984 2988
2985 2989 revs = list(revs)
2986 2990 revs.extend(opts.get(b'rev'))
2987 2991 # a dict of data to be stored in state file
2988 2992 statedata = {}
2989 2993 # list of new nodes created by ongoing graft
2990 2994 statedata[b'newnodes'] = []
2991 2995
2992 2996 cmdutil.resolvecommitoptions(ui, opts)
2993 2997
2994 2998 editor = cmdutil.getcommiteditor(
2995 2999 editform=b'graft', **pycompat.strkwargs(opts)
2996 3000 )
2997 3001
2998 3002 cmdutil.check_at_most_one_arg(opts, b'abort', b'stop', b'continue')
2999 3003
3000 3004 cont = False
3001 3005 if opts.get(b'no_commit'):
3002 3006 cmdutil.check_incompatible_arguments(
3003 3007 opts,
3004 3008 b'no_commit',
3005 3009 [b'edit', b'currentuser', b'currentdate', b'log'],
3006 3010 )
3007 3011
3008 3012 graftstate = statemod.cmdstate(repo, b'graftstate')
3009 3013
3010 3014 if opts.get(b'stop'):
3011 3015 cmdutil.check_incompatible_arguments(
3012 3016 opts,
3013 3017 b'stop',
3014 3018 [
3015 3019 b'edit',
3016 3020 b'log',
3017 3021 b'user',
3018 3022 b'date',
3019 3023 b'currentdate',
3020 3024 b'currentuser',
3021 3025 b'rev',
3022 3026 ],
3023 3027 )
3024 3028 return _stopgraft(ui, repo, graftstate)
3025 3029 elif opts.get(b'abort'):
3026 3030 cmdutil.check_incompatible_arguments(
3027 3031 opts,
3028 3032 b'abort',
3029 3033 [
3030 3034 b'edit',
3031 3035 b'log',
3032 3036 b'user',
3033 3037 b'date',
3034 3038 b'currentdate',
3035 3039 b'currentuser',
3036 3040 b'rev',
3037 3041 ],
3038 3042 )
3039 3043 return cmdutil.abortgraft(ui, repo, graftstate)
3040 3044 elif opts.get(b'continue'):
3041 3045 cont = True
3042 3046 if revs:
3043 3047 raise error.Abort(_(b"can't specify --continue and revisions"))
3044 3048 # read in unfinished revisions
3045 3049 if graftstate.exists():
3046 3050 statedata = cmdutil.readgraftstate(repo, graftstate)
3047 3051 if statedata.get(b'date'):
3048 3052 opts[b'date'] = statedata[b'date']
3049 3053 if statedata.get(b'user'):
3050 3054 opts[b'user'] = statedata[b'user']
3051 3055 if statedata.get(b'log'):
3052 3056 opts[b'log'] = True
3053 3057 if statedata.get(b'no_commit'):
3054 3058 opts[b'no_commit'] = statedata.get(b'no_commit')
3055 3059 if statedata.get(b'base'):
3056 3060 opts[b'base'] = statedata.get(b'base')
3057 3061 nodes = statedata[b'nodes']
3058 3062 revs = [repo[node].rev() for node in nodes]
3059 3063 else:
3060 3064 cmdutil.wrongtooltocontinue(repo, _(b'graft'))
3061 3065 else:
3062 3066 if not revs:
3063 3067 raise error.Abort(_(b'no revisions specified'))
3064 3068 cmdutil.checkunfinished(repo)
3065 3069 cmdutil.bailifchanged(repo)
3066 3070 revs = scmutil.revrange(repo, revs)
3067 3071
3068 3072 skipped = set()
3069 3073 basectx = None
3070 3074 if opts.get(b'base'):
3071 3075 basectx = scmutil.revsingle(repo, opts[b'base'], None)
3072 3076 if basectx is None:
3073 3077 # check for merges
3074 3078 for rev in repo.revs(b'%ld and merge()', revs):
3075 3079 ui.warn(_(b'skipping ungraftable merge revision %d\n') % rev)
3076 3080 skipped.add(rev)
3077 3081 revs = [r for r in revs if r not in skipped]
3078 3082 if not revs:
3079 3083 return -1
3080 3084 if basectx is not None and len(revs) != 1:
3081 3085 raise error.Abort(_(b'only one revision allowed with --base '))
3082 3086
3083 3087 # Don't check in the --continue case, in effect retaining --force across
3084 3088 # --continues. That's because without --force, any revisions we decided to
3085 3089 # skip would have been filtered out here, so they wouldn't have made their
3086 3090 # way to the graftstate. With --force, any revisions we would have otherwise
3087 3091 # skipped would not have been filtered out, and if they hadn't been applied
3088 3092 # already, they'd have been in the graftstate.
3089 3093 if not (cont or opts.get(b'force')) and basectx is None:
3090 3094 # check for ancestors of dest branch
3091 3095 ancestors = repo.revs(b'%ld & (::.)', revs)
3092 3096 for rev in ancestors:
3093 3097 ui.warn(_(b'skipping ancestor revision %d:%s\n') % (rev, repo[rev]))
3094 3098
3095 3099 revs = [r for r in revs if r not in ancestors]
3096 3100
3097 3101 if not revs:
3098 3102 return -1
3099 3103
3100 3104 # analyze revs for earlier grafts
3101 3105 ids = {}
3102 3106 for ctx in repo.set(b"%ld", revs):
3103 3107 ids[ctx.hex()] = ctx.rev()
3104 3108 n = ctx.extra().get(b'source')
3105 3109 if n:
3106 3110 ids[n] = ctx.rev()
3107 3111
3108 3112 # check ancestors for earlier grafts
3109 3113 ui.debug(b'scanning for duplicate grafts\n')
3110 3114
3111 3115 # The only changesets we can be sure doesn't contain grafts of any
3112 3116 # revs, are the ones that are common ancestors of *all* revs:
3113 3117 for rev in repo.revs(b'only(%d,ancestor(%ld))', repo[b'.'].rev(), revs):
3114 3118 ctx = repo[rev]
3115 3119 n = ctx.extra().get(b'source')
3116 3120 if n in ids:
3117 3121 try:
3118 3122 r = repo[n].rev()
3119 3123 except error.RepoLookupError:
3120 3124 r = None
3121 3125 if r in revs:
3122 3126 ui.warn(
3123 3127 _(
3124 3128 b'skipping revision %d:%s '
3125 3129 b'(already grafted to %d:%s)\n'
3126 3130 )
3127 3131 % (r, repo[r], rev, ctx)
3128 3132 )
3129 3133 revs.remove(r)
3130 3134 elif ids[n] in revs:
3131 3135 if r is None:
3132 3136 ui.warn(
3133 3137 _(
3134 3138 b'skipping already grafted revision %d:%s '
3135 3139 b'(%d:%s also has unknown origin %s)\n'
3136 3140 )
3137 3141 % (ids[n], repo[ids[n]], rev, ctx, n[:12])
3138 3142 )
3139 3143 else:
3140 3144 ui.warn(
3141 3145 _(
3142 3146 b'skipping already grafted revision %d:%s '
3143 3147 b'(%d:%s also has origin %d:%s)\n'
3144 3148 )
3145 3149 % (ids[n], repo[ids[n]], rev, ctx, r, n[:12])
3146 3150 )
3147 3151 revs.remove(ids[n])
3148 3152 elif ctx.hex() in ids:
3149 3153 r = ids[ctx.hex()]
3150 3154 if r in revs:
3151 3155 ui.warn(
3152 3156 _(
3153 3157 b'skipping already grafted revision %d:%s '
3154 3158 b'(was grafted from %d:%s)\n'
3155 3159 )
3156 3160 % (r, repo[r], rev, ctx)
3157 3161 )
3158 3162 revs.remove(r)
3159 3163 if not revs:
3160 3164 return -1
3161 3165
3162 3166 if opts.get(b'no_commit'):
3163 3167 statedata[b'no_commit'] = True
3164 3168 if opts.get(b'base'):
3165 3169 statedata[b'base'] = opts[b'base']
3166 3170 for pos, ctx in enumerate(repo.set(b"%ld", revs)):
3167 3171 desc = b'%d:%s "%s"' % (
3168 3172 ctx.rev(),
3169 3173 ctx,
3170 3174 ctx.description().split(b'\n', 1)[0],
3171 3175 )
3172 3176 names = repo.nodetags(ctx.node()) + repo.nodebookmarks(ctx.node())
3173 3177 if names:
3174 3178 desc += b' (%s)' % b' '.join(names)
3175 3179 ui.status(_(b'grafting %s\n') % desc)
3176 3180 if opts.get(b'dry_run'):
3177 3181 continue
3178 3182
3179 3183 source = ctx.extra().get(b'source')
3180 3184 extra = {}
3181 3185 if source:
3182 3186 extra[b'source'] = source
3183 3187 extra[b'intermediate-source'] = ctx.hex()
3184 3188 else:
3185 3189 extra[b'source'] = ctx.hex()
3186 3190 user = ctx.user()
3187 3191 if opts.get(b'user'):
3188 3192 user = opts[b'user']
3189 3193 statedata[b'user'] = user
3190 3194 date = ctx.date()
3191 3195 if opts.get(b'date'):
3192 3196 date = opts[b'date']
3193 3197 statedata[b'date'] = date
3194 3198 message = ctx.description()
3195 3199 if opts.get(b'log'):
3196 3200 message += b'\n(grafted from %s)' % ctx.hex()
3197 3201 statedata[b'log'] = True
3198 3202
3199 3203 # we don't merge the first commit when continuing
3200 3204 if not cont:
3201 3205 # perform the graft merge with p1(rev) as 'ancestor'
3202 3206 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
3203 3207 base = ctx.p1() if basectx is None else basectx
3204 3208 with ui.configoverride(overrides, b'graft'):
3205 3209 stats = mergemod.graft(repo, ctx, base, [b'local', b'graft'])
3206 3210 # report any conflicts
3207 3211 if stats.unresolvedcount > 0:
3208 3212 # write out state for --continue
3209 3213 nodes = [repo[rev].hex() for rev in revs[pos:]]
3210 3214 statedata[b'nodes'] = nodes
3211 3215 stateversion = 1
3212 3216 graftstate.save(stateversion, statedata)
3213 3217 ui.error(_(b"abort: unresolved conflicts, can't continue\n"))
3214 3218 ui.error(_(b"(use 'hg resolve' and 'hg graft --continue')\n"))
3215 3219 return 1
3216 3220 else:
3217 3221 cont = False
3218 3222
3219 3223 # commit if --no-commit is false
3220 3224 if not opts.get(b'no_commit'):
3221 3225 node = repo.commit(
3222 3226 text=message, user=user, date=date, extra=extra, editor=editor
3223 3227 )
3224 3228 if node is None:
3225 3229 ui.warn(
3226 3230 _(b'note: graft of %d:%s created no changes to commit\n')
3227 3231 % (ctx.rev(), ctx)
3228 3232 )
3229 3233 # checking that newnodes exist because old state files won't have it
3230 3234 elif statedata.get(b'newnodes') is not None:
3231 3235 statedata[b'newnodes'].append(node)
3232 3236
3233 3237 # remove state when we complete successfully
3234 3238 if not opts.get(b'dry_run'):
3235 3239 graftstate.delete()
3236 3240
3237 3241 return 0
3238 3242
3239 3243
3240 3244 def _stopgraft(ui, repo, graftstate):
3241 3245 """stop the interrupted graft"""
3242 3246 if not graftstate.exists():
3243 3247 raise error.Abort(_(b"no interrupted graft found"))
3244 3248 pctx = repo[b'.']
3245 3249 mergemod.clean_update(pctx)
3246 3250 graftstate.delete()
3247 3251 ui.status(_(b"stopped the interrupted graft\n"))
3248 3252 ui.status(_(b"working directory is now at %s\n") % pctx.hex()[:12])
3249 3253 return 0
3250 3254
3251 3255
3252 3256 statemod.addunfinished(
3253 3257 b'graft',
3254 3258 fname=b'graftstate',
3255 3259 clearable=True,
3256 3260 stopflag=True,
3257 3261 continueflag=True,
3258 3262 abortfunc=cmdutil.hgabortgraft,
3259 3263 cmdhint=_(b"use 'hg graft --continue' or 'hg graft --stop' to stop"),
3260 3264 )
3261 3265
3262 3266
3263 3267 @command(
3264 3268 b'grep',
3265 3269 [
3266 3270 (b'0', b'print0', None, _(b'end fields with NUL')),
3267 3271 (b'', b'all', None, _(b'an alias to --diff (DEPRECATED)')),
3268 3272 (
3269 3273 b'',
3270 3274 b'diff',
3271 3275 None,
3272 3276 _(
3273 3277 b'search revision differences for when the pattern was added '
3274 3278 b'or removed'
3275 3279 ),
3276 3280 ),
3277 3281 (b'a', b'text', None, _(b'treat all files as text')),
3278 3282 (
3279 3283 b'f',
3280 3284 b'follow',
3281 3285 None,
3282 3286 _(
3283 3287 b'follow changeset history,'
3284 3288 b' or file history across copies and renames'
3285 3289 ),
3286 3290 ),
3287 3291 (b'i', b'ignore-case', None, _(b'ignore case when matching')),
3288 3292 (
3289 3293 b'l',
3290 3294 b'files-with-matches',
3291 3295 None,
3292 3296 _(b'print only filenames and revisions that match'),
3293 3297 ),
3294 3298 (b'n', b'line-number', None, _(b'print matching line numbers')),
3295 3299 (
3296 3300 b'r',
3297 3301 b'rev',
3298 3302 [],
3299 3303 _(b'search files changed within revision range'),
3300 3304 _(b'REV'),
3301 3305 ),
3302 3306 (
3303 3307 b'',
3304 3308 b'all-files',
3305 3309 None,
3306 3310 _(
3307 3311 b'include all files in the changeset while grepping (DEPRECATED)'
3308 3312 ),
3309 3313 ),
3310 3314 (b'u', b'user', None, _(b'list the author (long with -v)')),
3311 3315 (b'd', b'date', None, _(b'list the date (short with -q)')),
3312 3316 ]
3313 3317 + formatteropts
3314 3318 + walkopts,
3315 3319 _(b'[--diff] [OPTION]... PATTERN [FILE]...'),
3316 3320 helpcategory=command.CATEGORY_FILE_CONTENTS,
3317 3321 inferrepo=True,
3318 3322 intents={INTENT_READONLY},
3319 3323 )
3320 3324 def grep(ui, repo, pattern, *pats, **opts):
3321 3325 """search for a pattern in specified files
3322 3326
3323 3327 Search the working directory or revision history for a regular
3324 3328 expression in the specified files for the entire repository.
3325 3329
3326 3330 By default, grep searches the repository files in the working
3327 3331 directory and prints the files where it finds a match. To specify
3328 3332 historical revisions instead of the working directory, use the
3329 3333 --rev flag.
3330 3334
3331 3335 To search instead historical revision differences that contains a
3332 3336 change in match status ("-" for a match that becomes a non-match,
3333 3337 or "+" for a non-match that becomes a match), use the --diff flag.
3334 3338
3335 3339 PATTERN can be any Python (roughly Perl-compatible) regular
3336 3340 expression.
3337 3341
3338 3342 If no FILEs are specified and the --rev flag isn't supplied, all
3339 3343 files in the working directory are searched. When using the --rev
3340 3344 flag and specifying FILEs, use the --follow argument to also
3341 3345 follow the specified FILEs across renames and copies.
3342 3346
3343 3347 .. container:: verbose
3344 3348
3345 3349 Template:
3346 3350
3347 3351 The following keywords are supported in addition to the common template
3348 3352 keywords and functions. See also :hg:`help templates`.
3349 3353
3350 3354 :change: String. Character denoting insertion ``+`` or removal ``-``.
3351 3355 Available if ``--diff`` is specified.
3352 3356 :lineno: Integer. Line number of the match.
3353 3357 :path: String. Repository-absolute path of the file.
3354 3358 :texts: List of text chunks.
3355 3359
3356 3360 And each entry of ``{texts}`` provides the following sub-keywords.
3357 3361
3358 3362 :matched: Boolean. True if the chunk matches the specified pattern.
3359 3363 :text: String. Chunk content.
3360 3364
3361 3365 See :hg:`help templates.operators` for the list expansion syntax.
3362 3366
3363 3367 Returns 0 if a match is found, 1 otherwise.
3364 3368
3365 3369 """
3366 3370 cmdutil.check_incompatible_arguments(opts, 'all_files', ['all', 'diff'])
3367 3371 opts = pycompat.byteskwargs(opts)
3368 3372 diff = opts.get(b'all') or opts.get(b'diff')
3369 3373 follow = opts.get(b'follow')
3370 3374 if opts.get(b'all_files') is None and not diff:
3371 3375 opts[b'all_files'] = True
3372 3376 plaingrep = (
3373 3377 opts.get(b'all_files')
3374 3378 and not opts.get(b'rev')
3375 3379 and not opts.get(b'follow')
3376 3380 )
3377 3381 all_files = opts.get(b'all_files')
3378 3382 if plaingrep:
3379 3383 opts[b'rev'] = [b'wdir()']
3380 3384
3381 3385 reflags = re.M
3382 3386 if opts.get(b'ignore_case'):
3383 3387 reflags |= re.I
3384 3388 try:
3385 3389 regexp = util.re.compile(pattern, reflags)
3386 3390 except re.error as inst:
3387 3391 ui.warn(
3388 3392 _(b"grep: invalid match pattern: %s\n") % pycompat.bytestr(inst)
3389 3393 )
3390 3394 return 1
3391 3395 sep, eol = b':', b'\n'
3392 3396 if opts.get(b'print0'):
3393 3397 sep = eol = b'\0'
3394 3398
3395 3399 searcher = grepmod.grepsearcher(
3396 3400 ui, repo, regexp, all_files=all_files, diff=diff, follow=follow
3397 3401 )
3398 3402
3399 3403 getfile = searcher._getfile
3400 3404
3401 3405 uipathfn = scmutil.getuipathfn(repo)
3402 3406
3403 3407 def display(fm, fn, ctx, pstates, states):
3404 3408 rev = scmutil.intrev(ctx)
3405 3409 if fm.isplain():
3406 3410 formatuser = ui.shortuser
3407 3411 else:
3408 3412 formatuser = pycompat.bytestr
3409 3413 if ui.quiet:
3410 3414 datefmt = b'%Y-%m-%d'
3411 3415 else:
3412 3416 datefmt = b'%a %b %d %H:%M:%S %Y %1%2'
3413 3417 found = False
3414 3418
3415 3419 @util.cachefunc
3416 3420 def binary():
3417 3421 flog = getfile(fn)
3418 3422 try:
3419 3423 return stringutil.binary(flog.read(ctx.filenode(fn)))
3420 3424 except error.WdirUnsupported:
3421 3425 return ctx[fn].isbinary()
3422 3426
3423 3427 fieldnamemap = {b'linenumber': b'lineno'}
3424 3428 if diff:
3425 3429 iter = grepmod.difflinestates(pstates, states)
3426 3430 else:
3427 3431 iter = [(b'', l) for l in states]
3428 3432 for change, l in iter:
3429 3433 fm.startitem()
3430 3434 fm.context(ctx=ctx)
3431 3435 fm.data(node=fm.hexfunc(scmutil.binnode(ctx)), path=fn)
3432 3436 fm.plain(uipathfn(fn), label=b'grep.filename')
3433 3437
3434 3438 cols = [
3435 3439 (b'rev', b'%d', rev, not plaingrep, b''),
3436 3440 (
3437 3441 b'linenumber',
3438 3442 b'%d',
3439 3443 l.linenum,
3440 3444 opts.get(b'line_number'),
3441 3445 b'',
3442 3446 ),
3443 3447 ]
3444 3448 if diff:
3445 3449 cols.append(
3446 3450 (
3447 3451 b'change',
3448 3452 b'%s',
3449 3453 change,
3450 3454 True,
3451 3455 b'grep.inserted '
3452 3456 if change == b'+'
3453 3457 else b'grep.deleted ',
3454 3458 )
3455 3459 )
3456 3460 cols.extend(
3457 3461 [
3458 3462 (
3459 3463 b'user',
3460 3464 b'%s',
3461 3465 formatuser(ctx.user()),
3462 3466 opts.get(b'user'),
3463 3467 b'',
3464 3468 ),
3465 3469 (
3466 3470 b'date',
3467 3471 b'%s',
3468 3472 fm.formatdate(ctx.date(), datefmt),
3469 3473 opts.get(b'date'),
3470 3474 b'',
3471 3475 ),
3472 3476 ]
3473 3477 )
3474 3478 for name, fmt, data, cond, extra_label in cols:
3475 3479 if cond:
3476 3480 fm.plain(sep, label=b'grep.sep')
3477 3481 field = fieldnamemap.get(name, name)
3478 3482 label = extra_label + (b'grep.%s' % name)
3479 3483 fm.condwrite(cond, field, fmt, data, label=label)
3480 3484 if not opts.get(b'files_with_matches'):
3481 3485 fm.plain(sep, label=b'grep.sep')
3482 3486 if not opts.get(b'text') and binary():
3483 3487 fm.plain(_(b" Binary file matches"))
3484 3488 else:
3485 3489 displaymatches(fm.nested(b'texts', tmpl=b'{text}'), l)
3486 3490 fm.plain(eol)
3487 3491 found = True
3488 3492 if opts.get(b'files_with_matches'):
3489 3493 break
3490 3494 return found
3491 3495
3492 3496 def displaymatches(fm, l):
3493 3497 p = 0
3494 3498 for s, e in l.findpos(regexp):
3495 3499 if p < s:
3496 3500 fm.startitem()
3497 3501 fm.write(b'text', b'%s', l.line[p:s])
3498 3502 fm.data(matched=False)
3499 3503 fm.startitem()
3500 3504 fm.write(b'text', b'%s', l.line[s:e], label=b'grep.match')
3501 3505 fm.data(matched=True)
3502 3506 p = e
3503 3507 if p < len(l.line):
3504 3508 fm.startitem()
3505 3509 fm.write(b'text', b'%s', l.line[p:])
3506 3510 fm.data(matched=False)
3507 3511 fm.end()
3508 3512
3509 3513 found = False
3510 3514
3511 3515 wopts = logcmdutil.walkopts(
3512 3516 pats=pats,
3513 3517 opts=opts,
3514 3518 revspec=opts[b'rev'],
3515 3519 include_pats=opts[b'include'],
3516 3520 exclude_pats=opts[b'exclude'],
3517 3521 follow=follow,
3518 3522 force_changelog_traversal=all_files,
3519 3523 filter_revisions_by_pats=not all_files,
3520 3524 )
3521 3525 revs, makefilematcher = logcmdutil.makewalker(repo, wopts)
3522 3526
3523 3527 ui.pager(b'grep')
3524 3528 fm = ui.formatter(b'grep', opts)
3525 3529 for fn, ctx, pstates, states in searcher.searchfiles(revs, makefilematcher):
3526 3530 r = display(fm, fn, ctx, pstates, states)
3527 3531 found = found or r
3528 3532 if r and not diff and not all_files:
3529 3533 searcher.skipfile(fn, ctx.rev())
3530 3534 fm.end()
3531 3535
3532 3536 return not found
3533 3537
3534 3538
3535 3539 @command(
3536 3540 b'heads',
3537 3541 [
3538 3542 (
3539 3543 b'r',
3540 3544 b'rev',
3541 3545 b'',
3542 3546 _(b'show only heads which are descendants of STARTREV'),
3543 3547 _(b'STARTREV'),
3544 3548 ),
3545 3549 (b't', b'topo', False, _(b'show topological heads only')),
3546 3550 (
3547 3551 b'a',
3548 3552 b'active',
3549 3553 False,
3550 3554 _(b'show active branchheads only (DEPRECATED)'),
3551 3555 ),
3552 3556 (b'c', b'closed', False, _(b'show normal and closed branch heads')),
3553 3557 ]
3554 3558 + templateopts,
3555 3559 _(b'[-ct] [-r STARTREV] [REV]...'),
3556 3560 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
3557 3561 intents={INTENT_READONLY},
3558 3562 )
3559 3563 def heads(ui, repo, *branchrevs, **opts):
3560 3564 """show branch heads
3561 3565
3562 3566 With no arguments, show all open branch heads in the repository.
3563 3567 Branch heads are changesets that have no descendants on the
3564 3568 same branch. They are where development generally takes place and
3565 3569 are the usual targets for update and merge operations.
3566 3570
3567 3571 If one or more REVs are given, only open branch heads on the
3568 3572 branches associated with the specified changesets are shown. This
3569 3573 means that you can use :hg:`heads .` to see the heads on the
3570 3574 currently checked-out branch.
3571 3575
3572 3576 If -c/--closed is specified, also show branch heads marked closed
3573 3577 (see :hg:`commit --close-branch`).
3574 3578
3575 3579 If STARTREV is specified, only those heads that are descendants of
3576 3580 STARTREV will be displayed.
3577 3581
3578 3582 If -t/--topo is specified, named branch mechanics will be ignored and only
3579 3583 topological heads (changesets with no children) will be shown.
3580 3584
3581 3585 Returns 0 if matching heads are found, 1 if not.
3582 3586 """
3583 3587
3584 3588 opts = pycompat.byteskwargs(opts)
3585 3589 start = None
3586 3590 rev = opts.get(b'rev')
3587 3591 if rev:
3588 3592 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
3589 3593 start = scmutil.revsingle(repo, rev, None).node()
3590 3594
3591 3595 if opts.get(b'topo'):
3592 3596 heads = [repo[h] for h in repo.heads(start)]
3593 3597 else:
3594 3598 heads = []
3595 3599 for branch in repo.branchmap():
3596 3600 heads += repo.branchheads(branch, start, opts.get(b'closed'))
3597 3601 heads = [repo[h] for h in heads]
3598 3602
3599 3603 if branchrevs:
3600 3604 branches = {
3601 3605 repo[r].branch() for r in scmutil.revrange(repo, branchrevs)
3602 3606 }
3603 3607 heads = [h for h in heads if h.branch() in branches]
3604 3608
3605 3609 if opts.get(b'active') and branchrevs:
3606 3610 dagheads = repo.heads(start)
3607 3611 heads = [h for h in heads if h.node() in dagheads]
3608 3612
3609 3613 if branchrevs:
3610 3614 haveheads = {h.branch() for h in heads}
3611 3615 if branches - haveheads:
3612 3616 headless = b', '.join(b for b in branches - haveheads)
3613 3617 msg = _(b'no open branch heads found on branches %s')
3614 3618 if opts.get(b'rev'):
3615 3619 msg += _(b' (started at %s)') % opts[b'rev']
3616 3620 ui.warn((msg + b'\n') % headless)
3617 3621
3618 3622 if not heads:
3619 3623 return 1
3620 3624
3621 3625 ui.pager(b'heads')
3622 3626 heads = sorted(heads, key=lambda x: -(x.rev()))
3623 3627 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
3624 3628 for ctx in heads:
3625 3629 displayer.show(ctx)
3626 3630 displayer.close()
3627 3631
3628 3632
3629 3633 @command(
3630 3634 b'help',
3631 3635 [
3632 3636 (b'e', b'extension', None, _(b'show only help for extensions')),
3633 3637 (b'c', b'command', None, _(b'show only help for commands')),
3634 3638 (b'k', b'keyword', None, _(b'show topics matching keyword')),
3635 3639 (
3636 3640 b's',
3637 3641 b'system',
3638 3642 [],
3639 3643 _(b'show help for specific platform(s)'),
3640 3644 _(b'PLATFORM'),
3641 3645 ),
3642 3646 ],
3643 3647 _(b'[-eck] [-s PLATFORM] [TOPIC]'),
3644 3648 helpcategory=command.CATEGORY_HELP,
3645 3649 norepo=True,
3646 3650 intents={INTENT_READONLY},
3647 3651 )
3648 3652 def help_(ui, name=None, **opts):
3649 3653 """show help for a given topic or a help overview
3650 3654
3651 3655 With no arguments, print a list of commands with short help messages.
3652 3656
3653 3657 Given a topic, extension, or command name, print help for that
3654 3658 topic.
3655 3659
3656 3660 Returns 0 if successful.
3657 3661 """
3658 3662
3659 3663 keep = opts.get('system') or []
3660 3664 if len(keep) == 0:
3661 3665 if pycompat.sysplatform.startswith(b'win'):
3662 3666 keep.append(b'windows')
3663 3667 elif pycompat.sysplatform == b'OpenVMS':
3664 3668 keep.append(b'vms')
3665 3669 elif pycompat.sysplatform == b'plan9':
3666 3670 keep.append(b'plan9')
3667 3671 else:
3668 3672 keep.append(b'unix')
3669 3673 keep.append(pycompat.sysplatform.lower())
3670 3674 if ui.verbose:
3671 3675 keep.append(b'verbose')
3672 3676
3673 3677 commands = sys.modules[__name__]
3674 3678 formatted = help.formattedhelp(ui, commands, name, keep=keep, **opts)
3675 3679 ui.pager(b'help')
3676 3680 ui.write(formatted)
3677 3681
3678 3682
3679 3683 @command(
3680 3684 b'identify|id',
3681 3685 [
3682 3686 (b'r', b'rev', b'', _(b'identify the specified revision'), _(b'REV')),
3683 3687 (b'n', b'num', None, _(b'show local revision number')),
3684 3688 (b'i', b'id', None, _(b'show global revision id')),
3685 3689 (b'b', b'branch', None, _(b'show branch')),
3686 3690 (b't', b'tags', None, _(b'show tags')),
3687 3691 (b'B', b'bookmarks', None, _(b'show bookmarks')),
3688 3692 ]
3689 3693 + remoteopts
3690 3694 + formatteropts,
3691 3695 _(b'[-nibtB] [-r REV] [SOURCE]'),
3692 3696 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
3693 3697 optionalrepo=True,
3694 3698 intents={INTENT_READONLY},
3695 3699 )
3696 3700 def identify(
3697 3701 ui,
3698 3702 repo,
3699 3703 source=None,
3700 3704 rev=None,
3701 3705 num=None,
3702 3706 id=None,
3703 3707 branch=None,
3704 3708 tags=None,
3705 3709 bookmarks=None,
3706 3710 **opts
3707 3711 ):
3708 3712 """identify the working directory or specified revision
3709 3713
3710 3714 Print a summary identifying the repository state at REV using one or
3711 3715 two parent hash identifiers, followed by a "+" if the working
3712 3716 directory has uncommitted changes, the branch name (if not default),
3713 3717 a list of tags, and a list of bookmarks.
3714 3718
3715 3719 When REV is not given, print a summary of the current state of the
3716 3720 repository including the working directory. Specify -r. to get information
3717 3721 of the working directory parent without scanning uncommitted changes.
3718 3722
3719 3723 Specifying a path to a repository root or Mercurial bundle will
3720 3724 cause lookup to operate on that repository/bundle.
3721 3725
3722 3726 .. container:: verbose
3723 3727
3724 3728 Template:
3725 3729
3726 3730 The following keywords are supported in addition to the common template
3727 3731 keywords and functions. See also :hg:`help templates`.
3728 3732
3729 3733 :dirty: String. Character ``+`` denoting if the working directory has
3730 3734 uncommitted changes.
3731 3735 :id: String. One or two nodes, optionally followed by ``+``.
3732 3736 :parents: List of strings. Parent nodes of the changeset.
3733 3737
3734 3738 Examples:
3735 3739
3736 3740 - generate a build identifier for the working directory::
3737 3741
3738 3742 hg id --id > build-id.dat
3739 3743
3740 3744 - find the revision corresponding to a tag::
3741 3745
3742 3746 hg id -n -r 1.3
3743 3747
3744 3748 - check the most recent revision of a remote repository::
3745 3749
3746 3750 hg id -r tip https://www.mercurial-scm.org/repo/hg/
3747 3751
3748 3752 See :hg:`log` for generating more information about specific revisions,
3749 3753 including full hash identifiers.
3750 3754
3751 3755 Returns 0 if successful.
3752 3756 """
3753 3757
3754 3758 opts = pycompat.byteskwargs(opts)
3755 3759 if not repo and not source:
3756 3760 raise error.Abort(
3757 3761 _(b"there is no Mercurial repository here (.hg not found)")
3758 3762 )
3759 3763
3760 3764 default = not (num or id or branch or tags or bookmarks)
3761 3765 output = []
3762 3766 revs = []
3763 3767
3764 3768 if source:
3765 3769 source, branches = hg.parseurl(ui.expandpath(source))
3766 3770 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
3767 3771 repo = peer.local()
3768 3772 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
3769 3773
3770 3774 fm = ui.formatter(b'identify', opts)
3771 3775 fm.startitem()
3772 3776
3773 3777 if not repo:
3774 3778 if num or branch or tags:
3775 3779 raise error.Abort(
3776 3780 _(b"can't query remote revision number, branch, or tags")
3777 3781 )
3778 3782 if not rev and revs:
3779 3783 rev = revs[0]
3780 3784 if not rev:
3781 3785 rev = b"tip"
3782 3786
3783 3787 remoterev = peer.lookup(rev)
3784 3788 hexrev = fm.hexfunc(remoterev)
3785 3789 if default or id:
3786 3790 output = [hexrev]
3787 3791 fm.data(id=hexrev)
3788 3792
3789 3793 @util.cachefunc
3790 3794 def getbms():
3791 3795 bms = []
3792 3796
3793 3797 if b'bookmarks' in peer.listkeys(b'namespaces'):
3794 3798 hexremoterev = hex(remoterev)
3795 3799 bms = [
3796 3800 bm
3797 3801 for bm, bmr in pycompat.iteritems(
3798 3802 peer.listkeys(b'bookmarks')
3799 3803 )
3800 3804 if bmr == hexremoterev
3801 3805 ]
3802 3806
3803 3807 return sorted(bms)
3804 3808
3805 3809 if fm.isplain():
3806 3810 if bookmarks:
3807 3811 output.extend(getbms())
3808 3812 elif default and not ui.quiet:
3809 3813 # multiple bookmarks for a single parent separated by '/'
3810 3814 bm = b'/'.join(getbms())
3811 3815 if bm:
3812 3816 output.append(bm)
3813 3817 else:
3814 3818 fm.data(node=hex(remoterev))
3815 3819 if bookmarks or b'bookmarks' in fm.datahint():
3816 3820 fm.data(bookmarks=fm.formatlist(getbms(), name=b'bookmark'))
3817 3821 else:
3818 3822 if rev:
3819 3823 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
3820 3824 ctx = scmutil.revsingle(repo, rev, None)
3821 3825
3822 3826 if ctx.rev() is None:
3823 3827 ctx = repo[None]
3824 3828 parents = ctx.parents()
3825 3829 taglist = []
3826 3830 for p in parents:
3827 3831 taglist.extend(p.tags())
3828 3832
3829 3833 dirty = b""
3830 3834 if ctx.dirty(missing=True, merge=False, branch=False):
3831 3835 dirty = b'+'
3832 3836 fm.data(dirty=dirty)
3833 3837
3834 3838 hexoutput = [fm.hexfunc(p.node()) for p in parents]
3835 3839 if default or id:
3836 3840 output = [b"%s%s" % (b'+'.join(hexoutput), dirty)]
3837 3841 fm.data(id=b"%s%s" % (b'+'.join(hexoutput), dirty))
3838 3842
3839 3843 if num:
3840 3844 numoutput = [b"%d" % p.rev() for p in parents]
3841 3845 output.append(b"%s%s" % (b'+'.join(numoutput), dirty))
3842 3846
3843 3847 fm.data(
3844 3848 parents=fm.formatlist(
3845 3849 [fm.hexfunc(p.node()) for p in parents], name=b'node'
3846 3850 )
3847 3851 )
3848 3852 else:
3849 3853 hexoutput = fm.hexfunc(ctx.node())
3850 3854 if default or id:
3851 3855 output = [hexoutput]
3852 3856 fm.data(id=hexoutput)
3853 3857
3854 3858 if num:
3855 3859 output.append(pycompat.bytestr(ctx.rev()))
3856 3860 taglist = ctx.tags()
3857 3861
3858 3862 if default and not ui.quiet:
3859 3863 b = ctx.branch()
3860 3864 if b != b'default':
3861 3865 output.append(b"(%s)" % b)
3862 3866
3863 3867 # multiple tags for a single parent separated by '/'
3864 3868 t = b'/'.join(taglist)
3865 3869 if t:
3866 3870 output.append(t)
3867 3871
3868 3872 # multiple bookmarks for a single parent separated by '/'
3869 3873 bm = b'/'.join(ctx.bookmarks())
3870 3874 if bm:
3871 3875 output.append(bm)
3872 3876 else:
3873 3877 if branch:
3874 3878 output.append(ctx.branch())
3875 3879
3876 3880 if tags:
3877 3881 output.extend(taglist)
3878 3882
3879 3883 if bookmarks:
3880 3884 output.extend(ctx.bookmarks())
3881 3885
3882 3886 fm.data(node=ctx.hex())
3883 3887 fm.data(branch=ctx.branch())
3884 3888 fm.data(tags=fm.formatlist(taglist, name=b'tag', sep=b':'))
3885 3889 fm.data(bookmarks=fm.formatlist(ctx.bookmarks(), name=b'bookmark'))
3886 3890 fm.context(ctx=ctx)
3887 3891
3888 3892 fm.plain(b"%s\n" % b' '.join(output))
3889 3893 fm.end()
3890 3894
3891 3895
3892 3896 @command(
3893 3897 b'import|patch',
3894 3898 [
3895 3899 (
3896 3900 b'p',
3897 3901 b'strip',
3898 3902 1,
3899 3903 _(
3900 3904 b'directory strip option for patch. This has the same '
3901 3905 b'meaning as the corresponding patch option'
3902 3906 ),
3903 3907 _(b'NUM'),
3904 3908 ),
3905 3909 (b'b', b'base', b'', _(b'base path (DEPRECATED)'), _(b'PATH')),
3906 3910 (b'', b'secret', None, _(b'use the secret phase for committing')),
3907 3911 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
3908 3912 (
3909 3913 b'f',
3910 3914 b'force',
3911 3915 None,
3912 3916 _(b'skip check for outstanding uncommitted changes (DEPRECATED)'),
3913 3917 ),
3914 3918 (
3915 3919 b'',
3916 3920 b'no-commit',
3917 3921 None,
3918 3922 _(b"don't commit, just update the working directory"),
3919 3923 ),
3920 3924 (
3921 3925 b'',
3922 3926 b'bypass',
3923 3927 None,
3924 3928 _(b"apply patch without touching the working directory"),
3925 3929 ),
3926 3930 (b'', b'partial', None, _(b'commit even if some hunks fail')),
3927 3931 (b'', b'exact', None, _(b'abort if patch would apply lossily')),
3928 3932 (b'', b'prefix', b'', _(b'apply patch to subdirectory'), _(b'DIR')),
3929 3933 (
3930 3934 b'',
3931 3935 b'import-branch',
3932 3936 None,
3933 3937 _(b'use any branch information in patch (implied by --exact)'),
3934 3938 ),
3935 3939 ]
3936 3940 + commitopts
3937 3941 + commitopts2
3938 3942 + similarityopts,
3939 3943 _(b'[OPTION]... PATCH...'),
3940 3944 helpcategory=command.CATEGORY_IMPORT_EXPORT,
3941 3945 )
3942 3946 def import_(ui, repo, patch1=None, *patches, **opts):
3943 3947 """import an ordered set of patches
3944 3948
3945 3949 Import a list of patches and commit them individually (unless
3946 3950 --no-commit is specified).
3947 3951
3948 3952 To read a patch from standard input (stdin), use "-" as the patch
3949 3953 name. If a URL is specified, the patch will be downloaded from
3950 3954 there.
3951 3955
3952 3956 Import first applies changes to the working directory (unless
3953 3957 --bypass is specified), import will abort if there are outstanding
3954 3958 changes.
3955 3959
3956 3960 Use --bypass to apply and commit patches directly to the
3957 3961 repository, without affecting the working directory. Without
3958 3962 --exact, patches will be applied on top of the working directory
3959 3963 parent revision.
3960 3964
3961 3965 You can import a patch straight from a mail message. Even patches
3962 3966 as attachments work (to use the body part, it must have type
3963 3967 text/plain or text/x-patch). From and Subject headers of email
3964 3968 message are used as default committer and commit message. All
3965 3969 text/plain body parts before first diff are added to the commit
3966 3970 message.
3967 3971
3968 3972 If the imported patch was generated by :hg:`export`, user and
3969 3973 description from patch override values from message headers and
3970 3974 body. Values given on command line with -m/--message and -u/--user
3971 3975 override these.
3972 3976
3973 3977 If --exact is specified, import will set the working directory to
3974 3978 the parent of each patch before applying it, and will abort if the
3975 3979 resulting changeset has a different ID than the one recorded in
3976 3980 the patch. This will guard against various ways that portable
3977 3981 patch formats and mail systems might fail to transfer Mercurial
3978 3982 data or metadata. See :hg:`bundle` for lossless transmission.
3979 3983
3980 3984 Use --partial to ensure a changeset will be created from the patch
3981 3985 even if some hunks fail to apply. Hunks that fail to apply will be
3982 3986 written to a <target-file>.rej file. Conflicts can then be resolved
3983 3987 by hand before :hg:`commit --amend` is run to update the created
3984 3988 changeset. This flag exists to let people import patches that
3985 3989 partially apply without losing the associated metadata (author,
3986 3990 date, description, ...).
3987 3991
3988 3992 .. note::
3989 3993
3990 3994 When no hunks apply cleanly, :hg:`import --partial` will create
3991 3995 an empty changeset, importing only the patch metadata.
3992 3996
3993 3997 With -s/--similarity, hg will attempt to discover renames and
3994 3998 copies in the patch in the same way as :hg:`addremove`.
3995 3999
3996 4000 It is possible to use external patch programs to perform the patch
3997 4001 by setting the ``ui.patch`` configuration option. For the default
3998 4002 internal tool, the fuzz can also be configured via ``patch.fuzz``.
3999 4003 See :hg:`help config` for more information about configuration
4000 4004 files and how to use these options.
4001 4005
4002 4006 See :hg:`help dates` for a list of formats valid for -d/--date.
4003 4007
4004 4008 .. container:: verbose
4005 4009
4006 4010 Examples:
4007 4011
4008 4012 - import a traditional patch from a website and detect renames::
4009 4013
4010 4014 hg import -s 80 http://example.com/bugfix.patch
4011 4015
4012 4016 - import a changeset from an hgweb server::
4013 4017
4014 4018 hg import https://www.mercurial-scm.org/repo/hg/rev/5ca8c111e9aa
4015 4019
4016 4020 - import all the patches in an Unix-style mbox::
4017 4021
4018 4022 hg import incoming-patches.mbox
4019 4023
4020 4024 - import patches from stdin::
4021 4025
4022 4026 hg import -
4023 4027
4024 4028 - attempt to exactly restore an exported changeset (not always
4025 4029 possible)::
4026 4030
4027 4031 hg import --exact proposed-fix.patch
4028 4032
4029 4033 - use an external tool to apply a patch which is too fuzzy for
4030 4034 the default internal tool.
4031 4035
4032 4036 hg import --config ui.patch="patch --merge" fuzzy.patch
4033 4037
4034 4038 - change the default fuzzing from 2 to a less strict 7
4035 4039
4036 4040 hg import --config ui.fuzz=7 fuzz.patch
4037 4041
4038 4042 Returns 0 on success, 1 on partial success (see --partial).
4039 4043 """
4040 4044
4041 4045 cmdutil.check_incompatible_arguments(
4042 4046 opts, 'no_commit', ['bypass', 'secret']
4043 4047 )
4044 4048 cmdutil.check_incompatible_arguments(opts, 'exact', ['edit', 'prefix'])
4045 4049 opts = pycompat.byteskwargs(opts)
4046 4050 if not patch1:
4047 4051 raise error.Abort(_(b'need at least one patch to import'))
4048 4052
4049 4053 patches = (patch1,) + patches
4050 4054
4051 4055 date = opts.get(b'date')
4052 4056 if date:
4053 4057 opts[b'date'] = dateutil.parsedate(date)
4054 4058
4055 4059 exact = opts.get(b'exact')
4056 4060 update = not opts.get(b'bypass')
4057 4061 try:
4058 4062 sim = float(opts.get(b'similarity') or 0)
4059 4063 except ValueError:
4060 4064 raise error.Abort(_(b'similarity must be a number'))
4061 4065 if sim < 0 or sim > 100:
4062 4066 raise error.Abort(_(b'similarity must be between 0 and 100'))
4063 4067 if sim and not update:
4064 4068 raise error.Abort(_(b'cannot use --similarity with --bypass'))
4065 4069
4066 4070 base = opts[b"base"]
4067 4071 msgs = []
4068 4072 ret = 0
4069 4073
4070 4074 with repo.wlock():
4071 4075 if update:
4072 4076 cmdutil.checkunfinished(repo)
4073 4077 if exact or not opts.get(b'force'):
4074 4078 cmdutil.bailifchanged(repo)
4075 4079
4076 4080 if not opts.get(b'no_commit'):
4077 4081 lock = repo.lock
4078 4082 tr = lambda: repo.transaction(b'import')
4079 4083 dsguard = util.nullcontextmanager
4080 4084 else:
4081 4085 lock = util.nullcontextmanager
4082 4086 tr = util.nullcontextmanager
4083 4087 dsguard = lambda: dirstateguard.dirstateguard(repo, b'import')
4084 4088 with lock(), tr(), dsguard():
4085 4089 parents = repo[None].parents()
4086 4090 for patchurl in patches:
4087 4091 if patchurl == b'-':
4088 4092 ui.status(_(b'applying patch from stdin\n'))
4089 4093 patchfile = ui.fin
4090 4094 patchurl = b'stdin' # for error message
4091 4095 else:
4092 4096 patchurl = os.path.join(base, patchurl)
4093 4097 ui.status(_(b'applying %s\n') % patchurl)
4094 4098 patchfile = hg.openpath(ui, patchurl, sendaccept=False)
4095 4099
4096 4100 haspatch = False
4097 4101 for hunk in patch.split(patchfile):
4098 4102 with patch.extract(ui, hunk) as patchdata:
4099 4103 msg, node, rej = cmdutil.tryimportone(
4100 4104 ui, repo, patchdata, parents, opts, msgs, hg.clean
4101 4105 )
4102 4106 if msg:
4103 4107 haspatch = True
4104 4108 ui.note(msg + b'\n')
4105 4109 if update or exact:
4106 4110 parents = repo[None].parents()
4107 4111 else:
4108 4112 parents = [repo[node]]
4109 4113 if rej:
4110 4114 ui.write_err(_(b"patch applied partially\n"))
4111 4115 ui.write_err(
4112 4116 _(
4113 4117 b"(fix the .rej files and run "
4114 4118 b"`hg commit --amend`)\n"
4115 4119 )
4116 4120 )
4117 4121 ret = 1
4118 4122 break
4119 4123
4120 4124 if not haspatch:
4121 4125 raise error.Abort(_(b'%s: no diffs found') % patchurl)
4122 4126
4123 4127 if msgs:
4124 4128 repo.savecommitmessage(b'\n* * *\n'.join(msgs))
4125 4129 return ret
4126 4130
4127 4131
4128 4132 @command(
4129 4133 b'incoming|in',
4130 4134 [
4131 4135 (
4132 4136 b'f',
4133 4137 b'force',
4134 4138 None,
4135 4139 _(b'run even if remote repository is unrelated'),
4136 4140 ),
4137 4141 (b'n', b'newest-first', None, _(b'show newest record first')),
4138 4142 (b'', b'bundle', b'', _(b'file to store the bundles into'), _(b'FILE')),
4139 4143 (
4140 4144 b'r',
4141 4145 b'rev',
4142 4146 [],
4143 4147 _(b'a remote changeset intended to be added'),
4144 4148 _(b'REV'),
4145 4149 ),
4146 4150 (b'B', b'bookmarks', False, _(b"compare bookmarks")),
4147 4151 (
4148 4152 b'b',
4149 4153 b'branch',
4150 4154 [],
4151 4155 _(b'a specific branch you would like to pull'),
4152 4156 _(b'BRANCH'),
4153 4157 ),
4154 4158 ]
4155 4159 + logopts
4156 4160 + remoteopts
4157 4161 + subrepoopts,
4158 4162 _(b'[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'),
4159 4163 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
4160 4164 )
4161 4165 def incoming(ui, repo, source=b"default", **opts):
4162 4166 """show new changesets found in source
4163 4167
4164 4168 Show new changesets found in the specified path/URL or the default
4165 4169 pull location. These are the changesets that would have been pulled
4166 4170 by :hg:`pull` at the time you issued this command.
4167 4171
4168 4172 See pull for valid source format details.
4169 4173
4170 4174 .. container:: verbose
4171 4175
4172 4176 With -B/--bookmarks, the result of bookmark comparison between
4173 4177 local and remote repositories is displayed. With -v/--verbose,
4174 4178 status is also displayed for each bookmark like below::
4175 4179
4176 4180 BM1 01234567890a added
4177 4181 BM2 1234567890ab advanced
4178 4182 BM3 234567890abc diverged
4179 4183 BM4 34567890abcd changed
4180 4184
4181 4185 The action taken locally when pulling depends on the
4182 4186 status of each bookmark:
4183 4187
4184 4188 :``added``: pull will create it
4185 4189 :``advanced``: pull will update it
4186 4190 :``diverged``: pull will create a divergent bookmark
4187 4191 :``changed``: result depends on remote changesets
4188 4192
4189 4193 From the point of view of pulling behavior, bookmark
4190 4194 existing only in the remote repository are treated as ``added``,
4191 4195 even if it is in fact locally deleted.
4192 4196
4193 4197 .. container:: verbose
4194 4198
4195 4199 For remote repository, using --bundle avoids downloading the
4196 4200 changesets twice if the incoming is followed by a pull.
4197 4201
4198 4202 Examples:
4199 4203
4200 4204 - show incoming changes with patches and full description::
4201 4205
4202 4206 hg incoming -vp
4203 4207
4204 4208 - show incoming changes excluding merges, store a bundle::
4205 4209
4206 4210 hg in -vpM --bundle incoming.hg
4207 4211 hg pull incoming.hg
4208 4212
4209 4213 - briefly list changes inside a bundle::
4210 4214
4211 4215 hg in changes.hg -T "{desc|firstline}\\n"
4212 4216
4213 4217 Returns 0 if there are incoming changes, 1 otherwise.
4214 4218 """
4215 4219 opts = pycompat.byteskwargs(opts)
4216 4220 if opts.get(b'graph'):
4217 4221 logcmdutil.checkunsupportedgraphflags([], opts)
4218 4222
4219 4223 def display(other, chlist, displayer):
4220 4224 revdag = logcmdutil.graphrevs(other, chlist, opts)
4221 4225 logcmdutil.displaygraph(
4222 4226 ui, repo, revdag, displayer, graphmod.asciiedges
4223 4227 )
4224 4228
4225 4229 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
4226 4230 return 0
4227 4231
4228 4232 cmdutil.check_incompatible_arguments(opts, b'subrepos', [b'bundle'])
4229 4233
4230 4234 if opts.get(b'bookmarks'):
4231 4235 source, branches = hg.parseurl(
4232 4236 ui.expandpath(source), opts.get(b'branch')
4233 4237 )
4234 4238 other = hg.peer(repo, opts, source)
4235 4239 if b'bookmarks' not in other.listkeys(b'namespaces'):
4236 4240 ui.warn(_(b"remote doesn't support bookmarks\n"))
4237 4241 return 0
4238 4242 ui.pager(b'incoming')
4239 4243 ui.status(_(b'comparing with %s\n') % util.hidepassword(source))
4240 4244 return bookmarks.incoming(ui, repo, other)
4241 4245
4242 4246 repo._subtoppath = ui.expandpath(source)
4243 4247 try:
4244 4248 return hg.incoming(ui, repo, source, opts)
4245 4249 finally:
4246 4250 del repo._subtoppath
4247 4251
4248 4252
4249 4253 @command(
4250 4254 b'init',
4251 4255 remoteopts,
4252 4256 _(b'[-e CMD] [--remotecmd CMD] [DEST]'),
4253 4257 helpcategory=command.CATEGORY_REPO_CREATION,
4254 4258 helpbasic=True,
4255 4259 norepo=True,
4256 4260 )
4257 4261 def init(ui, dest=b".", **opts):
4258 4262 """create a new repository in the given directory
4259 4263
4260 4264 Initialize a new repository in the given directory. If the given
4261 4265 directory does not exist, it will be created.
4262 4266
4263 4267 If no directory is given, the current directory is used.
4264 4268
4265 4269 It is possible to specify an ``ssh://`` URL as the destination.
4266 4270 See :hg:`help urls` for more information.
4267 4271
4268 4272 Returns 0 on success.
4269 4273 """
4270 4274 opts = pycompat.byteskwargs(opts)
4271 4275 hg.peer(ui, opts, ui.expandpath(dest), create=True)
4272 4276
4273 4277
4274 4278 @command(
4275 4279 b'locate',
4276 4280 [
4277 4281 (
4278 4282 b'r',
4279 4283 b'rev',
4280 4284 b'',
4281 4285 _(b'search the repository as it is in REV'),
4282 4286 _(b'REV'),
4283 4287 ),
4284 4288 (
4285 4289 b'0',
4286 4290 b'print0',
4287 4291 None,
4288 4292 _(b'end filenames with NUL, for use with xargs'),
4289 4293 ),
4290 4294 (
4291 4295 b'f',
4292 4296 b'fullpath',
4293 4297 None,
4294 4298 _(b'print complete paths from the filesystem root'),
4295 4299 ),
4296 4300 ]
4297 4301 + walkopts,
4298 4302 _(b'[OPTION]... [PATTERN]...'),
4299 4303 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
4300 4304 )
4301 4305 def locate(ui, repo, *pats, **opts):
4302 4306 """locate files matching specific patterns (DEPRECATED)
4303 4307
4304 4308 Print files under Mercurial control in the working directory whose
4305 4309 names match the given patterns.
4306 4310
4307 4311 By default, this command searches all directories in the working
4308 4312 directory. To search just the current directory and its
4309 4313 subdirectories, use "--include .".
4310 4314
4311 4315 If no patterns are given to match, this command prints the names
4312 4316 of all files under Mercurial control in the working directory.
4313 4317
4314 4318 If you want to feed the output of this command into the "xargs"
4315 4319 command, use the -0 option to both this command and "xargs". This
4316 4320 will avoid the problem of "xargs" treating single filenames that
4317 4321 contain whitespace as multiple filenames.
4318 4322
4319 4323 See :hg:`help files` for a more versatile command.
4320 4324
4321 4325 Returns 0 if a match is found, 1 otherwise.
4322 4326 """
4323 4327 opts = pycompat.byteskwargs(opts)
4324 4328 if opts.get(b'print0'):
4325 4329 end = b'\0'
4326 4330 else:
4327 4331 end = b'\n'
4328 4332 ctx = scmutil.revsingle(repo, opts.get(b'rev'), None)
4329 4333
4330 4334 ret = 1
4331 4335 m = scmutil.match(
4332 4336 ctx, pats, opts, default=b'relglob', badfn=lambda x, y: False
4333 4337 )
4334 4338
4335 4339 ui.pager(b'locate')
4336 4340 if ctx.rev() is None:
4337 4341 # When run on the working copy, "locate" includes removed files, so
4338 4342 # we get the list of files from the dirstate.
4339 4343 filesgen = sorted(repo.dirstate.matches(m))
4340 4344 else:
4341 4345 filesgen = ctx.matches(m)
4342 4346 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=bool(pats))
4343 4347 for abs in filesgen:
4344 4348 if opts.get(b'fullpath'):
4345 4349 ui.write(repo.wjoin(abs), end)
4346 4350 else:
4347 4351 ui.write(uipathfn(abs), end)
4348 4352 ret = 0
4349 4353
4350 4354 return ret
4351 4355
4352 4356
4353 4357 @command(
4354 4358 b'log|history',
4355 4359 [
4356 4360 (
4357 4361 b'f',
4358 4362 b'follow',
4359 4363 None,
4360 4364 _(
4361 4365 b'follow changeset history, or file history across copies and renames'
4362 4366 ),
4363 4367 ),
4364 4368 (
4365 4369 b'',
4366 4370 b'follow-first',
4367 4371 None,
4368 4372 _(b'only follow the first parent of merge changesets (DEPRECATED)'),
4369 4373 ),
4370 4374 (
4371 4375 b'd',
4372 4376 b'date',
4373 4377 b'',
4374 4378 _(b'show revisions matching date spec'),
4375 4379 _(b'DATE'),
4376 4380 ),
4377 4381 (b'C', b'copies', None, _(b'show copied files')),
4378 4382 (
4379 4383 b'k',
4380 4384 b'keyword',
4381 4385 [],
4382 4386 _(b'do case-insensitive search for a given text'),
4383 4387 _(b'TEXT'),
4384 4388 ),
4385 4389 (
4386 4390 b'r',
4387 4391 b'rev',
4388 4392 [],
4389 4393 _(b'show the specified revision or revset'),
4390 4394 _(b'REV'),
4391 4395 ),
4392 4396 (
4393 4397 b'L',
4394 4398 b'line-range',
4395 4399 [],
4396 4400 _(b'follow line range of specified file (EXPERIMENTAL)'),
4397 4401 _(b'FILE,RANGE'),
4398 4402 ),
4399 4403 (
4400 4404 b'',
4401 4405 b'removed',
4402 4406 None,
4403 4407 _(b'include revisions where files were removed'),
4404 4408 ),
4405 4409 (
4406 4410 b'm',
4407 4411 b'only-merges',
4408 4412 None,
4409 4413 _(b'show only merges (DEPRECATED) (use -r "merge()" instead)'),
4410 4414 ),
4411 4415 (b'u', b'user', [], _(b'revisions committed by user'), _(b'USER')),
4412 4416 (
4413 4417 b'',
4414 4418 b'only-branch',
4415 4419 [],
4416 4420 _(
4417 4421 b'show only changesets within the given named branch (DEPRECATED)'
4418 4422 ),
4419 4423 _(b'BRANCH'),
4420 4424 ),
4421 4425 (
4422 4426 b'b',
4423 4427 b'branch',
4424 4428 [],
4425 4429 _(b'show changesets within the given named branch'),
4426 4430 _(b'BRANCH'),
4427 4431 ),
4428 4432 (
4429 4433 b'P',
4430 4434 b'prune',
4431 4435 [],
4432 4436 _(b'do not display revision or any of its ancestors'),
4433 4437 _(b'REV'),
4434 4438 ),
4435 4439 ]
4436 4440 + logopts
4437 4441 + walkopts,
4438 4442 _(b'[OPTION]... [FILE]'),
4439 4443 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
4440 4444 helpbasic=True,
4441 4445 inferrepo=True,
4442 4446 intents={INTENT_READONLY},
4443 4447 )
4444 4448 def log(ui, repo, *pats, **opts):
4445 4449 """show revision history of entire repository or files
4446 4450
4447 4451 Print the revision history of the specified files or the entire
4448 4452 project.
4449 4453
4450 4454 If no revision range is specified, the default is ``tip:0`` unless
4451 4455 --follow is set, in which case the working directory parent is
4452 4456 used as the starting revision.
4453 4457
4454 4458 File history is shown without following rename or copy history of
4455 4459 files. Use -f/--follow with a filename to follow history across
4456 4460 renames and copies. --follow without a filename will only show
4457 4461 ancestors of the starting revision.
4458 4462
4459 4463 By default this command prints revision number and changeset id,
4460 4464 tags, non-trivial parents, user, date and time, and a summary for
4461 4465 each commit. When the -v/--verbose switch is used, the list of
4462 4466 changed files and full commit message are shown.
4463 4467
4464 4468 With --graph the revisions are shown as an ASCII art DAG with the most
4465 4469 recent changeset at the top.
4466 4470 'o' is a changeset, '@' is a working directory parent, '%' is a changeset
4467 4471 involved in an unresolved merge conflict, '_' closes a branch,
4468 4472 'x' is obsolete, '*' is unstable, and '+' represents a fork where the
4469 4473 changeset from the lines below is a parent of the 'o' merge on the same
4470 4474 line.
4471 4475 Paths in the DAG are represented with '|', '/' and so forth. ':' in place
4472 4476 of a '|' indicates one or more revisions in a path are omitted.
4473 4477
4474 4478 .. container:: verbose
4475 4479
4476 4480 Use -L/--line-range FILE,M:N options to follow the history of lines
4477 4481 from M to N in FILE. With -p/--patch only diff hunks affecting
4478 4482 specified line range will be shown. This option requires --follow;
4479 4483 it can be specified multiple times. Currently, this option is not
4480 4484 compatible with --graph. This option is experimental.
4481 4485
4482 4486 .. note::
4483 4487
4484 4488 :hg:`log --patch` may generate unexpected diff output for merge
4485 4489 changesets, as it will only compare the merge changeset against
4486 4490 its first parent. Also, only files different from BOTH parents
4487 4491 will appear in files:.
4488 4492
4489 4493 .. note::
4490 4494
4491 4495 For performance reasons, :hg:`log FILE` may omit duplicate changes
4492 4496 made on branches and will not show removals or mode changes. To
4493 4497 see all such changes, use the --removed switch.
4494 4498
4495 4499 .. container:: verbose
4496 4500
4497 4501 .. note::
4498 4502
4499 4503 The history resulting from -L/--line-range options depends on diff
4500 4504 options; for instance if white-spaces are ignored, respective changes
4501 4505 with only white-spaces in specified line range will not be listed.
4502 4506
4503 4507 .. container:: verbose
4504 4508
4505 4509 Some examples:
4506 4510
4507 4511 - changesets with full descriptions and file lists::
4508 4512
4509 4513 hg log -v
4510 4514
4511 4515 - changesets ancestral to the working directory::
4512 4516
4513 4517 hg log -f
4514 4518
4515 4519 - last 10 commits on the current branch::
4516 4520
4517 4521 hg log -l 10 -b .
4518 4522
4519 4523 - changesets showing all modifications of a file, including removals::
4520 4524
4521 4525 hg log --removed file.c
4522 4526
4523 4527 - all changesets that touch a directory, with diffs, excluding merges::
4524 4528
4525 4529 hg log -Mp lib/
4526 4530
4527 4531 - all revision numbers that match a keyword::
4528 4532
4529 4533 hg log -k bug --template "{rev}\\n"
4530 4534
4531 4535 - the full hash identifier of the working directory parent::
4532 4536
4533 4537 hg log -r . --template "{node}\\n"
4534 4538
4535 4539 - list available log templates::
4536 4540
4537 4541 hg log -T list
4538 4542
4539 4543 - check if a given changeset is included in a tagged release::
4540 4544
4541 4545 hg log -r "a21ccf and ancestor(1.9)"
4542 4546
4543 4547 - find all changesets by some user in a date range::
4544 4548
4545 4549 hg log -k alice -d "may 2008 to jul 2008"
4546 4550
4547 4551 - summary of all changesets after the last tag::
4548 4552
4549 4553 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
4550 4554
4551 4555 - changesets touching lines 13 to 23 for file.c::
4552 4556
4553 4557 hg log -L file.c,13:23
4554 4558
4555 4559 - changesets touching lines 13 to 23 for file.c and lines 2 to 6 of
4556 4560 main.c with patch::
4557 4561
4558 4562 hg log -L file.c,13:23 -L main.c,2:6 -p
4559 4563
4560 4564 See :hg:`help dates` for a list of formats valid for -d/--date.
4561 4565
4562 4566 See :hg:`help revisions` for more about specifying and ordering
4563 4567 revisions.
4564 4568
4565 4569 See :hg:`help templates` for more about pre-packaged styles and
4566 4570 specifying custom templates. The default template used by the log
4567 4571 command can be customized via the ``ui.logtemplate`` configuration
4568 4572 setting.
4569 4573
4570 4574 Returns 0 on success.
4571 4575
4572 4576 """
4573 4577 opts = pycompat.byteskwargs(opts)
4574 4578 linerange = opts.get(b'line_range')
4575 4579
4576 4580 if linerange and not opts.get(b'follow'):
4577 4581 raise error.Abort(_(b'--line-range requires --follow'))
4578 4582
4579 4583 if linerange and pats:
4580 4584 # TODO: take pats as patterns with no line-range filter
4581 4585 raise error.Abort(
4582 4586 _(b'FILE arguments are not compatible with --line-range option')
4583 4587 )
4584 4588
4585 4589 repo = scmutil.unhidehashlikerevs(repo, opts.get(b'rev'), b'nowarn')
4586 4590 revs, differ = logcmdutil.getrevs(
4587 4591 repo, logcmdutil.parseopts(ui, pats, opts)
4588 4592 )
4589 4593 if linerange:
4590 4594 # TODO: should follow file history from logcmdutil._initialrevs(),
4591 4595 # then filter the result by logcmdutil._makerevset() and --limit
4592 4596 revs, differ = logcmdutil.getlinerangerevs(repo, revs, opts)
4593 4597
4594 4598 getcopies = None
4595 4599 if opts.get(b'copies'):
4596 4600 endrev = None
4597 4601 if revs:
4598 4602 endrev = revs.max() + 1
4599 4603 getcopies = scmutil.getcopiesfn(repo, endrev=endrev)
4600 4604
4601 4605 ui.pager(b'log')
4602 4606 displayer = logcmdutil.changesetdisplayer(
4603 4607 ui, repo, opts, differ, buffered=True
4604 4608 )
4605 4609 if opts.get(b'graph'):
4606 4610 displayfn = logcmdutil.displaygraphrevs
4607 4611 else:
4608 4612 displayfn = logcmdutil.displayrevs
4609 4613 displayfn(ui, repo, revs, displayer, getcopies)
4610 4614
4611 4615
4612 4616 @command(
4613 4617 b'manifest',
4614 4618 [
4615 4619 (b'r', b'rev', b'', _(b'revision to display'), _(b'REV')),
4616 4620 (b'', b'all', False, _(b"list files from all revisions")),
4617 4621 ]
4618 4622 + formatteropts,
4619 4623 _(b'[-r REV]'),
4620 4624 helpcategory=command.CATEGORY_MAINTENANCE,
4621 4625 intents={INTENT_READONLY},
4622 4626 )
4623 4627 def manifest(ui, repo, node=None, rev=None, **opts):
4624 4628 """output the current or given revision of the project manifest
4625 4629
4626 4630 Print a list of version controlled files for the given revision.
4627 4631 If no revision is given, the first parent of the working directory
4628 4632 is used, or the null revision if no revision is checked out.
4629 4633
4630 4634 With -v, print file permissions, symlink and executable bits.
4631 4635 With --debug, print file revision hashes.
4632 4636
4633 4637 If option --all is specified, the list of all files from all revisions
4634 4638 is printed. This includes deleted and renamed files.
4635 4639
4636 4640 Returns 0 on success.
4637 4641 """
4638 4642 opts = pycompat.byteskwargs(opts)
4639 4643 fm = ui.formatter(b'manifest', opts)
4640 4644
4641 4645 if opts.get(b'all'):
4642 4646 if rev or node:
4643 4647 raise error.Abort(_(b"can't specify a revision with --all"))
4644 4648
4645 4649 res = set()
4646 4650 for rev in repo:
4647 4651 ctx = repo[rev]
4648 4652 res |= set(ctx.files())
4649 4653
4650 4654 ui.pager(b'manifest')
4651 4655 for f in sorted(res):
4652 4656 fm.startitem()
4653 4657 fm.write(b"path", b'%s\n', f)
4654 4658 fm.end()
4655 4659 return
4656 4660
4657 4661 if rev and node:
4658 4662 raise error.Abort(_(b"please specify just one revision"))
4659 4663
4660 4664 if not node:
4661 4665 node = rev
4662 4666
4663 4667 char = {b'l': b'@', b'x': b'*', b'': b'', b't': b'd'}
4664 4668 mode = {b'l': b'644', b'x': b'755', b'': b'644', b't': b'755'}
4665 4669 if node:
4666 4670 repo = scmutil.unhidehashlikerevs(repo, [node], b'nowarn')
4667 4671 ctx = scmutil.revsingle(repo, node)
4668 4672 mf = ctx.manifest()
4669 4673 ui.pager(b'manifest')
4670 4674 for f in ctx:
4671 4675 fm.startitem()
4672 4676 fm.context(ctx=ctx)
4673 4677 fl = ctx[f].flags()
4674 4678 fm.condwrite(ui.debugflag, b'hash', b'%s ', hex(mf[f]))
4675 4679 fm.condwrite(ui.verbose, b'mode type', b'%s %1s ', mode[fl], char[fl])
4676 4680 fm.write(b'path', b'%s\n', f)
4677 4681 fm.end()
4678 4682
4679 4683
4680 4684 @command(
4681 4685 b'merge',
4682 4686 [
4683 4687 (
4684 4688 b'f',
4685 4689 b'force',
4686 4690 None,
4687 4691 _(b'force a merge including outstanding changes (DEPRECATED)'),
4688 4692 ),
4689 4693 (b'r', b'rev', b'', _(b'revision to merge'), _(b'REV')),
4690 4694 (
4691 4695 b'P',
4692 4696 b'preview',
4693 4697 None,
4694 4698 _(b'review revisions to merge (no merge is performed)'),
4695 4699 ),
4696 4700 (b'', b'abort', None, _(b'abort the ongoing merge')),
4697 4701 ]
4698 4702 + mergetoolopts,
4699 4703 _(b'[-P] [[-r] REV]'),
4700 4704 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
4701 4705 helpbasic=True,
4702 4706 )
4703 4707 def merge(ui, repo, node=None, **opts):
4704 4708 """merge another revision into working directory
4705 4709
4706 4710 The current working directory is updated with all changes made in
4707 4711 the requested revision since the last common predecessor revision.
4708 4712
4709 4713 Files that changed between either parent are marked as changed for
4710 4714 the next commit and a commit must be performed before any further
4711 4715 updates to the repository are allowed. The next commit will have
4712 4716 two parents.
4713 4717
4714 4718 ``--tool`` can be used to specify the merge tool used for file
4715 4719 merges. It overrides the HGMERGE environment variable and your
4716 4720 configuration files. See :hg:`help merge-tools` for options.
4717 4721
4718 4722 If no revision is specified, the working directory's parent is a
4719 4723 head revision, and the current branch contains exactly one other
4720 4724 head, the other head is merged with by default. Otherwise, an
4721 4725 explicit revision with which to merge must be provided.
4722 4726
4723 4727 See :hg:`help resolve` for information on handling file conflicts.
4724 4728
4725 4729 To undo an uncommitted merge, use :hg:`merge --abort` which
4726 4730 will check out a clean copy of the original merge parent, losing
4727 4731 all changes.
4728 4732
4729 4733 Returns 0 on success, 1 if there are unresolved files.
4730 4734 """
4731 4735
4732 4736 opts = pycompat.byteskwargs(opts)
4733 4737 abort = opts.get(b'abort')
4734 4738 if abort and repo.dirstate.p2() == nullid:
4735 4739 cmdutil.wrongtooltocontinue(repo, _(b'merge'))
4736 4740 cmdutil.check_incompatible_arguments(opts, b'abort', [b'rev', b'preview'])
4737 4741 if abort:
4738 4742 state = cmdutil.getunfinishedstate(repo)
4739 4743 if state and state._opname != b'merge':
4740 4744 raise error.Abort(
4741 4745 _(b'cannot abort merge with %s in progress') % (state._opname),
4742 4746 hint=state.hint(),
4743 4747 )
4744 4748 if node:
4745 4749 raise error.Abort(_(b"cannot specify a node with --abort"))
4746 4750 return hg.abortmerge(repo.ui, repo)
4747 4751
4748 4752 if opts.get(b'rev') and node:
4749 4753 raise error.Abort(_(b"please specify just one revision"))
4750 4754 if not node:
4751 4755 node = opts.get(b'rev')
4752 4756
4753 4757 if node:
4754 4758 ctx = scmutil.revsingle(repo, node)
4755 4759 else:
4756 4760 if ui.configbool(b'commands', b'merge.require-rev'):
4757 4761 raise error.Abort(
4758 4762 _(
4759 4763 b'configuration requires specifying revision to merge '
4760 4764 b'with'
4761 4765 )
4762 4766 )
4763 4767 ctx = repo[destutil.destmerge(repo)]
4764 4768
4765 4769 if ctx.node() is None:
4766 4770 raise error.Abort(_(b'merging with the working copy has no effect'))
4767 4771
4768 4772 if opts.get(b'preview'):
4769 4773 # find nodes that are ancestors of p2 but not of p1
4770 4774 p1 = repo[b'.'].node()
4771 4775 p2 = ctx.node()
4772 4776 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4773 4777
4774 4778 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
4775 4779 for node in nodes:
4776 4780 displayer.show(repo[node])
4777 4781 displayer.close()
4778 4782 return 0
4779 4783
4780 4784 # ui.forcemerge is an internal variable, do not document
4781 4785 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
4782 4786 with ui.configoverride(overrides, b'merge'):
4783 4787 force = opts.get(b'force')
4784 4788 labels = [b'working copy', b'merge rev']
4785 4789 return hg.merge(ctx, force=force, labels=labels)
4786 4790
4787 4791
4788 4792 statemod.addunfinished(
4789 4793 b'merge',
4790 4794 fname=None,
4791 4795 clearable=True,
4792 4796 allowcommit=True,
4793 4797 cmdmsg=_(b'outstanding uncommitted merge'),
4794 4798 abortfunc=hg.abortmerge,
4795 4799 statushint=_(
4796 4800 b'To continue: hg commit\nTo abort: hg merge --abort'
4797 4801 ),
4798 4802 cmdhint=_(b"use 'hg commit' or 'hg merge --abort'"),
4799 4803 )
4800 4804
4801 4805
4802 4806 @command(
4803 4807 b'outgoing|out',
4804 4808 [
4805 4809 (
4806 4810 b'f',
4807 4811 b'force',
4808 4812 None,
4809 4813 _(b'run even when the destination is unrelated'),
4810 4814 ),
4811 4815 (
4812 4816 b'r',
4813 4817 b'rev',
4814 4818 [],
4815 4819 _(b'a changeset intended to be included in the destination'),
4816 4820 _(b'REV'),
4817 4821 ),
4818 4822 (b'n', b'newest-first', None, _(b'show newest record first')),
4819 4823 (b'B', b'bookmarks', False, _(b'compare bookmarks')),
4820 4824 (
4821 4825 b'b',
4822 4826 b'branch',
4823 4827 [],
4824 4828 _(b'a specific branch you would like to push'),
4825 4829 _(b'BRANCH'),
4826 4830 ),
4827 4831 ]
4828 4832 + logopts
4829 4833 + remoteopts
4830 4834 + subrepoopts,
4831 4835 _(b'[-M] [-p] [-n] [-f] [-r REV]... [DEST]'),
4832 4836 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
4833 4837 )
4834 4838 def outgoing(ui, repo, dest=None, **opts):
4835 4839 """show changesets not found in the destination
4836 4840
4837 4841 Show changesets not found in the specified destination repository
4838 4842 or the default push location. These are the changesets that would
4839 4843 be pushed if a push was requested.
4840 4844
4841 4845 See pull for details of valid destination formats.
4842 4846
4843 4847 .. container:: verbose
4844 4848
4845 4849 With -B/--bookmarks, the result of bookmark comparison between
4846 4850 local and remote repositories is displayed. With -v/--verbose,
4847 4851 status is also displayed for each bookmark like below::
4848 4852
4849 4853 BM1 01234567890a added
4850 4854 BM2 deleted
4851 4855 BM3 234567890abc advanced
4852 4856 BM4 34567890abcd diverged
4853 4857 BM5 4567890abcde changed
4854 4858
4855 4859 The action taken when pushing depends on the
4856 4860 status of each bookmark:
4857 4861
4858 4862 :``added``: push with ``-B`` will create it
4859 4863 :``deleted``: push with ``-B`` will delete it
4860 4864 :``advanced``: push will update it
4861 4865 :``diverged``: push with ``-B`` will update it
4862 4866 :``changed``: push with ``-B`` will update it
4863 4867
4864 4868 From the point of view of pushing behavior, bookmarks
4865 4869 existing only in the remote repository are treated as
4866 4870 ``deleted``, even if it is in fact added remotely.
4867 4871
4868 4872 Returns 0 if there are outgoing changes, 1 otherwise.
4869 4873 """
4870 4874 # hg._outgoing() needs to re-resolve the path in order to handle #branch
4871 4875 # style URLs, so don't overwrite dest.
4872 4876 path = ui.paths.getpath(dest, default=(b'default-push', b'default'))
4873 4877 if not path:
4874 4878 raise error.Abort(
4875 4879 _(b'default repository not configured!'),
4876 4880 hint=_(b"see 'hg help config.paths'"),
4877 4881 )
4878 4882
4879 4883 opts = pycompat.byteskwargs(opts)
4880 4884 if opts.get(b'graph'):
4881 4885 logcmdutil.checkunsupportedgraphflags([], opts)
4882 4886 o, other = hg._outgoing(ui, repo, dest, opts)
4883 4887 if not o:
4884 4888 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4885 4889 return
4886 4890
4887 4891 revdag = logcmdutil.graphrevs(repo, o, opts)
4888 4892 ui.pager(b'outgoing')
4889 4893 displayer = logcmdutil.changesetdisplayer(ui, repo, opts, buffered=True)
4890 4894 logcmdutil.displaygraph(
4891 4895 ui, repo, revdag, displayer, graphmod.asciiedges
4892 4896 )
4893 4897 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4894 4898 return 0
4895 4899
4896 4900 if opts.get(b'bookmarks'):
4897 4901 dest = path.pushloc or path.loc
4898 4902 other = hg.peer(repo, opts, dest)
4899 4903 if b'bookmarks' not in other.listkeys(b'namespaces'):
4900 4904 ui.warn(_(b"remote doesn't support bookmarks\n"))
4901 4905 return 0
4902 4906 ui.status(_(b'comparing with %s\n') % util.hidepassword(dest))
4903 4907 ui.pager(b'outgoing')
4904 4908 return bookmarks.outgoing(ui, repo, other)
4905 4909
4906 4910 repo._subtoppath = path.pushloc or path.loc
4907 4911 try:
4908 4912 return hg.outgoing(ui, repo, dest, opts)
4909 4913 finally:
4910 4914 del repo._subtoppath
4911 4915
4912 4916
4913 4917 @command(
4914 4918 b'parents',
4915 4919 [
4916 4920 (
4917 4921 b'r',
4918 4922 b'rev',
4919 4923 b'',
4920 4924 _(b'show parents of the specified revision'),
4921 4925 _(b'REV'),
4922 4926 ),
4923 4927 ]
4924 4928 + templateopts,
4925 4929 _(b'[-r REV] [FILE]'),
4926 4930 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
4927 4931 inferrepo=True,
4928 4932 )
4929 4933 def parents(ui, repo, file_=None, **opts):
4930 4934 """show the parents of the working directory or revision (DEPRECATED)
4931 4935
4932 4936 Print the working directory's parent revisions. If a revision is
4933 4937 given via -r/--rev, the parent of that revision will be printed.
4934 4938 If a file argument is given, the revision in which the file was
4935 4939 last changed (before the working directory revision or the
4936 4940 argument to --rev if given) is printed.
4937 4941
4938 4942 This command is equivalent to::
4939 4943
4940 4944 hg log -r "p1()+p2()" or
4941 4945 hg log -r "p1(REV)+p2(REV)" or
4942 4946 hg log -r "max(::p1() and file(FILE))+max(::p2() and file(FILE))" or
4943 4947 hg log -r "max(::p1(REV) and file(FILE))+max(::p2(REV) and file(FILE))"
4944 4948
4945 4949 See :hg:`summary` and :hg:`help revsets` for related information.
4946 4950
4947 4951 Returns 0 on success.
4948 4952 """
4949 4953
4950 4954 opts = pycompat.byteskwargs(opts)
4951 4955 rev = opts.get(b'rev')
4952 4956 if rev:
4953 4957 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
4954 4958 ctx = scmutil.revsingle(repo, rev, None)
4955 4959
4956 4960 if file_:
4957 4961 m = scmutil.match(ctx, (file_,), opts)
4958 4962 if m.anypats() or len(m.files()) != 1:
4959 4963 raise error.Abort(_(b'can only specify an explicit filename'))
4960 4964 file_ = m.files()[0]
4961 4965 filenodes = []
4962 4966 for cp in ctx.parents():
4963 4967 if not cp:
4964 4968 continue
4965 4969 try:
4966 4970 filenodes.append(cp.filenode(file_))
4967 4971 except error.LookupError:
4968 4972 pass
4969 4973 if not filenodes:
4970 4974 raise error.Abort(_(b"'%s' not found in manifest!") % file_)
4971 4975 p = []
4972 4976 for fn in filenodes:
4973 4977 fctx = repo.filectx(file_, fileid=fn)
4974 4978 p.append(fctx.node())
4975 4979 else:
4976 4980 p = [cp.node() for cp in ctx.parents()]
4977 4981
4978 4982 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
4979 4983 for n in p:
4980 4984 if n != nullid:
4981 4985 displayer.show(repo[n])
4982 4986 displayer.close()
4983 4987
4984 4988
4985 4989 @command(
4986 4990 b'paths',
4987 4991 formatteropts,
4988 4992 _(b'[NAME]'),
4989 4993 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
4990 4994 optionalrepo=True,
4991 4995 intents={INTENT_READONLY},
4992 4996 )
4993 4997 def paths(ui, repo, search=None, **opts):
4994 4998 """show aliases for remote repositories
4995 4999
4996 5000 Show definition of symbolic path name NAME. If no name is given,
4997 5001 show definition of all available names.
4998 5002
4999 5003 Option -q/--quiet suppresses all output when searching for NAME
5000 5004 and shows only the path names when listing all definitions.
5001 5005
5002 5006 Path names are defined in the [paths] section of your
5003 5007 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
5004 5008 repository, ``.hg/hgrc`` is used, too.
5005 5009
5006 5010 The path names ``default`` and ``default-push`` have a special
5007 5011 meaning. When performing a push or pull operation, they are used
5008 5012 as fallbacks if no location is specified on the command-line.
5009 5013 When ``default-push`` is set, it will be used for push and
5010 5014 ``default`` will be used for pull; otherwise ``default`` is used
5011 5015 as the fallback for both. When cloning a repository, the clone
5012 5016 source is written as ``default`` in ``.hg/hgrc``.
5013 5017
5014 5018 .. note::
5015 5019
5016 5020 ``default`` and ``default-push`` apply to all inbound (e.g.
5017 5021 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email`
5018 5022 and :hg:`bundle`) operations.
5019 5023
5020 5024 See :hg:`help urls` for more information.
5021 5025
5022 5026 .. container:: verbose
5023 5027
5024 5028 Template:
5025 5029
5026 5030 The following keywords are supported. See also :hg:`help templates`.
5027 5031
5028 5032 :name: String. Symbolic name of the path alias.
5029 5033 :pushurl: String. URL for push operations.
5030 5034 :url: String. URL or directory path for the other operations.
5031 5035
5032 5036 Returns 0 on success.
5033 5037 """
5034 5038
5035 5039 opts = pycompat.byteskwargs(opts)
5036 5040 ui.pager(b'paths')
5037 5041 if search:
5038 5042 pathitems = [
5039 5043 (name, path)
5040 5044 for name, path in pycompat.iteritems(ui.paths)
5041 5045 if name == search
5042 5046 ]
5043 5047 else:
5044 5048 pathitems = sorted(pycompat.iteritems(ui.paths))
5045 5049
5046 5050 fm = ui.formatter(b'paths', opts)
5047 5051 if fm.isplain():
5048 5052 hidepassword = util.hidepassword
5049 5053 else:
5050 5054 hidepassword = bytes
5051 5055 if ui.quiet:
5052 5056 namefmt = b'%s\n'
5053 5057 else:
5054 5058 namefmt = b'%s = '
5055 5059 showsubopts = not search and not ui.quiet
5056 5060
5057 5061 for name, path in pathitems:
5058 5062 fm.startitem()
5059 5063 fm.condwrite(not search, b'name', namefmt, name)
5060 5064 fm.condwrite(not ui.quiet, b'url', b'%s\n', hidepassword(path.rawloc))
5061 5065 for subopt, value in sorted(path.suboptions.items()):
5062 5066 assert subopt not in (b'name', b'url')
5063 5067 if showsubopts:
5064 5068 fm.plain(b'%s:%s = ' % (name, subopt))
5065 5069 fm.condwrite(showsubopts, subopt, b'%s\n', value)
5066 5070
5067 5071 fm.end()
5068 5072
5069 5073 if search and not pathitems:
5070 5074 if not ui.quiet:
5071 5075 ui.warn(_(b"not found!\n"))
5072 5076 return 1
5073 5077 else:
5074 5078 return 0
5075 5079
5076 5080
5077 5081 @command(
5078 5082 b'phase',
5079 5083 [
5080 5084 (b'p', b'public', False, _(b'set changeset phase to public')),
5081 5085 (b'd', b'draft', False, _(b'set changeset phase to draft')),
5082 5086 (b's', b'secret', False, _(b'set changeset phase to secret')),
5083 5087 (b'f', b'force', False, _(b'allow to move boundary backward')),
5084 5088 (b'r', b'rev', [], _(b'target revision'), _(b'REV')),
5085 5089 ],
5086 5090 _(b'[-p|-d|-s] [-f] [-r] [REV...]'),
5087 5091 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
5088 5092 )
5089 5093 def phase(ui, repo, *revs, **opts):
5090 5094 """set or show the current phase name
5091 5095
5092 5096 With no argument, show the phase name of the current revision(s).
5093 5097
5094 5098 With one of -p/--public, -d/--draft or -s/--secret, change the
5095 5099 phase value of the specified revisions.
5096 5100
5097 5101 Unless -f/--force is specified, :hg:`phase` won't move changesets from a
5098 5102 lower phase to a higher phase. Phases are ordered as follows::
5099 5103
5100 5104 public < draft < secret
5101 5105
5102 5106 Returns 0 on success, 1 if some phases could not be changed.
5103 5107
5104 5108 (For more information about the phases concept, see :hg:`help phases`.)
5105 5109 """
5106 5110 opts = pycompat.byteskwargs(opts)
5107 5111 # search for a unique phase argument
5108 5112 targetphase = None
5109 5113 for idx, name in enumerate(phases.cmdphasenames):
5110 5114 if opts[name]:
5111 5115 if targetphase is not None:
5112 5116 raise error.Abort(_(b'only one phase can be specified'))
5113 5117 targetphase = idx
5114 5118
5115 5119 # look for specified revision
5116 5120 revs = list(revs)
5117 5121 revs.extend(opts[b'rev'])
5118 5122 if not revs:
5119 5123 # display both parents as the second parent phase can influence
5120 5124 # the phase of a merge commit
5121 5125 revs = [c.rev() for c in repo[None].parents()]
5122 5126
5123 5127 revs = scmutil.revrange(repo, revs)
5124 5128
5125 5129 ret = 0
5126 5130 if targetphase is None:
5127 5131 # display
5128 5132 for r in revs:
5129 5133 ctx = repo[r]
5130 5134 ui.write(b'%i: %s\n' % (ctx.rev(), ctx.phasestr()))
5131 5135 else:
5132 5136 with repo.lock(), repo.transaction(b"phase") as tr:
5133 5137 # set phase
5134 5138 if not revs:
5135 5139 raise error.Abort(_(b'empty revision set'))
5136 5140 nodes = [repo[r].node() for r in revs]
5137 5141 # moving revision from public to draft may hide them
5138 5142 # We have to check result on an unfiltered repository
5139 5143 unfi = repo.unfiltered()
5140 5144 getphase = unfi._phasecache.phase
5141 5145 olddata = [getphase(unfi, r) for r in unfi]
5142 5146 phases.advanceboundary(repo, tr, targetphase, nodes)
5143 5147 if opts[b'force']:
5144 5148 phases.retractboundary(repo, tr, targetphase, nodes)
5145 5149 getphase = unfi._phasecache.phase
5146 5150 newdata = [getphase(unfi, r) for r in unfi]
5147 5151 changes = sum(newdata[r] != olddata[r] for r in unfi)
5148 5152 cl = unfi.changelog
5149 5153 rejected = [n for n in nodes if newdata[cl.rev(n)] < targetphase]
5150 5154 if rejected:
5151 5155 ui.warn(
5152 5156 _(
5153 5157 b'cannot move %i changesets to a higher '
5154 5158 b'phase, use --force\n'
5155 5159 )
5156 5160 % len(rejected)
5157 5161 )
5158 5162 ret = 1
5159 5163 if changes:
5160 5164 msg = _(b'phase changed for %i changesets\n') % changes
5161 5165 if ret:
5162 5166 ui.status(msg)
5163 5167 else:
5164 5168 ui.note(msg)
5165 5169 else:
5166 5170 ui.warn(_(b'no phases changed\n'))
5167 5171 return ret
5168 5172
5169 5173
5170 5174 def postincoming(ui, repo, modheads, optupdate, checkout, brev):
5171 5175 """Run after a changegroup has been added via pull/unbundle
5172 5176
5173 5177 This takes arguments below:
5174 5178
5175 5179 :modheads: change of heads by pull/unbundle
5176 5180 :optupdate: updating working directory is needed or not
5177 5181 :checkout: update destination revision (or None to default destination)
5178 5182 :brev: a name, which might be a bookmark to be activated after updating
5179 5183 """
5180 5184 if modheads == 0:
5181 5185 return
5182 5186 if optupdate:
5183 5187 try:
5184 5188 return hg.updatetotally(ui, repo, checkout, brev)
5185 5189 except error.UpdateAbort as inst:
5186 5190 msg = _(b"not updating: %s") % stringutil.forcebytestr(inst)
5187 5191 hint = inst.hint
5188 5192 raise error.UpdateAbort(msg, hint=hint)
5189 5193 if modheads is not None and modheads > 1:
5190 5194 currentbranchheads = len(repo.branchheads())
5191 5195 if currentbranchheads == modheads:
5192 5196 ui.status(
5193 5197 _(b"(run 'hg heads' to see heads, 'hg merge' to merge)\n")
5194 5198 )
5195 5199 elif currentbranchheads > 1:
5196 5200 ui.status(
5197 5201 _(b"(run 'hg heads .' to see heads, 'hg merge' to merge)\n")
5198 5202 )
5199 5203 else:
5200 5204 ui.status(_(b"(run 'hg heads' to see heads)\n"))
5201 5205 elif not ui.configbool(b'commands', b'update.requiredest'):
5202 5206 ui.status(_(b"(run 'hg update' to get a working copy)\n"))
5203 5207
5204 5208
5205 5209 @command(
5206 5210 b'pull',
5207 5211 [
5208 5212 (
5209 5213 b'u',
5210 5214 b'update',
5211 5215 None,
5212 5216 _(b'update to new branch head if new descendants were pulled'),
5213 5217 ),
5214 5218 (
5215 5219 b'f',
5216 5220 b'force',
5217 5221 None,
5218 5222 _(b'run even when remote repository is unrelated'),
5219 5223 ),
5220 5224 (b'', b'confirm', None, _(b'confirm pull before applying changes'),),
5221 5225 (
5222 5226 b'r',
5223 5227 b'rev',
5224 5228 [],
5225 5229 _(b'a remote changeset intended to be added'),
5226 5230 _(b'REV'),
5227 5231 ),
5228 5232 (b'B', b'bookmark', [], _(b"bookmark to pull"), _(b'BOOKMARK')),
5229 5233 (
5230 5234 b'b',
5231 5235 b'branch',
5232 5236 [],
5233 5237 _(b'a specific branch you would like to pull'),
5234 5238 _(b'BRANCH'),
5235 5239 ),
5236 5240 ]
5237 5241 + remoteopts,
5238 5242 _(b'[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'),
5239 5243 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
5240 5244 helpbasic=True,
5241 5245 )
5242 5246 def pull(ui, repo, source=b"default", **opts):
5243 5247 """pull changes from the specified source
5244 5248
5245 5249 Pull changes from a remote repository to a local one.
5246 5250
5247 5251 This finds all changes from the repository at the specified path
5248 5252 or URL and adds them to a local repository (the current one unless
5249 5253 -R is specified). By default, this does not update the copy of the
5250 5254 project in the working directory.
5251 5255
5252 5256 When cloning from servers that support it, Mercurial may fetch
5253 5257 pre-generated data. When this is done, hooks operating on incoming
5254 5258 changesets and changegroups may fire more than once, once for each
5255 5259 pre-generated bundle and as well as for any additional remaining
5256 5260 data. See :hg:`help -e clonebundles` for more.
5257 5261
5258 5262 Use :hg:`incoming` if you want to see what would have been added
5259 5263 by a pull at the time you issued this command. If you then decide
5260 5264 to add those changes to the repository, you should use :hg:`pull
5261 5265 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
5262 5266
5263 5267 If SOURCE is omitted, the 'default' path will be used.
5264 5268 See :hg:`help urls` for more information.
5265 5269
5266 5270 Specifying bookmark as ``.`` is equivalent to specifying the active
5267 5271 bookmark's name.
5268 5272
5269 5273 Returns 0 on success, 1 if an update had unresolved files.
5270 5274 """
5271 5275
5272 5276 opts = pycompat.byteskwargs(opts)
5273 5277 if ui.configbool(b'commands', b'update.requiredest') and opts.get(
5274 5278 b'update'
5275 5279 ):
5276 5280 msg = _(b'update destination required by configuration')
5277 5281 hint = _(b'use hg pull followed by hg update DEST')
5278 5282 raise error.Abort(msg, hint=hint)
5279 5283
5280 5284 source, branches = hg.parseurl(ui.expandpath(source), opts.get(b'branch'))
5281 5285 ui.status(_(b'pulling from %s\n') % util.hidepassword(source))
5282 5286 other = hg.peer(repo, opts, source)
5283 5287 try:
5284 5288 revs, checkout = hg.addbranchrevs(
5285 5289 repo, other, branches, opts.get(b'rev')
5286 5290 )
5287 5291
5288 5292 pullopargs = {}
5289 5293
5290 5294 nodes = None
5291 5295 if opts.get(b'bookmark') or revs:
5292 5296 # The list of bookmark used here is the same used to actually update
5293 5297 # the bookmark names, to avoid the race from issue 4689 and we do
5294 5298 # all lookup and bookmark queries in one go so they see the same
5295 5299 # version of the server state (issue 4700).
5296 5300 nodes = []
5297 5301 fnodes = []
5298 5302 revs = revs or []
5299 5303 if revs and not other.capable(b'lookup'):
5300 5304 err = _(
5301 5305 b"other repository doesn't support revision lookup, "
5302 5306 b"so a rev cannot be specified."
5303 5307 )
5304 5308 raise error.Abort(err)
5305 5309 with other.commandexecutor() as e:
5306 5310 fremotebookmarks = e.callcommand(
5307 5311 b'listkeys', {b'namespace': b'bookmarks'}
5308 5312 )
5309 5313 for r in revs:
5310 5314 fnodes.append(e.callcommand(b'lookup', {b'key': r}))
5311 5315 remotebookmarks = fremotebookmarks.result()
5312 5316 remotebookmarks = bookmarks.unhexlifybookmarks(remotebookmarks)
5313 5317 pullopargs[b'remotebookmarks'] = remotebookmarks
5314 5318 for b in opts.get(b'bookmark', []):
5315 5319 b = repo._bookmarks.expandname(b)
5316 5320 if b not in remotebookmarks:
5317 5321 raise error.Abort(_(b'remote bookmark %s not found!') % b)
5318 5322 nodes.append(remotebookmarks[b])
5319 5323 for i, rev in enumerate(revs):
5320 5324 node = fnodes[i].result()
5321 5325 nodes.append(node)
5322 5326 if rev == checkout:
5323 5327 checkout = node
5324 5328
5325 5329 wlock = util.nullcontextmanager()
5326 5330 if opts.get(b'update'):
5327 5331 wlock = repo.wlock()
5328 5332 with wlock:
5329 5333 pullopargs.update(opts.get(b'opargs', {}))
5330 5334 modheads = exchange.pull(
5331 5335 repo,
5332 5336 other,
5333 5337 heads=nodes,
5334 5338 force=opts.get(b'force'),
5335 5339 bookmarks=opts.get(b'bookmark', ()),
5336 5340 opargs=pullopargs,
5337 5341 confirm=opts.get(b'confirm'),
5338 5342 ).cgresult
5339 5343
5340 5344 # brev is a name, which might be a bookmark to be activated at
5341 5345 # the end of the update. In other words, it is an explicit
5342 5346 # destination of the update
5343 5347 brev = None
5344 5348
5345 5349 if checkout:
5346 5350 checkout = repo.unfiltered().changelog.rev(checkout)
5347 5351
5348 5352 # order below depends on implementation of
5349 5353 # hg.addbranchrevs(). opts['bookmark'] is ignored,
5350 5354 # because 'checkout' is determined without it.
5351 5355 if opts.get(b'rev'):
5352 5356 brev = opts[b'rev'][0]
5353 5357 elif opts.get(b'branch'):
5354 5358 brev = opts[b'branch'][0]
5355 5359 else:
5356 5360 brev = branches[0]
5357 5361 repo._subtoppath = source
5358 5362 try:
5359 5363 ret = postincoming(
5360 5364 ui, repo, modheads, opts.get(b'update'), checkout, brev
5361 5365 )
5362 5366 except error.FilteredRepoLookupError as exc:
5363 5367 msg = _(b'cannot update to target: %s') % exc.args[0]
5364 5368 exc.args = (msg,) + exc.args[1:]
5365 5369 raise
5366 5370 finally:
5367 5371 del repo._subtoppath
5368 5372
5369 5373 finally:
5370 5374 other.close()
5371 5375 return ret
5372 5376
5373 5377
5374 5378 @command(
5375 5379 b'push',
5376 5380 [
5377 5381 (b'f', b'force', None, _(b'force push')),
5378 5382 (
5379 5383 b'r',
5380 5384 b'rev',
5381 5385 [],
5382 5386 _(b'a changeset intended to be included in the destination'),
5383 5387 _(b'REV'),
5384 5388 ),
5385 5389 (b'B', b'bookmark', [], _(b"bookmark to push"), _(b'BOOKMARK')),
5386 5390 (
5387 5391 b'b',
5388 5392 b'branch',
5389 5393 [],
5390 5394 _(b'a specific branch you would like to push'),
5391 5395 _(b'BRANCH'),
5392 5396 ),
5393 5397 (b'', b'new-branch', False, _(b'allow pushing a new branch')),
5394 5398 (
5395 5399 b'',
5396 5400 b'pushvars',
5397 5401 [],
5398 5402 _(b'variables that can be sent to server (ADVANCED)'),
5399 5403 ),
5400 5404 (
5401 5405 b'',
5402 5406 b'publish',
5403 5407 False,
5404 5408 _(b'push the changeset as public (EXPERIMENTAL)'),
5405 5409 ),
5406 5410 ]
5407 5411 + remoteopts,
5408 5412 _(b'[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'),
5409 5413 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
5410 5414 helpbasic=True,
5411 5415 )
5412 5416 def push(ui, repo, dest=None, **opts):
5413 5417 """push changes to the specified destination
5414 5418
5415 5419 Push changesets from the local repository to the specified
5416 5420 destination.
5417 5421
5418 5422 This operation is symmetrical to pull: it is identical to a pull
5419 5423 in the destination repository from the current one.
5420 5424
5421 5425 By default, push will not allow creation of new heads at the
5422 5426 destination, since multiple heads would make it unclear which head
5423 5427 to use. In this situation, it is recommended to pull and merge
5424 5428 before pushing.
5425 5429
5426 5430 Use --new-branch if you want to allow push to create a new named
5427 5431 branch that is not present at the destination. This allows you to
5428 5432 only create a new branch without forcing other changes.
5429 5433
5430 5434 .. note::
5431 5435
5432 5436 Extra care should be taken with the -f/--force option,
5433 5437 which will push all new heads on all branches, an action which will
5434 5438 almost always cause confusion for collaborators.
5435 5439
5436 5440 If -r/--rev is used, the specified revision and all its ancestors
5437 5441 will be pushed to the remote repository.
5438 5442
5439 5443 If -B/--bookmark is used, the specified bookmarked revision, its
5440 5444 ancestors, and the bookmark will be pushed to the remote
5441 5445 repository. Specifying ``.`` is equivalent to specifying the active
5442 5446 bookmark's name.
5443 5447
5444 5448 Please see :hg:`help urls` for important details about ``ssh://``
5445 5449 URLs. If DESTINATION is omitted, a default path will be used.
5446 5450
5447 5451 .. container:: verbose
5448 5452
5449 5453 The --pushvars option sends strings to the server that become
5450 5454 environment variables prepended with ``HG_USERVAR_``. For example,
5451 5455 ``--pushvars ENABLE_FEATURE=true``, provides the server side hooks with
5452 5456 ``HG_USERVAR_ENABLE_FEATURE=true`` as part of their environment.
5453 5457
5454 5458 pushvars can provide for user-overridable hooks as well as set debug
5455 5459 levels. One example is having a hook that blocks commits containing
5456 5460 conflict markers, but enables the user to override the hook if the file
5457 5461 is using conflict markers for testing purposes or the file format has
5458 5462 strings that look like conflict markers.
5459 5463
5460 5464 By default, servers will ignore `--pushvars`. To enable it add the
5461 5465 following to your configuration file::
5462 5466
5463 5467 [push]
5464 5468 pushvars.server = true
5465 5469
5466 5470 Returns 0 if push was successful, 1 if nothing to push.
5467 5471 """
5468 5472
5469 5473 opts = pycompat.byteskwargs(opts)
5470 5474 if opts.get(b'bookmark'):
5471 5475 ui.setconfig(b'bookmarks', b'pushing', opts[b'bookmark'], b'push')
5472 5476 for b in opts[b'bookmark']:
5473 5477 # translate -B options to -r so changesets get pushed
5474 5478 b = repo._bookmarks.expandname(b)
5475 5479 if b in repo._bookmarks:
5476 5480 opts.setdefault(b'rev', []).append(b)
5477 5481 else:
5478 5482 # if we try to push a deleted bookmark, translate it to null
5479 5483 # this lets simultaneous -r, -b options continue working
5480 5484 opts.setdefault(b'rev', []).append(b"null")
5481 5485
5482 5486 path = ui.paths.getpath(dest, default=(b'default-push', b'default'))
5483 5487 if not path:
5484 5488 raise error.Abort(
5485 5489 _(b'default repository not configured!'),
5486 5490 hint=_(b"see 'hg help config.paths'"),
5487 5491 )
5488 5492 dest = path.pushloc or path.loc
5489 5493 branches = (path.branch, opts.get(b'branch') or [])
5490 5494 ui.status(_(b'pushing to %s\n') % util.hidepassword(dest))
5491 5495 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get(b'rev'))
5492 5496 other = hg.peer(repo, opts, dest)
5493 5497
5494 5498 if revs:
5495 5499 revs = [repo[r].node() for r in scmutil.revrange(repo, revs)]
5496 5500 if not revs:
5497 5501 raise error.Abort(
5498 5502 _(b"specified revisions evaluate to an empty set"),
5499 5503 hint=_(b"use different revision arguments"),
5500 5504 )
5501 5505 elif path.pushrev:
5502 5506 # It doesn't make any sense to specify ancestor revisions. So limit
5503 5507 # to DAG heads to make discovery simpler.
5504 5508 expr = revsetlang.formatspec(b'heads(%r)', path.pushrev)
5505 5509 revs = scmutil.revrange(repo, [expr])
5506 5510 revs = [repo[rev].node() for rev in revs]
5507 5511 if not revs:
5508 5512 raise error.Abort(
5509 5513 _(b'default push revset for path evaluates to an empty set')
5510 5514 )
5511 5515 elif ui.configbool(b'commands', b'push.require-revs'):
5512 5516 raise error.Abort(
5513 5517 _(b'no revisions specified to push'),
5514 5518 hint=_(b'did you mean "hg push -r ."?'),
5515 5519 )
5516 5520
5517 5521 repo._subtoppath = dest
5518 5522 try:
5519 5523 # push subrepos depth-first for coherent ordering
5520 5524 c = repo[b'.']
5521 5525 subs = c.substate # only repos that are committed
5522 5526 for s in sorted(subs):
5523 5527 result = c.sub(s).push(opts)
5524 5528 if result == 0:
5525 5529 return not result
5526 5530 finally:
5527 5531 del repo._subtoppath
5528 5532
5529 5533 opargs = dict(opts.get(b'opargs', {})) # copy opargs since we may mutate it
5530 5534 opargs.setdefault(b'pushvars', []).extend(opts.get(b'pushvars', []))
5531 5535
5532 5536 pushop = exchange.push(
5533 5537 repo,
5534 5538 other,
5535 5539 opts.get(b'force'),
5536 5540 revs=revs,
5537 5541 newbranch=opts.get(b'new_branch'),
5538 5542 bookmarks=opts.get(b'bookmark', ()),
5539 5543 publish=opts.get(b'publish'),
5540 5544 opargs=opargs,
5541 5545 )
5542 5546
5543 5547 result = not pushop.cgresult
5544 5548
5545 5549 if pushop.bkresult is not None:
5546 5550 if pushop.bkresult == 2:
5547 5551 result = 2
5548 5552 elif not result and pushop.bkresult:
5549 5553 result = 2
5550 5554
5551 5555 return result
5552 5556
5553 5557
5554 5558 @command(
5555 5559 b'recover',
5556 5560 [(b'', b'verify', False, b"run `hg verify` after successful recover"),],
5557 5561 helpcategory=command.CATEGORY_MAINTENANCE,
5558 5562 )
5559 5563 def recover(ui, repo, **opts):
5560 5564 """roll back an interrupted transaction
5561 5565
5562 5566 Recover from an interrupted commit or pull.
5563 5567
5564 5568 This command tries to fix the repository status after an
5565 5569 interrupted operation. It should only be necessary when Mercurial
5566 5570 suggests it.
5567 5571
5568 5572 Returns 0 if successful, 1 if nothing to recover or verify fails.
5569 5573 """
5570 5574 ret = repo.recover()
5571 5575 if ret:
5572 5576 if opts['verify']:
5573 5577 return hg.verify(repo)
5574 5578 else:
5575 5579 msg = _(
5576 5580 b"(verify step skipped, run `hg verify` to check your "
5577 5581 b"repository content)\n"
5578 5582 )
5579 5583 ui.warn(msg)
5580 5584 return 0
5581 5585 return 1
5582 5586
5583 5587
5584 5588 @command(
5585 5589 b'remove|rm',
5586 5590 [
5587 5591 (b'A', b'after', None, _(b'record delete for missing files')),
5588 5592 (b'f', b'force', None, _(b'forget added files, delete modified files')),
5589 5593 ]
5590 5594 + subrepoopts
5591 5595 + walkopts
5592 5596 + dryrunopts,
5593 5597 _(b'[OPTION]... FILE...'),
5594 5598 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5595 5599 helpbasic=True,
5596 5600 inferrepo=True,
5597 5601 )
5598 5602 def remove(ui, repo, *pats, **opts):
5599 5603 """remove the specified files on the next commit
5600 5604
5601 5605 Schedule the indicated files for removal from the current branch.
5602 5606
5603 5607 This command schedules the files to be removed at the next commit.
5604 5608 To undo a remove before that, see :hg:`revert`. To undo added
5605 5609 files, see :hg:`forget`.
5606 5610
5607 5611 .. container:: verbose
5608 5612
5609 5613 -A/--after can be used to remove only files that have already
5610 5614 been deleted, -f/--force can be used to force deletion, and -Af
5611 5615 can be used to remove files from the next revision without
5612 5616 deleting them from the working directory.
5613 5617
5614 5618 The following table details the behavior of remove for different
5615 5619 file states (columns) and option combinations (rows). The file
5616 5620 states are Added [A], Clean [C], Modified [M] and Missing [!]
5617 5621 (as reported by :hg:`status`). The actions are Warn, Remove
5618 5622 (from branch) and Delete (from disk):
5619 5623
5620 5624 ========= == == == ==
5621 5625 opt/state A C M !
5622 5626 ========= == == == ==
5623 5627 none W RD W R
5624 5628 -f R RD RD R
5625 5629 -A W W W R
5626 5630 -Af R R R R
5627 5631 ========= == == == ==
5628 5632
5629 5633 .. note::
5630 5634
5631 5635 :hg:`remove` never deletes files in Added [A] state from the
5632 5636 working directory, not even if ``--force`` is specified.
5633 5637
5634 5638 Returns 0 on success, 1 if any warnings encountered.
5635 5639 """
5636 5640
5637 5641 opts = pycompat.byteskwargs(opts)
5638 5642 after, force = opts.get(b'after'), opts.get(b'force')
5639 5643 dryrun = opts.get(b'dry_run')
5640 5644 if not pats and not after:
5641 5645 raise error.Abort(_(b'no files specified'))
5642 5646
5643 5647 m = scmutil.match(repo[None], pats, opts)
5644 5648 subrepos = opts.get(b'subrepos')
5645 5649 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
5646 5650 return cmdutil.remove(
5647 5651 ui, repo, m, b"", uipathfn, after, force, subrepos, dryrun=dryrun
5648 5652 )
5649 5653
5650 5654
5651 5655 @command(
5652 5656 b'rename|move|mv',
5653 5657 [
5654 5658 (b'A', b'after', None, _(b'record a rename that has already occurred')),
5655 5659 (
5656 5660 b'',
5657 5661 b'at-rev',
5658 5662 b'',
5659 5663 _(b'(un)mark renames in the given revision (EXPERIMENTAL)'),
5660 5664 _(b'REV'),
5661 5665 ),
5662 5666 (
5663 5667 b'f',
5664 5668 b'force',
5665 5669 None,
5666 5670 _(b'forcibly move over an existing managed file'),
5667 5671 ),
5668 5672 ]
5669 5673 + walkopts
5670 5674 + dryrunopts,
5671 5675 _(b'[OPTION]... SOURCE... DEST'),
5672 5676 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5673 5677 )
5674 5678 def rename(ui, repo, *pats, **opts):
5675 5679 """rename files; equivalent of copy + remove
5676 5680
5677 5681 Mark dest as copies of sources; mark sources for deletion. If dest
5678 5682 is a directory, copies are put in that directory. If dest is a
5679 5683 file, there can only be one source.
5680 5684
5681 5685 By default, this command copies the contents of files as they
5682 5686 exist in the working directory. If invoked with -A/--after, the
5683 5687 operation is recorded, but no copying is performed.
5684 5688
5685 5689 This command takes effect at the next commit. To undo a rename
5686 5690 before that, see :hg:`revert`.
5687 5691
5688 5692 Returns 0 on success, 1 if errors are encountered.
5689 5693 """
5690 5694 opts = pycompat.byteskwargs(opts)
5691 5695 with repo.wlock():
5692 5696 return cmdutil.copy(ui, repo, pats, opts, rename=True)
5693 5697
5694 5698
5695 5699 @command(
5696 5700 b'resolve',
5697 5701 [
5698 5702 (b'a', b'all', None, _(b'select all unresolved files')),
5699 5703 (b'l', b'list', None, _(b'list state of files needing merge')),
5700 5704 (b'm', b'mark', None, _(b'mark files as resolved')),
5701 5705 (b'u', b'unmark', None, _(b'mark files as unresolved')),
5702 5706 (b'n', b'no-status', None, _(b'hide status prefix')),
5703 5707 (b'', b're-merge', None, _(b're-merge files')),
5704 5708 ]
5705 5709 + mergetoolopts
5706 5710 + walkopts
5707 5711 + formatteropts,
5708 5712 _(b'[OPTION]... [FILE]...'),
5709 5713 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5710 5714 inferrepo=True,
5711 5715 )
5712 5716 def resolve(ui, repo, *pats, **opts):
5713 5717 """redo merges or set/view the merge status of files
5714 5718
5715 5719 Merges with unresolved conflicts are often the result of
5716 5720 non-interactive merging using the ``internal:merge`` configuration
5717 5721 setting, or a command-line merge tool like ``diff3``. The resolve
5718 5722 command is used to manage the files involved in a merge, after
5719 5723 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
5720 5724 working directory must have two parents). See :hg:`help
5721 5725 merge-tools` for information on configuring merge tools.
5722 5726
5723 5727 The resolve command can be used in the following ways:
5724 5728
5725 5729 - :hg:`resolve [--re-merge] [--tool TOOL] FILE...`: attempt to re-merge
5726 5730 the specified files, discarding any previous merge attempts. Re-merging
5727 5731 is not performed for files already marked as resolved. Use ``--all/-a``
5728 5732 to select all unresolved files. ``--tool`` can be used to specify
5729 5733 the merge tool used for the given files. It overrides the HGMERGE
5730 5734 environment variable and your configuration files. Previous file
5731 5735 contents are saved with a ``.orig`` suffix.
5732 5736
5733 5737 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
5734 5738 (e.g. after having manually fixed-up the files). The default is
5735 5739 to mark all unresolved files.
5736 5740
5737 5741 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
5738 5742 default is to mark all resolved files.
5739 5743
5740 5744 - :hg:`resolve -l`: list files which had or still have conflicts.
5741 5745 In the printed list, ``U`` = unresolved and ``R`` = resolved.
5742 5746 You can use ``set:unresolved()`` or ``set:resolved()`` to filter
5743 5747 the list. See :hg:`help filesets` for details.
5744 5748
5745 5749 .. note::
5746 5750
5747 5751 Mercurial will not let you commit files with unresolved merge
5748 5752 conflicts. You must use :hg:`resolve -m ...` before you can
5749 5753 commit after a conflicting merge.
5750 5754
5751 5755 .. container:: verbose
5752 5756
5753 5757 Template:
5754 5758
5755 5759 The following keywords are supported in addition to the common template
5756 5760 keywords and functions. See also :hg:`help templates`.
5757 5761
5758 5762 :mergestatus: String. Character denoting merge conflicts, ``U`` or ``R``.
5759 5763 :path: String. Repository-absolute path of the file.
5760 5764
5761 5765 Returns 0 on success, 1 if any files fail a resolve attempt.
5762 5766 """
5763 5767
5764 5768 opts = pycompat.byteskwargs(opts)
5765 5769 confirm = ui.configbool(b'commands', b'resolve.confirm')
5766 5770 flaglist = b'all mark unmark list no_status re_merge'.split()
5767 5771 all, mark, unmark, show, nostatus, remerge = [opts.get(o) for o in flaglist]
5768 5772
5769 5773 actioncount = len(list(filter(None, [show, mark, unmark, remerge])))
5770 5774 if actioncount > 1:
5771 5775 raise error.Abort(_(b"too many actions specified"))
5772 5776 elif actioncount == 0 and ui.configbool(
5773 5777 b'commands', b'resolve.explicit-re-merge'
5774 5778 ):
5775 5779 hint = _(b'use --mark, --unmark, --list or --re-merge')
5776 5780 raise error.Abort(_(b'no action specified'), hint=hint)
5777 5781 if pats and all:
5778 5782 raise error.Abort(_(b"can't specify --all and patterns"))
5779 5783 if not (all or pats or show or mark or unmark):
5780 5784 raise error.Abort(
5781 5785 _(b'no files or directories specified'),
5782 5786 hint=b'use --all to re-merge all unresolved files',
5783 5787 )
5784 5788
5785 5789 if confirm:
5786 5790 if all:
5787 5791 if ui.promptchoice(
5788 5792 _(b're-merge all unresolved files (yn)?$$ &Yes $$ &No')
5789 5793 ):
5790 5794 raise error.Abort(_(b'user quit'))
5791 5795 if mark and not pats:
5792 5796 if ui.promptchoice(
5793 5797 _(
5794 5798 b'mark all unresolved files as resolved (yn)?'
5795 5799 b'$$ &Yes $$ &No'
5796 5800 )
5797 5801 ):
5798 5802 raise error.Abort(_(b'user quit'))
5799 5803 if unmark and not pats:
5800 5804 if ui.promptchoice(
5801 5805 _(
5802 5806 b'mark all resolved files as unresolved (yn)?'
5803 5807 b'$$ &Yes $$ &No'
5804 5808 )
5805 5809 ):
5806 5810 raise error.Abort(_(b'user quit'))
5807 5811
5808 5812 uipathfn = scmutil.getuipathfn(repo)
5809 5813
5810 5814 if show:
5811 5815 ui.pager(b'resolve')
5812 5816 fm = ui.formatter(b'resolve', opts)
5813 5817 ms = mergestatemod.mergestate.read(repo)
5814 5818 wctx = repo[None]
5815 5819 m = scmutil.match(wctx, pats, opts)
5816 5820
5817 5821 # Labels and keys based on merge state. Unresolved path conflicts show
5818 5822 # as 'P'. Resolved path conflicts show as 'R', the same as normal
5819 5823 # resolved conflicts.
5820 5824 mergestateinfo = {
5821 5825 mergestatemod.MERGE_RECORD_UNRESOLVED: (
5822 5826 b'resolve.unresolved',
5823 5827 b'U',
5824 5828 ),
5825 5829 mergestatemod.MERGE_RECORD_RESOLVED: (b'resolve.resolved', b'R'),
5826 5830 mergestatemod.MERGE_RECORD_UNRESOLVED_PATH: (
5827 5831 b'resolve.unresolved',
5828 5832 b'P',
5829 5833 ),
5830 5834 mergestatemod.MERGE_RECORD_RESOLVED_PATH: (
5831 5835 b'resolve.resolved',
5832 5836 b'R',
5833 5837 ),
5834 5838 }
5835 5839
5836 5840 for f in ms:
5837 5841 if not m(f):
5838 5842 continue
5839 5843
5840 5844 label, key = mergestateinfo[ms[f]]
5841 5845 fm.startitem()
5842 5846 fm.context(ctx=wctx)
5843 5847 fm.condwrite(not nostatus, b'mergestatus', b'%s ', key, label=label)
5844 5848 fm.data(path=f)
5845 5849 fm.plain(b'%s\n' % uipathfn(f), label=label)
5846 5850 fm.end()
5847 5851 return 0
5848 5852
5849 5853 with repo.wlock():
5850 5854 ms = mergestatemod.mergestate.read(repo)
5851 5855
5852 5856 if not (ms.active() or repo.dirstate.p2() != nullid):
5853 5857 raise error.Abort(
5854 5858 _(b'resolve command not applicable when not merging')
5855 5859 )
5856 5860
5857 5861 wctx = repo[None]
5858 5862 m = scmutil.match(wctx, pats, opts)
5859 5863 ret = 0
5860 5864 didwork = False
5861 5865
5862 5866 tocomplete = []
5863 5867 hasconflictmarkers = []
5864 5868 if mark:
5865 5869 markcheck = ui.config(b'commands', b'resolve.mark-check')
5866 5870 if markcheck not in [b'warn', b'abort']:
5867 5871 # Treat all invalid / unrecognized values as 'none'.
5868 5872 markcheck = False
5869 5873 for f in ms:
5870 5874 if not m(f):
5871 5875 continue
5872 5876
5873 5877 didwork = True
5874 5878
5875 5879 # path conflicts must be resolved manually
5876 5880 if ms[f] in (
5877 5881 mergestatemod.MERGE_RECORD_UNRESOLVED_PATH,
5878 5882 mergestatemod.MERGE_RECORD_RESOLVED_PATH,
5879 5883 ):
5880 5884 if mark:
5881 5885 ms.mark(f, mergestatemod.MERGE_RECORD_RESOLVED_PATH)
5882 5886 elif unmark:
5883 5887 ms.mark(f, mergestatemod.MERGE_RECORD_UNRESOLVED_PATH)
5884 5888 elif ms[f] == mergestatemod.MERGE_RECORD_UNRESOLVED_PATH:
5885 5889 ui.warn(
5886 5890 _(b'%s: path conflict must be resolved manually\n')
5887 5891 % uipathfn(f)
5888 5892 )
5889 5893 continue
5890 5894
5891 5895 if mark:
5892 5896 if markcheck:
5893 5897 fdata = repo.wvfs.tryread(f)
5894 5898 if (
5895 5899 filemerge.hasconflictmarkers(fdata)
5896 5900 and ms[f] != mergestatemod.MERGE_RECORD_RESOLVED
5897 5901 ):
5898 5902 hasconflictmarkers.append(f)
5899 5903 ms.mark(f, mergestatemod.MERGE_RECORD_RESOLVED)
5900 5904 elif unmark:
5901 5905 ms.mark(f, mergestatemod.MERGE_RECORD_UNRESOLVED)
5902 5906 else:
5903 5907 # backup pre-resolve (merge uses .orig for its own purposes)
5904 5908 a = repo.wjoin(f)
5905 5909 try:
5906 5910 util.copyfile(a, a + b".resolve")
5907 5911 except (IOError, OSError) as inst:
5908 5912 if inst.errno != errno.ENOENT:
5909 5913 raise
5910 5914
5911 5915 try:
5912 5916 # preresolve file
5913 5917 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
5914 5918 with ui.configoverride(overrides, b'resolve'):
5915 5919 complete, r = ms.preresolve(f, wctx)
5916 5920 if not complete:
5917 5921 tocomplete.append(f)
5918 5922 elif r:
5919 5923 ret = 1
5920 5924 finally:
5921 5925 ms.commit()
5922 5926
5923 5927 # replace filemerge's .orig file with our resolve file, but only
5924 5928 # for merges that are complete
5925 5929 if complete:
5926 5930 try:
5927 5931 util.rename(
5928 5932 a + b".resolve", scmutil.backuppath(ui, repo, f)
5929 5933 )
5930 5934 except OSError as inst:
5931 5935 if inst.errno != errno.ENOENT:
5932 5936 raise
5933 5937
5934 5938 if hasconflictmarkers:
5935 5939 ui.warn(
5936 5940 _(
5937 5941 b'warning: the following files still have conflict '
5938 5942 b'markers:\n'
5939 5943 )
5940 5944 + b''.join(
5941 5945 b' ' + uipathfn(f) + b'\n' for f in hasconflictmarkers
5942 5946 )
5943 5947 )
5944 5948 if markcheck == b'abort' and not all and not pats:
5945 5949 raise error.Abort(
5946 5950 _(b'conflict markers detected'),
5947 5951 hint=_(b'use --all to mark anyway'),
5948 5952 )
5949 5953
5950 5954 for f in tocomplete:
5951 5955 try:
5952 5956 # resolve file
5953 5957 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
5954 5958 with ui.configoverride(overrides, b'resolve'):
5955 5959 r = ms.resolve(f, wctx)
5956 5960 if r:
5957 5961 ret = 1
5958 5962 finally:
5959 5963 ms.commit()
5960 5964
5961 5965 # replace filemerge's .orig file with our resolve file
5962 5966 a = repo.wjoin(f)
5963 5967 try:
5964 5968 util.rename(a + b".resolve", scmutil.backuppath(ui, repo, f))
5965 5969 except OSError as inst:
5966 5970 if inst.errno != errno.ENOENT:
5967 5971 raise
5968 5972
5969 5973 ms.commit()
5970 5974 branchmerge = repo.dirstate.p2() != nullid
5971 5975 mergestatemod.recordupdates(repo, ms.actions(), branchmerge, None)
5972 5976
5973 5977 if not didwork and pats:
5974 5978 hint = None
5975 5979 if not any([p for p in pats if p.find(b':') >= 0]):
5976 5980 pats = [b'path:%s' % p for p in pats]
5977 5981 m = scmutil.match(wctx, pats, opts)
5978 5982 for f in ms:
5979 5983 if not m(f):
5980 5984 continue
5981 5985
5982 5986 def flag(o):
5983 5987 if o == b're_merge':
5984 5988 return b'--re-merge '
5985 5989 return b'-%s ' % o[0:1]
5986 5990
5987 5991 flags = b''.join([flag(o) for o in flaglist if opts.get(o)])
5988 5992 hint = _(b"(try: hg resolve %s%s)\n") % (
5989 5993 flags,
5990 5994 b' '.join(pats),
5991 5995 )
5992 5996 break
5993 5997 ui.warn(_(b"arguments do not match paths that need resolving\n"))
5994 5998 if hint:
5995 5999 ui.warn(hint)
5996 6000
5997 6001 unresolvedf = list(ms.unresolved())
5998 6002 if not unresolvedf:
5999 6003 ui.status(_(b'(no more unresolved files)\n'))
6000 6004 cmdutil.checkafterresolved(repo)
6001 6005
6002 6006 return ret
6003 6007
6004 6008
6005 6009 @command(
6006 6010 b'revert',
6007 6011 [
6008 6012 (b'a', b'all', None, _(b'revert all changes when no arguments given')),
6009 6013 (b'd', b'date', b'', _(b'tipmost revision matching date'), _(b'DATE')),
6010 6014 (b'r', b'rev', b'', _(b'revert to the specified revision'), _(b'REV')),
6011 6015 (b'C', b'no-backup', None, _(b'do not save backup copies of files')),
6012 6016 (b'i', b'interactive', None, _(b'interactively select the changes')),
6013 6017 ]
6014 6018 + walkopts
6015 6019 + dryrunopts,
6016 6020 _(b'[OPTION]... [-r REV] [NAME]...'),
6017 6021 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6018 6022 )
6019 6023 def revert(ui, repo, *pats, **opts):
6020 6024 """restore files to their checkout state
6021 6025
6022 6026 .. note::
6023 6027
6024 6028 To check out earlier revisions, you should use :hg:`update REV`.
6025 6029 To cancel an uncommitted merge (and lose your changes),
6026 6030 use :hg:`merge --abort`.
6027 6031
6028 6032 With no revision specified, revert the specified files or directories
6029 6033 to the contents they had in the parent of the working directory.
6030 6034 This restores the contents of files to an unmodified
6031 6035 state and unschedules adds, removes, copies, and renames. If the
6032 6036 working directory has two parents, you must explicitly specify a
6033 6037 revision.
6034 6038
6035 6039 Using the -r/--rev or -d/--date options, revert the given files or
6036 6040 directories to their states as of a specific revision. Because
6037 6041 revert does not change the working directory parents, this will
6038 6042 cause these files to appear modified. This can be helpful to "back
6039 6043 out" some or all of an earlier change. See :hg:`backout` for a
6040 6044 related method.
6041 6045
6042 6046 Modified files are saved with a .orig suffix before reverting.
6043 6047 To disable these backups, use --no-backup. It is possible to store
6044 6048 the backup files in a custom directory relative to the root of the
6045 6049 repository by setting the ``ui.origbackuppath`` configuration
6046 6050 option.
6047 6051
6048 6052 See :hg:`help dates` for a list of formats valid for -d/--date.
6049 6053
6050 6054 See :hg:`help backout` for a way to reverse the effect of an
6051 6055 earlier changeset.
6052 6056
6053 6057 Returns 0 on success.
6054 6058 """
6055 6059
6056 6060 opts = pycompat.byteskwargs(opts)
6057 6061 if opts.get(b"date"):
6058 6062 cmdutil.check_incompatible_arguments(opts, b'date', [b'rev'])
6059 6063 opts[b"rev"] = cmdutil.finddate(ui, repo, opts[b"date"])
6060 6064
6061 6065 parent, p2 = repo.dirstate.parents()
6062 6066 if not opts.get(b'rev') and p2 != nullid:
6063 6067 # revert after merge is a trap for new users (issue2915)
6064 6068 raise error.Abort(
6065 6069 _(b'uncommitted merge with no revision specified'),
6066 6070 hint=_(b"use 'hg update' or see 'hg help revert'"),
6067 6071 )
6068 6072
6069 6073 rev = opts.get(b'rev')
6070 6074 if rev:
6071 6075 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
6072 6076 ctx = scmutil.revsingle(repo, rev)
6073 6077
6074 6078 if not (
6075 6079 pats
6076 6080 or opts.get(b'include')
6077 6081 or opts.get(b'exclude')
6078 6082 or opts.get(b'all')
6079 6083 or opts.get(b'interactive')
6080 6084 ):
6081 6085 msg = _(b"no files or directories specified")
6082 6086 if p2 != nullid:
6083 6087 hint = _(
6084 6088 b"uncommitted merge, use --all to discard all changes,"
6085 6089 b" or 'hg update -C .' to abort the merge"
6086 6090 )
6087 6091 raise error.Abort(msg, hint=hint)
6088 6092 dirty = any(repo.status())
6089 6093 node = ctx.node()
6090 6094 if node != parent:
6091 6095 if dirty:
6092 6096 hint = (
6093 6097 _(
6094 6098 b"uncommitted changes, use --all to discard all"
6095 6099 b" changes, or 'hg update %d' to update"
6096 6100 )
6097 6101 % ctx.rev()
6098 6102 )
6099 6103 else:
6100 6104 hint = (
6101 6105 _(
6102 6106 b"use --all to revert all files,"
6103 6107 b" or 'hg update %d' to update"
6104 6108 )
6105 6109 % ctx.rev()
6106 6110 )
6107 6111 elif dirty:
6108 6112 hint = _(b"uncommitted changes, use --all to discard all changes")
6109 6113 else:
6110 6114 hint = _(b"use --all to revert all files")
6111 6115 raise error.Abort(msg, hint=hint)
6112 6116
6113 6117 return cmdutil.revert(ui, repo, ctx, *pats, **pycompat.strkwargs(opts))
6114 6118
6115 6119
6116 6120 @command(
6117 6121 b'rollback',
6118 6122 dryrunopts + [(b'f', b'force', False, _(b'ignore safety measures'))],
6119 6123 helpcategory=command.CATEGORY_MAINTENANCE,
6120 6124 )
6121 6125 def rollback(ui, repo, **opts):
6122 6126 """roll back the last transaction (DANGEROUS) (DEPRECATED)
6123 6127
6124 6128 Please use :hg:`commit --amend` instead of rollback to correct
6125 6129 mistakes in the last commit.
6126 6130
6127 6131 This command should be used with care. There is only one level of
6128 6132 rollback, and there is no way to undo a rollback. It will also
6129 6133 restore the dirstate at the time of the last transaction, losing
6130 6134 any dirstate changes since that time. This command does not alter
6131 6135 the working directory.
6132 6136
6133 6137 Transactions are used to encapsulate the effects of all commands
6134 6138 that create new changesets or propagate existing changesets into a
6135 6139 repository.
6136 6140
6137 6141 .. container:: verbose
6138 6142
6139 6143 For example, the following commands are transactional, and their
6140 6144 effects can be rolled back:
6141 6145
6142 6146 - commit
6143 6147 - import
6144 6148 - pull
6145 6149 - push (with this repository as the destination)
6146 6150 - unbundle
6147 6151
6148 6152 To avoid permanent data loss, rollback will refuse to rollback a
6149 6153 commit transaction if it isn't checked out. Use --force to
6150 6154 override this protection.
6151 6155
6152 6156 The rollback command can be entirely disabled by setting the
6153 6157 ``ui.rollback`` configuration setting to false. If you're here
6154 6158 because you want to use rollback and it's disabled, you can
6155 6159 re-enable the command by setting ``ui.rollback`` to true.
6156 6160
6157 6161 This command is not intended for use on public repositories. Once
6158 6162 changes are visible for pull by other users, rolling a transaction
6159 6163 back locally is ineffective (someone else may already have pulled
6160 6164 the changes). Furthermore, a race is possible with readers of the
6161 6165 repository; for example an in-progress pull from the repository
6162 6166 may fail if a rollback is performed.
6163 6167
6164 6168 Returns 0 on success, 1 if no rollback data is available.
6165 6169 """
6166 6170 if not ui.configbool(b'ui', b'rollback'):
6167 6171 raise error.Abort(
6168 6172 _(b'rollback is disabled because it is unsafe'),
6169 6173 hint=b'see `hg help -v rollback` for information',
6170 6174 )
6171 6175 return repo.rollback(dryrun=opts.get('dry_run'), force=opts.get('force'))
6172 6176
6173 6177
6174 6178 @command(
6175 6179 b'root',
6176 6180 [] + formatteropts,
6177 6181 intents={INTENT_READONLY},
6178 6182 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6179 6183 )
6180 6184 def root(ui, repo, **opts):
6181 6185 """print the root (top) of the current working directory
6182 6186
6183 6187 Print the root directory of the current repository.
6184 6188
6185 6189 .. container:: verbose
6186 6190
6187 6191 Template:
6188 6192
6189 6193 The following keywords are supported in addition to the common template
6190 6194 keywords and functions. See also :hg:`help templates`.
6191 6195
6192 6196 :hgpath: String. Path to the .hg directory.
6193 6197 :storepath: String. Path to the directory holding versioned data.
6194 6198
6195 6199 Returns 0 on success.
6196 6200 """
6197 6201 opts = pycompat.byteskwargs(opts)
6198 6202 with ui.formatter(b'root', opts) as fm:
6199 6203 fm.startitem()
6200 6204 fm.write(b'reporoot', b'%s\n', repo.root)
6201 6205 fm.data(hgpath=repo.path, storepath=repo.spath)
6202 6206
6203 6207
6204 6208 @command(
6205 6209 b'serve',
6206 6210 [
6207 6211 (
6208 6212 b'A',
6209 6213 b'accesslog',
6210 6214 b'',
6211 6215 _(b'name of access log file to write to'),
6212 6216 _(b'FILE'),
6213 6217 ),
6214 6218 (b'd', b'daemon', None, _(b'run server in background')),
6215 6219 (b'', b'daemon-postexec', [], _(b'used internally by daemon mode')),
6216 6220 (
6217 6221 b'E',
6218 6222 b'errorlog',
6219 6223 b'',
6220 6224 _(b'name of error log file to write to'),
6221 6225 _(b'FILE'),
6222 6226 ),
6223 6227 # use string type, then we can check if something was passed
6224 6228 (
6225 6229 b'p',
6226 6230 b'port',
6227 6231 b'',
6228 6232 _(b'port to listen on (default: 8000)'),
6229 6233 _(b'PORT'),
6230 6234 ),
6231 6235 (
6232 6236 b'a',
6233 6237 b'address',
6234 6238 b'',
6235 6239 _(b'address to listen on (default: all interfaces)'),
6236 6240 _(b'ADDR'),
6237 6241 ),
6238 6242 (
6239 6243 b'',
6240 6244 b'prefix',
6241 6245 b'',
6242 6246 _(b'prefix path to serve from (default: server root)'),
6243 6247 _(b'PREFIX'),
6244 6248 ),
6245 6249 (
6246 6250 b'n',
6247 6251 b'name',
6248 6252 b'',
6249 6253 _(b'name to show in web pages (default: working directory)'),
6250 6254 _(b'NAME'),
6251 6255 ),
6252 6256 (
6253 6257 b'',
6254 6258 b'web-conf',
6255 6259 b'',
6256 6260 _(b"name of the hgweb config file (see 'hg help hgweb')"),
6257 6261 _(b'FILE'),
6258 6262 ),
6259 6263 (
6260 6264 b'',
6261 6265 b'webdir-conf',
6262 6266 b'',
6263 6267 _(b'name of the hgweb config file (DEPRECATED)'),
6264 6268 _(b'FILE'),
6265 6269 ),
6266 6270 (
6267 6271 b'',
6268 6272 b'pid-file',
6269 6273 b'',
6270 6274 _(b'name of file to write process ID to'),
6271 6275 _(b'FILE'),
6272 6276 ),
6273 6277 (b'', b'stdio', None, _(b'for remote clients (ADVANCED)')),
6274 6278 (
6275 6279 b'',
6276 6280 b'cmdserver',
6277 6281 b'',
6278 6282 _(b'for remote clients (ADVANCED)'),
6279 6283 _(b'MODE'),
6280 6284 ),
6281 6285 (b't', b'templates', b'', _(b'web templates to use'), _(b'TEMPLATE')),
6282 6286 (b'', b'style', b'', _(b'template style to use'), _(b'STYLE')),
6283 6287 (b'6', b'ipv6', None, _(b'use IPv6 in addition to IPv4')),
6284 6288 (b'', b'certificate', b'', _(b'SSL certificate file'), _(b'FILE')),
6285 6289 (b'', b'print-url', None, _(b'start and print only the URL')),
6286 6290 ]
6287 6291 + subrepoopts,
6288 6292 _(b'[OPTION]...'),
6289 6293 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
6290 6294 helpbasic=True,
6291 6295 optionalrepo=True,
6292 6296 )
6293 6297 def serve(ui, repo, **opts):
6294 6298 """start stand-alone webserver
6295 6299
6296 6300 Start a local HTTP repository browser and pull server. You can use
6297 6301 this for ad-hoc sharing and browsing of repositories. It is
6298 6302 recommended to use a real web server to serve a repository for
6299 6303 longer periods of time.
6300 6304
6301 6305 Please note that the server does not implement access control.
6302 6306 This means that, by default, anybody can read from the server and
6303 6307 nobody can write to it by default. Set the ``web.allow-push``
6304 6308 option to ``*`` to allow everybody to push to the server. You
6305 6309 should use a real web server if you need to authenticate users.
6306 6310
6307 6311 By default, the server logs accesses to stdout and errors to
6308 6312 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
6309 6313 files.
6310 6314
6311 6315 To have the server choose a free port number to listen on, specify
6312 6316 a port number of 0; in this case, the server will print the port
6313 6317 number it uses.
6314 6318
6315 6319 Returns 0 on success.
6316 6320 """
6317 6321
6318 6322 cmdutil.check_incompatible_arguments(opts, 'stdio', ['cmdserver'])
6319 6323 opts = pycompat.byteskwargs(opts)
6320 6324 if opts[b"print_url"] and ui.verbose:
6321 6325 raise error.Abort(_(b"cannot use --print-url with --verbose"))
6322 6326
6323 6327 if opts[b"stdio"]:
6324 6328 if repo is None:
6325 6329 raise error.RepoError(
6326 6330 _(b"there is no Mercurial repository here (.hg not found)")
6327 6331 )
6328 6332 s = wireprotoserver.sshserver(ui, repo)
6329 6333 s.serve_forever()
6330 6334
6331 6335 service = server.createservice(ui, repo, opts)
6332 6336 return server.runservice(opts, initfn=service.init, runfn=service.run)
6333 6337
6334 6338
6335 6339 @command(
6336 6340 b'shelve',
6337 6341 [
6338 6342 (
6339 6343 b'A',
6340 6344 b'addremove',
6341 6345 None,
6342 6346 _(b'mark new/missing files as added/removed before shelving'),
6343 6347 ),
6344 6348 (b'u', b'unknown', None, _(b'store unknown files in the shelve')),
6345 6349 (b'', b'cleanup', None, _(b'delete all shelved changes')),
6346 6350 (
6347 6351 b'',
6348 6352 b'date',
6349 6353 b'',
6350 6354 _(b'shelve with the specified commit date'),
6351 6355 _(b'DATE'),
6352 6356 ),
6353 6357 (b'd', b'delete', None, _(b'delete the named shelved change(s)')),
6354 6358 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
6355 6359 (
6356 6360 b'k',
6357 6361 b'keep',
6358 6362 False,
6359 6363 _(b'shelve, but keep changes in the working directory'),
6360 6364 ),
6361 6365 (b'l', b'list', None, _(b'list current shelves')),
6362 6366 (b'm', b'message', b'', _(b'use text as shelve message'), _(b'TEXT')),
6363 6367 (
6364 6368 b'n',
6365 6369 b'name',
6366 6370 b'',
6367 6371 _(b'use the given name for the shelved commit'),
6368 6372 _(b'NAME'),
6369 6373 ),
6370 6374 (
6371 6375 b'p',
6372 6376 b'patch',
6373 6377 None,
6374 6378 _(
6375 6379 b'output patches for changes (provide the names of the shelved '
6376 6380 b'changes as positional arguments)'
6377 6381 ),
6378 6382 ),
6379 6383 (b'i', b'interactive', None, _(b'interactive mode')),
6380 6384 (
6381 6385 b'',
6382 6386 b'stat',
6383 6387 None,
6384 6388 _(
6385 6389 b'output diffstat-style summary of changes (provide the names of '
6386 6390 b'the shelved changes as positional arguments)'
6387 6391 ),
6388 6392 ),
6389 6393 ]
6390 6394 + cmdutil.walkopts,
6391 6395 _(b'hg shelve [OPTION]... [FILE]...'),
6392 6396 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6393 6397 )
6394 6398 def shelve(ui, repo, *pats, **opts):
6395 6399 '''save and set aside changes from the working directory
6396 6400
6397 6401 Shelving takes files that "hg status" reports as not clean, saves
6398 6402 the modifications to a bundle (a shelved change), and reverts the
6399 6403 files so that their state in the working directory becomes clean.
6400 6404
6401 6405 To restore these changes to the working directory, using "hg
6402 6406 unshelve"; this will work even if you switch to a different
6403 6407 commit.
6404 6408
6405 6409 When no files are specified, "hg shelve" saves all not-clean
6406 6410 files. If specific files or directories are named, only changes to
6407 6411 those files are shelved.
6408 6412
6409 6413 In bare shelve (when no files are specified, without interactive,
6410 6414 include and exclude option), shelving remembers information if the
6411 6415 working directory was on newly created branch, in other words working
6412 6416 directory was on different branch than its first parent. In this
6413 6417 situation unshelving restores branch information to the working directory.
6414 6418
6415 6419 Each shelved change has a name that makes it easier to find later.
6416 6420 The name of a shelved change defaults to being based on the active
6417 6421 bookmark, or if there is no active bookmark, the current named
6418 6422 branch. To specify a different name, use ``--name``.
6419 6423
6420 6424 To see a list of existing shelved changes, use the ``--list``
6421 6425 option. For each shelved change, this will print its name, age,
6422 6426 and description; use ``--patch`` or ``--stat`` for more details.
6423 6427
6424 6428 To delete specific shelved changes, use ``--delete``. To delete
6425 6429 all shelved changes, use ``--cleanup``.
6426 6430 '''
6427 6431 opts = pycompat.byteskwargs(opts)
6428 6432 allowables = [
6429 6433 (b'addremove', {b'create'}), # 'create' is pseudo action
6430 6434 (b'unknown', {b'create'}),
6431 6435 (b'cleanup', {b'cleanup'}),
6432 6436 # ('date', {'create'}), # ignored for passing '--date "0 0"' in tests
6433 6437 (b'delete', {b'delete'}),
6434 6438 (b'edit', {b'create'}),
6435 6439 (b'keep', {b'create'}),
6436 6440 (b'list', {b'list'}),
6437 6441 (b'message', {b'create'}),
6438 6442 (b'name', {b'create'}),
6439 6443 (b'patch', {b'patch', b'list'}),
6440 6444 (b'stat', {b'stat', b'list'}),
6441 6445 ]
6442 6446
6443 6447 def checkopt(opt):
6444 6448 if opts.get(opt):
6445 6449 for i, allowable in allowables:
6446 6450 if opts[i] and opt not in allowable:
6447 6451 raise error.Abort(
6448 6452 _(
6449 6453 b"options '--%s' and '--%s' may not be "
6450 6454 b"used together"
6451 6455 )
6452 6456 % (opt, i)
6453 6457 )
6454 6458 return True
6455 6459
6456 6460 if checkopt(b'cleanup'):
6457 6461 if pats:
6458 6462 raise error.Abort(_(b"cannot specify names when using '--cleanup'"))
6459 6463 return shelvemod.cleanupcmd(ui, repo)
6460 6464 elif checkopt(b'delete'):
6461 6465 return shelvemod.deletecmd(ui, repo, pats)
6462 6466 elif checkopt(b'list'):
6463 6467 return shelvemod.listcmd(ui, repo, pats, opts)
6464 6468 elif checkopt(b'patch') or checkopt(b'stat'):
6465 6469 return shelvemod.patchcmds(ui, repo, pats, opts)
6466 6470 else:
6467 6471 return shelvemod.createcmd(ui, repo, pats, opts)
6468 6472
6469 6473
6470 6474 _NOTTERSE = b'nothing'
6471 6475
6472 6476
6473 6477 @command(
6474 6478 b'status|st',
6475 6479 [
6476 6480 (b'A', b'all', None, _(b'show status of all files')),
6477 6481 (b'm', b'modified', None, _(b'show only modified files')),
6478 6482 (b'a', b'added', None, _(b'show only added files')),
6479 6483 (b'r', b'removed', None, _(b'show only removed files')),
6480 6484 (b'd', b'deleted', None, _(b'show only missing files')),
6481 6485 (b'c', b'clean', None, _(b'show only files without changes')),
6482 6486 (b'u', b'unknown', None, _(b'show only unknown (not tracked) files')),
6483 6487 (b'i', b'ignored', None, _(b'show only ignored files')),
6484 6488 (b'n', b'no-status', None, _(b'hide status prefix')),
6485 6489 (b't', b'terse', _NOTTERSE, _(b'show the terse output (EXPERIMENTAL)')),
6486 6490 (
6487 6491 b'C',
6488 6492 b'copies',
6489 6493 None,
6490 6494 _(b'show source of copied files (DEFAULT: ui.statuscopies)'),
6491 6495 ),
6492 6496 (
6493 6497 b'0',
6494 6498 b'print0',
6495 6499 None,
6496 6500 _(b'end filenames with NUL, for use with xargs'),
6497 6501 ),
6498 6502 (b'', b'rev', [], _(b'show difference from revision'), _(b'REV')),
6499 6503 (
6500 6504 b'',
6501 6505 b'change',
6502 6506 b'',
6503 6507 _(b'list the changed files of a revision'),
6504 6508 _(b'REV'),
6505 6509 ),
6506 6510 ]
6507 6511 + walkopts
6508 6512 + subrepoopts
6509 6513 + formatteropts,
6510 6514 _(b'[OPTION]... [FILE]...'),
6511 6515 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6512 6516 helpbasic=True,
6513 6517 inferrepo=True,
6514 6518 intents={INTENT_READONLY},
6515 6519 )
6516 6520 def status(ui, repo, *pats, **opts):
6517 6521 """show changed files in the working directory
6518 6522
6519 6523 Show status of files in the repository. If names are given, only
6520 6524 files that match are shown. Files that are clean or ignored or
6521 6525 the source of a copy/move operation, are not listed unless
6522 6526 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
6523 6527 Unless options described with "show only ..." are given, the
6524 6528 options -mardu are used.
6525 6529
6526 6530 Option -q/--quiet hides untracked (unknown and ignored) files
6527 6531 unless explicitly requested with -u/--unknown or -i/--ignored.
6528 6532
6529 6533 .. note::
6530 6534
6531 6535 :hg:`status` may appear to disagree with diff if permissions have
6532 6536 changed or a merge has occurred. The standard diff format does
6533 6537 not report permission changes and diff only reports changes
6534 6538 relative to one merge parent.
6535 6539
6536 6540 If one revision is given, it is used as the base revision.
6537 6541 If two revisions are given, the differences between them are
6538 6542 shown. The --change option can also be used as a shortcut to list
6539 6543 the changed files of a revision from its first parent.
6540 6544
6541 6545 The codes used to show the status of files are::
6542 6546
6543 6547 M = modified
6544 6548 A = added
6545 6549 R = removed
6546 6550 C = clean
6547 6551 ! = missing (deleted by non-hg command, but still tracked)
6548 6552 ? = not tracked
6549 6553 I = ignored
6550 6554 = origin of the previous file (with --copies)
6551 6555
6552 6556 .. container:: verbose
6553 6557
6554 6558 The -t/--terse option abbreviates the output by showing only the directory
6555 6559 name if all the files in it share the same status. The option takes an
6556 6560 argument indicating the statuses to abbreviate: 'm' for 'modified', 'a'
6557 6561 for 'added', 'r' for 'removed', 'd' for 'deleted', 'u' for 'unknown', 'i'
6558 6562 for 'ignored' and 'c' for clean.
6559 6563
6560 6564 It abbreviates only those statuses which are passed. Note that clean and
6561 6565 ignored files are not displayed with '--terse ic' unless the -c/--clean
6562 6566 and -i/--ignored options are also used.
6563 6567
6564 6568 The -v/--verbose option shows information when the repository is in an
6565 6569 unfinished merge, shelve, rebase state etc. You can have this behavior
6566 6570 turned on by default by enabling the ``commands.status.verbose`` option.
6567 6571
6568 6572 You can skip displaying some of these states by setting
6569 6573 ``commands.status.skipstates`` to one or more of: 'bisect', 'graft',
6570 6574 'histedit', 'merge', 'rebase', or 'unshelve'.
6571 6575
6572 6576 Template:
6573 6577
6574 6578 The following keywords are supported in addition to the common template
6575 6579 keywords and functions. See also :hg:`help templates`.
6576 6580
6577 6581 :path: String. Repository-absolute path of the file.
6578 6582 :source: String. Repository-absolute path of the file originated from.
6579 6583 Available if ``--copies`` is specified.
6580 6584 :status: String. Character denoting file's status.
6581 6585
6582 6586 Examples:
6583 6587
6584 6588 - show changes in the working directory relative to a
6585 6589 changeset::
6586 6590
6587 6591 hg status --rev 9353
6588 6592
6589 6593 - show changes in the working directory relative to the
6590 6594 current directory (see :hg:`help patterns` for more information)::
6591 6595
6592 6596 hg status re:
6593 6597
6594 6598 - show all changes including copies in an existing changeset::
6595 6599
6596 6600 hg status --copies --change 9353
6597 6601
6598 6602 - get a NUL separated list of added files, suitable for xargs::
6599 6603
6600 6604 hg status -an0
6601 6605
6602 6606 - show more information about the repository status, abbreviating
6603 6607 added, removed, modified, deleted, and untracked paths::
6604 6608
6605 6609 hg status -v -t mardu
6606 6610
6607 6611 Returns 0 on success.
6608 6612
6609 6613 """
6610 6614
6611 6615 cmdutil.check_at_most_one_arg(opts, 'rev', 'change')
6612 6616 opts = pycompat.byteskwargs(opts)
6613 6617 revs = opts.get(b'rev')
6614 6618 change = opts.get(b'change')
6615 6619 terse = opts.get(b'terse')
6616 6620 if terse is _NOTTERSE:
6617 6621 if revs:
6618 6622 terse = b''
6619 6623 else:
6620 6624 terse = ui.config(b'commands', b'status.terse')
6621 6625
6622 6626 if revs and terse:
6623 6627 msg = _(b'cannot use --terse with --rev')
6624 6628 raise error.Abort(msg)
6625 6629 elif change:
6626 6630 repo = scmutil.unhidehashlikerevs(repo, [change], b'nowarn')
6627 6631 ctx2 = scmutil.revsingle(repo, change, None)
6628 6632 ctx1 = ctx2.p1()
6629 6633 else:
6630 6634 repo = scmutil.unhidehashlikerevs(repo, revs, b'nowarn')
6631 6635 ctx1, ctx2 = scmutil.revpair(repo, revs)
6632 6636
6633 6637 forcerelativevalue = None
6634 6638 if ui.hasconfig(b'commands', b'status.relative'):
6635 6639 forcerelativevalue = ui.configbool(b'commands', b'status.relative')
6636 6640 uipathfn = scmutil.getuipathfn(
6637 6641 repo,
6638 6642 legacyrelativevalue=bool(pats),
6639 6643 forcerelativevalue=forcerelativevalue,
6640 6644 )
6641 6645
6642 6646 if opts.get(b'print0'):
6643 6647 end = b'\0'
6644 6648 else:
6645 6649 end = b'\n'
6646 6650 states = b'modified added removed deleted unknown ignored clean'.split()
6647 6651 show = [k for k in states if opts.get(k)]
6648 6652 if opts.get(b'all'):
6649 6653 show += ui.quiet and (states[:4] + [b'clean']) or states
6650 6654
6651 6655 if not show:
6652 6656 if ui.quiet:
6653 6657 show = states[:4]
6654 6658 else:
6655 6659 show = states[:5]
6656 6660
6657 6661 m = scmutil.match(ctx2, pats, opts)
6658 6662 if terse:
6659 6663 # we need to compute clean and unknown to terse
6660 6664 stat = repo.status(
6661 6665 ctx1.node(),
6662 6666 ctx2.node(),
6663 6667 m,
6664 6668 b'ignored' in show or b'i' in terse,
6665 6669 clean=True,
6666 6670 unknown=True,
6667 6671 listsubrepos=opts.get(b'subrepos'),
6668 6672 )
6669 6673
6670 6674 stat = cmdutil.tersedir(stat, terse)
6671 6675 else:
6672 6676 stat = repo.status(
6673 6677 ctx1.node(),
6674 6678 ctx2.node(),
6675 6679 m,
6676 6680 b'ignored' in show,
6677 6681 b'clean' in show,
6678 6682 b'unknown' in show,
6679 6683 opts.get(b'subrepos'),
6680 6684 )
6681 6685
6682 6686 changestates = zip(
6683 6687 states,
6684 6688 pycompat.iterbytestr(b'MAR!?IC'),
6685 6689 [getattr(stat, s.decode('utf8')) for s in states],
6686 6690 )
6687 6691
6688 6692 copy = {}
6689 6693 if (
6690 6694 opts.get(b'all')
6691 6695 or opts.get(b'copies')
6692 6696 or ui.configbool(b'ui', b'statuscopies')
6693 6697 ) and not opts.get(b'no_status'):
6694 6698 copy = copies.pathcopies(ctx1, ctx2, m)
6695 6699
6696 6700 morestatus = None
6697 6701 if (
6698 6702 ui.verbose or ui.configbool(b'commands', b'status.verbose')
6699 6703 ) and not ui.plain():
6700 6704 morestatus = cmdutil.readmorestatus(repo)
6701 6705
6702 6706 ui.pager(b'status')
6703 6707 fm = ui.formatter(b'status', opts)
6704 6708 fmt = b'%s' + end
6705 6709 showchar = not opts.get(b'no_status')
6706 6710
6707 6711 for state, char, files in changestates:
6708 6712 if state in show:
6709 6713 label = b'status.' + state
6710 6714 for f in files:
6711 6715 fm.startitem()
6712 6716 fm.context(ctx=ctx2)
6713 6717 fm.data(itemtype=b'file', path=f)
6714 6718 fm.condwrite(showchar, b'status', b'%s ', char, label=label)
6715 6719 fm.plain(fmt % uipathfn(f), label=label)
6716 6720 if f in copy:
6717 6721 fm.data(source=copy[f])
6718 6722 fm.plain(
6719 6723 (b' %s' + end) % uipathfn(copy[f]),
6720 6724 label=b'status.copied',
6721 6725 )
6722 6726 if morestatus:
6723 6727 morestatus.formatfile(f, fm)
6724 6728
6725 6729 if morestatus:
6726 6730 morestatus.formatfooter(fm)
6727 6731 fm.end()
6728 6732
6729 6733
6730 6734 @command(
6731 6735 b'summary|sum',
6732 6736 [(b'', b'remote', None, _(b'check for push and pull'))],
6733 6737 b'[--remote]',
6734 6738 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6735 6739 helpbasic=True,
6736 6740 intents={INTENT_READONLY},
6737 6741 )
6738 6742 def summary(ui, repo, **opts):
6739 6743 """summarize working directory state
6740 6744
6741 6745 This generates a brief summary of the working directory state,
6742 6746 including parents, branch, commit status, phase and available updates.
6743 6747
6744 6748 With the --remote option, this will check the default paths for
6745 6749 incoming and outgoing changes. This can be time-consuming.
6746 6750
6747 6751 Returns 0 on success.
6748 6752 """
6749 6753
6750 6754 opts = pycompat.byteskwargs(opts)
6751 6755 ui.pager(b'summary')
6752 6756 ctx = repo[None]
6753 6757 parents = ctx.parents()
6754 6758 pnode = parents[0].node()
6755 6759 marks = []
6756 6760
6757 6761 try:
6758 6762 ms = mergestatemod.mergestate.read(repo)
6759 6763 except error.UnsupportedMergeRecords as e:
6760 6764 s = b' '.join(e.recordtypes)
6761 6765 ui.warn(
6762 6766 _(b'warning: merge state has unsupported record types: %s\n') % s
6763 6767 )
6764 6768 unresolved = []
6765 6769 else:
6766 6770 unresolved = list(ms.unresolved())
6767 6771
6768 6772 for p in parents:
6769 6773 # label with log.changeset (instead of log.parent) since this
6770 6774 # shows a working directory parent *changeset*:
6771 6775 # i18n: column positioning for "hg summary"
6772 6776 ui.write(
6773 6777 _(b'parent: %d:%s ') % (p.rev(), p),
6774 6778 label=logcmdutil.changesetlabels(p),
6775 6779 )
6776 6780 ui.write(b' '.join(p.tags()), label=b'log.tag')
6777 6781 if p.bookmarks():
6778 6782 marks.extend(p.bookmarks())
6779 6783 if p.rev() == -1:
6780 6784 if not len(repo):
6781 6785 ui.write(_(b' (empty repository)'))
6782 6786 else:
6783 6787 ui.write(_(b' (no revision checked out)'))
6784 6788 if p.obsolete():
6785 6789 ui.write(_(b' (obsolete)'))
6786 6790 if p.isunstable():
6787 6791 instabilities = (
6788 6792 ui.label(instability, b'trouble.%s' % instability)
6789 6793 for instability in p.instabilities()
6790 6794 )
6791 6795 ui.write(b' (' + b', '.join(instabilities) + b')')
6792 6796 ui.write(b'\n')
6793 6797 if p.description():
6794 6798 ui.status(
6795 6799 b' ' + p.description().splitlines()[0].strip() + b'\n',
6796 6800 label=b'log.summary',
6797 6801 )
6798 6802
6799 6803 branch = ctx.branch()
6800 6804 bheads = repo.branchheads(branch)
6801 6805 # i18n: column positioning for "hg summary"
6802 6806 m = _(b'branch: %s\n') % branch
6803 6807 if branch != b'default':
6804 6808 ui.write(m, label=b'log.branch')
6805 6809 else:
6806 6810 ui.status(m, label=b'log.branch')
6807 6811
6808 6812 if marks:
6809 6813 active = repo._activebookmark
6810 6814 # i18n: column positioning for "hg summary"
6811 6815 ui.write(_(b'bookmarks:'), label=b'log.bookmark')
6812 6816 if active is not None:
6813 6817 if active in marks:
6814 6818 ui.write(b' *' + active, label=bookmarks.activebookmarklabel)
6815 6819 marks.remove(active)
6816 6820 else:
6817 6821 ui.write(b' [%s]' % active, label=bookmarks.activebookmarklabel)
6818 6822 for m in marks:
6819 6823 ui.write(b' ' + m, label=b'log.bookmark')
6820 6824 ui.write(b'\n', label=b'log.bookmark')
6821 6825
6822 6826 status = repo.status(unknown=True)
6823 6827
6824 6828 c = repo.dirstate.copies()
6825 6829 copied, renamed = [], []
6826 6830 for d, s in pycompat.iteritems(c):
6827 6831 if s in status.removed:
6828 6832 status.removed.remove(s)
6829 6833 renamed.append(d)
6830 6834 else:
6831 6835 copied.append(d)
6832 6836 if d in status.added:
6833 6837 status.added.remove(d)
6834 6838
6835 6839 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
6836 6840
6837 6841 labels = [
6838 6842 (ui.label(_(b'%d modified'), b'status.modified'), status.modified),
6839 6843 (ui.label(_(b'%d added'), b'status.added'), status.added),
6840 6844 (ui.label(_(b'%d removed'), b'status.removed'), status.removed),
6841 6845 (ui.label(_(b'%d renamed'), b'status.copied'), renamed),
6842 6846 (ui.label(_(b'%d copied'), b'status.copied'), copied),
6843 6847 (ui.label(_(b'%d deleted'), b'status.deleted'), status.deleted),
6844 6848 (ui.label(_(b'%d unknown'), b'status.unknown'), status.unknown),
6845 6849 (ui.label(_(b'%d unresolved'), b'resolve.unresolved'), unresolved),
6846 6850 (ui.label(_(b'%d subrepos'), b'status.modified'), subs),
6847 6851 ]
6848 6852 t = []
6849 6853 for l, s in labels:
6850 6854 if s:
6851 6855 t.append(l % len(s))
6852 6856
6853 6857 t = b', '.join(t)
6854 6858 cleanworkdir = False
6855 6859
6856 6860 if repo.vfs.exists(b'graftstate'):
6857 6861 t += _(b' (graft in progress)')
6858 6862 if repo.vfs.exists(b'updatestate'):
6859 6863 t += _(b' (interrupted update)')
6860 6864 elif len(parents) > 1:
6861 6865 t += _(b' (merge)')
6862 6866 elif branch != parents[0].branch():
6863 6867 t += _(b' (new branch)')
6864 6868 elif parents[0].closesbranch() and pnode in repo.branchheads(
6865 6869 branch, closed=True
6866 6870 ):
6867 6871 t += _(b' (head closed)')
6868 6872 elif not (
6869 6873 status.modified
6870 6874 or status.added
6871 6875 or status.removed
6872 6876 or renamed
6873 6877 or copied
6874 6878 or subs
6875 6879 ):
6876 6880 t += _(b' (clean)')
6877 6881 cleanworkdir = True
6878 6882 elif pnode not in bheads:
6879 6883 t += _(b' (new branch head)')
6880 6884
6881 6885 if parents:
6882 6886 pendingphase = max(p.phase() for p in parents)
6883 6887 else:
6884 6888 pendingphase = phases.public
6885 6889
6886 6890 if pendingphase > phases.newcommitphase(ui):
6887 6891 t += b' (%s)' % phases.phasenames[pendingphase]
6888 6892
6889 6893 if cleanworkdir:
6890 6894 # i18n: column positioning for "hg summary"
6891 6895 ui.status(_(b'commit: %s\n') % t.strip())
6892 6896 else:
6893 6897 # i18n: column positioning for "hg summary"
6894 6898 ui.write(_(b'commit: %s\n') % t.strip())
6895 6899
6896 6900 # all ancestors of branch heads - all ancestors of parent = new csets
6897 6901 new = len(
6898 6902 repo.changelog.findmissing([pctx.node() for pctx in parents], bheads)
6899 6903 )
6900 6904
6901 6905 if new == 0:
6902 6906 # i18n: column positioning for "hg summary"
6903 6907 ui.status(_(b'update: (current)\n'))
6904 6908 elif pnode not in bheads:
6905 6909 # i18n: column positioning for "hg summary"
6906 6910 ui.write(_(b'update: %d new changesets (update)\n') % new)
6907 6911 else:
6908 6912 # i18n: column positioning for "hg summary"
6909 6913 ui.write(
6910 6914 _(b'update: %d new changesets, %d branch heads (merge)\n')
6911 6915 % (new, len(bheads))
6912 6916 )
6913 6917
6914 6918 t = []
6915 6919 draft = len(repo.revs(b'draft()'))
6916 6920 if draft:
6917 6921 t.append(_(b'%d draft') % draft)
6918 6922 secret = len(repo.revs(b'secret()'))
6919 6923 if secret:
6920 6924 t.append(_(b'%d secret') % secret)
6921 6925
6922 6926 if draft or secret:
6923 6927 ui.status(_(b'phases: %s\n') % b', '.join(t))
6924 6928
6925 6929 if obsolete.isenabled(repo, obsolete.createmarkersopt):
6926 6930 for trouble in (b"orphan", b"contentdivergent", b"phasedivergent"):
6927 6931 numtrouble = len(repo.revs(trouble + b"()"))
6928 6932 # We write all the possibilities to ease translation
6929 6933 troublemsg = {
6930 6934 b"orphan": _(b"orphan: %d changesets"),
6931 6935 b"contentdivergent": _(b"content-divergent: %d changesets"),
6932 6936 b"phasedivergent": _(b"phase-divergent: %d changesets"),
6933 6937 }
6934 6938 if numtrouble > 0:
6935 6939 ui.status(troublemsg[trouble] % numtrouble + b"\n")
6936 6940
6937 6941 cmdutil.summaryhooks(ui, repo)
6938 6942
6939 6943 if opts.get(b'remote'):
6940 6944 needsincoming, needsoutgoing = True, True
6941 6945 else:
6942 6946 needsincoming, needsoutgoing = False, False
6943 6947 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
6944 6948 if i:
6945 6949 needsincoming = True
6946 6950 if o:
6947 6951 needsoutgoing = True
6948 6952 if not needsincoming and not needsoutgoing:
6949 6953 return
6950 6954
6951 6955 def getincoming():
6952 6956 source, branches = hg.parseurl(ui.expandpath(b'default'))
6953 6957 sbranch = branches[0]
6954 6958 try:
6955 6959 other = hg.peer(repo, {}, source)
6956 6960 except error.RepoError:
6957 6961 if opts.get(b'remote'):
6958 6962 raise
6959 6963 return source, sbranch, None, None, None
6960 6964 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
6961 6965 if revs:
6962 6966 revs = [other.lookup(rev) for rev in revs]
6963 6967 ui.debug(b'comparing with %s\n' % util.hidepassword(source))
6964 6968 repo.ui.pushbuffer()
6965 6969 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
6966 6970 repo.ui.popbuffer()
6967 6971 return source, sbranch, other, commoninc, commoninc[1]
6968 6972
6969 6973 if needsincoming:
6970 6974 source, sbranch, sother, commoninc, incoming = getincoming()
6971 6975 else:
6972 6976 source = sbranch = sother = commoninc = incoming = None
6973 6977
6974 6978 def getoutgoing():
6975 6979 dest, branches = hg.parseurl(ui.expandpath(b'default-push', b'default'))
6976 6980 dbranch = branches[0]
6977 6981 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
6978 6982 if source != dest:
6979 6983 try:
6980 6984 dother = hg.peer(repo, {}, dest)
6981 6985 except error.RepoError:
6982 6986 if opts.get(b'remote'):
6983 6987 raise
6984 6988 return dest, dbranch, None, None
6985 6989 ui.debug(b'comparing with %s\n' % util.hidepassword(dest))
6986 6990 elif sother is None:
6987 6991 # there is no explicit destination peer, but source one is invalid
6988 6992 return dest, dbranch, None, None
6989 6993 else:
6990 6994 dother = sother
6991 6995 if source != dest or (sbranch is not None and sbranch != dbranch):
6992 6996 common = None
6993 6997 else:
6994 6998 common = commoninc
6995 6999 if revs:
6996 7000 revs = [repo.lookup(rev) for rev in revs]
6997 7001 repo.ui.pushbuffer()
6998 7002 outgoing = discovery.findcommonoutgoing(
6999 7003 repo, dother, onlyheads=revs, commoninc=common
7000 7004 )
7001 7005 repo.ui.popbuffer()
7002 7006 return dest, dbranch, dother, outgoing
7003 7007
7004 7008 if needsoutgoing:
7005 7009 dest, dbranch, dother, outgoing = getoutgoing()
7006 7010 else:
7007 7011 dest = dbranch = dother = outgoing = None
7008 7012
7009 7013 if opts.get(b'remote'):
7010 7014 t = []
7011 7015 if incoming:
7012 7016 t.append(_(b'1 or more incoming'))
7013 7017 o = outgoing.missing
7014 7018 if o:
7015 7019 t.append(_(b'%d outgoing') % len(o))
7016 7020 other = dother or sother
7017 7021 if b'bookmarks' in other.listkeys(b'namespaces'):
7018 7022 counts = bookmarks.summary(repo, other)
7019 7023 if counts[0] > 0:
7020 7024 t.append(_(b'%d incoming bookmarks') % counts[0])
7021 7025 if counts[1] > 0:
7022 7026 t.append(_(b'%d outgoing bookmarks') % counts[1])
7023 7027
7024 7028 if t:
7025 7029 # i18n: column positioning for "hg summary"
7026 7030 ui.write(_(b'remote: %s\n') % (b', '.join(t)))
7027 7031 else:
7028 7032 # i18n: column positioning for "hg summary"
7029 7033 ui.status(_(b'remote: (synced)\n'))
7030 7034
7031 7035 cmdutil.summaryremotehooks(
7032 7036 ui,
7033 7037 repo,
7034 7038 opts,
7035 7039 (
7036 7040 (source, sbranch, sother, commoninc),
7037 7041 (dest, dbranch, dother, outgoing),
7038 7042 ),
7039 7043 )
7040 7044
7041 7045
7042 7046 @command(
7043 7047 b'tag',
7044 7048 [
7045 7049 (b'f', b'force', None, _(b'force tag')),
7046 7050 (b'l', b'local', None, _(b'make the tag local')),
7047 7051 (b'r', b'rev', b'', _(b'revision to tag'), _(b'REV')),
7048 7052 (b'', b'remove', None, _(b'remove a tag')),
7049 7053 # -l/--local is already there, commitopts cannot be used
7050 7054 (b'e', b'edit', None, _(b'invoke editor on commit messages')),
7051 7055 (b'm', b'message', b'', _(b'use text as commit message'), _(b'TEXT')),
7052 7056 ]
7053 7057 + commitopts2,
7054 7058 _(b'[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'),
7055 7059 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
7056 7060 )
7057 7061 def tag(ui, repo, name1, *names, **opts):
7058 7062 """add one or more tags for the current or given revision
7059 7063
7060 7064 Name a particular revision using <name>.
7061 7065
7062 7066 Tags are used to name particular revisions of the repository and are
7063 7067 very useful to compare different revisions, to go back to significant
7064 7068 earlier versions or to mark branch points as releases, etc. Changing
7065 7069 an existing tag is normally disallowed; use -f/--force to override.
7066 7070
7067 7071 If no revision is given, the parent of the working directory is
7068 7072 used.
7069 7073
7070 7074 To facilitate version control, distribution, and merging of tags,
7071 7075 they are stored as a file named ".hgtags" which is managed similarly
7072 7076 to other project files and can be hand-edited if necessary. This
7073 7077 also means that tagging creates a new commit. The file
7074 7078 ".hg/localtags" is used for local tags (not shared among
7075 7079 repositories).
7076 7080
7077 7081 Tag commits are usually made at the head of a branch. If the parent
7078 7082 of the working directory is not a branch head, :hg:`tag` aborts; use
7079 7083 -f/--force to force the tag commit to be based on a non-head
7080 7084 changeset.
7081 7085
7082 7086 See :hg:`help dates` for a list of formats valid for -d/--date.
7083 7087
7084 7088 Since tag names have priority over branch names during revision
7085 7089 lookup, using an existing branch name as a tag name is discouraged.
7086 7090
7087 7091 Returns 0 on success.
7088 7092 """
7089 7093 cmdutil.check_incompatible_arguments(opts, 'remove', ['rev'])
7090 7094 opts = pycompat.byteskwargs(opts)
7091 7095 with repo.wlock(), repo.lock():
7092 7096 rev_ = b"."
7093 7097 names = [t.strip() for t in (name1,) + names]
7094 7098 if len(names) != len(set(names)):
7095 7099 raise error.Abort(_(b'tag names must be unique'))
7096 7100 for n in names:
7097 7101 scmutil.checknewlabel(repo, n, b'tag')
7098 7102 if not n:
7099 7103 raise error.Abort(
7100 7104 _(b'tag names cannot consist entirely of whitespace')
7101 7105 )
7102 7106 if opts.get(b'rev'):
7103 7107 rev_ = opts[b'rev']
7104 7108 message = opts.get(b'message')
7105 7109 if opts.get(b'remove'):
7106 7110 if opts.get(b'local'):
7107 7111 expectedtype = b'local'
7108 7112 else:
7109 7113 expectedtype = b'global'
7110 7114
7111 7115 for n in names:
7112 7116 if repo.tagtype(n) == b'global':
7113 7117 alltags = tagsmod.findglobaltags(ui, repo)
7114 7118 if alltags[n][0] == nullid:
7115 7119 raise error.Abort(_(b"tag '%s' is already removed") % n)
7116 7120 if not repo.tagtype(n):
7117 7121 raise error.Abort(_(b"tag '%s' does not exist") % n)
7118 7122 if repo.tagtype(n) != expectedtype:
7119 7123 if expectedtype == b'global':
7120 7124 raise error.Abort(
7121 7125 _(b"tag '%s' is not a global tag") % n
7122 7126 )
7123 7127 else:
7124 7128 raise error.Abort(_(b"tag '%s' is not a local tag") % n)
7125 7129 rev_ = b'null'
7126 7130 if not message:
7127 7131 # we don't translate commit messages
7128 7132 message = b'Removed tag %s' % b', '.join(names)
7129 7133 elif not opts.get(b'force'):
7130 7134 for n in names:
7131 7135 if n in repo.tags():
7132 7136 raise error.Abort(
7133 7137 _(b"tag '%s' already exists (use -f to force)") % n
7134 7138 )
7135 7139 if not opts.get(b'local'):
7136 7140 p1, p2 = repo.dirstate.parents()
7137 7141 if p2 != nullid:
7138 7142 raise error.Abort(_(b'uncommitted merge'))
7139 7143 bheads = repo.branchheads()
7140 7144 if not opts.get(b'force') and bheads and p1 not in bheads:
7141 7145 raise error.Abort(
7142 7146 _(
7143 7147 b'working directory is not at a branch head '
7144 7148 b'(use -f to force)'
7145 7149 )
7146 7150 )
7147 7151 node = scmutil.revsingle(repo, rev_).node()
7148 7152
7149 7153 if not message:
7150 7154 # we don't translate commit messages
7151 7155 message = b'Added tag %s for changeset %s' % (
7152 7156 b', '.join(names),
7153 7157 short(node),
7154 7158 )
7155 7159
7156 7160 date = opts.get(b'date')
7157 7161 if date:
7158 7162 date = dateutil.parsedate(date)
7159 7163
7160 7164 if opts.get(b'remove'):
7161 7165 editform = b'tag.remove'
7162 7166 else:
7163 7167 editform = b'tag.add'
7164 7168 editor = cmdutil.getcommiteditor(
7165 7169 editform=editform, **pycompat.strkwargs(opts)
7166 7170 )
7167 7171
7168 7172 # don't allow tagging the null rev
7169 7173 if (
7170 7174 not opts.get(b'remove')
7171 7175 and scmutil.revsingle(repo, rev_).rev() == nullrev
7172 7176 ):
7173 7177 raise error.Abort(_(b"cannot tag null revision"))
7174 7178
7175 7179 tagsmod.tag(
7176 7180 repo,
7177 7181 names,
7178 7182 node,
7179 7183 message,
7180 7184 opts.get(b'local'),
7181 7185 opts.get(b'user'),
7182 7186 date,
7183 7187 editor=editor,
7184 7188 )
7185 7189
7186 7190
7187 7191 @command(
7188 7192 b'tags',
7189 7193 formatteropts,
7190 7194 b'',
7191 7195 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
7192 7196 intents={INTENT_READONLY},
7193 7197 )
7194 7198 def tags(ui, repo, **opts):
7195 7199 """list repository tags
7196 7200
7197 7201 This lists both regular and local tags. When the -v/--verbose
7198 7202 switch is used, a third column "local" is printed for local tags.
7199 7203 When the -q/--quiet switch is used, only the tag name is printed.
7200 7204
7201 7205 .. container:: verbose
7202 7206
7203 7207 Template:
7204 7208
7205 7209 The following keywords are supported in addition to the common template
7206 7210 keywords and functions such as ``{tag}``. See also
7207 7211 :hg:`help templates`.
7208 7212
7209 7213 :type: String. ``local`` for local tags.
7210 7214
7211 7215 Returns 0 on success.
7212 7216 """
7213 7217
7214 7218 opts = pycompat.byteskwargs(opts)
7215 7219 ui.pager(b'tags')
7216 7220 fm = ui.formatter(b'tags', opts)
7217 7221 hexfunc = fm.hexfunc
7218 7222
7219 7223 for t, n in reversed(repo.tagslist()):
7220 7224 hn = hexfunc(n)
7221 7225 label = b'tags.normal'
7222 7226 tagtype = b''
7223 7227 if repo.tagtype(t) == b'local':
7224 7228 label = b'tags.local'
7225 7229 tagtype = b'local'
7226 7230
7227 7231 fm.startitem()
7228 7232 fm.context(repo=repo)
7229 7233 fm.write(b'tag', b'%s', t, label=label)
7230 7234 fmt = b" " * (30 - encoding.colwidth(t)) + b' %5d:%s'
7231 7235 fm.condwrite(
7232 7236 not ui.quiet,
7233 7237 b'rev node',
7234 7238 fmt,
7235 7239 repo.changelog.rev(n),
7236 7240 hn,
7237 7241 label=label,
7238 7242 )
7239 7243 fm.condwrite(
7240 7244 ui.verbose and tagtype, b'type', b' %s', tagtype, label=label
7241 7245 )
7242 7246 fm.plain(b'\n')
7243 7247 fm.end()
7244 7248
7245 7249
7246 7250 @command(
7247 7251 b'tip',
7248 7252 [
7249 7253 (b'p', b'patch', None, _(b'show patch')),
7250 7254 (b'g', b'git', None, _(b'use git extended diff format')),
7251 7255 ]
7252 7256 + templateopts,
7253 7257 _(b'[-p] [-g]'),
7254 7258 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
7255 7259 )
7256 7260 def tip(ui, repo, **opts):
7257 7261 """show the tip revision (DEPRECATED)
7258 7262
7259 7263 The tip revision (usually just called the tip) is the changeset
7260 7264 most recently added to the repository (and therefore the most
7261 7265 recently changed head).
7262 7266
7263 7267 If you have just made a commit, that commit will be the tip. If
7264 7268 you have just pulled changes from another repository, the tip of
7265 7269 that repository becomes the current tip. The "tip" tag is special
7266 7270 and cannot be renamed or assigned to a different changeset.
7267 7271
7268 7272 This command is deprecated, please use :hg:`heads` instead.
7269 7273
7270 7274 Returns 0 on success.
7271 7275 """
7272 7276 opts = pycompat.byteskwargs(opts)
7273 7277 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
7274 7278 displayer.show(repo[b'tip'])
7275 7279 displayer.close()
7276 7280
7277 7281
7278 7282 @command(
7279 7283 b'unbundle',
7280 7284 [
7281 7285 (
7282 7286 b'u',
7283 7287 b'update',
7284 7288 None,
7285 7289 _(b'update to new branch head if changesets were unbundled'),
7286 7290 )
7287 7291 ],
7288 7292 _(b'[-u] FILE...'),
7289 7293 helpcategory=command.CATEGORY_IMPORT_EXPORT,
7290 7294 )
7291 7295 def unbundle(ui, repo, fname1, *fnames, **opts):
7292 7296 """apply one or more bundle files
7293 7297
7294 7298 Apply one or more bundle files generated by :hg:`bundle`.
7295 7299
7296 7300 Returns 0 on success, 1 if an update has unresolved files.
7297 7301 """
7298 7302 fnames = (fname1,) + fnames
7299 7303
7300 7304 with repo.lock():
7301 7305 for fname in fnames:
7302 7306 f = hg.openpath(ui, fname)
7303 7307 gen = exchange.readbundle(ui, f, fname)
7304 7308 if isinstance(gen, streamclone.streamcloneapplier):
7305 7309 raise error.Abort(
7306 7310 _(
7307 7311 b'packed bundles cannot be applied with '
7308 7312 b'"hg unbundle"'
7309 7313 ),
7310 7314 hint=_(b'use "hg debugapplystreamclonebundle"'),
7311 7315 )
7312 7316 url = b'bundle:' + fname
7313 7317 try:
7314 7318 txnname = b'unbundle'
7315 7319 if not isinstance(gen, bundle2.unbundle20):
7316 7320 txnname = b'unbundle\n%s' % util.hidepassword(url)
7317 7321 with repo.transaction(txnname) as tr:
7318 7322 op = bundle2.applybundle(
7319 7323 repo, gen, tr, source=b'unbundle', url=url
7320 7324 )
7321 7325 except error.BundleUnknownFeatureError as exc:
7322 7326 raise error.Abort(
7323 7327 _(b'%s: unknown bundle feature, %s') % (fname, exc),
7324 7328 hint=_(
7325 7329 b"see https://mercurial-scm.org/"
7326 7330 b"wiki/BundleFeature for more "
7327 7331 b"information"
7328 7332 ),
7329 7333 )
7330 7334 modheads = bundle2.combinechangegroupresults(op)
7331 7335
7332 7336 return postincoming(ui, repo, modheads, opts.get('update'), None, None)
7333 7337
7334 7338
7335 7339 @command(
7336 7340 b'unshelve',
7337 7341 [
7338 7342 (b'a', b'abort', None, _(b'abort an incomplete unshelve operation')),
7339 7343 (
7340 7344 b'c',
7341 7345 b'continue',
7342 7346 None,
7343 7347 _(b'continue an incomplete unshelve operation'),
7344 7348 ),
7345 7349 (b'i', b'interactive', None, _(b'use interactive mode (EXPERIMENTAL)')),
7346 7350 (b'k', b'keep', None, _(b'keep shelve after unshelving')),
7347 7351 (
7348 7352 b'n',
7349 7353 b'name',
7350 7354 b'',
7351 7355 _(b'restore shelved change with given name'),
7352 7356 _(b'NAME'),
7353 7357 ),
7354 7358 (b't', b'tool', b'', _(b'specify merge tool')),
7355 7359 (
7356 7360 b'',
7357 7361 b'date',
7358 7362 b'',
7359 7363 _(b'set date for temporary commits (DEPRECATED)'),
7360 7364 _(b'DATE'),
7361 7365 ),
7362 7366 ],
7363 7367 _(b'hg unshelve [OPTION]... [[-n] SHELVED]'),
7364 7368 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
7365 7369 )
7366 7370 def unshelve(ui, repo, *shelved, **opts):
7367 7371 """restore a shelved change to the working directory
7368 7372
7369 7373 This command accepts an optional name of a shelved change to
7370 7374 restore. If none is given, the most recent shelved change is used.
7371 7375
7372 7376 If a shelved change is applied successfully, the bundle that
7373 7377 contains the shelved changes is moved to a backup location
7374 7378 (.hg/shelve-backup).
7375 7379
7376 7380 Since you can restore a shelved change on top of an arbitrary
7377 7381 commit, it is possible that unshelving will result in a conflict
7378 7382 between your changes and the commits you are unshelving onto. If
7379 7383 this occurs, you must resolve the conflict, then use
7380 7384 ``--continue`` to complete the unshelve operation. (The bundle
7381 7385 will not be moved until you successfully complete the unshelve.)
7382 7386
7383 7387 (Alternatively, you can use ``--abort`` to abandon an unshelve
7384 7388 that causes a conflict. This reverts the unshelved changes, and
7385 7389 leaves the bundle in place.)
7386 7390
7387 7391 If bare shelved change (without interactive, include and exclude
7388 7392 option) was done on newly created branch it would restore branch
7389 7393 information to the working directory.
7390 7394
7391 7395 After a successful unshelve, the shelved changes are stored in a
7392 7396 backup directory. Only the N most recent backups are kept. N
7393 7397 defaults to 10 but can be overridden using the ``shelve.maxbackups``
7394 7398 configuration option.
7395 7399
7396 7400 .. container:: verbose
7397 7401
7398 7402 Timestamp in seconds is used to decide order of backups. More
7399 7403 than ``maxbackups`` backups are kept, if same timestamp
7400 7404 prevents from deciding exact order of them, for safety.
7401 7405
7402 7406 Selected changes can be unshelved with ``--interactive`` flag.
7403 7407 The working directory is updated with the selected changes, and
7404 7408 only the unselected changes remain shelved.
7405 7409 Note: The whole shelve is applied to working directory first before
7406 7410 running interactively. So, this will bring up all the conflicts between
7407 7411 working directory and the shelve, irrespective of which changes will be
7408 7412 unshelved.
7409 7413 """
7410 7414 with repo.wlock():
7411 7415 return shelvemod.unshelvecmd(ui, repo, *shelved, **opts)
7412 7416
7413 7417
7414 7418 statemod.addunfinished(
7415 7419 b'unshelve',
7416 7420 fname=b'shelvedstate',
7417 7421 continueflag=True,
7418 7422 abortfunc=shelvemod.hgabortunshelve,
7419 7423 continuefunc=shelvemod.hgcontinueunshelve,
7420 7424 cmdmsg=_(b'unshelve already in progress'),
7421 7425 )
7422 7426
7423 7427
7424 7428 @command(
7425 7429 b'update|up|checkout|co',
7426 7430 [
7427 7431 (b'C', b'clean', None, _(b'discard uncommitted changes (no backup)')),
7428 7432 (b'c', b'check', None, _(b'require clean working directory')),
7429 7433 (b'm', b'merge', None, _(b'merge uncommitted changes')),
7430 7434 (b'd', b'date', b'', _(b'tipmost revision matching date'), _(b'DATE')),
7431 7435 (b'r', b'rev', b'', _(b'revision'), _(b'REV')),
7432 7436 ]
7433 7437 + mergetoolopts,
7434 7438 _(b'[-C|-c|-m] [-d DATE] [[-r] REV]'),
7435 7439 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
7436 7440 helpbasic=True,
7437 7441 )
7438 7442 def update(ui, repo, node=None, **opts):
7439 7443 """update working directory (or switch revisions)
7440 7444
7441 7445 Update the repository's working directory to the specified
7442 7446 changeset. If no changeset is specified, update to the tip of the
7443 7447 current named branch and move the active bookmark (see :hg:`help
7444 7448 bookmarks`).
7445 7449
7446 7450 Update sets the working directory's parent revision to the specified
7447 7451 changeset (see :hg:`help parents`).
7448 7452
7449 7453 If the changeset is not a descendant or ancestor of the working
7450 7454 directory's parent and there are uncommitted changes, the update is
7451 7455 aborted. With the -c/--check option, the working directory is checked
7452 7456 for uncommitted changes; if none are found, the working directory is
7453 7457 updated to the specified changeset.
7454 7458
7455 7459 .. container:: verbose
7456 7460
7457 7461 The -C/--clean, -c/--check, and -m/--merge options control what
7458 7462 happens if the working directory contains uncommitted changes.
7459 7463 At most of one of them can be specified.
7460 7464
7461 7465 1. If no option is specified, and if
7462 7466 the requested changeset is an ancestor or descendant of
7463 7467 the working directory's parent, the uncommitted changes
7464 7468 are merged into the requested changeset and the merged
7465 7469 result is left uncommitted. If the requested changeset is
7466 7470 not an ancestor or descendant (that is, it is on another
7467 7471 branch), the update is aborted and the uncommitted changes
7468 7472 are preserved.
7469 7473
7470 7474 2. With the -m/--merge option, the update is allowed even if the
7471 7475 requested changeset is not an ancestor or descendant of
7472 7476 the working directory's parent.
7473 7477
7474 7478 3. With the -c/--check option, the update is aborted and the
7475 7479 uncommitted changes are preserved.
7476 7480
7477 7481 4. With the -C/--clean option, uncommitted changes are discarded and
7478 7482 the working directory is updated to the requested changeset.
7479 7483
7480 7484 To cancel an uncommitted merge (and lose your changes), use
7481 7485 :hg:`merge --abort`.
7482 7486
7483 7487 Use null as the changeset to remove the working directory (like
7484 7488 :hg:`clone -U`).
7485 7489
7486 7490 If you want to revert just one file to an older revision, use
7487 7491 :hg:`revert [-r REV] NAME`.
7488 7492
7489 7493 See :hg:`help dates` for a list of formats valid for -d/--date.
7490 7494
7491 7495 Returns 0 on success, 1 if there are unresolved files.
7492 7496 """
7493 7497 cmdutil.check_at_most_one_arg(opts, 'clean', 'check', 'merge')
7494 7498 rev = opts.get('rev')
7495 7499 date = opts.get('date')
7496 7500 clean = opts.get('clean')
7497 7501 check = opts.get('check')
7498 7502 merge = opts.get('merge')
7499 7503 if rev and node:
7500 7504 raise error.Abort(_(b"please specify just one revision"))
7501 7505
7502 7506 if ui.configbool(b'commands', b'update.requiredest'):
7503 7507 if not node and not rev and not date:
7504 7508 raise error.Abort(
7505 7509 _(b'you must specify a destination'),
7506 7510 hint=_(b'for example: hg update ".::"'),
7507 7511 )
7508 7512
7509 7513 if rev is None or rev == b'':
7510 7514 rev = node
7511 7515
7512 7516 if date and rev is not None:
7513 7517 raise error.Abort(_(b"you can't specify a revision and a date"))
7514 7518
7515 7519 updatecheck = None
7516 7520 if check:
7517 7521 updatecheck = b'abort'
7518 7522 elif merge:
7519 7523 updatecheck = b'none'
7520 7524
7521 7525 with repo.wlock():
7522 7526 cmdutil.clearunfinished(repo)
7523 7527 if date:
7524 7528 rev = cmdutil.finddate(ui, repo, date)
7525 7529
7526 7530 # if we defined a bookmark, we have to remember the original name
7527 7531 brev = rev
7528 7532 if rev:
7529 7533 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
7530 7534 ctx = scmutil.revsingle(repo, rev, default=None)
7531 7535 rev = ctx.rev()
7532 7536 hidden = ctx.hidden()
7533 7537 overrides = {(b'ui', b'forcemerge'): opts.get('tool', b'')}
7534 7538 with ui.configoverride(overrides, b'update'):
7535 7539 ret = hg.updatetotally(
7536 7540 ui, repo, rev, brev, clean=clean, updatecheck=updatecheck
7537 7541 )
7538 7542 if hidden:
7539 7543 ctxstr = ctx.hex()[:12]
7540 7544 ui.warn(_(b"updated to hidden changeset %s\n") % ctxstr)
7541 7545
7542 7546 if ctx.obsolete():
7543 7547 obsfatemsg = obsutil._getfilteredreason(repo, ctxstr, ctx)
7544 7548 ui.warn(b"(%s)\n" % obsfatemsg)
7545 7549 return ret
7546 7550
7547 7551
7548 7552 @command(
7549 7553 b'verify',
7550 7554 [(b'', b'full', False, b'perform more checks (EXPERIMENTAL)')],
7551 7555 helpcategory=command.CATEGORY_MAINTENANCE,
7552 7556 )
7553 7557 def verify(ui, repo, **opts):
7554 7558 """verify the integrity of the repository
7555 7559
7556 7560 Verify the integrity of the current repository.
7557 7561
7558 7562 This will perform an extensive check of the repository's
7559 7563 integrity, validating the hashes and checksums of each entry in
7560 7564 the changelog, manifest, and tracked files, as well as the
7561 7565 integrity of their crosslinks and indices.
7562 7566
7563 7567 Please see https://mercurial-scm.org/wiki/RepositoryCorruption
7564 7568 for more information about recovery from corruption of the
7565 7569 repository.
7566 7570
7567 7571 Returns 0 on success, 1 if errors are encountered.
7568 7572 """
7569 7573 opts = pycompat.byteskwargs(opts)
7570 7574
7571 7575 level = None
7572 7576 if opts[b'full']:
7573 7577 level = verifymod.VERIFY_FULL
7574 7578 return hg.verify(repo, level)
7575 7579
7576 7580
7577 7581 @command(
7578 7582 b'version',
7579 7583 [] + formatteropts,
7580 7584 helpcategory=command.CATEGORY_HELP,
7581 7585 norepo=True,
7582 7586 intents={INTENT_READONLY},
7583 7587 )
7584 7588 def version_(ui, **opts):
7585 7589 """output version and copyright information
7586 7590
7587 7591 .. container:: verbose
7588 7592
7589 7593 Template:
7590 7594
7591 7595 The following keywords are supported. See also :hg:`help templates`.
7592 7596
7593 7597 :extensions: List of extensions.
7594 7598 :ver: String. Version number.
7595 7599
7596 7600 And each entry of ``{extensions}`` provides the following sub-keywords
7597 7601 in addition to ``{ver}``.
7598 7602
7599 7603 :bundled: Boolean. True if included in the release.
7600 7604 :name: String. Extension name.
7601 7605 """
7602 7606 opts = pycompat.byteskwargs(opts)
7603 7607 if ui.verbose:
7604 7608 ui.pager(b'version')
7605 7609 fm = ui.formatter(b"version", opts)
7606 7610 fm.startitem()
7607 7611 fm.write(
7608 7612 b"ver", _(b"Mercurial Distributed SCM (version %s)\n"), util.version()
7609 7613 )
7610 7614 license = _(
7611 7615 b"(see https://mercurial-scm.org for more information)\n"
7612 7616 b"\nCopyright (C) 2005-2020 Matt Mackall and others\n"
7613 7617 b"This is free software; see the source for copying conditions. "
7614 7618 b"There is NO\nwarranty; "
7615 7619 b"not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
7616 7620 )
7617 7621 if not ui.quiet:
7618 7622 fm.plain(license)
7619 7623
7620 7624 if ui.verbose:
7621 7625 fm.plain(_(b"\nEnabled extensions:\n\n"))
7622 7626 # format names and versions into columns
7623 7627 names = []
7624 7628 vers = []
7625 7629 isinternals = []
7626 7630 for name, module in sorted(extensions.extensions()):
7627 7631 names.append(name)
7628 7632 vers.append(extensions.moduleversion(module) or None)
7629 7633 isinternals.append(extensions.ismoduleinternal(module))
7630 7634 fn = fm.nested(b"extensions", tmpl=b'{name}\n')
7631 7635 if names:
7632 7636 namefmt = b" %%-%ds " % max(len(n) for n in names)
7633 7637 places = [_(b"external"), _(b"internal")]
7634 7638 for n, v, p in zip(names, vers, isinternals):
7635 7639 fn.startitem()
7636 7640 fn.condwrite(ui.verbose, b"name", namefmt, n)
7637 7641 if ui.verbose:
7638 7642 fn.plain(b"%s " % places[p])
7639 7643 fn.data(bundled=p)
7640 7644 fn.condwrite(ui.verbose and v, b"ver", b"%s", v)
7641 7645 if ui.verbose:
7642 7646 fn.plain(b"\n")
7643 7647 fn.end()
7644 7648 fm.end()
7645 7649
7646 7650
7647 7651 def loadcmdtable(ui, name, cmdtable):
7648 7652 """Load command functions from specified cmdtable
7649 7653 """
7650 7654 overrides = [cmd for cmd in cmdtable if cmd in table]
7651 7655 if overrides:
7652 7656 ui.warn(
7653 7657 _(b"extension '%s' overrides commands: %s\n")
7654 7658 % (name, b" ".join(overrides))
7655 7659 )
7656 7660 table.update(cmdtable)
@@ -1,823 +1,823 b''
1 1 $ hg init basic
2 2 $ cd basic
3 3
4 4 should complain
5 5
6 6 $ hg backout
7 7 abort: please specify a revision to backout
8 8 [255]
9 9 $ hg backout -r 0 0
10 10 abort: please specify just one revision
11 11 [255]
12 12
13 13 basic operation
14 14 (this also tests that editor is invoked if the commit message is not
15 15 specified explicitly)
16 16
17 17 $ echo a > a
18 18 $ hg commit -d '0 0' -A -m a
19 19 adding a
20 20 $ echo b >> a
21 21 $ hg commit -d '1 0' -m b
22 22
23 23 $ hg status --rev tip --rev "tip^1"
24 24 M a
25 25 $ HGEDITOR=cat hg backout -d '2 0' tip --tool=true
26 26 reverting a
27 27 Backed out changeset a820f4f40a57
28 28
29 29
30 30 HG: Enter commit message. Lines beginning with 'HG:' are removed.
31 31 HG: Leave message empty to abort commit.
32 32 HG: --
33 33 HG: user: test
34 34 HG: branch 'default'
35 35 HG: changed a
36 36 changeset 2:2929462c3dff backs out changeset 1:a820f4f40a57
37 37 $ cat a
38 38 a
39 39 $ hg summary
40 40 parent: 2:2929462c3dff tip
41 41 Backed out changeset a820f4f40a57
42 42 branch: default
43 43 commit: (clean)
44 44 update: (current)
45 45 phases: 3 draft
46 46
47 47 commit option
48 48
49 49 $ cd ..
50 50 $ hg init commit
51 51 $ cd commit
52 52
53 53 $ echo tomatoes > a
54 54 $ hg add a
55 55 $ hg commit -d '0 0' -m tomatoes
56 56
57 57 $ echo chair > b
58 58 $ hg add b
59 59 $ hg commit -d '1 0' -m chair
60 60
61 61 $ echo grapes >> a
62 62 $ hg commit -d '2 0' -m grapes
63 63
64 64 $ hg backout -d '4 0' 1 --tool=:fail
65 65 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
66 66 changeset 3:1c2161e97c0a backs out changeset 1:22cb4f70d813
67 67 $ hg summary
68 68 parent: 3:1c2161e97c0a tip
69 69 Backed out changeset 22cb4f70d813
70 70 branch: default
71 71 commit: (clean)
72 72 update: (current)
73 73 phases: 4 draft
74 74
75 75 $ echo ypples > a
76 76 $ hg commit -d '5 0' -m ypples
77 77
78 78 $ hg backout -d '6 0' 2 --tool=:fail
79 79 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
80 80 use 'hg resolve' to retry unresolved file merges
81 81 [1]
82 82 $ hg summary
83 83 parent: 4:ed99997b793d tip
84 84 ypples
85 85 branch: default
86 86 commit: 1 unresolved (clean)
87 87 update: (current)
88 88 phases: 5 draft
89 89 $ hg log -G
90 90 @ changeset: 4:ed99997b793d
91 91 | tag: tip
92 92 | user: test
93 93 | date: Thu Jan 01 00:00:05 1970 +0000
94 94 | summary: ypples
95 95 |
96 96 o changeset: 3:1c2161e97c0a
97 97 | user: test
98 98 | date: Thu Jan 01 00:00:04 1970 +0000
99 99 | summary: Backed out changeset 22cb4f70d813
100 100 |
101 101 o changeset: 2:a8c6e511cfee
102 102 | user: test
103 103 | date: Thu Jan 01 00:00:02 1970 +0000
104 104 | summary: grapes
105 105 |
106 106 % changeset: 1:22cb4f70d813
107 107 | user: test
108 108 | date: Thu Jan 01 00:00:01 1970 +0000
109 109 | summary: chair
110 110 |
111 111 o changeset: 0:a5cb2dde5805
112 112 user: test
113 113 date: Thu Jan 01 00:00:00 1970 +0000
114 114 summary: tomatoes
115 115
116 116
117 117 file that was removed is recreated
118 118 (this also tests that editor is not invoked if the commit message is
119 119 specified explicitly)
120 120
121 121 $ cd ..
122 122 $ hg init remove
123 123 $ cd remove
124 124
125 125 $ echo content > a
126 126 $ hg commit -d '0 0' -A -m a
127 127 adding a
128 128
129 129 $ hg rm a
130 130 $ hg commit -d '1 0' -m b
131 131
132 132 $ HGEDITOR=cat hg backout -d '2 0' tip --tool=true -m "Backed out changeset 76862dcce372"
133 133 adding a
134 134 changeset 2:de31bdc76c0d backs out changeset 1:76862dcce372
135 135 $ cat a
136 136 content
137 137 $ hg summary
138 138 parent: 2:de31bdc76c0d tip
139 139 Backed out changeset 76862dcce372
140 140 branch: default
141 141 commit: (clean)
142 142 update: (current)
143 143 phases: 3 draft
144 144
145 145 backout of backout is as if nothing happened
146 146
147 147 $ hg backout -d '3 0' --merge tip --tool=true
148 148 removing a
149 149 changeset 3:7f6d0f120113 backs out changeset 2:de31bdc76c0d
150 150 $ test -f a
151 151 [1]
152 152 $ hg summary
153 153 parent: 3:7f6d0f120113 tip
154 154 Backed out changeset de31bdc76c0d
155 155 branch: default
156 156 commit: (clean)
157 157 update: (current)
158 158 phases: 4 draft
159 159
160 160 Test that 'hg rollback' restores dirstate just before opening
161 161 transaction: in-memory dirstate changes should be written into
162 162 '.hg/journal.dirstate' as expected.
163 163
164 164 $ echo 'removed soon' > b
165 165 $ hg commit -A -d '4 0' -m 'prepare for subsequent removing'
166 166 adding b
167 167 $ echo 'newly added' > c
168 168 $ hg add c
169 169 $ hg remove b
170 170 $ hg commit -d '5 0' -m 'prepare for subsequent backout'
171 171 $ touch -t 200001010000 c
172 172 $ hg status -A
173 173 C c
174 174 $ hg debugstate --no-dates
175 175 n 644 12 set c
176 176 $ hg backout -d '6 0' -m 'to be rollback-ed soon' -r .
177 177 removing c
178 178 adding b
179 179 changeset 6:4bfec048029d backs out changeset 5:fac0b729a654
180 180 $ hg rollback -q
181 181 $ hg status -A
182 182 A b
183 183 R c
184 184 $ hg debugstate --no-dates
185 185 a 0 -1 unset b
186 186 r 0 0 set c
187 187
188 188 across branch
189 189
190 190 $ cd ..
191 191 $ hg init branch
192 192 $ cd branch
193 193 $ echo a > a
194 194 $ hg ci -Am0
195 195 adding a
196 196 $ echo b > b
197 197 $ hg ci -Am1
198 198 adding b
199 199 $ hg co -C 0
200 200 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
201 201 $ hg summary
202 202 parent: 0:f7b1eb17ad24
203 203 0
204 204 branch: default
205 205 commit: (clean)
206 206 update: 1 new changesets (update)
207 207 phases: 2 draft
208 208
209 209 should fail
210 210
211 211 $ hg backout 1
212 212 abort: cannot backout change that is not an ancestor
213 213 [255]
214 214 $ echo c > c
215 215 $ hg ci -Am2
216 216 adding c
217 217 created new head
218 218 $ hg summary
219 219 parent: 2:db815d6d32e6 tip
220 220 2
221 221 branch: default
222 222 commit: (clean)
223 223 update: 1 new changesets, 2 branch heads (merge)
224 224 phases: 3 draft
225 225
226 226 should fail
227 227
228 228 $ hg backout 1
229 229 abort: cannot backout change that is not an ancestor
230 230 [255]
231 231 $ hg summary
232 232 parent: 2:db815d6d32e6 tip
233 233 2
234 234 branch: default
235 235 commit: (clean)
236 236 update: 1 new changesets, 2 branch heads (merge)
237 237 phases: 3 draft
238 238
239 239 backout with merge
240 240
241 241 $ cd ..
242 242 $ hg init merge
243 243 $ cd merge
244 244
245 245 $ echo line 1 > a
246 246 $ echo line 2 >> a
247 247 $ hg commit -d '0 0' -A -m a
248 248 adding a
249 249 $ hg summary
250 250 parent: 0:59395513a13a tip
251 251 a
252 252 branch: default
253 253 commit: (clean)
254 254 update: (current)
255 255 phases: 1 draft
256 256
257 257 remove line 1
258 258
259 259 $ echo line 2 > a
260 260 $ hg commit -d '1 0' -m b
261 261
262 262 $ echo line 3 >> a
263 263 $ hg commit -d '2 0' -m c
264 264
265 265 $ hg backout --merge -d '3 0' 1 --tool=true
266 266 reverting a
267 267 created new head
268 268 changeset 3:26b8ccb9ad91 backs out changeset 1:5a50a024c182
269 269 merging with changeset 3:26b8ccb9ad91
270 270 merging a
271 271 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
272 272 (branch merge, don't forget to commit)
273 273 $ hg commit -d '4 0' -m d
274 274 $ hg summary
275 275 parent: 4:c7df5e0b9c09 tip
276 276 d
277 277 branch: default
278 278 commit: (clean)
279 279 update: (current)
280 280 phases: 5 draft
281 281
282 282 check line 1 is back
283 283
284 284 $ cat a
285 285 line 1
286 286 line 2
287 287 line 3
288 288
289 289 Test visibility of in-memory dirstate changes outside transaction to
290 290 external hook process
291 291
292 292 $ cat > $TESTTMP/checkvisibility.sh <<EOF
293 293 > echo "==== \$1:"
294 294 > hg parents --template "{rev}:{node|short}\n"
295 295 > echo "===="
296 296 > EOF
297 297
298 298 "hg backout --merge REV1" at REV2 below implies steps below:
299 299
300 300 (1) update to REV1 (REV2 => REV1)
301 301 (2) revert by REV1^1
302 302 (3) commit backing out revision (REV3)
303 303 (4) update to REV2 (REV3 => REV2)
304 304 (5) merge with REV3 (REV2 => REV2, REV3)
305 305
306 306 == test visibility to external preupdate hook
307 307
308 308 $ hg update -q -C 2
309 309 $ hg --config extensions.strip= strip 3
310 310 saved backup bundle to * (glob)
311 311
312 312 $ cat >> .hg/hgrc <<EOF
313 313 > [hooks]
314 314 > preupdate.visibility = sh $TESTTMP/checkvisibility.sh preupdate
315 315 > EOF
316 316
317 317 ("-m" is needed to avoid writing dirstate changes out at other than
318 318 invocation of the hook to be examined)
319 319
320 320 $ hg backout --merge -d '3 0' 1 --tool=true -m 'fixed comment'
321 321 ==== preupdate:
322 322 2:6ea3f2a197a2
323 323 ====
324 324 reverting a
325 325 created new head
326 326 changeset 3:d92a3f57f067 backs out changeset 1:5a50a024c182
327 327 ==== preupdate:
328 328 3:d92a3f57f067
329 329 ====
330 330 merging with changeset 3:d92a3f57f067
331 331 ==== preupdate:
332 332 2:6ea3f2a197a2
333 333 ====
334 334 merging a
335 335 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
336 336 (branch merge, don't forget to commit)
337 337
338 338 $ cat >> .hg/hgrc <<EOF
339 339 > [hooks]
340 340 > preupdate.visibility =
341 341 > EOF
342 342
343 343 == test visibility to external update hook
344 344
345 345 $ hg update -q -C 2
346 346 $ hg --config extensions.strip= strip 3
347 347 saved backup bundle to * (glob)
348 348
349 349 $ cat >> .hg/hgrc <<EOF
350 350 > [hooks]
351 351 > update.visibility = sh $TESTTMP/checkvisibility.sh update
352 352 > EOF
353 353
354 354 $ hg backout --merge -d '3 0' 1 --tool=true -m 'fixed comment'
355 355 ==== update:
356 356 1:5a50a024c182
357 357 ====
358 358 reverting a
359 359 created new head
360 360 changeset 3:d92a3f57f067 backs out changeset 1:5a50a024c182
361 361 ==== update:
362 362 2:6ea3f2a197a2
363 363 ====
364 364 merging with changeset 3:d92a3f57f067
365 365 merging a
366 366 ==== update:
367 367 2:6ea3f2a197a2
368 368 3:d92a3f57f067
369 369 ====
370 370 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
371 371 (branch merge, don't forget to commit)
372 372
373 373 $ cat >> .hg/hgrc <<EOF
374 374 > [hooks]
375 375 > update.visibility =
376 376 > EOF
377 377
378 378 $ cd ..
379 379
380 380 backout should not back out subsequent changesets
381 381
382 382 $ hg init onecs
383 383 $ cd onecs
384 384 $ echo 1 > a
385 385 $ hg commit -d '0 0' -A -m a
386 386 adding a
387 387 $ echo 2 >> a
388 388 $ hg commit -d '1 0' -m b
389 389 $ echo 1 > b
390 390 $ hg commit -d '2 0' -A -m c
391 391 adding b
392 392 $ hg summary
393 393 parent: 2:882396649954 tip
394 394 c
395 395 branch: default
396 396 commit: (clean)
397 397 update: (current)
398 398 phases: 3 draft
399 399
400 400 without --merge
401 401 $ hg backout --no-commit -d '3 0' 1 --tool=true
402 402 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
403 403 changeset 22bca4c721e5 backed out, don't forget to commit.
404 404 $ hg locate b
405 405 b
406 406 $ hg update -C tip
407 407 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
408 408 $ hg locate b
409 409 b
410 410 $ hg summary
411 411 parent: 2:882396649954 tip
412 412 c
413 413 branch: default
414 414 commit: (clean)
415 415 update: (current)
416 416 phases: 3 draft
417 417
418 418 with --merge
419 419 $ hg backout --merge -d '3 0' 1 --tool=true
420 420 reverting a
421 421 created new head
422 422 changeset 3:3202beb76721 backs out changeset 1:22bca4c721e5
423 423 merging with changeset 3:3202beb76721
424 424 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
425 425 (branch merge, don't forget to commit)
426 426 $ hg locate b
427 427 b
428 428 $ hg update -C tip
429 429 1 files updated, 0 files merged, 1 files removed, 0 files unresolved
430 430 $ hg locate b
431 431 [1]
432 432
433 433 $ cd ..
434 434 $ hg init m
435 435 $ cd m
436 436 $ echo a > a
437 437 $ hg commit -d '0 0' -A -m a
438 438 adding a
439 439 $ echo b > b
440 440 $ hg commit -d '1 0' -A -m b
441 441 adding b
442 442 $ echo c > c
443 443 $ hg commit -d '2 0' -A -m b
444 444 adding c
445 445 $ hg update 1
446 446 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
447 447 $ echo d > d
448 448 $ hg commit -d '3 0' -A -m c
449 449 adding d
450 450 created new head
451 451 $ hg merge 2
452 452 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
453 453 (branch merge, don't forget to commit)
454 454 $ hg commit -d '4 0' -A -m d
455 455 $ hg summary
456 456 parent: 4:b2f3bb92043e tip
457 457 d
458 458 branch: default
459 459 commit: (clean)
460 460 update: (current)
461 461 phases: 5 draft
462 462
463 463 backout of merge should fail
464 464
465 465 $ hg backout 4
466 466 abort: cannot backout a merge changeset
467 467 [255]
468 468
469 469 backout of merge with bad parent should fail
470 470
471 471 $ hg backout --parent 0 4
472 472 abort: cb9a9f314b8b is not a parent of b2f3bb92043e
473 473 [255]
474 474
475 475 backout of non-merge with parent should fail
476 476
477 477 $ hg backout --parent 0 3
478 478 abort: cannot use --parent on non-merge changeset
479 479 [255]
480 480
481 481 backout with valid parent should be ok
482 482
483 483 $ hg backout -d '5 0' --parent 2 4 --tool=true
484 484 removing d
485 485 changeset 5:10e5328c8435 backs out changeset 4:b2f3bb92043e
486 486 $ hg summary
487 487 parent: 5:10e5328c8435 tip
488 488 Backed out changeset b2f3bb92043e
489 489 branch: default
490 490 commit: (clean)
491 491 update: (current)
492 492 phases: 6 draft
493 493
494 494 $ hg rollback
495 495 repository tip rolled back to revision 4 (undo commit)
496 496 working directory now based on revision 4
497 497 $ hg update -C
498 498 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
499 499 $ hg summary
500 500 parent: 4:b2f3bb92043e tip
501 501 d
502 502 branch: default
503 503 commit: (clean)
504 504 update: (current)
505 505 phases: 5 draft
506 506
507 507 $ hg backout -d '6 0' --parent 3 4 --tool=true
508 508 removing c
509 509 changeset 5:033590168430 backs out changeset 4:b2f3bb92043e
510 510 $ hg summary
511 511 parent: 5:033590168430 tip
512 512 Backed out changeset b2f3bb92043e
513 513 branch: default
514 514 commit: (clean)
515 515 update: (current)
516 516 phases: 6 draft
517 517
518 518 $ cd ..
519 519
520 520 named branches
521 521
522 522 $ hg init named_branches
523 523 $ cd named_branches
524 524
525 525 $ echo default > default
526 526 $ hg ci -d '0 0' -Am default
527 527 adding default
528 528 $ hg branch branch1
529 529 marked working directory as branch branch1
530 530 (branches are permanent and global, did you want a bookmark?)
531 531 $ echo branch1 > file1
532 532 $ hg ci -d '1 0' -Am file1
533 533 adding file1
534 534 $ hg branch branch2
535 535 marked working directory as branch branch2
536 536 $ echo branch2 > file2
537 537 $ hg ci -d '2 0' -Am file2
538 538 adding file2
539 539
540 540 without --merge
541 541 $ hg backout --no-commit -r 1 --tool=true
542 542 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
543 543 changeset bf1602f437f3 backed out, don't forget to commit.
544 544 $ hg branch
545 545 branch2
546 546 $ hg status -A
547 547 R file1
548 548 C default
549 549 C file2
550 550 $ hg summary
551 551 parent: 2:45bbcd363bf0 tip
552 552 file2
553 553 branch: branch2
554 554 commit: 1 removed
555 555 update: (current)
556 556 phases: 3 draft
557 557
558 558 with --merge
559 559 (this also tests that editor is invoked if '--edit' is specified
560 560 explicitly regardless of '--message')
561 561
562 562 $ hg update -qC
563 563 $ HGEDITOR=cat hg backout --merge -d '3 0' -r 1 -m 'backout on branch1' --tool=true --edit
564 564 removing file1
565 565 backout on branch1
566 566
567 567
568 568 HG: Enter commit message. Lines beginning with 'HG:' are removed.
569 569 HG: Leave message empty to abort commit.
570 570 HG: --
571 571 HG: user: test
572 572 HG: branch 'branch2'
573 573 HG: removed file1
574 574 created new head
575 575 changeset 3:d4e8f6db59fb backs out changeset 1:bf1602f437f3
576 576 merging with changeset 3:d4e8f6db59fb
577 577 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
578 578 (branch merge, don't forget to commit)
579 579 $ hg summary
580 580 parent: 2:45bbcd363bf0
581 581 file2
582 582 parent: 3:d4e8f6db59fb tip
583 583 backout on branch1
584 584 branch: branch2
585 585 commit: 1 removed (merge)
586 586 update: (current)
587 587 phases: 4 draft
588 588 $ hg update -q -C 2
589 589
590 590 on branch2 with branch1 not merged, so file1 should still exist:
591 591
592 592 $ hg id
593 593 45bbcd363bf0 (branch2)
594 594 $ hg st -A
595 595 C default
596 596 C file1
597 597 C file2
598 598 $ hg summary
599 599 parent: 2:45bbcd363bf0
600 600 file2
601 601 branch: branch2
602 602 commit: (clean)
603 603 update: 1 new changesets, 2 branch heads (merge)
604 604 phases: 4 draft
605 605
606 606 on branch2 with branch1 merged, so file1 should be gone:
607 607
608 608 $ hg merge
609 609 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
610 610 (branch merge, don't forget to commit)
611 611 $ hg ci -d '4 0' -m 'merge backout of branch1'
612 612 $ hg id
613 613 d97a8500a969 (branch2) tip
614 614 $ hg st -A
615 615 C default
616 616 C file2
617 617 $ hg summary
618 618 parent: 4:d97a8500a969 tip
619 619 merge backout of branch1
620 620 branch: branch2
621 621 commit: (clean)
622 622 update: (current)
623 623 phases: 5 draft
624 624
625 625 on branch1, so no file1 and file2:
626 626
627 627 $ hg co -C branch1
628 628 1 files updated, 0 files merged, 1 files removed, 0 files unresolved
629 629 $ hg id
630 630 bf1602f437f3 (branch1)
631 631 $ hg st -A
632 632 C default
633 633 C file1
634 634 $ hg summary
635 635 parent: 1:bf1602f437f3
636 636 file1
637 637 branch: branch1
638 638 commit: (clean)
639 639 update: (current)
640 640 phases: 5 draft
641 641
642 642 $ cd ..
643 643
644 644 backout of empty changeset (issue4190)
645 645
646 646 $ hg init emptycommit
647 647 $ cd emptycommit
648 648
649 649 $ touch file1
650 650 $ hg ci -Aqm file1
651 651 $ hg branch -q branch1
652 652 $ hg ci -qm branch1
653 653 $ hg backout -v 1
654 654 resolving manifests
655 655 nothing changed
656 656 [1]
657 657
658 658 $ cd ..
659 659
660 660
661 661 Test usage of `hg resolve` in case of conflict
662 662 (issue4163)
663 663
664 664 $ hg init issue4163
665 665 $ cd issue4163
666 666 $ touch foo
667 667 $ hg add foo
668 668 $ cat > foo << EOF
669 669 > one
670 670 > two
671 671 > three
672 672 > four
673 673 > five
674 674 > six
675 675 > seven
676 676 > height
677 677 > nine
678 678 > ten
679 679 > EOF
680 680 $ hg ci -m 'initial'
681 681 $ cat > foo << EOF
682 682 > one
683 683 > two
684 684 > THREE
685 685 > four
686 686 > five
687 687 > six
688 688 > seven
689 689 > height
690 690 > nine
691 691 > ten
692 692 > EOF
693 693 $ hg ci -m 'capital three'
694 694 $ cat > foo << EOF
695 695 > one
696 696 > two
697 697 > THREE
698 698 > four
699 699 > five
700 700 > six
701 701 > seven
702 702 > height
703 703 > nine
704 704 > TEN
705 705 > EOF
706 706 $ hg ci -m 'capital ten'
707 707 $ hg backout -r 'desc("capital three")' --tool internal:fail
708 708 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
709 709 use 'hg resolve' to retry unresolved file merges
710 710 [1]
711 711 $ hg status
712 712 $ hg debugmergestate -v
713 713 v1 and v2 states match: using v2
714 714 local: b71750c4b0fdf719734971e3ef90dbeab5919a2d
715 715 other: a30dd8addae3ce71b8667868478542bc417439e6
716 716 file: foo (state "u")
717 717 local path: foo (hash 0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33, flags "")
718 718 ancestor path: foo (node f89532f44c247a0e993d63e3a734dd781ab04708)
719 719 other path: foo (node f50039b486d6fa1a90ae51778388cad161f425ee)
720 720 extra: ancestorlinknode = 91360952243723bd5b1138d5f26bd8c8564cb553
721 721 $ mv .hg/merge/state2 .hg/merge/state2-moved
722 722 $ hg debugmergestate -v
723 723 no version 2 merge state
724 724 local: b71750c4b0fdf719734971e3ef90dbeab5919a2d
725 725 other: b71750c4b0fdf719734971e3ef90dbeab5919a2d
726 726 file: foo (state "u")
727 727 local path: foo (hash 0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33, flags "")
728 728 ancestor path: foo (node f89532f44c247a0e993d63e3a734dd781ab04708)
729 729 other path: (node foo)
730 730 $ mv .hg/merge/state2-moved .hg/merge/state2
731 731 $ hg resolve -l # still unresolved
732 732 U foo
733 733 $ hg summary
734 734 parent: 2:b71750c4b0fd tip
735 735 capital ten
736 736 branch: default
737 737 commit: 1 unresolved (clean)
738 738 update: (current)
739 739 phases: 3 draft
740 740 $ hg log -G
741 741 @ changeset: 2:b71750c4b0fd
742 742 | tag: tip
743 743 | user: test
744 744 | date: Thu Jan 01 00:00:00 1970 +0000
745 745 | summary: capital ten
746 746 |
747 747 o changeset: 1:913609522437
748 748 | user: test
749 749 | date: Thu Jan 01 00:00:00 1970 +0000
750 750 | summary: capital three
751 751 |
752 752 % changeset: 0:a30dd8addae3
753 753 user: test
754 754 date: Thu Jan 01 00:00:00 1970 +0000
755 755 summary: initial
756 756
757 757 $ hg resolve --all --debug
758 758 picked tool ':merge' for foo (binary False symlink False changedelete False)
759 759 merging foo
760 760 my foo@b71750c4b0fd+ other foo@a30dd8addae3 ancestor foo@913609522437
761 761 premerge successful
762 762 (no more unresolved files)
763 763 continue: hg commit
764 764 $ hg status
765 765 M foo
766 766 ? foo.orig
767 767 $ hg resolve -l
768 768 R foo
769 769 $ hg summary
770 770 parent: 2:b71750c4b0fd tip
771 771 capital ten
772 772 branch: default
773 773 commit: 1 modified, 1 unknown
774 774 update: (current)
775 775 phases: 3 draft
776 776 $ cat foo
777 777 one
778 778 two
779 779 three
780 780 four
781 781 five
782 782 six
783 783 seven
784 784 height
785 785 nine
786 786 TEN
787 787
788 788 --no-commit shouldn't commit
789 789
790 790 $ hg init a
791 791 $ cd a
792 792 $ for i in 1 2 3; do
793 793 > touch $i
794 794 > hg ci -Am $i
795 795 > done
796 796 adding 1
797 797 adding 2
798 798 adding 3
799 799 $ hg backout --no-commit .
800 800 removing 3
801 801 changeset cccc23d9d68f backed out, don't forget to commit.
802 802 $ hg revert -aq
803 803
804 804 --no-commit can't be used with --merge
805 805
806 806 $ hg backout --merge --no-commit 2
807 807 abort: cannot specify both --no-commit and --merge
808 808 [255]
809 809
810 810 Ensure that backout out the same changeset twice performs correctly:
811 811
812 812 $ hg backout 2
813 813 removing 3
814 814 changeset 3:8f188de730d9 backs out changeset 2:cccc23d9d68f
815 815 $ echo 4 > 4
816 816 $ hg ci -A -m 4
817 817 adding 4
818 818 $ hg up 2
819 819 1 files updated, 0 files merged, 1 files removed, 0 files unresolved
820 820 $ hg backout 2
821 821 removing 3
822 created new head
822 warning: commit already existed in the repository!
823 823 changeset 3:8f188de730d9 backs out changeset 2:cccc23d9d68f
@@ -1,2091 +1,2092 b''
1 1 test merge-tools configuration - mostly exercising filemerge.py
2 2
3 3 $ unset HGMERGE # make sure HGMERGE doesn't interfere with the test
4 4 $ cat >> $HGRCPATH << EOF
5 5 > [ui]
6 6 > merge=
7 7 > [commands]
8 8 > merge.require-rev=True
9 9 > EOF
10 10 $ hg init repo
11 11 $ cd repo
12 12
13 13 revision 0
14 14
15 15 $ echo "revision 0" > f
16 16 $ echo "space" >> f
17 17 $ hg commit -Am "revision 0"
18 18 adding f
19 19
20 20 revision 1
21 21
22 22 $ echo "revision 1" > f
23 23 $ echo "space" >> f
24 24 $ hg commit -Am "revision 1"
25 25 $ hg update 0 > /dev/null
26 26
27 27 revision 2
28 28
29 29 $ echo "revision 2" > f
30 30 $ echo "space" >> f
31 31 $ hg commit -Am "revision 2"
32 32 created new head
33 33 $ hg update 0 > /dev/null
34 34
35 35 revision 3 - simple to merge
36 36
37 37 $ echo "revision 3" >> f
38 38 $ hg commit -Am "revision 3"
39 39 created new head
40 40
41 41 revision 4 - hard to merge
42 42
43 43 $ hg update 0 > /dev/null
44 44 $ echo "revision 4" > f
45 45 $ hg commit -Am "revision 4"
46 46 created new head
47 47
48 48 $ echo "[merge-tools]" > .hg/hgrc
49 49
50 50 $ beforemerge() {
51 51 > cat .hg/hgrc
52 52 > echo "# hg update -C 1"
53 53 > hg update -C 1 > /dev/null
54 54 > }
55 55 $ aftermerge() {
56 56 > echo "# cat f"
57 57 > cat f
58 58 > echo "# hg stat"
59 59 > hg stat
60 60 > echo "# hg resolve --list"
61 61 > hg resolve --list
62 62 > rm -f f.orig
63 63 > }
64 64
65 65 Tool selection
66 66
67 67 default is internal merge:
68 68
69 69 $ beforemerge
70 70 [merge-tools]
71 71 # hg update -C 1
72 72
73 73 hg merge -r 2
74 74 override $PATH to ensure hgmerge not visible; use $PYTHON in case we're
75 75 running from a devel copy, not a temp installation
76 76
77 77 $ PATH="/usr/sbin" "$PYTHON" "$BINDIR"/hg merge -r 2
78 78 merging f
79 79 warning: conflicts while merging f! (edit, then use 'hg resolve --mark')
80 80 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
81 81 use 'hg resolve' to retry unresolved file merges or 'hg merge --abort' to abandon
82 82 [1]
83 83 $ aftermerge
84 84 # cat f
85 85 <<<<<<< working copy: ef83787e2614 - test: revision 1
86 86 revision 1
87 87 =======
88 88 revision 2
89 89 >>>>>>> merge rev: 0185f4e0cf02 - test: revision 2
90 90 space
91 91 # hg stat
92 92 M f
93 93 ? f.orig
94 94 # hg resolve --list
95 95 U f
96 96
97 97 simplest hgrc using false for merge:
98 98
99 99 $ echo "false.whatever=" >> .hg/hgrc
100 100 $ beforemerge
101 101 [merge-tools]
102 102 false.whatever=
103 103 # hg update -C 1
104 104 $ hg merge -r 2
105 105 merging f
106 106 merging f failed!
107 107 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
108 108 use 'hg resolve' to retry unresolved file merges or 'hg merge --abort' to abandon
109 109 [1]
110 110 $ aftermerge
111 111 # cat f
112 112 revision 1
113 113 space
114 114 # hg stat
115 115 M f
116 116 ? f.orig
117 117 # hg resolve --list
118 118 U f
119 119
120 120 #if unix-permissions
121 121
122 122 unexecutable file in $PATH shouldn't be found:
123 123
124 124 $ echo "echo fail" > false
125 125 $ hg up -qC 1
126 126 $ PATH="`pwd`:/usr/sbin" "$PYTHON" "$BINDIR"/hg merge -r 2
127 127 merging f
128 128 warning: conflicts while merging f! (edit, then use 'hg resolve --mark')
129 129 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
130 130 use 'hg resolve' to retry unresolved file merges or 'hg merge --abort' to abandon
131 131 [1]
132 132 $ rm false
133 133
134 134 #endif
135 135
136 136 executable directory in $PATH shouldn't be found:
137 137
138 138 $ mkdir false
139 139 $ hg up -qC 1
140 140 $ PATH="`pwd`:/usr/sbin" "$PYTHON" "$BINDIR"/hg merge -r 2
141 141 merging f
142 142 warning: conflicts while merging f! (edit, then use 'hg resolve --mark')
143 143 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
144 144 use 'hg resolve' to retry unresolved file merges or 'hg merge --abort' to abandon
145 145 [1]
146 146 $ rmdir false
147 147
148 148 true with higher .priority gets precedence:
149 149
150 150 $ echo "true.priority=1" >> .hg/hgrc
151 151 $ beforemerge
152 152 [merge-tools]
153 153 false.whatever=
154 154 true.priority=1
155 155 # hg update -C 1
156 156 $ hg merge -r 2
157 157 merging f
158 158 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
159 159 (branch merge, don't forget to commit)
160 160 $ aftermerge
161 161 # cat f
162 162 revision 1
163 163 space
164 164 # hg stat
165 165 M f
166 166 # hg resolve --list
167 167 R f
168 168
169 169 unless lowered on command line:
170 170
171 171 $ beforemerge
172 172 [merge-tools]
173 173 false.whatever=
174 174 true.priority=1
175 175 # hg update -C 1
176 176 $ hg merge -r 2 --config merge-tools.true.priority=-7
177 177 merging f
178 178 merging f failed!
179 179 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
180 180 use 'hg resolve' to retry unresolved file merges or 'hg merge --abort' to abandon
181 181 [1]
182 182 $ aftermerge
183 183 # cat f
184 184 revision 1
185 185 space
186 186 # hg stat
187 187 M f
188 188 ? f.orig
189 189 # hg resolve --list
190 190 U f
191 191
192 192 or false set higher on command line:
193 193
194 194 $ beforemerge
195 195 [merge-tools]
196 196 false.whatever=
197 197 true.priority=1
198 198 # hg update -C 1
199 199 $ hg merge -r 2 --config merge-tools.false.priority=117
200 200 merging f
201 201 merging f failed!
202 202 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
203 203 use 'hg resolve' to retry unresolved file merges or 'hg merge --abort' to abandon
204 204 [1]
205 205 $ aftermerge
206 206 # cat f
207 207 revision 1
208 208 space
209 209 # hg stat
210 210 M f
211 211 ? f.orig
212 212 # hg resolve --list
213 213 U f
214 214
215 215 or true set to disabled:
216 216 $ beforemerge
217 217 [merge-tools]
218 218 false.whatever=
219 219 true.priority=1
220 220 # hg update -C 1
221 221 $ hg merge -r 2 --config merge-tools.true.disabled=yes
222 222 merging f
223 223 merging f failed!
224 224 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
225 225 use 'hg resolve' to retry unresolved file merges or 'hg merge --abort' to abandon
226 226 [1]
227 227 $ aftermerge
228 228 # cat f
229 229 revision 1
230 230 space
231 231 # hg stat
232 232 M f
233 233 ? f.orig
234 234 # hg resolve --list
235 235 U f
236 236
237 237 or true.executable not found in PATH:
238 238
239 239 $ beforemerge
240 240 [merge-tools]
241 241 false.whatever=
242 242 true.priority=1
243 243 # hg update -C 1
244 244 $ hg merge -r 2 --config merge-tools.true.executable=nonexistentmergetool
245 245 merging f
246 246 merging f failed!
247 247 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
248 248 use 'hg resolve' to retry unresolved file merges or 'hg merge --abort' to abandon
249 249 [1]
250 250 $ aftermerge
251 251 # cat f
252 252 revision 1
253 253 space
254 254 # hg stat
255 255 M f
256 256 ? f.orig
257 257 # hg resolve --list
258 258 U f
259 259
260 260 or true.executable with bogus path:
261 261
262 262 $ beforemerge
263 263 [merge-tools]
264 264 false.whatever=
265 265 true.priority=1
266 266 # hg update -C 1
267 267 $ hg merge -r 2 --config merge-tools.true.executable=/nonexistent/mergetool
268 268 merging f
269 269 merging f failed!
270 270 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
271 271 use 'hg resolve' to retry unresolved file merges or 'hg merge --abort' to abandon
272 272 [1]
273 273 $ aftermerge
274 274 # cat f
275 275 revision 1
276 276 space
277 277 # hg stat
278 278 M f
279 279 ? f.orig
280 280 # hg resolve --list
281 281 U f
282 282
283 283 but true.executable set to cat found in PATH works:
284 284
285 285 $ echo "true.executable=cat" >> .hg/hgrc
286 286 $ beforemerge
287 287 [merge-tools]
288 288 false.whatever=
289 289 true.priority=1
290 290 true.executable=cat
291 291 # hg update -C 1
292 292 $ hg merge -r 2
293 293 merging f
294 294 revision 1
295 295 space
296 296 revision 0
297 297 space
298 298 revision 2
299 299 space
300 300 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
301 301 (branch merge, don't forget to commit)
302 302 $ aftermerge
303 303 # cat f
304 304 revision 1
305 305 space
306 306 # hg stat
307 307 M f
308 308 # hg resolve --list
309 309 R f
310 310
311 311 and true.executable set to cat with path works:
312 312
313 313 $ beforemerge
314 314 [merge-tools]
315 315 false.whatever=
316 316 true.priority=1
317 317 true.executable=cat
318 318 # hg update -C 1
319 319 $ hg merge -r 2 --config merge-tools.true.executable=cat
320 320 merging f
321 321 revision 1
322 322 space
323 323 revision 0
324 324 space
325 325 revision 2
326 326 space
327 327 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
328 328 (branch merge, don't forget to commit)
329 329 $ aftermerge
330 330 # cat f
331 331 revision 1
332 332 space
333 333 # hg stat
334 334 M f
335 335 # hg resolve --list
336 336 R f
337 337
338 338 executable set to python script that succeeds:
339 339
340 340 $ cat > "$TESTTMP/myworkingmerge.py" <<EOF
341 341 > def myworkingmergefn(ui, repo, args, **kwargs):
342 342 > return False
343 343 > EOF
344 344 $ beforemerge
345 345 [merge-tools]
346 346 false.whatever=
347 347 true.priority=1
348 348 true.executable=cat
349 349 # hg update -C 1
350 350 $ hg merge -r 2 --config merge-tools.true.executable="python:$TESTTMP/myworkingmerge.py:myworkingmergefn"
351 351 merging f
352 352 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
353 353 (branch merge, don't forget to commit)
354 354 $ aftermerge
355 355 # cat f
356 356 revision 1
357 357 space
358 358 # hg stat
359 359 M f
360 360 # hg resolve --list
361 361 R f
362 362
363 363 executable set to python script that fails:
364 364
365 365 $ cat > "$TESTTMP/mybrokenmerge.py" <<EOF
366 366 > def mybrokenmergefn(ui, repo, args, **kwargs):
367 367 > ui.write(b"some fail message\n")
368 368 > return True
369 369 > EOF
370 370 $ beforemerge
371 371 [merge-tools]
372 372 false.whatever=
373 373 true.priority=1
374 374 true.executable=cat
375 375 # hg update -C 1
376 376 $ hg merge -r 2 --config merge-tools.true.executable="python:$TESTTMP/mybrokenmerge.py:mybrokenmergefn"
377 377 merging f
378 378 some fail message
379 379 abort: $TESTTMP/mybrokenmerge.py hook failed
380 380 [255]
381 381 $ aftermerge
382 382 # cat f
383 383 revision 1
384 384 space
385 385 # hg stat
386 386 ? f.orig
387 387 # hg resolve --list
388 388 U f
389 389
390 390 executable set to python script that is missing function:
391 391
392 392 $ beforemerge
393 393 [merge-tools]
394 394 false.whatever=
395 395 true.priority=1
396 396 true.executable=cat
397 397 # hg update -C 1
398 398 $ hg merge -r 2 --config merge-tools.true.executable="python:$TESTTMP/myworkingmerge.py:missingFunction"
399 399 merging f
400 400 abort: $TESTTMP/myworkingmerge.py does not have function: missingFunction
401 401 [255]
402 402 $ aftermerge
403 403 # cat f
404 404 revision 1
405 405 space
406 406 # hg stat
407 407 ? f.orig
408 408 # hg resolve --list
409 409 U f
410 410
411 411 executable set to missing python script:
412 412
413 413 $ beforemerge
414 414 [merge-tools]
415 415 false.whatever=
416 416 true.priority=1
417 417 true.executable=cat
418 418 # hg update -C 1
419 419 $ hg merge -r 2 --config merge-tools.true.executable="python:$TESTTMP/missingpythonscript.py:mergefn"
420 420 merging f
421 421 abort: loading python merge script failed: $TESTTMP/missingpythonscript.py
422 422 [255]
423 423 $ aftermerge
424 424 # cat f
425 425 revision 1
426 426 space
427 427 # hg stat
428 428 ? f.orig
429 429 # hg resolve --list
430 430 U f
431 431
432 432 executable set to python script but callable function is missing:
433 433
434 434 $ beforemerge
435 435 [merge-tools]
436 436 false.whatever=
437 437 true.priority=1
438 438 true.executable=cat
439 439 # hg update -C 1
440 440 $ hg merge -r 2 --config merge-tools.true.executable="python:$TESTTMP/myworkingmerge.py"
441 441 abort: invalid 'python:' syntax: python:$TESTTMP/myworkingmerge.py
442 442 [255]
443 443 $ aftermerge
444 444 # cat f
445 445 revision 1
446 446 space
447 447 # hg stat
448 448 # hg resolve --list
449 449 U f
450 450
451 451 executable set to python script but callable function is empty string:
452 452
453 453 $ beforemerge
454 454 [merge-tools]
455 455 false.whatever=
456 456 true.priority=1
457 457 true.executable=cat
458 458 # hg update -C 1
459 459 $ hg merge -r 2 --config merge-tools.true.executable="python:$TESTTMP/myworkingmerge.py:"
460 460 abort: invalid 'python:' syntax: python:$TESTTMP/myworkingmerge.py:
461 461 [255]
462 462 $ aftermerge
463 463 # cat f
464 464 revision 1
465 465 space
466 466 # hg stat
467 467 # hg resolve --list
468 468 U f
469 469
470 470 executable set to python script but callable function is missing and path contains colon:
471 471
472 472 $ beforemerge
473 473 [merge-tools]
474 474 false.whatever=
475 475 true.priority=1
476 476 true.executable=cat
477 477 # hg update -C 1
478 478 $ hg merge -r 2 --config merge-tools.true.executable="python:$TESTTMP/some:dir/myworkingmerge.py"
479 479 abort: invalid 'python:' syntax: python:$TESTTMP/some:dir/myworkingmerge.py
480 480 [255]
481 481 $ aftermerge
482 482 # cat f
483 483 revision 1
484 484 space
485 485 # hg stat
486 486 # hg resolve --list
487 487 U f
488 488
489 489 executable set to python script filename that contains spaces:
490 490
491 491 $ mkdir -p "$TESTTMP/my path"
492 492 $ cat > "$TESTTMP/my path/my working merge with spaces in filename.py" <<EOF
493 493 > def myworkingmergefn(ui, repo, args, **kwargs):
494 494 > return False
495 495 > EOF
496 496 $ beforemerge
497 497 [merge-tools]
498 498 false.whatever=
499 499 true.priority=1
500 500 true.executable=cat
501 501 # hg update -C 1
502 502 $ hg merge -r 2 --config "merge-tools.true.executable=python:$TESTTMP/my path/my working merge with spaces in filename.py:myworkingmergefn"
503 503 merging f
504 504 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
505 505 (branch merge, don't forget to commit)
506 506 $ aftermerge
507 507 # cat f
508 508 revision 1
509 509 space
510 510 # hg stat
511 511 M f
512 512 # hg resolve --list
513 513 R f
514 514
515 515 #if unix-permissions
516 516
517 517 environment variables in true.executable are handled:
518 518
519 519 $ echo 'echo "custom merge tool"' > .hg/merge.sh
520 520 $ beforemerge
521 521 [merge-tools]
522 522 false.whatever=
523 523 true.priority=1
524 524 true.executable=cat
525 525 # hg update -C 1
526 526 $ hg --config merge-tools.true.executable='sh' \
527 527 > --config merge-tools.true.args=.hg/merge.sh \
528 528 > merge -r 2
529 529 merging f
530 530 custom merge tool
531 531 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
532 532 (branch merge, don't forget to commit)
533 533 $ aftermerge
534 534 # cat f
535 535 revision 1
536 536 space
537 537 # hg stat
538 538 M f
539 539 # hg resolve --list
540 540 R f
541 541
542 542 #endif
543 543
544 544 Tool selection and merge-patterns
545 545
546 546 merge-patterns specifies new tool false:
547 547
548 548 $ beforemerge
549 549 [merge-tools]
550 550 false.whatever=
551 551 true.priority=1
552 552 true.executable=cat
553 553 # hg update -C 1
554 554 $ hg merge -r 2 --config merge-patterns.f=false
555 555 merging f
556 556 merging f failed!
557 557 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
558 558 use 'hg resolve' to retry unresolved file merges or 'hg merge --abort' to abandon
559 559 [1]
560 560 $ aftermerge
561 561 # cat f
562 562 revision 1
563 563 space
564 564 # hg stat
565 565 M f
566 566 ? f.orig
567 567 # hg resolve --list
568 568 U f
569 569
570 570 merge-patterns specifies executable not found in PATH and gets warning:
571 571
572 572 $ beforemerge
573 573 [merge-tools]
574 574 false.whatever=
575 575 true.priority=1
576 576 true.executable=cat
577 577 # hg update -C 1
578 578 $ hg merge -r 2 --config merge-patterns.f=true --config merge-tools.true.executable=nonexistentmergetool
579 579 couldn't find merge tool true (for pattern f)
580 580 merging f
581 581 couldn't find merge tool true (for pattern f)
582 582 merging f failed!
583 583 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
584 584 use 'hg resolve' to retry unresolved file merges or 'hg merge --abort' to abandon
585 585 [1]
586 586 $ aftermerge
587 587 # cat f
588 588 revision 1
589 589 space
590 590 # hg stat
591 591 M f
592 592 ? f.orig
593 593 # hg resolve --list
594 594 U f
595 595
596 596 merge-patterns specifies executable with bogus path and gets warning:
597 597
598 598 $ beforemerge
599 599 [merge-tools]
600 600 false.whatever=
601 601 true.priority=1
602 602 true.executable=cat
603 603 # hg update -C 1
604 604 $ hg merge -r 2 --config merge-patterns.f=true --config merge-tools.true.executable=/nonexistent/mergetool
605 605 couldn't find merge tool true (for pattern f)
606 606 merging f
607 607 couldn't find merge tool true (for pattern f)
608 608 merging f failed!
609 609 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
610 610 use 'hg resolve' to retry unresolved file merges or 'hg merge --abort' to abandon
611 611 [1]
612 612 $ aftermerge
613 613 # cat f
614 614 revision 1
615 615 space
616 616 # hg stat
617 617 M f
618 618 ? f.orig
619 619 # hg resolve --list
620 620 U f
621 621
622 622 ui.merge overrules priority
623 623
624 624 ui.merge specifies false:
625 625
626 626 $ beforemerge
627 627 [merge-tools]
628 628 false.whatever=
629 629 true.priority=1
630 630 true.executable=cat
631 631 # hg update -C 1
632 632 $ hg merge -r 2 --config ui.merge=false
633 633 merging f
634 634 merging f failed!
635 635 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
636 636 use 'hg resolve' to retry unresolved file merges or 'hg merge --abort' to abandon
637 637 [1]
638 638 $ aftermerge
639 639 # cat f
640 640 revision 1
641 641 space
642 642 # hg stat
643 643 M f
644 644 ? f.orig
645 645 # hg resolve --list
646 646 U f
647 647
648 648 ui.merge specifies internal:fail:
649 649
650 650 $ beforemerge
651 651 [merge-tools]
652 652 false.whatever=
653 653 true.priority=1
654 654 true.executable=cat
655 655 # hg update -C 1
656 656 $ hg merge -r 2 --config ui.merge=internal:fail
657 657 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
658 658 use 'hg resolve' to retry unresolved file merges or 'hg merge --abort' to abandon
659 659 [1]
660 660 $ aftermerge
661 661 # cat f
662 662 revision 1
663 663 space
664 664 # hg stat
665 665 M f
666 666 # hg resolve --list
667 667 U f
668 668
669 669 ui.merge specifies :local (without internal prefix):
670 670
671 671 $ beforemerge
672 672 [merge-tools]
673 673 false.whatever=
674 674 true.priority=1
675 675 true.executable=cat
676 676 # hg update -C 1
677 677 $ hg merge -r 2 --config ui.merge=:local
678 678 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
679 679 (branch merge, don't forget to commit)
680 680 $ aftermerge
681 681 # cat f
682 682 revision 1
683 683 space
684 684 # hg stat
685 685 M f
686 686 # hg resolve --list
687 687 R f
688 688
689 689 ui.merge specifies internal:other:
690 690
691 691 $ beforemerge
692 692 [merge-tools]
693 693 false.whatever=
694 694 true.priority=1
695 695 true.executable=cat
696 696 # hg update -C 1
697 697 $ hg merge -r 2 --config ui.merge=internal:other
698 698 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
699 699 (branch merge, don't forget to commit)
700 700 $ aftermerge
701 701 # cat f
702 702 revision 2
703 703 space
704 704 # hg stat
705 705 M f
706 706 # hg resolve --list
707 707 R f
708 708
709 709 ui.merge specifies internal:prompt:
710 710
711 711 $ beforemerge
712 712 [merge-tools]
713 713 false.whatever=
714 714 true.priority=1
715 715 true.executable=cat
716 716 # hg update -C 1
717 717 $ hg merge -r 2 --config ui.merge=internal:prompt
718 718 file 'f' needs to be resolved.
719 719 You can keep (l)ocal [working copy], take (o)ther [merge rev], or leave (u)nresolved.
720 720 What do you want to do? u
721 721 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
722 722 use 'hg resolve' to retry unresolved file merges or 'hg merge --abort' to abandon
723 723 [1]
724 724 $ aftermerge
725 725 # cat f
726 726 revision 1
727 727 space
728 728 # hg stat
729 729 M f
730 730 # hg resolve --list
731 731 U f
732 732
733 733 ui.merge specifies :prompt, with 'leave unresolved' chosen
734 734
735 735 $ beforemerge
736 736 [merge-tools]
737 737 false.whatever=
738 738 true.priority=1
739 739 true.executable=cat
740 740 # hg update -C 1
741 741 $ hg merge -r 2 --config ui.merge=:prompt --config ui.interactive=True << EOF
742 742 > u
743 743 > EOF
744 744 file 'f' needs to be resolved.
745 745 You can keep (l)ocal [working copy], take (o)ther [merge rev], or leave (u)nresolved.
746 746 What do you want to do? u
747 747 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
748 748 use 'hg resolve' to retry unresolved file merges or 'hg merge --abort' to abandon
749 749 [1]
750 750 $ aftermerge
751 751 # cat f
752 752 revision 1
753 753 space
754 754 # hg stat
755 755 M f
756 756 # hg resolve --list
757 757 U f
758 758
759 759 prompt with EOF
760 760
761 761 $ beforemerge
762 762 [merge-tools]
763 763 false.whatever=
764 764 true.priority=1
765 765 true.executable=cat
766 766 # hg update -C 1
767 767 $ hg merge -r 2 --config ui.merge=internal:prompt --config ui.interactive=true
768 768 file 'f' needs to be resolved.
769 769 You can keep (l)ocal [working copy], take (o)ther [merge rev], or leave (u)nresolved.
770 770 What do you want to do?
771 771 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
772 772 use 'hg resolve' to retry unresolved file merges or 'hg merge --abort' to abandon
773 773 [1]
774 774 $ aftermerge
775 775 # cat f
776 776 revision 1
777 777 space
778 778 # hg stat
779 779 M f
780 780 # hg resolve --list
781 781 U f
782 782 $ hg resolve --all --config ui.merge=internal:prompt --config ui.interactive=true
783 783 file 'f' needs to be resolved.
784 784 You can keep (l)ocal [working copy], take (o)ther [merge rev], or leave (u)nresolved.
785 785 What do you want to do?
786 786 [1]
787 787 $ aftermerge
788 788 # cat f
789 789 revision 1
790 790 space
791 791 # hg stat
792 792 M f
793 793 ? f.orig
794 794 # hg resolve --list
795 795 U f
796 796 $ rm f
797 797 $ hg resolve --all --config ui.merge=internal:prompt --config ui.interactive=true
798 798 file 'f' needs to be resolved.
799 799 You can keep (l)ocal [working copy], take (o)ther [merge rev], or leave (u)nresolved.
800 800 What do you want to do?
801 801 [1]
802 802 $ aftermerge
803 803 # cat f
804 804 revision 1
805 805 space
806 806 # hg stat
807 807 M f
808 808 # hg resolve --list
809 809 U f
810 810 $ hg resolve --all --config ui.merge=internal:prompt
811 811 file 'f' needs to be resolved.
812 812 You can keep (l)ocal [working copy], take (o)ther [merge rev], or leave (u)nresolved.
813 813 What do you want to do? u
814 814 [1]
815 815 $ aftermerge
816 816 # cat f
817 817 revision 1
818 818 space
819 819 # hg stat
820 820 M f
821 821 ? f.orig
822 822 # hg resolve --list
823 823 U f
824 824
825 825 ui.merge specifies internal:dump:
826 826
827 827 $ beforemerge
828 828 [merge-tools]
829 829 false.whatever=
830 830 true.priority=1
831 831 true.executable=cat
832 832 # hg update -C 1
833 833 $ hg merge -r 2 --config ui.merge=internal:dump
834 834 merging f
835 835 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
836 836 use 'hg resolve' to retry unresolved file merges or 'hg merge --abort' to abandon
837 837 [1]
838 838 $ aftermerge
839 839 # cat f
840 840 revision 1
841 841 space
842 842 # hg stat
843 843 M f
844 844 ? f.base
845 845 ? f.local
846 846 ? f.orig
847 847 ? f.other
848 848 # hg resolve --list
849 849 U f
850 850
851 851 f.base:
852 852
853 853 $ cat f.base
854 854 revision 0
855 855 space
856 856
857 857 f.local:
858 858
859 859 $ cat f.local
860 860 revision 1
861 861 space
862 862
863 863 f.other:
864 864
865 865 $ cat f.other
866 866 revision 2
867 867 space
868 868 $ rm f.base f.local f.other
869 869
870 870 check that internal:dump doesn't dump files if premerge runs
871 871 successfully
872 872
873 873 $ beforemerge
874 874 [merge-tools]
875 875 false.whatever=
876 876 true.priority=1
877 877 true.executable=cat
878 878 # hg update -C 1
879 879 $ hg merge -r 3 --config ui.merge=internal:dump
880 880 merging f
881 881 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
882 882 (branch merge, don't forget to commit)
883 883
884 884 $ aftermerge
885 885 # cat f
886 886 revision 1
887 887 space
888 888 revision 3
889 889 # hg stat
890 890 M f
891 891 # hg resolve --list
892 892 R f
893 893
894 894 check that internal:forcedump dumps files, even if local and other can
895 895 be merged easily
896 896
897 897 $ beforemerge
898 898 [merge-tools]
899 899 false.whatever=
900 900 true.priority=1
901 901 true.executable=cat
902 902 # hg update -C 1
903 903 $ hg merge -r 3 --config ui.merge=internal:forcedump
904 904 merging f
905 905 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
906 906 use 'hg resolve' to retry unresolved file merges or 'hg merge --abort' to abandon
907 907 [1]
908 908 $ aftermerge
909 909 # cat f
910 910 revision 1
911 911 space
912 912 # hg stat
913 913 M f
914 914 ? f.base
915 915 ? f.local
916 916 ? f.orig
917 917 ? f.other
918 918 # hg resolve --list
919 919 U f
920 920
921 921 $ cat f.base
922 922 revision 0
923 923 space
924 924
925 925 $ cat f.local
926 926 revision 1
927 927 space
928 928
929 929 $ cat f.other
930 930 revision 0
931 931 space
932 932 revision 3
933 933
934 934 $ rm -f f.base f.local f.other
935 935
936 936 ui.merge specifies internal:other but is overruled by pattern for false:
937 937
938 938 $ beforemerge
939 939 [merge-tools]
940 940 false.whatever=
941 941 true.priority=1
942 942 true.executable=cat
943 943 # hg update -C 1
944 944 $ hg merge -r 2 --config ui.merge=internal:other --config merge-patterns.f=false
945 945 merging f
946 946 merging f failed!
947 947 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
948 948 use 'hg resolve' to retry unresolved file merges or 'hg merge --abort' to abandon
949 949 [1]
950 950 $ aftermerge
951 951 # cat f
952 952 revision 1
953 953 space
954 954 # hg stat
955 955 M f
956 956 ? f.orig
957 957 # hg resolve --list
958 958 U f
959 959
960 960 Premerge
961 961
962 962 ui.merge specifies internal:other but is overruled by --tool=false
963 963
964 964 $ beforemerge
965 965 [merge-tools]
966 966 false.whatever=
967 967 true.priority=1
968 968 true.executable=cat
969 969 # hg update -C 1
970 970 $ hg merge -r 2 --config ui.merge=internal:other --tool=false
971 971 merging f
972 972 merging f failed!
973 973 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
974 974 use 'hg resolve' to retry unresolved file merges or 'hg merge --abort' to abandon
975 975 [1]
976 976 $ aftermerge
977 977 # cat f
978 978 revision 1
979 979 space
980 980 # hg stat
981 981 M f
982 982 ? f.orig
983 983 # hg resolve --list
984 984 U f
985 985
986 986 HGMERGE specifies internal:other but is overruled by --tool=false
987 987
988 988 $ HGMERGE=internal:other ; export HGMERGE
989 989 $ beforemerge
990 990 [merge-tools]
991 991 false.whatever=
992 992 true.priority=1
993 993 true.executable=cat
994 994 # hg update -C 1
995 995 $ hg merge -r 2 --tool=false
996 996 merging f
997 997 merging f failed!
998 998 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
999 999 use 'hg resolve' to retry unresolved file merges or 'hg merge --abort' to abandon
1000 1000 [1]
1001 1001 $ aftermerge
1002 1002 # cat f
1003 1003 revision 1
1004 1004 space
1005 1005 # hg stat
1006 1006 M f
1007 1007 ? f.orig
1008 1008 # hg resolve --list
1009 1009 U f
1010 1010
1011 1011 $ unset HGMERGE # make sure HGMERGE doesn't interfere with remaining tests
1012 1012
1013 1013 update is a merge ...
1014 1014
1015 1015 (this also tests that files reverted with '--rev REV' are treated as
1016 1016 "modified", even if none of mode, size and timestamp of them isn't
1017 1017 changed on the filesystem (see also issue4583))
1018 1018
1019 1019 $ cat >> $HGRCPATH <<EOF
1020 1020 > [fakedirstatewritetime]
1021 1021 > # emulate invoking dirstate.write() via repo.status()
1022 1022 > # at 2000-01-01 00:00
1023 1023 > fakenow = 200001010000
1024 1024 > EOF
1025 1025
1026 1026 $ beforemerge
1027 1027 [merge-tools]
1028 1028 false.whatever=
1029 1029 true.priority=1
1030 1030 true.executable=cat
1031 1031 # hg update -C 1
1032 1032 $ hg update -q 0
1033 1033 $ f -s f
1034 1034 f: size=17
1035 1035 $ touch -t 200001010000 f
1036 1036 $ hg debugrebuildstate
1037 1037 $ cat >> $HGRCPATH <<EOF
1038 1038 > [extensions]
1039 1039 > fakedirstatewritetime = $TESTDIR/fakedirstatewritetime.py
1040 1040 > EOF
1041 1041 $ hg revert -q -r 1 .
1042 1042 $ cat >> $HGRCPATH <<EOF
1043 1043 > [extensions]
1044 1044 > fakedirstatewritetime = !
1045 1045 > EOF
1046 1046 $ f -s f
1047 1047 f: size=17
1048 1048 $ touch -t 200001010000 f
1049 1049 $ hg status f
1050 1050 M f
1051 1051 $ hg update -r 2
1052 1052 merging f
1053 1053 revision 1
1054 1054 space
1055 1055 revision 0
1056 1056 space
1057 1057 revision 2
1058 1058 space
1059 1059 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
1060 1060 $ aftermerge
1061 1061 # cat f
1062 1062 revision 1
1063 1063 space
1064 1064 # hg stat
1065 1065 M f
1066 1066 # hg resolve --list
1067 1067 R f
1068 1068
1069 1069 update should also have --tool
1070 1070
1071 1071 $ beforemerge
1072 1072 [merge-tools]
1073 1073 false.whatever=
1074 1074 true.priority=1
1075 1075 true.executable=cat
1076 1076 # hg update -C 1
1077 1077 $ hg update -q 0
1078 1078 $ f -s f
1079 1079 f: size=17
1080 1080 $ touch -t 200001010000 f
1081 1081 $ hg debugrebuildstate
1082 1082 $ cat >> $HGRCPATH <<EOF
1083 1083 > [extensions]
1084 1084 > fakedirstatewritetime = $TESTDIR/fakedirstatewritetime.py
1085 1085 > EOF
1086 1086 $ hg revert -q -r 1 .
1087 1087 $ cat >> $HGRCPATH <<EOF
1088 1088 > [extensions]
1089 1089 > fakedirstatewritetime = !
1090 1090 > EOF
1091 1091 $ f -s f
1092 1092 f: size=17
1093 1093 $ touch -t 200001010000 f
1094 1094 $ hg status f
1095 1095 M f
1096 1096 $ hg update -r 2 --tool false
1097 1097 merging f
1098 1098 merging f failed!
1099 1099 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
1100 1100 use 'hg resolve' to retry unresolved file merges
1101 1101 [1]
1102 1102 $ aftermerge
1103 1103 # cat f
1104 1104 revision 1
1105 1105 space
1106 1106 # hg stat
1107 1107 M f
1108 1108 ? f.orig
1109 1109 # hg resolve --list
1110 1110 U f
1111 1111
1112 1112 Default is silent simplemerge:
1113 1113
1114 1114 $ beforemerge
1115 1115 [merge-tools]
1116 1116 false.whatever=
1117 1117 true.priority=1
1118 1118 true.executable=cat
1119 1119 # hg update -C 1
1120 1120 $ hg merge -r 3
1121 1121 merging f
1122 1122 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
1123 1123 (branch merge, don't forget to commit)
1124 1124 $ aftermerge
1125 1125 # cat f
1126 1126 revision 1
1127 1127 space
1128 1128 revision 3
1129 1129 # hg stat
1130 1130 M f
1131 1131 # hg resolve --list
1132 1132 R f
1133 1133
1134 1134 .premerge=True is same:
1135 1135
1136 1136 $ beforemerge
1137 1137 [merge-tools]
1138 1138 false.whatever=
1139 1139 true.priority=1
1140 1140 true.executable=cat
1141 1141 # hg update -C 1
1142 1142 $ hg merge -r 3 --config merge-tools.true.premerge=True
1143 1143 merging f
1144 1144 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
1145 1145 (branch merge, don't forget to commit)
1146 1146 $ aftermerge
1147 1147 # cat f
1148 1148 revision 1
1149 1149 space
1150 1150 revision 3
1151 1151 # hg stat
1152 1152 M f
1153 1153 # hg resolve --list
1154 1154 R f
1155 1155
1156 1156 .premerge=False executes merge-tool:
1157 1157
1158 1158 $ beforemerge
1159 1159 [merge-tools]
1160 1160 false.whatever=
1161 1161 true.priority=1
1162 1162 true.executable=cat
1163 1163 # hg update -C 1
1164 1164 $ hg merge -r 3 --config merge-tools.true.premerge=False
1165 1165 merging f
1166 1166 revision 1
1167 1167 space
1168 1168 revision 0
1169 1169 space
1170 1170 revision 0
1171 1171 space
1172 1172 revision 3
1173 1173 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
1174 1174 (branch merge, don't forget to commit)
1175 1175 $ aftermerge
1176 1176 # cat f
1177 1177 revision 1
1178 1178 space
1179 1179 # hg stat
1180 1180 M f
1181 1181 # hg resolve --list
1182 1182 R f
1183 1183
1184 1184 premerge=keep keeps conflict markers in:
1185 1185
1186 1186 $ beforemerge
1187 1187 [merge-tools]
1188 1188 false.whatever=
1189 1189 true.priority=1
1190 1190 true.executable=cat
1191 1191 # hg update -C 1
1192 1192 $ hg merge -r 4 --config merge-tools.true.premerge=keep
1193 1193 merging f
1194 1194 <<<<<<< working copy: ef83787e2614 - test: revision 1
1195 1195 revision 1
1196 1196 space
1197 1197 =======
1198 1198 revision 4
1199 1199 >>>>>>> merge rev: 81448d39c9a0 - test: revision 4
1200 1200 revision 0
1201 1201 space
1202 1202 revision 4
1203 1203 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
1204 1204 (branch merge, don't forget to commit)
1205 1205 $ aftermerge
1206 1206 # cat f
1207 1207 <<<<<<< working copy: ef83787e2614 - test: revision 1
1208 1208 revision 1
1209 1209 space
1210 1210 =======
1211 1211 revision 4
1212 1212 >>>>>>> merge rev: 81448d39c9a0 - test: revision 4
1213 1213 # hg stat
1214 1214 M f
1215 1215 # hg resolve --list
1216 1216 R f
1217 1217
1218 1218 premerge=keep-merge3 keeps conflict markers with base content:
1219 1219
1220 1220 $ beforemerge
1221 1221 [merge-tools]
1222 1222 false.whatever=
1223 1223 true.priority=1
1224 1224 true.executable=cat
1225 1225 # hg update -C 1
1226 1226 $ hg merge -r 4 --config merge-tools.true.premerge=keep-merge3
1227 1227 merging f
1228 1228 <<<<<<< working copy: ef83787e2614 - test: revision 1
1229 1229 revision 1
1230 1230 space
1231 1231 ||||||| base
1232 1232 revision 0
1233 1233 space
1234 1234 =======
1235 1235 revision 4
1236 1236 >>>>>>> merge rev: 81448d39c9a0 - test: revision 4
1237 1237 revision 0
1238 1238 space
1239 1239 revision 4
1240 1240 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
1241 1241 (branch merge, don't forget to commit)
1242 1242 $ aftermerge
1243 1243 # cat f
1244 1244 <<<<<<< working copy: ef83787e2614 - test: revision 1
1245 1245 revision 1
1246 1246 space
1247 1247 ||||||| base
1248 1248 revision 0
1249 1249 space
1250 1250 =======
1251 1251 revision 4
1252 1252 >>>>>>> merge rev: 81448d39c9a0 - test: revision 4
1253 1253 # hg stat
1254 1254 M f
1255 1255 # hg resolve --list
1256 1256 R f
1257 1257
1258 1258 premerge=keep respects ui.mergemarkers=basic:
1259 1259
1260 1260 $ beforemerge
1261 1261 [merge-tools]
1262 1262 false.whatever=
1263 1263 true.priority=1
1264 1264 true.executable=cat
1265 1265 # hg update -C 1
1266 1266 $ hg merge -r 4 --config merge-tools.true.premerge=keep --config ui.mergemarkers=basic
1267 1267 merging f
1268 1268 <<<<<<< working copy
1269 1269 revision 1
1270 1270 space
1271 1271 =======
1272 1272 revision 4
1273 1273 >>>>>>> merge rev
1274 1274 revision 0
1275 1275 space
1276 1276 revision 4
1277 1277 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
1278 1278 (branch merge, don't forget to commit)
1279 1279 $ aftermerge
1280 1280 # cat f
1281 1281 <<<<<<< working copy
1282 1282 revision 1
1283 1283 space
1284 1284 =======
1285 1285 revision 4
1286 1286 >>>>>>> merge rev
1287 1287 # hg stat
1288 1288 M f
1289 1289 # hg resolve --list
1290 1290 R f
1291 1291
1292 1292 premerge=keep ignores ui.mergemarkers=basic if true.mergemarkers=detailed:
1293 1293
1294 1294 $ beforemerge
1295 1295 [merge-tools]
1296 1296 false.whatever=
1297 1297 true.priority=1
1298 1298 true.executable=cat
1299 1299 # hg update -C 1
1300 1300 $ hg merge -r 4 --config merge-tools.true.premerge=keep \
1301 1301 > --config ui.mergemarkers=basic \
1302 1302 > --config merge-tools.true.mergemarkers=detailed
1303 1303 merging f
1304 1304 <<<<<<< working copy: ef83787e2614 - test: revision 1
1305 1305 revision 1
1306 1306 space
1307 1307 =======
1308 1308 revision 4
1309 1309 >>>>>>> merge rev: 81448d39c9a0 - test: revision 4
1310 1310 revision 0
1311 1311 space
1312 1312 revision 4
1313 1313 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
1314 1314 (branch merge, don't forget to commit)
1315 1315 $ aftermerge
1316 1316 # cat f
1317 1317 <<<<<<< working copy: ef83787e2614 - test: revision 1
1318 1318 revision 1
1319 1319 space
1320 1320 =======
1321 1321 revision 4
1322 1322 >>>>>>> merge rev: 81448d39c9a0 - test: revision 4
1323 1323 # hg stat
1324 1324 M f
1325 1325 # hg resolve --list
1326 1326 R f
1327 1327
1328 1328 premerge=keep respects ui.mergemarkertemplate instead of
1329 1329 true.mergemarkertemplate if true.mergemarkers=basic:
1330 1330
1331 1331 $ beforemerge
1332 1332 [merge-tools]
1333 1333 false.whatever=
1334 1334 true.priority=1
1335 1335 true.executable=cat
1336 1336 # hg update -C 1
1337 1337 $ hg merge -r 4 --config merge-tools.true.premerge=keep \
1338 1338 > --config ui.mergemarkertemplate='uitmpl {rev}' \
1339 1339 > --config merge-tools.true.mergemarkertemplate='tooltmpl {short(node)}'
1340 1340 merging f
1341 1341 <<<<<<< working copy: uitmpl 1
1342 1342 revision 1
1343 1343 space
1344 1344 =======
1345 1345 revision 4
1346 1346 >>>>>>> merge rev: uitmpl 4
1347 1347 revision 0
1348 1348 space
1349 1349 revision 4
1350 1350 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
1351 1351 (branch merge, don't forget to commit)
1352 1352 $ aftermerge
1353 1353 # cat f
1354 1354 <<<<<<< working copy: uitmpl 1
1355 1355 revision 1
1356 1356 space
1357 1357 =======
1358 1358 revision 4
1359 1359 >>>>>>> merge rev: uitmpl 4
1360 1360 # hg stat
1361 1361 M f
1362 1362 # hg resolve --list
1363 1363 R f
1364 1364
1365 1365 premerge=keep respects true.mergemarkertemplate instead of
1366 1366 true.mergemarkertemplate if true.mergemarkers=detailed:
1367 1367
1368 1368 $ beforemerge
1369 1369 [merge-tools]
1370 1370 false.whatever=
1371 1371 true.priority=1
1372 1372 true.executable=cat
1373 1373 # hg update -C 1
1374 1374 $ hg merge -r 4 --config merge-tools.true.premerge=keep \
1375 1375 > --config ui.mergemarkertemplate='uitmpl {rev}' \
1376 1376 > --config merge-tools.true.mergemarkertemplate='tooltmpl {short(node)}' \
1377 1377 > --config merge-tools.true.mergemarkers=detailed
1378 1378 merging f
1379 1379 <<<<<<< working copy: tooltmpl ef83787e2614
1380 1380 revision 1
1381 1381 space
1382 1382 =======
1383 1383 revision 4
1384 1384 >>>>>>> merge rev: tooltmpl 81448d39c9a0
1385 1385 revision 0
1386 1386 space
1387 1387 revision 4
1388 1388 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
1389 1389 (branch merge, don't forget to commit)
1390 1390 $ aftermerge
1391 1391 # cat f
1392 1392 <<<<<<< working copy: tooltmpl ef83787e2614
1393 1393 revision 1
1394 1394 space
1395 1395 =======
1396 1396 revision 4
1397 1397 >>>>>>> merge rev: tooltmpl 81448d39c9a0
1398 1398 # hg stat
1399 1399 M f
1400 1400 # hg resolve --list
1401 1401 R f
1402 1402
1403 1403 Tool execution
1404 1404
1405 1405 set tools.args explicit to include $base $local $other $output:
1406 1406
1407 1407 $ beforemerge
1408 1408 [merge-tools]
1409 1409 false.whatever=
1410 1410 true.priority=1
1411 1411 true.executable=cat
1412 1412 # hg update -C 1
1413 1413 $ hg merge -r 2 --config merge-tools.true.executable=head --config merge-tools.true.args='$base $local $other $output' \
1414 1414 > | sed 's,==> .* <==,==> ... <==,g'
1415 1415 merging f
1416 1416 ==> ... <==
1417 1417 revision 0
1418 1418 space
1419 1419
1420 1420 ==> ... <==
1421 1421 revision 1
1422 1422 space
1423 1423
1424 1424 ==> ... <==
1425 1425 revision 2
1426 1426 space
1427 1427
1428 1428 ==> ... <==
1429 1429 revision 1
1430 1430 space
1431 1431 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
1432 1432 (branch merge, don't forget to commit)
1433 1433 $ aftermerge
1434 1434 # cat f
1435 1435 revision 1
1436 1436 space
1437 1437 # hg stat
1438 1438 M f
1439 1439 # hg resolve --list
1440 1440 R f
1441 1441
1442 1442 Merge with "echo mergeresult > $local":
1443 1443
1444 1444 $ beforemerge
1445 1445 [merge-tools]
1446 1446 false.whatever=
1447 1447 true.priority=1
1448 1448 true.executable=cat
1449 1449 # hg update -C 1
1450 1450 $ hg merge -r 2 --config merge-tools.true.executable=echo --config merge-tools.true.args='mergeresult > $local'
1451 1451 merging f
1452 1452 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
1453 1453 (branch merge, don't forget to commit)
1454 1454 $ aftermerge
1455 1455 # cat f
1456 1456 mergeresult
1457 1457 # hg stat
1458 1458 M f
1459 1459 # hg resolve --list
1460 1460 R f
1461 1461
1462 1462 - and $local is the file f:
1463 1463
1464 1464 $ beforemerge
1465 1465 [merge-tools]
1466 1466 false.whatever=
1467 1467 true.priority=1
1468 1468 true.executable=cat
1469 1469 # hg update -C 1
1470 1470 $ hg merge -r 2 --config merge-tools.true.executable=echo --config merge-tools.true.args='mergeresult > f'
1471 1471 merging f
1472 1472 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
1473 1473 (branch merge, don't forget to commit)
1474 1474 $ aftermerge
1475 1475 # cat f
1476 1476 mergeresult
1477 1477 # hg stat
1478 1478 M f
1479 1479 # hg resolve --list
1480 1480 R f
1481 1481
1482 1482 Merge with "echo mergeresult > $output" - the variable is a bit magic:
1483 1483
1484 1484 $ beforemerge
1485 1485 [merge-tools]
1486 1486 false.whatever=
1487 1487 true.priority=1
1488 1488 true.executable=cat
1489 1489 # hg update -C 1
1490 1490 $ hg merge -r 2 --config merge-tools.true.executable=echo --config merge-tools.true.args='mergeresult > $output'
1491 1491 merging f
1492 1492 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
1493 1493 (branch merge, don't forget to commit)
1494 1494 $ aftermerge
1495 1495 # cat f
1496 1496 mergeresult
1497 1497 # hg stat
1498 1498 M f
1499 1499 # hg resolve --list
1500 1500 R f
1501 1501
1502 1502 Merge using tool with a path that must be quoted:
1503 1503
1504 1504 $ beforemerge
1505 1505 [merge-tools]
1506 1506 false.whatever=
1507 1507 true.priority=1
1508 1508 true.executable=cat
1509 1509 # hg update -C 1
1510 1510 $ cat <<EOF > 'my merge tool'
1511 1511 > cat "\$1" "\$2" "\$3" > "\$4"
1512 1512 > EOF
1513 1513 $ hg --config merge-tools.true.executable='sh' \
1514 1514 > --config merge-tools.true.args='"./my merge tool" $base $local $other $output' \
1515 1515 > merge -r 2
1516 1516 merging f
1517 1517 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
1518 1518 (branch merge, don't forget to commit)
1519 1519 $ rm -f 'my merge tool'
1520 1520 $ aftermerge
1521 1521 # cat f
1522 1522 revision 0
1523 1523 space
1524 1524 revision 1
1525 1525 space
1526 1526 revision 2
1527 1527 space
1528 1528 # hg stat
1529 1529 M f
1530 1530 # hg resolve --list
1531 1531 R f
1532 1532
1533 1533 Merge using a tool that supports labellocal, labelother, and labelbase, checking
1534 1534 that they're quoted properly as well. This is using the default 'basic'
1535 1535 mergemarkers even though ui.mergemarkers is 'detailed', so it's ignoring both
1536 1536 mergemarkertemplate settings:
1537 1537
1538 1538 $ beforemerge
1539 1539 [merge-tools]
1540 1540 false.whatever=
1541 1541 true.priority=1
1542 1542 true.executable=cat
1543 1543 # hg update -C 1
1544 1544 $ cat <<EOF > printargs_merge_tool
1545 1545 > while test \$# -gt 0; do echo arg: \"\$1\"; shift; done
1546 1546 > EOF
1547 1547 $ hg --config merge-tools.true.executable='sh' \
1548 1548 > --config merge-tools.true.args='./printargs_merge_tool ll:$labellocal lo: $labelother lb:$labelbase": "$base' \
1549 1549 > --config merge-tools.true.mergemarkertemplate='tooltmpl {short(node)}' \
1550 1550 > --config ui.mergemarkertemplate='uitmpl {rev}' \
1551 1551 > --config ui.mergemarkers=detailed \
1552 1552 > merge -r 2
1553 1553 merging f
1554 1554 arg: "ll:working copy"
1555 1555 arg: "lo:"
1556 1556 arg: "merge rev"
1557 1557 arg: "lb:base: */f~base.*" (glob)
1558 1558 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
1559 1559 (branch merge, don't forget to commit)
1560 1560 $ rm -f 'printargs_merge_tool'
1561 1561
1562 1562 Same test with experimental.mergetempdirprefix set:
1563 1563
1564 1564 $ beforemerge
1565 1565 [merge-tools]
1566 1566 false.whatever=
1567 1567 true.priority=1
1568 1568 true.executable=cat
1569 1569 # hg update -C 1
1570 1570 $ cat <<EOF > printargs_merge_tool
1571 1571 > while test \$# -gt 0; do echo arg: \"\$1\"; shift; done
1572 1572 > EOF
1573 1573 $ hg --config experimental.mergetempdirprefix=$TESTTMP/hgmerge. \
1574 1574 > --config merge-tools.true.executable='sh' \
1575 1575 > --config merge-tools.true.args='./printargs_merge_tool ll:$labellocal lo: $labelother lb:$labelbase": "$base' \
1576 1576 > --config merge-tools.true.mergemarkertemplate='tooltmpl {short(node)}' \
1577 1577 > --config ui.mergemarkertemplate='uitmpl {rev}' \
1578 1578 > --config ui.mergemarkers=detailed \
1579 1579 > merge -r 2
1580 1580 merging f
1581 1581 arg: "ll:working copy"
1582 1582 arg: "lo:"
1583 1583 arg: "merge rev"
1584 1584 arg: "lb:base: */hgmerge.*/f~base" (glob)
1585 1585 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
1586 1586 (branch merge, don't forget to commit)
1587 1587 $ rm -f 'printargs_merge_tool'
1588 1588
1589 1589 Merge using a tool that supports labellocal, labelother, and labelbase, checking
1590 1590 that they're quoted properly as well. This is using 'detailed' mergemarkers,
1591 1591 even though ui.mergemarkers is 'basic', and using the tool's
1592 1592 mergemarkertemplate:
1593 1593
1594 1594 $ beforemerge
1595 1595 [merge-tools]
1596 1596 false.whatever=
1597 1597 true.priority=1
1598 1598 true.executable=cat
1599 1599 # hg update -C 1
1600 1600 $ cat <<EOF > printargs_merge_tool
1601 1601 > while test \$# -gt 0; do echo arg: \"\$1\"; shift; done
1602 1602 > EOF
1603 1603 $ hg --config merge-tools.true.executable='sh' \
1604 1604 > --config merge-tools.true.args='./printargs_merge_tool ll:$labellocal lo: $labelother lb:$labelbase": "$base' \
1605 1605 > --config merge-tools.true.mergemarkers=detailed \
1606 1606 > --config merge-tools.true.mergemarkertemplate='tooltmpl {short(node)}' \
1607 1607 > --config ui.mergemarkertemplate='uitmpl {rev}' \
1608 1608 > --config ui.mergemarkers=basic \
1609 1609 > merge -r 2
1610 1610 merging f
1611 1611 arg: "ll:working copy: tooltmpl ef83787e2614"
1612 1612 arg: "lo:"
1613 1613 arg: "merge rev: tooltmpl 0185f4e0cf02"
1614 1614 arg: "lb:base: */f~base.*" (glob)
1615 1615 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
1616 1616 (branch merge, don't forget to commit)
1617 1617 $ rm -f 'printargs_merge_tool'
1618 1618
1619 1619 The merge tool still gets labellocal and labelother as 'basic' even when
1620 1620 premerge=keep is used and has 'detailed' markers:
1621 1621
1622 1622 $ beforemerge
1623 1623 [merge-tools]
1624 1624 false.whatever=
1625 1625 true.priority=1
1626 1626 true.executable=cat
1627 1627 # hg update -C 1
1628 1628 $ cat <<EOF > mytool
1629 1629 > echo labellocal: \"\$1\"
1630 1630 > echo labelother: \"\$2\"
1631 1631 > echo "output (arg)": \"\$3\"
1632 1632 > echo "output (contents)":
1633 1633 > cat "\$3"
1634 1634 > EOF
1635 1635 $ hg --config merge-tools.true.executable='sh' \
1636 1636 > --config merge-tools.true.args='mytool $labellocal $labelother $output' \
1637 1637 > --config merge-tools.true.premerge=keep \
1638 1638 > --config merge-tools.true.mergemarkertemplate='tooltmpl {short(node)}' \
1639 1639 > --config ui.mergemarkertemplate='uitmpl {rev}' \
1640 1640 > --config ui.mergemarkers=detailed \
1641 1641 > merge -r 2
1642 1642 merging f
1643 1643 labellocal: "working copy"
1644 1644 labelother: "merge rev"
1645 1645 output (arg): "$TESTTMP/repo/f"
1646 1646 output (contents):
1647 1647 <<<<<<< working copy: uitmpl 1
1648 1648 revision 1
1649 1649 =======
1650 1650 revision 2
1651 1651 >>>>>>> merge rev: uitmpl 2
1652 1652 space
1653 1653 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
1654 1654 (branch merge, don't forget to commit)
1655 1655 $ rm -f 'mytool'
1656 1656
1657 1657 premerge=keep uses the *tool's* mergemarkertemplate if tool's
1658 1658 mergemarkers=detailed; labellocal and labelother also use the tool's template
1659 1659
1660 1660 $ beforemerge
1661 1661 [merge-tools]
1662 1662 false.whatever=
1663 1663 true.priority=1
1664 1664 true.executable=cat
1665 1665 # hg update -C 1
1666 1666 $ cat <<EOF > mytool
1667 1667 > echo labellocal: \"\$1\"
1668 1668 > echo labelother: \"\$2\"
1669 1669 > echo "output (arg)": \"\$3\"
1670 1670 > echo "output (contents)":
1671 1671 > cat "\$3"
1672 1672 > EOF
1673 1673 $ hg --config merge-tools.true.executable='sh' \
1674 1674 > --config merge-tools.true.args='mytool $labellocal $labelother $output' \
1675 1675 > --config merge-tools.true.premerge=keep \
1676 1676 > --config merge-tools.true.mergemarkers=detailed \
1677 1677 > --config merge-tools.true.mergemarkertemplate='tooltmpl {short(node)}' \
1678 1678 > --config ui.mergemarkertemplate='uitmpl {rev}' \
1679 1679 > --config ui.mergemarkers=detailed \
1680 1680 > merge -r 2
1681 1681 merging f
1682 1682 labellocal: "working copy: tooltmpl ef83787e2614"
1683 1683 labelother: "merge rev: tooltmpl 0185f4e0cf02"
1684 1684 output (arg): "$TESTTMP/repo/f"
1685 1685 output (contents):
1686 1686 <<<<<<< working copy: tooltmpl ef83787e2614
1687 1687 revision 1
1688 1688 =======
1689 1689 revision 2
1690 1690 >>>>>>> merge rev: tooltmpl 0185f4e0cf02
1691 1691 space
1692 1692 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
1693 1693 (branch merge, don't forget to commit)
1694 1694 $ rm -f 'mytool'
1695 1695
1696 1696 Issue3581: Merging a filename that needs to be quoted
1697 1697 (This test doesn't work on Windows filesystems even on Linux, so check
1698 1698 for Unix-like permission)
1699 1699
1700 1700 #if unix-permissions
1701 1701 $ beforemerge
1702 1702 [merge-tools]
1703 1703 false.whatever=
1704 1704 true.priority=1
1705 1705 true.executable=cat
1706 1706 # hg update -C 1
1707 1707 $ echo "revision 5" > '"; exit 1; echo "'
1708 1708 $ hg commit -Am "revision 5"
1709 1709 adding "; exit 1; echo "
1710 1710 warning: filename contains '"', which is reserved on Windows: '"; exit 1; echo "'
1711 1711 $ hg update -C 1 > /dev/null
1712 1712 $ echo "revision 6" > '"; exit 1; echo "'
1713 1713 $ hg commit -Am "revision 6"
1714 1714 adding "; exit 1; echo "
1715 1715 warning: filename contains '"', which is reserved on Windows: '"; exit 1; echo "'
1716 1716 created new head
1717 1717 $ hg merge --config merge-tools.true.executable="true" -r 5
1718 1718 merging "; exit 1; echo "
1719 1719 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
1720 1720 (branch merge, don't forget to commit)
1721 1721 $ hg update -C 1 > /dev/null
1722 1722
1723 1723 #else
1724 1724
1725 1725 Match the non-portable filename commits above for test stability
1726 1726
1727 1727 $ hg import --bypass -q - << EOF
1728 1728 > # HG changeset patch
1729 1729 > revision 5
1730 1730 >
1731 1731 > diff --git a/"; exit 1; echo " b/"; exit 1; echo "
1732 1732 > new file mode 100644
1733 1733 > --- /dev/null
1734 1734 > +++ b/"; exit 1; echo "
1735 1735 > @@ -0,0 +1,1 @@
1736 1736 > +revision 5
1737 1737 > EOF
1738 1738
1739 1739 $ hg import --bypass -q - << EOF
1740 1740 > # HG changeset patch
1741 1741 > revision 6
1742 1742 >
1743 1743 > diff --git a/"; exit 1; echo " b/"; exit 1; echo "
1744 1744 > new file mode 100644
1745 1745 > --- /dev/null
1746 1746 > +++ b/"; exit 1; echo "
1747 1747 > @@ -0,0 +1,1 @@
1748 1748 > +revision 6
1749 1749 > EOF
1750 1750
1751 1751 #endif
1752 1752
1753 1753 Merge post-processing
1754 1754
1755 1755 cat is a bad merge-tool and doesn't change:
1756 1756
1757 1757 $ beforemerge
1758 1758 [merge-tools]
1759 1759 false.whatever=
1760 1760 true.priority=1
1761 1761 true.executable=cat
1762 1762 # hg update -C 1
1763 1763 $ hg merge -y -r 2 --config merge-tools.true.checkchanged=1
1764 1764 merging f
1765 1765 revision 1
1766 1766 space
1767 1767 revision 0
1768 1768 space
1769 1769 revision 2
1770 1770 space
1771 1771 output file f appears unchanged
1772 1772 was merge successful (yn)? n
1773 1773 merging f failed!
1774 1774 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
1775 1775 use 'hg resolve' to retry unresolved file merges or 'hg merge --abort' to abandon
1776 1776 [1]
1777 1777 $ aftermerge
1778 1778 # cat f
1779 1779 revision 1
1780 1780 space
1781 1781 # hg stat
1782 1782 M f
1783 1783 ? f.orig
1784 1784 # hg resolve --list
1785 1785 U f
1786 1786
1787 1787 missingbinary is a merge-tool that doesn't exist:
1788 1788
1789 1789 $ echo "missingbinary.executable=doesnotexist" >> .hg/hgrc
1790 1790 $ beforemerge
1791 1791 [merge-tools]
1792 1792 false.whatever=
1793 1793 true.priority=1
1794 1794 true.executable=cat
1795 1795 missingbinary.executable=doesnotexist
1796 1796 # hg update -C 1
1797 1797 $ hg merge -y -r 2 --config ui.merge=missingbinary
1798 1798 couldn't find merge tool missingbinary (for pattern f)
1799 1799 merging f
1800 1800 couldn't find merge tool missingbinary (for pattern f)
1801 1801 revision 1
1802 1802 space
1803 1803 revision 0
1804 1804 space
1805 1805 revision 2
1806 1806 space
1807 1807 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
1808 1808 (branch merge, don't forget to commit)
1809 1809
1810 1810 $ hg update -q -C 1
1811 1811 $ rm f
1812 1812
1813 1813 internal merge cannot handle symlinks and shouldn't try:
1814 1814
1815 1815 #if symlink
1816 1816
1817 1817 $ ln -s symlink f
1818 1818 $ hg commit -qm 'f is symlink'
1819 1819
1820 1820 #else
1821 1821
1822 1822 $ hg import --bypass -q - << EOF
1823 1823 > # HG changeset patch
1824 1824 > f is symlink
1825 1825 >
1826 1826 > diff --git a/f b/f
1827 1827 > old mode 100644
1828 1828 > new mode 120000
1829 1829 > --- a/f
1830 1830 > +++ b/f
1831 1831 > @@ -1,2 +1,1 @@
1832 1832 > -revision 1
1833 1833 > -space
1834 1834 > +symlink
1835 1835 > \ No newline at end of file
1836 1836 > EOF
1837 1837
1838 1838 Resolve 'other [destination] changed f which local [working copy] deleted' prompt
1839 1839 $ hg up -q -C --config ui.interactive=True << EOF
1840 1840 > c
1841 1841 > EOF
1842 1842
1843 1843 #endif
1844 1844
1845 1845 $ hg merge -r 2 --tool internal:merge
1846 1846 merging f
1847 1847 warning: internal :merge cannot merge symlinks for f
1848 1848 warning: conflicts while merging f! (edit, then use 'hg resolve --mark')
1849 1849 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
1850 1850 use 'hg resolve' to retry unresolved file merges or 'hg merge --abort' to abandon
1851 1851 [1]
1852 1852
1853 1853 Verify naming of temporary files and that extension is preserved:
1854 1854
1855 1855 $ hg update -q -C 1
1856 1856 $ hg mv f f.txt
1857 1857 $ hg ci -qm "f.txt"
1858 1858 $ hg update -q -C 2
1859 1859 $ hg merge -y -r tip --tool echo --config merge-tools.echo.args='$base $local $other $output'
1860 1860 merging f and f.txt to f.txt
1861 1861 */f~base.* */f~local.*.txt */f~other.*.txt $TESTTMP/repo/f.txt (glob)
1862 1862 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
1863 1863 (branch merge, don't forget to commit)
1864 1864
1865 1865 Verify naming of temporary files and that extension is preserved
1866 1866 (experimental.mergetempdirprefix version):
1867 1867
1868 1868 $ hg update -q -C 1
1869 1869 $ hg mv f f.txt
1870 1870 $ hg ci -qm "f.txt"
1871 warning: commit already existed in the repository!
1871 1872 $ hg update -q -C 2
1872 1873 $ hg merge -y -r tip --tool echo \
1873 1874 > --config merge-tools.echo.args='$base $local $other $output' \
1874 1875 > --config experimental.mergetempdirprefix=$TESTTMP/hgmerge.
1875 1876 merging f and f.txt to f.txt
1876 1877 $TESTTMP/hgmerge.*/f~base $TESTTMP/hgmerge.*/f~local.txt $TESTTMP/hgmerge.*/f~other.txt $TESTTMP/repo/f.txt (glob)
1877 1878 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
1878 1879 (branch merge, don't forget to commit)
1879 1880
1880 1881 Binary files capability checking
1881 1882
1882 1883 $ hg update -q -C 0
1883 1884 $ python <<EOF
1884 1885 > with open('b', 'wb') as fp:
1885 1886 > fp.write(b'\x00\x01\x02\x03')
1886 1887 > EOF
1887 1888 $ hg add b
1888 1889 $ hg commit -qm "add binary file (#1)"
1889 1890
1890 1891 $ hg update -q -C 0
1891 1892 $ python <<EOF
1892 1893 > with open('b', 'wb') as fp:
1893 1894 > fp.write(b'\x03\x02\x01\x00')
1894 1895 > EOF
1895 1896 $ hg add b
1896 1897 $ hg commit -qm "add binary file (#2)"
1897 1898
1898 1899 By default, binary files capability of internal merge tools is not
1899 1900 checked strictly.
1900 1901
1901 1902 (for merge-patterns, chosen unintentionally)
1902 1903
1903 1904 $ hg merge 9 \
1904 1905 > --config merge-patterns.b=:merge-other \
1905 1906 > --config merge-patterns.re:[a-z]=:other
1906 1907 warning: check merge-patterns configurations, if ':merge-other' for binary file 'b' is unintentional
1907 1908 (see 'hg help merge-tools' for binary files capability)
1908 1909 merging b
1909 1910 warning: b looks like a binary file.
1910 1911 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
1911 1912 use 'hg resolve' to retry unresolved file merges or 'hg merge --abort' to abandon
1912 1913 [1]
1913 1914 (Testing that commands.merge.require-rev doesn't break --abort)
1914 1915 $ hg merge --abort -q
1915 1916
1916 1917 (for ui.merge, ignored unintentionally)
1917 1918
1918 1919 $ hg merge 9 \
1919 1920 > --config merge-tools.:other.binary=true \
1920 1921 > --config ui.merge=:other
1921 1922 tool :other (for pattern b) can't handle binary
1922 1923 tool true can't handle binary
1923 1924 tool :other can't handle binary
1924 1925 tool false can't handle binary
1925 1926 no tool found to merge b
1926 1927 file 'b' needs to be resolved.
1927 1928 You can keep (l)ocal [working copy], take (o)ther [merge rev], or leave (u)nresolved.
1928 1929 What do you want to do? u
1929 1930 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
1930 1931 use 'hg resolve' to retry unresolved file merges or 'hg merge --abort' to abandon
1931 1932 [1]
1932 1933 $ hg merge --abort -q
1933 1934
1934 1935 With merge.strict-capability-check=true, binary files capability of
1935 1936 internal merge tools is checked strictly.
1936 1937
1937 1938 $ f --hexdump b
1938 1939 b:
1939 1940 0000: 03 02 01 00 |....|
1940 1941
1941 1942 (for merge-patterns)
1942 1943
1943 1944 $ hg merge 9 --config merge.strict-capability-check=true \
1944 1945 > --config merge-tools.:merge-other.binary=true \
1945 1946 > --config merge-patterns.b=:merge-other \
1946 1947 > --config merge-patterns.re:[a-z]=:other
1947 1948 tool :merge-other (for pattern b) can't handle binary
1948 1949 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
1949 1950 (branch merge, don't forget to commit)
1950 1951 $ f --hexdump b
1951 1952 b:
1952 1953 0000: 00 01 02 03 |....|
1953 1954 $ hg merge --abort -q
1954 1955
1955 1956 (for ui.merge)
1956 1957
1957 1958 $ hg merge 9 --config merge.strict-capability-check=true \
1958 1959 > --config ui.merge=:other
1959 1960 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
1960 1961 (branch merge, don't forget to commit)
1961 1962 $ f --hexdump b
1962 1963 b:
1963 1964 0000: 00 01 02 03 |....|
1964 1965 $ hg merge --abort -q
1965 1966
1966 1967 Check that the extra information is printed correctly
1967 1968
1968 1969 $ hg merge 9 \
1969 1970 > --config merge-tools.testecho.executable='echo' \
1970 1971 > --config merge-tools.testecho.args='merge runs here ...' \
1971 1972 > --config merge-tools.testecho.binary=True \
1972 1973 > --config ui.merge=testecho \
1973 1974 > --config ui.pre-merge-tool-output-template='\n{label("extmerge.running_merge_tool", "Running merge tool for {path} ({toolpath}):")}\n{separate("\n", extmerge_section(local), extmerge_section(base), extmerge_section(other))}\n' \
1974 1975 > --config 'templatealias.extmerge_section(sect)="- {pad("{sect.name} ({sect.label})", 20, left=True)}: {revset(sect.node)%"{rev}:{shortest(node,8)} {desc|firstline} {separate(" ", tags, bookmarks, branch)}"}"'
1975 1976 merging b
1976 1977
1977 1978 Running merge tool for b ("*/bin/echo.exe"): (glob) (windows !)
1978 1979 Running merge tool for b (*/bin/echo): (glob) (no-windows !)
1979 1980 - local (working copy): 10:2d1f533d add binary file (#2) tip default
1980 1981 - base (base): -1:00000000 default
1981 1982 - other (merge rev): 9:1e7ad7d7 add binary file (#1) default
1982 1983 merge runs here ...
1983 1984 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
1984 1985 (branch merge, don't forget to commit)
1985 1986
1986 1987 Check that debugpicktool examines which merge tool is chosen for
1987 1988 specified file as expected
1988 1989
1989 1990 $ beforemerge
1990 1991 [merge-tools]
1991 1992 false.whatever=
1992 1993 true.priority=1
1993 1994 true.executable=cat
1994 1995 missingbinary.executable=doesnotexist
1995 1996 # hg update -C 1
1996 1997
1997 1998 (default behavior: checking files in the working parent context)
1998 1999
1999 2000 $ hg manifest
2000 2001 f
2001 2002 $ hg debugpickmergetool
2002 2003 f = true
2003 2004
2004 2005 (-X/-I and file patterns limmit examination targets)
2005 2006
2006 2007 $ hg debugpickmergetool -X f
2007 2008 $ hg debugpickmergetool unknown
2008 2009 unknown: no such file in rev ef83787e2614
2009 2010
2010 2011 (--changedelete emulates merging change and delete)
2011 2012
2012 2013 $ hg debugpickmergetool --changedelete
2013 2014 f = :prompt
2014 2015
2015 2016 (-r REV causes checking files in specified revision)
2016 2017
2017 2018 $ hg manifest -r 8
2018 2019 f.txt
2019 2020 $ hg debugpickmergetool -r 8
2020 2021 f.txt = true
2021 2022
2022 2023 #if symlink
2023 2024
2024 2025 (symlink causes chosing :prompt)
2025 2026
2026 2027 $ hg debugpickmergetool -r 6d00b3726f6e
2027 2028 f = :prompt
2028 2029
2029 2030 (by default, it is assumed that no internal merge tools has symlinks
2030 2031 capability)
2031 2032
2032 2033 $ hg debugpickmergetool \
2033 2034 > -r 6d00b3726f6e \
2034 2035 > --config merge-tools.:merge-other.symlink=true \
2035 2036 > --config merge-patterns.f=:merge-other \
2036 2037 > --config merge-patterns.re:[f]=:merge-local \
2037 2038 > --config merge-patterns.re:[a-z]=:other
2038 2039 f = :prompt
2039 2040
2040 2041 $ hg debugpickmergetool \
2041 2042 > -r 6d00b3726f6e \
2042 2043 > --config merge-tools.:other.symlink=true \
2043 2044 > --config ui.merge=:other
2044 2045 f = :prompt
2045 2046
2046 2047 (with strict-capability-check=true, actual symlink capabilities are
2047 2048 checked striclty)
2048 2049
2049 2050 $ hg debugpickmergetool --config merge.strict-capability-check=true \
2050 2051 > -r 6d00b3726f6e \
2051 2052 > --config merge-tools.:merge-other.symlink=true \
2052 2053 > --config merge-patterns.f=:merge-other \
2053 2054 > --config merge-patterns.re:[f]=:merge-local \
2054 2055 > --config merge-patterns.re:[a-z]=:other
2055 2056 f = :other
2056 2057
2057 2058 $ hg debugpickmergetool --config merge.strict-capability-check=true \
2058 2059 > -r 6d00b3726f6e \
2059 2060 > --config ui.merge=:other
2060 2061 f = :other
2061 2062
2062 2063 $ hg debugpickmergetool --config merge.strict-capability-check=true \
2063 2064 > -r 6d00b3726f6e \
2064 2065 > --config merge-tools.:merge-other.symlink=true \
2065 2066 > --config ui.merge=:merge-other
2066 2067 f = :prompt
2067 2068
2068 2069 #endif
2069 2070
2070 2071 (--verbose shows some configurations)
2071 2072
2072 2073 $ hg debugpickmergetool --tool foobar -v
2073 2074 with --tool 'foobar'
2074 2075 f = foobar
2075 2076
2076 2077 $ HGMERGE=false hg debugpickmergetool -v
2077 2078 with HGMERGE='false'
2078 2079 f = false
2079 2080
2080 2081 $ hg debugpickmergetool --config ui.merge=false -v
2081 2082 with ui.merge='false'
2082 2083 f = false
2083 2084
2084 2085 (--debug shows errors detected intermediately)
2085 2086
2086 2087 $ hg debugpickmergetool --config merge-patterns.f=true --config merge-tools.true.executable=nonexistentmergetool --debug f
2087 2088 couldn't find merge tool true (for pattern f)
2088 2089 couldn't find merge tool true
2089 2090 f = false
2090 2091
2091 2092 $ cd ..
@@ -1,1053 +1,1054 b''
1 1 $ cat > $TESTTMP/hook.sh << 'EOF'
2 2 > echo "test-hook-close-phase: $HG_NODE: $HG_OLDPHASE -> $HG_PHASE"
3 3 > EOF
4 4
5 5 $ cat >> $HGRCPATH << EOF
6 6 > [extensions]
7 7 > phasereport=$TESTDIR/testlib/ext-phase-report.py
8 8 > [hooks]
9 9 > txnclose-phase.test = sh $TESTTMP/hook.sh
10 10 > EOF
11 11
12 12 $ hglog() { hg log --template "{rev} {phaseidx} {desc}\n" $*; }
13 13 $ mkcommit() {
14 14 > echo "$1" > "$1"
15 15 > hg add "$1"
16 16 > message="$1"
17 17 > shift
18 18 > hg ci -m "$message" $*
19 19 > }
20 20
21 21 $ hg init initialrepo
22 22 $ cd initialrepo
23 23
24 24 Cannot change null revision phase
25 25
26 26 $ hg phase --force --secret null
27 27 abort: cannot change null revision phase
28 28 [255]
29 29 $ hg phase null
30 30 -1: public
31 31
32 32 $ mkcommit A
33 33 test-debug-phase: new rev 0: x -> 1
34 34 test-hook-close-phase: 4a2df7238c3b48766b5e22fafbb8a2f506ec8256: -> draft
35 35
36 36 New commit are draft by default
37 37
38 38 $ hglog
39 39 0 1 A
40 40
41 41 Following commit are draft too
42 42
43 43 $ mkcommit B
44 44 test-debug-phase: new rev 1: x -> 1
45 45 test-hook-close-phase: 27547f69f25460a52fff66ad004e58da7ad3fb56: -> draft
46 46
47 47 $ hglog
48 48 1 1 B
49 49 0 1 A
50 50
51 51 Working directory phase is secret when its parent is secret.
52 52
53 53 $ hg phase --force --secret .
54 54 test-debug-phase: move rev 0: 1 -> 2
55 55 test-debug-phase: move rev 1: 1 -> 2
56 56 test-hook-close-phase: 4a2df7238c3b48766b5e22fafbb8a2f506ec8256: draft -> secret
57 57 test-hook-close-phase: 27547f69f25460a52fff66ad004e58da7ad3fb56: draft -> secret
58 58 $ hg log -r 'wdir()' -T '{phase}\n'
59 59 secret
60 60 $ hg log -r 'wdir() and public()' -T '{phase}\n'
61 61 $ hg log -r 'wdir() and draft()' -T '{phase}\n'
62 62 $ hg log -r 'wdir() and secret()' -T '{phase}\n'
63 63 secret
64 64
65 65 Working directory phase is draft when its parent is draft.
66 66
67 67 $ hg phase --draft .
68 68 test-debug-phase: move rev 1: 2 -> 1
69 69 test-hook-close-phase: 27547f69f25460a52fff66ad004e58da7ad3fb56: secret -> draft
70 70 $ hg log -r 'wdir()' -T '{phase}\n'
71 71 draft
72 72 $ hg log -r 'wdir() and public()' -T '{phase}\n'
73 73 $ hg log -r 'wdir() and draft()' -T '{phase}\n'
74 74 draft
75 75 $ hg log -r 'wdir() and secret()' -T '{phase}\n'
76 76
77 77 Working directory phase is secret when a new commit will be created as secret,
78 78 even if the parent is draft.
79 79
80 80 $ hg log -r 'wdir() and secret()' -T '{phase}\n' \
81 81 > --config phases.new-commit='secret'
82 82 secret
83 83
84 84 Working directory phase is draft when its parent is public.
85 85
86 86 $ hg phase --public .
87 87 test-debug-phase: move rev 0: 1 -> 0
88 88 test-debug-phase: move rev 1: 1 -> 0
89 89 test-hook-close-phase: 4a2df7238c3b48766b5e22fafbb8a2f506ec8256: draft -> public
90 90 test-hook-close-phase: 27547f69f25460a52fff66ad004e58da7ad3fb56: draft -> public
91 91 $ hg log -r 'wdir()' -T '{phase}\n'
92 92 draft
93 93 $ hg log -r 'wdir() and public()' -T '{phase}\n'
94 94 $ hg log -r 'wdir() and draft()' -T '{phase}\n'
95 95 draft
96 96 $ hg log -r 'wdir() and secret()' -T '{phase}\n'
97 97 $ hg log -r 'wdir() and secret()' -T '{phase}\n' \
98 98 > --config phases.new-commit='secret'
99 99 secret
100 100
101 101 Draft commit are properly created over public one:
102 102
103 103 $ hg phase
104 104 1: public
105 105 $ hglog
106 106 1 0 B
107 107 0 0 A
108 108
109 109 $ mkcommit C
110 110 test-debug-phase: new rev 2: x -> 1
111 111 test-hook-close-phase: f838bfaca5c7226600ebcfd84f3c3c13a28d3757: -> draft
112 112 $ mkcommit D
113 113 test-debug-phase: new rev 3: x -> 1
114 114 test-hook-close-phase: b3325c91a4d916bcc4cdc83ea3fe4ece46a42f6e: -> draft
115 115
116 116 $ hglog
117 117 3 1 D
118 118 2 1 C
119 119 1 0 B
120 120 0 0 A
121 121
122 122 Test creating changeset as secret
123 123
124 124 $ mkcommit E --config phases.new-commit='secret'
125 125 test-debug-phase: new rev 4: x -> 2
126 126 test-hook-close-phase: a603bfb5a83e312131cebcd05353c217d4d21dde: -> secret
127 127 $ hglog
128 128 4 2 E
129 129 3 1 D
130 130 2 1 C
131 131 1 0 B
132 132 0 0 A
133 133
134 134 Test the secret property is inherited
135 135
136 136 $ mkcommit H
137 137 test-debug-phase: new rev 5: x -> 2
138 138 test-hook-close-phase: a030c6be5127abc010fcbff1851536552e6951a8: -> secret
139 139 $ hglog
140 140 5 2 H
141 141 4 2 E
142 142 3 1 D
143 143 2 1 C
144 144 1 0 B
145 145 0 0 A
146 146
147 147 Even on merge
148 148
149 149 $ hg up -q 1
150 150 $ mkcommit "B'"
151 151 test-debug-phase: new rev 6: x -> 1
152 152 created new head
153 153 test-hook-close-phase: cf9fe039dfd67e829edf6522a45de057b5c86519: -> draft
154 154 $ hglog
155 155 6 1 B'
156 156 5 2 H
157 157 4 2 E
158 158 3 1 D
159 159 2 1 C
160 160 1 0 B
161 161 0 0 A
162 162 $ hg merge 4 # E
163 163 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
164 164 (branch merge, don't forget to commit)
165 165 $ hg phase
166 166 6: draft
167 167 4: secret
168 168 $ hg ci -m "merge B' and E"
169 169 test-debug-phase: new rev 7: x -> 2
170 170 test-hook-close-phase: 17a481b3bccb796c0521ae97903d81c52bfee4af: -> secret
171 171
172 172 $ hglog
173 173 7 2 merge B' and E
174 174 6 1 B'
175 175 5 2 H
176 176 4 2 E
177 177 3 1 D
178 178 2 1 C
179 179 1 0 B
180 180 0 0 A
181 181
182 182 Test secret changeset are not pushed
183 183
184 184 $ hg init ../push-dest
185 185 $ cat > ../push-dest/.hg/hgrc << EOF
186 186 > [phases]
187 187 > publish=False
188 188 > EOF
189 189 $ hg outgoing ../push-dest --template='{rev} {phase} {desc|firstline}\n'
190 190 comparing with ../push-dest
191 191 searching for changes
192 192 0 public A
193 193 1 public B
194 194 2 draft C
195 195 3 draft D
196 196 6 draft B'
197 197 $ hg outgoing -r 'branch(default)' ../push-dest --template='{rev} {phase} {desc|firstline}\n'
198 198 comparing with ../push-dest
199 199 searching for changes
200 200 0 public A
201 201 1 public B
202 202 2 draft C
203 203 3 draft D
204 204 6 draft B'
205 205
206 206 $ hg push ../push-dest -f # force because we push multiple heads
207 207 pushing to ../push-dest
208 208 searching for changes
209 209 adding changesets
210 210 adding manifests
211 211 adding file changes
212 212 added 5 changesets with 5 changes to 5 files (+1 heads)
213 213 test-debug-phase: new rev 0: x -> 0
214 214 test-debug-phase: new rev 1: x -> 0
215 215 test-debug-phase: new rev 2: x -> 1
216 216 test-debug-phase: new rev 3: x -> 1
217 217 test-debug-phase: new rev 4: x -> 1
218 218 test-hook-close-phase: 4a2df7238c3b48766b5e22fafbb8a2f506ec8256: -> public
219 219 test-hook-close-phase: 27547f69f25460a52fff66ad004e58da7ad3fb56: -> public
220 220 test-hook-close-phase: f838bfaca5c7226600ebcfd84f3c3c13a28d3757: -> draft
221 221 test-hook-close-phase: b3325c91a4d916bcc4cdc83ea3fe4ece46a42f6e: -> draft
222 222 test-hook-close-phase: cf9fe039dfd67e829edf6522a45de057b5c86519: -> draft
223 223 $ hglog
224 224 7 2 merge B' and E
225 225 6 1 B'
226 226 5 2 H
227 227 4 2 E
228 228 3 1 D
229 229 2 1 C
230 230 1 0 B
231 231 0 0 A
232 232 $ cd ../push-dest
233 233 $ hglog
234 234 4 1 B'
235 235 3 1 D
236 236 2 1 C
237 237 1 0 B
238 238 0 0 A
239 239
240 240 (Issue3303)
241 241 Check that remote secret changeset are ignore when checking creation of remote heads
242 242
243 243 We add a secret head into the push destination. This secret head shadows a
244 244 visible shared between the initial repo and the push destination.
245 245
246 246 $ hg up -q 4 # B'
247 247 $ mkcommit Z --config phases.new-commit=secret
248 248 test-debug-phase: new rev 5: x -> 2
249 249 test-hook-close-phase: 2713879da13d6eea1ff22b442a5a87cb31a7ce6a: -> secret
250 250 $ hg phase .
251 251 5: secret
252 252
253 253 We now try to push a new public changeset that descend from the common public
254 254 head shadowed by the remote secret head.
255 255
256 256 $ cd ../initialrepo
257 257 $ hg up -q 6 #B'
258 258 $ mkcommit I
259 259 test-debug-phase: new rev 8: x -> 1
260 260 created new head
261 261 test-hook-close-phase: 6d6770faffce199f1fddd1cf87f6f026138cf061: -> draft
262 262 $ hg push ../push-dest
263 263 pushing to ../push-dest
264 264 searching for changes
265 265 adding changesets
266 266 adding manifests
267 267 adding file changes
268 268 added 1 changesets with 1 changes to 1 files (+1 heads)
269 269 test-debug-phase: new rev 6: x -> 1
270 270 test-hook-close-phase: 6d6770faffce199f1fddd1cf87f6f026138cf061: -> draft
271 271
272 272 :note: The "(+1 heads)" is wrong as we do not had any visible head
273 273
274 274 check that branch cache with "served" filter are properly computed and stored
275 275
276 276 $ ls ../push-dest/.hg/cache/branch2*
277 277 ../push-dest/.hg/cache/branch2-base
278 278 ../push-dest/.hg/cache/branch2-served
279 279 $ cat ../push-dest/.hg/cache/branch2-served
280 280 6d6770faffce199f1fddd1cf87f6f026138cf061 6 465891ffab3c47a3c23792f7dc84156e19a90722
281 281 b3325c91a4d916bcc4cdc83ea3fe4ece46a42f6e o default
282 282 6d6770faffce199f1fddd1cf87f6f026138cf061 o default
283 283 $ hg heads -R ../push-dest --template '{rev}:{node} {phase}\n' #update visible cache too
284 284 6:6d6770faffce199f1fddd1cf87f6f026138cf061 draft
285 285 5:2713879da13d6eea1ff22b442a5a87cb31a7ce6a secret
286 286 3:b3325c91a4d916bcc4cdc83ea3fe4ece46a42f6e draft
287 287 $ ls ../push-dest/.hg/cache/branch2*
288 288 ../push-dest/.hg/cache/branch2-base
289 289 ../push-dest/.hg/cache/branch2-served
290 290 ../push-dest/.hg/cache/branch2-visible
291 291 $ cat ../push-dest/.hg/cache/branch2-served
292 292 6d6770faffce199f1fddd1cf87f6f026138cf061 6 465891ffab3c47a3c23792f7dc84156e19a90722
293 293 b3325c91a4d916bcc4cdc83ea3fe4ece46a42f6e o default
294 294 6d6770faffce199f1fddd1cf87f6f026138cf061 o default
295 295 $ cat ../push-dest/.hg/cache/branch2-visible
296 296 6d6770faffce199f1fddd1cf87f6f026138cf061 6
297 297 b3325c91a4d916bcc4cdc83ea3fe4ece46a42f6e o default
298 298 2713879da13d6eea1ff22b442a5a87cb31a7ce6a o default
299 299 6d6770faffce199f1fddd1cf87f6f026138cf061 o default
300 300
301 301
302 302 Restore condition prior extra insertion.
303 303 $ hg -q --config extensions.mq= strip .
304 304 $ hg up -q 7
305 305 $ cd ..
306 306
307 307 Test secret changeset are not pull
308 308
309 309 $ hg init pull-dest
310 310 $ cd pull-dest
311 311 $ hg pull ../initialrepo
312 312 pulling from ../initialrepo
313 313 requesting all changes
314 314 adding changesets
315 315 adding manifests
316 316 adding file changes
317 317 added 5 changesets with 5 changes to 5 files (+1 heads)
318 318 new changesets 4a2df7238c3b:cf9fe039dfd6
319 319 test-debug-phase: new rev 0: x -> 0
320 320 test-debug-phase: new rev 1: x -> 0
321 321 test-debug-phase: new rev 2: x -> 0
322 322 test-debug-phase: new rev 3: x -> 0
323 323 test-debug-phase: new rev 4: x -> 0
324 324 test-hook-close-phase: 4a2df7238c3b48766b5e22fafbb8a2f506ec8256: -> public
325 325 test-hook-close-phase: 27547f69f25460a52fff66ad004e58da7ad3fb56: -> public
326 326 test-hook-close-phase: f838bfaca5c7226600ebcfd84f3c3c13a28d3757: -> public
327 327 test-hook-close-phase: b3325c91a4d916bcc4cdc83ea3fe4ece46a42f6e: -> public
328 328 test-hook-close-phase: cf9fe039dfd67e829edf6522a45de057b5c86519: -> public
329 329 (run 'hg heads' to see heads, 'hg merge' to merge)
330 330 $ hglog
331 331 4 0 B'
332 332 3 0 D
333 333 2 0 C
334 334 1 0 B
335 335 0 0 A
336 336 $ cd ..
337 337
338 338 But secret can still be bundled explicitly
339 339
340 340 $ cd initialrepo
341 341 $ hg bundle --base '4^' -r 'children(4)' ../secret-bundle.hg
342 342 4 changesets found
343 343 $ cd ..
344 344
345 345 Test secret changeset are not cloned
346 346 (during local clone)
347 347
348 348 $ hg clone -qU initialrepo clone-dest
349 349 test-debug-phase: new rev 0: x -> 0
350 350 test-debug-phase: new rev 1: x -> 0
351 351 test-debug-phase: new rev 2: x -> 0
352 352 test-debug-phase: new rev 3: x -> 0
353 353 test-debug-phase: new rev 4: x -> 0
354 354 test-hook-close-phase: 4a2df7238c3b48766b5e22fafbb8a2f506ec8256: -> public
355 355 test-hook-close-phase: 27547f69f25460a52fff66ad004e58da7ad3fb56: -> public
356 356 test-hook-close-phase: f838bfaca5c7226600ebcfd84f3c3c13a28d3757: -> public
357 357 test-hook-close-phase: b3325c91a4d916bcc4cdc83ea3fe4ece46a42f6e: -> public
358 358 test-hook-close-phase: cf9fe039dfd67e829edf6522a45de057b5c86519: -> public
359 359 $ hglog -R clone-dest
360 360 4 0 B'
361 361 3 0 D
362 362 2 0 C
363 363 1 0 B
364 364 0 0 A
365 365
366 366 Test summary
367 367
368 368 $ hg summary -R clone-dest --verbose
369 369 parent: -1:000000000000 (no revision checked out)
370 370 branch: default
371 371 commit: (clean)
372 372 update: 5 new changesets (update)
373 373 $ hg summary -R initialrepo
374 374 parent: 7:17a481b3bccb tip
375 375 merge B' and E
376 376 branch: default
377 377 commit: (clean) (secret)
378 378 update: 1 new changesets, 2 branch heads (merge)
379 379 phases: 3 draft, 3 secret
380 380 $ hg summary -R initialrepo --quiet
381 381 parent: 7:17a481b3bccb tip
382 382 update: 1 new changesets, 2 branch heads (merge)
383 383
384 384 Test revset
385 385
386 386 $ cd initialrepo
387 387 $ hglog -r 'public()'
388 388 0 0 A
389 389 1 0 B
390 390 $ hglog -r 'draft()'
391 391 2 1 C
392 392 3 1 D
393 393 6 1 B'
394 394 $ hglog -r 'secret()'
395 395 4 2 E
396 396 5 2 H
397 397 7 2 merge B' and E
398 398
399 399 test that phase are displayed in log at debug level
400 400
401 401 $ hg log --debug
402 402 changeset: 7:17a481b3bccb796c0521ae97903d81c52bfee4af
403 403 tag: tip
404 404 phase: secret
405 405 parent: 6:cf9fe039dfd67e829edf6522a45de057b5c86519
406 406 parent: 4:a603bfb5a83e312131cebcd05353c217d4d21dde
407 407 manifest: 7:5e724ffacba267b2ab726c91fc8b650710deaaa8
408 408 user: test
409 409 date: Thu Jan 01 00:00:00 1970 +0000
410 410 files+: C D E
411 411 extra: branch=default
412 412 description:
413 413 merge B' and E
414 414
415 415
416 416 changeset: 6:cf9fe039dfd67e829edf6522a45de057b5c86519
417 417 phase: draft
418 418 parent: 1:27547f69f25460a52fff66ad004e58da7ad3fb56
419 419 parent: -1:0000000000000000000000000000000000000000
420 420 manifest: 6:ab8bfef2392903058bf4ebb9e7746e8d7026b27a
421 421 user: test
422 422 date: Thu Jan 01 00:00:00 1970 +0000
423 423 files+: B'
424 424 extra: branch=default
425 425 description:
426 426 B'
427 427
428 428
429 429 changeset: 5:a030c6be5127abc010fcbff1851536552e6951a8
430 430 phase: secret
431 431 parent: 4:a603bfb5a83e312131cebcd05353c217d4d21dde
432 432 parent: -1:0000000000000000000000000000000000000000
433 433 manifest: 5:5c710aa854874fe3d5fa7192e77bdb314cc08b5a
434 434 user: test
435 435 date: Thu Jan 01 00:00:00 1970 +0000
436 436 files+: H
437 437 extra: branch=default
438 438 description:
439 439 H
440 440
441 441
442 442 changeset: 4:a603bfb5a83e312131cebcd05353c217d4d21dde
443 443 phase: secret
444 444 parent: 3:b3325c91a4d916bcc4cdc83ea3fe4ece46a42f6e
445 445 parent: -1:0000000000000000000000000000000000000000
446 446 manifest: 4:7173fd1c27119750b959e3a0f47ed78abe75d6dc
447 447 user: test
448 448 date: Thu Jan 01 00:00:00 1970 +0000
449 449 files+: E
450 450 extra: branch=default
451 451 description:
452 452 E
453 453
454 454
455 455 changeset: 3:b3325c91a4d916bcc4cdc83ea3fe4ece46a42f6e
456 456 phase: draft
457 457 parent: 2:f838bfaca5c7226600ebcfd84f3c3c13a28d3757
458 458 parent: -1:0000000000000000000000000000000000000000
459 459 manifest: 3:6e1f4c47ecb533ffd0c8e52cdc88afb6cd39e20c
460 460 user: test
461 461 date: Thu Jan 01 00:00:00 1970 +0000
462 462 files+: D
463 463 extra: branch=default
464 464 description:
465 465 D
466 466
467 467
468 468 changeset: 2:f838bfaca5c7226600ebcfd84f3c3c13a28d3757
469 469 phase: draft
470 470 parent: 1:27547f69f25460a52fff66ad004e58da7ad3fb56
471 471 parent: -1:0000000000000000000000000000000000000000
472 472 manifest: 2:66a5a01817fdf5239c273802b5b7618d051c89e4
473 473 user: test
474 474 date: Thu Jan 01 00:00:00 1970 +0000
475 475 files+: C
476 476 extra: branch=default
477 477 description:
478 478 C
479 479
480 480
481 481 changeset: 1:27547f69f25460a52fff66ad004e58da7ad3fb56
482 482 phase: public
483 483 parent: 0:4a2df7238c3b48766b5e22fafbb8a2f506ec8256
484 484 parent: -1:0000000000000000000000000000000000000000
485 485 manifest: 1:cb5cbbc1bfbf24cc34b9e8c16914e9caa2d2a7fd
486 486 user: test
487 487 date: Thu Jan 01 00:00:00 1970 +0000
488 488 files+: B
489 489 extra: branch=default
490 490 description:
491 491 B
492 492
493 493
494 494 changeset: 0:4a2df7238c3b48766b5e22fafbb8a2f506ec8256
495 495 phase: public
496 496 parent: -1:0000000000000000000000000000000000000000
497 497 parent: -1:0000000000000000000000000000000000000000
498 498 manifest: 0:007d8c9d88841325f5c6b06371b35b4e8a2b1a83
499 499 user: test
500 500 date: Thu Jan 01 00:00:00 1970 +0000
501 501 files+: A
502 502 extra: branch=default
503 503 description:
504 504 A
505 505
506 506
507 507
508 508
509 509 (Issue3707)
510 510 test invalid phase name
511 511
512 512 $ mkcommit I --config phases.new-commit='babar'
513 513 transaction abort!
514 514 rollback completed
515 515 abort: phases.new-commit: not a valid phase name ('babar')
516 516 [255]
517 517 Test phase command
518 518 ===================
519 519
520 520 initial picture
521 521
522 522 $ hg log -G --template "{rev} {phase} {desc}\n"
523 523 @ 7 secret merge B' and E
524 524 |\
525 525 | o 6 draft B'
526 526 | |
527 527 +---o 5 secret H
528 528 | |
529 529 o | 4 secret E
530 530 | |
531 531 o | 3 draft D
532 532 | |
533 533 o | 2 draft C
534 534 |/
535 535 o 1 public B
536 536 |
537 537 o 0 public A
538 538
539 539
540 540 display changesets phase
541 541
542 542 (mixing -r and plain rev specification)
543 543
544 544 $ hg phase 1::4 -r 7
545 545 1: public
546 546 2: draft
547 547 3: draft
548 548 4: secret
549 549 7: secret
550 550
551 551
552 552 move changeset forward
553 553
554 554 (with -r option)
555 555
556 556 $ hg phase --public -r 2
557 557 test-debug-phase: move rev 2: 1 -> 0
558 558 test-hook-close-phase: f838bfaca5c7226600ebcfd84f3c3c13a28d3757: draft -> public
559 559 $ hg log -G --template "{rev} {phase} {desc}\n"
560 560 @ 7 secret merge B' and E
561 561 |\
562 562 | o 6 draft B'
563 563 | |
564 564 +---o 5 secret H
565 565 | |
566 566 o | 4 secret E
567 567 | |
568 568 o | 3 draft D
569 569 | |
570 570 o | 2 public C
571 571 |/
572 572 o 1 public B
573 573 |
574 574 o 0 public A
575 575
576 576
577 577 move changeset backward
578 578
579 579 (without -r option)
580 580
581 581 $ hg phase --draft --force 2
582 582 test-debug-phase: move rev 2: 0 -> 1
583 583 test-hook-close-phase: f838bfaca5c7226600ebcfd84f3c3c13a28d3757: public -> draft
584 584 $ hg log -G --template "{rev} {phase} {desc}\n"
585 585 @ 7 secret merge B' and E
586 586 |\
587 587 | o 6 draft B'
588 588 | |
589 589 +---o 5 secret H
590 590 | |
591 591 o | 4 secret E
592 592 | |
593 593 o | 3 draft D
594 594 | |
595 595 o | 2 draft C
596 596 |/
597 597 o 1 public B
598 598 |
599 599 o 0 public A
600 600
601 601
602 602 move changeset forward and backward
603 603
604 604 $ hg phase --draft --force 1::4
605 605 test-debug-phase: move rev 1: 0 -> 1
606 606 test-debug-phase: move rev 4: 2 -> 1
607 607 test-hook-close-phase: 27547f69f25460a52fff66ad004e58da7ad3fb56: public -> draft
608 608 test-hook-close-phase: a603bfb5a83e312131cebcd05353c217d4d21dde: secret -> draft
609 609 $ hg log -G --template "{rev} {phase} {desc}\n"
610 610 @ 7 secret merge B' and E
611 611 |\
612 612 | o 6 draft B'
613 613 | |
614 614 +---o 5 secret H
615 615 | |
616 616 o | 4 draft E
617 617 | |
618 618 o | 3 draft D
619 619 | |
620 620 o | 2 draft C
621 621 |/
622 622 o 1 draft B
623 623 |
624 624 o 0 public A
625 625
626 626 test partial failure
627 627
628 628 $ hg phase --public 7
629 629 test-debug-phase: move rev 1: 1 -> 0
630 630 test-debug-phase: move rev 2: 1 -> 0
631 631 test-debug-phase: move rev 3: 1 -> 0
632 632 test-debug-phase: move rev 4: 1 -> 0
633 633 test-debug-phase: move rev 6: 1 -> 0
634 634 test-debug-phase: move rev 7: 2 -> 0
635 635 test-hook-close-phase: 27547f69f25460a52fff66ad004e58da7ad3fb56: draft -> public
636 636 test-hook-close-phase: f838bfaca5c7226600ebcfd84f3c3c13a28d3757: draft -> public
637 637 test-hook-close-phase: b3325c91a4d916bcc4cdc83ea3fe4ece46a42f6e: draft -> public
638 638 test-hook-close-phase: a603bfb5a83e312131cebcd05353c217d4d21dde: draft -> public
639 639 test-hook-close-phase: cf9fe039dfd67e829edf6522a45de057b5c86519: draft -> public
640 640 test-hook-close-phase: 17a481b3bccb796c0521ae97903d81c52bfee4af: secret -> public
641 641 $ hg phase --draft '5 or 7'
642 642 test-debug-phase: move rev 5: 2 -> 1
643 643 test-hook-close-phase: a030c6be5127abc010fcbff1851536552e6951a8: secret -> draft
644 644 cannot move 1 changesets to a higher phase, use --force
645 645 phase changed for 1 changesets
646 646 [1]
647 647 $ hg log -G --template "{rev} {phase} {desc}\n"
648 648 @ 7 public merge B' and E
649 649 |\
650 650 | o 6 public B'
651 651 | |
652 652 +---o 5 draft H
653 653 | |
654 654 o | 4 public E
655 655 | |
656 656 o | 3 public D
657 657 | |
658 658 o | 2 public C
659 659 |/
660 660 o 1 public B
661 661 |
662 662 o 0 public A
663 663
664 664
665 665 test complete failure
666 666
667 667 $ hg phase --draft 7
668 668 cannot move 1 changesets to a higher phase, use --force
669 669 no phases changed
670 670 [1]
671 671
672 672 $ cd ..
673 673
674 674 test hidden changeset are not cloned as public (issue3935)
675 675
676 676 $ cd initialrepo
677 677
678 678 (enabling evolution)
679 679 $ cat >> $HGRCPATH << EOF
680 680 > [experimental]
681 681 > evolution.createmarkers=True
682 682 > EOF
683 683
684 684 (making a changeset hidden; H in that case)
685 685 $ hg debugobsolete `hg id --debug -r 5`
686 686 1 new obsolescence markers
687 687 obsoleted 1 changesets
688 688
689 689 $ cd ..
690 690 $ hg clone initialrepo clonewithobs
691 691 requesting all changes
692 692 adding changesets
693 693 adding manifests
694 694 adding file changes
695 695 added 7 changesets with 6 changes to 6 files
696 696 new changesets 4a2df7238c3b:17a481b3bccb
697 697 test-debug-phase: new rev 0: x -> 0
698 698 test-debug-phase: new rev 1: x -> 0
699 699 test-debug-phase: new rev 2: x -> 0
700 700 test-debug-phase: new rev 3: x -> 0
701 701 test-debug-phase: new rev 4: x -> 0
702 702 test-debug-phase: new rev 5: x -> 0
703 703 test-debug-phase: new rev 6: x -> 0
704 704 test-hook-close-phase: 4a2df7238c3b48766b5e22fafbb8a2f506ec8256: -> public
705 705 test-hook-close-phase: 27547f69f25460a52fff66ad004e58da7ad3fb56: -> public
706 706 test-hook-close-phase: f838bfaca5c7226600ebcfd84f3c3c13a28d3757: -> public
707 707 test-hook-close-phase: b3325c91a4d916bcc4cdc83ea3fe4ece46a42f6e: -> public
708 708 test-hook-close-phase: a603bfb5a83e312131cebcd05353c217d4d21dde: -> public
709 709 test-hook-close-phase: cf9fe039dfd67e829edf6522a45de057b5c86519: -> public
710 710 test-hook-close-phase: 17a481b3bccb796c0521ae97903d81c52bfee4af: -> public
711 711 updating to branch default
712 712 6 files updated, 0 files merged, 0 files removed, 0 files unresolved
713 713 $ cd clonewithobs
714 714 $ hg log -G --template "{rev} {phase} {desc}\n"
715 715 @ 6 public merge B' and E
716 716 |\
717 717 | o 5 public B'
718 718 | |
719 719 o | 4 public E
720 720 | |
721 721 o | 3 public D
722 722 | |
723 723 o | 2 public C
724 724 |/
725 725 o 1 public B
726 726 |
727 727 o 0 public A
728 728
729 729
730 730 test verify repo containing hidden changesets, which should not abort just
731 731 because repo.cancopy() is False
732 732
733 733 $ cd ../initialrepo
734 734 $ hg verify
735 735 checking changesets
736 736 checking manifests
737 737 crosschecking files in changesets and manifests
738 738 checking files
739 739 checked 8 changesets with 7 changes to 7 files
740 740
741 741 $ cd ..
742 742
743 743 check whether HG_PENDING makes pending changes only in related
744 744 repositories visible to an external hook.
745 745
746 746 (emulate a transaction running concurrently by copied
747 747 .hg/phaseroots.pending in subsequent test)
748 748
749 749 $ cat > $TESTTMP/savepending.sh <<EOF
750 750 > cp .hg/store/phaseroots.pending .hg/store/phaseroots.pending.saved
751 751 > exit 1 # to avoid changing phase for subsequent tests
752 752 > EOF
753 753 $ cd push-dest
754 754 $ hg phase 6
755 755 6: draft
756 756 $ hg --config hooks.pretxnclose="sh $TESTTMP/savepending.sh" phase -f -s 6
757 757 transaction abort!
758 758 rollback completed
759 759 abort: pretxnclose hook exited with status 1
760 760 [255]
761 761 $ cp .hg/store/phaseroots.pending.saved .hg/store/phaseroots.pending
762 762
763 763 (check (in)visibility of phaseroot while transaction running in repo)
764 764
765 765 $ cat > $TESTTMP/checkpending.sh <<EOF
766 766 > echo '@initialrepo'
767 767 > hg -R "$TESTTMP/initialrepo" phase 7
768 768 > echo '@push-dest'
769 769 > hg -R "$TESTTMP/push-dest" phase 6
770 770 > exit 1 # to avoid changing phase for subsequent tests
771 771 > EOF
772 772 $ cd ../initialrepo
773 773 $ hg phase 7
774 774 7: public
775 775 $ hg --config hooks.pretxnclose="sh $TESTTMP/checkpending.sh" phase -f -s 7
776 776 @initialrepo
777 777 7: secret
778 778 @push-dest
779 779 6: draft
780 780 transaction abort!
781 781 rollback completed
782 782 abort: pretxnclose hook exited with status 1
783 783 [255]
784 784
785 785 Check that pretxnclose-phase hook can control phase movement
786 786
787 787 $ hg phase --force b3325c91a4d9 --secret
788 788 test-debug-phase: move rev 3: 0 -> 2
789 789 test-debug-phase: move rev 4: 0 -> 2
790 790 test-debug-phase: move rev 5: 1 -> 2
791 791 test-debug-phase: move rev 7: 0 -> 2
792 792 test-hook-close-phase: b3325c91a4d916bcc4cdc83ea3fe4ece46a42f6e: public -> secret
793 793 test-hook-close-phase: a603bfb5a83e312131cebcd05353c217d4d21dde: public -> secret
794 794 test-hook-close-phase: a030c6be5127abc010fcbff1851536552e6951a8: draft -> secret
795 795 test-hook-close-phase: 17a481b3bccb796c0521ae97903d81c52bfee4af: public -> secret
796 796 $ hg log -G -T phases
797 797 @ changeset: 7:17a481b3bccb
798 798 |\ tag: tip
799 799 | | phase: secret
800 800 | | parent: 6:cf9fe039dfd6
801 801 | | parent: 4:a603bfb5a83e
802 802 | | user: test
803 803 | | date: Thu Jan 01 00:00:00 1970 +0000
804 804 | | summary: merge B' and E
805 805 | |
806 806 | o changeset: 6:cf9fe039dfd6
807 807 | | phase: public
808 808 | | parent: 1:27547f69f254
809 809 | | user: test
810 810 | | date: Thu Jan 01 00:00:00 1970 +0000
811 811 | | summary: B'
812 812 | |
813 813 o | changeset: 4:a603bfb5a83e
814 814 | | phase: secret
815 815 | | user: test
816 816 | | date: Thu Jan 01 00:00:00 1970 +0000
817 817 | | summary: E
818 818 | |
819 819 o | changeset: 3:b3325c91a4d9
820 820 | | phase: secret
821 821 | | user: test
822 822 | | date: Thu Jan 01 00:00:00 1970 +0000
823 823 | | summary: D
824 824 | |
825 825 o | changeset: 2:f838bfaca5c7
826 826 |/ phase: public
827 827 | user: test
828 828 | date: Thu Jan 01 00:00:00 1970 +0000
829 829 | summary: C
830 830 |
831 831 o changeset: 1:27547f69f254
832 832 | phase: public
833 833 | user: test
834 834 | date: Thu Jan 01 00:00:00 1970 +0000
835 835 | summary: B
836 836 |
837 837 o changeset: 0:4a2df7238c3b
838 838 phase: public
839 839 user: test
840 840 date: Thu Jan 01 00:00:00 1970 +0000
841 841 summary: A
842 842
843 843
844 844 Install a hook that prevent b3325c91a4d9 to become public
845 845
846 846 $ cat >> .hg/hgrc << EOF
847 847 > [hooks]
848 848 > pretxnclose-phase.nopublish_D = sh -c "(echo \$HG_NODE| grep -v b3325c91a4d9>/dev/null) || [ 'public' != \$HG_PHASE ]"
849 849 > EOF
850 850
851 851 Try various actions. only the draft move should succeed
852 852
853 853 $ hg phase --public b3325c91a4d9
854 854 transaction abort!
855 855 rollback completed
856 856 abort: pretxnclose-phase.nopublish_D hook exited with status 1
857 857 [255]
858 858 $ hg phase --public a603bfb5a83e
859 859 transaction abort!
860 860 rollback completed
861 861 abort: pretxnclose-phase.nopublish_D hook exited with status 1
862 862 [255]
863 863 $ hg phase --draft 17a481b3bccb
864 864 test-debug-phase: move rev 3: 2 -> 1
865 865 test-debug-phase: move rev 4: 2 -> 1
866 866 test-debug-phase: move rev 7: 2 -> 1
867 867 test-hook-close-phase: b3325c91a4d916bcc4cdc83ea3fe4ece46a42f6e: secret -> draft
868 868 test-hook-close-phase: a603bfb5a83e312131cebcd05353c217d4d21dde: secret -> draft
869 869 test-hook-close-phase: 17a481b3bccb796c0521ae97903d81c52bfee4af: secret -> draft
870 870 $ hg phase --public 17a481b3bccb
871 871 transaction abort!
872 872 rollback completed
873 873 abort: pretxnclose-phase.nopublish_D hook exited with status 1
874 874 [255]
875 875
876 876 $ cd ..
877 877
878 878 Test for the "internal" phase
879 879 =============================
880 880
881 881 Check we deny its usage on older repository
882 882
883 883 $ hg init no-internal-phase --config format.internal-phase=no
884 884 $ cd no-internal-phase
885 885 $ cat .hg/requires
886 886 dotencode
887 887 fncache
888 888 generaldelta
889 889 revlogv1
890 890 sparserevlog
891 891 store
892 892 $ echo X > X
893 893 $ hg add X
894 894 $ hg status
895 895 A X
896 896 $ hg --config "phases.new-commit=internal" commit -m "my test internal commit" 2>&1 | grep ProgrammingError
897 897 ** ProgrammingError: this repository does not support the internal phase
898 898 raise error.ProgrammingError(msg)
899 899 *ProgrammingError: this repository does not support the internal phase (glob)
900 900 $ hg --config "phases.new-commit=archived" commit -m "my test archived commit" 2>&1 | grep ProgrammingError
901 901 ** ProgrammingError: this repository does not support the archived phase
902 902 raise error.ProgrammingError(msg)
903 903 *ProgrammingError: this repository does not support the archived phase (glob)
904 904
905 905 $ cd ..
906 906
907 907 Check it works fine with repository that supports it.
908 908
909 909 $ hg init internal-phase --config format.internal-phase=yes
910 910 $ cd internal-phase
911 911 $ cat .hg/requires
912 912 dotencode
913 913 fncache
914 914 generaldelta
915 915 internal-phase
916 916 revlogv1
917 917 sparserevlog
918 918 store
919 919 $ mkcommit A
920 920 test-debug-phase: new rev 0: x -> 1
921 921 test-hook-close-phase: 4a2df7238c3b48766b5e22fafbb8a2f506ec8256: -> draft
922 922
923 923 Commit an internal changesets
924 924
925 925 $ echo B > B
926 926 $ hg add B
927 927 $ hg status
928 928 A B
929 929 $ hg --config "phases.new-commit=internal" commit -m "my test internal commit"
930 930 test-debug-phase: new rev 1: x -> 96
931 931 test-hook-close-phase: c01c42dffc7f81223397e99652a0703f83e1c5ea: -> internal
932 932
933 933 The changeset is a working parent descendant.
934 934 Per the usual visibility rules, it is made visible.
935 935
936 936 $ hg log -G -l 3
937 937 @ changeset: 1:c01c42dffc7f
938 938 | tag: tip
939 939 | user: test
940 940 | date: Thu Jan 01 00:00:00 1970 +0000
941 941 | summary: my test internal commit
942 942 |
943 943 o changeset: 0:4a2df7238c3b
944 944 user: test
945 945 date: Thu Jan 01 00:00:00 1970 +0000
946 946 summary: A
947 947
948 948
949 949 Commit is hidden as expected
950 950
951 951 $ hg up 0
952 952 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
953 953 $ hg log -G
954 954 @ changeset: 0:4a2df7238c3b
955 955 tag: tip
956 956 user: test
957 957 date: Thu Jan 01 00:00:00 1970 +0000
958 958 summary: A
959 959
960 960
961 961 Test for archived phase
962 962 -----------------------
963 963
964 964 Commit an archived changesets
965 965
966 966 $ echo B > B
967 967 $ hg add B
968 968 $ hg status
969 969 A B
970 970 $ hg --config "phases.new-commit=archived" commit -m "my test archived commit"
971 971 test-debug-phase: new rev 2: x -> 32
972 972 test-hook-close-phase: 8df5997c3361518f733d1ae67cd3adb9b0eaf125: -> archived
973 973
974 974 The changeset is a working parent descendant.
975 975 Per the usual visibility rules, it is made visible.
976 976
977 977 $ hg log -G -l 3
978 978 @ changeset: 2:8df5997c3361
979 979 | tag: tip
980 980 | parent: 0:4a2df7238c3b
981 981 | user: test
982 982 | date: Thu Jan 01 00:00:00 1970 +0000
983 983 | summary: my test archived commit
984 984 |
985 985 o changeset: 0:4a2df7238c3b
986 986 user: test
987 987 date: Thu Jan 01 00:00:00 1970 +0000
988 988 summary: A
989 989
990 990
991 991 Commit is hidden as expected
992 992
993 993 $ hg up 0
994 994 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
995 995 $ hg log -G
996 996 @ changeset: 0:4a2df7238c3b
997 997 tag: tip
998 998 user: test
999 999 date: Thu Jan 01 00:00:00 1970 +0000
1000 1000 summary: A
1001 1001
1002 1002 $ cd ..
1003 1003
1004 1004 Recommitting an exact match of a public commit shouldn't change it to
1005 1005 draft:
1006 1006
1007 1007 $ cd initialrepo
1008 1008 $ hg phase -r 2
1009 1009 2: public
1010 1010 $ hg up -C 1
1011 1011 0 files updated, 0 files merged, 4 files removed, 0 files unresolved
1012 1012 $ mkcommit C
1013 created new head
1013 warning: commit already existed in the repository!
1014 1014 $ hg phase -r 2
1015 1015 2: public
1016 1016
1017 1017 Same, but for secret:
1018 1018
1019 1019 $ hg up 7
1020 1020 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
1021 1021 $ mkcommit F -s
1022 1022 test-debug-phase: new rev 8: x -> 2
1023 1023 test-hook-close-phase: de414268ec5ce2330c590b942fbb5ff0b0ca1a0a: -> secret
1024 1024 $ hg up 7
1025 1025 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
1026 1026 $ hg phase
1027 1027 7: draft
1028 1028 $ mkcommit F
1029 1029 test-debug-phase: new rev 8: x -> 2
1030 warning: commit already existed in the repository!
1030 1031 test-hook-close-phase: de414268ec5ce2330c590b942fbb5ff0b0ca1a0a: -> secret
1031 1032 $ hg phase -r tip
1032 1033 8: secret
1033 1034
1034 1035 But what about obsoleted changesets?
1035 1036
1036 1037 $ hg up 4
1037 1038 0 files updated, 0 files merged, 2 files removed, 0 files unresolved
1038 1039 $ mkcommit H
1039 1040 test-debug-phase: new rev 5: x -> 2
1040 created new head
1041 warning: commit already existed in the repository!
1041 1042 test-hook-close-phase: a030c6be5127abc010fcbff1851536552e6951a8: -> secret
1042 1043 $ hg phase -r 5
1043 1044 5: secret
1044 1045 $ hg par
1045 1046 changeset: 5:a030c6be5127
1046 1047 user: test
1047 1048 date: Thu Jan 01 00:00:00 1970 +0000
1048 1049 obsolete: pruned
1049 1050 summary: H
1050 1051
1051 1052 $ hg up tip
1052 1053 2 files updated, 0 files merged, 1 files removed, 0 files unresolved
1053 1054 $ cd ..
@@ -1,208 +1,209 b''
1 1 #require no-windows
2 2
3 3 $ . "$TESTDIR/remotefilelog-library.sh"
4 4
5 5 $ hg init master
6 6 $ cd master
7 7 $ cat >> .hg/hgrc <<EOF
8 8 > [remotefilelog]
9 9 > server=True
10 10 > EOF
11 11 $ echo x > x
12 12 $ echo y > y
13 13 $ echo z > z
14 14 $ hg commit -qAm xy
15 15
16 16 $ cd ..
17 17
18 18 $ hgcloneshallow ssh://user@dummy/master shallow -q
19 19 3 files fetched over 1 fetches - (3 misses, 0.00% hit ratio) over *s (glob)
20 20 $ cd shallow
21 21
22 22 # status
23 23
24 24 $ clearcache
25 25 $ echo xx > x
26 26 $ echo yy > y
27 27 $ touch a
28 28 $ hg status
29 29 M x
30 30 M y
31 31 ? a
32 32 1 files fetched over 1 fetches - (1 misses, 0.00% hit ratio) over *s (glob)
33 33 $ hg add a
34 34 $ hg status
35 35 M x
36 36 M y
37 37 A a
38 38
39 39 # diff
40 40
41 41 $ hg debugrebuilddirstate # fixes dirstate non-determinism
42 42 $ hg add a
43 43 $ clearcache
44 44 $ hg diff
45 45 diff -r f3d0bb0d1e48 x
46 46 --- a/x* (glob)
47 47 +++ b/x* (glob)
48 48 @@ -1,1 +1,1 @@
49 49 -x
50 50 +xx
51 51 diff -r f3d0bb0d1e48 y
52 52 --- a/y* (glob)
53 53 +++ b/y* (glob)
54 54 @@ -1,1 +1,1 @@
55 55 -y
56 56 +yy
57 57 3 files fetched over 1 fetches - (3 misses, 0.00% hit ratio) over *s (glob)
58 58
59 59 # local commit
60 60
61 61 $ clearcache
62 62 $ echo a > a
63 63 $ echo xxx > x
64 64 $ echo yyy > y
65 65 $ hg commit -m a
66 66 ? files fetched over 1 fetches - (? misses, 0.00% hit ratio) over *s (glob)
67 67
68 68 # local commit where the dirstate is clean -- ensure that we do just one fetch
69 69 # (update to a commit on the server first)
70 70
71 71 $ hg --config debug.dirstate.delaywrite=1 up 0
72 72 2 files updated, 0 files merged, 1 files removed, 0 files unresolved
73 73 $ clearcache
74 74 $ hg debugdirstate
75 75 n 644 2 * x (glob)
76 76 n 644 2 * y (glob)
77 77 n 644 2 * z (glob)
78 78 $ echo xxxx > x
79 79 $ echo yyyy > y
80 80 $ hg commit -m x
81 81 created new head
82 82 2 files fetched over 1 fetches - (2 misses, 0.00% hit ratio) over *s (glob)
83 83
84 84 # restore state for future tests
85 85
86 86 $ hg -q strip .
87 87 $ hg -q up tip
88 88
89 89 # rebase
90 90
91 91 $ clearcache
92 92 $ cd ../master
93 93 $ echo w > w
94 94 $ hg commit -qAm w
95 95
96 96 $ cd ../shallow
97 97 $ hg pull
98 98 pulling from ssh://user@dummy/master
99 99 searching for changes
100 100 adding changesets
101 101 adding manifests
102 102 adding file changes
103 103 added 1 changesets with 0 changes to 0 files (+1 heads)
104 104 new changesets fed61014d323
105 105 (run 'hg heads' to see heads, 'hg merge' to merge)
106 106
107 107 $ hg rebase -d tip
108 108 rebasing 1:9abfe7bca547 "a"
109 109 saved backup bundle to $TESTTMP/shallow/.hg/strip-backup/9abfe7bca547-8b11e5ff-rebase.hg (glob)
110 110 3 files fetched over 2 fetches - (3 misses, 0.00% hit ratio) over *s (glob)
111 111
112 112 # strip
113 113
114 114 $ clearcache
115 115 $ hg debugrebuilddirstate # fixes dirstate non-determinism
116 116 $ hg strip -r .
117 117 2 files updated, 0 files merged, 1 files removed, 0 files unresolved
118 118 saved backup bundle to $TESTTMP/shallow/.hg/strip-backup/19edf50f4de7-df3d0f74-backup.hg (glob)
119 119 4 files fetched over 2 fetches - (4 misses, 0.00% hit ratio) over *s (glob)
120 120
121 121 # unbundle
122 122
123 123 $ clearcache
124 124 $ ls -A
125 125 .hg
126 126 w
127 127 x
128 128 y
129 129 z
130 130
131 131 $ hg debugrebuilddirstate # fixes dirstate non-determinism
132 132 $ hg unbundle .hg/strip-backup/19edf50f4de7-df3d0f74-backup.hg
133 133 adding changesets
134 134 adding manifests
135 135 adding file changes
136 136 added 1 changesets with 0 changes to 0 files
137 137 new changesets 19edf50f4de7 (1 drafts)
138 138 (run 'hg update' to get a working copy)
139 139
140 140 $ hg up
141 141 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
142 142 4 files fetched over 1 fetches - (4 misses, 0.00% hit ratio) over *s (glob)
143 143 $ cat a
144 144 a
145 145
146 146 # revert
147 147
148 148 $ clearcache
149 149 $ hg revert -r .~2 y z
150 150 no changes needed to z
151 151 2 files fetched over 2 fetches - (2 misses, 0.00% hit ratio) over *s (glob)
152 152 $ hg checkout -C -r . -q
153 153
154 154 # explicit bundle should produce full bundle file
155 155
156 156 $ hg bundle -r 2 --base 1 ../local.bundle
157 157 1 changesets found
158 158 1 files fetched over 1 fetches - (1 misses, 0.00% hit ratio) over *s (glob)
159 159 $ cd ..
160 160
161 161 $ hgcloneshallow ssh://user@dummy/master shallow2 -q
162 162 1 files fetched over 1 fetches - (1 misses, 0.00% hit ratio) over *s (glob)
163 163 $ cd shallow2
164 164 $ hg unbundle ../local.bundle
165 165 adding changesets
166 166 adding manifests
167 167 adding file changes
168 168 added 1 changesets with 3 changes to 3 files
169 169 new changesets 19edf50f4de7 (1 drafts)
170 170 (run 'hg update' to get a working copy)
171 171
172 172 $ hg log -r 2 --stat
173 173 changeset: 2:19edf50f4de7
174 174 tag: tip
175 175 user: test
176 176 date: Thu Jan 01 00:00:00 1970 +0000
177 177 summary: a
178 178
179 179 a | 1 +
180 180 x | 2 +-
181 181 y | 2 +-
182 182 3 files changed, 3 insertions(+), 2 deletions(-)
183 183
184 184 # Merge
185 185
186 186 $ echo merge >> w
187 187 $ hg commit -m w
188 188 created new head
189 189 $ hg merge 2
190 190 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
191 191 (branch merge, don't forget to commit)
192 192 $ hg commit -m merge
193 193 $ hg strip -q -r ".^"
194 194
195 195 # commit without producing new node
196 196
197 197 $ cd $TESTTMP
198 198 $ hgcloneshallow ssh://user@dummy/master shallow3 -q
199 199 $ cd shallow3
200 200 $ echo 1 > A
201 201 $ hg commit -m foo -A A
202 202 $ hg log -r . -T '{node}\n'
203 203 383ce605500277f879b7460a16ba620eb6930b7f
204 204 $ hg update -r '.^' -q
205 205 $ echo 1 > A
206 206 $ hg commit -m foo -A A
207 warning: commit already existed in the repository!
207 208 $ hg log -r . -T '{node}\n'
208 209 383ce605500277f879b7460a16ba620eb6930b7f
@@ -1,419 +1,421 b''
1 1 Test for command `hg unamend` which lives in uncommit extension
2 2 ===============================================================
3 3
4 4 $ cat >> $HGRCPATH << EOF
5 5 > [alias]
6 6 > glog = log -G -T '{rev}:{node|short} {desc}'
7 7 > [experimental]
8 8 > evolution = createmarkers, allowunstable
9 9 > [extensions]
10 10 > rebase =
11 11 > amend =
12 12 > uncommit =
13 13 > EOF
14 14
15 15 Repo Setup
16 16
17 17 $ hg init repo
18 18 $ cd repo
19 19 $ for ch in a b c d e f g h; do touch $ch; echo "foo" >> $ch; hg ci -Aqm "Added "$ch; done
20 20
21 21 $ hg glog
22 22 @ 7:ec2426147f0e Added h
23 23 |
24 24 o 6:87d6d6676308 Added g
25 25 |
26 26 o 5:825660c69f0c Added f
27 27 |
28 28 o 4:aa98ab95a928 Added e
29 29 |
30 30 o 3:62615734edd5 Added d
31 31 |
32 32 o 2:28ad74487de9 Added c
33 33 |
34 34 o 1:29becc82797a Added b
35 35 |
36 36 o 0:18d04c59bb5d Added a
37 37
38 38 Trying to unamend when there was no amend done
39 39
40 40 $ hg unamend
41 41 abort: changeset must have one predecessor, found 0 predecessors
42 42 [255]
43 43
44 44 Unamend on clean wdir and tip
45 45
46 46 $ echo "bar" >> h
47 47 $ hg amend
48 48
49 49 $ hg exp
50 50 # HG changeset patch
51 51 # User test
52 52 # Date 0 0
53 53 # Thu Jan 01 00:00:00 1970 +0000
54 54 # Node ID c9fa1a715c1b7661c0fafb362a9f30bd75878d7d
55 55 # Parent 87d6d66763085b629e6d7ed56778c79827273022
56 56 Added h
57 57
58 58 diff -r 87d6d6676308 -r c9fa1a715c1b h
59 59 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
60 60 +++ b/h Thu Jan 01 00:00:00 1970 +0000
61 61 @@ -0,0 +1,2 @@
62 62 +foo
63 63 +bar
64 64
65 65 $ hg glog --hidden
66 66 @ 8:c9fa1a715c1b Added h
67 67 |
68 68 | x 7:ec2426147f0e Added h
69 69 |/
70 70 o 6:87d6d6676308 Added g
71 71 |
72 72 o 5:825660c69f0c Added f
73 73 |
74 74 o 4:aa98ab95a928 Added e
75 75 |
76 76 o 3:62615734edd5 Added d
77 77 |
78 78 o 2:28ad74487de9 Added c
79 79 |
80 80 o 1:29becc82797a Added b
81 81 |
82 82 o 0:18d04c59bb5d Added a
83 83
84 84 $ hg unamend
85 85 $ hg glog --hidden
86 86 @ 9:46d02d47eec6 Added h
87 87 |
88 88 | x 8:c9fa1a715c1b Added h
89 89 |/
90 90 | x 7:ec2426147f0e Added h
91 91 |/
92 92 o 6:87d6d6676308 Added g
93 93 |
94 94 o 5:825660c69f0c Added f
95 95 |
96 96 o 4:aa98ab95a928 Added e
97 97 |
98 98 o 3:62615734edd5 Added d
99 99 |
100 100 o 2:28ad74487de9 Added c
101 101 |
102 102 o 1:29becc82797a Added b
103 103 |
104 104 o 0:18d04c59bb5d Added a
105 105
106 106 $ hg diff
107 107 diff -r 46d02d47eec6 h
108 108 --- a/h Thu Jan 01 00:00:00 1970 +0000
109 109 +++ b/h Thu Jan 01 00:00:00 1970 +0000
110 110 @@ -1,1 +1,2 @@
111 111 foo
112 112 +bar
113 113
114 114 $ hg exp
115 115 # HG changeset patch
116 116 # User test
117 117 # Date 0 0
118 118 # Thu Jan 01 00:00:00 1970 +0000
119 119 # Node ID 46d02d47eec6ca096b8dcab3f8f5579c40c3dd9a
120 120 # Parent 87d6d66763085b629e6d7ed56778c79827273022
121 121 Added h
122 122
123 123 diff -r 87d6d6676308 -r 46d02d47eec6 h
124 124 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
125 125 +++ b/h Thu Jan 01 00:00:00 1970 +0000
126 126 @@ -0,0 +1,1 @@
127 127 +foo
128 128
129 129 $ hg status
130 130 M h
131 131
132 132 $ hg log -r . -T '{extras % "{extra}\n"}' --config alias.log=log
133 133 branch=default
134 134 unamend_source=c9fa1a715c1b7661c0fafb362a9f30bd75878d7d
135 135
136 136 Using unamend to undo an unamed (intentional)
137 137
138 138 $ hg unamend
139 139 $ hg exp
140 140 # HG changeset patch
141 141 # User test
142 142 # Date 0 0
143 143 # Thu Jan 01 00:00:00 1970 +0000
144 144 # Node ID 850ddfc1bc662997ec6094ada958f01f0cc8070a
145 145 # Parent 87d6d66763085b629e6d7ed56778c79827273022
146 146 Added h
147 147
148 148 diff -r 87d6d6676308 -r 850ddfc1bc66 h
149 149 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
150 150 +++ b/h Thu Jan 01 00:00:00 1970 +0000
151 151 @@ -0,0 +1,2 @@
152 152 +foo
153 153 +bar
154 154 $ hg diff
155 155
156 156 Unamend on a dirty working directory
157 157
158 158 $ echo "bar" >> a
159 159 $ hg amend
160 160 $ echo "foobar" >> a
161 161 $ echo "bar" >> b
162 162 $ hg status
163 163 M a
164 164 M b
165 165
166 166 $ hg unamend
167 167
168 168 $ hg status
169 169 M a
170 170 M b
171 171
172 172 $ hg diff
173 173 diff -r ec338db45d51 a
174 174 --- a/a Thu Jan 01 00:00:00 1970 +0000
175 175 +++ b/a Thu Jan 01 00:00:00 1970 +0000
176 176 @@ -1,1 +1,3 @@
177 177 foo
178 178 +bar
179 179 +foobar
180 180 diff -r ec338db45d51 b
181 181 --- a/b Thu Jan 01 00:00:00 1970 +0000
182 182 +++ b/b Thu Jan 01 00:00:00 1970 +0000
183 183 @@ -1,1 +1,2 @@
184 184 foo
185 185 +bar
186 186
187 187 Unamending an added file
188 188
189 189 $ hg ci -m "Added things to a and b"
190 190 $ echo foo > bar
191 191 $ hg add bar
192 192 $ hg amend
193 193
194 194 $ hg unamend
195 195 $ hg status
196 196 A bar
197 197
198 198 $ hg revert --all
199 199 forgetting bar
200 200
201 201 Unamending a removed file
202 202
203 203 $ hg remove a
204 204 $ hg amend
205 205
206 206 $ hg unamend
207 207 $ hg status
208 208 R a
209 209 ? bar
210 210
211 211 $ hg revert --all
212 212 undeleting a
213 213
214 214 Unamending an added file with dirty wdir status
215 215
216 216 $ hg add bar
217 217 $ hg amend
218 218 $ echo bar >> bar
219 219 $ hg status
220 220 M bar
221 221
222 222 $ hg unamend
223 223 $ hg status
224 224 A bar
225 225 $ hg diff
226 226 diff -r 7f79409af972 bar
227 227 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
228 228 +++ b/bar Thu Jan 01 00:00:00 1970 +0000
229 229 @@ -0,0 +1,2 @@
230 230 +foo
231 231 +bar
232 232
233 233 $ hg revert --all
234 234 forgetting bar
235 235 $ rm bar
236 236
237 237 Unamending in middle of a stack
238 238
239 239 $ hg glog
240 240 @ 19:7f79409af972 Added things to a and b
241 241 |
242 242 o 12:ec338db45d51 Added h
243 243 |
244 244 o 6:87d6d6676308 Added g
245 245 |
246 246 o 5:825660c69f0c Added f
247 247 |
248 248 o 4:aa98ab95a928 Added e
249 249 |
250 250 o 3:62615734edd5 Added d
251 251 |
252 252 o 2:28ad74487de9 Added c
253 253 |
254 254 o 1:29becc82797a Added b
255 255 |
256 256 o 0:18d04c59bb5d Added a
257 257
258 258 $ hg up 5
259 259 2 files updated, 0 files merged, 2 files removed, 0 files unresolved
260 260 $ echo bar >> f
261 261 $ hg amend
262 262 3 new orphan changesets
263 263 $ hg rebase -s 6 -d . -q
264 264
265 265 $ hg glog
266 266 o 23:03ddd6fc5af1 Added things to a and b
267 267 |
268 268 o 22:3e7b64ee157b Added h
269 269 |
270 270 o 21:49635b68477e Added g
271 271 |
272 272 @ 20:93f0e8ffab32 Added f
273 273 |
274 274 o 4:aa98ab95a928 Added e
275 275 |
276 276 o 3:62615734edd5 Added d
277 277 |
278 278 o 2:28ad74487de9 Added c
279 279 |
280 280 o 1:29becc82797a Added b
281 281 |
282 282 o 0:18d04c59bb5d Added a
283 283
284 284
285 285 $ hg --config experimental.evolution=createmarkers unamend
286 286 abort: cannot unamend changeset with children
287 287 [255]
288 288
289 289 $ hg unamend
290 290 3 new orphan changesets
291 291
292 292 Trying to unamend a public changeset
293 293
294 294 $ hg up -C 23
295 295 5 files updated, 0 files merged, 0 files removed, 0 files unresolved
296 296 $ hg phase -r . -p
297 297 1 new phase-divergent changesets
298 298 $ hg unamend
299 299 abort: cannot unamend public changesets
300 300 (see 'hg help phases' for details)
301 301 [255]
302 302
303 303 Testing whether unamend retains copies or not
304 304
305 305 $ hg status
306 306
307 307 $ hg mv a foo
308 308
309 309 $ hg ci -m "Moved a to foo"
310 310 $ hg exp --git
311 311 # HG changeset patch
312 312 # User test
313 313 # Date 0 0
314 314 # Thu Jan 01 00:00:00 1970 +0000
315 315 # Node ID cfef290346fbee5126313d7e1aab51d877679b09
316 316 # Parent 03ddd6fc5af19e028c44a2fd6d790dd22712f231
317 317 Moved a to foo
318 318
319 319 diff --git a/a b/foo
320 320 rename from a
321 321 rename to foo
322 322
323 323 $ hg mv b foobar
324 324 $ hg diff --git
325 325 diff --git a/b b/foobar
326 326 rename from b
327 327 rename to foobar
328 328 $ hg amend
329 329
330 330 $ hg exp --git
331 331 # HG changeset patch
332 332 # User test
333 333 # Date 0 0
334 334 # Thu Jan 01 00:00:00 1970 +0000
335 335 # Node ID eca050985275bb271ce3092b54e56ea5c85d29a3
336 336 # Parent 03ddd6fc5af19e028c44a2fd6d790dd22712f231
337 337 Moved a to foo
338 338
339 339 diff --git a/a b/foo
340 340 rename from a
341 341 rename to foo
342 342 diff --git a/b b/foobar
343 343 rename from b
344 344 rename to foobar
345 345
346 346 $ hg mv c wat
347 347 $ hg unamend
348 348
349 349 $ hg verify -v
350 350 repository uses revlog format 1
351 351 checking changesets
352 352 checking manifests
353 353 crosschecking files in changesets and manifests
354 354 checking files
355 355 checked 28 changesets with 16 changes to 11 files
356 356
357 357 Retained copies in new prdecessor commit
358 358
359 359 $ hg exp --git
360 360 # HG changeset patch
361 361 # User test
362 362 # Date 0 0
363 363 # Thu Jan 01 00:00:00 1970 +0000
364 364 # Node ID 552e3af4f01f620f88ca27be1f898316235b736a
365 365 # Parent 03ddd6fc5af19e028c44a2fd6d790dd22712f231
366 366 Moved a to foo
367 367
368 368 diff --git a/a b/foo
369 369 rename from a
370 370 rename to foo
371 371
372 372 Retained copies in working directoy
373 373
374 374 $ hg diff --git
375 375 diff --git a/b b/foobar
376 376 rename from b
377 377 rename to foobar
378 378 diff --git a/c b/wat
379 379 rename from c
380 380 rename to wat
381 381 $ hg revert -qa
382 382 $ rm foobar wat
383 383
384 384 Rename a->b, then amend b->c. After unamend, should look like b->c.
385 385
386 386 $ hg co -q 0
387 387 $ hg mv a b
388 388 $ hg ci -qm 'move to a b'
389 389 $ hg mv b c
390 390 $ hg amend
391 391 $ hg unamend
392 392 $ hg st --copies --change .
393 393 A b
394 394 a
395 395 R a
396 396 $ hg st --copies
397 397 A c
398 398 b
399 399 R b
400 400 $ hg revert -qa
401 401 $ rm c
402 402
403 403 Rename a->b, then amend b->c, and working copy change c->d. After unamend, should look like b->d
404 404
405 405 $ hg co -q 0
406 406 $ hg mv a b
407 407 $ hg ci -qm 'move to a b'
408 warning: commit already existed in the repository!
408 409 $ hg mv b c
409 410 $ hg amend
411 warning: commit already existed in the repository!
410 412 $ hg mv c d
411 413 $ hg unamend
412 414 $ hg st --copies --change .
413 415 A b
414 416 a
415 417 R a
416 418 $ hg st --copies
417 419 A d
418 420 b
419 421 R b
General Comments 0
You need to be logged in to leave comments. Login now