Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .devcontainer/configure-host.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,11 @@ def ensure_native_image(image: str) -> None:


def host_service(system: str, home: Path) -> dict:
"""Use VM paths on macOS, never Unix sockets on the macOS shared filesystem."""
"""Use VM paths on macOS, never Unix sockets on the macOS shared filesystem.

Returns:
The Compose service configuration for the development container.
"""
service: dict = {"volumes": []}
image = os.environ.get("PHLEX_DEV_IMAGE")
if system == "Darwin":
Expand Down
6 changes: 5 additions & 1 deletion ci/promote_phlex_dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@


def promote_dependencies(env) -> list[str]:
"""Register existing link/run dependencies as abstract and concrete roots."""
"""Register existing link/run dependencies as abstract and concrete roots.

Returns:
Names of dependencies newly promoted to roots.
"""
from spack.spec import Spec

phlex_roots = [spec for spec in env.concrete_roots() if spec.name == "phlex"]
Expand Down
2 changes: 1 addition & 1 deletion ci/upgrade_repos.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def clean_package_imports(repo_obj: Repo) -> None:
for file in files:
if file == "package.py":
file_path = Path(root) / file
with open(file_path, "r", encoding="utf-8") as f:
with open(file_path, encoding="utf-8") as f:
content = f.read()

modified_content = content
Expand Down
4 changes: 2 additions & 2 deletions plugins/python/python/phlex/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Phlex Python support module."""

from ._typing import * # noqa: F403 no names used in this file
from ._variant import * # noqa: F403 idem
from ._typing import * # noqa: F403
from ._variant import * # noqa: F403
5 changes: 3 additions & 2 deletions plugins/python/python/phlex/_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@
import ctypes
import inspect
import typing
from collections.abc import Callable
from types import UnionType
from typing import Any, Callable, Dict, Union
from typing import Any, Union

import numpy as np

Expand Down Expand Up @@ -133,7 +134,7 @@ def _build_ctypes_map() -> dict[type, str]:
}


def normalize_type(tp: Any, globalns: Dict | None = None, localns: Dict | None = None) -> str:
def normalize_type(tp: Any, globalns: dict | None = None, localns: dict | None = None) -> str:
"""Recursively normalize any Python annotation to a canonical name.

This normalization supports:
Expand Down
11 changes: 9 additions & 2 deletions plugins/python/python/phlex/_variant.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,12 @@ def __init__(self, arg: str):
self.arg = arg

def __str__(self):
"""Report the argument that is missing an annotation."""
return "argument '%s' is not annotated" % self.arg
"""Report the argument that is missing an annotation.

Returns:
A message naming the argument without an annotation.
"""
return f"argument '{self.arg}' is not annotated"


class Variant:
Expand Down Expand Up @@ -107,6 +111,9 @@ def __call__(self, *args, **kwargs):

Raises:
AssertionError: To indicate incorrect usage, unless overridden.

Returns:
The wrapped callable's result when direct calls are enabled.
"""
assert self._allow_call, (
f"Variant '{self.__name__}' was called directly. "
Expand Down
13 changes: 13 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,17 @@ select = [
"B", # flake8-bugbear
"C4", # flake8-comprehensions
"D", # pydocstyle
"DOC201", # require Returns sections for documented return values
"E", # pycodestyle errors
"F", # pyflakes
"I", # isort
"PGH004", # require specific noqa codes
"RUF100", # reject unused noqa directives
"UP", # pyupgrade
"W", # pycodestyle warnings
]
preview = true
explicit-preview-rules = true
ignore = []
extend-ignore = [
"E731", # do not assign a lambda expression, use a def
Expand Down Expand Up @@ -103,6 +109,13 @@ known-first-party = [
"validate_clang_tidy_fixes",
]

[tool.ruff.lint.per-file-ignores]
# Ignore missing docstring requirements for test files and typing stubs
"test/**/*" = ["D", "DOC201"]
"scripts/test/**/*" = ["D", "DOC201"]
"test/python/test_typing.py" = ["UP006", "UP035"]
"*.pyi" = ["D", "DOC201"]

[tool.ruff.lint.pydocstyle]
convention = "google"

Expand Down
27 changes: 19 additions & 8 deletions scripts/check_codeql_alerts.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import urllib.parse
import urllib.request
from dataclasses import dataclass
from datetime import datetime, timezone
from datetime import UTC, datetime
from pathlib import Path
from typing import Any

Expand Down Expand Up @@ -236,7 +236,7 @@ def _log(msg: str) -> None:
try:
_LOG_PATH.parent.mkdir(parents=True, exist_ok=True)
# Use timezone-aware UTC timestamp to avoid deprecation warnings.
ts = datetime.now(timezone.utc).isoformat()
ts = datetime.now(UTC).isoformat()
with open(_LOG_PATH, "a", encoding="utf-8") as fh:
fh.write(f"{ts} {msg}\n")
except Exception:
Expand All @@ -254,7 +254,7 @@ def _init_log(log_path: Path) -> None:
_LOG_PATH = log_path
try:
_LOG_PATH.parent.mkdir(parents=True, exist_ok=True)
ts = datetime.now(timezone.utc).isoformat()
ts = datetime.now(UTC).isoformat()
with open(_LOG_PATH, "w", encoding="utf-8") as fh:
fh.write(f"{ts} CodeQL alerts helper log (truncated for new run)\n")
except Exception:
Expand All @@ -281,8 +281,7 @@ def _paginate_alerts_api(
raise GitHubAPIError("Unexpected response when listing alerts (expected list).")
if not result:
return
for alert in result:
yield alert
yield from result
# GitHub returns fewer than per_page items on the last page
if len(result) < per_page:
return
Expand Down Expand Up @@ -313,7 +312,11 @@ def _format_physical_location(phys: dict[str, Any]) -> str | None:


def _to_alert_api(raw: dict) -> Alert:
"""Convert a raw code-scanning alert object from the API into Alert dataclass."""
"""Convert a raw code-scanning alert object from the API into Alert dataclass.

