Debian Codegraph @

hgext/absorb.py

raw
1 # absorb.py
2 #
3 # Copyright 2016 Facebook, Inc.
4 #
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
7
8 """apply working directory changes to changesets (EXPERIMENTAL)
9
10 The absorb extension provides a command to use annotate information to
11 amend modified chunks into the corresponding non-public changesets.
12
13 ::
14
15 [absorb]
16 # only check 50 recent non-public changesets at most
17 max-stack-size = 50
18 # whether to add noise to new commits to avoid obsolescence cycle
19 add-noise = 1
20 # make `amend --correlated` a shortcut to the main command
21 amend-flag = correlated
22
23 [color]
24 absorb.description = yellow
25 absorb.node = blue bold
26 absorb.path = bold
27 """
28
29 # TODO:
30 # * Rename config items to [commands] namespace
31 # * Converge getdraftstack() with other code in core
32 # * move many attributes on fixupstate to be private
33
34 from __future__ import annotations
35
36 import collections
37
38 from mercurial.i18n import _
39 from mercurial.node import (
40 hex,
41 short,
42 )
43 from mercurial import (
44 cmdutil,
45 commands,
46 context,
47 crecord,
48 error,
49 linelog,
50 mdiff,
51 obsolete,
52 patch,
53 phases,
54 pycompat,
55 registrar,
56 rewriteutil,
57 scmutil,
58 util,
59 )
60 from mercurial.utils import stringutil
61
62 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
63 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
64 # be specifying the version(s) of Mercurial they are tested with, or
65 # leave the attribute unspecified.
66 testedwith = b'ships-with-hg-core'
67
68 cmdtable = {}
69 command = registrar.command(cmdtable)
70
71 configtable = {}
72 configitem = registrar.configitem(configtable)
73
74 configitem(b'absorb', b'add-noise', default=True)
75 configitem(b'absorb', b'amend-flag', default=None)
76 configitem(b'absorb', b'max-stack-size', default=50)
77
78 colortable = {
79 b'absorb.description': b'yellow',
80 b'absorb.node': b'blue bold',
81 b'absorb.path': b'bold',
82 }
83
84 defaultdict = collections.defaultdict
85
86
87 class nullui:
88 """blank ui object doing nothing"""
89
90 debugflag = False
91 verbose = False
92 quiet = True
93
94 def __getitem__(name):
95 def nullfunc(*args, **kwds):
96 return
97
98 return nullfunc
99
100
101 class emptyfilecontext:
102 """minimal filecontext representing an empty file"""
103
104 def __init__(self, repo):
105 self._repo = repo
106
107 def data(self):
108 return b''
109
110 def node(self):
111 return self._repo.nullid
112
113
114 def uniq(lst):
115 """list -> list. remove duplicated items without changing the order"""
116 seen = set()
117 result = []
118 for x in lst:
119 if x not in seen:
120 seen.add(x)
121 result.append(x)
122 return result
123
124
125 def getdraftstack(headctx, limit=None):
126 """(ctx, int?) -> [ctx]. get a linear stack of non-public changesets.
127
128 changesets are sorted in topo order, oldest first.
129 return at most limit items, if limit is a positive number.
130
131 merges are considered as non-draft as well. i.e. every commit
132 returned has and only has 1 parent.
133 """
134 ctx = headctx
135 result = []
136 while ctx.phase() != phases.public:
137 if limit and len(result) >= limit:
138 break
139 parents = ctx.parents()
140 if len(parents) != 1:
141 break
142 result.append(ctx)
143 ctx = parents[0]
144 result.reverse()
145 return result
146
147
148 def getfilestack(stack, path, seenfctxs=None):
149 """([ctx], str, set) -> [fctx], {ctx: fctx}
150
151 stack is a list of contexts, from old to new. usually they are what
152 "getdraftstack" returns.
153
154 follows renames, but not copies.
155
156 seenfctxs is a set of filecontexts that will be considered "immutable".
157 they are usually what this function returned in earlier calls, useful
158 to avoid issues that a file was "moved" to multiple places and was then
159 modified differently, like: "a" was copied to "b", "a" was also copied to
160 "c" and then "a" was deleted, then both "b" and "c" were "moved" from "a"
161 and we enforce only one of them to be able to affect "a"'s content.
162
163 return an empty list and an empty dict, if the specified path does not
164 exist in stack[-1] (the top of the stack).
165
166 otherwise, return a list of de-duplicated filecontexts, and the map to
167 convert ctx in the stack to fctx, for possible mutable fctxs. the first item
168 of the list would be outside the stack and should be considered immutable.
169 the remaining items are within the stack.
170
171 for example, given the following changelog and corresponding filelog
172 revisions:
173
174 changelog: 3----4----5----6----7
175 filelog: x 0----1----1----2 (x: no such file yet)
176
177 - if stack = [5, 6, 7], returns ([0, 1, 2], {5: 1, 6: 1, 7: 2})
178 - if stack = [3, 4, 5], returns ([e, 0, 1], {4: 0, 5: 1}), where "e" is a
179 dummy empty filecontext.
180 - if stack = [2], returns ([], {})
181 - if stack = [7], returns ([1, 2], {7: 2})
182 - if stack = [6, 7], returns ([1, 2], {6: 1, 7: 2}), although {6: 1} can be
183 removed, since 1 is immutable.
184 """
185 if seenfctxs is None:
186 seenfctxs = set()
187 assert stack
188
189 if path not in stack[-1]:
190 return [], {}
191
192 fctxs = []
193 fctxmap = {}
194
195 pctx = stack[0].p1() # the public (immutable) ctx we stop at
196 for ctx in reversed(stack):
197 if path not in ctx: # the file is added in the next commit
198 pctx = ctx
199 break
200 fctx = ctx[path]
201 fctxs.append(fctx)
202 if fctx in seenfctxs: # treat fctx as the immutable one
203 pctx = None # do not add another immutable fctx
204 break
205 fctxmap[ctx] = fctx # only for mutable fctxs
206 copy = fctx.copysource()
207 if copy:
208 path = copy # follow rename
209 if path in ctx: # but do not follow copy
210 pctx = ctx.p1()
211 break
212
213 if pctx is not None: # need an extra immutable fctx
214 if path in pctx:
215 fctxs.append(pctx[path])
216 else:
217 fctxs.append(emptyfilecontext(pctx.repo()))
218
219 fctxs.reverse()
220 # note: we rely on a property of hg: filerev is not reused for linear
221 # history. i.e. it's impossible to have:
222 # changelog: 4----5----6 (linear, no merges)
223 # filelog: 1----2----1
224 # ^ reuse filerev (impossible)
225 # because parents are part of the hash. if that's not true, we need to
226 # remove uniq and find a different way to identify fctxs.
227 return uniq(fctxs), fctxmap
228
229
230 class overlaystore(patch.filestore):
231 """read-only, hybrid store based on a dict and ctx.
232 memworkingcopy: {path: content}, overrides file contents.
233 """
234
235 def __init__(self, basectx, memworkingcopy):
236 self.basectx = basectx
237 self.memworkingcopy = memworkingcopy
238
239 def getfile(self, path):
240 """comply with mercurial.patch.filestore.getfile"""
241 if path not in self.basectx:
242 return None, None, None
243 fctx = self.basectx[path]
244 if path in self.memworkingcopy:
245 content = self.memworkingcopy[path]
246 else:
247 content = fctx.data()
248 mode = (fctx.islink(), fctx.isexec())
249 copy = fctx.copysource()
250 return content, mode, copy
251
252
253 def overlaycontext(memworkingcopy, ctx, parents=None, extra=None, desc=None):
254 """({path: content}, ctx, (p1node, p2node)?, {}?) -> memctx
255 memworkingcopy overrides file contents.
256 """
257 # parents must contain 2 items: (node1, node2)
258 if parents is None:
259 parents = ctx.repo().changelog.parents(ctx.node())
260 if extra is None:
261 extra = ctx.extra()
262 if desc is None:
263 desc = ctx.description()
264 date = ctx.date()
265 user = ctx.user()
266 files = set(ctx.files()).union(memworkingcopy)
267 store = overlaystore(ctx, memworkingcopy)
268 return context.memctx(
269 repo=ctx.repo(),
270 parents=parents,
271 text=desc,
272 files=files,
273 filectxfn=store,
274 user=user,
275 date=date,
276 branch=None,
277 extra=extra,
278 )
279
280
281 class filefixupstate:
282 """state needed to apply fixups to a single file
283
284 internally, it keeps file contents of several revisions and a linelog.
285
286 the linelog uses odd revision numbers for original contents (fctxs passed
287 to __init__), and even revision numbers for fixups, like:
288
289 linelog rev 1: self.fctxs[0] (from an immutable "public" changeset)
290 linelog rev 2: fixups made to self.fctxs[0]
291 linelog rev 3: self.fctxs[1] (a child of fctxs[0])
292 linelog rev 4: fixups made to self.fctxs[1]
293 ...
294
295 a typical use is like:
296
297 1. call diffwith, to calculate self.fixups
298 2. (optionally), present self.fixups to the user, or change it
299 3. call apply, to apply changes
300 4. read results from "finalcontents", or call getfinalcontent
301 """
302
303 def __init__(self, fctxs, path, ui=None, **opts):
304 """([fctx], ui or None) -> None
305
306 fctxs should be linear, and sorted by topo order - oldest first.
307 fctxs[0] will be considered as "immutable" and will not be changed.
308 """
309 self.fctxs = fctxs
310 self.path = path
311 self.ui = ui or nullui()
312 self.opts = opts
313
314 # following fields are built from fctxs. they exist for perf reason
315 self.contents = [f.data() for f in fctxs]
316 self.contentlines = pycompat.maplist(mdiff.splitnewlines, self.contents)
317 self.linelog = self._buildlinelog()
318 if self.ui.debugflag:
319 assert self._checkoutlinelog() == self.contents
320
321 # following fields will be filled later
322 self.chunkstats = [0, 0] # [adopted, total : int]
323 self.targetlines = [] # [str]
324 self.fixups = [] # [(linelog rev, a1, a2, b1, b2)]
325 self.finalcontents = [] # [str]
326 self.ctxaffected = set()
327
328 def diffwith(self, targetfctx, fm=None):
329 """calculate fixups needed by examining the differences between
330 self.fctxs[-1] and targetfctx, chunk by chunk.
331
332 targetfctx is the target state we move towards. we may or may not be
333 able to get there because not all modified chunks can be amended into
334 a non-public fctx unambiguously.
335
336 call this only once, before apply().
337
338 update self.fixups, self.chunkstats, and self.targetlines.
339 """
340 a = self.contents[-1]
341 alines = self.contentlines[-1]
342 b = targetfctx.data()
343 blines = mdiff.splitnewlines(b)
344 self.targetlines = blines
345
346 self.linelog.annotate(self.linelog.maxrev)
347 annotated = self.linelog.annotateresult # [(linelog rev, linenum)]
348 assert len(annotated) == len(alines)
349 # add a dummy end line to make insertion at the end easier
350 if annotated:
351 dummyendline = (annotated[-1][0], annotated[-1][1] + 1)
352 annotated.append(dummyendline)
353
354 # analyse diff blocks
355 for chunk in self._alldiffchunks(a, b, alines, blines):
356 newfixups = self._analysediffchunk(chunk, annotated)
357 self.chunkstats[0] += bool(newfixups) # 1 or 0
358 self.chunkstats[1] += 1
359 self.fixups += newfixups
360 if fm is not None:
361 self._showchanges(fm, alines, blines, chunk, newfixups)
362
363 def apply(self):
364 """apply self.fixups. update self.linelog, self.finalcontents.
365
366 call this only once, before getfinalcontent(), after diffwith().
367 """
368 # the following is unnecessary, as it's done by "diffwith":
369 # self.linelog.annotate(self.linelog.maxrev)
370 for rev, a1, a2, b1, b2 in reversed(self.fixups):
371 blines = self.targetlines[b1:b2]
372 if self.ui.debugflag:
373 idx = (max(rev - 1, 0)) // 2
374 self.ui.write(
375 _(b'%s: chunk %d:%d -> %d lines\n')
376 % (short(self.fctxs[idx].node()), a1, a2, len(blines))
377 )
378 self.linelog.replacelines(rev, a1, a2, b1, b2)
379 if self.opts.get('edit_lines', False):
380 self.finalcontents = self._checkoutlinelogwithedits()
381 else:
382 self.finalcontents = self._checkoutlinelog()
383
384 def getfinalcontent(self, fctx):
385 """(fctx) -> str. get modified file content for a given filecontext"""
386 idx = self.fctxs.index(fctx)
387 return self.finalcontents[idx]
388
389 def _analysediffchunk(self, chunk, annotated):
390 """analyse a different chunk and return new fixups found
391
392 return [] if no lines from the chunk can be safely applied.
393
394 the chunk (or lines) cannot be safely applied, if, for example:
395 - the modified (deleted) lines belong to a public changeset
396 (self.fctxs[0])
397 - the chunk is a pure insertion and the adjacent lines (at most 2
398 lines) belong to different non-public changesets, or do not belong
399 to any non-public changesets.
400 - the chunk is modifying lines from different changesets.
401 in this case, if the number of lines deleted equals to the number
402 of lines added, assume it's a simple 1:1 map (could be wrong).
403 otherwise, give up.
404 - the chunk is modifying lines from a single non-public changeset,
405 but other revisions touch the area as well. i.e. the lines are
406 not continuous as seen from the linelog.
407 """
408 a1, a2, b1, b2 = chunk
409 # find involved indexes from annotate result
410 involved = annotated[a1:a2]
411 if not involved and annotated: # a1 == a2 and a is not empty
412 # pure insertion, check nearby lines. ignore lines belong
413 # to the public (first) changeset (i.e. annotated[i][0] == 1)
414 nearbylinenums = {a2, max(0, a1 - 1)}
415 involved = [
416 annotated[i] for i in nearbylinenums if annotated[i][0] != 1
417 ]
418 involvedrevs = list({r for r, l in involved})
419 newfixups = []
420 if len(involvedrevs) == 1 and self._iscontinuous(a1, a2 - 1, True):
421 # chunk belongs to a single revision
422 rev = involvedrevs[0]
423 if rev > 1:
424 fixuprev = rev + 1
425 newfixups.append((fixuprev, a1, a2, b1, b2))
426 elif a2 - a1 == b2 - b1 or b1 == b2:
427 # 1:1 line mapping, or chunk was deleted
428 for i in range(a1, a2):
429 rev, linenum = annotated[i]
430 if rev > 1:
431 if b1 == b2: # deletion, simply remove that single line
432 nb1 = nb2 = 0
433 else: # 1:1 line mapping, change the corresponding rev
434 nb1 = b1 + i - a1
435 nb2 = nb1 + 1
436 fixuprev = rev + 1
437 newfixups.append((fixuprev, i, i + 1, nb1, nb2))
438 return self._optimizefixups(newfixups)
439
440 @staticmethod
441 def _alldiffchunks(a, b, alines, blines):
442 """like mdiff.allblocks, but only care about differences"""
443 blocks = mdiff.allblocks(a, b, lines1=alines, lines2=blines)
444 for chunk, btype in blocks:
445 if btype != b'!':
446 continue
447 yield chunk
448
449 def _buildlinelog(self):
450 """calculate the initial linelog based on self.content{,line}s.
451 this is similar to running a partial "annotate".
452 """
453 llog = linelog.linelog()
454 a, alines = b'', []
455 for i in range(len(self.contents)):
456 b, blines = self.contents[i], self.contentlines[i]
457 llrev = i * 2 + 1
458 chunks = self._alldiffchunks(a, b, alines, blines)
459 for a1, a2, b1, b2 in reversed(list(chunks)):
460 llog.replacelines(llrev, a1, a2, b1, b2)
461 a, alines = b, blines
462 return llog
463
464 def _checkoutlinelog(self):
465 """() -> [str]. check out file contents from linelog"""
466 contents = []
467 for i in range(len(self.contents)):
468 rev = (i + 1) * 2
469 self.linelog.annotate(rev)
470 content = b''.join(map(self._getline, self.linelog.annotateresult))
471 contents.append(content)
472 return contents
473
474 def _checkoutlinelogwithedits(self):
475 """() -> [str]. prompt all lines for edit"""
476 alllines = self.linelog.getalllines()
477 # header
478 editortext = (
479 _(
480 b'HG: editing %s\nHG: "y" means the line to the right '
481 b'exists in the changeset to the top\nHG:\n'
482 )
483 % self.fctxs[-1].path()
484 )
485 # [(idx, fctx)]. hide the dummy emptyfilecontext
486 visiblefctxs = [
487 (i, f)
488 for i, f in enumerate(self.fctxs)
489 if not isinstance(f, emptyfilecontext)
490 ]
491 for i, (j, f) in enumerate(visiblefctxs):
492 editortext += _(b'HG: %s/%s %s %s\n') % (
493 b'|' * i,
494 b'-' * (len(visiblefctxs) - i + 1),
495 short(f.node()),
496 f.description().split(b'\n', 1)[0],
497 )
498 editortext += _(b'HG: %s\n') % (b'|' * len(visiblefctxs))
499 # figure out the lifetime of a line, this is relatively inefficient,
500 # but probably fine
501 lineset = defaultdict(lambda: set()) # {(llrev, linenum): {llrev}}
502 for i, f in visiblefctxs:
503 self.linelog.annotate((i + 1) * 2)
504 for l in self.linelog.annotateresult:
505 lineset[l].add(i)
506 # append lines
507 for l in alllines:
508 editortext += b' %s : %s' % (
509 b''.join(
510 [
511 (b'y' if i in lineset[l] else b' ')
512 for i, _f in visiblefctxs
513 ]
514 ),
515 self._getline(l),
516 )
517 # run editor
518 editedtext = self.ui.edit(editortext, b'', action=b'absorb')
519 if not editedtext:
520 raise error.InputError(_(b'empty editor text'))
521 # parse edited result
522 contents = [b''] * len(self.fctxs)
523 leftpadpos = 4
524 colonpos = leftpadpos + len(visiblefctxs) + 1
525 for l in mdiff.splitnewlines(editedtext):
526 if l.startswith(b'HG:'):
527 continue
528 if l[colonpos - 1 : colonpos + 2] != b' : ':
529 raise error.InputError(_(b'malformed line: %s') % l)
530 linecontent = l[colonpos + 2 :]
531 for i, ch in enumerate(
532 pycompat.bytestr(l[leftpadpos : colonpos - 1])
533 ):
534 if ch == b'y':
535 contents[visiblefctxs[i][0]] += linecontent
536 # chunkstats is hard to calculate if anything changes, therefore
537 # set them to just a simple value (1, 1).
538 if editedtext != editortext:
539 self.chunkstats = [1, 1]
540 return contents
541
542 def _getline(self, lineinfo):
543 """((rev, linenum)) -> str. convert rev+line number to line content"""
544 rev, linenum = lineinfo
545 if rev & 1: # odd: original line taken from fctxs
546 return self.contentlines[rev // 2][linenum]
547 else: # even: fixup line from targetfctx
548 return self.targetlines[linenum]
549
550 def _iscontinuous(self, a1, a2, closedinterval=False):
551 """(a1, a2 : int) -> bool
552
553 check if these lines are continuous. i.e. no other insertions or
554 deletions (from other revisions) among these lines.
555
556 closedinterval decides whether a2 should be included or not. i.e. is
557 it [a1, a2), or [a1, a2] ?
558 """
559 if a1 >= a2:
560 return True
561 llog = self.linelog
562 offset1 = llog.getoffset(a1)
563 offset2 = llog.getoffset(a2) + int(closedinterval)
564 linesinbetween = llog.getalllines(offset1, offset2)
565 return len(linesinbetween) == a2 - a1 + int(closedinterval)
566
567 def _optimizefixups(self, fixups):
568 """[(rev, a1, a2, b1, b2)] -> [(rev, a1, a2, b1, b2)].
569 merge adjacent fixups to make them less fragmented.
570 """
571 result = []
572 pcurrentchunk = [[-1, -1, -1, -1, -1]]
573
574 def pushchunk():
575 if pcurrentchunk[0][0] != -1:
576 result.append(tuple(pcurrentchunk[0]))
577
578 for i, chunk in enumerate(fixups):
579 rev, a1, a2, b1, b2 = chunk
580 lastrev = pcurrentchunk[0][0]
581 lasta2 = pcurrentchunk[0][2]
582 lastb2 = pcurrentchunk[0][4]
583 if (
584 a1 == lasta2
585 and b1 == lastb2
586 and rev == lastrev
587 and self._iscontinuous(max(a1 - 1, 0), a1)
588 ):
589 # merge into currentchunk
590 pcurrentchunk[0][2] = a2
591 pcurrentchunk[0][4] = b2
592 else:
593 pushchunk()
594 pcurrentchunk[0] = list(chunk)
595 pushchunk()
596 return result
597
598 def _showchanges(self, fm, alines, blines, chunk, fixups):
599 def trim(line):
600 if line.endswith(b'\n'):
601 line = line[:-1]
602 return line
603
604 # this is not optimized for perf but _showchanges only gets executed
605 # with an extra command-line flag.
606 a1, a2, b1, b2 = chunk
607 aidxs, bidxs = [0] * (a2 - a1), [0] * (b2 - b1)
608 for idx, fa1, fa2, fb1, fb2 in fixups:
609 for i in range(fa1, fa2):
610 aidxs[i - a1] = (max(idx, 1) - 1) // 2
611 for i in range(fb1, fb2):
612 bidxs[i - b1] = (max(idx, 1) - 1) // 2
613
614 fm.startitem()
615 fm.write(
616 b'hunk',
617 b' %s\n',
618 b'@@ -%d,%d +%d,%d @@' % (a1, a2 - a1, b1, b2 - b1),
619 label=b'diff.hunk',
620 )
621 fm.data(path=self.path, linetype=b'hunk')
622
623 def writeline(idx, diffchar, line, linetype, linelabel):
624 fm.startitem()
625 node = b''
626 if idx:
627 ctx = self.fctxs[idx]
628 fm.context(fctx=ctx)
629 node = ctx.hex()
630 self.ctxaffected.add(ctx.changectx())
631 fm.write(b'node', b'%-7.7s ', node, label=b'absorb.node')
632 fm.write(
633 b'diffchar ' + linetype,
634 b'%s%s\n',
635 diffchar,
636 line,
637 label=linelabel,
638 )
639 fm.data(path=self.path, linetype=linetype)
640
641 for i in range(a1, a2):
642 writeline(
643 aidxs[i - a1],
644 b'-',
645 trim(alines[i]),
646 b'deleted',
647 b'diff.deleted',
648 )
649 for i in range(b1, b2):
650 writeline(
651 bidxs[i - b1],
652 b'+',
653 trim(blines[i]),
654 b'inserted',
655 b'diff.inserted',
656 )
657
658
659 class fixupstate:
660 """state needed to run absorb
661
662 internally, it keeps paths and filefixupstates.
663
664 a typical use is like filefixupstates:
665
666 1. call diffwith, to calculate fixups
667 2. (optionally), present fixups to the user, or edit fixups
668 3. call apply, to apply changes to memory
669 4. call commit, to commit changes to hg database
670 """
671
672 def __init__(self, stack, ui=None, **opts):
673 """([ctx], ui or None) -> None
674
675 stack: should be linear, and sorted by topo order - oldest first.
676 all commits in stack are considered mutable.
677 """
678 assert stack
679 self.ui = ui or nullui()
680 self.opts = opts
681 self.stack = stack
682 self.repo = stack[-1].repo().unfiltered()
683
684 # following fields will be filled later
685 self.paths = [] # [str]
686 self.status = None # ctx.status output
687 self.fctxmap = {} # {path: {ctx: fctx}}
688 self.fixupmap = {} # {path: filefixupstate}
689 self.replacemap = {} # {oldnode: newnode or None}
690 self.finalnode = None # head after all fixups
691 self.ctxaffected = set() # ctx that will be absorbed into
692
693 def diffwith(self, targetctx, match=None, fm=None):
694 """diff and prepare fixups. update self.fixupmap, self.paths"""
695 # only care about modified files
696 self.status = self.stack[-1].status(targetctx, match)
697 self.paths = []
698 # but if --edit-lines is used, the user may want to edit files
699 # even if they are not modified
700 editopt = self.opts.get('edit_lines')
701 if not self.status.modified and editopt and match:
702 interestingpaths = match.files()
703 else:
704 interestingpaths = self.status.modified
705 # prepare the filefixupstate
706 seenfctxs = set()
707 # sorting is necessary to eliminate ambiguity for the "double move"
708 # case: "hg cp A B; hg cp A C; hg rm A", then only "B" can affect "A".
709 for path in sorted(interestingpaths):
710 self.ui.debug(b'calculating fixups for %s\n' % path)
711 targetfctx = targetctx[path]
712 fctxs, ctx2fctx = getfilestack(self.stack, path, seenfctxs)
713 # ignore symbolic links or binary, or unchanged files
714 if any(
715 f.islink() or stringutil.binary(f.data())
716 for f in [targetfctx] + fctxs
717 if not isinstance(f, emptyfilecontext)
718 ):
719 continue
720 if targetfctx.data() == fctxs[-1].data() and not editopt:
721 continue
722 seenfctxs.update(fctxs[1:])
723 self.fctxmap[path] = ctx2fctx
724 fstate = filefixupstate(fctxs, path, ui=self.ui, **self.opts)
725 if fm is not None:
726 fm.startitem()
727 fm.plain(b'showing changes for ')
728 fm.write(b'path', b'%s\n', path, label=b'absorb.path')
729 fm.data(linetype=b'path')
730 fstate.diffwith(targetfctx, fm)
731 self.fixupmap[path] = fstate
732 self.paths.append(path)
733 self.ctxaffected.update(fstate.ctxaffected)
734
735 def apply(self):
736 """apply fixups to individual filefixupstates"""
737 for path, state in self.fixupmap.items():
738 if self.ui.debugflag:
739 self.ui.write(_(b'applying fixups to %s\n') % path)
740 state.apply()
741
742 @property
743 def chunkstats(self):
744 """-> {path: chunkstats}. collect chunkstats from filefixupstates"""
745 return {path: state.chunkstats for path, state in self.fixupmap.items()}
746
747 def commit(self):
748 """commit changes. update self.finalnode, self.replacemap"""
749 with self.repo.transaction(b'absorb') as tr:
750 self._commitstack()
751 self._movebookmarks(tr)
752 if self.repo[b'.'].node() in self.replacemap:
753 self._moveworkingdirectoryparent()
754 self._cleanupoldcommits()
755 return self.finalnode
756
757 def printchunkstats(self):
758 """print things like '1 of 2 chunk(s) applied'"""
759 ui = self.ui
760 chunkstats = self.chunkstats
761 if ui.verbose:
762 # chunkstats for each file
763 for path, stat in chunkstats.items():
764 if stat[0]:
765 ui.write(
766 _(b'%s: %d of %d chunk(s) applied\n')
767 % (path, stat[0], stat[1])
768 )
769 elif not ui.quiet:
770 # a summary for all files
771 stats = chunkstats.values()
772 applied, total = (sum(s[i] for s in stats) for i in (0, 1))
773 ui.write(_(b'%d of %d chunk(s) applied\n') % (applied, total))
774
775 def _commitstack(self):
776 """make new commits. update self.finalnode, self.replacemap.
777 it is splitted from "commit" to avoid too much indentation.
778 """
779 # last node (20-char) committed by us
780 lastcommitted = None
781 # p1 which overrides the parent of the next commit, "None" means use
782 # the original parent unchanged
783 nextp1 = None
784 for ctx in self.stack:
785 memworkingcopy = self._getnewfilecontents(ctx)
786 if not memworkingcopy and not lastcommitted:
787 # nothing changed, nothing commited
788 nextp1 = ctx
789 continue
790 willbecomenoop = ctx.files() and self._willbecomenoop(
791 memworkingcopy, ctx, nextp1
792 )
793 if self.skip_empty_successor and willbecomenoop:
794 # changeset is no longer necessary
795 self.replacemap[ctx.node()] = None
796 msg = _(b'became empty and was dropped')
797 else:
798 # changeset needs re-commit
799 nodestr = self._commitsingle(memworkingcopy, ctx, p1=nextp1)
800 lastcommitted = self.repo[nodestr]
801 nextp1 = lastcommitted
802 self.replacemap[ctx.node()] = lastcommitted.node()
803 if memworkingcopy:
804 if willbecomenoop:
805 msg = _(b'%d file(s) changed, became empty as %s')
806 else:
807 msg = _(b'%d file(s) changed, became %s')
808 msg = msg % (
809 len(memworkingcopy),
810 self._ctx2str(lastcommitted),
811 )
812 else:
813 msg = _(b'became %s') % self._ctx2str(lastcommitted)
814 if self.ui.verbose and msg:
815 self.ui.write(_(b'%s: %s\n') % (self._ctx2str(ctx), msg))
816 self.finalnode = lastcommitted and lastcommitted.node()
817
818 def _ctx2str(self, ctx):
819 if self.ui.debugflag:
820 return b'%d:%s' % (ctx.rev(), ctx.hex())
821 else:
822 return b'%d:%s' % (ctx.rev(), short(ctx.node()))
823
824 def _getnewfilecontents(self, ctx):
825 """(ctx) -> {path: str}
826
827 fetch file contents from filefixupstates.
828 return the working copy overrides - files different from ctx.
829 """
830 result = {}
831 for path in self.paths:
832 ctx2fctx = self.fctxmap[path] # {ctx: fctx}
833 if ctx not in ctx2fctx:
834 continue
835 fctx = ctx2fctx[ctx]
836 content = fctx.data()
837 newcontent = self.fixupmap[path].getfinalcontent(fctx)
838 if content != newcontent:
839 result[fctx.path()] = newcontent
840 return result
841
842 def _movebookmarks(self, tr):
843 repo = self.repo
844 needupdate = [
845 (name, self.replacemap[hsh])
846 for name, hsh in repo._bookmarks.items()
847 if hsh in self.replacemap
848 ]
849 changes = []
850 for name, hsh in needupdate:
851 if hsh:
852 changes.append((name, hsh))
853 if self.ui.verbose:
854 self.ui.write(
855 _(b'moving bookmark %s to %s\n') % (name, hex(hsh))
856 )
857 else:
858 changes.append((name, None))
859 if self.ui.verbose:
860 self.ui.write(_(b'deleting bookmark %s\n') % name)
861 repo._bookmarks.applychanges(repo, tr, changes)
862
863 def _moveworkingdirectoryparent(self):
864 if not self.finalnode:
865 # Find the latest not-{obsoleted,stripped} parent.
866 revs = self.repo.revs(b'max(::. - %ln)', self.replacemap.keys())
867 ctx = self.repo[revs.first()]
868 self.finalnode = ctx.node()
869 else:
870 ctx = self.repo[self.finalnode]
871
872 dirstate = self.repo.dirstate
873 # dirstate.rebuild invalidates fsmonitorstate, causing "hg status" to
874 # be slow. in absorb's case, no need to invalidate fsmonitorstate.
875 noop = lambda: 0
876 restore = noop
877 if hasattr(dirstate, '_fsmonitorstate'):
878 bak = dirstate._fsmonitorstate.invalidate
879
880 def restore():
881 dirstate._fsmonitorstate.invalidate = bak
882
883 dirstate._fsmonitorstate.invalidate = noop
884 try:
885 with dirstate.changing_parents(self.repo):
886 dirstate.rebuild(ctx.node(), ctx.manifest(), self.paths)
887 finally:
888 restore()
889
890 @staticmethod
891 def _willbecomenoop(memworkingcopy, ctx, pctx=None):
892 """({path: content}, ctx, ctx) -> bool. test if a commit will be noop
893
894 if it will become an empty commit (does not change anything, after the
895 memworkingcopy overrides), return True. otherwise return False.
896 """
897 if not pctx:
898 parents = ctx.parents()
899 if len(parents) != 1:
900 return False
901 pctx = parents[0]
902 if ctx.branch() != pctx.branch():
903 return False
904 if ctx.extra().get(b'close'):
905 return False
906 # ctx changes more files (not a subset of memworkingcopy)
907 if not set(ctx.files()).issubset(set(memworkingcopy)):
908 return False
909 for path, content in memworkingcopy.items():
910 if path not in pctx or path not in ctx:
911 return False
912 fctx = ctx[path]
913 pfctx = pctx[path]
914 if pfctx.flags() != fctx.flags():
915 return False
916 if pfctx.data() != content:
917 return False
918 return True
919
920 def _commitsingle(self, memworkingcopy, ctx, p1=None):
921 """(ctx, {path: content}, node) -> node. make a single commit
922
923 the commit is a clone from ctx, with a (optionally) different p1, and
924 different file contents replaced by memworkingcopy.
925 """
926 parents = p1 and (p1, self.repo.nullid)
927 extra = ctx.extra()
928 if self._useobsolete and self.ui.configbool(b'absorb', b'add-noise'):
929 extra[b'absorb_source'] = ctx.hex()
930
931 desc = rewriteutil.update_hash_refs(
932 ctx.repo(),
933 ctx.description(),
934 {
935 oldnode: [newnode]
936 for oldnode, newnode in self.replacemap.items()
937 },
938 )
939 mctx = overlaycontext(
940 memworkingcopy, ctx, parents, extra=extra, desc=desc
941 )
942 return mctx.commit()
943
944 @util.propertycache
945 def _useobsolete(self):
946 """() -> bool"""
947 return obsolete.isenabled(self.repo, obsolete.createmarkersopt)
948
949 def _cleanupoldcommits(self):
950 replacements = {
951 k: ([v] if v is not None else [])
952 for k, v in self.replacemap.items()
953 }
954 if replacements:
955 cmdutil.cleanup_nodes(
956 self.repo, replacements, operation=b'absorb', fixphase=True
957 )
958
959 @util.propertycache
960 def skip_empty_successor(self):
961 return rewriteutil.skip_empty_successor(self.ui, b'absorb')
962
963
964 def _parsechunk(hunk):
965 """(crecord.uihunk or patch.recordhunk) -> (path, (a1, a2, [bline]))"""
966 if type(hunk) not in (crecord.uihunk, patch.recordhunk):
967 return None, None
968 path = hunk.header.filename()
969 a1 = hunk.fromline + len(hunk.before) - 1
970 # remove before and after context
971 hunk.before = hunk.after = []
972 buf = util.stringio()
973 hunk.write(buf)
974 patchlines = mdiff.splitnewlines(buf.getvalue())
975 # hunk.prettystr() will update hunk.removed
976 a2 = a1 + hunk.removed
977 blines = [l[1:] for l in patchlines[1:] if not l.startswith(b'-')]
978 return path, (a1, a2, blines)
979
980
981 def overlaydiffcontext(ctx, chunks):
982 """(ctx, [crecord.uihunk]) -> memctx
983
984 return a memctx with some [1] patches (chunks) applied to ctx.
985 [1]: modifications are handled. renames, mode changes, etc. are ignored.
986 """
987 # sadly the applying-patch logic is hardly reusable, and messy:
988 # 1. the core logic "_applydiff" is too heavy - it writes .rej files, it
989 # needs a file stream of a patch and will re-parse it, while we have
990 # structured hunk objects at hand.
991 # 2. a lot of different implementations about "chunk" (patch.hunk,
992 # patch.recordhunk, crecord.uihunk)
993 # as we only care about applying changes to modified files, no mode
994 # change, no binary diff, and no renames, it's probably okay to
995 # re-invent the logic using much simpler code here.
996 memworkingcopy = {} # {path: content}
997 patchmap = defaultdict(lambda: []) # {path: [(a1, a2, [bline])]}
998 for path, info in map(_parsechunk, chunks):
999 if not path or not info:
1000 continue
1001 patchmap[path].append(info)
1002 for path, patches in patchmap.items():
1003 if path not in ctx or not patches:
1004 continue
1005 patches.sort(reverse=True)
1006 lines = mdiff.splitnewlines(ctx[path].data())
1007 for a1, a2, blines in patches:
1008 lines[a1:a2] = blines
1009 memworkingcopy[path] = b''.join(lines)
1010 return overlaycontext(memworkingcopy, ctx)
1011
1012
1013 def absorb(ui, repo, stack=None, targetctx=None, pats=None, **opts):
1014 """pick fixup chunks from targetctx, apply them to stack.
1015
1016 if targetctx is None, the working copy context will be used.
1017 if stack is None, the current draft stack will be used.
1018 return fixupstate.
1019 """
1020 if stack is None:
1021 limit = ui.configint(b'absorb', b'max-stack-size')
1022 headctx = repo[b'.']
1023 if len(headctx.parents()) > 1:
1024 raise error.InputError(_(b'cannot absorb into a merge'))
1025 stack = getdraftstack(headctx, limit)
1026 if limit and len(stack) >= limit:
1027 ui.warn(
1028 _(
1029 b'absorb: only the recent %d changesets will '
1030 b'be analysed\n'
1031 )
1032 % limit
1033 )
1034 if not stack:
1035 raise error.InputError(_(b'no mutable changeset to change'))
1036 if targetctx is None: # default to working copy
1037 targetctx = repo[None]
1038 if pats is None:
1039 pats = ()
1040
1041 state = fixupstate(stack, ui=ui, **opts)
1042 matcher = scmutil.match(targetctx, pats, pycompat.byteskwargs(opts))
1043 if opts.get('interactive'):
1044 diff = patch.diff(repo, stack[-1].node(), targetctx.node(), matcher)
1045 origchunks = patch.parsepatch(diff)
1046 chunks = cmdutil.recordfilter(ui, origchunks, matcher)[0]
1047 targetctx = overlaydiffcontext(stack[-1], chunks)
1048 if opts.get('edit_lines'):
1049 # If we're going to open the editor, don't ask the user to confirm
1050 # first
1051 opts['apply_changes'] = True
1052 fm = None
1053 if opts.get('print_changes') or not opts.get('apply_changes'):
1054 fm = ui.formatter(b'absorb', pycompat.byteskwargs(opts))
1055 state.diffwith(targetctx, matcher, fm)
1056 if fm is not None:
1057 fm.startitem()
1058 fm.write(
1059 b"count", b"\n%d changesets affected\n", len(state.ctxaffected)
1060 )
1061 fm.data(linetype=b'summary')
1062 for ctx in reversed(stack):
1063 if ctx not in state.ctxaffected:
1064 continue
1065 fm.startitem()
1066 fm.context(ctx=ctx)
1067 fm.data(linetype=b'changeset')
1068 fm.write(b'node', b'%-7.7s ', ctx.hex(), label=b'absorb.node')
1069 descfirstline = stringutil.firstline(ctx.description())
1070 fm.write(
1071 b'descfirstline',
1072 b'%s\n',
1073 descfirstline,
1074 label=b'absorb.description',
1075 )
1076 fm.end()
1077 if not opts.get('dry_run'):
1078 if (
1079 not opts.get('apply_changes')
1080 and state.ctxaffected
1081 and ui.promptchoice(
1082 b"apply changes (y/N)? $$ &Yes $$ &No", default=1
1083 )
1084 ):
1085 raise error.CanceledError(_(b'absorb cancelled\n'))
1086
1087 state.apply()
1088 if state.commit():
1089 state.printchunkstats()
1090 elif not ui.quiet:
1091 ui.write(_(b'nothing applied\n'))
1092 return state
1093
1094
1095 @command(
1096 b'absorb',
1097 [
1098 (
1099 b'a',
1100 b'apply-changes',
1101 None,
1102 _(b'apply changes without prompting for confirmation'),
1103 ),
1104 (
1105 b'p',
1106 b'print-changes',
1107 None,
1108 _(b'always print which changesets are modified by which changes'),
1109 ),
1110 (
1111 b'i',
1112 b'interactive',
1113 None,
1114 _(b'interactively select which chunks to apply'),
1115 ),
1116 (
1117 b'e',
1118 b'edit-lines',
1119 None,
1120 _(
1121 b'edit what lines belong to which changesets before commit '
1122 b'(EXPERIMENTAL)'
1123 ),
1124 ),
1125 ]
1126 + commands.dryrunopts
1127 + commands.templateopts
1128 + commands.walkopts,
1129 _(b'hg absorb [OPTION] [FILE]...'),
1130 helpcategory=command.CATEGORY_COMMITTING,
1131 helpbasic=True,
1132 )
1133 def absorbcmd(ui, repo, *pats, **opts):
1134 """incorporate corrections into the stack of draft changesets
1135
1136 absorb analyzes each change in your working directory and attempts to
1137 amend the changed lines into the changesets in your stack that first
1138 introduced those lines.
1139
1140 If absorb cannot find an unambiguous changeset to amend for a change,
1141 that change will be left in the working directory, untouched. They can be
1142 observed by :hg:`status` or :hg:`diff` afterwards. In other words,
1143 absorb does not write to the working directory.
1144
1145 Changesets outside the revset `::. and not public() and not merge()` will
1146 not be changed.
1147
1148 Changesets that become empty after applying the changes will be deleted.
1149
1150 By default, absorb will show what it plans to do and prompt for
1151 confirmation. If you are confident that the changes will be absorbed
1152 to the correct place, run :hg:`absorb -a` to apply the changes
1153 immediately.
1154
1155 Returns 0 on success, 1 if all chunks were ignored and nothing amended.
1156 """
1157 with repo.wlock(), repo.lock():
1158 if not opts['dry_run']:
1159 cmdutil.checkunfinished(repo)
1160
1161 state = absorb(ui, repo, pats=pats, **opts)
1162 if sum(s[0] for s in state.chunkstats.values()) == 0:
1163 return 1