##// END OF EJS Templates
path: pass `path` to `peer` in `hg histedit`...
marmoute -
r50607:905eb32f default
parent child Browse files
Show More
@@ -1,2683 +1,2682 b''
1 1 # histedit.py - interactive history editing for mercurial
2 2 #
3 3 # Copyright 2009 Augie Fackler <raf@durin42.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 """interactive history editing
8 8
9 9 With this extension installed, Mercurial gains one new command: histedit. Usage
10 10 is as follows, assuming the following history::
11 11
12 12 @ 3[tip] 7c2fd3b9020c 2009-04-27 18:04 -0500 durin42
13 13 | Add delta
14 14 |
15 15 o 2 030b686bedc4 2009-04-27 18:04 -0500 durin42
16 16 | Add gamma
17 17 |
18 18 o 1 c561b4e977df 2009-04-27 18:04 -0500 durin42
19 19 | Add beta
20 20 |
21 21 o 0 d8d2fcd0e319 2009-04-27 18:04 -0500 durin42
22 22 Add alpha
23 23
24 24 If you were to run ``hg histedit c561b4e977df``, you would see the following
25 25 file open in your editor::
26 26
27 27 pick c561b4e977df Add beta
28 28 pick 030b686bedc4 Add gamma
29 29 pick 7c2fd3b9020c Add delta
30 30
31 31 # Edit history between c561b4e977df and 7c2fd3b9020c
32 32 #
33 33 # Commits are listed from least to most recent
34 34 #
35 35 # Commands:
36 36 # p, pick = use commit
37 37 # e, edit = use commit, but allow edits before making new commit
38 38 # f, fold = use commit, but combine it with the one above
39 39 # r, roll = like fold, but discard this commit's description and date
40 40 # d, drop = remove commit from history
41 41 # m, mess = edit commit message without changing commit content
42 42 # b, base = checkout changeset and apply further changesets from there
43 43 #
44 44
45 45 In this file, lines beginning with ``#`` are ignored. You must specify a rule
46 46 for each revision in your history. For example, if you had meant to add gamma
47 47 before beta, and then wanted to add delta in the same revision as beta, you
48 48 would reorganize the file to look like this::
49 49
50 50 pick 030b686bedc4 Add gamma
51 51 pick c561b4e977df Add beta
52 52 fold 7c2fd3b9020c Add delta
53 53
54 54 # Edit history between c561b4e977df and 7c2fd3b9020c
55 55 #
56 56 # Commits are listed from least to most recent
57 57 #
58 58 # Commands:
59 59 # p, pick = use commit
60 60 # e, edit = use commit, but allow edits before making new commit
61 61 # f, fold = use commit, but combine it with the one above
62 62 # r, roll = like fold, but discard this commit's description and date
63 63 # d, drop = remove commit from history
64 64 # m, mess = edit commit message without changing commit content
65 65 # b, base = checkout changeset and apply further changesets from there
66 66 #
67 67
68 68 At which point you close the editor and ``histedit`` starts working. When you
69 69 specify a ``fold`` operation, ``histedit`` will open an editor when it folds
70 70 those revisions together, offering you a chance to clean up the commit message::
71 71
72 72 Add beta
73 73 ***
74 74 Add delta
75 75
76 76 Edit the commit message to your liking, then close the editor. The date used
77 77 for the commit will be the later of the two commits' dates. For this example,
78 78 let's assume that the commit message was changed to ``Add beta and delta.``
79 79 After histedit has run and had a chance to remove any old or temporary
80 80 revisions it needed, the history looks like this::
81 81
82 82 @ 2[tip] 989b4d060121 2009-04-27 18:04 -0500 durin42
83 83 | Add beta and delta.
84 84 |
85 85 o 1 081603921c3f 2009-04-27 18:04 -0500 durin42
86 86 | Add gamma
87 87 |
88 88 o 0 d8d2fcd0e319 2009-04-27 18:04 -0500 durin42
89 89 Add alpha
90 90
91 91 Note that ``histedit`` does *not* remove any revisions (even its own temporary
92 92 ones) until after it has completed all the editing operations, so it will
93 93 probably perform several strip operations when it's done. For the above example,
94 94 it had to run strip twice. Strip can be slow depending on a variety of factors,
95 95 so you might need to be a little patient. You can choose to keep the original
96 96 revisions by passing the ``--keep`` flag.
97 97
98 98 The ``edit`` operation will drop you back to a command prompt,
99 99 allowing you to edit files freely, or even use ``hg record`` to commit
100 100 some changes as a separate commit. When you're done, any remaining
101 101 uncommitted changes will be committed as well. When done, run ``hg
102 102 histedit --continue`` to finish this step. If there are uncommitted
103 103 changes, you'll be prompted for a new commit message, but the default
104 104 commit message will be the original message for the ``edit`` ed
105 105 revision, and the date of the original commit will be preserved.
106 106
107 107 The ``message`` operation will give you a chance to revise a commit
108 108 message without changing the contents. It's a shortcut for doing
109 109 ``edit`` immediately followed by `hg histedit --continue``.
110 110
111 111 If ``histedit`` encounters a conflict when moving a revision (while
112 112 handling ``pick`` or ``fold``), it'll stop in a similar manner to
113 113 ``edit`` with the difference that it won't prompt you for a commit
114 114 message when done. If you decide at this point that you don't like how
115 115 much work it will be to rearrange history, or that you made a mistake,
116 116 you can use ``hg histedit --abort`` to abandon the new changes you
117 117 have made and return to the state before you attempted to edit your
118 118 history.
119 119
120 120 If we clone the histedit-ed example repository above and add four more
121 121 changes, such that we have the following history::
122 122
123 123 @ 6[tip] 038383181893 2009-04-27 18:04 -0500 stefan
124 124 | Add theta
125 125 |
126 126 o 5 140988835471 2009-04-27 18:04 -0500 stefan
127 127 | Add eta
128 128 |
129 129 o 4 122930637314 2009-04-27 18:04 -0500 stefan
130 130 | Add zeta
131 131 |
132 132 o 3 836302820282 2009-04-27 18:04 -0500 stefan
133 133 | Add epsilon
134 134 |
135 135 o 2 989b4d060121 2009-04-27 18:04 -0500 durin42
136 136 | Add beta and delta.
137 137 |
138 138 o 1 081603921c3f 2009-04-27 18:04 -0500 durin42
139 139 | Add gamma
140 140 |
141 141 o 0 d8d2fcd0e319 2009-04-27 18:04 -0500 durin42
142 142 Add alpha
143 143
144 144 If you run ``hg histedit --outgoing`` on the clone then it is the same
145 145 as running ``hg histedit 836302820282``. If you need plan to push to a
146 146 repository that Mercurial does not detect to be related to the source
147 147 repo, you can add a ``--force`` option.
148 148
149 149 Config
150 150 ------
151 151
152 152 Histedit rule lines are truncated to 80 characters by default. You
153 153 can customize this behavior by setting a different length in your
154 154 configuration file::
155 155
156 156 [histedit]
157 157 linelen = 120 # truncate rule lines at 120 characters
158 158
159 159 The summary of a change can be customized as well::
160 160
161 161 [histedit]
162 162 summary-template = '{rev} {bookmarks} {desc|firstline}'
163 163
164 164 The customized summary should be kept short enough that rule lines
165 165 will fit in the configured line length. See above if that requires
166 166 customization.
167 167
168 168 ``hg histedit`` attempts to automatically choose an appropriate base
169 169 revision to use. To change which base revision is used, define a
170 170 revset in your configuration file::
171 171
172 172 [histedit]
173 173 defaultrev = only(.) & draft()
174 174
175 175 By default each edited revision needs to be present in histedit commands.
176 176 To remove revision you need to use ``drop`` operation. You can configure
177 177 the drop to be implicit for missing commits by adding::
178 178
179 179 [histedit]
180 180 dropmissing = True
181 181
182 182 By default, histedit will close the transaction after each action. For
183 183 performance purposes, you can configure histedit to use a single transaction
184 184 across the entire histedit. WARNING: This setting introduces a significant risk
185 185 of losing the work you've done in a histedit if the histedit aborts
186 186 unexpectedly::
187 187
188 188 [histedit]
189 189 singletransaction = True
190 190
191 191 """
192 192
193 193
194 194 # chistedit dependencies that are not available everywhere
195 195 try:
196 196 import fcntl
197 197 import termios
198 198 except ImportError:
199 199 fcntl = None
200 200 termios = None
201 201
202 202 import binascii
203 203 import functools
204 204 import os
205 205 import pickle
206 206 import struct
207 207
208 208 from mercurial.i18n import _
209 209 from mercurial.pycompat import (
210 210 getattr,
211 211 open,
212 212 )
213 213 from mercurial.node import (
214 214 bin,
215 215 hex,
216 216 short,
217 217 )
218 218 from mercurial import (
219 219 bundle2,
220 220 cmdutil,
221 221 context,
222 222 copies,
223 223 destutil,
224 224 discovery,
225 225 encoding,
226 226 error,
227 227 exchange,
228 228 extensions,
229 229 hg,
230 230 logcmdutil,
231 231 merge as mergemod,
232 232 mergestate as mergestatemod,
233 233 mergeutil,
234 234 obsolete,
235 235 pycompat,
236 236 registrar,
237 237 repair,
238 238 rewriteutil,
239 239 scmutil,
240 240 state as statemod,
241 241 util,
242 242 )
243 243 from mercurial.utils import (
244 244 dateutil,
245 245 stringutil,
246 246 urlutil,
247 247 )
248 248
249 249 cmdtable = {}
250 250 command = registrar.command(cmdtable)
251 251
252 252 configtable = {}
253 253 configitem = registrar.configitem(configtable)
254 254 configitem(
255 255 b'experimental',
256 256 b'histedit.autoverb',
257 257 default=False,
258 258 )
259 259 configitem(
260 260 b'histedit',
261 261 b'defaultrev',
262 262 default=None,
263 263 )
264 264 configitem(
265 265 b'histedit',
266 266 b'dropmissing',
267 267 default=False,
268 268 )
269 269 configitem(
270 270 b'histedit',
271 271 b'linelen',
272 272 default=80,
273 273 )
274 274 configitem(
275 275 b'histedit',
276 276 b'singletransaction',
277 277 default=False,
278 278 )
279 279 configitem(
280 280 b'ui',
281 281 b'interface.histedit',
282 282 default=None,
283 283 )
284 284 configitem(b'histedit', b'summary-template', default=b'{rev} {desc|firstline}')
285 285 # TODO: Teach the text-based histedit interface to respect this config option
286 286 # before we make it non-experimental.
287 287 configitem(
288 288 b'histedit', b'later-commits-first', default=False, experimental=True
289 289 )
290 290
291 291 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
292 292 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
293 293 # be specifying the version(s) of Mercurial they are tested with, or
294 294 # leave the attribute unspecified.
295 295 testedwith = b'ships-with-hg-core'
296 296
297 297 actiontable = {}
298 298 primaryactions = set()
299 299 secondaryactions = set()
300 300 tertiaryactions = set()
301 301 internalactions = set()
302 302
303 303
304 304 def geteditcomment(ui, first, last):
305 305 """construct the editor comment
306 306 The comment includes::
307 307 - an intro
308 308 - sorted primary commands
309 309 - sorted short commands
310 310 - sorted long commands
311 311 - additional hints
312 312
313 313 Commands are only included once.
314 314 """
315 315 intro = _(
316 316 b"""Edit history between %s and %s
317 317
318 318 Commits are listed from least to most recent
319 319
320 320 You can reorder changesets by reordering the lines
321 321
322 322 Commands:
323 323 """
324 324 )
325 325 actions = []
326 326
327 327 def addverb(v):
328 328 a = actiontable[v]
329 329 lines = a.message.split(b"\n")
330 330 if len(a.verbs):
331 331 v = b', '.join(sorted(a.verbs, key=lambda v: len(v)))
332 332 actions.append(b" %s = %s" % (v, lines[0]))
333 333 actions.extend([b' %s'] * (len(lines) - 1))
334 334
335 335 for v in (
336 336 sorted(primaryactions)
337 337 + sorted(secondaryactions)
338 338 + sorted(tertiaryactions)
339 339 ):
340 340 addverb(v)
341 341 actions.append(b'')
342 342
343 343 hints = []
344 344 if ui.configbool(b'histedit', b'dropmissing'):
345 345 hints.append(
346 346 b"Deleting a changeset from the list "
347 347 b"will DISCARD it from the edited history!"
348 348 )
349 349
350 350 lines = (intro % (first, last)).split(b'\n') + actions + hints
351 351
352 352 return b''.join([b'# %s\n' % l if l else b'#\n' for l in lines])
353 353
354 354
355 355 class histeditstate:
356 356 def __init__(self, repo):
357 357 self.repo = repo
358 358 self.actions = None
359 359 self.keep = None
360 360 self.topmost = None
361 361 self.parentctxnode = None
362 362 self.lock = None
363 363 self.wlock = None
364 364 self.backupfile = None
365 365 self.stateobj = statemod.cmdstate(repo, b'histedit-state')
366 366 self.replacements = []
367 367
368 368 def read(self):
369 369 """Load histedit state from disk and set fields appropriately."""
370 370 if not self.stateobj.exists():
371 371 cmdutil.wrongtooltocontinue(self.repo, _(b'histedit'))
372 372
373 373 data = self._read()
374 374
375 375 self.parentctxnode = data[b'parentctxnode']
376 376 actions = parserules(data[b'rules'], self)
377 377 self.actions = actions
378 378 self.keep = data[b'keep']
379 379 self.topmost = data[b'topmost']
380 380 self.replacements = data[b'replacements']
381 381 self.backupfile = data[b'backupfile']
382 382
383 383 def _read(self):
384 384 fp = self.repo.vfs.read(b'histedit-state')
385 385 if fp.startswith(b'v1\n'):
386 386 data = self._load()
387 387 parentctxnode, rules, keep, topmost, replacements, backupfile = data
388 388 else:
389 389 data = pickle.loads(fp)
390 390 parentctxnode, rules, keep, topmost, replacements = data
391 391 backupfile = None
392 392 rules = b"\n".join([b"%s %s" % (verb, rest) for [verb, rest] in rules])
393 393
394 394 return {
395 395 b'parentctxnode': parentctxnode,
396 396 b"rules": rules,
397 397 b"keep": keep,
398 398 b"topmost": topmost,
399 399 b"replacements": replacements,
400 400 b"backupfile": backupfile,
401 401 }
402 402
403 403 def write(self, tr=None):
404 404 if tr:
405 405 tr.addfilegenerator(
406 406 b'histedit-state',
407 407 (b'histedit-state',),
408 408 self._write,
409 409 location=b'plain',
410 410 )
411 411 else:
412 412 with self.repo.vfs(b"histedit-state", b"w") as f:
413 413 self._write(f)
414 414
415 415 def _write(self, fp):
416 416 fp.write(b'v1\n')
417 417 fp.write(b'%s\n' % hex(self.parentctxnode))
418 418 fp.write(b'%s\n' % hex(self.topmost))
419 419 fp.write(b'%s\n' % (b'True' if self.keep else b'False'))
420 420 fp.write(b'%d\n' % len(self.actions))
421 421 for action in self.actions:
422 422 fp.write(b'%s\n' % action.tostate())
423 423 fp.write(b'%d\n' % len(self.replacements))
424 424 for replacement in self.replacements:
425 425 fp.write(
426 426 b'%s%s\n'
427 427 % (
428 428 hex(replacement[0]),
429 429 b''.join(hex(r) for r in replacement[1]),
430 430 )
431 431 )
432 432 backupfile = self.backupfile
433 433 if not backupfile:
434 434 backupfile = b''
435 435 fp.write(b'%s\n' % backupfile)
436 436
437 437 def _load(self):
438 438 fp = self.repo.vfs(b'histedit-state', b'r')
439 439 lines = [l[:-1] for l in fp.readlines()]
440 440
441 441 index = 0
442 442 lines[index] # version number
443 443 index += 1
444 444
445 445 parentctxnode = bin(lines[index])
446 446 index += 1
447 447
448 448 topmost = bin(lines[index])
449 449 index += 1
450 450
451 451 keep = lines[index] == b'True'
452 452 index += 1
453 453
454 454 # Rules
455 455 rules = []
456 456 rulelen = int(lines[index])
457 457 index += 1
458 458 for i in range(rulelen):
459 459 ruleaction = lines[index]
460 460 index += 1
461 461 rule = lines[index]
462 462 index += 1
463 463 rules.append((ruleaction, rule))
464 464
465 465 # Replacements
466 466 replacements = []
467 467 replacementlen = int(lines[index])
468 468 index += 1
469 469 for i in range(replacementlen):
470 470 replacement = lines[index]
471 471 original = bin(replacement[:40])
472 472 succ = [
473 473 bin(replacement[i : i + 40])
474 474 for i in range(40, len(replacement), 40)
475 475 ]
476 476 replacements.append((original, succ))
477 477 index += 1
478 478
479 479 backupfile = lines[index]
480 480 index += 1
481 481
482 482 fp.close()
483 483
484 484 return parentctxnode, rules, keep, topmost, replacements, backupfile
485 485
486 486 def clear(self):
487 487 if self.inprogress():
488 488 self.repo.vfs.unlink(b'histedit-state')
489 489
490 490 def inprogress(self):
491 491 return self.repo.vfs.exists(b'histedit-state')
492 492
493 493
494 494 class histeditaction:
495 495 def __init__(self, state, node):
496 496 self.state = state
497 497 self.repo = state.repo
498 498 self.node = node
499 499
500 500 @classmethod
501 501 def fromrule(cls, state, rule):
502 502 """Parses the given rule, returning an instance of the histeditaction."""
503 503 ruleid = rule.strip().split(b' ', 1)[0]
504 504 # ruleid can be anything from rev numbers, hashes, "bookmarks" etc
505 505 # Check for validation of rule ids and get the rulehash
506 506 try:
507 507 rev = bin(ruleid)
508 508 except binascii.Error:
509 509 try:
510 510 _ctx = scmutil.revsingle(state.repo, ruleid)
511 511 rulehash = _ctx.hex()
512 512 rev = bin(rulehash)
513 513 except error.RepoLookupError:
514 514 raise error.ParseError(_(b"invalid changeset %s") % ruleid)
515 515 return cls(state, rev)
516 516
517 517 def verify(self, prev, expected, seen):
518 518 """Verifies semantic correctness of the rule"""
519 519 repo = self.repo
520 520 ha = hex(self.node)
521 521 self.node = scmutil.resolvehexnodeidprefix(repo, ha)
522 522 if self.node is None:
523 523 raise error.ParseError(_(b'unknown changeset %s listed') % ha[:12])
524 524 self._verifynodeconstraints(prev, expected, seen)
525 525
526 526 def _verifynodeconstraints(self, prev, expected, seen):
527 527 # by default command need a node in the edited list
528 528 if self.node not in expected:
529 529 raise error.ParseError(
530 530 _(b'%s "%s" changeset was not a candidate')
531 531 % (self.verb, short(self.node)),
532 532 hint=_(b'only use listed changesets'),
533 533 )
534 534 # and only one command per node
535 535 if self.node in seen:
536 536 raise error.ParseError(
537 537 _(b'duplicated command for changeset %s') % short(self.node)
538 538 )
539 539
540 540 def torule(self):
541 541 """build a histedit rule line for an action
542 542
543 543 by default lines are in the form:
544 544 <hash> <rev> <summary>
545 545 """
546 546 ctx = self.repo[self.node]
547 547 ui = self.repo.ui
548 548 # We don't want color codes in the commit message template, so
549 549 # disable the label() template function while we render it.
550 550 with ui.configoverride(
551 551 {(b'templatealias', b'label(l,x)'): b"x"}, b'histedit'
552 552 ):
553 553 summary = cmdutil.rendertemplate(
554 554 ctx, ui.config(b'histedit', b'summary-template')
555 555 )
556 556 line = b'%s %s %s' % (self.verb, ctx, stringutil.firstline(summary))
557 557 # trim to 75 columns by default so it's not stupidly wide in my editor
558 558 # (the 5 more are left for verb)
559 559 maxlen = self.repo.ui.configint(b'histedit', b'linelen')
560 560 maxlen = max(maxlen, 22) # avoid truncating hash
561 561 return stringutil.ellipsis(line, maxlen)
562 562
563 563 def tostate(self):
564 564 """Print an action in format used by histedit state files
565 565 (the first line is a verb, the remainder is the second)
566 566 """
567 567 return b"%s\n%s" % (self.verb, hex(self.node))
568 568
569 569 def run(self):
570 570 """Runs the action. The default behavior is simply apply the action's
571 571 rulectx onto the current parentctx."""
572 572 self.applychange()
573 573 self.continuedirty()
574 574 return self.continueclean()
575 575
576 576 def applychange(self):
577 577 """Applies the changes from this action's rulectx onto the current
578 578 parentctx, but does not commit them."""
579 579 repo = self.repo
580 580 rulectx = repo[self.node]
581 581 with repo.ui.silent():
582 582 hg.update(repo, self.state.parentctxnode, quietempty=True)
583 583 stats = applychanges(repo.ui, repo, rulectx, {})
584 584 repo.dirstate.setbranch(rulectx.branch())
585 585 if stats.unresolvedcount:
586 586 raise error.InterventionRequired(
587 587 _(b'Fix up the change (%s %s)') % (self.verb, short(self.node)),
588 588 hint=_(b'hg histedit --continue to resume'),
589 589 )
590 590
591 591 def continuedirty(self):
592 592 """Continues the action when changes have been applied to the working
593 593 copy. The default behavior is to commit the dirty changes."""
594 594 repo = self.repo
595 595 rulectx = repo[self.node]
596 596
597 597 editor = self.commiteditor()
598 598 commit = commitfuncfor(repo, rulectx)
599 599 if repo.ui.configbool(b'rewrite', b'update-timestamp'):
600 600 date = dateutil.makedate()
601 601 else:
602 602 date = rulectx.date()
603 603 commit(
604 604 text=rulectx.description(),
605 605 user=rulectx.user(),
606 606 date=date,
607 607 extra=rulectx.extra(),
608 608 editor=editor,
609 609 )
610 610
611 611 def commiteditor(self):
612 612 """The editor to be used to edit the commit message."""
613 613 return False
614 614
615 615 def continueclean(self):
616 616 """Continues the action when the working copy is clean. The default
617 617 behavior is to accept the current commit as the new version of the
618 618 rulectx."""
619 619 ctx = self.repo[b'.']
620 620 if ctx.node() == self.state.parentctxnode:
621 621 self.repo.ui.warn(
622 622 _(b'%s: skipping changeset (no changes)\n') % short(self.node)
623 623 )
624 624 return ctx, [(self.node, tuple())]
625 625 if ctx.node() == self.node:
626 626 # Nothing changed
627 627 return ctx, []
628 628 return ctx, [(self.node, (ctx.node(),))]
629 629
630 630
631 631 def commitfuncfor(repo, src):
632 632 """Build a commit function for the replacement of <src>
633 633
634 634 This function ensure we apply the same treatment to all changesets.
635 635
636 636 - Add a 'histedit_source' entry in extra.
637 637
638 638 Note that fold has its own separated logic because its handling is a bit
639 639 different and not easily factored out of the fold method.
640 640 """
641 641 phasemin = src.phase()
642 642
643 643 def commitfunc(**kwargs):
644 644 overrides = {(b'phases', b'new-commit'): phasemin}
645 645 with repo.ui.configoverride(overrides, b'histedit'):
646 646 extra = kwargs.get('extra', {}).copy()
647 647 extra[b'histedit_source'] = src.hex()
648 648 kwargs['extra'] = extra
649 649 return repo.commit(**kwargs)
650 650
651 651 return commitfunc
652 652
653 653
654 654 def applychanges(ui, repo, ctx, opts):
655 655 """Merge changeset from ctx (only) in the current working directory"""
656 656 if ctx.p1().node() == repo.dirstate.p1():
657 657 # edits are "in place" we do not need to make any merge,
658 658 # just applies changes on parent for editing
659 659 with ui.silent():
660 660 cmdutil.revert(ui, repo, ctx, all=True)
661 661 stats = mergemod.updateresult(0, 0, 0, 0)
662 662 else:
663 663 try:
664 664 # ui.forcemerge is an internal variable, do not document
665 665 repo.ui.setconfig(
666 666 b'ui', b'forcemerge', opts.get(b'tool', b''), b'histedit'
667 667 )
668 668 stats = mergemod.graft(
669 669 repo,
670 670 ctx,
671 671 labels=[
672 672 b'already edited',
673 673 b'current change',
674 674 b'parent of current change',
675 675 ],
676 676 )
677 677 finally:
678 678 repo.ui.setconfig(b'ui', b'forcemerge', b'', b'histedit')
679 679 return stats
680 680
681 681
682 682 def collapse(repo, firstctx, lastctx, commitopts, skipprompt=False):
683 683 """collapse the set of revisions from first to last as new one.
684 684
685 685 Expected commit options are:
686 686 - message
687 687 - date
688 688 - username
689 689 Commit message is edited in all cases.
690 690
691 691 This function works in memory."""
692 692 ctxs = list(repo.set(b'%d::%d', firstctx.rev(), lastctx.rev()))
693 693 if not ctxs:
694 694 return None
695 695 for c in ctxs:
696 696 if not c.mutable():
697 697 raise error.ParseError(
698 698 _(b"cannot fold into public change %s") % short(c.node())
699 699 )
700 700 base = firstctx.p1()
701 701
702 702 # commit a new version of the old changeset, including the update
703 703 # collect all files which might be affected
704 704 files = set()
705 705 for ctx in ctxs:
706 706 files.update(ctx.files())
707 707
708 708 # Recompute copies (avoid recording a -> b -> a)
709 709 copied = copies.pathcopies(base, lastctx)
710 710
711 711 # prune files which were reverted by the updates
712 712 files = [f for f in files if not cmdutil.samefile(f, lastctx, base)]
713 713 # commit version of these files as defined by head
714 714 headmf = lastctx.manifest()
715 715
716 716 def filectxfn(repo, ctx, path):
717 717 if path in headmf:
718 718 fctx = lastctx[path]
719 719 flags = fctx.flags()
720 720 mctx = context.memfilectx(
721 721 repo,
722 722 ctx,
723 723 fctx.path(),
724 724 fctx.data(),
725 725 islink=b'l' in flags,
726 726 isexec=b'x' in flags,
727 727 copysource=copied.get(path),
728 728 )
729 729 return mctx
730 730 return None
731 731
732 732 if commitopts.get(b'message'):
733 733 message = commitopts[b'message']
734 734 else:
735 735 message = firstctx.description()
736 736 user = commitopts.get(b'user')
737 737 date = commitopts.get(b'date')
738 738 extra = commitopts.get(b'extra')
739 739
740 740 parents = (firstctx.p1().node(), firstctx.p2().node())
741 741 editor = None
742 742 if not skipprompt:
743 743 editor = cmdutil.getcommiteditor(edit=True, editform=b'histedit.fold')
744 744 new = context.memctx(
745 745 repo,
746 746 parents=parents,
747 747 text=message,
748 748 files=files,
749 749 filectxfn=filectxfn,
750 750 user=user,
751 751 date=date,
752 752 extra=extra,
753 753 editor=editor,
754 754 )
755 755 return repo.commitctx(new)
756 756
757 757
758 758 def _isdirtywc(repo):
759 759 return repo[None].dirty(missing=True)
760 760
761 761
762 762 def abortdirty():
763 763 raise error.StateError(
764 764 _(b'working copy has pending changes'),
765 765 hint=_(
766 766 b'amend, commit, or revert them and run histedit '
767 767 b'--continue, or abort with histedit --abort'
768 768 ),
769 769 )
770 770
771 771
772 772 def action(verbs, message, priority=False, internal=False):
773 773 def wrap(cls):
774 774 assert not priority or not internal
775 775 verb = verbs[0]
776 776 if priority:
777 777 primaryactions.add(verb)
778 778 elif internal:
779 779 internalactions.add(verb)
780 780 elif len(verbs) > 1:
781 781 secondaryactions.add(verb)
782 782 else:
783 783 tertiaryactions.add(verb)
784 784
785 785 cls.verb = verb
786 786 cls.verbs = verbs
787 787 cls.message = message
788 788 for verb in verbs:
789 789 actiontable[verb] = cls
790 790 return cls
791 791
792 792 return wrap
793 793
794 794
795 795 @action([b'pick', b'p'], _(b'use commit'), priority=True)
796 796 class pick(histeditaction):
797 797 def run(self):
798 798 rulectx = self.repo[self.node]
799 799 if rulectx.p1().node() == self.state.parentctxnode:
800 800 self.repo.ui.debug(b'node %s unchanged\n' % short(self.node))
801 801 return rulectx, []
802 802
803 803 return super(pick, self).run()
804 804
805 805
806 806 @action(
807 807 [b'edit', b'e'],
808 808 _(b'use commit, but allow edits before making new commit'),
809 809 priority=True,
810 810 )
811 811 class edit(histeditaction):
812 812 def run(self):
813 813 repo = self.repo
814 814 rulectx = repo[self.node]
815 815 hg.update(repo, self.state.parentctxnode, quietempty=True)
816 816 applychanges(repo.ui, repo, rulectx, {})
817 817 hint = _(b'to edit %s, `hg histedit --continue` after making changes')
818 818 raise error.InterventionRequired(
819 819 _(b'Editing (%s), commit as needed now to split the change')
820 820 % short(self.node),
821 821 hint=hint % short(self.node),
822 822 )
823 823
824 824 def commiteditor(self):
825 825 return cmdutil.getcommiteditor(edit=True, editform=b'histedit.edit')
826 826
827 827
828 828 @action([b'fold', b'f'], _(b'use commit, but combine it with the one above'))
829 829 class fold(histeditaction):
830 830 def verify(self, prev, expected, seen):
831 831 """Verifies semantic correctness of the fold rule"""
832 832 super(fold, self).verify(prev, expected, seen)
833 833 repo = self.repo
834 834 if not prev:
835 835 c = repo[self.node].p1()
836 836 elif not prev.verb in (b'pick', b'base'):
837 837 return
838 838 else:
839 839 c = repo[prev.node]
840 840 if not c.mutable():
841 841 raise error.ParseError(
842 842 _(b"cannot fold into public change %s") % short(c.node())
843 843 )
844 844
845 845 def continuedirty(self):
846 846 repo = self.repo
847 847 rulectx = repo[self.node]
848 848
849 849 commit = commitfuncfor(repo, rulectx)
850 850 commit(
851 851 text=b'fold-temp-revision %s' % short(self.node),
852 852 user=rulectx.user(),
853 853 date=rulectx.date(),
854 854 extra=rulectx.extra(),
855 855 )
856 856
857 857 def continueclean(self):
858 858 repo = self.repo
859 859 ctx = repo[b'.']
860 860 rulectx = repo[self.node]
861 861 parentctxnode = self.state.parentctxnode
862 862 if ctx.node() == parentctxnode:
863 863 repo.ui.warn(_(b'%s: empty changeset\n') % short(self.node))
864 864 return ctx, [(self.node, (parentctxnode,))]
865 865
866 866 parentctx = repo[parentctxnode]
867 867 newcommits = {
868 868 c.node()
869 869 for c in repo.set(b'(%d::. - %d)', parentctx.rev(), parentctx.rev())
870 870 }
871 871 if not newcommits:
872 872 repo.ui.warn(
873 873 _(
874 874 b'%s: cannot fold - working copy is not a '
875 875 b'descendant of previous commit %s\n'
876 876 )
877 877 % (short(self.node), short(parentctxnode))
878 878 )
879 879 return ctx, [(self.node, (ctx.node(),))]
880 880
881 881 middlecommits = newcommits.copy()
882 882 middlecommits.discard(ctx.node())
883 883
884 884 return self.finishfold(
885 885 repo.ui, repo, parentctx, rulectx, ctx.node(), middlecommits
886 886 )
887 887
888 888 def skipprompt(self):
889 889 """Returns true if the rule should skip the message editor.
890 890
891 891 For example, 'fold' wants to show an editor, but 'rollup'
892 892 doesn't want to.
893 893 """
894 894 return False
895 895
896 896 def mergedescs(self):
897 897 """Returns true if the rule should merge messages of multiple changes.
898 898
899 899 This exists mainly so that 'rollup' rules can be a subclass of
900 900 'fold'.
901 901 """
902 902 return True
903 903
904 904 def firstdate(self):
905 905 """Returns true if the rule should preserve the date of the first
906 906 change.
907 907
908 908 This exists mainly so that 'rollup' rules can be a subclass of
909 909 'fold'.
910 910 """
911 911 return False
912 912
913 913 def finishfold(self, ui, repo, ctx, oldctx, newnode, internalchanges):
914 914 mergemod.update(ctx.p1())
915 915 ### prepare new commit data
916 916 commitopts = {}
917 917 commitopts[b'user'] = ctx.user()
918 918 # commit message
919 919 if not self.mergedescs():
920 920 newmessage = ctx.description()
921 921 else:
922 922 newmessage = (
923 923 b'\n***\n'.join(
924 924 [ctx.description()]
925 925 + [repo[r].description() for r in internalchanges]
926 926 + [oldctx.description()]
927 927 )
928 928 + b'\n'
929 929 )
930 930 commitopts[b'message'] = newmessage
931 931 # date
932 932 if self.firstdate():
933 933 commitopts[b'date'] = ctx.date()
934 934 else:
935 935 commitopts[b'date'] = max(ctx.date(), oldctx.date())
936 936 # if date is to be updated to current
937 937 if ui.configbool(b'rewrite', b'update-timestamp'):
938 938 commitopts[b'date'] = dateutil.makedate()
939 939
940 940 extra = ctx.extra().copy()
941 941 # histedit_source
942 942 # note: ctx is likely a temporary commit but that the best we can do
943 943 # here. This is sufficient to solve issue3681 anyway.
944 944 extra[b'histedit_source'] = b'%s,%s' % (ctx.hex(), oldctx.hex())
945 945 commitopts[b'extra'] = extra
946 946 phasemin = max(ctx.phase(), oldctx.phase())
947 947 overrides = {(b'phases', b'new-commit'): phasemin}
948 948 with repo.ui.configoverride(overrides, b'histedit'):
949 949 n = collapse(
950 950 repo,
951 951 ctx,
952 952 repo[newnode],
953 953 commitopts,
954 954 skipprompt=self.skipprompt(),
955 955 )
956 956 if n is None:
957 957 return ctx, []
958 958 mergemod.update(repo[n])
959 959 replacements = [
960 960 (oldctx.node(), (newnode,)),
961 961 (ctx.node(), (n,)),
962 962 (newnode, (n,)),
963 963 ]
964 964 for ich in internalchanges:
965 965 replacements.append((ich, (n,)))
966 966 return repo[n], replacements
967 967
968 968
969 969 @action(
970 970 [b'base', b'b'],
971 971 _(b'checkout changeset and apply further changesets from there'),
972 972 )
973 973 class base(histeditaction):
974 974 def run(self):
975 975 if self.repo[b'.'].node() != self.node:
976 976 mergemod.clean_update(self.repo[self.node])
977 977 return self.continueclean()
978 978
979 979 def continuedirty(self):
980 980 abortdirty()
981 981
982 982 def continueclean(self):
983 983 basectx = self.repo[b'.']
984 984 return basectx, []
985 985
986 986 def _verifynodeconstraints(self, prev, expected, seen):
987 987 # base can only be use with a node not in the edited set
988 988 if self.node in expected:
989 989 msg = _(b'%s "%s" changeset was an edited list candidate')
990 990 raise error.ParseError(
991 991 msg % (self.verb, short(self.node)),
992 992 hint=_(b'base must only use unlisted changesets'),
993 993 )
994 994
995 995
996 996 @action(
997 997 [b'_multifold'],
998 998 _(
999 999 """fold subclass used for when multiple folds happen in a row
1000 1000
1001 1001 We only want to fire the editor for the folded message once when
1002 1002 (say) four changes are folded down into a single change. This is
1003 1003 similar to rollup, but we should preserve both messages so that
1004 1004 when the last fold operation runs we can show the user all the
1005 1005 commit messages in their editor.
1006 1006 """
1007 1007 ),
1008 1008 internal=True,
1009 1009 )
1010 1010 class _multifold(fold):
1011 1011 def skipprompt(self):
1012 1012 return True
1013 1013
1014 1014
1015 1015 @action(
1016 1016 [b"roll", b"r"],
1017 1017 _(b"like fold, but discard this commit's description and date"),
1018 1018 )
1019 1019 class rollup(fold):
1020 1020 def mergedescs(self):
1021 1021 return False
1022 1022
1023 1023 def skipprompt(self):
1024 1024 return True
1025 1025
1026 1026 def firstdate(self):
1027 1027 return True
1028 1028
1029 1029
1030 1030 @action([b"drop", b"d"], _(b'remove commit from history'))
1031 1031 class drop(histeditaction):
1032 1032 def run(self):
1033 1033 parentctx = self.repo[self.state.parentctxnode]
1034 1034 return parentctx, [(self.node, tuple())]
1035 1035
1036 1036
1037 1037 @action(
1038 1038 [b"mess", b"m"],
1039 1039 _(b'edit commit message without changing commit content'),
1040 1040 priority=True,
1041 1041 )
1042 1042 class message(histeditaction):
1043 1043 def commiteditor(self):
1044 1044 return cmdutil.getcommiteditor(edit=True, editform=b'histedit.mess')
1045 1045
1046 1046
1047 1047 def findoutgoing(ui, repo, remote=None, force=False, opts=None):
1048 1048 """utility function to find the first outgoing changeset
1049 1049
1050 1050 Used by initialization code"""
1051 1051 if opts is None:
1052 1052 opts = {}
1053 1053 path = urlutil.get_unique_push_path(b'histedit', repo, ui, remote)
1054 dest = path.loc
1055
1056 ui.status(_(b'comparing with %s\n') % urlutil.hidepassword(dest))
1054
1055 ui.status(_(b'comparing with %s\n') % urlutil.hidepassword(path.loc))
1057 1056
1058 1057 revs, checkout = hg.addbranchrevs(repo, repo, (path.branch, []), None)
1059 other = hg.peer(repo, opts, dest)
1058 other = hg.peer(repo, opts, path)
1060 1059
1061 1060 if revs:
1062 1061 revs = [repo.lookup(rev) for rev in revs]
1063 1062
1064 1063 outgoing = discovery.findcommonoutgoing(repo, other, revs, force=force)
1065 1064 if not outgoing.missing:
1066 1065 raise error.StateError(_(b'no outgoing ancestors'))
1067 1066 roots = list(repo.revs(b"roots(%ln)", outgoing.missing))
1068 1067 if len(roots) > 1:
1069 1068 msg = _(b'there are ambiguous outgoing revisions')
1070 1069 hint = _(b"see 'hg help histedit' for more detail")
1071 1070 raise error.StateError(msg, hint=hint)
1072 1071 return repo[roots[0]].node()
1073 1072
1074 1073
1075 1074 # Curses Support
1076 1075 try:
1077 1076 import curses
1078 1077 except ImportError:
1079 1078 curses = None
1080 1079
1081 1080 KEY_LIST = [b'pick', b'edit', b'fold', b'drop', b'mess', b'roll']
1082 1081 ACTION_LABELS = {
1083 1082 b'fold': b'^fold',
1084 1083 b'roll': b'^roll',
1085 1084 }
1086 1085
1087 1086 COLOR_HELP, COLOR_SELECTED, COLOR_OK, COLOR_WARN, COLOR_CURRENT = 1, 2, 3, 4, 5
1088 1087 COLOR_DIFF_ADD_LINE, COLOR_DIFF_DEL_LINE, COLOR_DIFF_OFFSET = 6, 7, 8
1089 1088 COLOR_ROLL, COLOR_ROLL_CURRENT, COLOR_ROLL_SELECTED = 9, 10, 11
1090 1089
1091 1090 E_QUIT, E_HISTEDIT = 1, 2
1092 1091 E_PAGEDOWN, E_PAGEUP, E_LINEUP, E_LINEDOWN, E_RESIZE = 3, 4, 5, 6, 7
1093 1092 MODE_INIT, MODE_PATCH, MODE_RULES, MODE_HELP = 0, 1, 2, 3
1094 1093
1095 1094 KEYTABLE = {
1096 1095 b'global': {
1097 1096 b'h': b'next-action',
1098 1097 b'KEY_RIGHT': b'next-action',
1099 1098 b'l': b'prev-action',
1100 1099 b'KEY_LEFT': b'prev-action',
1101 1100 b'q': b'quit',
1102 1101 b'c': b'histedit',
1103 1102 b'C': b'histedit',
1104 1103 b'v': b'showpatch',
1105 1104 b'?': b'help',
1106 1105 },
1107 1106 MODE_RULES: {
1108 1107 b'd': b'action-drop',
1109 1108 b'e': b'action-edit',
1110 1109 b'f': b'action-fold',
1111 1110 b'm': b'action-mess',
1112 1111 b'p': b'action-pick',
1113 1112 b'r': b'action-roll',
1114 1113 b' ': b'select',
1115 1114 b'j': b'down',
1116 1115 b'k': b'up',
1117 1116 b'KEY_DOWN': b'down',
1118 1117 b'KEY_UP': b'up',
1119 1118 b'J': b'move-down',
1120 1119 b'K': b'move-up',
1121 1120 b'KEY_NPAGE': b'move-down',
1122 1121 b'KEY_PPAGE': b'move-up',
1123 1122 b'0': b'goto', # Used for 0..9
1124 1123 },
1125 1124 MODE_PATCH: {
1126 1125 b' ': b'page-down',
1127 1126 b'KEY_NPAGE': b'page-down',
1128 1127 b'KEY_PPAGE': b'page-up',
1129 1128 b'j': b'line-down',
1130 1129 b'k': b'line-up',
1131 1130 b'KEY_DOWN': b'line-down',
1132 1131 b'KEY_UP': b'line-up',
1133 1132 b'J': b'down',
1134 1133 b'K': b'up',
1135 1134 },
1136 1135 MODE_HELP: {},
1137 1136 }
1138 1137
1139 1138
1140 1139 def screen_size():
1141 1140 return struct.unpack(b'hh', fcntl.ioctl(1, termios.TIOCGWINSZ, b' '))
1142 1141
1143 1142
1144 1143 class histeditrule:
1145 1144 def __init__(self, ui, ctx, pos, action=b'pick'):
1146 1145 self.ui = ui
1147 1146 self.ctx = ctx
1148 1147 self.action = action
1149 1148 self.origpos = pos
1150 1149 self.pos = pos
1151 1150 self.conflicts = []
1152 1151
1153 1152 def __bytes__(self):
1154 1153 # Example display of several histeditrules:
1155 1154 #
1156 1155 # #10 pick 316392:06a16c25c053 add option to skip tests
1157 1156 # #11 ^roll 316393:71313c964cc5 <RED>oops a fixup commit</RED>
1158 1157 # #12 pick 316394:ab31f3973b0d include mfbt for mozilla-config.h
1159 1158 # #13 ^fold 316395:14ce5803f4c3 fix warnings
1160 1159 #
1161 1160 # The carets point to the changeset being folded into ("roll this
1162 1161 # changeset into the changeset above").
1163 1162 return b'%s%s' % (self.prefix, self.desc)
1164 1163
1165 1164 __str__ = encoding.strmethod(__bytes__)
1166 1165
1167 1166 @property
1168 1167 def prefix(self):
1169 1168 # Some actions ('fold' and 'roll') combine a patch with a
1170 1169 # previous one. Add a marker showing which patch they apply
1171 1170 # to.
1172 1171 action = ACTION_LABELS.get(self.action, self.action)
1173 1172
1174 1173 h = self.ctx.hex()[0:12]
1175 1174 r = self.ctx.rev()
1176 1175
1177 1176 return b"#%s %s %d:%s " % (
1178 1177 (b'%d' % self.origpos).ljust(2),
1179 1178 action.ljust(6),
1180 1179 r,
1181 1180 h,
1182 1181 )
1183 1182
1184 1183 @util.propertycache
1185 1184 def desc(self):
1186 1185 summary = cmdutil.rendertemplate(
1187 1186 self.ctx, self.ui.config(b'histedit', b'summary-template')
1188 1187 )
1189 1188 if summary:
1190 1189 return summary
1191 1190 # This is split off from the prefix property so that we can
1192 1191 # separately make the description for 'roll' red (since it
1193 1192 # will get discarded).
1194 1193 return stringutil.firstline(self.ctx.description())
1195 1194
1196 1195 def checkconflicts(self, other):
1197 1196 if other.pos > self.pos and other.origpos <= self.origpos:
1198 1197 if set(other.ctx.files()) & set(self.ctx.files()) != set():
1199 1198 self.conflicts.append(other)
1200 1199 return self.conflicts
1201 1200
1202 1201 if other in self.conflicts:
1203 1202 self.conflicts.remove(other)
1204 1203 return self.conflicts
1205 1204
1206 1205
1207 1206 def makecommands(rules):
1208 1207 """Returns a list of commands consumable by histedit --commands based on
1209 1208 our list of rules"""
1210 1209 commands = []
1211 1210 for rules in rules:
1212 1211 commands.append(b'%s %s\n' % (rules.action, rules.ctx))
1213 1212 return commands
1214 1213
1215 1214
1216 1215 def addln(win, y, x, line, color=None):
1217 1216 """Add a line to the given window left padding but 100% filled with
1218 1217 whitespace characters, so that the color appears on the whole line"""
1219 1218 maxy, maxx = win.getmaxyx()
1220 1219 length = maxx - 1 - x
1221 1220 line = bytes(line).ljust(length)[:length]
1222 1221 if y < 0:
1223 1222 y = maxy + y
1224 1223 if x < 0:
1225 1224 x = maxx + x
1226 1225 if color:
1227 1226 win.addstr(y, x, line, color)
1228 1227 else:
1229 1228 win.addstr(y, x, line)
1230 1229
1231 1230
1232 1231 def _trunc_head(line, n):
1233 1232 if len(line) <= n:
1234 1233 return line
1235 1234 return b'> ' + line[-(n - 2) :]
1236 1235
1237 1236
1238 1237 def _trunc_tail(line, n):
1239 1238 if len(line) <= n:
1240 1239 return line
1241 1240 return line[: n - 2] + b' >'
1242 1241
1243 1242
1244 1243 class _chistedit_state:
1245 1244 def __init__(
1246 1245 self,
1247 1246 repo,
1248 1247 rules,
1249 1248 stdscr,
1250 1249 ):
1251 1250 self.repo = repo
1252 1251 self.rules = rules
1253 1252 self.stdscr = stdscr
1254 1253 self.later_on_top = repo.ui.configbool(
1255 1254 b'histedit', b'later-commits-first'
1256 1255 )
1257 1256 # The current item in display order, initialized to point to the top
1258 1257 # of the screen.
1259 1258 self.pos = 0
1260 1259 self.selected = None
1261 1260 self.mode = (MODE_INIT, MODE_INIT)
1262 1261 self.page_height = None
1263 1262 self.modes = {
1264 1263 MODE_RULES: {
1265 1264 b'line_offset': 0,
1266 1265 },
1267 1266 MODE_PATCH: {
1268 1267 b'line_offset': 0,
1269 1268 },
1270 1269 }
1271 1270
1272 1271 def render_commit(self, win):
1273 1272 """Renders the commit window that shows the log of the current selected
1274 1273 commit"""
1275 1274 rule = self.rules[self.display_pos_to_rule_pos(self.pos)]
1276 1275
1277 1276 ctx = rule.ctx
1278 1277 win.box()
1279 1278
1280 1279 maxy, maxx = win.getmaxyx()
1281 1280 length = maxx - 3
1282 1281
1283 1282 line = b"changeset: %d:%s" % (ctx.rev(), ctx.hex()[:12])
1284 1283 win.addstr(1, 1, line[:length])
1285 1284
1286 1285 line = b"user: %s" % ctx.user()
1287 1286 win.addstr(2, 1, line[:length])
1288 1287
1289 1288 bms = self.repo.nodebookmarks(ctx.node())
1290 1289 line = b"bookmark: %s" % b' '.join(bms)
1291 1290 win.addstr(3, 1, line[:length])
1292 1291
1293 1292 line = b"summary: %s" % stringutil.firstline(ctx.description())
1294 1293 win.addstr(4, 1, line[:length])
1295 1294
1296 1295 line = b"files: "
1297 1296 win.addstr(5, 1, line)
1298 1297 fnx = 1 + len(line)
1299 1298 fnmaxx = length - fnx + 1
1300 1299 y = 5
1301 1300 fnmaxn = maxy - (1 + y) - 1
1302 1301 files = ctx.files()
1303 1302 for i, line1 in enumerate(files):
1304 1303 if len(files) > fnmaxn and i == fnmaxn - 1:
1305 1304 win.addstr(y, fnx, _trunc_tail(b','.join(files[i:]), fnmaxx))
1306 1305 y = y + 1
1307 1306 break
1308 1307 win.addstr(y, fnx, _trunc_head(line1, fnmaxx))
1309 1308 y = y + 1
1310 1309
1311 1310 conflicts = rule.conflicts
1312 1311 if len(conflicts) > 0:
1313 1312 conflictstr = b','.join(map(lambda r: r.ctx.hex()[:12], conflicts))
1314 1313 conflictstr = b"changed files overlap with %s" % conflictstr
1315 1314 else:
1316 1315 conflictstr = b'no overlap'
1317 1316
1318 1317 win.addstr(y, 1, conflictstr[:length])
1319 1318 win.noutrefresh()
1320 1319
1321 1320 def helplines(self):
1322 1321 if self.mode[0] == MODE_PATCH:
1323 1322 help = b"""\
1324 1323 ?: help, k/up: line up, j/down: line down, v: stop viewing patch
1325 1324 pgup: prev page, space/pgdn: next page, c: commit, q: abort
1326 1325 """
1327 1326 else:
1328 1327 help = b"""\
1329 1328 ?: help, k/up: move up, j/down: move down, space: select, v: view patch
1330 1329 d: drop, e: edit, f: fold, m: mess, p: pick, r: roll
1331 1330 pgup/K: move patch up, pgdn/J: move patch down, c: commit, q: abort
1332 1331 """
1333 1332 if self.later_on_top:
1334 1333 help += b"Newer commits are shown above older commits.\n"
1335 1334 else:
1336 1335 help += b"Older commits are shown above newer commits.\n"
1337 1336 return help.splitlines()
1338 1337
1339 1338 def render_help(self, win):
1340 1339 maxy, maxx = win.getmaxyx()
1341 1340 for y, line in enumerate(self.helplines()):
1342 1341 if y >= maxy:
1343 1342 break
1344 1343 addln(win, y, 0, line, curses.color_pair(COLOR_HELP))
1345 1344 win.noutrefresh()
1346 1345
1347 1346 def layout(self):
1348 1347 maxy, maxx = self.stdscr.getmaxyx()
1349 1348 helplen = len(self.helplines())
1350 1349 mainlen = maxy - helplen - 12
1351 1350 if mainlen < 1:
1352 1351 raise error.Abort(
1353 1352 _(b"terminal dimensions %d by %d too small for curses histedit")
1354 1353 % (maxy, maxx),
1355 1354 hint=_(
1356 1355 b"enlarge your terminal or use --config ui.interface=text"
1357 1356 ),
1358 1357 )
1359 1358 return {
1360 1359 b'commit': (12, maxx),
1361 1360 b'help': (helplen, maxx),
1362 1361 b'main': (mainlen, maxx),
1363 1362 }
1364 1363
1365 1364 def display_pos_to_rule_pos(self, display_pos):
1366 1365 """Converts a position in display order to rule order.
1367 1366
1368 1367 The `display_pos` is the order from the top in display order, not
1369 1368 considering which items are currently visible on the screen. Thus,
1370 1369 `display_pos=0` is the item at the top (possibly after scrolling to
1371 1370 the top)
1372 1371 """
1373 1372 if self.later_on_top:
1374 1373 return len(self.rules) - 1 - display_pos
1375 1374 else:
1376 1375 return display_pos
1377 1376
1378 1377 def render_rules(self, rulesscr):
1379 1378 start = self.modes[MODE_RULES][b'line_offset']
1380 1379
1381 1380 conflicts = [r.ctx for r in self.rules if r.conflicts]
1382 1381 if len(conflicts) > 0:
1383 1382 line = b"potential conflict in %s" % b','.join(
1384 1383 map(pycompat.bytestr, conflicts)
1385 1384 )
1386 1385 addln(rulesscr, -1, 0, line, curses.color_pair(COLOR_WARN))
1387 1386
1388 1387 for display_pos in range(start, len(self.rules)):
1389 1388 y = display_pos - start
1390 1389 if y < 0 or y >= self.page_height:
1391 1390 continue
1392 1391 rule_pos = self.display_pos_to_rule_pos(display_pos)
1393 1392 rule = self.rules[rule_pos]
1394 1393 if len(rule.conflicts) > 0:
1395 1394 rulesscr.addstr(y, 0, b" ", curses.color_pair(COLOR_WARN))
1396 1395 else:
1397 1396 rulesscr.addstr(y, 0, b" ", curses.COLOR_BLACK)
1398 1397
1399 1398 if display_pos == self.selected:
1400 1399 rollcolor = COLOR_ROLL_SELECTED
1401 1400 addln(rulesscr, y, 2, rule, curses.color_pair(COLOR_SELECTED))
1402 1401 elif display_pos == self.pos:
1403 1402 rollcolor = COLOR_ROLL_CURRENT
1404 1403 addln(
1405 1404 rulesscr,
1406 1405 y,
1407 1406 2,
1408 1407 rule,
1409 1408 curses.color_pair(COLOR_CURRENT) | curses.A_BOLD,
1410 1409 )
1411 1410 else:
1412 1411 rollcolor = COLOR_ROLL
1413 1412 addln(rulesscr, y, 2, rule)
1414 1413
1415 1414 if rule.action == b'roll':
1416 1415 rulesscr.addstr(
1417 1416 y,
1418 1417 2 + len(rule.prefix),
1419 1418 rule.desc,
1420 1419 curses.color_pair(rollcolor),
1421 1420 )
1422 1421
1423 1422 rulesscr.noutrefresh()
1424 1423
1425 1424 def render_string(self, win, output, diffcolors=False):
1426 1425 maxy, maxx = win.getmaxyx()
1427 1426 length = min(maxy - 1, len(output))
1428 1427 for y in range(0, length):
1429 1428 line = output[y]
1430 1429 if diffcolors:
1431 1430 if line and line[0] == b'+':
1432 1431 win.addstr(
1433 1432 y, 0, line, curses.color_pair(COLOR_DIFF_ADD_LINE)
1434 1433 )
1435 1434 elif line and line[0] == b'-':
1436 1435 win.addstr(
1437 1436 y, 0, line, curses.color_pair(COLOR_DIFF_DEL_LINE)
1438 1437 )
1439 1438 elif line.startswith(b'@@ '):
1440 1439 win.addstr(y, 0, line, curses.color_pair(COLOR_DIFF_OFFSET))
1441 1440 else:
1442 1441 win.addstr(y, 0, line)
1443 1442 else:
1444 1443 win.addstr(y, 0, line)
1445 1444 win.noutrefresh()
1446 1445
1447 1446 def render_patch(self, win):
1448 1447 start = self.modes[MODE_PATCH][b'line_offset']
1449 1448 content = self.modes[MODE_PATCH][b'patchcontents']
1450 1449 self.render_string(win, content[start:], diffcolors=True)
1451 1450
1452 1451 def event(self, ch):
1453 1452 """Change state based on the current character input
1454 1453
1455 1454 This takes the current state and based on the current character input from
1456 1455 the user we change the state.
1457 1456 """
1458 1457 oldpos = self.pos
1459 1458
1460 1459 if ch in (curses.KEY_RESIZE, b"KEY_RESIZE"):
1461 1460 return E_RESIZE
1462 1461
1463 1462 lookup_ch = ch
1464 1463 if ch is not None and b'0' <= ch <= b'9':
1465 1464 lookup_ch = b'0'
1466 1465
1467 1466 curmode, prevmode = self.mode
1468 1467 action = KEYTABLE[curmode].get(
1469 1468 lookup_ch, KEYTABLE[b'global'].get(lookup_ch)
1470 1469 )
1471 1470 if action is None:
1472 1471 return
1473 1472 if action in (b'down', b'move-down'):
1474 1473 newpos = min(oldpos + 1, len(self.rules) - 1)
1475 1474 self.move_cursor(oldpos, newpos)
1476 1475 if self.selected is not None or action == b'move-down':
1477 1476 self.swap(oldpos, newpos)
1478 1477 elif action in (b'up', b'move-up'):
1479 1478 newpos = max(0, oldpos - 1)
1480 1479 self.move_cursor(oldpos, newpos)
1481 1480 if self.selected is not None or action == b'move-up':
1482 1481 self.swap(oldpos, newpos)
1483 1482 elif action == b'next-action':
1484 1483 self.cycle_action(oldpos, next=True)
1485 1484 elif action == b'prev-action':
1486 1485 self.cycle_action(oldpos, next=False)
1487 1486 elif action == b'select':
1488 1487 self.selected = oldpos if self.selected is None else None
1489 1488 self.make_selection(self.selected)
1490 1489 elif action == b'goto' and int(ch) < len(self.rules) <= 10:
1491 1490 newrule = next((r for r in self.rules if r.origpos == int(ch)))
1492 1491 self.move_cursor(oldpos, newrule.pos)
1493 1492 if self.selected is not None:
1494 1493 self.swap(oldpos, newrule.pos)
1495 1494 elif action.startswith(b'action-'):
1496 1495 self.change_action(oldpos, action[7:])
1497 1496 elif action == b'showpatch':
1498 1497 self.change_mode(MODE_PATCH if curmode != MODE_PATCH else prevmode)
1499 1498 elif action == b'help':
1500 1499 self.change_mode(MODE_HELP if curmode != MODE_HELP else prevmode)
1501 1500 elif action == b'quit':
1502 1501 return E_QUIT
1503 1502 elif action == b'histedit':
1504 1503 return E_HISTEDIT
1505 1504 elif action == b'page-down':
1506 1505 return E_PAGEDOWN
1507 1506 elif action == b'page-up':
1508 1507 return E_PAGEUP
1509 1508 elif action == b'line-down':
1510 1509 return E_LINEDOWN
1511 1510 elif action == b'line-up':
1512 1511 return E_LINEUP
1513 1512
1514 1513 def patch_contents(self):
1515 1514 repo = self.repo
1516 1515 rule = self.rules[self.display_pos_to_rule_pos(self.pos)]
1517 1516 displayer = logcmdutil.changesetdisplayer(
1518 1517 repo.ui,
1519 1518 repo,
1520 1519 {b"patch": True, b"template": b"status"},
1521 1520 buffered=True,
1522 1521 )
1523 1522 overrides = {(b'ui', b'verbose'): True}
1524 1523 with repo.ui.configoverride(overrides, source=b'histedit'):
1525 1524 displayer.show(rule.ctx)
1526 1525 displayer.close()
1527 1526 return displayer.hunk[rule.ctx.rev()].splitlines()
1528 1527
1529 1528 def move_cursor(self, oldpos, newpos):
1530 1529 """Change the rule/changeset that the cursor is pointing to, regardless of
1531 1530 current mode (you can switch between patches from the view patch window)."""
1532 1531 self.pos = newpos
1533 1532
1534 1533 mode, _ = self.mode
1535 1534 if mode == MODE_RULES:
1536 1535 # Scroll through the list by updating the view for MODE_RULES, so that
1537 1536 # even if we are not currently viewing the rules, switching back will
1538 1537 # result in the cursor's rule being visible.
1539 1538 modestate = self.modes[MODE_RULES]
1540 1539 if newpos < modestate[b'line_offset']:
1541 1540 modestate[b'line_offset'] = newpos
1542 1541 elif newpos > modestate[b'line_offset'] + self.page_height - 1:
1543 1542 modestate[b'line_offset'] = newpos - self.page_height + 1
1544 1543
1545 1544 # Reset the patch view region to the top of the new patch.
1546 1545 self.modes[MODE_PATCH][b'line_offset'] = 0
1547 1546
1548 1547 def change_mode(self, mode):
1549 1548 curmode, _ = self.mode
1550 1549 self.mode = (mode, curmode)
1551 1550 if mode == MODE_PATCH:
1552 1551 self.modes[MODE_PATCH][b'patchcontents'] = self.patch_contents()
1553 1552
1554 1553 def make_selection(self, pos):
1555 1554 self.selected = pos
1556 1555
1557 1556 def swap(self, oldpos, newpos):
1558 1557 """Swap two positions and calculate necessary conflicts in
1559 1558 O(|newpos-oldpos|) time"""
1560 1559 old_rule_pos = self.display_pos_to_rule_pos(oldpos)
1561 1560 new_rule_pos = self.display_pos_to_rule_pos(newpos)
1562 1561
1563 1562 rules = self.rules
1564 1563 assert 0 <= old_rule_pos < len(rules) and 0 <= new_rule_pos < len(rules)
1565 1564
1566 1565 rules[old_rule_pos], rules[new_rule_pos] = (
1567 1566 rules[new_rule_pos],
1568 1567 rules[old_rule_pos],
1569 1568 )
1570 1569
1571 1570 # TODO: swap should not know about histeditrule's internals
1572 1571 rules[new_rule_pos].pos = new_rule_pos
1573 1572 rules[old_rule_pos].pos = old_rule_pos
1574 1573
1575 1574 start = min(old_rule_pos, new_rule_pos)
1576 1575 end = max(old_rule_pos, new_rule_pos)
1577 1576 for r in range(start, end + 1):
1578 1577 rules[new_rule_pos].checkconflicts(rules[r])
1579 1578 rules[old_rule_pos].checkconflicts(rules[r])
1580 1579
1581 1580 if self.selected:
1582 1581 self.make_selection(newpos)
1583 1582
1584 1583 def change_action(self, pos, action):
1585 1584 """Change the action state on the given position to the new action"""
1586 1585 assert 0 <= pos < len(self.rules)
1587 1586 self.rules[pos].action = action
1588 1587
1589 1588 def cycle_action(self, pos, next=False):
1590 1589 """Changes the action state the next or the previous action from
1591 1590 the action list"""
1592 1591 assert 0 <= pos < len(self.rules)
1593 1592 current = self.rules[pos].action
1594 1593
1595 1594 assert current in KEY_LIST
1596 1595
1597 1596 index = KEY_LIST.index(current)
1598 1597 if next:
1599 1598 index += 1
1600 1599 else:
1601 1600 index -= 1
1602 1601 self.change_action(pos, KEY_LIST[index % len(KEY_LIST)])
1603 1602
1604 1603 def change_view(self, delta, unit):
1605 1604 """Change the region of whatever is being viewed (a patch or the list of
1606 1605 changesets). 'delta' is an amount (+/- 1) and 'unit' is 'page' or 'line'."""
1607 1606 mode, _ = self.mode
1608 1607 if mode != MODE_PATCH:
1609 1608 return
1610 1609 mode_state = self.modes[mode]
1611 1610 num_lines = len(mode_state[b'patchcontents'])
1612 1611 page_height = self.page_height
1613 1612 unit = page_height if unit == b'page' else 1
1614 1613 num_pages = 1 + (num_lines - 1) // page_height
1615 1614 max_offset = (num_pages - 1) * page_height
1616 1615 newline = mode_state[b'line_offset'] + delta * unit
1617 1616 mode_state[b'line_offset'] = max(0, min(max_offset, newline))
1618 1617
1619 1618
1620 1619 def _chisteditmain(repo, rules, stdscr):
1621 1620 try:
1622 1621 curses.use_default_colors()
1623 1622 except curses.error:
1624 1623 pass
1625 1624
1626 1625 # initialize color pattern
1627 1626 curses.init_pair(COLOR_HELP, curses.COLOR_WHITE, curses.COLOR_BLUE)
1628 1627 curses.init_pair(COLOR_SELECTED, curses.COLOR_BLACK, curses.COLOR_WHITE)
1629 1628 curses.init_pair(COLOR_WARN, curses.COLOR_BLACK, curses.COLOR_YELLOW)
1630 1629 curses.init_pair(COLOR_OK, curses.COLOR_BLACK, curses.COLOR_GREEN)
1631 1630 curses.init_pair(COLOR_CURRENT, curses.COLOR_WHITE, curses.COLOR_MAGENTA)
1632 1631 curses.init_pair(COLOR_DIFF_ADD_LINE, curses.COLOR_GREEN, -1)
1633 1632 curses.init_pair(COLOR_DIFF_DEL_LINE, curses.COLOR_RED, -1)
1634 1633 curses.init_pair(COLOR_DIFF_OFFSET, curses.COLOR_MAGENTA, -1)
1635 1634 curses.init_pair(COLOR_ROLL, curses.COLOR_RED, -1)
1636 1635 curses.init_pair(
1637 1636 COLOR_ROLL_CURRENT, curses.COLOR_BLACK, curses.COLOR_MAGENTA
1638 1637 )
1639 1638 curses.init_pair(COLOR_ROLL_SELECTED, curses.COLOR_RED, curses.COLOR_WHITE)
1640 1639
1641 1640 # don't display the cursor
1642 1641 try:
1643 1642 curses.curs_set(0)
1644 1643 except curses.error:
1645 1644 pass
1646 1645
1647 1646 def drawvertwin(size, y, x):
1648 1647 win = curses.newwin(size[0], size[1], y, x)
1649 1648 y += size[0]
1650 1649 return win, y, x
1651 1650
1652 1651 state = _chistedit_state(repo, rules, stdscr)
1653 1652
1654 1653 # eventloop
1655 1654 ch = None
1656 1655 stdscr.clear()
1657 1656 stdscr.refresh()
1658 1657 while True:
1659 1658 oldmode, unused = state.mode
1660 1659 if oldmode == MODE_INIT:
1661 1660 state.change_mode(MODE_RULES)
1662 1661 e = state.event(ch)
1663 1662
1664 1663 if e == E_QUIT:
1665 1664 return False
1666 1665 if e == E_HISTEDIT:
1667 1666 return state.rules
1668 1667 else:
1669 1668 if e == E_RESIZE:
1670 1669 size = screen_size()
1671 1670 if size != stdscr.getmaxyx():
1672 1671 curses.resizeterm(*size)
1673 1672
1674 1673 sizes = state.layout()
1675 1674 curmode, unused = state.mode
1676 1675 if curmode != oldmode:
1677 1676 state.page_height = sizes[b'main'][0]
1678 1677 # Adjust the view to fit the current screen size.
1679 1678 state.move_cursor(state.pos, state.pos)
1680 1679
1681 1680 # Pack the windows against the top, each pane spread across the
1682 1681 # full width of the screen.
1683 1682 y, x = (0, 0)
1684 1683 helpwin, y, x = drawvertwin(sizes[b'help'], y, x)
1685 1684 mainwin, y, x = drawvertwin(sizes[b'main'], y, x)
1686 1685 commitwin, y, x = drawvertwin(sizes[b'commit'], y, x)
1687 1686
1688 1687 if e in (E_PAGEDOWN, E_PAGEUP, E_LINEDOWN, E_LINEUP):
1689 1688 if e == E_PAGEDOWN:
1690 1689 state.change_view(+1, b'page')
1691 1690 elif e == E_PAGEUP:
1692 1691 state.change_view(-1, b'page')
1693 1692 elif e == E_LINEDOWN:
1694 1693 state.change_view(+1, b'line')
1695 1694 elif e == E_LINEUP:
1696 1695 state.change_view(-1, b'line')
1697 1696
1698 1697 # start rendering
1699 1698 commitwin.erase()
1700 1699 helpwin.erase()
1701 1700 mainwin.erase()
1702 1701 if curmode == MODE_PATCH:
1703 1702 state.render_patch(mainwin)
1704 1703 elif curmode == MODE_HELP:
1705 1704 state.render_string(mainwin, __doc__.strip().splitlines())
1706 1705 else:
1707 1706 state.render_rules(mainwin)
1708 1707 state.render_commit(commitwin)
1709 1708 state.render_help(helpwin)
1710 1709 curses.doupdate()
1711 1710 # done rendering
1712 1711 ch = encoding.strtolocal(stdscr.getkey())
1713 1712
1714 1713
1715 1714 def _chistedit(ui, repo, freeargs, opts):
1716 1715 """interactively edit changeset history via a curses interface
1717 1716
1718 1717 Provides a ncurses interface to histedit. Press ? in chistedit mode
1719 1718 to see an extensive help. Requires python-curses to be installed."""
1720 1719
1721 1720 if curses is None:
1722 1721 raise error.Abort(_(b"Python curses library required"))
1723 1722
1724 1723 # disable color
1725 1724 ui._colormode = None
1726 1725
1727 1726 try:
1728 1727 keep = opts.get(b'keep')
1729 1728 revs = opts.get(b'rev', [])[:]
1730 1729 cmdutil.checkunfinished(repo)
1731 1730 cmdutil.bailifchanged(repo)
1732 1731
1733 1732 revs.extend(freeargs)
1734 1733 if not revs:
1735 1734 defaultrev = destutil.desthistedit(ui, repo)
1736 1735 if defaultrev is not None:
1737 1736 revs.append(defaultrev)
1738 1737 if len(revs) != 1:
1739 1738 raise error.InputError(
1740 1739 _(b'histedit requires exactly one ancestor revision')
1741 1740 )
1742 1741
1743 1742 rr = list(repo.set(b'roots(%ld)', logcmdutil.revrange(repo, revs)))
1744 1743 if len(rr) != 1:
1745 1744 raise error.InputError(
1746 1745 _(
1747 1746 b'The specified revisions must have '
1748 1747 b'exactly one common root'
1749 1748 )
1750 1749 )
1751 1750 root = rr[0].node()
1752 1751
1753 1752 topmost = repo.dirstate.p1()
1754 1753 revs = between(repo, root, topmost, keep)
1755 1754 if not revs:
1756 1755 raise error.InputError(
1757 1756 _(b'%s is not an ancestor of working directory') % short(root)
1758 1757 )
1759 1758
1760 1759 rules = []
1761 1760 for i, r in enumerate(revs):
1762 1761 rules.append(histeditrule(ui, repo[r], i))
1763 1762 with util.with_lc_ctype():
1764 1763 rc = curses.wrapper(functools.partial(_chisteditmain, repo, rules))
1765 1764 curses.echo()
1766 1765 curses.endwin()
1767 1766 if rc is False:
1768 1767 ui.write(_(b"histedit aborted\n"))
1769 1768 return 0
1770 1769 if type(rc) is list:
1771 1770 ui.status(_(b"performing changes\n"))
1772 1771 rules = makecommands(rc)
1773 1772 with repo.vfs(b'chistedit', b'w+') as fp:
1774 1773 for r in rules:
1775 1774 fp.write(r)
1776 1775 opts[b'commands'] = fp.name
1777 1776 return _texthistedit(ui, repo, freeargs, opts)
1778 1777 except KeyboardInterrupt:
1779 1778 pass
1780 1779 return -1
1781 1780
1782 1781
1783 1782 @command(
1784 1783 b'histedit',
1785 1784 [
1786 1785 (
1787 1786 b'',
1788 1787 b'commands',
1789 1788 b'',
1790 1789 _(b'read history edits from the specified file'),
1791 1790 _(b'FILE'),
1792 1791 ),
1793 1792 (b'c', b'continue', False, _(b'continue an edit already in progress')),
1794 1793 (b'', b'edit-plan', False, _(b'edit remaining actions list')),
1795 1794 (
1796 1795 b'k',
1797 1796 b'keep',
1798 1797 False,
1799 1798 _(b"don't strip old nodes after edit is complete"),
1800 1799 ),
1801 1800 (b'', b'abort', False, _(b'abort an edit in progress')),
1802 1801 (b'o', b'outgoing', False, _(b'changesets not found in destination')),
1803 1802 (
1804 1803 b'f',
1805 1804 b'force',
1806 1805 False,
1807 1806 _(b'force outgoing even for unrelated repositories'),
1808 1807 ),
1809 1808 (b'r', b'rev', [], _(b'first revision to be edited'), _(b'REV')),
1810 1809 ]
1811 1810 + cmdutil.formatteropts,
1812 1811 _(b"[OPTIONS] ([ANCESTOR] | --outgoing [URL])"),
1813 1812 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
1814 1813 )
1815 1814 def histedit(ui, repo, *freeargs, **opts):
1816 1815 """interactively edit changeset history
1817 1816
1818 1817 This command lets you edit a linear series of changesets (up to
1819 1818 and including the working directory, which should be clean).
1820 1819 You can:
1821 1820
1822 1821 - `pick` to [re]order a changeset
1823 1822
1824 1823 - `drop` to omit changeset
1825 1824
1826 1825 - `mess` to reword the changeset commit message
1827 1826
1828 1827 - `fold` to combine it with the preceding changeset (using the later date)
1829 1828
1830 1829 - `roll` like fold, but discarding this commit's description and date
1831 1830
1832 1831 - `edit` to edit this changeset (preserving date)
1833 1832
1834 1833 - `base` to checkout changeset and apply further changesets from there
1835 1834
1836 1835 There are a number of ways to select the root changeset:
1837 1836
1838 1837 - Specify ANCESTOR directly
1839 1838
1840 1839 - Use --outgoing -- it will be the first linear changeset not
1841 1840 included in destination. (See :hg:`help config.paths.default-push`)
1842 1841
1843 1842 - Otherwise, the value from the "histedit.defaultrev" config option
1844 1843 is used as a revset to select the base revision when ANCESTOR is not
1845 1844 specified. The first revision returned by the revset is used. By
1846 1845 default, this selects the editable history that is unique to the
1847 1846 ancestry of the working directory.
1848 1847
1849 1848 .. container:: verbose
1850 1849
1851 1850 If you use --outgoing, this command will abort if there are ambiguous
1852 1851 outgoing revisions. For example, if there are multiple branches
1853 1852 containing outgoing revisions.
1854 1853
1855 1854 Use "min(outgoing() and ::.)" or similar revset specification
1856 1855 instead of --outgoing to specify edit target revision exactly in
1857 1856 such ambiguous situation. See :hg:`help revsets` for detail about
1858 1857 selecting revisions.
1859 1858
1860 1859 .. container:: verbose
1861 1860
1862 1861 Examples:
1863 1862
1864 1863 - A number of changes have been made.
1865 1864 Revision 3 is no longer needed.
1866 1865
1867 1866 Start history editing from revision 3::
1868 1867
1869 1868 hg histedit -r 3
1870 1869
1871 1870 An editor opens, containing the list of revisions,
1872 1871 with specific actions specified::
1873 1872
1874 1873 pick 5339bf82f0ca 3 Zworgle the foobar
1875 1874 pick 8ef592ce7cc4 4 Bedazzle the zerlog
1876 1875 pick 0a9639fcda9d 5 Morgify the cromulancy
1877 1876
1878 1877 Additional information about the possible actions
1879 1878 to take appears below the list of revisions.
1880 1879
1881 1880 To remove revision 3 from the history,
1882 1881 its action (at the beginning of the relevant line)
1883 1882 is changed to 'drop'::
1884 1883
1885 1884 drop 5339bf82f0ca 3 Zworgle the foobar
1886 1885 pick 8ef592ce7cc4 4 Bedazzle the zerlog
1887 1886 pick 0a9639fcda9d 5 Morgify the cromulancy
1888 1887
1889 1888 - A number of changes have been made.
1890 1889 Revision 2 and 4 need to be swapped.
1891 1890
1892 1891 Start history editing from revision 2::
1893 1892
1894 1893 hg histedit -r 2
1895 1894
1896 1895 An editor opens, containing the list of revisions,
1897 1896 with specific actions specified::
1898 1897
1899 1898 pick 252a1af424ad 2 Blorb a morgwazzle
1900 1899 pick 5339bf82f0ca 3 Zworgle the foobar
1901 1900 pick 8ef592ce7cc4 4 Bedazzle the zerlog
1902 1901
1903 1902 To swap revision 2 and 4, its lines are swapped
1904 1903 in the editor::
1905 1904
1906 1905 pick 8ef592ce7cc4 4 Bedazzle the zerlog
1907 1906 pick 5339bf82f0ca 3 Zworgle the foobar
1908 1907 pick 252a1af424ad 2 Blorb a morgwazzle
1909 1908
1910 1909 Returns 0 on success, 1 if user intervention is required (not only
1911 1910 for intentional "edit" command, but also for resolving unexpected
1912 1911 conflicts).
1913 1912 """
1914 1913 opts = pycompat.byteskwargs(opts)
1915 1914
1916 1915 # kludge: _chistedit only works for starting an edit, not aborting
1917 1916 # or continuing, so fall back to regular _texthistedit for those
1918 1917 # operations.
1919 1918 if ui.interface(b'histedit') == b'curses' and _getgoal(opts) == goalnew:
1920 1919 return _chistedit(ui, repo, freeargs, opts)
1921 1920 return _texthistedit(ui, repo, freeargs, opts)
1922 1921
1923 1922
1924 1923 def _texthistedit(ui, repo, freeargs, opts):
1925 1924 state = histeditstate(repo)
1926 1925 with repo.wlock() as wlock, repo.lock() as lock:
1927 1926 state.wlock = wlock
1928 1927 state.lock = lock
1929 1928 _histedit(ui, repo, state, freeargs, opts)
1930 1929
1931 1930
1932 1931 goalcontinue = b'continue'
1933 1932 goalabort = b'abort'
1934 1933 goaleditplan = b'edit-plan'
1935 1934 goalnew = b'new'
1936 1935
1937 1936
1938 1937 def _getgoal(opts):
1939 1938 if opts.get(b'continue'):
1940 1939 return goalcontinue
1941 1940 if opts.get(b'abort'):
1942 1941 return goalabort
1943 1942 if opts.get(b'edit_plan'):
1944 1943 return goaleditplan
1945 1944 return goalnew
1946 1945
1947 1946
1948 1947 def _readfile(ui, path):
1949 1948 if path == b'-':
1950 1949 with ui.timeblockedsection(b'histedit'):
1951 1950 return ui.fin.read()
1952 1951 else:
1953 1952 with open(path, b'rb') as f:
1954 1953 return f.read()
1955 1954
1956 1955
1957 1956 def _validateargs(ui, repo, freeargs, opts, goal, rules, revs):
1958 1957 # TODO only abort if we try to histedit mq patches, not just
1959 1958 # blanket if mq patches are applied somewhere
1960 1959 mq = getattr(repo, 'mq', None)
1961 1960 if mq and mq.applied:
1962 1961 raise error.StateError(_(b'source has mq patches applied'))
1963 1962
1964 1963 # basic argument incompatibility processing
1965 1964 outg = opts.get(b'outgoing')
1966 1965 editplan = opts.get(b'edit_plan')
1967 1966 abort = opts.get(b'abort')
1968 1967 force = opts.get(b'force')
1969 1968 if force and not outg:
1970 1969 raise error.InputError(_(b'--force only allowed with --outgoing'))
1971 1970 if goal == b'continue':
1972 1971 if any((outg, abort, revs, freeargs, rules, editplan)):
1973 1972 raise error.InputError(_(b'no arguments allowed with --continue'))
1974 1973 elif goal == b'abort':
1975 1974 if any((outg, revs, freeargs, rules, editplan)):
1976 1975 raise error.InputError(_(b'no arguments allowed with --abort'))
1977 1976 elif goal == b'edit-plan':
1978 1977 if any((outg, revs, freeargs)):
1979 1978 raise error.InputError(
1980 1979 _(b'only --commands argument allowed with --edit-plan')
1981 1980 )
1982 1981 else:
1983 1982 if outg:
1984 1983 if revs:
1985 1984 raise error.InputError(
1986 1985 _(b'no revisions allowed with --outgoing')
1987 1986 )
1988 1987 if len(freeargs) > 1:
1989 1988 raise error.InputError(
1990 1989 _(b'only one repo argument allowed with --outgoing')
1991 1990 )
1992 1991 else:
1993 1992 revs.extend(freeargs)
1994 1993 if len(revs) == 0:
1995 1994 defaultrev = destutil.desthistedit(ui, repo)
1996 1995 if defaultrev is not None:
1997 1996 revs.append(defaultrev)
1998 1997
1999 1998 if len(revs) != 1:
2000 1999 raise error.InputError(
2001 2000 _(b'histedit requires exactly one ancestor revision')
2002 2001 )
2003 2002
2004 2003
2005 2004 def _histedit(ui, repo, state, freeargs, opts):
2006 2005 fm = ui.formatter(b'histedit', opts)
2007 2006 fm.startitem()
2008 2007 goal = _getgoal(opts)
2009 2008 revs = opts.get(b'rev', [])
2010 2009 nobackup = not ui.configbool(b'rewrite', b'backup-bundle')
2011 2010 rules = opts.get(b'commands', b'')
2012 2011 state.keep = opts.get(b'keep', False)
2013 2012
2014 2013 _validateargs(ui, repo, freeargs, opts, goal, rules, revs)
2015 2014
2016 2015 hastags = False
2017 2016 if revs:
2018 2017 revs = logcmdutil.revrange(repo, revs)
2019 2018 ctxs = [repo[rev] for rev in revs]
2020 2019 for ctx in ctxs:
2021 2020 tags = [tag for tag in ctx.tags() if tag != b'tip']
2022 2021 if not hastags:
2023 2022 hastags = len(tags)
2024 2023 if hastags:
2025 2024 if ui.promptchoice(
2026 2025 _(
2027 2026 b'warning: tags associated with the given'
2028 2027 b' changeset will be lost after histedit.\n'
2029 2028 b'do you want to continue (yN)? $$ &Yes $$ &No'
2030 2029 ),
2031 2030 default=1,
2032 2031 ):
2033 2032 raise error.CanceledError(_(b'histedit cancelled\n'))
2034 2033 # rebuild state
2035 2034 if goal == goalcontinue:
2036 2035 state.read()
2037 2036 state = bootstrapcontinue(ui, state, opts)
2038 2037 elif goal == goaleditplan:
2039 2038 _edithisteditplan(ui, repo, state, rules)
2040 2039 return
2041 2040 elif goal == goalabort:
2042 2041 _aborthistedit(ui, repo, state, nobackup=nobackup)
2043 2042 return
2044 2043 else:
2045 2044 # goal == goalnew
2046 2045 _newhistedit(ui, repo, state, revs, freeargs, opts)
2047 2046
2048 2047 _continuehistedit(ui, repo, state)
2049 2048 _finishhistedit(ui, repo, state, fm)
2050 2049 fm.end()
2051 2050
2052 2051
2053 2052 def _continuehistedit(ui, repo, state):
2054 2053 """This function runs after either:
2055 2054 - bootstrapcontinue (if the goal is 'continue')
2056 2055 - _newhistedit (if the goal is 'new')
2057 2056 """
2058 2057 # preprocess rules so that we can hide inner folds from the user
2059 2058 # and only show one editor
2060 2059 actions = state.actions[:]
2061 2060 for idx, (action, nextact) in enumerate(zip(actions, actions[1:] + [None])):
2062 2061 if action.verb == b'fold' and nextact and nextact.verb == b'fold':
2063 2062 state.actions[idx].__class__ = _multifold
2064 2063
2065 2064 # Force an initial state file write, so the user can run --abort/continue
2066 2065 # even if there's an exception before the first transaction serialize.
2067 2066 state.write()
2068 2067
2069 2068 tr = None
2070 2069 # Don't use singletransaction by default since it rolls the entire
2071 2070 # transaction back if an unexpected exception happens (like a
2072 2071 # pretxncommit hook throws, or the user aborts the commit msg editor).
2073 2072 if ui.configbool(b"histedit", b"singletransaction"):
2074 2073 # Don't use a 'with' for the transaction, since actions may close
2075 2074 # and reopen a transaction. For example, if the action executes an
2076 2075 # external process it may choose to commit the transaction first.
2077 2076 tr = repo.transaction(b'histedit')
2078 2077 progress = ui.makeprogress(
2079 2078 _(b"editing"), unit=_(b'changes'), total=len(state.actions)
2080 2079 )
2081 2080 with progress, util.acceptintervention(tr):
2082 2081 while state.actions:
2083 2082 state.write(tr=tr)
2084 2083 actobj = state.actions[0]
2085 2084 progress.increment(item=actobj.torule())
2086 2085 ui.debug(
2087 2086 b'histedit: processing %s %s\n' % (actobj.verb, actobj.torule())
2088 2087 )
2089 2088 parentctx, replacement_ = actobj.run()
2090 2089 state.parentctxnode = parentctx.node()
2091 2090 state.replacements.extend(replacement_)
2092 2091 state.actions.pop(0)
2093 2092
2094 2093 state.write()
2095 2094
2096 2095
2097 2096 def _finishhistedit(ui, repo, state, fm):
2098 2097 """This action runs when histedit is finishing its session"""
2099 2098 mergemod.update(repo[state.parentctxnode])
2100 2099
2101 2100 mapping, tmpnodes, created, ntm = processreplacement(state)
2102 2101 if mapping:
2103 2102 for prec, succs in mapping.items():
2104 2103 if not succs:
2105 2104 ui.debug(b'histedit: %s is dropped\n' % short(prec))
2106 2105 else:
2107 2106 ui.debug(
2108 2107 b'histedit: %s is replaced by %s\n'
2109 2108 % (short(prec), short(succs[0]))
2110 2109 )
2111 2110 if len(succs) > 1:
2112 2111 m = b'histedit: %s'
2113 2112 for n in succs[1:]:
2114 2113 ui.debug(m % short(n))
2115 2114
2116 2115 if not state.keep:
2117 2116 if mapping:
2118 2117 movetopmostbookmarks(repo, state.topmost, ntm)
2119 2118 # TODO update mq state
2120 2119 else:
2121 2120 mapping = {}
2122 2121
2123 2122 for n in tmpnodes:
2124 2123 if n in repo:
2125 2124 mapping[n] = ()
2126 2125
2127 2126 # remove entries about unknown nodes
2128 2127 has_node = repo.unfiltered().changelog.index.has_node
2129 2128 mapping = {
2130 2129 k: v
2131 2130 for k, v in mapping.items()
2132 2131 if has_node(k) and all(has_node(n) for n in v)
2133 2132 }
2134 2133 scmutil.cleanupnodes(repo, mapping, b'histedit')
2135 2134 hf = fm.hexfunc
2136 2135 fl = fm.formatlist
2137 2136 fd = fm.formatdict
2138 2137 nodechanges = fd(
2139 2138 {
2140 2139 hf(oldn): fl([hf(n) for n in newn], name=b'node')
2141 2140 for oldn, newn in mapping.items()
2142 2141 },
2143 2142 key=b"oldnode",
2144 2143 value=b"newnodes",
2145 2144 )
2146 2145 fm.data(nodechanges=nodechanges)
2147 2146
2148 2147 state.clear()
2149 2148 if os.path.exists(repo.sjoin(b'undo')):
2150 2149 os.unlink(repo.sjoin(b'undo'))
2151 2150 if repo.vfs.exists(b'histedit-last-edit.txt'):
2152 2151 repo.vfs.unlink(b'histedit-last-edit.txt')
2153 2152
2154 2153
2155 2154 def _aborthistedit(ui, repo, state, nobackup=False):
2156 2155 try:
2157 2156 state.read()
2158 2157 __, leafs, tmpnodes, __ = processreplacement(state)
2159 2158 ui.debug(b'restore wc to old parent %s\n' % short(state.topmost))
2160 2159
2161 2160 # Recover our old commits if necessary
2162 2161 if not state.topmost in repo and state.backupfile:
2163 2162 backupfile = repo.vfs.join(state.backupfile)
2164 2163 f = hg.openpath(ui, backupfile)
2165 2164 gen = exchange.readbundle(ui, f, backupfile)
2166 2165 with repo.transaction(b'histedit.abort') as tr:
2167 2166 bundle2.applybundle(
2168 2167 repo,
2169 2168 gen,
2170 2169 tr,
2171 2170 source=b'histedit',
2172 2171 url=b'bundle:' + backupfile,
2173 2172 )
2174 2173
2175 2174 os.remove(backupfile)
2176 2175
2177 2176 # check whether we should update away
2178 2177 if repo.unfiltered().revs(
2179 2178 b'parents() and (%n or %ln::)',
2180 2179 state.parentctxnode,
2181 2180 leafs | tmpnodes,
2182 2181 ):
2183 2182 hg.clean(repo, state.topmost, show_stats=True, quietempty=True)
2184 2183 cleanupnode(ui, repo, tmpnodes, nobackup=nobackup)
2185 2184 cleanupnode(ui, repo, leafs, nobackup=nobackup)
2186 2185 except Exception:
2187 2186 if state.inprogress():
2188 2187 ui.warn(
2189 2188 _(
2190 2189 b'warning: encountered an exception during histedit '
2191 2190 b'--abort; the repository may not have been completely '
2192 2191 b'cleaned up\n'
2193 2192 )
2194 2193 )
2195 2194 raise
2196 2195 finally:
2197 2196 state.clear()
2198 2197
2199 2198
2200 2199 def hgaborthistedit(ui, repo):
2201 2200 state = histeditstate(repo)
2202 2201 nobackup = not ui.configbool(b'rewrite', b'backup-bundle')
2203 2202 with repo.wlock() as wlock, repo.lock() as lock:
2204 2203 state.wlock = wlock
2205 2204 state.lock = lock
2206 2205 _aborthistedit(ui, repo, state, nobackup=nobackup)
2207 2206
2208 2207
2209 2208 def _edithisteditplan(ui, repo, state, rules):
2210 2209 state.read()
2211 2210 if not rules:
2212 2211 comment = geteditcomment(
2213 2212 ui, short(state.parentctxnode), short(state.topmost)
2214 2213 )
2215 2214 rules = ruleeditor(repo, ui, state.actions, comment)
2216 2215 else:
2217 2216 rules = _readfile(ui, rules)
2218 2217 actions = parserules(rules, state)
2219 2218 ctxs = [repo[act.node] for act in state.actions if act.node]
2220 2219 warnverifyactions(ui, repo, actions, state, ctxs)
2221 2220 state.actions = actions
2222 2221 state.write()
2223 2222
2224 2223
2225 2224 def _newhistedit(ui, repo, state, revs, freeargs, opts):
2226 2225 outg = opts.get(b'outgoing')
2227 2226 rules = opts.get(b'commands', b'')
2228 2227 force = opts.get(b'force')
2229 2228
2230 2229 cmdutil.checkunfinished(repo)
2231 2230 cmdutil.bailifchanged(repo)
2232 2231
2233 2232 topmost = repo.dirstate.p1()
2234 2233 if outg:
2235 2234 if freeargs:
2236 2235 remote = freeargs[0]
2237 2236 else:
2238 2237 remote = None
2239 2238 root = findoutgoing(ui, repo, remote, force, opts)
2240 2239 else:
2241 2240 rr = list(repo.set(b'roots(%ld)', logcmdutil.revrange(repo, revs)))
2242 2241 if len(rr) != 1:
2243 2242 raise error.InputError(
2244 2243 _(
2245 2244 b'The specified revisions must have '
2246 2245 b'exactly one common root'
2247 2246 )
2248 2247 )
2249 2248 root = rr[0].node()
2250 2249
2251 2250 revs = between(repo, root, topmost, state.keep)
2252 2251 if not revs:
2253 2252 raise error.InputError(
2254 2253 _(b'%s is not an ancestor of working directory') % short(root)
2255 2254 )
2256 2255
2257 2256 ctxs = [repo[r] for r in revs]
2258 2257
2259 2258 wctx = repo[None]
2260 2259 # Please don't ask me why `ancestors` is this value. I figured it
2261 2260 # out with print-debugging, not by actually understanding what the
2262 2261 # merge code is doing. :(
2263 2262 ancs = [repo[b'.']]
2264 2263 # Sniff-test to make sure we won't collide with untracked files in
2265 2264 # the working directory. If we don't do this, we can get a
2266 2265 # collision after we've started histedit and backing out gets ugly
2267 2266 # for everyone, especially the user.
2268 2267 for c in [ctxs[0].p1()] + ctxs:
2269 2268 try:
2270 2269 mergemod.calculateupdates(
2271 2270 repo,
2272 2271 wctx,
2273 2272 c,
2274 2273 ancs,
2275 2274 # These parameters were determined by print-debugging
2276 2275 # what happens later on inside histedit.
2277 2276 branchmerge=False,
2278 2277 force=False,
2279 2278 acceptremote=False,
2280 2279 followcopies=False,
2281 2280 )
2282 2281 except error.Abort:
2283 2282 raise error.StateError(
2284 2283 _(
2285 2284 b"untracked files in working directory conflict with files in %s"
2286 2285 )
2287 2286 % c
2288 2287 )
2289 2288
2290 2289 if not rules:
2291 2290 comment = geteditcomment(ui, short(root), short(topmost))
2292 2291 actions = [pick(state, r) for r in revs]
2293 2292 rules = ruleeditor(repo, ui, actions, comment)
2294 2293 else:
2295 2294 rules = _readfile(ui, rules)
2296 2295 actions = parserules(rules, state)
2297 2296 warnverifyactions(ui, repo, actions, state, ctxs)
2298 2297
2299 2298 parentctxnode = repo[root].p1().node()
2300 2299
2301 2300 state.parentctxnode = parentctxnode
2302 2301 state.actions = actions
2303 2302 state.topmost = topmost
2304 2303 state.replacements = []
2305 2304
2306 2305 ui.log(
2307 2306 b"histedit",
2308 2307 b"%d actions to histedit\n",
2309 2308 len(actions),
2310 2309 histedit_num_actions=len(actions),
2311 2310 )
2312 2311
2313 2312 # Create a backup so we can always abort completely.
2314 2313 backupfile = None
2315 2314 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
2316 2315 backupfile = repair.backupbundle(
2317 2316 repo, [parentctxnode], [topmost], root, b'histedit'
2318 2317 )
2319 2318 state.backupfile = backupfile
2320 2319
2321 2320
2322 2321 def _getsummary(ctx):
2323 2322 return stringutil.firstline(ctx.description())
2324 2323
2325 2324
2326 2325 def bootstrapcontinue(ui, state, opts):
2327 2326 repo = state.repo
2328 2327
2329 2328 ms = mergestatemod.mergestate.read(repo)
2330 2329 mergeutil.checkunresolved(ms)
2331 2330
2332 2331 if state.actions:
2333 2332 actobj = state.actions.pop(0)
2334 2333
2335 2334 if _isdirtywc(repo):
2336 2335 actobj.continuedirty()
2337 2336 if _isdirtywc(repo):
2338 2337 abortdirty()
2339 2338
2340 2339 parentctx, replacements = actobj.continueclean()
2341 2340
2342 2341 state.parentctxnode = parentctx.node()
2343 2342 state.replacements.extend(replacements)
2344 2343
2345 2344 return state
2346 2345
2347 2346
2348 2347 def between(repo, old, new, keep):
2349 2348 """select and validate the set of revision to edit
2350 2349
2351 2350 When keep is false, the specified set can't have children."""
2352 2351 revs = repo.revs(b'%n::%n', old, new)
2353 2352 if revs and not keep:
2354 2353 rewriteutil.precheck(repo, revs, b'edit')
2355 2354 if repo.revs(b'(%ld) and merge()', revs):
2356 2355 raise error.StateError(
2357 2356 _(b'cannot edit history that contains merges')
2358 2357 )
2359 2358 return pycompat.maplist(repo.changelog.node, revs)
2360 2359
2361 2360
2362 2361 def ruleeditor(repo, ui, actions, editcomment=b""):
2363 2362 """open an editor to edit rules
2364 2363
2365 2364 rules are in the format [ [act, ctx], ...] like in state.rules
2366 2365 """
2367 2366 if repo.ui.configbool(b"experimental", b"histedit.autoverb"):
2368 2367 newact = util.sortdict()
2369 2368 for act in actions:
2370 2369 ctx = repo[act.node]
2371 2370 summary = _getsummary(ctx)
2372 2371 fword = summary.split(b' ', 1)[0].lower()
2373 2372 added = False
2374 2373
2375 2374 # if it doesn't end with the special character '!' just skip this
2376 2375 if fword.endswith(b'!'):
2377 2376 fword = fword[:-1]
2378 2377 if fword in primaryactions | secondaryactions | tertiaryactions:
2379 2378 act.verb = fword
2380 2379 # get the target summary
2381 2380 tsum = summary[len(fword) + 1 :].lstrip()
2382 2381 # safe but slow: reverse iterate over the actions so we
2383 2382 # don't clash on two commits having the same summary
2384 2383 for na, l in reversed(list(newact.items())):
2385 2384 actx = repo[na.node]
2386 2385 asum = _getsummary(actx)
2387 2386 if asum == tsum:
2388 2387 added = True
2389 2388 l.append(act)
2390 2389 break
2391 2390
2392 2391 if not added:
2393 2392 newact[act] = []
2394 2393
2395 2394 # copy over and flatten the new list
2396 2395 actions = []
2397 2396 for na, l in newact.items():
2398 2397 actions.append(na)
2399 2398 actions += l
2400 2399
2401 2400 rules = b'\n'.join([act.torule() for act in actions])
2402 2401 rules += b'\n\n'
2403 2402 rules += editcomment
2404 2403 rules = ui.edit(
2405 2404 rules,
2406 2405 ui.username(),
2407 2406 {b'prefix': b'histedit'},
2408 2407 repopath=repo.path,
2409 2408 action=b'histedit',
2410 2409 )
2411 2410
2412 2411 # Save edit rules in .hg/histedit-last-edit.txt in case
2413 2412 # the user needs to ask for help after something
2414 2413 # surprising happens.
2415 2414 with repo.vfs(b'histedit-last-edit.txt', b'wb') as f:
2416 2415 f.write(rules)
2417 2416
2418 2417 return rules
2419 2418
2420 2419
2421 2420 def parserules(rules, state):
2422 2421 """Read the histedit rules string and return list of action objects"""
2423 2422 rules = [
2424 2423 l
2425 2424 for l in (r.strip() for r in rules.splitlines())
2426 2425 if l and not l.startswith(b'#')
2427 2426 ]
2428 2427 actions = []
2429 2428 for r in rules:
2430 2429 if b' ' not in r:
2431 2430 raise error.ParseError(_(b'malformed line "%s"') % r)
2432 2431 verb, rest = r.split(b' ', 1)
2433 2432
2434 2433 if verb not in actiontable:
2435 2434 raise error.ParseError(_(b'unknown action "%s"') % verb)
2436 2435
2437 2436 action = actiontable[verb].fromrule(state, rest)
2438 2437 actions.append(action)
2439 2438 return actions
2440 2439
2441 2440
2442 2441 def warnverifyactions(ui, repo, actions, state, ctxs):
2443 2442 try:
2444 2443 verifyactions(actions, state, ctxs)
2445 2444 except error.ParseError:
2446 2445 if repo.vfs.exists(b'histedit-last-edit.txt'):
2447 2446 ui.warn(
2448 2447 _(
2449 2448 b'warning: histedit rules saved '
2450 2449 b'to: .hg/histedit-last-edit.txt\n'
2451 2450 )
2452 2451 )
2453 2452 raise
2454 2453
2455 2454
2456 2455 def verifyactions(actions, state, ctxs):
2457 2456 """Verify that there exists exactly one action per given changeset and
2458 2457 other constraints.
2459 2458
2460 2459 Will abort if there are to many or too few rules, a malformed rule,
2461 2460 or a rule on a changeset outside of the user-given range.
2462 2461 """
2463 2462 expected = {c.node() for c in ctxs}
2464 2463 seen = set()
2465 2464 prev = None
2466 2465
2467 2466 if actions and actions[0].verb in [b'roll', b'fold']:
2468 2467 raise error.ParseError(
2469 2468 _(b'first changeset cannot use verb "%s"') % actions[0].verb
2470 2469 )
2471 2470
2472 2471 for action in actions:
2473 2472 action.verify(prev, expected, seen)
2474 2473 prev = action
2475 2474 if action.node is not None:
2476 2475 seen.add(action.node)
2477 2476 missing = sorted(expected - seen) # sort to stabilize output
2478 2477
2479 2478 if state.repo.ui.configbool(b'histedit', b'dropmissing'):
2480 2479 if len(actions) == 0:
2481 2480 raise error.ParseError(
2482 2481 _(b'no rules provided'),
2483 2482 hint=_(b'use strip extension to remove commits'),
2484 2483 )
2485 2484
2486 2485 drops = [drop(state, n) for n in missing]
2487 2486 # put the in the beginning so they execute immediately and
2488 2487 # don't show in the edit-plan in the future
2489 2488 actions[:0] = drops
2490 2489 elif missing:
2491 2490 raise error.ParseError(
2492 2491 _(b'missing rules for changeset %s') % short(missing[0]),
2493 2492 hint=_(
2494 2493 b'use "drop %s" to discard, see also: '
2495 2494 b"'hg help -e histedit.config'"
2496 2495 )
2497 2496 % short(missing[0]),
2498 2497 )
2499 2498
2500 2499
2501 2500 def adjustreplacementsfrommarkers(repo, oldreplacements):
2502 2501 """Adjust replacements from obsolescence markers
2503 2502
2504 2503 Replacements structure is originally generated based on
2505 2504 histedit's state and does not account for changes that are
2506 2505 not recorded there. This function fixes that by adding
2507 2506 data read from obsolescence markers"""
2508 2507 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
2509 2508 return oldreplacements
2510 2509
2511 2510 unfi = repo.unfiltered()
2512 2511 get_rev = unfi.changelog.index.get_rev
2513 2512 obsstore = repo.obsstore
2514 2513 newreplacements = list(oldreplacements)
2515 2514 oldsuccs = [r[1] for r in oldreplacements]
2516 2515 # successors that have already been added to succstocheck once
2517 2516 seensuccs = set().union(
2518 2517 *oldsuccs
2519 2518 ) # create a set from an iterable of tuples
2520 2519 succstocheck = list(seensuccs)
2521 2520 while succstocheck:
2522 2521 n = succstocheck.pop()
2523 2522 missing = get_rev(n) is None
2524 2523 markers = obsstore.successors.get(n, ())
2525 2524 if missing and not markers:
2526 2525 # dead end, mark it as such
2527 2526 newreplacements.append((n, ()))
2528 2527 for marker in markers:
2529 2528 nsuccs = marker[1]
2530 2529 newreplacements.append((n, nsuccs))
2531 2530 for nsucc in nsuccs:
2532 2531 if nsucc not in seensuccs:
2533 2532 seensuccs.add(nsucc)
2534 2533 succstocheck.append(nsucc)
2535 2534
2536 2535 return newreplacements
2537 2536
2538 2537
2539 2538 def processreplacement(state):
2540 2539 """process the list of replacements to return
2541 2540
2542 2541 1) the final mapping between original and created nodes
2543 2542 2) the list of temporary node created by histedit
2544 2543 3) the list of new commit created by histedit"""
2545 2544 replacements = adjustreplacementsfrommarkers(state.repo, state.replacements)
2546 2545 allsuccs = set()
2547 2546 replaced = set()
2548 2547 fullmapping = {}
2549 2548 # initialize basic set
2550 2549 # fullmapping records all operations recorded in replacement
2551 2550 for rep in replacements:
2552 2551 allsuccs.update(rep[1])
2553 2552 replaced.add(rep[0])
2554 2553 fullmapping.setdefault(rep[0], set()).update(rep[1])
2555 2554 new = allsuccs - replaced
2556 2555 tmpnodes = allsuccs & replaced
2557 2556 # Reduce content fullmapping into direct relation between original nodes
2558 2557 # and final node created during history edition
2559 2558 # Dropped changeset are replaced by an empty list
2560 2559 toproceed = set(fullmapping)
2561 2560 final = {}
2562 2561 while toproceed:
2563 2562 for x in list(toproceed):
2564 2563 succs = fullmapping[x]
2565 2564 for s in list(succs):
2566 2565 if s in toproceed:
2567 2566 # non final node with unknown closure
2568 2567 # We can't process this now
2569 2568 break
2570 2569 elif s in final:
2571 2570 # non final node, replace with closure
2572 2571 succs.remove(s)
2573 2572 succs.update(final[s])
2574 2573 else:
2575 2574 final[x] = succs
2576 2575 toproceed.remove(x)
2577 2576 # remove tmpnodes from final mapping
2578 2577 for n in tmpnodes:
2579 2578 del final[n]
2580 2579 # we expect all changes involved in final to exist in the repo
2581 2580 # turn `final` into list (topologically sorted)
2582 2581 get_rev = state.repo.changelog.index.get_rev
2583 2582 for prec, succs in final.items():
2584 2583 final[prec] = sorted(succs, key=get_rev)
2585 2584
2586 2585 # computed topmost element (necessary for bookmark)
2587 2586 if new:
2588 2587 newtopmost = sorted(new, key=state.repo.changelog.rev)[-1]
2589 2588 elif not final:
2590 2589 # Nothing rewritten at all. we won't need `newtopmost`
2591 2590 # It is the same as `oldtopmost` and `processreplacement` know it
2592 2591 newtopmost = None
2593 2592 else:
2594 2593 # every body died. The newtopmost is the parent of the root.
2595 2594 r = state.repo.changelog.rev
2596 2595 newtopmost = state.repo[sorted(final, key=r)[0]].p1().node()
2597 2596
2598 2597 return final, tmpnodes, new, newtopmost
2599 2598
2600 2599
2601 2600 def movetopmostbookmarks(repo, oldtopmost, newtopmost):
2602 2601 """Move bookmark from oldtopmost to newly created topmost
2603 2602
2604 2603 This is arguably a feature and we may only want that for the active
2605 2604 bookmark. But the behavior is kept compatible with the old version for now.
2606 2605 """
2607 2606 if not oldtopmost or not newtopmost:
2608 2607 return
2609 2608 oldbmarks = repo.nodebookmarks(oldtopmost)
2610 2609 if oldbmarks:
2611 2610 with repo.lock(), repo.transaction(b'histedit') as tr:
2612 2611 marks = repo._bookmarks
2613 2612 changes = []
2614 2613 for name in oldbmarks:
2615 2614 changes.append((name, newtopmost))
2616 2615 marks.applychanges(repo, tr, changes)
2617 2616
2618 2617
2619 2618 def cleanupnode(ui, repo, nodes, nobackup=False):
2620 2619 """strip a group of nodes from the repository
2621 2620
2622 2621 The set of node to strip may contains unknown nodes."""
2623 2622 with repo.lock():
2624 2623 # do not let filtering get in the way of the cleanse
2625 2624 # we should probably get rid of obsolescence marker created during the
2626 2625 # histedit, but we currently do not have such information.
2627 2626 repo = repo.unfiltered()
2628 2627 # Find all nodes that need to be stripped
2629 2628 # (we use %lr instead of %ln to silently ignore unknown items)
2630 2629 has_node = repo.changelog.index.has_node
2631 2630 nodes = sorted(n for n in nodes if has_node(n))
2632 2631 roots = [c.node() for c in repo.set(b"roots(%ln)", nodes)]
2633 2632 if roots:
2634 2633 backup = not nobackup
2635 2634 repair.strip(ui, repo, roots, backup=backup)
2636 2635
2637 2636
2638 2637 def stripwrapper(orig, ui, repo, nodelist, *args, **kwargs):
2639 2638 if isinstance(nodelist, bytes):
2640 2639 nodelist = [nodelist]
2641 2640 state = histeditstate(repo)
2642 2641 if state.inprogress():
2643 2642 state.read()
2644 2643 histedit_nodes = {
2645 2644 action.node for action in state.actions if action.node
2646 2645 }
2647 2646 common_nodes = histedit_nodes & set(nodelist)
2648 2647 if common_nodes:
2649 2648 raise error.Abort(
2650 2649 _(b"histedit in progress, can't strip %s")
2651 2650 % b', '.join(short(x) for x in common_nodes)
2652 2651 )
2653 2652 return orig(ui, repo, nodelist, *args, **kwargs)
2654 2653
2655 2654
2656 2655 extensions.wrapfunction(repair, b'strip', stripwrapper)
2657 2656
2658 2657
2659 2658 def summaryhook(ui, repo):
2660 2659 state = histeditstate(repo)
2661 2660 if not state.inprogress():
2662 2661 return
2663 2662 state.read()
2664 2663 if state.actions:
2665 2664 # i18n: column positioning for "hg summary"
2666 2665 ui.write(
2667 2666 _(b'hist: %s (histedit --continue)\n')
2668 2667 % (
2669 2668 ui.label(_(b'%d remaining'), b'histedit.remaining')
2670 2669 % len(state.actions)
2671 2670 )
2672 2671 )
2673 2672
2674 2673
2675 2674 def extsetup(ui):
2676 2675 cmdutil.summaryhooks.add(b'histedit', summaryhook)
2677 2676 statemod.addunfinished(
2678 2677 b'histedit',
2679 2678 fname=b'histedit-state',
2680 2679 allowcommit=True,
2681 2680 continueflag=True,
2682 2681 abortfunc=hgaborthistedit,
2683 2682 )
General Comments 0
You need to be logged in to leave comments. Login now