Skip to content

Commit

Permalink
Add Python formatting with Ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
hoodmane committed Aug 21, 2024
1 parent 0ef4968 commit ef9bd17
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
3 changes: 3 additions & 0 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ jobs:
- name: Install project deps with pnpm
run: |
pnpm i
- name: Install Ruff
run: |
pip install ruff
- name: Lint
run: |
python3 ./tools/cross/format.py --check
Expand Down
25 changes: 24 additions & 1 deletion tools/cross/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import logging
import os
import re
import shutil
import subprocess
from argparse import ArgumentParser, Namespace
from typing import List, Optional, Tuple, Callable
Expand All @@ -11,6 +12,7 @@

CLANG_FORMAT = os.environ.get("CLANG_FORMAT", "clang-format")
PRETTIER = os.environ.get("PRETTIER", "node_modules/.bin/prettier")
RUFF = os.environ.get("RUFF", "ruff")


def parse_args() -> Namespace:
Expand Down Expand Up @@ -78,7 +80,7 @@ def filter_files_by_exts(
return [
file
for file in files
if file.startswith(dir_path + "/") and file.endswith(exts)
if (dir_path == "." or file.startswith(dir_path + "/")) and file.endswith(exts)
]


Expand All @@ -102,6 +104,26 @@ def prettier(files: List[str], check: bool = False) -> bool:
return result.returncode == 0


def ruff(files: List[str], check: bool = False) -> bool:
if files and not shutil.which(RUFF):
msg = "Cannot find ruff, will not format Python"
if check:
# In ci, fail.
logging.error(msg)
return False
else:
# In a local checkout, let it go. If the user wants Python
# formatting they can install ruff and run again.
logging.warning(msg)
return True
return not check
cmd = [RUFF, "format"]
if check:
cmd.append("--check")
result = subprocess.run(cmd + files)
return result.returncode == 0


def git_get_modified_files(
target: str, source: Optional[str], staged: bool
) -> List[str]:
Expand Down Expand Up @@ -147,6 +169,7 @@ class FormatConfig:
formatter=prettier,
),
FormatConfig(directory="src", extensions=(".json",), formatter=prettier),
FormatConfig(directory=".", extensions=(".py",), formatter=ruff),
# TODO: lint bazel files
]

Expand Down

0 comments on commit ef9bd17

Please sign in to comment.