##// END OF EJS Templates
typing: add type hints to `cmdutil.findrepo()`...
Matt Harbison -
r52608:7601978f default
parent child Browse files
Show More
@@ -1,4227 +1,4227
1 1 # cmdutil.py - help for command processing in mercurial
2 2 #
3 3 # Copyright 2005-2007 Olivia Mackall <olivia@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
9 9 import copy as copymod
10 10 import errno
11 11 import functools
12 12 import os
13 13 import re
14 14
15 15 from typing import (
16 16 Any,
17 17 AnyStr,
18 18 Dict,
19 19 Iterable,
20 20 Optional,
21 21 TYPE_CHECKING,
22 22 cast,
23 23 )
24 24
25 25 from .i18n import _
26 26 from .node import (
27 27 hex,
28 28 nullrev,
29 29 short,
30 30 )
31 31 from .pycompat import (
32 32 open,
33 33 )
34 34 from .thirdparty import attr
35 35
36 36 from . import (
37 37 bookmarks,
38 38 bundle2,
39 39 changelog,
40 40 copies,
41 41 crecord as crecordmod,
42 42 encoding,
43 43 error,
44 44 exchange,
45 45 formatter,
46 46 logcmdutil,
47 47 match as matchmod,
48 48 merge as mergemod,
49 49 mergestate as mergestatemod,
50 50 mergeutil,
51 51 obsolete,
52 52 patch,
53 53 pathutil,
54 54 phases,
55 55 pycompat,
56 56 repair,
57 57 revlog,
58 58 rewriteutil,
59 59 scmutil,
60 60 state as statemod,
61 61 streamclone,
62 62 subrepoutil,
63 63 templatekw,
64 64 templater,
65 65 util,
66 66 vfs as vfsmod,
67 67 )
68 68
69 69 from .utils import (
70 70 dateutil,
71 71 stringutil,
72 72 urlutil,
73 73 )
74 74
75 75 from .revlogutils import (
76 76 constants as revlog_constants,
77 77 )
78 78
79 79 if TYPE_CHECKING:
80 80 from . import (
81 81 ui as uimod,
82 82 )
83 83
84 84 stringio = util.stringio
85 85
86 86 # templates of common command options
87 87
88 88 dryrunopts = [
89 89 (b'n', b'dry-run', None, _(b'do not perform actions, just print output')),
90 90 ]
91 91
92 92 confirmopts = [
93 93 (b'', b'confirm', None, _(b'ask before applying actions')),
94 94 ]
95 95
96 96 remoteopts = [
97 97 (b'e', b'ssh', b'', _(b'specify ssh command to use'), _(b'CMD')),
98 98 (
99 99 b'',
100 100 b'remotecmd',
101 101 b'',
102 102 _(b'specify hg command to run on the remote side'),
103 103 _(b'CMD'),
104 104 ),
105 105 (
106 106 b'',
107 107 b'insecure',
108 108 None,
109 109 _(b'do not verify server certificate (ignoring web.cacerts config)'),
110 110 ),
111 111 ]
112 112
113 113 walkopts = [
114 114 (
115 115 b'I',
116 116 b'include',
117 117 [],
118 118 _(b'include names matching the given patterns'),
119 119 _(b'PATTERN'),
120 120 ),
121 121 (
122 122 b'X',
123 123 b'exclude',
124 124 [],
125 125 _(b'exclude names matching the given patterns'),
126 126 _(b'PATTERN'),
127 127 ),
128 128 ]
129 129
130 130 commitopts = [
131 131 (b'm', b'message', b'', _(b'use text as commit message'), _(b'TEXT')),
132 132 (b'l', b'logfile', b'', _(b'read commit message from file'), _(b'FILE')),
133 133 ]
134 134
135 135 commitopts2 = [
136 136 (
137 137 b'd',
138 138 b'date',
139 139 b'',
140 140 _(b'record the specified date as commit date'),
141 141 _(b'DATE'),
142 142 ),
143 143 (
144 144 b'u',
145 145 b'user',
146 146 b'',
147 147 _(b'record the specified user as committer'),
148 148 _(b'USER'),
149 149 ),
150 150 ]
151 151
152 152 commitopts3 = [
153 153 (b'D', b'currentdate', None, _(b'record the current date as commit date')),
154 154 (b'U', b'currentuser', None, _(b'record the current user as committer')),
155 155 ]
156 156
157 157 formatteropts = [
158 158 (b'T', b'template', b'', _(b'display with template'), _(b'TEMPLATE')),
159 159 ]
160 160
161 161 templateopts = [
162 162 (
163 163 b'',
164 164 b'style',
165 165 b'',
166 166 _(b'display using template map file (DEPRECATED)'),
167 167 _(b'STYLE'),
168 168 ),
169 169 (b'T', b'template', b'', _(b'display with template'), _(b'TEMPLATE')),
170 170 ]
171 171
172 172 logopts = [
173 173 (b'p', b'patch', None, _(b'show patch')),
174 174 (b'g', b'git', None, _(b'use git extended diff format')),
175 175 (b'l', b'limit', b'', _(b'limit number of changes displayed'), _(b'NUM')),
176 176 (b'M', b'no-merges', None, _(b'do not show merges')),
177 177 (b'', b'stat', None, _(b'output diffstat-style summary of changes')),
178 178 (b'G', b'graph', None, _(b"show the revision DAG")),
179 179 ] + templateopts
180 180
181 181 diffopts = [
182 182 (b'a', b'text', None, _(b'treat all files as text')),
183 183 (
184 184 b'g',
185 185 b'git',
186 186 None,
187 187 _(b'use git extended diff format (DEFAULT: diff.git)'),
188 188 ),
189 189 (b'', b'binary', None, _(b'generate binary diffs in git mode (default)')),
190 190 (b'', b'nodates', None, _(b'omit dates from diff headers')),
191 191 ]
192 192
193 193 diffwsopts = [
194 194 (
195 195 b'w',
196 196 b'ignore-all-space',
197 197 None,
198 198 _(b'ignore white space when comparing lines'),
199 199 ),
200 200 (
201 201 b'b',
202 202 b'ignore-space-change',
203 203 None,
204 204 _(b'ignore changes in the amount of white space'),
205 205 ),
206 206 (
207 207 b'B',
208 208 b'ignore-blank-lines',
209 209 None,
210 210 _(b'ignore changes whose lines are all blank'),
211 211 ),
212 212 (
213 213 b'Z',
214 214 b'ignore-space-at-eol',
215 215 None,
216 216 _(b'ignore changes in whitespace at EOL'),
217 217 ),
218 218 ]
219 219
220 220 diffopts2 = (
221 221 [
222 222 (b'', b'noprefix', None, _(b'omit a/ and b/ prefixes from filenames')),
223 223 (
224 224 b'p',
225 225 b'show-function',
226 226 None,
227 227 _(
228 228 b'show which function each change is in (DEFAULT: diff.showfunc)'
229 229 ),
230 230 ),
231 231 (b'', b'reverse', None, _(b'produce a diff that undoes the changes')),
232 232 ]
233 233 + diffwsopts
234 234 + [
235 235 (
236 236 b'U',
237 237 b'unified',
238 238 b'',
239 239 _(b'number of lines of context to show'),
240 240 _(b'NUM'),
241 241 ),
242 242 (b'', b'stat', None, _(b'output diffstat-style summary of changes')),
243 243 (
244 244 b'',
245 245 b'root',
246 246 b'',
247 247 _(b'produce diffs relative to subdirectory'),
248 248 _(b'DIR'),
249 249 ),
250 250 ]
251 251 )
252 252
253 253 mergetoolopts = [
254 254 (b't', b'tool', b'', _(b'specify merge tool'), _(b'TOOL')),
255 255 ]
256 256
257 257 similarityopts = [
258 258 (
259 259 b's',
260 260 b'similarity',
261 261 b'',
262 262 _(b'guess renamed files by similarity (0<=s<=100)'),
263 263 _(b'SIMILARITY'),
264 264 )
265 265 ]
266 266
267 267 subrepoopts = [(b'S', b'subrepos', None, _(b'recurse into subrepositories'))]
268 268
269 269 debugrevlogopts = [
270 270 (b'c', b'changelog', False, _(b'open changelog')),
271 271 (b'm', b'manifest', False, _(b'open manifest')),
272 272 (b'', b'dir', b'', _(b'open directory manifest')),
273 273 ]
274 274
275 275 # special string such that everything below this line will be ingored in the
276 276 # editor text
277 277 _linebelow = b"^HG: ------------------------ >8 ------------------------$"
278 278
279 279
280 280 def check_at_most_one_arg(
281 281 opts: Dict[AnyStr, Any],
282 282 *args: AnyStr,
283 283 ) -> Optional[AnyStr]:
284 284 """abort if more than one of the arguments are in opts
285 285
286 286 Returns the unique argument or None if none of them were specified.
287 287 """
288 288
289 289 def to_display(name: AnyStr) -> bytes:
290 290 return pycompat.sysbytes(name).replace(b'_', b'-')
291 291
292 292 previous = None
293 293 for x in args:
294 294 if opts.get(x):
295 295 if previous:
296 296 raise error.InputError(
297 297 _(b'cannot specify both --%s and --%s')
298 298 % (to_display(previous), to_display(x))
299 299 )
300 300 previous = x
301 301 return previous
302 302
303 303
304 304 def check_incompatible_arguments(
305 305 opts: Dict[AnyStr, Any],
306 306 first: AnyStr,
307 307 others: Iterable[AnyStr],
308 308 ) -> None:
309 309 """abort if the first argument is given along with any of the others
310 310
311 311 Unlike check_at_most_one_arg(), `others` are not mutually exclusive
312 312 among themselves, and they're passed as a single collection.
313 313 """
314 314 for other in others:
315 315 check_at_most_one_arg(opts, first, other)
316 316
317 317
318 318 def resolve_commit_options(ui: "uimod.ui", opts: Dict[str, Any]) -> bool:
319 319 """modify commit options dict to handle related options
320 320
321 321 The return value indicates that ``rewrite.update-timestamp`` is the reason
322 322 the ``date`` option is set.
323 323 """
324 324 check_at_most_one_arg(opts, 'date', 'currentdate')
325 325 check_at_most_one_arg(opts, 'user', 'currentuser')
326 326
327 327 datemaydiffer = False # date-only change should be ignored?
328 328
329 329 if opts.get('currentdate'):
330 330 opts['date'] = b'%d %d' % dateutil.makedate()
331 331 elif (
332 332 not opts.get('date')
333 333 and ui.configbool(b'rewrite', b'update-timestamp')
334 334 and opts.get('currentdate') is None
335 335 ):
336 336 opts['date'] = b'%d %d' % dateutil.makedate()
337 337 datemaydiffer = True
338 338
339 339 if opts.get('currentuser'):
340 340 opts['user'] = ui.username()
341 341
342 342 return datemaydiffer
343 343
344 344
345 345 def check_note_size(opts: Dict[str, Any]) -> None:
346 346 """make sure note is of valid format"""
347 347
348 348 note = opts.get('note')
349 349 if not note:
350 350 return
351 351
352 352 if len(note) > 255:
353 353 raise error.InputError(_(b"cannot store a note of more than 255 bytes"))
354 354 if b'\n' in note:
355 355 raise error.InputError(_(b"note cannot contain a newline"))
356 356
357 357
358 358 def ishunk(x):
359 359 hunkclasses = (crecordmod.uihunk, patch.recordhunk)
360 360 return isinstance(x, hunkclasses)
361 361
362 362
363 363 def isheader(x):
364 364 headerclasses = (crecordmod.uiheader, patch.header)
365 365 return isinstance(x, headerclasses)
366 366
367 367
368 368 def newandmodified(chunks):
369 369 newlyaddedandmodifiedfiles = set()
370 370 alsorestore = set()
371 371 for chunk in chunks:
372 372 if isheader(chunk) and chunk.isnewfile():
373 373 newlyaddedandmodifiedfiles.add(chunk.filename())
374 374 alsorestore.update(set(chunk.files()) - {chunk.filename()})
375 375 return newlyaddedandmodifiedfiles, alsorestore
376 376
377 377
378 378 def parsealiases(cmd):
379 379 base_aliases = cmd.split(b"|")
380 380 all_aliases = set(base_aliases)
381 381 extra_aliases = []
382 382 for alias in base_aliases:
383 383 if b'-' in alias:
384 384 folded_alias = alias.replace(b'-', b'')
385 385 if folded_alias not in all_aliases:
386 386 all_aliases.add(folded_alias)
387 387 extra_aliases.append(folded_alias)
388 388 base_aliases.extend(extra_aliases)
389 389 return base_aliases
390 390
391 391
392 392 def setupwrapcolorwrite(ui):
393 393 # wrap ui.write so diff output can be labeled/colorized
394 394 def wrapwrite(orig, *args, **kw):
395 395 label = kw.pop('label', b'')
396 396 for chunk, l in patch.difflabel(lambda: args):
397 397 orig(chunk, label=label + l)
398 398
399 399 oldwrite = ui.write
400 400
401 401 def wrap(*args, **kwargs):
402 402 return wrapwrite(oldwrite, *args, **kwargs)
403 403
404 404 setattr(ui, 'write', wrap)
405 405 return oldwrite
406 406
407 407
408 408 def filterchunks(ui, originalhunks, usecurses, testfile, match, operation=None):
409 409 try:
410 410 if usecurses:
411 411 if testfile:
412 412 recordfn = crecordmod.testdecorator(
413 413 testfile, crecordmod.testchunkselector
414 414 )
415 415 else:
416 416 recordfn = crecordmod.chunkselector
417 417
418 418 return crecordmod.filterpatch(
419 419 ui, originalhunks, recordfn, operation
420 420 )
421 421 except crecordmod.fallbackerror as e:
422 422 ui.warn(b'%s\n' % e)
423 423 ui.warn(_(b'falling back to text mode\n'))
424 424
425 425 return patch.filterpatch(ui, originalhunks, match, operation)
426 426
427 427
428 428 def recordfilter(ui, originalhunks, match, operation=None):
429 429 """Prompts the user to filter the originalhunks and return a list of
430 430 selected hunks.
431 431 *operation* is used for to build ui messages to indicate the user what
432 432 kind of filtering they are doing: reverting, committing, shelving, etc.
433 433 (see patch.filterpatch).
434 434 """
435 435 usecurses = crecordmod.checkcurses(ui)
436 436 testfile = ui.config(b'experimental', b'crecordtest')
437 437 oldwrite = setupwrapcolorwrite(ui)
438 438 try:
439 439 newchunks, newopts = filterchunks(
440 440 ui, originalhunks, usecurses, testfile, match, operation
441 441 )
442 442 finally:
443 443 ui.write = oldwrite
444 444 return newchunks, newopts
445 445
446 446
447 447 def _record(
448 448 ui,
449 449 repo,
450 450 message,
451 451 match,
452 452 opts,
453 453 commitfunc,
454 454 backupall,
455 455 filterfn,
456 456 pats,
457 457 ):
458 458 """This is generic record driver.
459 459
460 460 Its job is to interactively filter local changes, and
461 461 accordingly prepare working directory into a state in which the
462 462 job can be delegated to a non-interactive commit command such as
463 463 'commit' or 'qrefresh'.
464 464
465 465 After the actual job is done by non-interactive command, the
466 466 working directory is restored to its original state.
467 467
468 468 In the end we'll record interesting changes, and everything else
469 469 will be left in place, so the user can continue working.
470 470 """
471 471 assert repo.currentwlock() is not None
472 472 if not opts.get(b'interactive-unshelve'):
473 473 checkunfinished(repo, commit=True)
474 474 wctx = repo[None]
475 475 merge = len(wctx.parents()) > 1
476 476 if merge:
477 477 raise error.InputError(
478 478 _(b'cannot partially commit a merge ' b'(use "hg commit" instead)')
479 479 )
480 480
481 481 def fail(f, msg):
482 482 raise error.InputError(b'%s: %s' % (f, msg))
483 483
484 484 force = opts.get(b'force')
485 485 if not force:
486 486 match = matchmod.badmatch(match, fail)
487 487
488 488 status = repo.status(match=match)
489 489
490 490 overrides = {(b'ui', b'commitsubrepos'): True}
491 491
492 492 with repo.ui.configoverride(overrides, b'record'):
493 493 # subrepoutil.precommit() modifies the status
494 494 tmpstatus = scmutil.status(
495 495 copymod.copy(status.modified),
496 496 copymod.copy(status.added),
497 497 copymod.copy(status.removed),
498 498 copymod.copy(status.deleted),
499 499 copymod.copy(status.unknown),
500 500 copymod.copy(status.ignored),
501 501 copymod.copy(status.clean), # pytype: disable=wrong-arg-count
502 502 )
503 503
504 504 # Force allows -X subrepo to skip the subrepo.
505 505 subs, commitsubs, newstate = subrepoutil.precommit(
506 506 repo.ui, wctx, tmpstatus, match, force=True
507 507 )
508 508 for s in subs:
509 509 if s in commitsubs:
510 510 dirtyreason = wctx.sub(s).dirtyreason(True)
511 511 raise error.Abort(dirtyreason)
512 512
513 513 if not force:
514 514 repo.checkcommitpatterns(wctx, match, status, fail)
515 515 diffopts = patch.difffeatureopts(
516 516 ui,
517 517 opts=opts,
518 518 whitespace=True,
519 519 section=b'commands',
520 520 configprefix=b'commit.interactive.',
521 521 )
522 522 diffopts.nodates = True
523 523 diffopts.git = True
524 524 diffopts.showfunc = True
525 525 originaldiff = patch.diff(repo, changes=status, opts=diffopts)
526 526 original_headers = patch.parsepatch(originaldiff)
527 527 match = scmutil.match(repo[None], pats)
528 528
529 529 # 1. filter patch, since we are intending to apply subset of it
530 530 try:
531 531 chunks, newopts = filterfn(ui, original_headers, match)
532 532 except error.PatchParseError as err:
533 533 raise error.InputError(_(b'error parsing patch: %s') % err)
534 534 except error.PatchApplicationError as err:
535 535 raise error.StateError(_(b'error applying patch: %s') % err)
536 536 opts.update(newopts)
537 537
538 538 # We need to keep a backup of files that have been newly added and
539 539 # modified during the recording process because there is a previous
540 540 # version without the edit in the workdir. We also will need to restore
541 541 # files that were the sources of renames so that the patch application
542 542 # works.
543 543 newlyaddedandmodifiedfiles, alsorestore = newandmodified(chunks)
544 544 contenders = set()
545 545 for h in chunks:
546 546 if isheader(h):
547 547 contenders.update(set(h.files()))
548 548
549 549 changed = status.modified + status.added + status.removed
550 550 newfiles = [f for f in changed if f in contenders]
551 551 if not newfiles:
552 552 ui.status(_(b'no changes to record\n'))
553 553 return 0
554 554
555 555 modified = set(status.modified)
556 556
557 557 # 2. backup changed files, so we can restore them in the end
558 558
559 559 if backupall:
560 560 tobackup = changed
561 561 else:
562 562 tobackup = [
563 563 f
564 564 for f in newfiles
565 565 if f in modified or f in newlyaddedandmodifiedfiles
566 566 ]
567 567 backups = {}
568 568 if tobackup:
569 569 backupdir = repo.vfs.join(b'record-backups')
570 570 try:
571 571 os.mkdir(backupdir)
572 572 except FileExistsError:
573 573 pass
574 574 try:
575 575 # backup continues
576 576 for f in tobackup:
577 577 fd, tmpname = pycompat.mkstemp(
578 578 prefix=os.path.basename(f) + b'.', dir=backupdir
579 579 )
580 580 os.close(fd)
581 581 ui.debug(b'backup %r as %r\n' % (f, tmpname))
582 582 util.copyfile(repo.wjoin(f), tmpname, copystat=True)
583 583 backups[f] = tmpname
584 584
585 585 fp = stringio()
586 586 for c in chunks:
587 587 fname = c.filename()
588 588 if fname in backups:
589 589 c.write(fp)
590 590 dopatch = fp.tell()
591 591 fp.seek(0)
592 592
593 593 # 2.5 optionally review / modify patch in text editor
594 594 if opts.get(b'review', False):
595 595 patchtext = (
596 596 crecordmod.diffhelptext + crecordmod.patchhelptext + fp.read()
597 597 )
598 598 reviewedpatch = ui.edit(
599 599 patchtext, b"", action=b"diff", repopath=repo.path
600 600 )
601 601 fp.truncate(0)
602 602 fp.write(reviewedpatch)
603 603 fp.seek(0)
604 604
605 605 [os.unlink(repo.wjoin(c)) for c in newlyaddedandmodifiedfiles]
606 606 # 3a. apply filtered patch to clean repo (clean)
607 607 if backups:
608 608 m = scmutil.matchfiles(repo, set(backups.keys()) | alsorestore)
609 609 mergemod.revert_to(repo[b'.'], matcher=m)
610 610
611 611 # 3b. (apply)
612 612 if dopatch:
613 613 try:
614 614 ui.debug(b'applying patch\n')
615 615 ui.debug(fp.getvalue())
616 616 patch.internalpatch(ui, repo, fp, 1, eolmode=None)
617 617 except error.PatchParseError as err:
618 618 raise error.InputError(pycompat.bytestr(err))
619 619 except error.PatchApplicationError as err:
620 620 raise error.StateError(pycompat.bytestr(err))
621 621 del fp
622 622
623 623 # 4. We prepared working directory according to filtered
624 624 # patch. Now is the time to delegate the job to
625 625 # commit/qrefresh or the like!
626 626
627 627 # Make all of the pathnames absolute.
628 628 newfiles = [repo.wjoin(nf) for nf in newfiles]
629 629 return commitfunc(ui, repo, *newfiles, **pycompat.strkwargs(opts))
630 630 finally:
631 631 # 5. finally restore backed-up files
632 632 try:
633 633 dirstate = repo.dirstate
634 634 for realname, tmpname in backups.items():
635 635 ui.debug(b'restoring %r to %r\n' % (tmpname, realname))
636 636
637 637 if dirstate.get_entry(realname).maybe_clean:
638 638 # without normallookup, restoring timestamp
639 639 # may cause partially committed files
640 640 # to be treated as unmodified
641 641
642 642 # XXX-PENDINGCHANGE: We should clarify the context in
643 643 # which this function is called to make sure it
644 644 # already called within a `pendingchange`, However we
645 645 # are taking a shortcut here in order to be able to
646 646 # quickly deprecated the older API.
647 647 with dirstate.changing_parents(repo):
648 648 dirstate.update_file(
649 649 realname,
650 650 p1_tracked=True,
651 651 wc_tracked=True,
652 652 possibly_dirty=True,
653 653 )
654 654
655 655 # copystat=True here and above are a hack to trick any
656 656 # editors that have f open that we haven't modified them.
657 657 #
658 658 # Also note that this racy as an editor could notice the
659 659 # file's mtime before we've finished writing it.
660 660 util.copyfile(tmpname, repo.wjoin(realname), copystat=True)
661 661 os.unlink(tmpname)
662 662 if tobackup:
663 663 os.rmdir(backupdir)
664 664 except OSError:
665 665 pass
666 666
667 667
668 668 def dorecord(
669 669 ui, repo, commitfunc, cmdsuggest, backupall, filterfn, *pats, **opts
670 670 ):
671 671 opts = pycompat.byteskwargs(opts)
672 672 if not ui.interactive():
673 673 if cmdsuggest:
674 674 msg = _(b'running non-interactively, use %s instead') % cmdsuggest
675 675 else:
676 676 msg = _(b'running non-interactively')
677 677 raise error.InputError(msg)
678 678
679 679 # make sure username is set before going interactive
680 680 if not opts.get(b'user'):
681 681 ui.username() # raise exception, username not provided
682 682
683 683 func = functools.partial(
684 684 _record,
685 685 commitfunc=commitfunc,
686 686 backupall=backupall,
687 687 filterfn=filterfn,
688 688 pats=pats,
689 689 )
690 690
691 691 return commit(ui, repo, func, pats, opts)
692 692
693 693
694 694 class dirnode:
695 695 """
696 696 Represent a directory in user working copy with information required for
697 697 the purpose of tersing its status.
698 698
699 699 path is the path to the directory, without a trailing '/'
700 700
701 701 statuses is a set of statuses of all files in this directory (this includes
702 702 all the files in all the subdirectories too)
703 703
704 704 files is a list of files which are direct child of this directory
705 705
706 706 subdirs is a dictionary of sub-directory name as the key and it's own
707 707 dirnode object as the value
708 708 """
709 709
710 710 def __init__(self, dirpath):
711 711 self.path = dirpath
712 712 self.statuses = set()
713 713 self.files = []
714 714 self.subdirs = {}
715 715
716 716 def _addfileindir(self, filename, status):
717 717 """Add a file in this directory as a direct child."""
718 718 self.files.append((filename, status))
719 719
720 720 def addfile(self, filename, status):
721 721 """
722 722 Add a file to this directory or to its direct parent directory.
723 723
724 724 If the file is not direct child of this directory, we traverse to the
725 725 directory of which this file is a direct child of and add the file
726 726 there.
727 727 """
728 728
729 729 # the filename contains a path separator, it means it's not the direct
730 730 # child of this directory
731 731 if b'/' in filename:
732 732 subdir, filep = filename.split(b'/', 1)
733 733
734 734 # does the dirnode object for subdir exists
735 735 if subdir not in self.subdirs:
736 736 subdirpath = pathutil.join(self.path, subdir)
737 737 self.subdirs[subdir] = dirnode(subdirpath)
738 738
739 739 # try adding the file in subdir
740 740 self.subdirs[subdir].addfile(filep, status)
741 741
742 742 else:
743 743 self._addfileindir(filename, status)
744 744
745 745 if status not in self.statuses:
746 746 self.statuses.add(status)
747 747
748 748 def iterfilepaths(self):
749 749 """Yield (status, path) for files directly under this directory."""
750 750 for f, st in self.files:
751 751 yield st, pathutil.join(self.path, f)
752 752
753 753 def tersewalk(self, terseargs):
754 754 """
755 755 Yield (status, path) obtained by processing the status of this
756 756 dirnode.
757 757
758 758 terseargs is the string of arguments passed by the user with `--terse`
759 759 flag.
760 760
761 761 Following are the cases which can happen:
762 762
763 763 1) All the files in the directory (including all the files in its
764 764 subdirectories) share the same status and the user has asked us to terse
765 765 that status. -> yield (status, dirpath). dirpath will end in '/'.
766 766
767 767 2) Otherwise, we do following:
768 768
769 769 a) Yield (status, filepath) for all the files which are in this
770 770 directory (only the ones in this directory, not the subdirs)
771 771
772 772 b) Recurse the function on all the subdirectories of this
773 773 directory
774 774 """
775 775
776 776 if len(self.statuses) == 1:
777 777 onlyst = self.statuses.pop()
778 778
779 779 # Making sure we terse only when the status abbreviation is
780 780 # passed as terse argument
781 781 if onlyst in terseargs:
782 782 yield onlyst, self.path + b'/'
783 783 return
784 784
785 785 # add the files to status list
786 786 for st, fpath in self.iterfilepaths():
787 787 yield st, fpath
788 788
789 789 # recurse on the subdirs
790 790 for dirobj in self.subdirs.values():
791 791 for st, fpath in dirobj.tersewalk(terseargs):
792 792 yield st, fpath
793 793
794 794
795 795 def tersedir(statuslist, terseargs):
796 796 """
797 797 Terse the status if all the files in a directory shares the same status.
798 798
799 799 statuslist is scmutil.status() object which contains a list of files for
800 800 each status.
801 801 terseargs is string which is passed by the user as the argument to `--terse`
802 802 flag.
803 803
804 804 The function makes a tree of objects of dirnode class, and at each node it
805 805 stores the information required to know whether we can terse a certain
806 806 directory or not.
807 807 """
808 808 # the order matters here as that is used to produce final list
809 809 allst = (b'm', b'a', b'r', b'd', b'u', b'i', b'c')
810 810
811 811 # checking the argument validity
812 812 for s in pycompat.bytestr(terseargs):
813 813 if s not in allst:
814 814 raise error.InputError(_(b"'%s' not recognized") % s)
815 815
816 816 # creating a dirnode object for the root of the repo
817 817 rootobj = dirnode(b'')
818 818 pstatus = (
819 819 ('modified', b'm'),
820 820 ('added', b'a'),
821 821 ('deleted', b'd'),
822 822 ('clean', b'c'),
823 823 ('unknown', b'u'),
824 824 ('ignored', b'i'),
825 825 ('removed', b'r'),
826 826 )
827 827
828 828 tersedict = {}
829 829 for attrname, statuschar in pstatus:
830 830 for f in getattr(statuslist, attrname):
831 831 rootobj.addfile(f, statuschar)
832 832 tersedict[statuschar] = []
833 833
834 834 # we won't be tersing the root dir, so add files in it
835 835 for st, fpath in rootobj.iterfilepaths():
836 836 tersedict[st].append(fpath)
837 837
838 838 # process each sub-directory and build tersedict
839 839 for subdir in rootobj.subdirs.values():
840 840 for st, f in subdir.tersewalk(terseargs):
841 841 tersedict[st].append(f)
842 842
843 843 tersedlist = []
844 844 for st in allst:
845 845 tersedict[st].sort()
846 846 tersedlist.append(tersedict[st])
847 847
848 848 return scmutil.status(*tersedlist)
849 849
850 850
851 851 def _commentlines(raw):
852 852 '''Surround lineswith a comment char and a new line'''
853 853 lines = raw.splitlines()
854 854 commentedlines = [b'# %s' % line for line in lines]
855 855 return b'\n'.join(commentedlines) + b'\n'
856 856
857 857
858 858 @attr.s(frozen=True)
859 859 class morestatus:
860 860 repo = attr.ib()
861 861 unfinishedop = attr.ib()
862 862 unfinishedmsg = attr.ib()
863 863 activemerge = attr.ib()
864 864 unresolvedpaths = attr.ib()
865 865 _formattedpaths = attr.ib(init=False, default=set())
866 866 _label = b'status.morestatus'
867 867
868 868 def formatfile(self, path, fm):
869 869 self._formattedpaths.add(path)
870 870 if self.activemerge and path in self.unresolvedpaths:
871 871 fm.data(unresolved=True)
872 872
873 873 def formatfooter(self, fm):
874 874 if self.unfinishedop or self.unfinishedmsg:
875 875 fm.startitem()
876 876 fm.data(itemtype=b'morestatus')
877 877
878 878 if self.unfinishedop:
879 879 fm.data(unfinished=self.unfinishedop)
880 880 statemsg = (
881 881 _(b'The repository is in an unfinished *%s* state.')
882 882 % self.unfinishedop
883 883 )
884 884 fm.plain(b'%s\n' % _commentlines(statemsg), label=self._label)
885 885 if self.unfinishedmsg:
886 886 fm.data(unfinishedmsg=self.unfinishedmsg)
887 887
888 888 # May also start new data items.
889 889 self._formatconflicts(fm)
890 890
891 891 if self.unfinishedmsg:
892 892 fm.plain(
893 893 b'%s\n' % _commentlines(self.unfinishedmsg), label=self._label
894 894 )
895 895
896 896 def _formatconflicts(self, fm):
897 897 if not self.activemerge:
898 898 return
899 899
900 900 if self.unresolvedpaths:
901 901 mergeliststr = b'\n'.join(
902 902 [
903 903 b' %s'
904 904 % util.pathto(self.repo.root, encoding.getcwd(), path)
905 905 for path in self.unresolvedpaths
906 906 ]
907 907 )
908 908 msg = (
909 909 _(
910 910 b'''Unresolved merge conflicts:
911 911
912 912 %s
913 913
914 914 To mark files as resolved: hg resolve --mark FILE'''
915 915 )
916 916 % mergeliststr
917 917 )
918 918
919 919 # If any paths with unresolved conflicts were not previously
920 920 # formatted, output them now.
921 921 for f in self.unresolvedpaths:
922 922 if f in self._formattedpaths:
923 923 # Already output.
924 924 continue
925 925 fm.startitem()
926 926 fm.context(repo=self.repo)
927 927 # We can't claim to know the status of the file - it may just
928 928 # have been in one of the states that were not requested for
929 929 # display, so it could be anything.
930 930 fm.data(itemtype=b'file', path=f, unresolved=True)
931 931
932 932 else:
933 933 msg = _(b'No unresolved merge conflicts.')
934 934
935 935 fm.plain(b'%s\n' % _commentlines(msg), label=self._label)
936 936
937 937
938 938 def readmorestatus(repo):
939 939 """Returns a morestatus object if the repo has unfinished state."""
940 940 statetuple = statemod.getrepostate(repo)
941 941 mergestate = mergestatemod.mergestate.read(repo)
942 942 activemerge = mergestate.active()
943 943 if not statetuple and not activemerge:
944 944 return None
945 945
946 946 unfinishedop = unfinishedmsg = unresolved = None
947 947 if statetuple:
948 948 unfinishedop, unfinishedmsg = statetuple
949 949 if activemerge:
950 950 unresolved = sorted(mergestate.unresolved())
951 951 return morestatus(
952 952 repo, unfinishedop, unfinishedmsg, activemerge, unresolved
953 953 )
954 954
955 955
956 956 def findpossible(cmd, table, strict=False):
957 957 """
958 958 Return cmd -> (aliases, command table entry)
959 959 for each matching command.
960 960 Return debug commands (or their aliases) only if no normal command matches.
961 961 """
962 962 choice = {}
963 963 debugchoice = {}
964 964
965 965 if cmd in table:
966 966 # short-circuit exact matches, "log" alias beats "log|history"
967 967 keys = [cmd]
968 968 else:
969 969 keys = table.keys()
970 970
971 971 allcmds = []
972 972 for e in keys:
973 973 aliases = parsealiases(e)
974 974 allcmds.extend(aliases)
975 975 found = None
976 976 if cmd in aliases:
977 977 found = cmd
978 978 elif not strict:
979 979 for a in aliases:
980 980 if a.startswith(cmd):
981 981 found = a
982 982 break
983 983 if found is not None:
984 984 if aliases[0].startswith(b"debug") or found.startswith(b"debug"):
985 985 debugchoice[found] = (aliases, table[e])
986 986 else:
987 987 choice[found] = (aliases, table[e])
988 988
989 989 if not choice and debugchoice:
990 990 choice = debugchoice
991 991
992 992 return choice, allcmds
993 993
994 994
995 995 def findcmd(cmd, table, strict=True):
996 996 """Return (aliases, command table entry) for command string."""
997 997 choice, allcmds = findpossible(cmd, table, strict)
998 998
999 999 if cmd in choice:
1000 1000 return choice[cmd]
1001 1001
1002 1002 if len(choice) > 1:
1003 1003 clist = sorted(choice)
1004 1004 raise error.AmbiguousCommand(cmd, clist)
1005 1005
1006 1006 if choice:
1007 1007 return list(choice.values())[0]
1008 1008
1009 1009 raise error.UnknownCommand(cmd, allcmds)
1010 1010
1011 1011
1012 1012 def changebranch(ui, repo, revs, label, **opts):
1013 1013 """Change the branch name of given revs to label"""
1014 1014
1015 1015 with repo.wlock(), repo.lock(), repo.transaction(b'branches'):
1016 1016 # abort in case of uncommitted merge or dirty wdir
1017 1017 bailifchanged(repo)
1018 1018 revs = logcmdutil.revrange(repo, revs)
1019 1019 if not revs:
1020 1020 raise error.InputError(b"empty revision set")
1021 1021 roots = repo.revs(b'roots(%ld)', revs)
1022 1022 if len(roots) > 1:
1023 1023 raise error.InputError(
1024 1024 _(b"cannot change branch of non-linear revisions")
1025 1025 )
1026 1026 rewriteutil.precheck(repo, revs, b'change branch of')
1027 1027
1028 1028 root = repo[roots.first()]
1029 1029 rpb = {parent.branch() for parent in root.parents()}
1030 1030 if (
1031 1031 not opts.get('force')
1032 1032 and label not in rpb
1033 1033 and label in repo.branchmap()
1034 1034 ):
1035 1035 raise error.InputError(
1036 1036 _(b"a branch of the same name already exists")
1037 1037 )
1038 1038
1039 1039 # make sure only topological heads
1040 1040 if repo.revs(b'heads(%ld) - head()', revs):
1041 1041 raise error.InputError(
1042 1042 _(b"cannot change branch in middle of a stack")
1043 1043 )
1044 1044
1045 1045 replacements = {}
1046 1046 # avoid import cycle mercurial.cmdutil -> mercurial.context ->
1047 1047 # mercurial.subrepo -> mercurial.cmdutil
1048 1048 from . import context
1049 1049
1050 1050 for rev in revs:
1051 1051 ctx = repo[rev]
1052 1052 oldbranch = ctx.branch()
1053 1053 # check if ctx has same branch
1054 1054 if oldbranch == label:
1055 1055 continue
1056 1056
1057 1057 def filectxfn(repo, newctx, path):
1058 1058 try:
1059 1059 return ctx[path]
1060 1060 except error.ManifestLookupError:
1061 1061 return None
1062 1062
1063 1063 ui.debug(
1064 1064 b"changing branch of '%s' from '%s' to '%s'\n"
1065 1065 % (hex(ctx.node()), oldbranch, label)
1066 1066 )
1067 1067 extra = ctx.extra()
1068 1068 extra[b'branch_change'] = hex(ctx.node())
1069 1069 # While changing branch of set of linear commits, make sure that
1070 1070 # we base our commits on new parent rather than old parent which
1071 1071 # was obsoleted while changing the branch
1072 1072 p1 = ctx.p1().node()
1073 1073 p2 = ctx.p2().node()
1074 1074 if p1 in replacements:
1075 1075 p1 = replacements[p1][0]
1076 1076 if p2 in replacements:
1077 1077 p2 = replacements[p2][0]
1078 1078
1079 1079 mc = context.memctx(
1080 1080 repo,
1081 1081 (p1, p2),
1082 1082 ctx.description(),
1083 1083 ctx.files(),
1084 1084 filectxfn,
1085 1085 user=ctx.user(),
1086 1086 date=ctx.date(),
1087 1087 extra=extra,
1088 1088 branch=label,
1089 1089 )
1090 1090
1091 1091 newnode = repo.commitctx(mc)
1092 1092 replacements[ctx.node()] = (newnode,)
1093 1093 ui.debug(b'new node id is %s\n' % hex(newnode))
1094 1094
1095 1095 # create obsmarkers and move bookmarks
1096 1096 scmutil.cleanupnodes(
1097 1097 repo, replacements, b'branch-change', fixphase=True
1098 1098 )
1099 1099
1100 1100 # move the working copy too
1101 1101 wctx = repo[None]
1102 1102 # in-progress merge is a bit too complex for now.
1103 1103 if len(wctx.parents()) == 1:
1104 1104 newid = replacements.get(wctx.p1().node())
1105 1105 if newid is not None:
1106 1106 # avoid import cycle mercurial.cmdutil -> mercurial.hg ->
1107 1107 # mercurial.cmdutil
1108 1108 from . import hg
1109 1109
1110 1110 hg.update(repo, newid[0], quietempty=True)
1111 1111
1112 1112 ui.status(_(b"changed branch on %d changesets\n") % len(replacements))
1113 1113
1114 1114
1115 def findrepo(p):
1115 def findrepo(p: bytes) -> Optional[bytes]:
1116 1116 while not os.path.isdir(os.path.join(p, b".hg")):
1117 1117 oldp, p = p, os.path.dirname(p)
1118 1118 if p == oldp:
1119 1119 return None
1120 1120
1121 1121 return p
1122 1122
1123 1123
1124 1124 def bailifchanged(repo, merge=True, hint=None):
1125 1125 """enforce the precondition that working directory must be clean.
1126 1126
1127 1127 'merge' can be set to false if a pending uncommitted merge should be
1128 1128 ignored (such as when 'update --check' runs).
1129 1129
1130 1130 'hint' is the usual hint given to Abort exception.
1131 1131 """
1132 1132
1133 1133 if merge and repo.dirstate.p2() != repo.nullid:
1134 1134 raise error.StateError(_(b'outstanding uncommitted merge'), hint=hint)
1135 1135 st = repo.status()
1136 1136 if st.modified or st.added or st.removed or st.deleted:
1137 1137 raise error.StateError(_(b'uncommitted changes'), hint=hint)
1138 1138 ctx = repo[None]
1139 1139 for s in sorted(ctx.substate):
1140 1140 ctx.sub(s).bailifchanged(hint=hint)
1141 1141
1142 1142
1143 1143 def logmessage(ui: "uimod.ui", opts: Dict[bytes, Any]) -> Optional[bytes]:
1144 1144 """get the log message according to -m and -l option"""
1145 1145
1146 1146 check_at_most_one_arg(opts, b'message', b'logfile')
1147 1147
1148 1148 message = cast(Optional[bytes], opts.get(b'message'))
1149 1149 logfile = opts.get(b'logfile')
1150 1150
1151 1151 if not message and logfile:
1152 1152 try:
1153 1153 if isstdiofilename(logfile):
1154 1154 message = ui.fin.read()
1155 1155 else:
1156 1156 message = b'\n'.join(util.readfile(logfile).splitlines())
1157 1157 except IOError as inst:
1158 1158 raise error.Abort(
1159 1159 _(b"can't read commit message '%s': %s")
1160 1160 % (logfile, encoding.strtolocal(inst.strerror))
1161 1161 )
1162 1162 return message
1163 1163
1164 1164
1165 1165 def mergeeditform(ctxorbool, baseformname):
1166 1166 """return appropriate editform name (referencing a committemplate)
1167 1167
1168 1168 'ctxorbool' is either a ctx to be committed, or a bool indicating whether
1169 1169 merging is committed.
1170 1170
1171 1171 This returns baseformname with '.merge' appended if it is a merge,
1172 1172 otherwise '.normal' is appended.
1173 1173 """
1174 1174 if isinstance(ctxorbool, bool):
1175 1175 if ctxorbool:
1176 1176 return baseformname + b".merge"
1177 1177 elif len(ctxorbool.parents()) > 1:
1178 1178 return baseformname + b".merge"
1179 1179
1180 1180 return baseformname + b".normal"
1181 1181
1182 1182
1183 1183 def getcommiteditor(
1184 1184 edit=False, finishdesc=None, extramsg=None, editform=b'', **opts
1185 1185 ):
1186 1186 """get appropriate commit message editor according to '--edit' option
1187 1187
1188 1188 'finishdesc' is a function to be called with edited commit message
1189 1189 (= 'description' of the new changeset) just after editing, but
1190 1190 before checking empty-ness. It should return actual text to be
1191 1191 stored into history. This allows to change description before
1192 1192 storing.
1193 1193
1194 1194 'extramsg' is a extra message to be shown in the editor instead of
1195 1195 'Leave message empty to abort commit' line. 'HG: ' prefix and EOL
1196 1196 is automatically added.
1197 1197
1198 1198 'editform' is a dot-separated list of names, to distinguish
1199 1199 the purpose of commit text editing.
1200 1200
1201 1201 'getcommiteditor' returns 'commitforceeditor' regardless of
1202 1202 'edit', if one of 'finishdesc' or 'extramsg' is specified, because
1203 1203 they are specific for usage in MQ.
1204 1204 """
1205 1205 if edit or finishdesc or extramsg:
1206 1206 return lambda r, c, s: commitforceeditor(
1207 1207 r, c, s, finishdesc=finishdesc, extramsg=extramsg, editform=editform
1208 1208 )
1209 1209 elif editform:
1210 1210 return lambda r, c, s: commiteditor(r, c, s, editform=editform)
1211 1211 else:
1212 1212 return commiteditor
1213 1213
1214 1214
1215 1215 def _escapecommandtemplate(tmpl):
1216 1216 parts = []
1217 1217 for typ, start, end in templater.scantemplate(tmpl, raw=True):
1218 1218 if typ == b'string':
1219 1219 parts.append(stringutil.escapestr(tmpl[start:end]))
1220 1220 else:
1221 1221 parts.append(tmpl[start:end])
1222 1222 return b''.join(parts)
1223 1223
1224 1224
1225 1225 def rendercommandtemplate(ui, tmpl, props):
1226 1226 r"""Expand a literal template 'tmpl' in a way suitable for command line
1227 1227
1228 1228 '\' in outermost string is not taken as an escape character because it
1229 1229 is a directory separator on Windows.
1230 1230
1231 1231 >>> from . import ui as uimod
1232 1232 >>> ui = uimod.ui()
1233 1233 >>> rendercommandtemplate(ui, b'c:\\{path}', {b'path': b'foo'})
1234 1234 'c:\\foo'
1235 1235 >>> rendercommandtemplate(ui, b'{"c:\\{path}"}', {'path': b'foo'})
1236 1236 'c:{path}'
1237 1237 """
1238 1238 if not tmpl:
1239 1239 return tmpl
1240 1240 t = formatter.maketemplater(ui, _escapecommandtemplate(tmpl))
1241 1241 return t.renderdefault(props)
1242 1242
1243 1243
1244 1244 def rendertemplate(ctx, tmpl, props=None):
1245 1245 """Expand a literal template 'tmpl' byte-string against one changeset
1246 1246
1247 1247 Each props item must be a stringify-able value or a callable returning
1248 1248 such value, i.e. no bare list nor dict should be passed.
1249 1249 """
1250 1250 repo = ctx.repo()
1251 1251 tres = formatter.templateresources(repo.ui, repo)
1252 1252 t = formatter.maketemplater(
1253 1253 repo.ui, tmpl, defaults=templatekw.keywords, resources=tres
1254 1254 )
1255 1255 mapping = {b'ctx': ctx}
1256 1256 if props:
1257 1257 mapping.update(props)
1258 1258 return t.renderdefault(mapping)
1259 1259
1260 1260
1261 1261 def format_changeset_summary(ui, ctx, command=None, default_spec=None):
1262 1262 """Format a changeset summary (one line)."""
1263 1263 spec = None
1264 1264 if command:
1265 1265 spec = ui.config(
1266 1266 b'command-templates', b'oneline-summary.%s' % command, None
1267 1267 )
1268 1268 if not spec:
1269 1269 spec = ui.config(b'command-templates', b'oneline-summary')
1270 1270 if not spec:
1271 1271 spec = default_spec
1272 1272 if not spec:
1273 1273 spec = (
1274 1274 b'{separate(" ", '
1275 1275 b'label("oneline-summary.changeset", "{rev}:{node|short}")'
1276 1276 b', '
1277 1277 b'join(filter(namespaces % "{ifeq(namespace, "branches", "", join(names % "{label("oneline-summary.{namespace}", name)}", " "))}"), " ")'
1278 1278 b')} '
1279 1279 b'"{label("oneline-summary.desc", desc|firstline)}"'
1280 1280 )
1281 1281 text = rendertemplate(ctx, spec)
1282 1282 return text.split(b'\n')[0]
1283 1283
1284 1284
1285 1285 def _buildfntemplate(pat, total=None, seqno=None, revwidth=None, pathname=None):
1286 1286 r"""Convert old-style filename format string to template string
1287 1287
1288 1288 >>> _buildfntemplate(b'foo-%b-%n.patch', seqno=0)
1289 1289 'foo-{reporoot|basename}-{seqno}.patch'
1290 1290 >>> _buildfntemplate(b'%R{tags % "{tag}"}%H')
1291 1291 '{rev}{tags % "{tag}"}{node}'
1292 1292
1293 1293 '\' in outermost strings has to be escaped because it is a directory
1294 1294 separator on Windows:
1295 1295
1296 1296 >>> _buildfntemplate(b'c:\\tmp\\%R\\%n.patch', seqno=0)
1297 1297 'c:\\\\tmp\\\\{rev}\\\\{seqno}.patch'
1298 1298 >>> _buildfntemplate(b'\\\\foo\\bar.patch')
1299 1299 '\\\\\\\\foo\\\\bar.patch'
1300 1300 >>> _buildfntemplate(b'\\{tags % "{tag}"}')
1301 1301 '\\\\{tags % "{tag}"}'
1302 1302
1303 1303 but inner strings follow the template rules (i.e. '\' is taken as an
1304 1304 escape character):
1305 1305
1306 1306 >>> _buildfntemplate(br'{"c:\tmp"}', seqno=0)
1307 1307 '{"c:\\tmp"}'
1308 1308 """
1309 1309 expander = {
1310 1310 b'H': b'{node}',
1311 1311 b'R': b'{rev}',
1312 1312 b'h': b'{node|short}',
1313 1313 b'm': br'{sub(r"[^\w]", "_", desc|firstline)}',
1314 1314 b'r': b'{if(revwidth, pad(rev, revwidth, "0", left=True), rev)}',
1315 1315 b'%': b'%',
1316 1316 b'b': b'{reporoot|basename}',
1317 1317 }
1318 1318 if total is not None:
1319 1319 expander[b'N'] = b'{total}'
1320 1320 if seqno is not None:
1321 1321 expander[b'n'] = b'{seqno}'
1322 1322 if total is not None and seqno is not None:
1323 1323 expander[b'n'] = b'{pad(seqno, total|stringify|count, "0", left=True)}'
1324 1324 if pathname is not None:
1325 1325 expander[b's'] = b'{pathname|basename}'
1326 1326 expander[b'd'] = b'{if(pathname|dirname, pathname|dirname, ".")}'
1327 1327 expander[b'p'] = b'{pathname}'
1328 1328
1329 1329 newname = []
1330 1330 for typ, start, end in templater.scantemplate(pat, raw=True):
1331 1331 if typ != b'string':
1332 1332 newname.append(pat[start:end])
1333 1333 continue
1334 1334 i = start
1335 1335 while i < end:
1336 1336 n = pat.find(b'%', i, end)
1337 1337 if n < 0:
1338 1338 newname.append(stringutil.escapestr(pat[i:end]))
1339 1339 break
1340 1340 newname.append(stringutil.escapestr(pat[i:n]))
1341 1341 if n + 2 > end:
1342 1342 raise error.Abort(
1343 1343 _(b"incomplete format spec in output filename")
1344 1344 )
1345 1345 c = pat[n + 1 : n + 2]
1346 1346 i = n + 2
1347 1347 try:
1348 1348 newname.append(expander[c])
1349 1349 except KeyError:
1350 1350 raise error.Abort(
1351 1351 _(b"invalid format spec '%%%s' in output filename") % c
1352 1352 )
1353 1353 return b''.join(newname)
1354 1354
1355 1355
1356 1356 def makefilename(ctx, pat, **props):
1357 1357 if not pat:
1358 1358 return pat
1359 1359 tmpl = _buildfntemplate(pat, **props)
1360 1360 # BUG: alias expansion shouldn't be made against template fragments
1361 1361 # rewritten from %-format strings, but we have no easy way to partially
1362 1362 # disable the expansion.
1363 1363 return rendertemplate(ctx, tmpl, pycompat.byteskwargs(props))
1364 1364
1365 1365
1366 1366 def isstdiofilename(pat):
1367 1367 """True if the given pat looks like a filename denoting stdin/stdout"""
1368 1368 return not pat or pat == b'-'
1369 1369
1370 1370
1371 1371 class _unclosablefile:
1372 1372 def __init__(self, fp):
1373 1373 self._fp = fp
1374 1374
1375 1375 def close(self):
1376 1376 pass
1377 1377
1378 1378 def __iter__(self):
1379 1379 return iter(self._fp)
1380 1380
1381 1381 def __getattr__(self, attr):
1382 1382 return getattr(self._fp, attr)
1383 1383
1384 1384 def __enter__(self):
1385 1385 return self
1386 1386
1387 1387 def __exit__(self, exc_type, exc_value, exc_tb):
1388 1388 pass
1389 1389
1390 1390
1391 1391 def makefileobj(ctx, pat, mode=b'wb', **props):
1392 1392 writable = mode not in (b'r', b'rb')
1393 1393
1394 1394 if isstdiofilename(pat):
1395 1395 repo = ctx.repo()
1396 1396 if writable:
1397 1397 fp = repo.ui.fout
1398 1398 else:
1399 1399 fp = repo.ui.fin
1400 1400 return _unclosablefile(fp)
1401 1401 fn = makefilename(ctx, pat, **props)
1402 1402 return open(fn, mode)
1403 1403
1404 1404
1405 1405 def openstorage(repo, cmd, file_, opts, returnrevlog=False):
1406 1406 """opens the changelog, manifest, a filelog or a given revlog"""
1407 1407 cl = opts[b'changelog']
1408 1408 mf = opts[b'manifest']
1409 1409 dir = opts[b'dir']
1410 1410 msg = None
1411 1411 if cl and mf:
1412 1412 msg = _(b'cannot specify --changelog and --manifest at the same time')
1413 1413 elif cl and dir:
1414 1414 msg = _(b'cannot specify --changelog and --dir at the same time')
1415 1415 elif cl or mf or dir:
1416 1416 if file_:
1417 1417 msg = _(b'cannot specify filename with --changelog or --manifest')
1418 1418 elif not repo:
1419 1419 msg = _(
1420 1420 b'cannot specify --changelog or --manifest or --dir '
1421 1421 b'without a repository'
1422 1422 )
1423 1423 if msg:
1424 1424 raise error.InputError(msg)
1425 1425
1426 1426 r = None
1427 1427 if repo:
1428 1428 if cl:
1429 1429 r = repo.unfiltered().changelog
1430 1430 elif dir:
1431 1431 if not scmutil.istreemanifest(repo):
1432 1432 raise error.InputError(
1433 1433 _(
1434 1434 b"--dir can only be used on repos with "
1435 1435 b"treemanifest enabled"
1436 1436 )
1437 1437 )
1438 1438 if not dir.endswith(b'/'):
1439 1439 dir = dir + b'/'
1440 1440 dirlog = repo.manifestlog.getstorage(dir)
1441 1441 if len(dirlog):
1442 1442 r = dirlog
1443 1443 elif mf:
1444 1444 r = repo.manifestlog.getstorage(b'')
1445 1445 elif file_:
1446 1446 filelog = repo.file(file_)
1447 1447 if len(filelog):
1448 1448 r = filelog
1449 1449
1450 1450 # Not all storage may be revlogs. If requested, try to return an actual
1451 1451 # revlog instance.
1452 1452 if returnrevlog:
1453 1453 if isinstance(r, revlog.revlog):
1454 1454 pass
1455 1455 elif hasattr(r, '_revlog'):
1456 1456 r = r._revlog # pytype: disable=attribute-error
1457 1457 elif r is not None:
1458 1458 raise error.InputError(
1459 1459 _(b'%r does not appear to be a revlog') % r
1460 1460 )
1461 1461
1462 1462 if not r:
1463 1463 if not returnrevlog:
1464 1464 raise error.InputError(_(b'cannot give path to non-revlog'))
1465 1465
1466 1466 if not file_:
1467 1467 raise error.CommandError(cmd, _(b'invalid arguments'))
1468 1468 if not os.path.isfile(file_):
1469 1469 raise error.InputError(_(b"revlog '%s' not found") % file_)
1470 1470
1471 1471 target = (revlog_constants.KIND_OTHER, b'free-form:%s' % file_)
1472 1472 r = revlog.revlog(
1473 1473 vfsmod.vfs(encoding.getcwd(), audit=False),
1474 1474 target=target,
1475 1475 radix=file_[:-2],
1476 1476 )
1477 1477 return r
1478 1478
1479 1479
1480 1480 def openrevlog(repo, cmd, file_, opts):
1481 1481 """Obtain a revlog backing storage of an item.
1482 1482
1483 1483 This is similar to ``openstorage()`` except it always returns a revlog.
1484 1484
1485 1485 In most cases, a caller cares about the main storage object - not the
1486 1486 revlog backing it. Therefore, this function should only be used by code
1487 1487 that needs to examine low-level revlog implementation details. e.g. debug
1488 1488 commands.
1489 1489 """
1490 1490 return openstorage(repo, cmd, file_, opts, returnrevlog=True)
1491 1491
1492 1492
1493 1493 def copy(ui, repo, pats, opts: Dict[bytes, Any], rename=False):
1494 1494 check_incompatible_arguments(opts, b'forget', [b'dry_run'])
1495 1495
1496 1496 # called with the repo lock held
1497 1497 #
1498 1498 # hgsep => pathname that uses "/" to separate directories
1499 1499 # ossep => pathname that uses os.sep to separate directories
1500 1500 cwd = repo.getcwd()
1501 1501 targets = {}
1502 1502 forget = opts.get(b"forget")
1503 1503 after = opts.get(b"after")
1504 1504 dryrun = opts.get(b"dry_run")
1505 1505 rev = opts.get(b'at_rev')
1506 1506 if rev:
1507 1507 if not forget and not after:
1508 1508 # TODO: Remove this restriction and make it also create the copy
1509 1509 # targets (and remove the rename source if rename==True).
1510 1510 raise error.InputError(_(b'--at-rev requires --after'))
1511 1511 ctx = logcmdutil.revsingle(repo, rev)
1512 1512 if len(ctx.parents()) > 1:
1513 1513 raise error.InputError(
1514 1514 _(b'cannot mark/unmark copy in merge commit')
1515 1515 )
1516 1516 else:
1517 1517 ctx = repo[None]
1518 1518
1519 1519 pctx = ctx.p1()
1520 1520
1521 1521 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
1522 1522
1523 1523 if forget:
1524 1524 if ctx.rev() is None:
1525 1525 new_ctx = ctx
1526 1526 else:
1527 1527 if len(ctx.parents()) > 1:
1528 1528 raise error.InputError(_(b'cannot unmark copy in merge commit'))
1529 1529 # avoid cycle context -> subrepo -> cmdutil
1530 1530 from . import context
1531 1531
1532 1532 rewriteutil.precheck(repo, [ctx.rev()], b'uncopy')
1533 1533 new_ctx = context.overlayworkingctx(repo)
1534 1534 new_ctx.setbase(ctx.p1())
1535 1535 mergemod.graft(repo, ctx, wctx=new_ctx)
1536 1536
1537 1537 match = scmutil.match(ctx, pats, opts)
1538 1538
1539 1539 current_copies = ctx.p1copies()
1540 1540 current_copies.update(ctx.p2copies())
1541 1541
1542 1542 uipathfn = scmutil.getuipathfn(repo)
1543 1543 for f in ctx.walk(match):
1544 1544 if f in current_copies:
1545 1545 new_ctx[f].markcopied(None)
1546 1546 elif match.exact(f):
1547 1547 ui.warn(
1548 1548 _(
1549 1549 b'%s: not unmarking as copy - file is not marked as copied\n'
1550 1550 )
1551 1551 % uipathfn(f)
1552 1552 )
1553 1553
1554 1554 if ctx.rev() is not None:
1555 1555 with repo.lock():
1556 1556 mem_ctx = new_ctx.tomemctx_for_amend(ctx)
1557 1557 new_node = mem_ctx.commit()
1558 1558
1559 1559 if repo.dirstate.p1() == ctx.node():
1560 1560 with repo.dirstate.changing_parents(repo):
1561 1561 scmutil.movedirstate(repo, repo[new_node])
1562 1562 replacements = {ctx.node(): [new_node]}
1563 1563 scmutil.cleanupnodes(
1564 1564 repo, replacements, b'uncopy', fixphase=True
1565 1565 )
1566 1566
1567 1567 return
1568 1568
1569 1569 pats = scmutil.expandpats(pats)
1570 1570 if not pats:
1571 1571 raise error.InputError(_(b'no source or destination specified'))
1572 1572 if len(pats) == 1:
1573 1573 raise error.InputError(_(b'no destination specified'))
1574 1574 dest = pats.pop()
1575 1575
1576 1576 def walkpat(pat):
1577 1577 srcs = []
1578 1578 # TODO: Inline and simplify the non-working-copy version of this code
1579 1579 # since it shares very little with the working-copy version of it.
1580 1580 ctx_to_walk = ctx if ctx.rev() is None else pctx
1581 1581 m = scmutil.match(ctx_to_walk, [pat], opts, globbed=True)
1582 1582 for abs in ctx_to_walk.walk(m):
1583 1583 rel = uipathfn(abs)
1584 1584 exact = m.exact(abs)
1585 1585 if abs not in ctx:
1586 1586 if abs in pctx:
1587 1587 if not after:
1588 1588 if exact:
1589 1589 ui.warn(
1590 1590 _(
1591 1591 b'%s: not copying - file has been marked '
1592 1592 b'for remove\n'
1593 1593 )
1594 1594 % rel
1595 1595 )
1596 1596 continue
1597 1597 else:
1598 1598 if exact:
1599 1599 ui.warn(
1600 1600 _(b'%s: not copying - file is not managed\n') % rel
1601 1601 )
1602 1602 continue
1603 1603
1604 1604 # abs: hgsep
1605 1605 # rel: ossep
1606 1606 srcs.append((abs, rel, exact))
1607 1607 return srcs
1608 1608
1609 1609 if ctx.rev() is not None:
1610 1610 rewriteutil.precheck(repo, [ctx.rev()], b'uncopy')
1611 1611 absdest = pathutil.canonpath(repo.root, cwd, dest)
1612 1612 if ctx.hasdir(absdest):
1613 1613 raise error.InputError(
1614 1614 _(b'%s: --at-rev does not support a directory as destination')
1615 1615 % uipathfn(absdest)
1616 1616 )
1617 1617 if absdest not in ctx:
1618 1618 raise error.InputError(
1619 1619 _(b'%s: copy destination does not exist in %s')
1620 1620 % (uipathfn(absdest), ctx)
1621 1621 )
1622 1622
1623 1623 # avoid cycle context -> subrepo -> cmdutil
1624 1624 from . import context
1625 1625
1626 1626 copylist = []
1627 1627 for pat in pats:
1628 1628 srcs = walkpat(pat)
1629 1629 if not srcs:
1630 1630 continue
1631 1631 for abs, rel, exact in srcs:
1632 1632 copylist.append(abs)
1633 1633
1634 1634 if not copylist:
1635 1635 raise error.InputError(_(b'no files to copy'))
1636 1636 # TODO: Add support for `hg cp --at-rev . foo bar dir` and
1637 1637 # `hg cp --at-rev . dir1 dir2`, preferably unifying the code with the
1638 1638 # existing functions below.
1639 1639 if len(copylist) != 1:
1640 1640 raise error.InputError(_(b'--at-rev requires a single source'))
1641 1641
1642 1642 new_ctx = context.overlayworkingctx(repo)
1643 1643 new_ctx.setbase(ctx.p1())
1644 1644 mergemod.graft(repo, ctx, wctx=new_ctx)
1645 1645
1646 1646 new_ctx.markcopied(absdest, copylist[0])
1647 1647
1648 1648 with repo.lock():
1649 1649 mem_ctx = new_ctx.tomemctx_for_amend(ctx)
1650 1650 new_node = mem_ctx.commit()
1651 1651
1652 1652 if repo.dirstate.p1() == ctx.node():
1653 1653 with repo.dirstate.changing_parents(repo):
1654 1654 scmutil.movedirstate(repo, repo[new_node])
1655 1655 replacements = {ctx.node(): [new_node]}
1656 1656 scmutil.cleanupnodes(repo, replacements, b'copy', fixphase=True)
1657 1657
1658 1658 return
1659 1659
1660 1660 # abssrc: hgsep
1661 1661 # relsrc: ossep
1662 1662 # otarget: ossep
1663 1663 def copyfile(abssrc, relsrc, otarget, exact):
1664 1664 abstarget = pathutil.canonpath(repo.root, cwd, otarget)
1665 1665 if b'/' in abstarget:
1666 1666 # We cannot normalize abstarget itself, this would prevent
1667 1667 # case only renames, like a => A.
1668 1668 abspath, absname = abstarget.rsplit(b'/', 1)
1669 1669 abstarget = repo.dirstate.normalize(abspath) + b'/' + absname
1670 1670 reltarget = repo.pathto(abstarget, cwd)
1671 1671 target = repo.wjoin(abstarget)
1672 1672 src = repo.wjoin(abssrc)
1673 1673 entry = repo.dirstate.get_entry(abstarget)
1674 1674
1675 1675 already_commited = entry.tracked and not entry.added
1676 1676
1677 1677 scmutil.checkportable(ui, abstarget)
1678 1678
1679 1679 # check for collisions
1680 1680 prevsrc = targets.get(abstarget)
1681 1681 if prevsrc is not None:
1682 1682 ui.warn(
1683 1683 _(b'%s: not overwriting - %s collides with %s\n')
1684 1684 % (
1685 1685 reltarget,
1686 1686 repo.pathto(abssrc, cwd),
1687 1687 repo.pathto(prevsrc, cwd),
1688 1688 )
1689 1689 )
1690 1690 return True # report a failure
1691 1691
1692 1692 # check for overwrites
1693 1693 exists = os.path.lexists(target)
1694 1694 samefile = False
1695 1695 if exists and abssrc != abstarget:
1696 1696 if repo.dirstate.normalize(abssrc) == repo.dirstate.normalize(
1697 1697 abstarget
1698 1698 ):
1699 1699 if not rename:
1700 1700 ui.warn(_(b"%s: can't copy - same file\n") % reltarget)
1701 1701 return True # report a failure
1702 1702 exists = False
1703 1703 samefile = True
1704 1704
1705 1705 if not after and exists or after and already_commited:
1706 1706 if not opts[b'force']:
1707 1707 if already_commited:
1708 1708 msg = _(b'%s: not overwriting - file already committed\n')
1709 1709 # Check if if the target was added in the parent and the
1710 1710 # source already existed in the grandparent.
1711 1711 looks_like_copy_in_pctx = abstarget in pctx and any(
1712 1712 abssrc in gpctx and abstarget not in gpctx
1713 1713 for gpctx in pctx.parents()
1714 1714 )
1715 1715 if looks_like_copy_in_pctx:
1716 1716 if rename:
1717 1717 hint = _(
1718 1718 b"('hg rename --at-rev .' to record the rename "
1719 1719 b"in the parent of the working copy)\n"
1720 1720 )
1721 1721 else:
1722 1722 hint = _(
1723 1723 b"('hg copy --at-rev .' to record the copy in "
1724 1724 b"the parent of the working copy)\n"
1725 1725 )
1726 1726 else:
1727 1727 if after:
1728 1728 flags = b'--after --force'
1729 1729 else:
1730 1730 flags = b'--force'
1731 1731 if rename:
1732 1732 hint = (
1733 1733 _(
1734 1734 b"('hg rename %s' to replace the file by "
1735 1735 b'recording a rename)\n'
1736 1736 )
1737 1737 % flags
1738 1738 )
1739 1739 else:
1740 1740 hint = (
1741 1741 _(
1742 1742 b"('hg copy %s' to replace the file by "
1743 1743 b'recording a copy)\n'
1744 1744 )
1745 1745 % flags
1746 1746 )
1747 1747 else:
1748 1748 msg = _(b'%s: not overwriting - file exists\n')
1749 1749 if rename:
1750 1750 hint = _(
1751 1751 b"('hg rename --after' to record the rename)\n"
1752 1752 )
1753 1753 else:
1754 1754 hint = _(b"('hg copy --after' to record the copy)\n")
1755 1755 ui.warn(msg % reltarget)
1756 1756 ui.warn(hint)
1757 1757 return True # report a failure
1758 1758
1759 1759 if after:
1760 1760 if not exists:
1761 1761 if rename:
1762 1762 ui.warn(
1763 1763 _(b'%s: not recording move - %s does not exist\n')
1764 1764 % (relsrc, reltarget)
1765 1765 )
1766 1766 else:
1767 1767 ui.warn(
1768 1768 _(b'%s: not recording copy - %s does not exist\n')
1769 1769 % (relsrc, reltarget)
1770 1770 )
1771 1771 return True # report a failure
1772 1772 elif not dryrun:
1773 1773 try:
1774 1774 if exists:
1775 1775 os.unlink(target)
1776 1776 targetdir = os.path.dirname(target) or b'.'
1777 1777 if not os.path.isdir(targetdir):
1778 1778 os.makedirs(targetdir)
1779 1779 if samefile:
1780 1780 tmp = target + b"~hgrename"
1781 1781 os.rename(src, tmp)
1782 1782 os.rename(tmp, target)
1783 1783 else:
1784 1784 # Preserve stat info on renames, not on copies; this matches
1785 1785 # Linux CLI behavior.
1786 1786 util.copyfile(src, target, copystat=rename)
1787 1787 srcexists = True
1788 1788 except IOError as inst:
1789 1789 if inst.errno == errno.ENOENT:
1790 1790 ui.warn(_(b'%s: deleted in working directory\n') % relsrc)
1791 1791 srcexists = False
1792 1792 else:
1793 1793 ui.warn(
1794 1794 _(b'%s: cannot copy - %s\n')
1795 1795 % (relsrc, encoding.strtolocal(inst.strerror))
1796 1796 )
1797 1797 return True # report a failure
1798 1798
1799 1799 if ui.verbose or not exact:
1800 1800 if rename:
1801 1801 ui.status(_(b'moving %s to %s\n') % (relsrc, reltarget))
1802 1802 else:
1803 1803 ui.status(_(b'copying %s to %s\n') % (relsrc, reltarget))
1804 1804
1805 1805 targets[abstarget] = abssrc
1806 1806
1807 1807 # fix up dirstate
1808 1808 scmutil.dirstatecopy(
1809 1809 ui, repo, ctx, abssrc, abstarget, dryrun=dryrun, cwd=cwd
1810 1810 )
1811 1811 if rename and not dryrun:
1812 1812 if not after and srcexists and not samefile:
1813 1813 rmdir = repo.ui.configbool(b'experimental', b'removeemptydirs')
1814 1814 repo.wvfs.unlinkpath(abssrc, rmdir=rmdir)
1815 1815 ctx.forget([abssrc])
1816 1816
1817 1817 # pat: ossep
1818 1818 # dest ossep
1819 1819 # srcs: list of (hgsep, hgsep, ossep, bool)
1820 1820 # return: function that takes hgsep and returns ossep
1821 1821 def targetpathfn(pat, dest, srcs):
1822 1822 if os.path.isdir(pat):
1823 1823 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1824 1824 abspfx = util.localpath(abspfx)
1825 1825 if destdirexists:
1826 1826 striplen = len(os.path.split(abspfx)[0])
1827 1827 else:
1828 1828 striplen = len(abspfx)
1829 1829 if striplen:
1830 1830 striplen += len(pycompat.ossep)
1831 1831 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
1832 1832 elif destdirexists:
1833 1833 res = lambda p: os.path.join(
1834 1834 dest, os.path.basename(util.localpath(p))
1835 1835 )
1836 1836 else:
1837 1837 res = lambda p: dest
1838 1838 return res
1839 1839
1840 1840 # pat: ossep
1841 1841 # dest ossep
1842 1842 # srcs: list of (hgsep, hgsep, ossep, bool)
1843 1843 # return: function that takes hgsep and returns ossep
1844 1844 def targetpathafterfn(pat, dest, srcs):
1845 1845 if matchmod.patkind(pat):
1846 1846 # a mercurial pattern
1847 1847 res = lambda p: os.path.join(
1848 1848 dest, os.path.basename(util.localpath(p))
1849 1849 )
1850 1850 else:
1851 1851 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1852 1852 if len(abspfx) < len(srcs[0][0]):
1853 1853 # A directory. Either the target path contains the last
1854 1854 # component of the source path or it does not.
1855 1855 def evalpath(striplen):
1856 1856 score = 0
1857 1857 for s in srcs:
1858 1858 t = os.path.join(dest, util.localpath(s[0])[striplen:])
1859 1859 if os.path.lexists(t):
1860 1860 score += 1
1861 1861 return score
1862 1862
1863 1863 abspfx = util.localpath(abspfx)
1864 1864 striplen = len(abspfx)
1865 1865 if striplen:
1866 1866 striplen += len(pycompat.ossep)
1867 1867 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
1868 1868 score = evalpath(striplen)
1869 1869 striplen1 = len(os.path.split(abspfx)[0])
1870 1870 if striplen1:
1871 1871 striplen1 += len(pycompat.ossep)
1872 1872 if evalpath(striplen1) > score:
1873 1873 striplen = striplen1
1874 1874 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
1875 1875 else:
1876 1876 # a file
1877 1877 if destdirexists:
1878 1878 res = lambda p: os.path.join(
1879 1879 dest, os.path.basename(util.localpath(p))
1880 1880 )
1881 1881 else:
1882 1882 res = lambda p: dest
1883 1883 return res
1884 1884
1885 1885 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
1886 1886 if not destdirexists:
1887 1887 if len(pats) > 1 or matchmod.patkind(pats[0]):
1888 1888 raise error.InputError(
1889 1889 _(
1890 1890 b'with multiple sources, destination must be an '
1891 1891 b'existing directory'
1892 1892 )
1893 1893 )
1894 1894 if util.endswithsep(dest):
1895 1895 raise error.InputError(
1896 1896 _(b'destination %s is not a directory') % dest
1897 1897 )
1898 1898
1899 1899 tfn = targetpathfn
1900 1900 if after:
1901 1901 tfn = targetpathafterfn
1902 1902 copylist = []
1903 1903 for pat in pats:
1904 1904 srcs = walkpat(pat)
1905 1905 if not srcs:
1906 1906 continue
1907 1907 copylist.append((tfn(pat, dest, srcs), srcs))
1908 1908 if not copylist:
1909 1909 hint = None
1910 1910 if rename:
1911 1911 hint = _(b'maybe you meant to use --after --at-rev=.')
1912 1912 raise error.InputError(_(b'no files to copy'), hint=hint)
1913 1913
1914 1914 errors = 0
1915 1915 for targetpath, srcs in copylist:
1916 1916 for abssrc, relsrc, exact in srcs:
1917 1917 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
1918 1918 errors += 1
1919 1919
1920 1920 return errors != 0
1921 1921
1922 1922
1923 1923 ## facility to let extension process additional data into an import patch
1924 1924 # list of identifier to be executed in order
1925 1925 extrapreimport = [] # run before commit
1926 1926 extrapostimport = [] # run after commit
1927 1927 # mapping from identifier to actual import function
1928 1928 #
1929 1929 # 'preimport' are run before the commit is made and are provided the following
1930 1930 # arguments:
1931 1931 # - repo: the localrepository instance,
1932 1932 # - patchdata: data extracted from patch header (cf m.patch.patchheadermap),
1933 1933 # - extra: the future extra dictionary of the changeset, please mutate it,
1934 1934 # - opts: the import options.
1935 1935 # XXX ideally, we would just pass an ctx ready to be computed, that would allow
1936 1936 # mutation of in memory commit and more. Feel free to rework the code to get
1937 1937 # there.
1938 1938 extrapreimportmap = {}
1939 1939 # 'postimport' are run after the commit is made and are provided the following
1940 1940 # argument:
1941 1941 # - ctx: the changectx created by import.
1942 1942 extrapostimportmap = {}
1943 1943
1944 1944
1945 1945 def tryimportone(ui, repo, patchdata, parents, opts, msgs, updatefunc):
1946 1946 """Utility function used by commands.import to import a single patch
1947 1947
1948 1948 This function is explicitly defined here to help the evolve extension to
1949 1949 wrap this part of the import logic.
1950 1950
1951 1951 The API is currently a bit ugly because it a simple code translation from
1952 1952 the import command. Feel free to make it better.
1953 1953
1954 1954 :patchdata: a dictionary containing parsed patch data (such as from
1955 1955 ``patch.extract()``)
1956 1956 :parents: nodes that will be parent of the created commit
1957 1957 :opts: the full dict of option passed to the import command
1958 1958 :msgs: list to save commit message to.
1959 1959 (used in case we need to save it when failing)
1960 1960 :updatefunc: a function that update a repo to a given node
1961 1961 updatefunc(<repo>, <node>)
1962 1962 """
1963 1963 # avoid cycle context -> subrepo -> cmdutil
1964 1964 from . import context
1965 1965
1966 1966 tmpname = patchdata.get(b'filename')
1967 1967 message = patchdata.get(b'message')
1968 1968 user = opts.get(b'user') or patchdata.get(b'user')
1969 1969 date = opts.get(b'date') or patchdata.get(b'date')
1970 1970 branch = patchdata.get(b'branch')
1971 1971 nodeid = patchdata.get(b'nodeid')
1972 1972 p1 = patchdata.get(b'p1')
1973 1973 p2 = patchdata.get(b'p2')
1974 1974
1975 1975 nocommit = opts.get(b'no_commit')
1976 1976 importbranch = opts.get(b'import_branch')
1977 1977 update = not opts.get(b'bypass')
1978 1978 strip = opts[b"strip"]
1979 1979 prefix = opts[b"prefix"]
1980 1980 sim = float(opts.get(b'similarity') or 0)
1981 1981
1982 1982 if not tmpname:
1983 1983 return None, None, False
1984 1984
1985 1985 rejects = False
1986 1986
1987 1987 cmdline_message = logmessage(ui, opts)
1988 1988 if cmdline_message:
1989 1989 # pickup the cmdline msg
1990 1990 message = cmdline_message
1991 1991 elif message:
1992 1992 # pickup the patch msg
1993 1993 message = message.strip()
1994 1994 else:
1995 1995 # launch the editor
1996 1996 message = None
1997 1997 ui.debug(b'message:\n%s\n' % (message or b''))
1998 1998
1999 1999 if len(parents) == 1:
2000 2000 parents.append(repo[nullrev])
2001 2001 if opts.get(b'exact'):
2002 2002 if not nodeid or not p1:
2003 2003 raise error.InputError(_(b'not a Mercurial patch'))
2004 2004 p1 = repo[p1]
2005 2005 p2 = repo[p2 or nullrev]
2006 2006 elif p2:
2007 2007 try:
2008 2008 p1 = repo[p1]
2009 2009 p2 = repo[p2]
2010 2010 # Without any options, consider p2 only if the
2011 2011 # patch is being applied on top of the recorded
2012 2012 # first parent.
2013 2013 if p1 != parents[0]:
2014 2014 p1 = parents[0]
2015 2015 p2 = repo[nullrev]
2016 2016 except error.RepoError:
2017 2017 p1, p2 = parents
2018 2018 if p2.rev() == nullrev:
2019 2019 ui.warn(
2020 2020 _(
2021 2021 b"warning: import the patch as a normal revision\n"
2022 2022 b"(use --exact to import the patch as a merge)\n"
2023 2023 )
2024 2024 )
2025 2025 else:
2026 2026 p1, p2 = parents
2027 2027
2028 2028 n = None
2029 2029 if update:
2030 2030 if p1 != parents[0]:
2031 2031 updatefunc(repo, p1.node())
2032 2032 if p2 != parents[1]:
2033 2033 repo.setparents(p1.node(), p2.node())
2034 2034
2035 2035 if opts.get(b'exact') or importbranch:
2036 2036 repo.dirstate.setbranch(
2037 2037 branch or b'default', repo.currenttransaction()
2038 2038 )
2039 2039
2040 2040 partial = opts.get(b'partial', False)
2041 2041 files = set()
2042 2042 try:
2043 2043 patch.patch(
2044 2044 ui,
2045 2045 repo,
2046 2046 tmpname,
2047 2047 strip=strip,
2048 2048 prefix=prefix,
2049 2049 files=files,
2050 2050 eolmode=None,
2051 2051 similarity=sim / 100.0,
2052 2052 )
2053 2053 except error.PatchParseError as e:
2054 2054 raise error.InputError(
2055 2055 pycompat.bytestr(e),
2056 2056 hint=_(
2057 2057 b'check that whitespace in the patch has not been mangled'
2058 2058 ),
2059 2059 )
2060 2060 except error.PatchApplicationError as e:
2061 2061 if not partial:
2062 2062 raise error.StateError(pycompat.bytestr(e))
2063 2063 if partial:
2064 2064 rejects = True
2065 2065
2066 2066 files = list(files)
2067 2067 if nocommit:
2068 2068 if message:
2069 2069 msgs.append(message)
2070 2070 else:
2071 2071 if opts.get(b'exact') or p2:
2072 2072 # If you got here, you either use --force and know what
2073 2073 # you are doing or used --exact or a merge patch while
2074 2074 # being updated to its first parent.
2075 2075 m = None
2076 2076 else:
2077 2077 m = scmutil.matchfiles(repo, files or [])
2078 2078 editform = mergeeditform(repo[None], b'import.normal')
2079 2079 if opts.get(b'exact'):
2080 2080 editor = None
2081 2081 else:
2082 2082 editor = getcommiteditor(
2083 2083 editform=editform, **pycompat.strkwargs(opts)
2084 2084 )
2085 2085 extra = {}
2086 2086 for idfunc in extrapreimport:
2087 2087 extrapreimportmap[idfunc](repo, patchdata, extra, opts)
2088 2088 overrides = {}
2089 2089 if partial:
2090 2090 overrides[(b'ui', b'allowemptycommit')] = True
2091 2091 if opts.get(b'secret'):
2092 2092 overrides[(b'phases', b'new-commit')] = b'secret'
2093 2093 with repo.ui.configoverride(overrides, b'import'):
2094 2094 n = repo.commit(
2095 2095 message, user, date, match=m, editor=editor, extra=extra
2096 2096 )
2097 2097 for idfunc in extrapostimport:
2098 2098 extrapostimportmap[idfunc](repo[n])
2099 2099 else:
2100 2100 if opts.get(b'exact') or importbranch:
2101 2101 branch = branch or b'default'
2102 2102 else:
2103 2103 branch = p1.branch()
2104 2104 store = patch.filestore()
2105 2105 try:
2106 2106 files = set()
2107 2107 try:
2108 2108 patch.patchrepo(
2109 2109 ui,
2110 2110 repo,
2111 2111 p1,
2112 2112 store,
2113 2113 tmpname,
2114 2114 strip,
2115 2115 prefix,
2116 2116 files,
2117 2117 eolmode=None,
2118 2118 )
2119 2119 except error.PatchParseError as e:
2120 2120 raise error.InputError(
2121 2121 stringutil.forcebytestr(e),
2122 2122 hint=_(
2123 2123 b'check that whitespace in the patch has not been mangled'
2124 2124 ),
2125 2125 )
2126 2126 except error.PatchApplicationError as e:
2127 2127 raise error.StateError(stringutil.forcebytestr(e))
2128 2128 if opts.get(b'exact'):
2129 2129 editor = None
2130 2130 else:
2131 2131 editor = getcommiteditor(editform=b'import.bypass')
2132 2132 memctx = context.memctx(
2133 2133 repo,
2134 2134 (p1.node(), p2.node()),
2135 2135 message,
2136 2136 files=files,
2137 2137 filectxfn=store,
2138 2138 user=user,
2139 2139 date=date,
2140 2140 branch=branch,
2141 2141 editor=editor,
2142 2142 )
2143 2143
2144 2144 overrides = {}
2145 2145 if opts.get(b'secret'):
2146 2146 overrides[(b'phases', b'new-commit')] = b'secret'
2147 2147 with repo.ui.configoverride(overrides, b'import'):
2148 2148 n = memctx.commit()
2149 2149 finally:
2150 2150 store.close()
2151 2151 if opts.get(b'exact') and nocommit:
2152 2152 # --exact with --no-commit is still useful in that it does merge
2153 2153 # and branch bits
2154 2154 ui.warn(_(b"warning: can't check exact import with --no-commit\n"))
2155 2155 elif opts.get(b'exact') and (not n or hex(n) != nodeid):
2156 2156 raise error.Abort(_(b'patch is damaged or loses information'))
2157 2157 msg = _(b'applied to working directory')
2158 2158 if n:
2159 2159 # i18n: refers to a short changeset id
2160 2160 msg = _(b'created %s') % short(n)
2161 2161 return msg, n, rejects
2162 2162
2163 2163
2164 2164 # facility to let extensions include additional data in an exported patch
2165 2165 # list of identifiers to be executed in order
2166 2166 extraexport = []
2167 2167 # mapping from identifier to actual export function
2168 2168 # function as to return a string to be added to the header or None
2169 2169 # it is given two arguments (sequencenumber, changectx)
2170 2170 extraexportmap = {}
2171 2171
2172 2172
2173 2173 def _exportsingle(repo, ctx, fm, match, switch_parent, seqno, diffopts):
2174 2174 node = scmutil.binnode(ctx)
2175 2175 parents = [p.node() for p in ctx.parents() if p]
2176 2176 branch = ctx.branch()
2177 2177 if switch_parent:
2178 2178 parents.reverse()
2179 2179
2180 2180 if parents:
2181 2181 prev = parents[0]
2182 2182 else:
2183 2183 prev = repo.nullid
2184 2184
2185 2185 fm.context(ctx=ctx)
2186 2186 fm.plain(b'# HG changeset patch\n')
2187 2187 fm.write(b'user', b'# User %s\n', ctx.user())
2188 2188 fm.plain(b'# Date %d %d\n' % ctx.date())
2189 2189 fm.write(b'date', b'# %s\n', fm.formatdate(ctx.date()))
2190 2190 fm.condwrite(
2191 2191 branch and branch != b'default', b'branch', b'# Branch %s\n', branch
2192 2192 )
2193 2193 fm.write(b'node', b'# Node ID %s\n', hex(node))
2194 2194 fm.plain(b'# Parent %s\n' % hex(prev))
2195 2195 if len(parents) > 1:
2196 2196 fm.plain(b'# Parent %s\n' % hex(parents[1]))
2197 2197 fm.data(parents=fm.formatlist(pycompat.maplist(hex, parents), name=b'node'))
2198 2198
2199 2199 # TODO: redesign extraexportmap function to support formatter
2200 2200 for headerid in extraexport:
2201 2201 header = extraexportmap[headerid](seqno, ctx)
2202 2202 if header is not None:
2203 2203 fm.plain(b'# %s\n' % header)
2204 2204
2205 2205 fm.write(b'desc', b'%s\n', ctx.description().rstrip())
2206 2206 fm.plain(b'\n')
2207 2207
2208 2208 if fm.isplain():
2209 2209 chunkiter = patch.diffui(repo, prev, node, match, opts=diffopts)
2210 2210 for chunk, label in chunkiter:
2211 2211 fm.plain(chunk, label=label)
2212 2212 else:
2213 2213 chunkiter = patch.diff(repo, prev, node, match, opts=diffopts)
2214 2214 # TODO: make it structured?
2215 2215 fm.data(diff=b''.join(chunkiter))
2216 2216
2217 2217
2218 2218 def _exportfile(repo, revs, fm, dest, switch_parent, diffopts, match):
2219 2219 """Export changesets to stdout or a single file"""
2220 2220 for seqno, rev in enumerate(revs, 1):
2221 2221 ctx = repo[rev]
2222 2222 if not dest.startswith(b'<'):
2223 2223 repo.ui.note(b"%s\n" % dest)
2224 2224 fm.startitem()
2225 2225 _exportsingle(repo, ctx, fm, match, switch_parent, seqno, diffopts)
2226 2226
2227 2227
2228 2228 def _exportfntemplate(
2229 2229 repo, revs, basefm, fntemplate, switch_parent, diffopts, match
2230 2230 ):
2231 2231 """Export changesets to possibly multiple files"""
2232 2232 total = len(revs)
2233 2233 revwidth = max(len(str(rev)) for rev in revs)
2234 2234 filemap = util.sortdict() # filename: [(seqno, rev), ...]
2235 2235
2236 2236 for seqno, rev in enumerate(revs, 1):
2237 2237 ctx = repo[rev]
2238 2238 dest = makefilename(
2239 2239 ctx, fntemplate, total=total, seqno=seqno, revwidth=revwidth
2240 2240 )
2241 2241 filemap.setdefault(dest, []).append((seqno, rev))
2242 2242
2243 2243 for dest in filemap:
2244 2244 with formatter.maybereopen(basefm, dest) as fm:
2245 2245 repo.ui.note(b"%s\n" % dest)
2246 2246 for seqno, rev in filemap[dest]:
2247 2247 fm.startitem()
2248 2248 ctx = repo[rev]
2249 2249 _exportsingle(
2250 2250 repo, ctx, fm, match, switch_parent, seqno, diffopts
2251 2251 )
2252 2252
2253 2253
2254 2254 def _prefetchchangedfiles(repo, revs, match):
2255 2255 allfiles = set()
2256 2256 for rev in revs:
2257 2257 for file in repo[rev].files():
2258 2258 if not match or match(file):
2259 2259 allfiles.add(file)
2260 2260 match = scmutil.matchfiles(repo, allfiles)
2261 2261 revmatches = [(rev, match) for rev in revs]
2262 2262 scmutil.prefetchfiles(repo, revmatches)
2263 2263
2264 2264
2265 2265 def export(
2266 2266 repo,
2267 2267 revs,
2268 2268 basefm,
2269 2269 fntemplate=b'hg-%h.patch',
2270 2270 switch_parent=False,
2271 2271 opts=None,
2272 2272 match=None,
2273 2273 ):
2274 2274 """export changesets as hg patches
2275 2275
2276 2276 Args:
2277 2277 repo: The repository from which we're exporting revisions.
2278 2278 revs: A list of revisions to export as revision numbers.
2279 2279 basefm: A formatter to which patches should be written.
2280 2280 fntemplate: An optional string to use for generating patch file names.
2281 2281 switch_parent: If True, show diffs against second parent when not nullid.
2282 2282 Default is false, which always shows diff against p1.
2283 2283 opts: diff options to use for generating the patch.
2284 2284 match: If specified, only export changes to files matching this matcher.
2285 2285
2286 2286 Returns:
2287 2287 Nothing.
2288 2288
2289 2289 Side Effect:
2290 2290 "HG Changeset Patch" data is emitted to one of the following
2291 2291 destinations:
2292 2292 fntemplate specified: Each rev is written to a unique file named using
2293 2293 the given template.
2294 2294 Otherwise: All revs will be written to basefm.
2295 2295 """
2296 2296 _prefetchchangedfiles(repo, revs, match)
2297 2297
2298 2298 if not fntemplate:
2299 2299 _exportfile(
2300 2300 repo, revs, basefm, b'<unnamed>', switch_parent, opts, match
2301 2301 )
2302 2302 else:
2303 2303 _exportfntemplate(
2304 2304 repo, revs, basefm, fntemplate, switch_parent, opts, match
2305 2305 )
2306 2306
2307 2307
2308 2308 def exportfile(repo, revs, fp, switch_parent=False, opts=None, match=None):
2309 2309 """Export changesets to the given file stream"""
2310 2310 _prefetchchangedfiles(repo, revs, match)
2311 2311
2312 2312 dest = getattr(fp, 'name', b'<unnamed>')
2313 2313 with formatter.formatter(repo.ui, fp, b'export', {}) as fm:
2314 2314 _exportfile(repo, revs, fm, dest, switch_parent, opts, match)
2315 2315
2316 2316
2317 2317 def showmarker(fm, marker, index=None):
2318 2318 """utility function to display obsolescence marker in a readable way
2319 2319
2320 2320 To be used by debug function."""
2321 2321 if index is not None:
2322 2322 fm.write(b'index', b'%i ', index)
2323 2323 fm.write(b'prednode', b'%s ', hex(marker.prednode()))
2324 2324 succs = marker.succnodes()
2325 2325 fm.condwrite(
2326 2326 succs,
2327 2327 b'succnodes',
2328 2328 b'%s ',
2329 2329 fm.formatlist(map(hex, succs), name=b'node'),
2330 2330 )
2331 2331 fm.write(b'flag', b'%X ', marker.flags())
2332 2332 parents = marker.parentnodes()
2333 2333 if parents is not None:
2334 2334 fm.write(
2335 2335 b'parentnodes',
2336 2336 b'{%s} ',
2337 2337 fm.formatlist(map(hex, parents), name=b'node', sep=b', '),
2338 2338 )
2339 2339 fm.write(b'date', b'(%s) ', fm.formatdate(marker.date()))
2340 2340 meta = marker.metadata().copy()
2341 2341 meta.pop(b'date', None)
2342 2342 smeta = pycompat.rapply(pycompat.maybebytestr, meta)
2343 2343 fm.write(
2344 2344 b'metadata', b'{%s}', fm.formatdict(smeta, fmt=b'%r: %r', sep=b', ')
2345 2345 )
2346 2346 fm.plain(b'\n')
2347 2347
2348 2348
2349 2349 def finddate(ui, repo, date):
2350 2350 """Find the tipmost changeset that matches the given date spec"""
2351 2351 mrevs = repo.revs(b'date(%s)', date)
2352 2352 try:
2353 2353 rev = mrevs.max()
2354 2354 except ValueError:
2355 2355 raise error.InputError(_(b"revision matching date not found"))
2356 2356
2357 2357 ui.status(
2358 2358 _(b"found revision %d from %s\n")
2359 2359 % (rev, dateutil.datestr(repo[rev].date()))
2360 2360 )
2361 2361 return b'%d' % rev
2362 2362
2363 2363
2364 2364 def add(ui, repo, match, prefix, uipathfn, explicitonly, **opts):
2365 2365 bad = []
2366 2366
2367 2367 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2368 2368 names = []
2369 2369 wctx = repo[None]
2370 2370 cca = None
2371 2371 abort, warn = scmutil.checkportabilityalert(ui)
2372 2372 if abort or warn:
2373 2373 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
2374 2374
2375 2375 match = repo.narrowmatch(match, includeexact=True)
2376 2376 badmatch = matchmod.badmatch(match, badfn)
2377 2377 dirstate = repo.dirstate
2378 2378 # We don't want to just call wctx.walk here, since it would return a lot of
2379 2379 # clean files, which we aren't interested in and takes time.
2380 2380 for f in sorted(
2381 2381 dirstate.walk(
2382 2382 badmatch,
2383 2383 subrepos=sorted(wctx.substate),
2384 2384 unknown=True,
2385 2385 ignored=False,
2386 2386 full=False,
2387 2387 )
2388 2388 ):
2389 2389 entry = dirstate.get_entry(f)
2390 2390 # We don't want to even attmpt to add back files that have been removed
2391 2391 # It would lead to a misleading message saying we're adding the path,
2392 2392 # and can also lead to file/dir conflicts when attempting to add it.
2393 2393 removed = entry and entry.removed
2394 2394 exact = match.exact(f)
2395 2395 if (
2396 2396 exact
2397 2397 or not explicitonly
2398 2398 and f not in wctx
2399 2399 and repo.wvfs.lexists(f)
2400 2400 and not removed
2401 2401 ):
2402 2402 if cca:
2403 2403 cca(f)
2404 2404 names.append(f)
2405 2405 if ui.verbose or not exact:
2406 2406 ui.status(
2407 2407 _(b'adding %s\n') % uipathfn(f), label=b'ui.addremove.added'
2408 2408 )
2409 2409
2410 2410 for subpath in sorted(wctx.substate):
2411 2411 sub = wctx.sub(subpath)
2412 2412 try:
2413 2413 submatch = matchmod.subdirmatcher(subpath, match)
2414 2414 subprefix = repo.wvfs.reljoin(prefix, subpath)
2415 2415 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2416 2416 if opts.get('subrepos'):
2417 2417 bad.extend(
2418 2418 sub.add(ui, submatch, subprefix, subuipathfn, False, **opts)
2419 2419 )
2420 2420 else:
2421 2421 bad.extend(
2422 2422 sub.add(ui, submatch, subprefix, subuipathfn, True, **opts)
2423 2423 )
2424 2424 except error.LookupError:
2425 2425 ui.status(
2426 2426 _(b"skipping missing subrepository: %s\n") % uipathfn(subpath)
2427 2427 )
2428 2428
2429 2429 if not opts.get('dry_run'):
2430 2430 rejected = wctx.add(names, prefix)
2431 2431 bad.extend(f for f in rejected if f in match.files())
2432 2432 return bad
2433 2433
2434 2434
2435 2435 def addwebdirpath(repo, serverpath, webconf):
2436 2436 webconf[serverpath] = repo.root
2437 2437 repo.ui.debug(b'adding %s = %s\n' % (serverpath, repo.root))
2438 2438
2439 2439 for r in repo.revs(b'filelog("path:.hgsub")'):
2440 2440 ctx = repo[r]
2441 2441 for subpath in ctx.substate:
2442 2442 ctx.sub(subpath).addwebdirpath(serverpath, webconf)
2443 2443
2444 2444
2445 2445 def forget(
2446 2446 ui, repo, match, prefix, uipathfn, explicitonly, dryrun, interactive
2447 2447 ):
2448 2448 if dryrun and interactive:
2449 2449 raise error.InputError(
2450 2450 _(b"cannot specify both --dry-run and --interactive")
2451 2451 )
2452 2452 bad = []
2453 2453 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2454 2454 wctx = repo[None]
2455 2455 forgot = []
2456 2456
2457 2457 s = repo.status(match=matchmod.badmatch(match, badfn), clean=True)
2458 2458 forget = sorted(s.modified + s.added + s.deleted + s.clean)
2459 2459 if explicitonly:
2460 2460 forget = [f for f in forget if match.exact(f)]
2461 2461
2462 2462 for subpath in sorted(wctx.substate):
2463 2463 sub = wctx.sub(subpath)
2464 2464 submatch = matchmod.subdirmatcher(subpath, match)
2465 2465 subprefix = repo.wvfs.reljoin(prefix, subpath)
2466 2466 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2467 2467 try:
2468 2468 subbad, subforgot = sub.forget(
2469 2469 submatch,
2470 2470 subprefix,
2471 2471 subuipathfn,
2472 2472 dryrun=dryrun,
2473 2473 interactive=interactive,
2474 2474 )
2475 2475 bad.extend([subpath + b'/' + f for f in subbad])
2476 2476 forgot.extend([subpath + b'/' + f for f in subforgot])
2477 2477 except error.LookupError:
2478 2478 ui.status(
2479 2479 _(b"skipping missing subrepository: %s\n") % uipathfn(subpath)
2480 2480 )
2481 2481
2482 2482 if not explicitonly:
2483 2483 for f in match.files():
2484 2484 if f not in repo.dirstate and not repo.wvfs.isdir(f):
2485 2485 if f not in forgot:
2486 2486 if repo.wvfs.exists(f):
2487 2487 # Don't complain if the exact case match wasn't given.
2488 2488 # But don't do this until after checking 'forgot', so
2489 2489 # that subrepo files aren't normalized, and this op is
2490 2490 # purely from data cached by the status walk above.
2491 2491 if repo.dirstate.normalize(f) in repo.dirstate:
2492 2492 continue
2493 2493 ui.warn(
2494 2494 _(
2495 2495 b'not removing %s: '
2496 2496 b'file is already untracked\n'
2497 2497 )
2498 2498 % uipathfn(f)
2499 2499 )
2500 2500 bad.append(f)
2501 2501
2502 2502 if interactive:
2503 2503 responses = _(
2504 2504 b'[Ynsa?]'
2505 2505 b'$$ &Yes, forget this file'
2506 2506 b'$$ &No, skip this file'
2507 2507 b'$$ &Skip remaining files'
2508 2508 b'$$ Include &all remaining files'
2509 2509 b'$$ &? (display help)'
2510 2510 )
2511 2511 for filename in forget[:]:
2512 2512 r = ui.promptchoice(
2513 2513 _(b'forget %s %s') % (uipathfn(filename), responses)
2514 2514 )
2515 2515 if r == 4: # ?
2516 2516 while r == 4:
2517 2517 for c, t in ui.extractchoices(responses)[1]:
2518 2518 ui.write(b'%s - %s\n' % (c, encoding.lower(t)))
2519 2519 r = ui.promptchoice(
2520 2520 _(b'forget %s %s') % (uipathfn(filename), responses)
2521 2521 )
2522 2522 if r == 0: # yes
2523 2523 continue
2524 2524 elif r == 1: # no
2525 2525 forget.remove(filename)
2526 2526 elif r == 2: # Skip
2527 2527 fnindex = forget.index(filename)
2528 2528 del forget[fnindex:]
2529 2529 break
2530 2530 elif r == 3: # All
2531 2531 break
2532 2532
2533 2533 for f in forget:
2534 2534 if ui.verbose or not match.exact(f) or interactive:
2535 2535 ui.status(
2536 2536 _(b'removing %s\n') % uipathfn(f), label=b'ui.addremove.removed'
2537 2537 )
2538 2538
2539 2539 if not dryrun:
2540 2540 rejected = wctx.forget(forget, prefix)
2541 2541 bad.extend(f for f in rejected if f in match.files())
2542 2542 forgot.extend(f for f in forget if f not in rejected)
2543 2543 return bad, forgot
2544 2544
2545 2545
2546 2546 def files(ui, ctx, m, uipathfn, fm, fmt, subrepos):
2547 2547 ret = 1
2548 2548
2549 2549 needsfctx = ui.verbose or {b'size', b'flags'} & fm.datahint()
2550 2550 if fm.isplain() and not needsfctx:
2551 2551 # Fast path. The speed-up comes from skipping the formatter, and batching
2552 2552 # calls to ui.write.
2553 2553 buf = []
2554 2554 for f in ctx.matches(m):
2555 2555 buf.append(fmt % uipathfn(f))
2556 2556 if len(buf) > 100:
2557 2557 ui.write(b''.join(buf))
2558 2558 del buf[:]
2559 2559 ret = 0
2560 2560 if buf:
2561 2561 ui.write(b''.join(buf))
2562 2562 else:
2563 2563 for f in ctx.matches(m):
2564 2564 fm.startitem()
2565 2565 fm.context(ctx=ctx)
2566 2566 if needsfctx:
2567 2567 fc = ctx[f]
2568 2568 fm.write(b'size flags', b'% 10d % 1s ', fc.size(), fc.flags())
2569 2569 fm.data(path=f)
2570 2570 fm.plain(fmt % uipathfn(f))
2571 2571 ret = 0
2572 2572
2573 2573 for subpath in sorted(ctx.substate):
2574 2574 submatch = matchmod.subdirmatcher(subpath, m)
2575 2575 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2576 2576 if subrepos or m.exact(subpath) or any(submatch.files()):
2577 2577 sub = ctx.sub(subpath)
2578 2578 try:
2579 2579 recurse = m.exact(subpath) or subrepos
2580 2580 if (
2581 2581 sub.printfiles(ui, submatch, subuipathfn, fm, fmt, recurse)
2582 2582 == 0
2583 2583 ):
2584 2584 ret = 0
2585 2585 except error.LookupError:
2586 2586 ui.status(
2587 2587 _(b"skipping missing subrepository: %s\n")
2588 2588 % uipathfn(subpath)
2589 2589 )
2590 2590
2591 2591 return ret
2592 2592
2593 2593
2594 2594 def remove(
2595 2595 ui, repo, m, prefix, uipathfn, after, force, subrepos, dryrun, warnings=None
2596 2596 ):
2597 2597 ret = 0
2598 2598 s = repo.status(match=m, clean=True)
2599 2599 modified, added, deleted, clean = s.modified, s.added, s.deleted, s.clean
2600 2600
2601 2601 wctx = repo[None]
2602 2602
2603 2603 if warnings is None:
2604 2604 warnings = []
2605 2605 warn = True
2606 2606 else:
2607 2607 warn = False
2608 2608
2609 2609 subs = sorted(wctx.substate)
2610 2610 progress = ui.makeprogress(
2611 2611 _(b'searching'), total=len(subs), unit=_(b'subrepos')
2612 2612 )
2613 2613 for subpath in subs:
2614 2614 submatch = matchmod.subdirmatcher(subpath, m)
2615 2615 subprefix = repo.wvfs.reljoin(prefix, subpath)
2616 2616 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2617 2617 if subrepos or m.exact(subpath) or any(submatch.files()):
2618 2618 progress.increment()
2619 2619 sub = wctx.sub(subpath)
2620 2620 try:
2621 2621 if sub.removefiles(
2622 2622 submatch,
2623 2623 subprefix,
2624 2624 subuipathfn,
2625 2625 after,
2626 2626 force,
2627 2627 subrepos,
2628 2628 dryrun,
2629 2629 warnings,
2630 2630 ):
2631 2631 ret = 1
2632 2632 except error.LookupError:
2633 2633 warnings.append(
2634 2634 _(b"skipping missing subrepository: %s\n")
2635 2635 % uipathfn(subpath)
2636 2636 )
2637 2637 progress.complete()
2638 2638
2639 2639 # warn about failure to delete explicit files/dirs
2640 2640 deleteddirs = pathutil.dirs(deleted)
2641 2641 files = m.files()
2642 2642 progress = ui.makeprogress(
2643 2643 _(b'deleting'), total=len(files), unit=_(b'files')
2644 2644 )
2645 2645 for f in files:
2646 2646
2647 2647 def insubrepo():
2648 2648 for subpath in wctx.substate:
2649 2649 if f.startswith(subpath + b'/'):
2650 2650 return True
2651 2651 return False
2652 2652
2653 2653 progress.increment()
2654 2654 isdir = f in deleteddirs or wctx.hasdir(f)
2655 2655 if f in repo.dirstate or isdir or f == b'.' or insubrepo() or f in subs:
2656 2656 continue
2657 2657
2658 2658 if repo.wvfs.exists(f):
2659 2659 if repo.wvfs.isdir(f):
2660 2660 warnings.append(
2661 2661 _(b'not removing %s: no tracked files\n') % uipathfn(f)
2662 2662 )
2663 2663 else:
2664 2664 warnings.append(
2665 2665 _(b'not removing %s: file is untracked\n') % uipathfn(f)
2666 2666 )
2667 2667 # missing files will generate a warning elsewhere
2668 2668 ret = 1
2669 2669 progress.complete()
2670 2670
2671 2671 if force:
2672 2672 list = modified + deleted + clean + added
2673 2673 elif after:
2674 2674 list = deleted
2675 2675 remaining = modified + added + clean
2676 2676 progress = ui.makeprogress(
2677 2677 _(b'skipping'), total=len(remaining), unit=_(b'files')
2678 2678 )
2679 2679 for f in remaining:
2680 2680 progress.increment()
2681 2681 if ui.verbose or (f in files):
2682 2682 warnings.append(
2683 2683 _(b'not removing %s: file still exists\n') % uipathfn(f)
2684 2684 )
2685 2685 ret = 1
2686 2686 progress.complete()
2687 2687 else:
2688 2688 list = deleted + clean
2689 2689 progress = ui.makeprogress(
2690 2690 _(b'skipping'), total=(len(modified) + len(added)), unit=_(b'files')
2691 2691 )
2692 2692 for f in modified:
2693 2693 progress.increment()
2694 2694 warnings.append(
2695 2695 _(
2696 2696 b'not removing %s: file is modified (use -f'
2697 2697 b' to force removal)\n'
2698 2698 )
2699 2699 % uipathfn(f)
2700 2700 )
2701 2701 ret = 1
2702 2702 for f in added:
2703 2703 progress.increment()
2704 2704 warnings.append(
2705 2705 _(
2706 2706 b"not removing %s: file has been marked for add"
2707 2707 b" (use 'hg forget' to undo add)\n"
2708 2708 )
2709 2709 % uipathfn(f)
2710 2710 )
2711 2711 ret = 1
2712 2712 progress.complete()
2713 2713
2714 2714 list = sorted(list)
2715 2715 progress = ui.makeprogress(
2716 2716 _(b'deleting'), total=len(list), unit=_(b'files')
2717 2717 )
2718 2718 for f in list:
2719 2719 if ui.verbose or not m.exact(f):
2720 2720 progress.increment()
2721 2721 ui.status(
2722 2722 _(b'removing %s\n') % uipathfn(f), label=b'ui.addremove.removed'
2723 2723 )
2724 2724 progress.complete()
2725 2725
2726 2726 if not dryrun:
2727 2727 with repo.wlock():
2728 2728 if not after:
2729 2729 for f in list:
2730 2730 if f in added:
2731 2731 continue # we never unlink added files on remove
2732 2732 rmdir = repo.ui.configbool(
2733 2733 b'experimental', b'removeemptydirs'
2734 2734 )
2735 2735 repo.wvfs.unlinkpath(f, ignoremissing=True, rmdir=rmdir)
2736 2736 repo[None].forget(list)
2737 2737
2738 2738 if warn:
2739 2739 for warning in warnings:
2740 2740 ui.warn(warning)
2741 2741
2742 2742 return ret
2743 2743
2744 2744
2745 2745 def _catfmtneedsdata(fm):
2746 2746 return not fm.datahint() or b'data' in fm.datahint()
2747 2747
2748 2748
2749 2749 def _updatecatformatter(fm, ctx, matcher, path, decode):
2750 2750 """Hook for adding data to the formatter used by ``hg cat``.
2751 2751
2752 2752 Extensions (e.g., lfs) can wrap this to inject keywords/data, but must call
2753 2753 this method first."""
2754 2754
2755 2755 # data() can be expensive to fetch (e.g. lfs), so don't fetch it if it
2756 2756 # wasn't requested.
2757 2757 data = b''
2758 2758 if _catfmtneedsdata(fm):
2759 2759 data = ctx[path].data()
2760 2760 if decode:
2761 2761 data = ctx.repo().wwritedata(path, data)
2762 2762 fm.startitem()
2763 2763 fm.context(ctx=ctx)
2764 2764 fm.write(b'data', b'%s', data)
2765 2765 fm.data(path=path)
2766 2766
2767 2767
2768 2768 def cat(ui, repo, ctx, matcher, basefm, fntemplate, prefix, **opts):
2769 2769 err = 1
2770 2770
2771 2771 def write(path):
2772 2772 filename = None
2773 2773 if fntemplate:
2774 2774 filename = makefilename(
2775 2775 ctx, fntemplate, pathname=os.path.join(prefix, path)
2776 2776 )
2777 2777 # attempt to create the directory if it does not already exist
2778 2778 try:
2779 2779 os.makedirs(os.path.dirname(filename))
2780 2780 except OSError:
2781 2781 pass
2782 2782 with formatter.maybereopen(basefm, filename) as fm:
2783 2783 _updatecatformatter(fm, ctx, matcher, path, opts.get('decode'))
2784 2784
2785 2785 # Automation often uses hg cat on single files, so special case it
2786 2786 # for performance to avoid the cost of parsing the manifest.
2787 2787 if len(matcher.files()) == 1 and not matcher.anypats():
2788 2788 file = matcher.files()[0]
2789 2789 mfl = repo.manifestlog
2790 2790 mfnode = ctx.manifestnode()
2791 2791 try:
2792 2792 if mfnode and mfl[mfnode].find(file)[0]:
2793 2793 if _catfmtneedsdata(basefm):
2794 2794 scmutil.prefetchfiles(repo, [(ctx.rev(), matcher)])
2795 2795 write(file)
2796 2796 return 0
2797 2797 except KeyError:
2798 2798 pass
2799 2799
2800 2800 if _catfmtneedsdata(basefm):
2801 2801 scmutil.prefetchfiles(repo, [(ctx.rev(), matcher)])
2802 2802
2803 2803 for abs in ctx.walk(matcher):
2804 2804 write(abs)
2805 2805 err = 0
2806 2806
2807 2807 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
2808 2808 for subpath in sorted(ctx.substate):
2809 2809 sub = ctx.sub(subpath)
2810 2810 try:
2811 2811 submatch = matchmod.subdirmatcher(subpath, matcher)
2812 2812 subprefix = os.path.join(prefix, subpath)
2813 2813 if not sub.cat(
2814 2814 submatch,
2815 2815 basefm,
2816 2816 fntemplate,
2817 2817 subprefix,
2818 2818 **opts,
2819 2819 ):
2820 2820 err = 0
2821 2821 except error.RepoLookupError:
2822 2822 ui.status(
2823 2823 _(b"skipping missing subrepository: %s\n") % uipathfn(subpath)
2824 2824 )
2825 2825
2826 2826 return err
2827 2827
2828 2828
2829 2829 class _AddRemoveContext:
2830 2830 """a small (hacky) context to deal with lazy opening of context
2831 2831
2832 2832 This is to be used in the `commit` function right below. This deals with
2833 2833 lazily open a `changing_files` context inside a `transaction` that span the
2834 2834 full commit operation.
2835 2835
2836 2836 We need :
2837 2837 - a `changing_files` context to wrap the dirstate change within the
2838 2838 "addremove" operation,
2839 2839 - a transaction to make sure these change are not written right after the
2840 2840 addremove, but when the commit operation succeed.
2841 2841
2842 2842 However it get complicated because:
2843 2843 - opening a transaction "this early" shuffle hooks order, especially the
2844 2844 `precommit` one happening after the `pretxtopen` one which I am not too
2845 2845 enthusiastic about.
2846 2846 - the `mq` extensions + the `record` extension stacks many layers of call
2847 2847 to implement `qrefresh --interactive` and this result with `mq` calling a
2848 2848 `strip` in the middle of this function. Which prevent the existence of
2849 2849 transaction wrapping all of its function code. (however, `qrefresh` never
2850 2850 call the `addremove` bits.
2851 2851 - the largefile extensions (and maybe other extensions?) wraps `addremove`
2852 2852 so slicing `addremove` in smaller bits is a complex endeavour.
2853 2853
2854 2854 So I eventually took a this shortcut that open the transaction if we
2855 2855 actually needs it, not disturbing much of the rest of the code.
2856 2856
2857 2857 It will result in some hooks order change for `hg commit --addremove`,
2858 2858 however it seems a corner case enough to ignore that for now (hopefully).
2859 2859
2860 2860 Notes that None of the above problems seems insurmountable, however I have
2861 2861 been fighting with this specific piece of code for a couple of day already
2862 2862 and I need a solution to keep moving forward on the bigger work around
2863 2863 `changing_files` context that is being introduced at the same time as this
2864 2864 hack.
2865 2865
2866 2866 Each problem seems to have a solution:
2867 2867 - the hook order issue could be solved by refactoring the many-layer stack
2868 2868 that currently composes a commit and calling them earlier,
2869 2869 - the mq issue could be solved by refactoring `mq` so that the final strip
2870 2870 is done after transaction closure. Be warned that the mq code is quite
2871 2871 antic however.
2872 2872 - large-file could be reworked in parallel of the `addremove` to be
2873 2873 friendlier to this.
2874 2874
2875 2875 However each of these tasks are too much a diversion right now. In addition
2876 2876 they will be much easier to undertake when the `changing_files` dust has
2877 2877 settled."""
2878 2878
2879 2879 def __init__(self, repo):
2880 2880 self._repo = repo
2881 2881 self._transaction = None
2882 2882 self._dirstate_context = None
2883 2883 self._state = None
2884 2884
2885 2885 def __enter__(self):
2886 2886 assert self._state is None
2887 2887 self._state = True
2888 2888 return self
2889 2889
2890 2890 def open_transaction(self):
2891 2891 """open a `transaction` and `changing_files` context
2892 2892
2893 2893 Call this when you know that change to the dirstate will be needed and
2894 2894 we need to open the transaction early
2895 2895
2896 2896 This will also open the dirstate `changing_files` context, so you should
2897 2897 call `close_dirstate_context` when the distate changes are done.
2898 2898 """
2899 2899 assert self._state is not None
2900 2900 if self._transaction is None:
2901 2901 self._transaction = self._repo.transaction(b'commit')
2902 2902 self._transaction.__enter__()
2903 2903 if self._dirstate_context is None:
2904 2904 self._dirstate_context = self._repo.dirstate.changing_files(
2905 2905 self._repo
2906 2906 )
2907 2907 self._dirstate_context.__enter__()
2908 2908
2909 2909 def close_dirstate_context(self):
2910 2910 """close the change_files if any
2911 2911
2912 2912 Call this after the (potential) `open_transaction` call to close the
2913 2913 (potential) changing_files context.
2914 2914 """
2915 2915 if self._dirstate_context is not None:
2916 2916 self._dirstate_context.__exit__(None, None, None)
2917 2917 self._dirstate_context = None
2918 2918
2919 2919 def __exit__(self, *args):
2920 2920 if self._dirstate_context is not None:
2921 2921 self._dirstate_context.__exit__(*args)
2922 2922 if self._transaction is not None:
2923 2923 self._transaction.__exit__(*args)
2924 2924
2925 2925
2926 2926 def commit(ui, repo, commitfunc, pats, opts):
2927 2927 '''commit the specified files or all outstanding changes'''
2928 2928 date = opts.get(b'date')
2929 2929 if date:
2930 2930 opts[b'date'] = dateutil.parsedate(date)
2931 2931
2932 2932 with repo.wlock(), repo.lock():
2933 2933 message = logmessage(ui, opts)
2934 2934 matcher = scmutil.match(repo[None], pats, opts)
2935 2935
2936 2936 with _AddRemoveContext(repo) as c:
2937 2937 # extract addremove carefully -- this function can be called from a
2938 2938 # command that doesn't support addremove
2939 2939 if opts.get(b'addremove'):
2940 2940 relative = scmutil.anypats(pats, opts)
2941 2941 uipathfn = scmutil.getuipathfn(
2942 2942 repo,
2943 2943 legacyrelativevalue=relative,
2944 2944 )
2945 2945 r = scmutil.addremove(
2946 2946 repo,
2947 2947 matcher,
2948 2948 b"",
2949 2949 uipathfn,
2950 2950 opts,
2951 2951 open_tr=c.open_transaction,
2952 2952 )
2953 2953 m = _(b"failed to mark all new/missing files as added/removed")
2954 2954 if r != 0:
2955 2955 raise error.Abort(m)
2956 2956 c.close_dirstate_context()
2957 2957 return commitfunc(ui, repo, message, matcher, opts)
2958 2958
2959 2959
2960 2960 def samefile(f, ctx1, ctx2):
2961 2961 if f in ctx1.manifest():
2962 2962 a = ctx1.filectx(f)
2963 2963 if f in ctx2.manifest():
2964 2964 b = ctx2.filectx(f)
2965 2965 return not a.cmp(b) and a.flags() == b.flags()
2966 2966 else:
2967 2967 return False
2968 2968 else:
2969 2969 return f not in ctx2.manifest()
2970 2970
2971 2971
2972 2972 def amend(ui, repo, old, extra, pats, opts: Dict[str, Any]):
2973 2973 # avoid cycle context -> subrepo -> cmdutil
2974 2974 from . import context
2975 2975
2976 2976 # amend will reuse the existing user if not specified, but the obsolete
2977 2977 # marker creation requires that the current user's name is specified.
2978 2978 if obsolete.isenabled(repo, obsolete.createmarkersopt):
2979 2979 ui.username() # raise exception if username not set
2980 2980
2981 2981 ui.note(_(b'amending changeset %s\n') % old)
2982 2982 base = old.p1()
2983 2983
2984 2984 with repo.wlock(), repo.lock(), repo.transaction(b'amend'):
2985 2985 # Participating changesets:
2986 2986 #
2987 2987 # wctx o - workingctx that contains changes from working copy
2988 2988 # | to go into amending commit
2989 2989 # |
2990 2990 # old o - changeset to amend
2991 2991 # |
2992 2992 # base o - first parent of the changeset to amend
2993 2993 wctx = repo[None]
2994 2994
2995 2995 # Copy to avoid mutating input
2996 2996 extra = extra.copy()
2997 2997 # Update extra dict from amended commit (e.g. to preserve graft
2998 2998 # source)
2999 2999 extra.update(old.extra())
3000 3000
3001 3001 # Also update it from the from the wctx
3002 3002 extra.update(wctx.extra())
3003 3003
3004 3004 # date-only change should be ignored?
3005 3005 datemaydiffer = resolve_commit_options(ui, opts)
3006 3006 opts = pycompat.byteskwargs(opts)
3007 3007
3008 3008 date = old.date()
3009 3009 if opts.get(b'date'):
3010 3010 date = dateutil.parsedate(opts.get(b'date'))
3011 3011 user = opts.get(b'user') or old.user()
3012 3012
3013 3013 if len(old.parents()) > 1:
3014 3014 # ctx.files() isn't reliable for merges, so fall back to the
3015 3015 # slower repo.status() method
3016 3016 st = base.status(old)
3017 3017 files = set(st.modified) | set(st.added) | set(st.removed)
3018 3018 else:
3019 3019 files = set(old.files())
3020 3020
3021 3021 # add/remove the files to the working copy if the "addremove" option
3022 3022 # was specified.
3023 3023 matcher = scmutil.match(wctx, pats, opts)
3024 3024 relative = scmutil.anypats(pats, opts)
3025 3025 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=relative)
3026 3026 if opts.get(b'addremove'):
3027 3027 with repo.dirstate.changing_files(repo):
3028 3028 if scmutil.addremove(repo, matcher, b"", uipathfn, opts) != 0:
3029 3029 m = _(
3030 3030 b"failed to mark all new/missing files as added/removed"
3031 3031 )
3032 3032 raise error.Abort(m)
3033 3033
3034 3034 # Check subrepos. This depends on in-place wctx._status update in
3035 3035 # subrepo.precommit(). To minimize the risk of this hack, we do
3036 3036 # nothing if .hgsub does not exist.
3037 3037 if b'.hgsub' in wctx or b'.hgsub' in old:
3038 3038 subs, commitsubs, newsubstate = subrepoutil.precommit(
3039 3039 ui, wctx, wctx._status, matcher
3040 3040 )
3041 3041 # amend should abort if commitsubrepos is enabled
3042 3042 assert not commitsubs
3043 3043 if subs:
3044 3044 subrepoutil.writestate(repo, newsubstate)
3045 3045
3046 3046 ms = mergestatemod.mergestate.read(repo)
3047 3047 mergeutil.checkunresolved(ms)
3048 3048
3049 3049 filestoamend = {f for f in wctx.files() if matcher(f)}
3050 3050
3051 3051 changes = len(filestoamend) > 0
3052 3052 changeset_copies = (
3053 3053 repo.ui.config(b'experimental', b'copies.read-from')
3054 3054 != b'filelog-only'
3055 3055 )
3056 3056 # If there are changes to amend or if copy information needs to be read
3057 3057 # from the changeset extras, we cannot take the fast path of using
3058 3058 # filectxs from the old commit.
3059 3059 if changes or changeset_copies:
3060 3060 # Recompute copies (avoid recording a -> b -> a)
3061 3061 copied = copies.pathcopies(base, wctx)
3062 3062 if old.p2():
3063 3063 copied.update(copies.pathcopies(old.p2(), wctx))
3064 3064
3065 3065 # Prune files which were reverted by the updates: if old
3066 3066 # introduced file X and the file was renamed in the working
3067 3067 # copy, then those two files are the same and
3068 3068 # we can discard X from our list of files. Likewise if X
3069 3069 # was removed, it's no longer relevant. If X is missing (aka
3070 3070 # deleted), old X must be preserved.
3071 3071 files.update(filestoamend)
3072 3072 files = [
3073 3073 f
3074 3074 for f in files
3075 3075 if (f not in filestoamend or not samefile(f, wctx, base))
3076 3076 ]
3077 3077
3078 3078 def filectxfn(repo, ctx_, path):
3079 3079 try:
3080 3080 # If the file being considered is not amongst the files
3081 3081 # to be amended, we should use the file context from the
3082 3082 # old changeset. This avoids issues when only some files in
3083 3083 # the working copy are being amended but there are also
3084 3084 # changes to other files from the old changeset.
3085 3085 if path in filestoamend:
3086 3086 # Return None for removed files.
3087 3087 if path in wctx.removed():
3088 3088 return None
3089 3089 fctx = wctx[path]
3090 3090 else:
3091 3091 fctx = old.filectx(path)
3092 3092 flags = fctx.flags()
3093 3093 mctx = context.memfilectx(
3094 3094 repo,
3095 3095 ctx_,
3096 3096 fctx.path(),
3097 3097 fctx.data(),
3098 3098 islink=b'l' in flags,
3099 3099 isexec=b'x' in flags,
3100 3100 copysource=copied.get(path),
3101 3101 )
3102 3102 return mctx
3103 3103 except KeyError:
3104 3104 return None
3105 3105
3106 3106 else:
3107 3107 ui.note(_(b'copying changeset %s to %s\n') % (old, base))
3108 3108
3109 3109 # Use version of files as in the old cset
3110 3110 def filectxfn(repo, ctx_, path):
3111 3111 try:
3112 3112 return old.filectx(path)
3113 3113 except KeyError:
3114 3114 return None
3115 3115
3116 3116 # See if we got a message from -m or -l, if not, open the editor with
3117 3117 # the message of the changeset to amend.
3118 3118 message = logmessage(ui, opts)
3119 3119
3120 3120 editform = mergeeditform(old, b'commit.amend')
3121 3121
3122 3122 if not message:
3123 3123 message = old.description()
3124 3124 # Default if message isn't provided and --edit is not passed is to
3125 3125 # invoke editor, but allow --no-edit. If somehow we don't have any
3126 3126 # description, let's always start the editor.
3127 3127 doedit = not message or opts.get(b'edit') in [True, None]
3128 3128 else:
3129 3129 # Default if message is provided is to not invoke editor, but allow
3130 3130 # --edit.
3131 3131 doedit = opts.get(b'edit') is True
3132 3132 editor = getcommiteditor(edit=doedit, editform=editform)
3133 3133
3134 3134 pureextra = extra.copy()
3135 3135 extra[b'amend_source'] = old.hex()
3136 3136
3137 3137 new = context.memctx(
3138 3138 repo,
3139 3139 parents=[base.node(), old.p2().node()],
3140 3140 text=message,
3141 3141 files=files,
3142 3142 filectxfn=filectxfn,
3143 3143 user=user,
3144 3144 date=date,
3145 3145 extra=extra,
3146 3146 editor=editor,
3147 3147 )
3148 3148
3149 3149 newdesc = changelog.stripdesc(new.description())
3150 3150 if (
3151 3151 (not changes)
3152 3152 and newdesc == old.description()
3153 3153 and user == old.user()
3154 3154 and (date == old.date() or datemaydiffer)
3155 3155 and pureextra == old.extra()
3156 3156 ):
3157 3157 # nothing changed. continuing here would create a new node
3158 3158 # anyway because of the amend_source noise.
3159 3159 #
3160 3160 # This not what we expect from amend.
3161 3161 return old.node()
3162 3162
3163 3163 commitphase = None
3164 3164 if opts.get(b'secret'):
3165 3165 commitphase = phases.secret
3166 3166 elif opts.get(b'draft'):
3167 3167 commitphase = phases.draft
3168 3168 newid = repo.commitctx(new)
3169 3169 ms.reset()
3170 3170
3171 3171 with repo.dirstate.changing_parents(repo):
3172 3172 # Reroute the working copy parent to the new changeset
3173 3173 repo.setparents(newid, repo.nullid)
3174 3174
3175 3175 # Fixing the dirstate because localrepo.commitctx does not update
3176 3176 # it. This is rather convenient because we did not need to update
3177 3177 # the dirstate for all the files in the new commit which commitctx
3178 3178 # could have done if it updated the dirstate. Now, we can
3179 3179 # selectively update the dirstate only for the amended files.
3180 3180 dirstate = repo.dirstate
3181 3181
3182 3182 # Update the state of the files which were added and modified in the
3183 3183 # amend to "normal" in the dirstate. We need to use "normallookup" since
3184 3184 # the files may have changed since the command started; using "normal"
3185 3185 # would mark them as clean but with uncommitted contents.
3186 3186 normalfiles = set(wctx.modified() + wctx.added()) & filestoamend
3187 3187 for f in normalfiles:
3188 3188 dirstate.update_file(
3189 3189 f, p1_tracked=True, wc_tracked=True, possibly_dirty=True
3190 3190 )
3191 3191
3192 3192 # Update the state of files which were removed in the amend
3193 3193 # to "removed" in the dirstate.
3194 3194 removedfiles = set(wctx.removed()) & filestoamend
3195 3195 for f in removedfiles:
3196 3196 dirstate.update_file(f, p1_tracked=False, wc_tracked=False)
3197 3197
3198 3198 mapping = {old.node(): (newid,)}
3199 3199 obsmetadata = None
3200 3200 if opts.get(b'note'):
3201 3201 obsmetadata = {b'note': encoding.fromlocal(opts[b'note'])}
3202 3202 backup = ui.configbool(b'rewrite', b'backup-bundle')
3203 3203 scmutil.cleanupnodes(
3204 3204 repo,
3205 3205 mapping,
3206 3206 b'amend',
3207 3207 metadata=obsmetadata,
3208 3208 fixphase=True,
3209 3209 targetphase=commitphase,
3210 3210 backup=backup,
3211 3211 )
3212 3212
3213 3213 return newid
3214 3214
3215 3215
3216 3216 def commiteditor(repo, ctx, subs, editform=b''):
3217 3217 if ctx.description():
3218 3218 return ctx.description()
3219 3219 return commitforceeditor(
3220 3220 repo, ctx, subs, editform=editform, unchangedmessagedetection=True
3221 3221 )
3222 3222
3223 3223
3224 3224 def commitforceeditor(
3225 3225 repo,
3226 3226 ctx,
3227 3227 subs,
3228 3228 finishdesc=None,
3229 3229 extramsg=None,
3230 3230 editform=b'',
3231 3231 unchangedmessagedetection=False,
3232 3232 ):
3233 3233 if not extramsg:
3234 3234 extramsg = _(b"Leave message empty to abort commit.")
3235 3235
3236 3236 forms = [e for e in editform.split(b'.') if e]
3237 3237 forms.insert(0, b'changeset')
3238 3238 templatetext = None
3239 3239 while forms:
3240 3240 ref = b'.'.join(forms)
3241 3241 if repo.ui.config(b'committemplate', ref):
3242 3242 templatetext = committext = buildcommittemplate(
3243 3243 repo, ctx, subs, extramsg, ref
3244 3244 )
3245 3245 break
3246 3246 forms.pop()
3247 3247 else:
3248 3248 committext = buildcommittext(repo, ctx, subs, extramsg)
3249 3249
3250 3250 # run editor in the repository root
3251 3251 olddir = encoding.getcwd()
3252 3252 os.chdir(repo.root)
3253 3253
3254 3254 # make in-memory changes visible to external process
3255 3255 tr = repo.currenttransaction()
3256 3256 repo.dirstate.write(tr)
3257 3257 pending = tr and tr.writepending() and repo.root
3258 3258
3259 3259 editortext = repo.ui.edit(
3260 3260 committext,
3261 3261 ctx.user(),
3262 3262 ctx.extra(),
3263 3263 editform=editform,
3264 3264 pending=pending,
3265 3265 repopath=repo.path,
3266 3266 action=b'commit',
3267 3267 )
3268 3268 text = editortext
3269 3269
3270 3270 # strip away anything below this special string (used for editors that want
3271 3271 # to display the diff)
3272 3272 stripbelow = re.search(_linebelow, text, flags=re.MULTILINE)
3273 3273 if stripbelow:
3274 3274 text = text[: stripbelow.start()]
3275 3275
3276 3276 text = re.sub(b"(?m)^HG:.*(\n|$)", b"", text)
3277 3277 os.chdir(olddir)
3278 3278
3279 3279 if finishdesc:
3280 3280 text = finishdesc(text)
3281 3281 if not text.strip():
3282 3282 raise error.InputError(_(b"empty commit message"))
3283 3283 if unchangedmessagedetection and editortext == templatetext:
3284 3284 raise error.InputError(_(b"commit message unchanged"))
3285 3285
3286 3286 return text
3287 3287
3288 3288
3289 3289 def buildcommittemplate(repo, ctx, subs, extramsg, ref):
3290 3290 ui = repo.ui
3291 3291 spec = formatter.reference_templatespec(ref)
3292 3292 t = logcmdutil.changesettemplater(ui, repo, spec)
3293 3293 t.t.cache.update(
3294 3294 (k, templater.unquotestring(v))
3295 3295 for k, v in repo.ui.configitems(b'committemplate')
3296 3296 )
3297 3297
3298 3298 if not extramsg:
3299 3299 extramsg = b'' # ensure that extramsg is string
3300 3300
3301 3301 ui.pushbuffer()
3302 3302 t.show(ctx, extramsg=extramsg)
3303 3303 return ui.popbuffer()
3304 3304
3305 3305
3306 3306 def hgprefix(msg):
3307 3307 return b"\n".join([b"HG: %s" % a for a in msg.split(b"\n") if a])
3308 3308
3309 3309
3310 3310 def buildcommittext(repo, ctx, subs, extramsg):
3311 3311 edittext = []
3312 3312 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
3313 3313 if ctx.description():
3314 3314 edittext.append(ctx.description())
3315 3315 edittext.append(b"")
3316 3316 edittext.append(b"") # Empty line between message and comments.
3317 3317 edittext.append(
3318 3318 hgprefix(
3319 3319 _(
3320 3320 b"Enter commit message."
3321 3321 b" Lines beginning with 'HG:' are removed."
3322 3322 )
3323 3323 )
3324 3324 )
3325 3325 edittext.append(hgprefix(extramsg))
3326 3326 edittext.append(b"HG: --")
3327 3327 edittext.append(hgprefix(_(b"user: %s") % ctx.user()))
3328 3328 if ctx.p2():
3329 3329 edittext.append(hgprefix(_(b"branch merge")))
3330 3330 if ctx.branch():
3331 3331 edittext.append(hgprefix(_(b"branch '%s'") % ctx.branch()))
3332 3332 if bookmarks.isactivewdirparent(repo):
3333 3333 edittext.append(hgprefix(_(b"bookmark '%s'") % repo._activebookmark))
3334 3334 edittext.extend([hgprefix(_(b"subrepo %s") % s) for s in subs])
3335 3335 edittext.extend([hgprefix(_(b"added %s") % f) for f in added])
3336 3336 edittext.extend([hgprefix(_(b"changed %s") % f) for f in modified])
3337 3337 edittext.extend([hgprefix(_(b"removed %s") % f) for f in removed])
3338 3338 if not added and not modified and not removed:
3339 3339 edittext.append(hgprefix(_(b"no files changed")))
3340 3340 edittext.append(b"")
3341 3341
3342 3342 return b"\n".join(edittext)
3343 3343
3344 3344
3345 3345 def commitstatus(repo, node, branch, bheads=None, tip=None, **opts):
3346 3346 ctx = repo[node]
3347 3347 parents = ctx.parents()
3348 3348
3349 3349 if tip is not None and repo.changelog.tip() == tip:
3350 3350 # avoid reporting something like "committed new head" when
3351 3351 # recommitting old changesets, and issue a helpful warning
3352 3352 # for most instances
3353 3353 repo.ui.warn(_(b"warning: commit already existed in the repository!\n"))
3354 3354 elif (
3355 3355 not opts.get('amend')
3356 3356 and bheads
3357 3357 and node not in bheads
3358 3358 and not any(
3359 3359 p.node() in bheads and p.branch() == branch for p in parents
3360 3360 )
3361 3361 ):
3362 3362 repo.ui.status(_(b'created new head\n'))
3363 3363 # The message is not printed for initial roots. For the other
3364 3364 # changesets, it is printed in the following situations:
3365 3365 #
3366 3366 # Par column: for the 2 parents with ...
3367 3367 # N: null or no parent
3368 3368 # B: parent is on another named branch
3369 3369 # C: parent is a regular non head changeset
3370 3370 # H: parent was a branch head of the current branch
3371 3371 # Msg column: whether we print "created new head" message
3372 3372 # In the following, it is assumed that there already exists some
3373 3373 # initial branch heads of the current branch, otherwise nothing is
3374 3374 # printed anyway.
3375 3375 #
3376 3376 # Par Msg Comment
3377 3377 # N N y additional topo root
3378 3378 #
3379 3379 # B N y additional branch root
3380 3380 # C N y additional topo head
3381 3381 # H N n usual case
3382 3382 #
3383 3383 # B B y weird additional branch root
3384 3384 # C B y branch merge
3385 3385 # H B n merge with named branch
3386 3386 #
3387 3387 # C C y additional head from merge
3388 3388 # C H n merge with a head
3389 3389 #
3390 3390 # H H n head merge: head count decreases
3391 3391
3392 3392 if not opts.get('close_branch'):
3393 3393 for r in parents:
3394 3394 if r.closesbranch() and r.branch() == branch:
3395 3395 repo.ui.status(
3396 3396 _(b'reopening closed branch head %d\n') % r.rev()
3397 3397 )
3398 3398
3399 3399 if repo.ui.debugflag:
3400 3400 repo.ui.write(
3401 3401 _(b'committed changeset %d:%s\n') % (ctx.rev(), ctx.hex())
3402 3402 )
3403 3403 elif repo.ui.verbose:
3404 3404 repo.ui.write(_(b'committed changeset %d:%s\n') % (ctx.rev(), ctx))
3405 3405
3406 3406
3407 3407 def postcommitstatus(repo, pats, opts):
3408 3408 return repo.status(match=scmutil.match(repo[None], pats, opts))
3409 3409
3410 3410
3411 3411 def revert(ui, repo, ctx, *pats, **opts):
3412 3412 opts = pycompat.byteskwargs(opts)
3413 3413 parent, p2 = repo.dirstate.parents()
3414 3414 node = ctx.node()
3415 3415
3416 3416 mf = ctx.manifest()
3417 3417 if node == p2:
3418 3418 parent = p2
3419 3419
3420 3420 # need all matching names in dirstate and manifest of target rev,
3421 3421 # so have to walk both. do not print errors if files exist in one
3422 3422 # but not other. in both cases, filesets should be evaluated against
3423 3423 # workingctx to get consistent result (issue4497). this means 'set:**'
3424 3424 # cannot be used to select missing files from target rev.
3425 3425
3426 3426 # `names` is a mapping for all elements in working copy and target revision
3427 3427 # The mapping is in the form:
3428 3428 # <abs path in repo> -> (<path from CWD>, <exactly specified by matcher?>)
3429 3429 names = {}
3430 3430 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
3431 3431
3432 3432 with repo.wlock(), repo.dirstate.changing_files(repo):
3433 3433 ## filling of the `names` mapping
3434 3434 # walk dirstate to fill `names`
3435 3435
3436 3436 interactive = opts.get(b'interactive', False)
3437 3437 wctx = repo[None]
3438 3438 m = scmutil.match(wctx, pats, opts)
3439 3439
3440 3440 # we'll need this later
3441 3441 targetsubs = sorted(s for s in wctx.substate if m(s))
3442 3442
3443 3443 if not m.always():
3444 3444 matcher = matchmod.badmatch(m, lambda x, y: False)
3445 3445 for abs in wctx.walk(matcher):
3446 3446 names[abs] = m.exact(abs)
3447 3447
3448 3448 # walk target manifest to fill `names`
3449 3449
3450 3450 def badfn(path, msg):
3451 3451 if path in names:
3452 3452 return
3453 3453 if path in ctx.substate:
3454 3454 return
3455 3455 path_ = path + b'/'
3456 3456 for f in names:
3457 3457 if f.startswith(path_):
3458 3458 return
3459 3459 ui.warn(b"%s: %s\n" % (uipathfn(path), msg))
3460 3460
3461 3461 for abs in ctx.walk(matchmod.badmatch(m, badfn)):
3462 3462 if abs not in names:
3463 3463 names[abs] = m.exact(abs)
3464 3464
3465 3465 # Find status of all file in `names`.
3466 3466 m = scmutil.matchfiles(repo, names)
3467 3467
3468 3468 changes = repo.status(
3469 3469 node1=node, match=m, unknown=True, ignored=True, clean=True
3470 3470 )
3471 3471 else:
3472 3472 changes = repo.status(node1=node, match=m)
3473 3473 for kind in changes:
3474 3474 for abs in kind:
3475 3475 names[abs] = m.exact(abs)
3476 3476
3477 3477 m = scmutil.matchfiles(repo, names)
3478 3478
3479 3479 modified = set(changes.modified)
3480 3480 added = set(changes.added)
3481 3481 removed = set(changes.removed)
3482 3482 _deleted = set(changes.deleted)
3483 3483 unknown = set(changes.unknown)
3484 3484 unknown.update(changes.ignored)
3485 3485 clean = set(changes.clean)
3486 3486 modadded = set()
3487 3487
3488 3488 # We need to account for the state of the file in the dirstate,
3489 3489 # even when we revert against something else than parent. This will
3490 3490 # slightly alter the behavior of revert (doing back up or not, delete
3491 3491 # or just forget etc).
3492 3492 if parent == node:
3493 3493 dsmodified = modified
3494 3494 dsadded = added
3495 3495 dsremoved = removed
3496 3496 # store all local modifications, useful later for rename detection
3497 3497 localchanges = dsmodified | dsadded
3498 3498 modified, added, removed = set(), set(), set()
3499 3499 else:
3500 3500 changes = repo.status(node1=parent, match=m)
3501 3501 dsmodified = set(changes.modified)
3502 3502 dsadded = set(changes.added)
3503 3503 dsremoved = set(changes.removed)
3504 3504 # store all local modifications, useful later for rename detection
3505 3505 localchanges = dsmodified | dsadded
3506 3506
3507 3507 # only take into account for removes between wc and target
3508 3508 clean |= dsremoved - removed
3509 3509 dsremoved &= removed
3510 3510 # distinct between dirstate remove and other
3511 3511 removed -= dsremoved
3512 3512
3513 3513 modadded = added & dsmodified
3514 3514 added -= modadded
3515 3515
3516 3516 # tell newly modified apart.
3517 3517 dsmodified &= modified
3518 3518 dsmodified |= modified & dsadded # dirstate added may need backup
3519 3519 modified -= dsmodified
3520 3520
3521 3521 # We need to wait for some post-processing to update this set
3522 3522 # before making the distinction. The dirstate will be used for
3523 3523 # that purpose.
3524 3524 dsadded = added
3525 3525
3526 3526 # in case of merge, files that are actually added can be reported as
3527 3527 # modified, we need to post process the result
3528 3528 if p2 != repo.nullid:
3529 3529 mergeadd = set(dsmodified)
3530 3530 for path in dsmodified:
3531 3531 if path in mf:
3532 3532 mergeadd.remove(path)
3533 3533 dsadded |= mergeadd
3534 3534 dsmodified -= mergeadd
3535 3535
3536 3536 # if f is a rename, update `names` to also revert the source
3537 3537 for f in localchanges:
3538 3538 src = repo.dirstate.copied(f)
3539 3539 # XXX should we check for rename down to target node?
3540 3540 if (
3541 3541 src
3542 3542 and src not in names
3543 3543 and repo.dirstate.get_entry(src).removed
3544 3544 ):
3545 3545 dsremoved.add(src)
3546 3546 names[src] = True
3547 3547
3548 3548 # determine the exact nature of the deleted changesets
3549 3549 deladded = set(_deleted)
3550 3550 for path in _deleted:
3551 3551 if path in mf:
3552 3552 deladded.remove(path)
3553 3553 deleted = _deleted - deladded
3554 3554
3555 3555 # distinguish between file to forget and the other
3556 3556 added = set()
3557 3557 for abs in dsadded:
3558 3558 if not repo.dirstate.get_entry(abs).added:
3559 3559 added.add(abs)
3560 3560 dsadded -= added
3561 3561
3562 3562 for abs in deladded:
3563 3563 if repo.dirstate.get_entry(abs).added:
3564 3564 dsadded.add(abs)
3565 3565 deladded -= dsadded
3566 3566
3567 3567 # For files marked as removed, we check if an unknown file is present at
3568 3568 # the same path. If a such file exists it may need to be backed up.
3569 3569 # Making the distinction at this stage helps have simpler backup
3570 3570 # logic.
3571 3571 removunk = set()
3572 3572 for abs in removed:
3573 3573 target = repo.wjoin(abs)
3574 3574 if os.path.lexists(target):
3575 3575 removunk.add(abs)
3576 3576 removed -= removunk
3577 3577
3578 3578 dsremovunk = set()
3579 3579 for abs in dsremoved:
3580 3580 target = repo.wjoin(abs)
3581 3581 if os.path.lexists(target):
3582 3582 dsremovunk.add(abs)
3583 3583 dsremoved -= dsremovunk
3584 3584
3585 3585 # action to be actually performed by revert
3586 3586 # (<list of file>, message>) tuple
3587 3587 actions = {
3588 3588 b'revert': ([], _(b'reverting %s\n')),
3589 3589 b'add': ([], _(b'adding %s\n')),
3590 3590 b'remove': ([], _(b'removing %s\n')),
3591 3591 b'drop': ([], _(b'removing %s\n')),
3592 3592 b'forget': ([], _(b'forgetting %s\n')),
3593 3593 b'undelete': ([], _(b'undeleting %s\n')),
3594 3594 b'noop': (None, _(b'no changes needed to %s\n')),
3595 3595 b'unknown': (None, _(b'file not managed: %s\n')),
3596 3596 }
3597 3597
3598 3598 # "constant" that convey the backup strategy.
3599 3599 # All set to `discard` if `no-backup` is set do avoid checking
3600 3600 # no_backup lower in the code.
3601 3601 # These values are ordered for comparison purposes
3602 3602 backupinteractive = 3 # do backup if interactively modified
3603 3603 backup = 2 # unconditionally do backup
3604 3604 check = 1 # check if the existing file differs from target
3605 3605 discard = 0 # never do backup
3606 3606 if opts.get(b'no_backup'):
3607 3607 backupinteractive = backup = check = discard
3608 3608 if interactive:
3609 3609 dsmodifiedbackup = backupinteractive
3610 3610 else:
3611 3611 dsmodifiedbackup = backup
3612 3612 tobackup = set()
3613 3613
3614 3614 backupanddel = actions[b'remove']
3615 3615 if not opts.get(b'no_backup'):
3616 3616 backupanddel = actions[b'drop']
3617 3617
3618 3618 disptable = (
3619 3619 # dispatch table:
3620 3620 # file state
3621 3621 # action
3622 3622 # make backup
3623 3623 ## Sets that results that will change file on disk
3624 3624 # Modified compared to target, no local change
3625 3625 (modified, actions[b'revert'], discard),
3626 3626 # Modified compared to target, but local file is deleted
3627 3627 (deleted, actions[b'revert'], discard),
3628 3628 # Modified compared to target, local change
3629 3629 (dsmodified, actions[b'revert'], dsmodifiedbackup),
3630 3630 # Added since target
3631 3631 (added, actions[b'remove'], discard),
3632 3632 # Added in working directory
3633 3633 (dsadded, actions[b'forget'], discard),
3634 3634 # Added since target, have local modification
3635 3635 (modadded, backupanddel, backup),
3636 3636 # Added since target but file is missing in working directory
3637 3637 (deladded, actions[b'drop'], discard),
3638 3638 # Removed since target, before working copy parent
3639 3639 (removed, actions[b'add'], discard),
3640 3640 # Same as `removed` but an unknown file exists at the same path
3641 3641 (removunk, actions[b'add'], check),
3642 3642 # Removed since targe, marked as such in working copy parent
3643 3643 (dsremoved, actions[b'undelete'], discard),
3644 3644 # Same as `dsremoved` but an unknown file exists at the same path
3645 3645 (dsremovunk, actions[b'undelete'], check),
3646 3646 ## the following sets does not result in any file changes
3647 3647 # File with no modification
3648 3648 (clean, actions[b'noop'], discard),
3649 3649 # Existing file, not tracked anywhere
3650 3650 (unknown, actions[b'unknown'], discard),
3651 3651 )
3652 3652
3653 3653 for abs, exact in sorted(names.items()):
3654 3654 # target file to be touch on disk (relative to cwd)
3655 3655 target = repo.wjoin(abs)
3656 3656 # search the entry in the dispatch table.
3657 3657 # if the file is in any of these sets, it was touched in the working
3658 3658 # directory parent and we are sure it needs to be reverted.
3659 3659 for table, (xlist, msg), dobackup in disptable:
3660 3660 if abs not in table:
3661 3661 continue
3662 3662 if xlist is not None:
3663 3663 xlist.append(abs)
3664 3664 if dobackup:
3665 3665 # If in interactive mode, don't automatically create
3666 3666 # .orig files (issue4793)
3667 3667 if dobackup == backupinteractive:
3668 3668 tobackup.add(abs)
3669 3669 elif backup <= dobackup or wctx[abs].cmp(ctx[abs]):
3670 3670 absbakname = scmutil.backuppath(ui, repo, abs)
3671 3671 bakname = os.path.relpath(
3672 3672 absbakname, start=repo.root
3673 3673 )
3674 3674 ui.note(
3675 3675 _(b'saving current version of %s as %s\n')
3676 3676 % (uipathfn(abs), uipathfn(bakname))
3677 3677 )
3678 3678 if not opts.get(b'dry_run'):
3679 3679 if interactive:
3680 3680 util.copyfile(target, absbakname)
3681 3681 else:
3682 3682 util.rename(target, absbakname)
3683 3683 if opts.get(b'dry_run'):
3684 3684 if ui.verbose or not exact:
3685 3685 ui.status(msg % uipathfn(abs))
3686 3686 elif exact:
3687 3687 ui.warn(msg % uipathfn(abs))
3688 3688 break
3689 3689
3690 3690 if not opts.get(b'dry_run'):
3691 3691 needdata = (b'revert', b'add', b'undelete')
3692 3692 oplist = [actions[name][0] for name in needdata]
3693 3693 prefetch = scmutil.prefetchfiles
3694 3694 matchfiles = scmutil.matchfiles(
3695 3695 repo, [f for sublist in oplist for f in sublist]
3696 3696 )
3697 3697 prefetch(
3698 3698 repo,
3699 3699 [(ctx.rev(), matchfiles)],
3700 3700 )
3701 3701 match = scmutil.match(repo[None], pats)
3702 3702 _performrevert(
3703 3703 repo,
3704 3704 ctx,
3705 3705 names,
3706 3706 uipathfn,
3707 3707 actions,
3708 3708 match,
3709 3709 interactive,
3710 3710 tobackup,
3711 3711 )
3712 3712
3713 3713 if targetsubs:
3714 3714 # Revert the subrepos on the revert list
3715 3715 for sub in targetsubs:
3716 3716 try:
3717 3717 wctx.sub(sub).revert(
3718 3718 ctx.substate[sub], *pats, **pycompat.strkwargs(opts)
3719 3719 )
3720 3720 except KeyError:
3721 3721 raise error.Abort(
3722 3722 b"subrepository '%s' does not exist in %s!"
3723 3723 % (sub, short(ctx.node()))
3724 3724 )
3725 3725
3726 3726
3727 3727 def _performrevert(
3728 3728 repo,
3729 3729 ctx,
3730 3730 names,
3731 3731 uipathfn,
3732 3732 actions,
3733 3733 match,
3734 3734 interactive=False,
3735 3735 tobackup=None,
3736 3736 ):
3737 3737 """function that actually perform all the actions computed for revert
3738 3738
3739 3739 This is an independent function to let extension to plug in and react to
3740 3740 the imminent revert.
3741 3741
3742 3742 Make sure you have the working directory locked when calling this function.
3743 3743 """
3744 3744 parent, p2 = repo.dirstate.parents()
3745 3745 node = ctx.node()
3746 3746 excluded_files = []
3747 3747
3748 3748 def checkout(f):
3749 3749 fc = ctx[f]
3750 3750 repo.wwrite(f, fc.data(), fc.flags())
3751 3751
3752 3752 def doremove(f):
3753 3753 try:
3754 3754 rmdir = repo.ui.configbool(b'experimental', b'removeemptydirs')
3755 3755 repo.wvfs.unlinkpath(f, rmdir=rmdir)
3756 3756 except OSError:
3757 3757 pass
3758 3758 repo.dirstate.set_untracked(f)
3759 3759
3760 3760 def prntstatusmsg(action, f):
3761 3761 exact = names[f]
3762 3762 if repo.ui.verbose or not exact:
3763 3763 repo.ui.status(actions[action][1] % uipathfn(f))
3764 3764
3765 3765 audit_path = pathutil.pathauditor(repo.root, cached=True)
3766 3766 for f in actions[b'forget'][0]:
3767 3767 if interactive:
3768 3768 choice = repo.ui.promptchoice(
3769 3769 _(b"forget added file %s (Yn)?$$ &Yes $$ &No") % uipathfn(f)
3770 3770 )
3771 3771 if choice == 0:
3772 3772 prntstatusmsg(b'forget', f)
3773 3773 repo.dirstate.set_untracked(f)
3774 3774 else:
3775 3775 excluded_files.append(f)
3776 3776 else:
3777 3777 prntstatusmsg(b'forget', f)
3778 3778 repo.dirstate.set_untracked(f)
3779 3779 for f in actions[b'remove'][0]:
3780 3780 audit_path(f)
3781 3781 if interactive:
3782 3782 choice = repo.ui.promptchoice(
3783 3783 _(b"remove added file %s (Yn)?$$ &Yes $$ &No") % uipathfn(f)
3784 3784 )
3785 3785 if choice == 0:
3786 3786 prntstatusmsg(b'remove', f)
3787 3787 doremove(f)
3788 3788 else:
3789 3789 excluded_files.append(f)
3790 3790 else:
3791 3791 prntstatusmsg(b'remove', f)
3792 3792 doremove(f)
3793 3793 for f in actions[b'drop'][0]:
3794 3794 audit_path(f)
3795 3795 prntstatusmsg(b'drop', f)
3796 3796 repo.dirstate.set_untracked(f)
3797 3797
3798 3798 # We are reverting to our parent. If possible, we had like `hg status`
3799 3799 # to report the file as clean. We have to be less agressive for
3800 3800 # merges to avoid losing information about copy introduced by the merge.
3801 3801 # This might comes with bugs ?
3802 3802 reset_copy = p2 == repo.nullid
3803 3803
3804 3804 def normal(filename):
3805 3805 return repo.dirstate.set_tracked(filename, reset_copy=reset_copy)
3806 3806
3807 3807 newlyaddedandmodifiedfiles = set()
3808 3808 if interactive:
3809 3809 # Prompt the user for changes to revert
3810 3810 torevert = [f for f in actions[b'revert'][0] if f not in excluded_files]
3811 3811 m = scmutil.matchfiles(repo, torevert)
3812 3812 diffopts = patch.difffeatureopts(
3813 3813 repo.ui,
3814 3814 whitespace=True,
3815 3815 section=b'commands',
3816 3816 configprefix=b'revert.interactive.',
3817 3817 )
3818 3818 diffopts.nodates = True
3819 3819 diffopts.git = True
3820 3820 operation = b'apply'
3821 3821 if node == parent:
3822 3822 if repo.ui.configbool(
3823 3823 b'experimental', b'revert.interactive.select-to-keep'
3824 3824 ):
3825 3825 operation = b'keep'
3826 3826 else:
3827 3827 operation = b'discard'
3828 3828
3829 3829 if operation == b'apply':
3830 3830 diff = patch.diff(repo, None, ctx.node(), m, opts=diffopts)
3831 3831 else:
3832 3832 diff = patch.diff(repo, ctx.node(), None, m, opts=diffopts)
3833 3833 original_headers = patch.parsepatch(diff)
3834 3834
3835 3835 try:
3836 3836 chunks, opts = recordfilter(
3837 3837 repo.ui, original_headers, match, operation=operation
3838 3838 )
3839 3839 if operation == b'discard':
3840 3840 chunks = patch.reversehunks(chunks)
3841 3841
3842 3842 except error.PatchParseError as err:
3843 3843 raise error.InputError(_(b'error parsing patch: %s') % err)
3844 3844 except error.PatchApplicationError as err:
3845 3845 raise error.StateError(_(b'error applying patch: %s') % err)
3846 3846
3847 3847 # FIXME: when doing an interactive revert of a copy, there's no way of
3848 3848 # performing a partial revert of the added file, the only option is
3849 3849 # "remove added file <name> (Yn)?", so we don't need to worry about the
3850 3850 # alsorestore value. Ideally we'd be able to partially revert
3851 3851 # copied/renamed files.
3852 3852 newlyaddedandmodifiedfiles, unusedalsorestore = newandmodified(chunks)
3853 3853 if tobackup is None:
3854 3854 tobackup = set()
3855 3855 # Apply changes
3856 3856 fp = stringio()
3857 3857 # chunks are serialized per file, but files aren't sorted
3858 3858 for f in sorted({c.header.filename() for c in chunks if ishunk(c)}):
3859 3859 prntstatusmsg(b'revert', f)
3860 3860 files = set()
3861 3861 for c in chunks:
3862 3862 if ishunk(c):
3863 3863 abs = c.header.filename()
3864 3864 # Create a backup file only if this hunk should be backed up
3865 3865 if c.header.filename() in tobackup:
3866 3866 target = repo.wjoin(abs)
3867 3867 bakname = scmutil.backuppath(repo.ui, repo, abs)
3868 3868 util.copyfile(target, bakname)
3869 3869 tobackup.remove(abs)
3870 3870 if abs not in files:
3871 3871 files.add(abs)
3872 3872 if operation == b'keep':
3873 3873 checkout(abs)
3874 3874 c.write(fp)
3875 3875 dopatch = fp.tell()
3876 3876 fp.seek(0)
3877 3877 if dopatch:
3878 3878 try:
3879 3879 patch.internalpatch(repo.ui, repo, fp, 1, eolmode=None)
3880 3880 except error.PatchParseError as err:
3881 3881 raise error.InputError(pycompat.bytestr(err))
3882 3882 except error.PatchApplicationError as err:
3883 3883 raise error.StateError(pycompat.bytestr(err))
3884 3884 del fp
3885 3885 else:
3886 3886 for f in actions[b'revert'][0]:
3887 3887 prntstatusmsg(b'revert', f)
3888 3888 checkout(f)
3889 3889 if normal:
3890 3890 normal(f)
3891 3891
3892 3892 for f in actions[b'add'][0]:
3893 3893 # Don't checkout modified files, they are already created by the diff
3894 3894 if f in newlyaddedandmodifiedfiles:
3895 3895 continue
3896 3896
3897 3897 if interactive:
3898 3898 choice = repo.ui.promptchoice(
3899 3899 _(b"add new file %s (Yn)?$$ &Yes $$ &No") % uipathfn(f)
3900 3900 )
3901 3901 if choice != 0:
3902 3902 continue
3903 3903 prntstatusmsg(b'add', f)
3904 3904 checkout(f)
3905 3905 repo.dirstate.set_tracked(f)
3906 3906
3907 3907 for f in actions[b'undelete'][0]:
3908 3908 if interactive:
3909 3909 choice = repo.ui.promptchoice(
3910 3910 _(b"add back removed file %s (Yn)?$$ &Yes $$ &No") % f
3911 3911 )
3912 3912 if choice == 0:
3913 3913 prntstatusmsg(b'undelete', f)
3914 3914 checkout(f)
3915 3915 normal(f)
3916 3916 else:
3917 3917 excluded_files.append(f)
3918 3918 else:
3919 3919 prntstatusmsg(b'undelete', f)
3920 3920 checkout(f)
3921 3921 normal(f)
3922 3922
3923 3923 copied = copies.pathcopies(repo[parent], ctx)
3924 3924
3925 3925 for f in (
3926 3926 actions[b'add'][0] + actions[b'undelete'][0] + actions[b'revert'][0]
3927 3927 ):
3928 3928 if f in copied:
3929 3929 repo.dirstate.copy(copied[f], f)
3930 3930
3931 3931
3932 3932 # a list of (ui, repo, otherpeer, opts, missing) functions called by
3933 3933 # commands.outgoing. "missing" is "missing" of the result of
3934 3934 # "findcommonoutgoing()"
3935 3935 outgoinghooks = util.hooks()
3936 3936
3937 3937 # a list of (ui, repo) functions called by commands.summary
3938 3938 summaryhooks = util.hooks()
3939 3939
3940 3940 # a list of (ui, repo, opts, changes) functions called by commands.summary.
3941 3941 #
3942 3942 # functions should return tuple of booleans below, if 'changes' is None:
3943 3943 # (whether-incomings-are-needed, whether-outgoings-are-needed)
3944 3944 #
3945 3945 # otherwise, 'changes' is a tuple of tuples below:
3946 3946 # - (sourceurl, sourcebranch, sourcepeer, incoming)
3947 3947 # - (desturl, destbranch, destpeer, outgoing)
3948 3948 summaryremotehooks = util.hooks()
3949 3949
3950 3950
3951 3951 def checkunfinished(repo, commit=False, skipmerge=False):
3952 3952 """Look for an unfinished multistep operation, like graft, and abort
3953 3953 if found. It's probably good to check this right before
3954 3954 bailifchanged().
3955 3955 """
3956 3956 # Check for non-clearable states first, so things like rebase will take
3957 3957 # precedence over update.
3958 3958 for state in statemod._unfinishedstates:
3959 3959 if (
3960 3960 state._clearable
3961 3961 or (commit and state._allowcommit)
3962 3962 or state._reportonly
3963 3963 ):
3964 3964 continue
3965 3965 if state.isunfinished(repo):
3966 3966 raise error.StateError(state.msg(), hint=state.hint())
3967 3967
3968 3968 for s in statemod._unfinishedstates:
3969 3969 if (
3970 3970 not s._clearable
3971 3971 or (commit and s._allowcommit)
3972 3972 or (s._opname == b'merge' and skipmerge)
3973 3973 or s._reportonly
3974 3974 ):
3975 3975 continue
3976 3976 if s.isunfinished(repo):
3977 3977 raise error.StateError(s.msg(), hint=s.hint())
3978 3978
3979 3979
3980 3980 def clearunfinished(repo):
3981 3981 """Check for unfinished operations (as above), and clear the ones
3982 3982 that are clearable.
3983 3983 """
3984 3984 for state in statemod._unfinishedstates:
3985 3985 if state._reportonly:
3986 3986 continue
3987 3987 if not state._clearable and state.isunfinished(repo):
3988 3988 raise error.StateError(state.msg(), hint=state.hint())
3989 3989
3990 3990 for s in statemod._unfinishedstates:
3991 3991 if s._opname == b'merge' or s._reportonly:
3992 3992 continue
3993 3993 if s._clearable and s.isunfinished(repo):
3994 3994 util.unlink(repo.vfs.join(s._fname))
3995 3995
3996 3996
3997 3997 def getunfinishedstate(repo):
3998 3998 """Checks for unfinished operations and returns statecheck object
3999 3999 for it"""
4000 4000 for state in statemod._unfinishedstates:
4001 4001 if state.isunfinished(repo):
4002 4002 return state
4003 4003 return None
4004 4004
4005 4005
4006 4006 def howtocontinue(repo):
4007 4007 """Check for an unfinished operation and return the command to finish
4008 4008 it.
4009 4009
4010 4010 statemod._unfinishedstates list is checked for an unfinished operation
4011 4011 and the corresponding message to finish it is generated if a method to
4012 4012 continue is supported by the operation.
4013 4013
4014 4014 Returns a (msg, warning) tuple. 'msg' is a string and 'warning' is
4015 4015 a boolean.
4016 4016 """
4017 4017 contmsg = _(b"continue: %s")
4018 4018 for state in statemod._unfinishedstates:
4019 4019 if not state._continueflag:
4020 4020 continue
4021 4021 if state.isunfinished(repo):
4022 4022 return contmsg % state.continuemsg(), True
4023 4023 if repo[None].dirty(missing=True, merge=False, branch=False):
4024 4024 return contmsg % _(b"hg commit"), False
4025 4025 return None, None
4026 4026
4027 4027
4028 4028 def checkafterresolved(repo):
4029 4029 """Inform the user about the next action after completing hg resolve
4030 4030
4031 4031 If there's a an unfinished operation that supports continue flag,
4032 4032 howtocontinue will yield repo.ui.warn as the reporter.
4033 4033
4034 4034 Otherwise, it will yield repo.ui.note.
4035 4035 """
4036 4036 msg, warning = howtocontinue(repo)
4037 4037 if msg is not None:
4038 4038 if warning:
4039 4039 repo.ui.warn(b"%s\n" % msg)
4040 4040 else:
4041 4041 repo.ui.note(b"%s\n" % msg)
4042 4042
4043 4043
4044 4044 def wrongtooltocontinue(repo, task):
4045 4045 """Raise an abort suggesting how to properly continue if there is an
4046 4046 active task.
4047 4047
4048 4048 Uses howtocontinue() to find the active task.
4049 4049
4050 4050 If there's no task (repo.ui.note for 'hg commit'), it does not offer
4051 4051 a hint.
4052 4052 """
4053 4053 after = howtocontinue(repo)
4054 4054 hint = None
4055 4055 if after[1]:
4056 4056 hint = after[0]
4057 4057 raise error.StateError(_(b'no %s in progress') % task, hint=hint)
4058 4058
4059 4059
4060 4060 def abortgraft(ui, repo, graftstate):
4061 4061 """abort the interrupted graft and rollbacks to the state before interrupted
4062 4062 graft"""
4063 4063 if not graftstate.exists():
4064 4064 raise error.StateError(_(b"no interrupted graft to abort"))
4065 4065 statedata = readgraftstate(repo, graftstate)
4066 4066 newnodes = statedata.get(b'newnodes')
4067 4067 if newnodes is None:
4068 4068 # and old graft state which does not have all the data required to abort
4069 4069 # the graft
4070 4070 raise error.Abort(_(b"cannot abort using an old graftstate"))
4071 4071
4072 4072 # changeset from which graft operation was started
4073 4073 if len(newnodes) > 0:
4074 4074 startctx = repo[newnodes[0]].p1()
4075 4075 else:
4076 4076 startctx = repo[b'.']
4077 4077 # whether to strip or not
4078 4078 cleanup = False
4079 4079
4080 4080 if newnodes:
4081 4081 newnodes = [repo[r].rev() for r in newnodes]
4082 4082 cleanup = True
4083 4083 # checking that none of the newnodes turned public or is public
4084 4084 immutable = [c for c in newnodes if not repo[c].mutable()]
4085 4085 if immutable:
4086 4086 repo.ui.warn(
4087 4087 _(b"cannot clean up public changesets %s\n")
4088 4088 % b', '.join(bytes(repo[r]) for r in immutable),
4089 4089 hint=_(b"see 'hg help phases' for details"),
4090 4090 )
4091 4091 cleanup = False
4092 4092
4093 4093 # checking that no new nodes are created on top of grafted revs
4094 4094 desc = set(repo.changelog.descendants(newnodes))
4095 4095 if desc - set(newnodes):
4096 4096 repo.ui.warn(
4097 4097 _(
4098 4098 b"new changesets detected on destination "
4099 4099 b"branch, can't strip\n"
4100 4100 )
4101 4101 )
4102 4102 cleanup = False
4103 4103
4104 4104 if cleanup:
4105 4105 with repo.wlock(), repo.lock():
4106 4106 mergemod.clean_update(startctx)
4107 4107 # stripping the new nodes created
4108 4108 strippoints = [
4109 4109 c.node() for c in repo.set(b"roots(%ld)", newnodes)
4110 4110 ]
4111 4111 repair.strip(repo.ui, repo, strippoints, backup=False)
4112 4112
4113 4113 if not cleanup:
4114 4114 # we don't update to the startnode if we can't strip
4115 4115 startctx = repo[b'.']
4116 4116 mergemod.clean_update(startctx)
4117 4117
4118 4118 ui.status(_(b"graft aborted\n"))
4119 4119 ui.status(_(b"working directory is now at %s\n") % startctx.hex()[:12])
4120 4120 graftstate.delete()
4121 4121 return 0
4122 4122
4123 4123
4124 4124 def readgraftstate(
4125 4125 repo: Any,
4126 4126 graftstate: statemod.cmdstate,
4127 4127 ) -> Dict[bytes, Any]:
4128 4128 """read the graft state file and return a dict of the data stored in it"""
4129 4129 try:
4130 4130 return graftstate.read()
4131 4131 except error.CorruptedState:
4132 4132 nodes = repo.vfs.read(b'graftstate').splitlines()
4133 4133 return {b'nodes': nodes}
4134 4134
4135 4135
4136 4136 def hgabortgraft(ui, repo):
4137 4137 """abort logic for aborting graft using 'hg abort'"""
4138 4138 with repo.wlock():
4139 4139 graftstate = statemod.cmdstate(repo, b'graftstate')
4140 4140 return abortgraft(ui, repo, graftstate)
4141 4141
4142 4142
4143 4143 def postincoming(ui, repo, modheads, optupdate, checkout, brev):
4144 4144 """Run after a changegroup has been added via pull/unbundle
4145 4145
4146 4146 This takes arguments below:
4147 4147
4148 4148 :modheads: change of heads by pull/unbundle
4149 4149 :optupdate: updating working directory is needed or not
4150 4150 :checkout: update destination revision (or None to default destination)
4151 4151 :brev: a name, which might be a bookmark to be activated after updating
4152 4152
4153 4153 return True if update raise any conflict, False otherwise.
4154 4154 """
4155 4155 if modheads == 0:
4156 4156 return False
4157 4157 if optupdate:
4158 4158 # avoid circular import
4159 4159 from . import hg
4160 4160
4161 4161 try:
4162 4162 return hg.updatetotally(ui, repo, checkout, brev)
4163 4163 except error.UpdateAbort as inst:
4164 4164 msg = _(b"not updating: %s") % stringutil.forcebytestr(inst)
4165 4165 hint = inst.hint
4166 4166 raise error.UpdateAbort(msg, hint=hint)
4167 4167 if ui.quiet:
4168 4168 pass # we won't report anything so the other clause are useless.
4169 4169 elif modheads is not None and modheads > 1:
4170 4170 currentbranchheads = len(repo.branchheads())
4171 4171 if currentbranchheads == modheads:
4172 4172 ui.status(
4173 4173 _(b"(run 'hg heads' to see heads, 'hg merge' to merge)\n")
4174 4174 )
4175 4175 elif currentbranchheads > 1:
4176 4176 ui.status(
4177 4177 _(b"(run 'hg heads .' to see heads, 'hg merge' to merge)\n")
4178 4178 )
4179 4179 else:
4180 4180 ui.status(_(b"(run 'hg heads' to see heads)\n"))
4181 4181 elif not ui.configbool(b'commands', b'update.requiredest'):
4182 4182 ui.status(_(b"(run 'hg update' to get a working copy)\n"))
4183 4183 return False
4184 4184
4185 4185
4186 4186 def unbundle_files(ui, repo, fnames, unbundle_source=b'unbundle'):
4187 4187 """utility for `hg unbundle` and `hg debug::unbundle`"""
4188 4188 assert fnames
4189 4189 # avoid circular import
4190 4190 from . import hg
4191 4191
4192 4192 with repo.lock():
4193 4193 for fname in fnames:
4194 4194 f = hg.openpath(ui, fname)
4195 4195 gen = exchange.readbundle(ui, f, fname)
4196 4196 if isinstance(gen, streamclone.streamcloneapplier):
4197 4197 raise error.InputError(
4198 4198 _(
4199 4199 b'packed bundles cannot be applied with '
4200 4200 b'"hg unbundle"'
4201 4201 ),
4202 4202 hint=_(b'use "hg debugapplystreamclonebundle"'),
4203 4203 )
4204 4204 url = b'bundle:' + fname
4205 4205 try:
4206 4206 txnname = b'unbundle'
4207 4207 if not isinstance(gen, bundle2.unbundle20):
4208 4208 txnname = b'unbundle\n%s' % urlutil.hidepassword(url)
4209 4209 with repo.transaction(txnname) as tr:
4210 4210 op = bundle2.applybundle(
4211 4211 repo,
4212 4212 gen,
4213 4213 tr,
4214 4214 source=unbundle_source, # used by debug::unbundle
4215 4215 url=url,
4216 4216 )
4217 4217 except error.BundleUnknownFeatureError as exc:
4218 4218 raise error.Abort(
4219 4219 _(b'%s: unknown bundle feature, %s') % (fname, exc),
4220 4220 hint=_(
4221 4221 b"see https://mercurial-scm.org/"
4222 4222 b"wiki/BundleFeature for more "
4223 4223 b"information"
4224 4224 ),
4225 4225 )
4226 4226 modheads = bundle2.combinechangegroupresults(op)
4227 4227 return modheads
General Comments 0
You need to be logged in to leave comments. Login now