blob: 5054bbadbc041f8ef3d3b32269e9759ce6307002 [file]
# Copyright 2026 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Common SHAC execution helpers for fx lint and fx format-code."""
import contextlib
import fnmatch
import json
import os
import pathlib
import platform
import shutil
import signal
import subprocess
import sys
import tempfile
import types
from collections.abc import Callable, Collection, Mapping, Sequence
import scm
_STATIC_CHECKS_TARGET = "//bundles/buildbot/static_checks"
# Mapping from SHAC check name to the compiled host tool name in tool_paths.json
# invoked via compiled_tool_path() in //scripts/shac/*.star.
_COMPILED_TOOL_FMT_CHECKS = types.MappingProxyType(
{
"cml_format": "cmc",
"dml_format": "cmc",
"fidl_format": "fidl-format",
"gidl_format": "gidl-format",
"json5_format": "formatjson5",
}
)
_COMPILED_TOOL_FMT_EXTENSIONS = types.MappingProxyType(
{
"cml_format": (".cml",),
"dml_format": (".dml",),
"fidl_format": (".fidl",),
"gidl_format": (".gidl",),
"json5_format": (".json5", ".persist", ".triage"),
}
)
_SARIF_FAIL_LEVELS = types.MappingProxyType(
{
"error": frozenset(("error",)),
"warning": frozenset(("error", "warning")),
"notice": frozenset(("error", "warning", "note")),
}
)
_COMPILED_TOOL_CHECKS = types.MappingProxyType(
{
**_COMPILED_TOOL_FMT_CHECKS,
"check_licenses": "check-licenses",
"clippy": "clippy-reporter",
"dml_lint": "dmlc",
"doc_checker": "doc-checker",
"fidl_lint": "fidl-lint",
"mdlint": "mdlint",
"readme_fuchsia_required_fields": "readme_fuchsia",
"rfcmeta": "rfcmeta",
"verify_bazel2gn": "bazel2gn",
}
)
# Tool names in tool_paths.json corresponding to the dependencies of
# //bundles/buildbot/static_checks/BUILD.gn invoked via compiled_tool_path() in
# //scripts/shac/common.star.
_STATIC_CHECK_TOOLS = frozenset(_COMPILED_TOOL_CHECKS.values())
def _resolve_shac_binary() -> pathlib.Path:
"""Locates the prebuilt shac binary from PREBUILT_SHAC or PATH.
Returns:
Path to the shac executable.
Raises:
FileNotFoundError: If PREBUILT_SHAC points to a non-existent file or
shac cannot be found on PATH.
"""
if prebuilt_shac := os.environ.get("PREBUILT_SHAC"):
candidate = pathlib.Path(prebuilt_shac)
if candidate.is_file():
return candidate
raise FileNotFoundError(
f"shac binary not found at PREBUILT_SHAC={prebuilt_shac}"
)
if (which_shac := shutil.which("shac")) is not None:
return pathlib.Path(which_shac)
raise FileNotFoundError("shac binary not found.")
def _validate_explicit_files(
explicit_files: Collection[str],
fuchsia_dir: pathlib.Path,
cwd: pathlib.Path,
) -> Sequence[str]:
"""Validates explicit file paths and prints an error for missing files."""
valid_files = []
for raw_path in explicit_files:
stripped_path = raw_path.strip()
if not stripped_path:
continue
absolute_path = scm.canonicalize_path(stripped_path, cwd, fuchsia_dir)
if not absolute_path.is_file():
print(f"ERROR: no such file: {absolute_path}", file=sys.stderr)
continue
valid_files.append(stripped_path)
return tuple(valid_files)
def split_comma_separated(
entries: Collection[str],
) -> Sequence[str]:
"""Splits repeatable comma-separated CLI flag entries into stripped items.
Args:
entries: Collection of raw CLI flag values (each possibly
comma-separated).
Returns:
A sequence of non-empty stripped strings in order of appearance.
"""
return tuple(
stripped
for entry in entries
for item in entry.split(",")
if (stripped := item.strip())
)
def resolve_workspace_paths(
default_fuchsia_dir: pathlib.Path,
) -> tuple[pathlib.Path, pathlib.Path, pathlib.Path]:
"""Resolves FUCHSIA_DIR, FUCHSIA_BUILD_DIR, and current working directory.
Args:
default_fuchsia_dir: Fallback Fuchsia root directory when FUCHSIA_DIR
is not set in the environment.
Returns:
A tuple of (fuchsia_dir, build_dir, cwd) as resolved absolute paths.
"""
if (fuchsia_dir_env := os.environ.get("FUCHSIA_DIR")) is not None:
fuchsia_dir = pathlib.Path(fuchsia_dir_env).resolve()
else:
fuchsia_dir = default_fuchsia_dir.resolve()
if (
fuchsia_build_dir_env := os.environ.get("FUCHSIA_BUILD_DIR")
) is not None:
build_dir = pathlib.Path(fuchsia_build_dir_env).resolve()
else:
build_dir = fuchsia_dir / "out" / "default"
cwd = pathlib.Path.cwd().resolve()
return (fuchsia_dir, build_dir, cwd)
def _build_shac_command(
shac_binary: pathlib.Path,
subcommand: str,
group: scm.RepoGroup,
fuchsia_dir: pathlib.Path,
build_dir: pathlib.Path,
*,
all_files: bool,
include_untracked: bool,
only_checks: Collection[str],
skip_checks: Collection[str],
extra_args: Sequence[str],
verbose: bool,
sarif_output: pathlib.Path | None,
) -> Sequence[str]:
"""Builds the shac command-line invocation for a single repository group."""
relative_fuchsia_dir = os.path.relpath(fuchsia_dir, group.repo_root)
relative_build_dir = os.path.relpath(build_dir, fuchsia_dir)
command = [
str(shac_binary),
subcommand,
"-C",
str(group.repo_root),
f"--var=fuchsia_dir={relative_fuchsia_dir}",
f"--var=fuchsia_build_dir={relative_build_dir}",
]
if all_files:
command.append("--all")
if not include_untracked:
command.append("--no-untracked")
if verbose:
command.append("--verbose")
else:
command.append("--quiet")
if sarif_output is not None:
command.append(f"--json-output={sarif_output}")
if only_checks:
command.append(f"--only={','.join(only_checks)}")
if skip_checks:
command.append(f"--skip={','.join(skip_checks)}")
if extra_args:
command.extend(extra_args)
if group.files:
command.extend(group.files)
return tuple(command)
def _host_platform_and_cpu() -> tuple[str, str]:
"""Returns the current host (os, cpu) matching tool_paths.json."""
host_os = "mac" if sys.platform == "darwin" else sys.platform
machine = platform.machine()
if machine == "x86_64":
host_cpu = "x64"
elif machine in ("aarch64", "arm64"):
host_cpu = "arm64"
else:
host_cpu = machine
return (host_os, host_cpu)
def _load_host_tool_entries(
build_dir: pathlib.Path,
) -> Mapping[str, tuple[str, str | None]] | None:
"""Loads {tool_name: (relative_path, gn_target)} from tool_paths.json."""
tool_paths_file = build_dir / "tool_paths.json"
try:
entries = json.loads(tool_paths_file.read_text())
except (FileNotFoundError, UnicodeDecodeError, json.JSONDecodeError):
return None
if not isinstance(entries, list):
return None
host_os, host_cpu = _host_platform_and_cpu()
tool_entries = {}
for entry in entries:
if (
isinstance(entry, dict)
and entry.get("os") == host_os
and entry.get("cpu") == host_cpu
and isinstance(tool_name := entry.get("name"), str)
and isinstance(tool_path := entry.get("path"), str)
):
raw_label = entry.get("label")
gn_target = (
raw_label.split("(", 1)[0]
if isinstance(raw_label, str) and raw_label.startswith("//")
else None
)
tool_entries[tool_name] = (tool_path, gn_target)
return tool_entries
def _are_static_check_tools_built(build_dir: pathlib.Path) -> bool:
"""Returns True if tool_paths.json and all static_checks binaries exist."""
tool_entries = _load_host_tool_entries(build_dir)
if tool_entries is None:
return False
for tool_name in _STATIC_CHECK_TOOLS:
tool_entry = tool_entries.get(tool_name)
if tool_entry is None:
return False
tool_binary = build_dir / tool_entry[0]
if not tool_binary.is_file() or not os.access(tool_binary, os.X_OK):
return False
return True
def _is_build_lock_held(build_dir: pathlib.Path) -> bool:
"""Returns True if an active `fx build` appears to hold `.build_lock`."""
lock_path = build_dir.parent / f"{build_dir.name}.build_lock"
try:
pid_text = lock_path.read_text().strip()
except FileNotFoundError:
return False
except (PermissionError, UnicodeDecodeError):
return True
if not pid_text:
return False
try:
pid = int(pid_text)
except ValueError:
return True
if pid <= 0:
return False
try:
os.kill(pid, 0)
except ProcessLookupError:
return False
except PermissionError:
return True
return True
def _eligible_fmt_checks(
only_checks: Collection[str],
skip_checks: Collection[str],
) -> Collection[str]:
"""Returns compiled-tool fmt check names eligible for the given flags."""
eligible = []
for check_name in sorted(_COMPILED_TOOL_FMT_CHECKS):
if only_checks and not any(
fnmatch.fnmatchcase(check_name, pat) for pat in only_checks
):
continue
if skip_checks and any(
fnmatch.fnmatchcase(check_name, pat) for pat in skip_checks
):
continue
eligible.append(check_name)
return tuple(eligible)
def _sarif_failing_levels(extra_args: Sequence[str]) -> Collection[str]:
"""Returns the set of SARIF result levels that cause `shac` to fail."""
fail_level = "error"
args_iter = iter(extra_args)
for arg in args_iter:
if arg.startswith("--fail-level="):
fail_level = arg.split("=", 1)[1]
elif arg == "--fail-level":
next_val = next(args_iter, None)
if next_val is not None:
fail_level = next_val
return _SARIF_FAIL_LEVELS.get(fail_level, _SARIF_FAIL_LEVELS["error"])
def _sarif_failed_checks(
sarif_path: pathlib.Path,
failing_levels: Collection[str],
) -> Collection[str]:
"""Extracts failing check names from a SHAC SARIF file, or `()` if none."""
try:
data = json.loads(sarif_path.read_text())
except (FileNotFoundError, UnicodeDecodeError, json.JSONDecodeError):
return ()
if not isinstance(data, dict):
return ()
runs = data.get("runs")
if not isinstance(runs, list):
return ()
failed_checks = []
for run in runs:
if not isinstance(run, dict):
continue
tool = run.get("tool")
driver = tool.get("driver") if isinstance(tool, dict) else None
check_name = driver.get("name") if isinstance(driver, dict) else None
if not isinstance(check_name, str) or not check_name:
continue
results = run.get("results")
if not isinstance(results, list):
continue
if any(
isinstance(result, dict)
and result.get("level", "error") in failing_levels
for result in results
):
failed_checks.append(check_name)
return tuple(failed_checks)
def _targets_for_checks(
build_dir: pathlib.Path,
check_names: Collection[str],
) -> Sequence[str]:
"""Resolves GN host targets for `check_names`, falling back to static_checks."""
tool_entries = _load_host_tool_entries(build_dir)
if tool_entries is None:
return (_STATIC_CHECKS_TARGET,)
targets = set()
for check_name in check_names:
tool_name = _COMPILED_TOOL_CHECKS.get(check_name)
if tool_name is None:
continue
entry = tool_entries.get(tool_name)
if entry is None or entry[1] is None:
return (_STATIC_CHECKS_TARGET,)
targets.add(entry[1])
return tuple(sorted(targets)) if targets else (_STATIC_CHECKS_TARGET,)
def _stat_tool_binary(path: pathlib.Path) -> tuple[int, int] | None:
"""Returns `(st_mtime_ns, st_size)` for a binary, or None if unavailable."""
try:
st = path.stat()
except (FileNotFoundError, NotADirectoryError):
return None
return (st.st_mtime_ns, st.st_size)
def _snapshot_tool_binaries(
build_dir: pathlib.Path,
targets: Collection[str],
) -> Mapping[str, tuple[int, int] | None]:
"""Captures `(st_mtime_ns, st_size)` for host tool binaries matching `targets`."""
tool_entries = _load_host_tool_entries(build_dir)
if tool_entries is None:
return {}
rebuild_all = _STATIC_CHECKS_TARGET in targets
snapshot = {}
for tool_name in sorted(_STATIC_CHECK_TOOLS):
entry = tool_entries.get(tool_name)
if entry is None:
continue
rel_path, gn_target = entry
if not rebuild_all and gn_target not in targets:
continue
snapshot[tool_name] = _stat_tool_binary(build_dir / rel_path)
return snapshot
def _rebuild_targets_for_failure(
subcommand: str,
build_dir: pathlib.Path,
sarif_path: pathlib.Path | None,
only_checks: Collection[str],
skip_checks: Collection[str],
files: Collection[str],
extra_args: Sequence[str],
) -> Sequence[str] | None:
"""Returns host GN targets to rebuild after a SHAC failure, or None."""
if sarif_path is not None:
failed_checks = _sarif_failed_checks(
sarif_path, _sarif_failing_levels(extra_args)
)
compiled_failures = tuple(
check for check in failed_checks if check in _COMPILED_TOOL_CHECKS
)
if not compiled_failures:
return None
return _targets_for_checks(build_dir, compiled_failures)
if subcommand != "fmt":
return None
eligible = _eligible_fmt_checks(only_checks, skip_checks)
if not eligible:
return None
emit_enabled = False
for arg in extra_args:
if arg == "--emit":
emit_enabled = True
elif arg.startswith("--emit="):
emit_enabled = arg.split("=", 1)[1].lower() not in (
"false",
"0",
"f",
)
if emit_enabled:
return None
if not files:
return _targets_for_checks(build_dir, eligible) if only_checks else None
matched_fmt = tuple(
check
for check in eligible
if any(
path.endswith(_COMPILED_TOOL_FMT_EXTENSIONS[check])
for path in files
)
)
if not matched_fmt:
return None
return _targets_for_checks(build_dir, matched_fmt)
def _run_fx_build(
fuchsia_dir: pathlib.Path,
env: Mapping[str, str],
targets: Sequence[str],
*,
verbose: bool,
dry_run: bool,
) -> bool:
"""Runs `fx build --host <targets>`. Returns True if executed."""
command = (
str(fuchsia_dir / "scripts" / "fx"),
"build",
"--host",
*targets,
)
if verbose:
print(f"Running: {' '.join(command)}")
if dry_run:
print(f"[dry-run] Would execute: {' '.join(command)}")
return False
subprocess.run(
command, cwd=fuchsia_dir, env=env, stdout=sys.stderr, check=True
)
return True
# SHAC executes checks inside a read-only sandbox and cannot invoke `fx build`
# on demand when resolving compiled host tools via `compiled_tool_path()` in
# //scripts/shac/common.star. In clean checkouts or `fx worktree` environments
# where a full build has not been run, missing host binaries in
# $FUCHSIA_BUILD_DIR would otherwise cause SHAC to fail.
#
# When tool_paths.json or any binary in //bundles/buildbot/static_checks is
# missing on disk, building the static_checks umbrella group as a pre-flight
# step ensures all required host tools are compiled while skipping `fx build`
# overhead and avoiding clobbering last_ninja_build_targets.txt when already
# present. If an existing compiled-tool check fails later due to a stale binary,
# `run_shac()` reactively rebuilds the relevant tool target(s) and retries once.
def _ensure_static_check_tools_built(
fuchsia_dir: pathlib.Path,
build_dir: pathlib.Path,
env: Mapping[str, str],
*,
verbose: bool,
dry_run: bool,
) -> bool:
"""Builds the static_checks host tool bundle if any binary is missing."""
if _are_static_check_tools_built(build_dir):
return False
return _run_fx_build(
fuchsia_dir,
env,
(_STATIC_CHECKS_TARGET,),
verbose=verbose,
dry_run=dry_run,
)
def run_shac(
subcommand: str,
fuchsia_dir: pathlib.Path,
build_dir: pathlib.Path,
cwd: pathlib.Path,
*,
all_files: bool = False,
all_repos: bool = False,
include_untracked: bool = False,
only_checks: Collection[str] = (),
skip_checks: Collection[str] = (),
explicit_files: Collection[str] | None = None,
extra_args: Sequence[str] = (),
verbose: bool = False,
dry_run: bool = False,
) -> None:
"""Runs a shac subcommand ('check', 'fix', or 'fmt') across repository groups.
Args:
subcommand: The SHAC subcommand to execute ('check', 'fix', or 'fmt').
fuchsia_dir: Absolute path to the Fuchsia checkout root.
build_dir: Path to the active Fuchsia build directory.
cwd: Current working directory for resolving relative paths.
all_files: If True, passes '--all' to SHAC to check all tracked files
instead of only modified files.
all_repos: If True, runs in every active repository in the checkout
instead of only the repository enclosing cwd. Has no effect when
explicit_files is given.
include_untracked: If True, allows SHAC to include untracked files in
git repositories; otherwise passes '--no-untracked'.
only_checks: Collection of check names to pass via '--only'.
skip_checks: Collection of check names to pass via '--skip'.
explicit_files: Optional collection of explicit file paths to check, or
None to run in the repository enclosing cwd (or across all active
repositories when all_repos is True) without file filtering.
If an empty collection (or if all specified files are missing),
returns without invoking SHAC.
extra_args: Sequence of extra CLI arguments forwarded to SHAC.
verbose: If True, passes '--verbose' to SHAC and logs command lines;
otherwise passes '--quiet' to SHAC.
dry_run: If True, prints the SHAC command lines without executing them.
Raises:
subprocess.CalledProcessError: If `fx build`, `shac`, or `git` exits
with a non-zero status code.
FileNotFoundError: If the `shac` binary cannot be found or if a target
path requires invoking `git` and the `git` executable cannot be
found.
"""
valid_files = None
if explicit_files is not None:
valid_files = _validate_explicit_files(explicit_files, fuchsia_dir, cwd)
if not valid_files:
return
shac_binary = _resolve_shac_binary()
shac_env = os.environ | {
"FUCHSIA_DIR": str(fuchsia_dir),
"FUCHSIA_BUILD_DIR": str(build_dir),
}
repo_groups = scm.get_repo_groups(
fuchsia_dir,
cwd,
explicit_files=valid_files,
all_repos=all_repos,
)
shac_groups = tuple(group for group in repo_groups if group.has_shac)
if not shac_groups:
roots = ", ".join(str(group.repo_root) for group in repo_groups)
print(
f"WARNING: no shac.textproto found in {roots}; nothing to do.",
file=sys.stderr,
)
return
rebuilt_targets = (
{_STATIC_CHECKS_TARGET}
if _ensure_static_check_tools_built(
fuchsia_dir,
build_dir,
shac_env,
verbose=verbose,
dry_run=dry_run,
)
else set()
)
has_json_output = any(
arg == "--json-output" or arg.startswith("--json-output=")
for arg in extra_args
)
use_sarif = (
not dry_run and not has_json_output and subcommand in ("check", "fix")
)
for group in shac_groups:
sarif_context = (
tempfile.TemporaryDirectory(prefix="shac_sarif_")
if use_sarif
else contextlib.nullcontext()
)
with sarif_context as sarif_dir:
sarif_path = (
pathlib.Path(sarif_dir) / "results.sarif.json"
if sarif_dir is not None
else None
)
command = _build_shac_command(
shac_binary,
subcommand,
group,
fuchsia_dir,
build_dir,
all_files=all_files,
include_untracked=include_untracked,
only_checks=only_checks,
skip_checks=skip_checks,
extra_args=extra_args,
verbose=verbose,
sarif_output=sarif_path,
)
if verbose:
print(f"Running: {' '.join(command)}")
if dry_run:
print(f"[dry-run] Would execute: {' '.join(command)}")
continue
try:
subprocess.run(
command,
cwd=group.repo_root,
env=shac_env,
stdin=subprocess.DEVNULL,
check=True,
)
except subprocess.CalledProcessError as exc:
if _STATIC_CHECKS_TARGET in rebuilt_targets:
raise
candidate_targets = _rebuild_targets_for_failure(
subcommand,
build_dir,
sarif_path,
only_checks,
skip_checks,
group.files,
extra_args,
)
if candidate_targets is None:
raise
targets = tuple(
target
for target in candidate_targets
if target not in rebuilt_targets
)
if not targets:
raise
if _is_build_lock_held(build_dir):
exc.add_note(
f"Note: skipped rebuilding {' '.join(targets)} because "
f"an active fx build holds {build_dir.parent / f'{build_dir.name}.build_lock'}. "
f"Retry or run `fx build --host {' '.join(targets)}`."
)
raise
before_snapshot = _snapshot_tool_binaries(build_dir, targets)
print(
f"Rebuilding static-check tool(s) ({' '.join(targets)})...",
file=sys.stderr,
)
if _run_fx_build(
fuchsia_dir,
shac_env,
targets,
verbose=verbose,
dry_run=False,
):
rebuilt_targets.update(targets)
after_snapshot = _snapshot_tool_binaries(build_dir, targets)
if before_snapshot and after_snapshot == before_snapshot:
raise
else:
continue
subprocess.run(
command,
cwd=group.repo_root,
env=shac_env,
stdin=subprocess.DEVNULL,
check=True,
)
def _exit_by_sigint() -> int:
"""Terminates the current process with SIGINT for POSIX cooperative exit."""
for stream in (sys.stdout, sys.stderr):
with contextlib.suppress(OSError, ValueError):
stream.flush()
signal.signal(signal.SIGINT, signal.SIG_DFL)
os.kill(os.getpid(), signal.SIGINT)
return 130
def cli_exit_status(action: Callable[[], None]) -> int:
"""Runs `action` and translates expected CLI errors into POSIX exit codes.
Subprocess failures from `fx build`, `shac`, or `git` exit with the child
process's exit status instead of printing a Python traceback. If the failing
subprocess captured stderr (such as `git rev-parse`) or carries exception
notes (such as skipped reactive rebuild notices), those are forwarded to
`sys.stderr`. `SIGINT` (either `KeyboardInterrupt` or a child dying from
`SIGINT`) re-raises `SIGINT` with `SIG_DFL` so calling shells observe
`WIFSIGNALED` and abort loops properly.
Args:
action: Zero-argument callable executing the CLI body.
Returns:
POSIX exit status (`0` on success, non-zero on failure).
"""
try:
action()
except subprocess.CalledProcessError as error:
if error.stderr:
if isinstance(error.stderr, bytes):
stderr_text = error.stderr.decode("utf-8", errors="replace")
else:
stderr_text = error.stderr
with contextlib.suppress(OSError, ValueError):
sys.stderr.write(stderr_text)
if not stderr_text.endswith("\n"):
sys.stderr.write("\n")
for note in getattr(error, "__notes__", ()):
with contextlib.suppress(OSError, ValueError):
print(note, file=sys.stderr)
if error.returncode == -signal.SIGINT:
return _exit_by_sigint()
if error.returncode < 0:
return 128 - error.returncode
return error.returncode if error.returncode > 0 else 1
except OSError as error:
with contextlib.suppress(OSError, ValueError):
print(f"ERROR: {error}", file=sys.stderr)
return 1
except KeyboardInterrupt:
return _exit_by_sigint()
return 0