Returns:
The normalized alert representation.
"""
rule = raw.get("rule") or {}
rule_id = str(rule.get("id") or "(rule id unavailable)")
instance = raw.get("most_recent_instance") or {}
Expand Down Expand Up @@ -973,7 +976,11 @@ def set_outputs(
def _compare_alerts_via_api(
owner: str, repo: str, ref: str, *, min_level: str = "warning"
) -> APIAlertComparison:
"""Compare alerts between a ref and the main branch using the GitHub API."""
"""Compare alerts between a ref and the main branch using the GitHub API.

Returns:
The categorized alert comparison.
"""
# Fetch PR metadata first so we can use the head SHA when querying PR alerts.
# The Code Scanning API does not support synthetic merge refs such as
# refs/pull/N/merge; using that ref returns zero results. The head SHA is
Expand Down Expand Up @@ -1130,7 +1137,11 @@ def _build_multi_section_comment(
*,
pr_number: int | None = None,
) -> str:
"""Build a detailed PR comment when multiple comparisons have been made."""
"""Build a detailed PR comment when multiple comparisons have been made.

Returns:
Markdown containing the comparison sections.
"""
lines: list[str] = []
# Matching summary (always include in PR comment)
if api_comp.new_vs_base or api_comp.fixed_vs_base:
Expand Down
6 changes: 5 additions & 1 deletion scripts/clang_tidy_check_summary.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,11 @@ def format_checklist(counts: dict[str, int], *, links: bool = False) -> str:


def build_arg_parser() -> argparse.ArgumentParser:
"""Build and return the argument parser for this script."""
"""Build and return the argument parser for this script.

Returns:
The configured command-line argument parser.
"""
parser = argparse.ArgumentParser(
prog="clang_tidy_check_summary.py",
description=(
Expand Down
12 changes: 10 additions & 2 deletions scripts/clang_tidy_diff_issues.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,11 @@ def filter_issues(


def build_arg_parser() -> argparse.ArgumentParser:
"""Build and return the argument parser."""
"""Build and return the argument parser.

Returns:
The configured command-line argument parser.
"""
parser = argparse.ArgumentParser(
description=(
"Report clang-tidy warnings and errors that fall on lines"
Expand Down Expand Up @@ -216,7 +220,11 @@ def build_arg_parser() -> argparse.ArgumentParser:


def main() -> int:
"""Parse arguments, filter issues, and report results."""
"""Parse arguments, filter issues, and report results.

Returns:
Zero on success, or a nonzero command-line error status.
"""
args = build_arg_parser().parse_args()

log_path = Path(args.log)
Expand Down
8 changes: 6 additions & 2 deletions scripts/clang_tidy_fixes_to_problems.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ class Diagnostic:
level: str = "warning"
file_path: str | None = None
file_offset: int | None = None
notes: list["DiagnosticNote"] | None = None
notes: list[DiagnosticNote] | None = None


@dataclass
Expand Down Expand Up @@ -329,7 +329,11 @@ def choose_workspace_note(


def build_arg_parser() -> argparse.ArgumentParser:
"""Build and return the argument parser for this script."""
"""Build and return the argument parser for this script.

Returns:
The configured command-line argument parser.
"""
parser = argparse.ArgumentParser(
prog="clang_tidy_fixes_to_problems.py",
description=(
Expand Down
3 changes: 1 addition & 2 deletions scripts/codeql_reset_dismissed_alerts.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,8 +175,7 @@ def _paginate_alerts(owner: str, repo: str) -> Iterator[dict]:
raise GitHubAPIError("Unexpected response when listing alerts (expected a JSON list).")
if not result:
return
for alert in result:
yield alert
yield from result
page += 1


Expand Down
30 changes: 25 additions & 5 deletions scripts/fix_header_guards.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@


def normalize_guard_component(component: str) -> str:
"""Convert a path component to a non-reserved macro identifier token."""
"""Convert a path component to a non-reserved macro identifier token.

