Best-effort diff against main or master.
(cwd: str, *, max_chars: int = 48_000)
| 266 | |
| 267 | |
| 268 | def run_git_diff(cwd: str, *, max_chars: int = 48_000) -> str: |
| 269 | """Best-effort diff against main or master.""" |
| 270 | for base in ("main", "master", "origin/main", "origin/master"): |
| 271 | try: |
| 272 | r = subprocess.run( |
| 273 | ["git", "merge-base", "HEAD", base], |
| 274 | cwd=cwd, |
| 275 | capture_output=True, |
| 276 | text=True, |
| 277 | timeout=15, |
| 278 | check=False, |
| 279 | ) |
| 280 | if r.returncode != 0 or not (r.stdout or "").strip(): |
| 281 | continue |
| 282 | merge_base = (r.stdout or "").strip() |
| 283 | d = subprocess.run( |
| 284 | ["git", "diff", merge_base, "HEAD"], |
| 285 | cwd=cwd, |
| 286 | capture_output=True, |
| 287 | text=True, |
| 288 | timeout=30, |
| 289 | check=False, |
| 290 | ) |
| 291 | if d.returncode == 0 and (d.stdout or "").strip(): |
| 292 | out = d.stdout |
| 293 | return out[:max_chars] + ("…\n(truncated)" if len(out) > max_chars else "") |
| 294 | except (OSError, subprocess.SubprocessError): |
| 295 | continue |
| 296 | try: |
| 297 | d = subprocess.run( |
| 298 | ["git", "diff", "HEAD~50..HEAD"], |
| 299 | cwd=cwd, |
| 300 | capture_output=True, |
| 301 | text=True, |
| 302 | timeout=30, |
| 303 | check=False, |
| 304 | ) |
| 305 | if d.returncode == 0 and (d.stdout or "").strip(): |
| 306 | out = d.stdout |
| 307 | return out[:max_chars] + ("…\n(truncated)" if len(out) > max_chars else "") |
| 308 | except (OSError, subprocess.SubprocessError): |
| 309 | pass |
| 310 | return "(Could not compute git diff. Ensure this is a git repo with commits.)" |