Coverage for src/governed_harness/ladder/hunks.py: 97%

58 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-12 16:06 +0000

1"""Hunks of a change and their reversal, for light mutation (#55, item 5). 

2 

3A hunk is a maximal run of changed lines between the baseline text of a file and its current 

4text (``difflib`` opcodes other than ``equal``, without context lines). Reverting one hunk puts 

5its baseline lines back and keeps every other change, so a test run on the result tells whether 

6some test notices that this hunk is gone. The order is deterministic: by path, then by position 

7in the file.""" 

8 

9from __future__ import annotations 

10 

11import difflib 

12from dataclasses import dataclass 

13 

14 

15@dataclass(frozen=True) 

16class Hunk: 

17 path: str 

18 index: int 

19 """Position of the hunk in the file (1-based).""" 

20 before_start: int 

21 before_end: int 

22 after_start: int 

23 after_end: int 

24 """Line ranges (0-based, end exclusive) in the baseline and in the current text.""" 

25 

26 @property 

27 def label(self) -> str: 

28 return f"{self.path}#{self.index} (lines {self.after_start + 1}-{max(self.after_end, self.after_start + 1)})" 

29 

30 def as_dict(self) -> dict[str, object]: 

31 return { 

32 "path": self.path, 

33 "index": self.index, 

34 "beforeLines": [self.before_start + 1, self.before_end], 

35 "afterLines": [self.after_start + 1, self.after_end], 

36 } 

37 

38 

39def _blocks(lines: list[str], start: int, end: int) -> list[tuple[int, int]]: 

40 """``start..end`` split after each run of blank lines that is followed by more lines, so 

41 that a new function added next to a changed line is a hunk of its own.""" 

42 blocks: list[tuple[int, int]] = [] 

43 begin = start 

44 index = start 

45 while index < end: 

46 if not lines[index].strip(): 

47 following = index 

48 while following < end and not lines[following].strip(): 

49 following += 1 

50 if following < end and any(lines[item].strip() for item in range(begin, index)): 50 ↛ 53line 50 didn't jump to line 53 because the condition on line 50 was always true

51 blocks.append((begin, following)) 

52 begin = following 

53 index = following 

54 continue 

55 index += 1 

56 blocks.append((begin, end)) 

57 return blocks 

58 

59 

60def hunks(path: str, before: str, after: str) -> list[Hunk]: 

61 """The hunks that turn ``before`` into ``after``. A changed region that adds several blocks 

62 of lines (separated by blank lines) gives one hunk per block: the first replaces the 

63 removed lines, the others are additions.""" 

64 old = before.splitlines(keepends=True) 

65 new = after.splitlines(keepends=True) 

66 matcher = difflib.SequenceMatcher(a=old, b=new, autojunk=False) 

67 found: list[Hunk] = [] 

68 for tag, i1, i2, j1, j2 in matcher.get_opcodes(): 

69 if tag == "equal": 

70 continue 

71 blocks = _blocks(new, j1, j2) if j2 > j1 else [(j1, j2)] 

72 for position, (start, end) in enumerate(blocks): 

73 first = position == 0 

74 found.append(Hunk(path, len(found) + 1, i1 if first else i2, i2, start, end)) 

75 return found 

76 

77 

78_COMMENT_PREFIXES = ("#", "//", "/*", "*", "--", ";") 

79 

80 

81def cosmetic(hunk: Hunk, before: str, after: str) -> bool: 

82 """Whether every line the hunk removes or adds is blank or a comment: reverting it cannot 

83 change behaviour, so it is not mutated.""" 

84 old = before.splitlines()[hunk.before_start : hunk.before_end] 

85 new = after.splitlines()[hunk.after_start : hunk.after_end] 

86 return all( 

87 not line.strip() or line.strip().startswith(_COMMENT_PREFIXES) for line in (*old, *new) 

88 ) 

89 

90 

91def revert(hunk: Hunk, before: str, after: str) -> str: 

92 """``after`` with the lines of ``hunk`` put back to their baseline content.""" 

93 old = before.splitlines(keepends=True) 

94 new = after.splitlines(keepends=True) 

95 return "".join( 

96 new[: hunk.after_start] + old[hunk.before_start : hunk.before_end] + new[hunk.after_end :] 

97 ) 

98 

99 

100__all__ = ["Hunk", "cosmetic", "hunks", "revert"]