| 1 |
#!/usr/bin/env bash |
| 2 |
|
| 3 |
# This script runs the ruff Python formatter on the repository. |
| 4 |
# By default, on non-main branches it only formats files changed relative to |
| 5 |
# the main branch. On the main branch or with --all, it formats all files. |
| 6 |
|
| 7 |
# Check version |
| 8 |
version_string=$(ruff --version | sed -E 's/^.*(\d+\.\d+-.*).*$/\1/') |
| 9 |
expected_version_string='0.15.20' |
| 10 |
if [[ "$version_string" =~ "$expected_version_string" ]]; then |
| 11 |
echo "ruff version '$version_string' matches '$expected_version_string'" |
| 12 |
else |
| 13 |
echo "ruff version '$version_string' doesn't match '$expected_version_string'" |
| 14 |
exit 1 |
| 15 |
fi |
| 16 |
|
| 17 |
root_folder=$(git rev-parse --show-toplevel) |
| 18 |
path_regex="^.*\(\.py\)$" |
| 19 |
|
| 20 |
format_all=false |
| 21 |
if [[ "$1" == "--all" ]]; then |
| 22 |
format_all=true |
| 23 |
fi |
| 24 |
|
| 25 |
current_branch=$(git rev-parse --abbrev-ref HEAD) |
| 26 |
|
| 27 |
staged_files=$( \ |
| 28 |
git diff --cached --name-only --diff-filter=d \ |
| 29 |
| grep "$path_regex" || true) |
| 30 |
|
| 31 |
if [[ "$format_all" == true ]] || [[ "$current_branch" == "main" ]]; then |
| 32 |
committed_files=$( \ |
| 33 |
git ls-tree --full-tree -r --name-only HEAD . \ |
| 34 |
| grep "$path_regex" || true) |
| 35 |
else |
| 36 |
merge_base=$(git merge-base main HEAD) |
| 37 |
committed_files=$( \ |
| 38 |
git diff --name-only --diff-filter=d "$merge_base" \ |
| 39 |
| grep "$path_regex" || true) |
| 40 |
fi |
| 41 |
|
| 42 |
all_files=$( \ |
| 43 |
printf '%s\n' "$committed_files" "$staged_files" \ |
| 44 |
| grep -v '^$' | sort -u \ |
| 45 |
| sed "s~^~$root_folder/~") |
| 46 |
|
| 47 |
if [[ -z "$all_files" ]]; then |
| 48 |
echo "No Python files to format" |
| 49 |
exit 0 |
| 50 |
fi |
| 51 |
num_files=$(echo "$all_files" | wc -l) |
| 52 |
echo "Formatting ${num_files} files" |
| 53 |
|
| 54 |
echo "$all_files" | tr '\n' '\0' | xargs -0 ruff format --config "${root_folder}/ruff.toml" |
| 55 |
echo "$all_files" | tr '\n' '\0' | xargs -0 ruff check --config "${root_folder}/ruff.toml" --fix |