|
3 | 3 | import os |
4 | 4 | import shlex |
5 | 5 | import subprocess |
6 | | -from typing import TYPE_CHECKING |
| 6 | +from typing import TYPE_CHECKING, Optional |
7 | 7 |
|
8 | 8 | import isort |
9 | 9 |
|
|
12 | 12 | if TYPE_CHECKING: |
13 | 13 | from pathlib import Path |
14 | 14 |
|
15 | | - |
16 | | -def should_format_file(filepath, max_lines_changed=100): |
17 | | - try: |
18 | | - # check if black is installed |
19 | | - subprocess.run(['black', '--version'], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) |
20 | | - |
21 | | - result = subprocess.run( |
22 | | - ['black', '--diff', filepath], |
23 | | - capture_output=True, |
24 | | - text=True |
25 | | - ) |
26 | | - |
27 | | - diff_lines = [line for line in result.stdout.split('\n') |
28 | | - if line.startswith(('+', '-')) and not line.startswith(('+++', '---'))] |
29 | | - |
30 | | - changes_count = len(diff_lines) |
31 | | - |
32 | | - if changes_count > max_lines_changed: |
33 | | - logger.debug(f"Skipping {filepath}: {changes_count} lines would change (max: {max_lines_changed})") |
34 | | - return False |
35 | | - |
36 | | - return True |
37 | | - |
38 | | - except subprocess.CalledProcessError: |
39 | | - logger.warning(f"black --diff command failed for {filepath}") |
40 | | - return False |
41 | | - except FileNotFoundError: |
42 | | - logger.warning("black formatter is not installed. Skipping formatting diff check.") |
43 | | - return False |
44 | | - |
45 | | - |
| 15 | +def get_diff_lines_output_by_black(filepath: str) -> Optional[str]: |
| 16 | + try: |
| 17 | + subprocess.run(['black', '--version'], check=True, |
| 18 | + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) |
| 19 | + result = subprocess.run( |
| 20 | + ['black', '--diff', filepath], |
| 21 | + capture_output=True, |
| 22 | + text=True |
| 23 | + ) |
| 24 | + return result.stdout.strip() if result.stdout else None |
| 25 | + except (FileNotFoundError): |
| 26 | + return None |
| 27 | + |
| 28 | + |
| 29 | +def get_diff_lines_output_by_ruff(filepath: str) -> Optional[str]: |
| 30 | + try: |
| 31 | + subprocess.run(['ruff', '--version'], check=True, |
| 32 | + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) |
| 33 | + result = subprocess.run( |
| 34 | + ['ruff', "format", '--diff', filepath], |
| 35 | + capture_output=True, |
| 36 | + text=True |
| 37 | + ) |
| 38 | + return result.stdout.strip() if result.stdout else None |
| 39 | + except (FileNotFoundError): |
| 40 | + return None |
| 41 | + |
| 42 | + |
| 43 | +def get_diff_lines_count(diff_output: str) -> int: |
| 44 | + diff_lines = [line for line in diff_output.split('\n') |
| 45 | + if line.startswith(('+', '-')) and not line.startswith(('+++', '---'))] |
| 46 | + return len(diff_lines) |
| 47 | + |
| 48 | +def is_safe_to_format(filepath: str, max_diff_lines: int = 100) -> bool: |
| 49 | + diff_changes_stdout = None |
| 50 | + |
| 51 | + diff_changes_stdout = get_diff_lines_output_by_black(filepath) |
| 52 | + |
| 53 | + if diff_changes_stdout is None: |
| 54 | + logger.warning(f"black formatter not found, trying ruff instead...") |
| 55 | + diff_changes_stdout = get_diff_lines_output_by_ruff(filepath) |
| 56 | + if diff_changes_stdout is None: |
| 57 | + msg = f"Both ruff, black formatters not found, skipping formatting diff check." |
| 58 | + logger.warning(msg) |
| 59 | + raise FileNotFoundError(msg) |
| 60 | + |
| 61 | + diff_lines_count = get_diff_lines_count(diff_changes_stdout) |
| 62 | + |
| 63 | + if diff_lines_count > max_diff_lines: |
| 64 | + logger.debug(f"Skipping {filepath}: {diff_lines_count} lines would change (max: {max_diff_lines})") |
| 65 | + return False |
| 66 | + else: |
| 67 | + return True |
| 68 | + |
46 | 69 |
|
47 | 70 | def format_code(formatter_cmds: list[str], path: Path, print_status: bool = True) -> str: # noqa |
48 | 71 | # TODO: Only allow a particular whitelist of formatters here to prevent arbitrary code execution |
49 | 72 | formatter_name = formatter_cmds[0].lower() |
50 | 73 | if not path.exists(): |
51 | 74 | msg = f"File {path} does not exist. Cannot format the file." |
52 | 75 | raise FileNotFoundError(msg) |
53 | | - if formatter_name == "disabled" or not should_format_file(path): |
| 76 | + if formatter_name == "disabled" or not is_safe_to_format(path): # few -> False, large -> True |
54 | 77 | return path.read_text(encoding="utf8") |
55 | 78 |
|
56 | 79 | file_token = "$file" # noqa: S105 |
|
0 commit comments