Returns:
The normalized preprocessor identifier component.
"""
normalized = re.sub(r"[^A-Z0-9_]", "_", component.upper())
normalized = re.sub(r"_+", "_", normalized)
if not normalized or not normalized[0].isalpha():
Expand All @@ -27,7 +31,11 @@ def normalize_guard_component(component: str) -> str:


def compute_expected_guard(file_path: Path, root: Path) -> str:
"""Compute expected guard macro: X_Y_HEADER_EXT."""
"""Compute expected guard macro: X_Y_HEADER_EXT.

Returns:
The expected header guard macro name.
"""
rel = file_path.relative_to(root)
# Include directory components only; a top-level header has none.
parts = [normalize_guard_component(part) for part in rel.parts[:-1]]
Expand All @@ -36,14 +44,22 @@ def compute_expected_guard(file_path: Path, root: Path) -> str:


def leading_comment_lines(content: str) -> int:
"""Count lines before the first token, ignoring whitespace and leading comments."""
"""Count lines before the first token, ignoring whitespace and leading comments.

Returns:
The number of lines before the first non-comment token.
"""
prefix = re.match(r"(?:\s+|//[^\n]*(?:\n|$)|/\*.*?\*/)*", content, re.DOTALL)
assert prefix is not None
return prefix.group().count("\n")


def check_header_guard(file_path: Path, root: Path) -> tuple[bool, str | None]:
"""Check if header guard is correct. Returns (is_valid, expected_guard)."""
"""Check if header guard is correct.

Returns:
A pair containing validity and the expected guard when invalid.
"""
if file_path.name.endswith(LINKDEF_SUFFIXES):
return True, None

Expand Down Expand Up @@ -82,7 +98,11 @@ def check_header_guard(file_path: Path, root: Path) -> tuple[bool, str | None]:


def fix_header_guard(file_path: Path, root: Path) -> bool:
"""Fix header guard. Returns True if modified."""
"""Fix header guard.

Returns:
Whether the file was modified.
"""
if file_path.name.endswith(LINKDEF_SUFFIXES):
return False

Expand Down
9 changes: 8 additions & 1 deletion scripts/sarif-alerts.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ def _collect_sarif_paths(inputs: list[Path]) -> list[Path]:
"""Expand any directory entries to the .sarif files they contain.

Files are returned in a stable, sorted order so output is reproducible.

Returns:
The input files and recursively discovered SARIF files.
"""
paths: list[Path] = []
for p in inputs:
Expand Down Expand Up @@ -98,7 +101,11 @@ def _process_sarif(


def _positive_int(value: str) -> int:
"""Argparse type for --max-message: reject values less than 1."""
"""Argparse type for --max-message: reject values less than 1.

Returns:
The validated positive integer.
"""
n = int(value)
if n < 1:
raise argparse.ArgumentTypeError(f"N must be at least 1, got {n}")
Expand Down
8 changes: 4 additions & 4 deletions scripts/test/test_check_codeql_alerts.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
import pytest

# sys.path is set up by scripts/test/conftest.py.
import check_codeql_alerts as M # noqa: E402
import check_codeql_alerts as M

# ---------------------------------------------------------------------------
# Helpers / fixtures
Expand Down Expand Up @@ -1025,7 +1025,7 @@ class TestCompareAlertsViaApi:
def _mock_paginate(self, pages: dict[str | None, list[dict]]) -> MagicMock:
"""Return a side_effect callable that dispatches on the `ref` kwarg."""

def _paginate(owner: str, repo: str, *, state: str = "open", ref: str | None = None): # noqa: ANN202
def _paginate(owner: str, repo: str, *, state: str = "open", ref: str | None = None):
yield from pages.get(ref, [])

return MagicMock(side_effect=_paginate)
Expand Down Expand Up @@ -1363,7 +1363,7 @@ def test_blank_lines_preserved_between_sections(self) -> None:
lines = body.splitlines()
h2_indices = [i for i, ln in enumerate(lines) if ln.startswith("##")]
assert len(h2_indices) >= 2
for a, b in zip(h2_indices, h2_indices[1:]): # noqa: B905
for a, b in zip(h2_indices, h2_indices[1:], strict=False):
assert b - a > 1, "H2 headings are directly adjacent (no blank line)"

def test_code_scanning_link_present(self, monkeypatch: pytest.MonkeyPatch) -> None:
Expand Down Expand Up @@ -1867,7 +1867,7 @@ def test_api_mode_pr_ref_produces_filtered_url(
sarif_dir = self._empty_sarif_dir(tmp_path)
pr_alert = _make_api_alert(number=1, severity="error", analysis_key="ak:1")

def _paginate(owner: str, repo: str, *, state: str = "open", ref: str | None = None): # noqa: ANN202
def _paginate(owner: str, repo: str, *, state: str = "open", ref: str | None = None):
if ref == "refs/pull/104/merge":
yield pr_alert
# main, base, and prev-commit refs return nothing
Expand Down
2 changes: 1 addition & 1 deletion scripts/test/test_clang_tidy_check_summary.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import pytest

# sys.path is set up by scripts/test/conftest.py.
import clang_tidy_check_summary as M # noqa: E402
import clang_tidy_check_summary as M

# ---------------------------------------------------------------------------
# Helpers
Expand Down
Loading
Loading