|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import json |
| 4 | +import shutil |
| 5 | +import subprocess |
| 6 | +import sys |
| 7 | +from pathlib import Path |
| 8 | +from tempfile import NamedTemporaryFile |
| 9 | + |
| 10 | + |
| 11 | +def get_staged_python_files(): |
| 12 | + result = subprocess.run( |
| 13 | + ['git', 'diff', '--cached', '--name-only', '--diff-filter=ACM'], capture_output=True, text=True |
| 14 | + ) |
| 15 | + return [f for f in result.stdout.strip().splitlines() if f.endswith('.py')] |
| 16 | + |
| 17 | + |
| 18 | +def get_changed_lines(file_path): |
| 19 | + result = subprocess.run(['git', 'diff', '--cached', '-U0', file_path], capture_output=True, text=True) |
| 20 | + lines = [] |
| 21 | + for line in result.stdout.splitlines(): |
| 22 | + if line.startswith('@@'): |
| 23 | + parts = line.split(' ') |
| 24 | + added = parts[2] # e.g., '+10,2' or '+5' |
| 25 | + start, _, count = added[1:].partition(',') |
| 26 | + start = int(start) |
| 27 | + count = int(count) if count else 1 |
| 28 | + lines.extend(range(start, start + count)) |
| 29 | + return set(lines) |
| 30 | + |
| 31 | + |
| 32 | +def apply_fixes_to_changed_lines(file_path, changed_lines): |
| 33 | + # Create a backup |
| 34 | + original = Path(file_path).read_text() |
| 35 | + |
| 36 | + # Let Ruff fix the whole file into a temp file |
| 37 | + with NamedTemporaryFile('w+', delete=False) as temp: |
| 38 | + temp_path = temp.name |
| 39 | + shutil.copyfile(file_path, temp_path) |
| 40 | + subprocess.run(['ruff', 'check', '--fix', '--select', 'Q', temp_path], capture_output=True) |
| 41 | + |
| 42 | + original_lines = original.splitlines() |
| 43 | + fixed_lines = Path(temp_path).read_text().splitlines() |
| 44 | + |
| 45 | + # Apply only the fixed lines that are within changed lines |
| 46 | + new_lines = [] |
| 47 | + for i, (orig, fixed) in enumerate(zip(original_lines, fixed_lines), start=1): |
| 48 | + if i in changed_lines and orig != fixed: |
| 49 | + new_lines.append(fixed) |
| 50 | + else: |
| 51 | + new_lines.append(orig) |
| 52 | + |
| 53 | + Path(file_path).write_text('\n'.join(new_lines) + '\n') |
| 54 | + subprocess.run(['git', 'add', file_path]) |
| 55 | + |
| 56 | + |
| 57 | +def main(): |
| 58 | + staged_files = get_staged_python_files() |
| 59 | + |
| 60 | + if not staged_files: |
| 61 | + sys.exit(0) |
| 62 | + |
| 63 | + for file in staged_files: |
| 64 | + changed_lines = get_changed_lines(file) |
| 65 | + if not changed_lines: |
| 66 | + continue |
| 67 | + |
| 68 | + apply_fixes_to_changed_lines(file, changed_lines) |
| 69 | + |
| 70 | + print('✅ Ruff autofix applied to changed lines only.') |
| 71 | + sys.exit(0) |
| 72 | + |
| 73 | + |
| 74 | +if __name__ == '__main__': |
| 75 | + main() |
0 commit comments