Coverage for src/pullapprove/printer.py: 36%

139 statements  

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

1""" 

2Printer classes for formatting and displaying PullApprove output. 

3""" 

4 

5from __future__ import annotations 

6 

7import hashlib 

8import json 

9from typing import TYPE_CHECKING 

10 

11import click 

12 

13from .config import ScopeModel 

14from .schemas import matches_schema 

15 

16if TYPE_CHECKING: 

17 from .matches import ChangeMatches 

18 

19# Base colors for scope names (cycle through these) 

20SCOPE_COLORS = ["green", "yellow", "blue", "magenta", "cyan", "red"] 

21 

22 

23def get_color_for_name(name: str) -> str: 

24 """Get a consistent color for a given name using deterministic hash.""" 

25 # Use MD5 for a deterministic hash across Python invocations 

26 name_hash = int(hashlib.md5(name.encode()).hexdigest()[:8], 16) 

27 return SCOPE_COLORS[name_hash % len(SCOPE_COLORS)] 

28 

29 

30def get_scope_display(scope: ScopeModel) -> str: 

31 """Get a colored display string for a scope. 

32 

33 Ownership is carried by the printed marker alone, never by brightness -- 

34 dimming `global` made the one scope that can pass a file by itself the 

35 faintest thing on screen. Same rule as the web UI (see ownership.ts). 

36 """ 

37 color = get_color_for_name(scope.name) 

38 

39 return click.style(scope.printed_name(), fg=color) 

40 

41 

42def print_scope_badge(scope_name: str, scopes: dict[str, ScopeModel]) -> str: 

43 """Print a scope badge with a dimmed arrow prefix.""" 

44 arrow = click.style("→ ", dim=True) 

45 if scope_name in scopes: 

46 return arrow + get_scope_display(scopes[scope_name]) 

47 return arrow + scope_name 

48 

49 

50class MatchesPrinter: 

51 """Handles printing of file/scope matches.""" 

52 

53 def __init__(self, *, matches: ChangeMatches, all_files: list[str]) -> None: 

54 self.matches = matches 

55 # Every file that was looked at, including the ones no scope owns 

56 self.all_files = all_files 

57 

58 def print_by_path(self, scope_filter: tuple[str, ...] | None = None) -> None: 

59 """Print matches organized by file path.""" 

60 all_paths = self.all_files 

61 

62 if not all_paths: 

63 click.echo("No files found.") 

64 return 

65 

66 if scope_filter: 

67 all_paths = self._paths_matching_scopes( 

68 paths=all_paths, scope_filter=scope_filter 

69 ) 

70 

71 if not all_paths: 

72 click.echo(f"No files found matching scopes: {', '.join(scope_filter)}") 

73 return 

74 

75 # Sort paths for consistent output 

76 for path in sorted(all_paths): 

77 line = path 

78 

79 # Get scope badges if file has scopes 

80 if path in self.matches.paths: 

81 path_match = self.matches.paths[path] 

82 if path_match.scopes: 

83 badges = [] 

84 for scope_name in path_match.scopes: 

85 badges.append( 

86 print_scope_badge(scope_name, self.matches.scopes) 

87 ) 

88 line += " " + " ".join(badges) 

89 click.echo(line) 

90 else: 

91 # Dim files without scopes 

92 click.echo(click.style(line, dim=True)) 

93 else: 

94 # Dim files without scopes 

95 click.echo(click.style(line, dim=True)) 

96 

97 # Print code patterns for this file if any 

98 code_patterns = self._get_file_code_patterns_simple(path) 

99 for pattern_line in code_patterns: 

100 click.echo(" " + pattern_line) 

101 

102 def _paths_matching_scopes( 

103 self, *, paths: list[str], scope_filter: tuple[str, ...] 

104 ) -> list[str]: 

105 """The paths where any path or code match has a scope in the filter.""" 

106 matching_paths = set() 

107 for path, path_match in self.matches.paths.items(): 

108 if any(s in scope_filter for s in path_match.scopes): 

109 matching_paths.add(path) 

110 for code_match in self.matches.code.values(): 

111 if any(s in scope_filter for s in code_match.scopes): 

112 matching_paths.add(code_match.path) 

113 

114 return [path for path in paths if path in matching_paths] 

115 

116 def print_json(self) -> None: 

117 """Print matches as JSON for other tools to read (see schemas.py).""" 

118 output = matches_schema(matches=self.matches, all_paths=self.all_files) 

119 click.echo(json.dumps(output, indent=2)) 

120 

121 def print_by_scope(self, scope_filter: tuple[str, ...] | None = None) -> None: 

122 """Print matches organized by scope.""" 

123 printed_any = False 

124 

125 # Filter scopes if a filter is provided 

126 scopes_to_show = sorted(self.matches.scopes.keys()) 

127 if scope_filter: 

128 scopes_to_show = [s for s in scopes_to_show if s in scope_filter] 

129 if not scopes_to_show: 

130 click.echo(f"No scopes found matching: {', '.join(scope_filter)}") 

