Coverage for /Users/les/Projects/crackerjack/crackerjack/services/git.py: 0%

145 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-09-03 15:39 -0700

1import subprocess 

2from pathlib import Path 

3 

4from rich.console import Console 

5 

6from .secure_subprocess import execute_secure_subprocess 

7from .security_logger import get_security_logger 

8 

9 

10class GitService: 

11 def __init__(self, console: Console, pkg_path: Path | None = None) -> None: 

12 self.console = console 

13 self.pkg_path = pkg_path or Path.cwd() 

14 

15 def _run_git_command(self, args: list[str]) -> subprocess.CompletedProcess[str]: 

16 """Execute Git commands with secure subprocess validation.""" 

17 cmd = ["git", *args] 

18 

19 try: 

20 return execute_secure_subprocess( 

21 command=cmd, 

22 cwd=self.pkg_path, 

23 capture_output=True, 

24 text=True, 

25 timeout=60, 

26 check=False, # Don't raise on non-zero exit codes 

27 ) 

28 except Exception as e: 

29 # Log security issues but return a compatible result 

30 security_logger = get_security_logger() 

31 security_logger.log_subprocess_failure( 

32 command=cmd, 

33 exit_code=-1, 

34 error_output=str(e), 

35 ) 

36 

37 # Create compatible result for Git operations 

38 class FailedGitResult: 

39 def __init__(self, command: list[str], error: str): 

40 self.args = command 

41 self.returncode = -1 

42 self.stdout = "" 

43 self.stderr = f"Git security validation failed: {error}" 

44 

45 return FailedGitResult(cmd, str(e)) 

46 

47 def is_git_repo(self) -> bool: 

48 try: 

49 result = self._run_git_command(["rev-parse", "- - git-dir"]) 

50 return result.returncode == 0 

51 except (subprocess.SubprocessError, OSError, FileNotFoundError): 

52 return False 

53 

54 def get_changed_files(self) -> list[str]: 

55 try: 

56 staged_result = self._run_git_command( 

57 ["diff", "--cached", "- - name-only", "- - diff-filter=ACMRT"] 

58 ) 

59 staged_files = ( 

60 staged_result.stdout.strip().split("\n") 

61 if staged_result.stdout.strip() 

62 else [] 

63 ) 

64 

65 unstaged_result = self._run_git_command( 

66 ["diff", "- - name-only", "- - diff-filter=ACMRT"] 

67 ) 

68 unstaged_files = ( 

69 unstaged_result.stdout.strip().split("\n") 

70 if unstaged_result.stdout.strip() 

71 else [] 

72 ) 

73 

74 untracked_result = self._run_git_command( 

75 ["ls-files", "--others", "- - exclude-standard"], 

76 ) 

77 untracked_files = ( 

78 untracked_result.stdout.strip().split("\n") 

79 if untracked_result.stdout.strip() 

80 else [] 

81 ) 

82 

83 all_files = set(staged_files + unstaged_files + untracked_files) 

84 return [f for f in all_files if f] 

85 except Exception as e: 

86 self.console.print(f"[yellow]⚠️[/ yellow] Error getting changed files: {e}") 

87 return [] 

88 

89 def get_staged_files(self) -> list[str]: 

90 try: 

91 result = self._run_git_command(["diff", "--cached", "- - name-only"]) 

92 return result.stdout.strip().split("\n") if result.stdout.strip() else [] 

93 except Exception as e: 

94 self.console.print(f"[yellow]⚠️[/ yellow] Error getting staged files: {e}") 

95 return [] 

96 

97 def add_files(self, files: list[str]) -> bool: 

98 try: 

99 for file in files: 

100 result = self._run_git_command(["add", file]) 

101 if result.returncode != 0: 

102 self.console.print( 

103 f"[red]❌[/ red] Failed to add {file}: {result.stderr}", 

104 ) 

105 return False 

106 return True 

107 except Exception as e: 

108 self.console.print(f"[red]❌[/ red] Error adding files: {e}") 

109 return False 

110 

111 def commit(self, message: str) -> bool: 

112 try: 

113 result = self._run_git_command(["commit", "- m", message]) 

114 if result.returncode == 0: 

115 self.console.print(f"[green]✅[/ green] Committed: {message}") 

116 return True 

117 

118 return self._handle_commit_failure(result, message) 

119 except Exception as e: 

120 self.console.print(f"[red]❌[/ red] Error committing: {e}") 

121 return False 

122 

123 def _handle_commit_failure( 

124 self, result: subprocess.CompletedProcess[str], message: str 

125 ) -> bool: 

126 if "files were modified by this hook" in result.stderr: 

