Skip to content

Commit

Permalink
format.py: Use bazel build, support excludes (#3062)
Browse files Browse the repository at this point in the history
  • Loading branch information
npaun authored Nov 5, 2024
1 parent 2263425 commit b2c31bd
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
3 changes: 2 additions & 1 deletion WORKSPACE
Original file line number Diff line number Diff line change
Expand Up @@ -434,7 +434,8 @@ http_file(

FILE_GROUP = """filegroup(
name="file",
srcs=["**/*"])"""
srcs=glob(["**"])
)"""

http_archive(
name = "ruff-darwin-arm64",
Expand Down
19 changes: 14 additions & 5 deletions tools/cross/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,15 +63,21 @@ def parse_args() -> Namespace:


def filter_files_by_globs(
files: list[Path], dir_path: Path, globs: tuple[str, ...]
files: list[Path], dir_path: Path, globs: tuple[str, ...], excludes: tuple[str, ...]
) -> list[Path]:
return [
file
for file in files
if file.is_relative_to(dir_path) and matches_any_glob(globs, file)
if file.is_relative_to(dir_path)
and matches_any_glob(globs, file)
and not relative_to_any(excludes, file)
]


def relative_to_any(excludes: tuple[str, ...], file: Path) -> bool:
return any(file.is_relative_to(exclude) for exclude in excludes)


def matches_any_glob(globs: tuple[str, ...], file: Path) -> bool:
return any(file.match(glob) for glob in globs)

Expand Down Expand Up @@ -116,10 +122,10 @@ def run_bazel_tool(
tool_path = init_external_dir() / tool_target / "file" / "downloaded"

if not tool_path.exists():
fetch_target = (
build_target = (
f"@{tool_target}//:file" if is_archive else f"@{tool_target}//file"
)
subprocess.run(["bazel", "fetch", fetch_target])
subprocess.run(["bazel", "build", build_target])

return subprocess.run([tool_path, *args])

Expand Down Expand Up @@ -202,6 +208,7 @@ class FormatConfig:
directory: str
globs: tuple[str, ...]
formatter: str
excludes: tuple[str, ...] = ()


FORMATTERS = {
Expand All @@ -213,7 +220,9 @@ class FormatConfig:


def format(config: FormatConfig, files: list[Path], check: bool) -> tuple[bool, str]:
matching_files = filter_files_by_globs(files, Path(config.directory), config.globs)
matching_files = filter_files_by_globs(
files, Path(config.directory), config.globs, config.excludes
)

if not matching_files:
return (
Expand Down

0 comments on commit b2c31bd

Please sign in to comment.