131 return 

132 

133 for scope_name in scopes_to_show: 

134 paths_for_scope = self._get_paths_for_scope(scope_name) 

135 code_only_files = ( 

136 self._get_code_only_files_for_scope(scope_name) 

137 if not paths_for_scope 

138 else [] 

139 ) 

140 

141 if paths_for_scope or code_only_files: 

142 printed_any = True 

143 # Use the scope's color for the header, and its printed name -- 

144 # the badges below spell it with the ownership marker, so the 

145 # header has to as well. 

146 scope = self.matches.scopes.get(scope_name) 

147 if scope: 

148 color = get_color_for_name(scope_name) 

149 click.secho(f"\n{scope.printed_name()}", bold=True, fg=color) 

150 else: 

151 click.secho(f"\n{scope_name}", bold=True, fg="cyan") 

152 # Combine path matches and code-only files 

153 all_files_for_scope = paths_for_scope + code_only_files 

154 

155 # Sort and print paths 

156 for path in sorted(all_files_for_scope): 

157 # Always show the current scope badge 

158 badges = [] 

159 badges.append(print_scope_badge(scope_name, self.matches.scopes)) 

160 

161 # Show if file belongs to OTHER scopes too 

162 if path in self.matches.paths: 

163 path_match = self.matches.paths[path] 

164 other_scopes = [s for s in path_match.scopes if s != scope_name] 

165 if other_scopes: 

166 badges.append(click.style("(also: ", dim=True)) 

167 for other_scope in sorted(other_scopes): 

168 badges.append( 

169 print_scope_badge(other_scope, self.matches.scopes) 

170 ) 

171 badges.append(click.style(")", dim=True)) 

172 

173 line = path + " " + "".join(badges) 

174 click.echo(line) 

175 

176 # Print code patterns for this file if any 

177 code_patterns = self._get_file_code_patterns_simple_for_scope( 

178 path, scope_name 

179 ) 

180 for pattern_line in code_patterns: 

181 click.echo(" " + pattern_line) 

182 

183 if not printed_any: 

184 click.echo("No scopes found with matching files.") 

185 

186 def _get_paths_for_scope(self, scope_name: str) -> list[str]: 

187 """Get all paths that match a specific scope.""" 

188 paths = [] 

189 for path, path_match in self.matches.paths.items(): 

190 if scope_name in path_match.scopes: 

191 paths.append(path) 

192 return paths 

193 

194 def _get_code_only_files_for_scope(self, scope_name: str) -> list[str]: 

195 """Get files that only match this scope via code patterns, not paths.""" 

196 code_files = set() 

197 for code_match in self.matches.code.values(): 

198 if scope_name in code_match.scopes: 

199 code_files.add(code_match.path) 

200 

201 # Remove files that already match via paths 

202 path_files = set(self._get_paths_for_scope(scope_name)) 

203 return sorted(code_files - path_files) 

204 

205 def _get_file_code_patterns_simple(self, path: str) -> list[str]: 

206 """Get code pattern lines for a file by its full path.""" 

207 code_patterns = [] 

208 for code_match in self.matches.code.values(): 

209 if code_match.path == path: 

210 location = f"line {code_match.start_line}" 

211 if code_match.start_line != code_match.end_line: 

212 location += f"-{code_match.end_line}" 

213 

214 badges = [] 

215 for scope_name in code_match.scopes: 

216 badges.append(print_scope_badge(scope_name, self.matches.scopes)) 

217 

218 code_patterns.append( 

219 (code_match.start_line, f"{location} " + " ".join(badges)) 

220 ) 

221 

222 # Sort by line number and return just the strings 

223 return [pattern[1] for pattern in sorted(code_patterns, key=lambda x: x[0])] 

224 

225 def _get_file_code_patterns_simple_for_scope( 

226 self, path: str, scope_name: str 

227 ) -> list[str]: 

228 """Get code pattern lines for a file filtered by a specific scope.""" 

229 code_patterns = [] 

230 for code_match in self.matches.code.values(): 

231 if code_match.path == path and scope_name in code_match.scopes: 

232 location = f"line {code_match.start_line}" 

233 if code_match.start_line != code_match.end_line: 

234 location += f"-{code_match.end_line}" 

235 

236 badges = [] 

237 # Always show the current scope first 

238 badges.append(print_scope_badge(scope_name, self.matches.scopes)) 

239 

240 # Show other scopes if any 

241 other_scopes = [s for s in code_match.scopes if s != scope_name] 

242 if other_scopes: 

243 badges.append(click.style("(also: ", dim=True)) 

244 for other_scope in sorted(other_scopes): 

245 badges.append( 

246 print_scope_badge(other_scope, self.matches.scopes) 

247 ) 

248 badges.append(click.style(")", dim=True)) 

249 

250 code_patterns.append( 

251 (code_match.start_line, f"{location} " + "".join(badges)) 

252 ) 

253 

254 # Sort by line number and return just the strings 

255 return [pattern[1] for pattern in sorted(code_patterns, key=lambda x: x[0])]