127 return self._retry_commit_after_restage(message) 

128 

129 return self._handle_hook_error(result) 

130 

131 def _retry_commit_after_restage(self, message: str) -> bool: 

132 self.console.print( 

133 "[yellow]🔄[/ yellow] Pre - commit hooks modified files - attempting to re-stage and retry commit" 

134 ) 

135 

136 add_result = self._run_git_command(["add", "- u"]) 

137 if add_result.returncode != 0: 

138 self.console.print( 

139 f"[red]❌[/ red] Failed to re-stage files: {add_result.stderr}" 

140 ) 

141 return False 

142 

143 retry_result = self._run_git_command(["commit", "- m", message]) 

144 if retry_result.returncode == 0: 

145 self.console.print( 

146 f"[green]✅[/ green] Committed after re-staging: {message}" 

147 ) 

148 return True 

149 

150 self.console.print( 

151 f"[red]❌[/ red] Commit failed on retry: {retry_result.stderr}" 

152 ) 

153 return False 

154 

155 def _handle_hook_error(self, result: subprocess.CompletedProcess[str]) -> bool: 

156 if "pre-commit" in result.stderr or "hook" in result.stderr.lower(): 

157 self.console.print("[red]❌[/ red] Commit blocked by pre-commit hooks") 

158 if result.stderr.strip(): 

159 self.console.print( 

160 f"[yellow]Hook output: [/ yellow]\n{result.stderr.strip()}" 

161 ) 

162 else: 

163 self.console.print(f"[red]❌[/ red] Commit failed: {result.stderr}") 

164 return False 

165 

166 def push(self) -> bool: 

167 try: 

168 result = self._run_git_command(["push"]) 

169 if result.returncode == 0: 

170 self.console.print("[green]✅[/ green] Pushed to remote") 

171 return True 

172 self.console.print(f"[red]❌[/ red] Push failed: {result.stderr}") 

173 return False 

174 except Exception as e: 

175 self.console.print(f"[red]❌[/ red] Error pushing: {e}") 

176 return False 

177 

178 def get_current_branch(self) -> str | None: 

179 try: 

180 result = self._run_git_command(["branch", "- - show-current"]) 

181 return result.stdout.strip() if result.returncode == 0 else None 

182 except (subprocess.SubprocessError, OSError, FileNotFoundError): 

183 return None 

184 

185 def get_commit_message_suggestions(self, files: list[str]) -> list[str]: 

186 if not files: 

187 return ["Update project files"] 

188 file_categories = self._categorize_files(files) 

189 messages = self._generate_category_messages(file_categories) 

190 messages.extend(self._generate_specific_messages(files)) 

191 

192 return messages[:5] 

193 

194 def _categorize_files(self, files: list[str]) -> set[str]: 

195 categories = { 

196 "docs": ["README", "CLAUDE", "docs /", ".md"], 

197 "tests": ["test_", "tests /", "conftest.py"], 

198 "config": ["pyproject.toml", ".yaml", ".yml", ".json", ".gitignore"], 

199 "ci": [".github /", "ci /", ".pre-commit"], 

200 "deps": ["requirements", "uv.lock", "Pipfile"], 

201 } 

202 file_categories: set[str] = set() 

203 for file in files: 

204 category = self._get_file_category(file, categories) 

205 file_categories.add(category) 

206 

207 return file_categories 

208 

209 def _get_file_category(self, file: str, categories: dict[str, list[str]]) -> str: 

210 for category, patterns in categories.items(): 

211 if any(pattern in file for pattern in patterns): 

212 return category 

213 return "core" 

214 

215 def _generate_category_messages(self, file_categories: set[str]) -> list[str]: 

216 if len(file_categories) == 1: 

217 return self._generate_single_category_message(next(iter(file_categories))) 

218 return [f"Update {', '.join(sorted(file_categories))}"] 

219 

220 def _generate_single_category_message(self, category: str) -> list[str]: 

221 category_messages = { 

222 "docs": "Update documentation", 

223 "tests": "Update tests", 

224 "config": "Update configuration", 

225 "ci": "Update CI / CD configuration", 

226 "deps": "Update dependencies", 

227 } 

228 return [category_messages.get(category, "Update core functionality")] 

229 

230 def _generate_specific_messages(self, files: list[str]) -> list[str]: 

231 messages: list[str] = [] 

232 if "pyproject.toml" in files: 

233 messages.append("Update project configuration") 

234 if any("test_" in f for f in files): 

235 messages.append("Improve test coverage") 

236 if "README.md" in files: 

237 messages.append("Update README documentation") 

238 

239 return messages