Coverage for src/pullapprove/git.py: 93%

61 statements  

« prev     ^ index     » next       coverage.py v7.14.1, created at 2026-10-31 23:22 -0500

1from __future__ import annotations 

2 

3import os 

4import subprocess 

5import sys 

6from collections.abc import Generator 

7from pathlib import Path 

8 

9 

10def git_pager() -> str: 

11 """The pager command git would use, honoring core.pager/GIT_PAGER/PAGER. 

12 

13 Returns a shell command string (git's pager values can include arguments or 

14 pipes, so callers run it through a shell, the way git does). Falls back to 

15 `cat` when git is unavailable or paging is disabled. 

16 """ 

17 try: 

18 output = subprocess.check_output(["git", "var", "GIT_PAGER"], text=True).strip() 

19 except (subprocess.CalledProcessError, OSError): 

20 output = "" 

21 return output or os.environ.get("PAGER", "") or "cat" 

22 

23 

24def page(text: str) -> None: 

25 """Display `text` through git's configured pager, the way `git diff` does.""" 

26 env = {**os.environ} 

27 env.setdefault("LESS", "FRX") # quit if one screen, keep colors, no init clear 

28 proc = subprocess.Popen( 

29 git_pager(), shell=True, stdin=subprocess.PIPE, text=True, env=env 

30 ) 

31 try: 

32 proc.communicate(text) 

33 except BrokenPipeError: 

34 pass # the pager was closed before reading everything (e.g. `q` in less) 

35 if proc.returncode: 

36 sys.stdout.write(text) # the pager failed to run; don't lose the output 

37 

38 

39def git_ls_files(path: Path) -> Generator[str]: 

40 """Yield files in the git repository one at a time. 

41 

42 A file deleted from the working tree is both cached and deleted, and git 

43 lists it once for each, so it's yielded the first time only. 

44 """ 

45 seen = set() 

46 process = subprocess.Popen( 

47 [ 

48 "git", 

49 "ls-files", 

50 "--cached", 

51 "--deleted", 

52 "--others", 

53 "--exclude-standard", 

54 ], 

55 cwd=path, 

56 stdout=subprocess.PIPE, 

57 text=True, 

58 ) 

59 

60 assert process.stdout is not None 

61 for line in process.stdout: 

62 file_path = line.strip() 

63 if file_path not in seen: 

64 seen.add(file_path) 

65 yield file_path 

66 

67 process.stdout.close() 

68 process.wait() 

69 

70 

71def git_ls_changes(path: Path) -> list[str]: 

72 """Every changed or untracked file in the working tree and index.""" 

73 # -z so paths come through unquoted, one NUL-terminated `XY path` entry 

74 # each (a rename's entry is followed by its old path) 

75 output = subprocess.check_output( 

76 ["git", "status", "--porcelain=v1", "-z", "--untracked-files=all"], 

77 cwd=path, 

78 text=True, 

79 encoding="utf-8", 

80 ) 

81 

82 changed = [] 

83 entries = iter(output.split("\0")) 

84 for entry in entries: 

85 if not entry: 

86 continue 

87 status, file_path = entry[:2], entry[3:] 

88 changed.append(file_path) 

89 if "R" in status or "C" in status: 

90 next(entries) 

91 return changed 

92 

93 

94# The diff GitHub serves for a pull request uses git's defaults: three lines 

95# of context, rename detection, the myers algorithm (checked against real 

96# pull requests). Passed explicitly so a gitconfig like 

97# `diff.algorithm = histogram` can't shape the hunks differently, since code 

98# patterns see context lines too. 

99HOST_DIFF_ARGS = ("--unified=3", "--find-renames", "--diff-algorithm=myers") 

100 

101 

102def git_commit_sha(*, path: Path, ref: str) -> str: 

103 """The commit `ref` names (`--end-of-options` so a ref can't pass for an 

104 option).""" 

105 return subprocess.check_output( 

106 ["git", "rev-parse", "--verify", "--quiet", "--end-of-options"] 

107 + [f"{ref}^{{commit}}"], 

108 cwd=path, 

109 text=True, 

110 encoding="utf-8", 

111 ).strip() 

112 

113 

114def git_ls_tree(*, path: Path, ref: str) -> list[str]: 

115 """Every file in `ref`'s tree, as repo-root-relative paths.""" 

116 output = subprocess.check_output( 

117 ["git", "ls-tree", "-r", "-z", "--name-only", "--full-tree", ref], 

118 cwd=path, 

119 text=True, 

120 encoding="utf-8", 

121 ) 

122 return [name for name in output.split("\0") if name] 

123 

124 

125def git_file_at(*, path: Path, ref: str, file_path: str) -> str: 

126 """A file's content as committed at `ref`.""" 

127 return subprocess.check_output( 

128 ["git", "cat-file", "blob", f"{ref}:{file_path}"], 

129 cwd=path, 

130 text=True, 

131 # The same decoding the working tree's configs get (tomllib reads UTF-8) 

132 encoding="utf-8", 

133 ) 

134 

135 

136def git_diff_stream(path: Path, *diff_args: str) -> Generator[str]: 

137 # `-c diff.noprefix=false` because our diff parser requires the `a/`/`b/` 

138 # (or mnemonic single-char) path prefixes to recognize file headers — a user 

139 # with `diff.noprefix = true` in their gitconfig would otherwise produce a 

140 # diff whose files we silently misattribute. `--no-color` for the same 

141 # reason: `color.ui = always` would put escape codes in front of every 

142 # line. An explicit `--no-prefix` or `--color` in diff_args still wins 

143 # (later flags override). 

144 process = subprocess.Popen( 

145 ["git", "-c", "diff.noprefix=false", "diff", "--no-ext-diff", "--no-color"] 

146 + list(diff_args), 

147 cwd=path, 

148 stdout=subprocess.PIPE, 

149 text=True, 

150 ) 

151 

152 assert process.stdout is not None 

153 yield from process.stdout 

154 

155 process.stdout.close() 

156 returncode = process.wait() 

157 # 0 = success, 1 = changes found (with --exit-code); anything else is a real 

158 # git error (bad revision, unknown option) that would otherwise masquerade 

159 # as an empty diff. git has already printed the reason to stderr. 

160 if returncode not in (0, 1): 

161 raise subprocess.CalledProcessError(returncode, ["git", "diff", *diff_args])