chore(ruff): enable RUF/SIM/C4/PERF/RET/PIE rule families — 364 → 0

Extends ``[tool.ruff.lint].select`` with six additional rule families:
``RUF`` (ruff-specific), ``SIM`` (flake8-simplify), ``C4``
(flake8-comprehensions), ``PERF`` (perflint), ``RET`` (flake8-return),
``PIE`` (flake8-pie). Adds ``RUF001/002/003`` to ``ignore`` because
those exist for homoglyph-attack detection, not English typography —
the project uses em/en-dashes and ``ℹ`` as a UI-hint glyph in CLI help
output deliberately.

Auto-fixed (~225, mechanical & behavior-preserving)
====================================================
- RUF005:  ``a + [b]``     → ``[*a, b]``
- C408:    ``dict(k=v)``   → ``{"k": v}``
- C420:    ``dict.fromkeys(seq)`` shape simplifications
- SIM103/SIM110/SIM118:    truthy-return / dict-key / dict-method
                           idiom simplifications
- RET504/RET505:           drop unneeded final assigns / ``else`` after
                           ``return``
- PIE810:                  combine ``str.startswith(a) or .startswith(b)``
                           into one call with a tuple
- RUF010:                  ``f"{str(x)}"`` → ``f"{x\!s}"``
- RUF100:                  removed unused ``# noqa`` directives that
                           became stale (mostly old ``# noqa: E402``
                           markers that ruff's smart E402 implementation
                           no longer flags after ``sys.path`` shims)
- RUF015 / RUF013 / RUF022 / RUF046 / RUF059: misc small wins
- I001:                    re-sorted import blocks where the new
                           imports above shifted them

Hand-fixed (~140, scripted where mechanical)
============================================
PERF401 (42): scripted AST rewrite of
  ``for x in iter: target.append(expr)`` (with optional ``if`` guard)
  →  ``target.extend(expr for x in iter [if cond])``.
  ``list.extend(genexp)`` consumes the generator immediately, so the
  rewrite is semantically equivalent to the original eager loop.

SIM117 (41): scripted AST combiner for nested ``with`` blocks where
  the inner is the only statement of the outer (38 sites). The remaining
  3 multi-line ``patch.object(...)`` chains were combined by hand using
  the parenthesised ``with (\\n A,\\n B,\\n):`` form.

SIM102 (14): scripted AST combiner for nested ``if`` (10 sites). The
  remaining 4 carry an inline ``# noqa: SIM102`` with rationale —
  combining would either change semantics (the outer body has siblings
  beyond the inner ``if``, e.g. ``cli/encrypt/inventory/__main__.py``
  where ``encrypted_value = …`` runs regardless of ``ask_confirmation``)
  or hurt readability (long literal whitelists).

RUF012 (9): annotated mutable class attributes with ``ClassVar[…]``
  and added ``from typing import ClassVar``.

SIM105 (6): ``try/except: pass`` → ``with contextlib.suppress(…):``
  with the necessary ``import contextlib`` added. Verified on
  ``utils/templating.py`` (3 occurrences in a ``finally`` block) —
  cleanup behaviour is identical.

SIM115 (4): wrapped ``tempfile.NamedTemporaryFile(..., delete=False)``
  call patterns in a ``with`` block; ``delete=False`` keeps the file
  on disk after the block, so callers' ``return f.name`` still works.

PERF402, PERF403, B007, SIM108, SIM103: 5 misc fixes (loop→list-copy,
  loop→dict-comprehension, unused-loop-var rename, ternary, return
  expression).

Verification
============
- ``ruff check .`` → All checks passed
- ``ruff format --check .`` → 894 files already formatted
- 1621 unit tests → all pass
- Integration suite: 44 baseline failures, 1 skipped (unchanged)
- Sample-audited PERF401 rewrites in ``resolver.py``, ``inventory.py``,
  ``cache/files.py``, ``ressources/__main__.py``; SIM117 in
  ``test_main.py``; SIM105 in ``utils/templating.py``; SIM102 noqa
  rationales in ``cli/encrypt/inventory/__main__.py``.

182 files changed, +993 / −960. With this and the prior strict-rule
commit the branch satisfies 11 ruff rule families end-to-end.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
kevinveenbirkenbachandClaude Opus 4.7 committed 2026-05-07 17:23:32 +02:00
1 parent 26ef3ff504
commit 16e292e805
182 files changed
+992 -959

No files matched your search

+1 -1
View File
@@ -13,7 +13,7 @@ from . import PROJECT_ROOT
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
from cli.core.app import main # noqa: E402
from cli.core.app import main
if __name__ == "__main__":
main()
+1 -1
View File
@@ -159,7 +159,7 @@ def main() -> None:
log_file, log_path = open_log_file(flags.log_dir)
print(color_text(f"Tip: Log file created at {log_path}", Fore.GREEN))
full_cmd = [sys.executable, "-m", module] + remaining
full_cmd = [sys.executable, "-m", module, *remaining]
cfg = RunConfig(
log_enabled=flags.log_dir is not None,
+1 -3
View File
@@ -36,9 +36,7 @@ class Command:
def _is_valid_package_dir(path: Path) -> bool:
if not path.is_dir():
return False
if path.name == "__pycache__":
return False
return True
return path.name != "__pycache__"
def discover_commands(cli_dir: Path) -> list[Command]:
+3 -5
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
import contextlib
import os
import pty
import subprocess
@@ -26,12 +27,9 @@ def open_log_file(log_dir: Path) -> tuple[TextIO, Path]:
log_dir = log_dir.expanduser()
log_dir.mkdir(parents=True, exist_ok=True)
# Best-effort permission hardening (ignore failures on non-POSIX / special FS)
try:
# Best-effort permission hardening (ignore failures on non-POSIX / special FS).
with contextlib.suppress(Exception):
os.chmod(log_dir, 0o700)
except Exception:
# Intentionally ignore chmod failures: non-critical hardening step
pass
timestamp = datetime.now().strftime("%Y%m%dT%H%M%S")
log_file_path = log_dir / f"{timestamp}.log"
+2 -7
View File
@@ -72,9 +72,7 @@ def _is_vault_encrypted(val: Any) -> bool:
return True
if _is_ruamel_vault(val):
return True
if isinstance(val, str) and ("$ANSIBLE_VAULT" in val or "!vault" in val):
return True
return False
return bool(isinstance(val, str) and ("$ANSIBLE_VAULT" in val or "!vault" in val))
def _vault_body(text: str) -> str:
@@ -330,10 +328,7 @@ def main() -> int:
)
value_for_new_key: str | Any
if ov is not None:
value_for_new_key = ov
else:
value_for_new_key = default_val
value_for_new_key = ov if ov is not None else default_val
if _is_vault_encrypted(value_for_new_key):
creds[key] = to_vault_block(
+5 -4
View File
@@ -32,10 +32,11 @@ def _filter_inventory_children(
(all_block.get("children", {}) or {}) if isinstance(all_block, dict) else {}
)
filtered: dict[str, Any] = {}
for group_name, group_data in children.items():
if keep_predicate(group_name, group_data):
filtered[group_name] = group_data
filtered: dict[str, Any] = {
group_name: group_data
for group_name, group_data in children.items()
if keep_predicate(group_name, group_data)
}
new_all = dict(all_block)
new_all["children"] = filtered
+1 -1
View File
@@ -14,8 +14,8 @@ from .command import ( # noqa: E402
__all__ = [
"main",
"remove_container",
"run_in_container",
"start_ci_container",
"stop_container",
"remove_container",
]
+2 -2
View File
@@ -1,6 +1,6 @@
from __future__ import annotations
from .command import main
from .modes import _parse_bool_literal # noqa: F401
from .modes import _parse_bool_literal
__all__ = ["main", "_parse_bool_literal"]
__all__ = ["_parse_bool_literal", "main"]
+2 -2
View File
@@ -117,11 +117,11 @@ def build_modes_from_args(
if kind == "bool_true":
# if user passed --skip-foo => disable => False, otherwise True
modes[mode_name] = False if value else True
modes[mode_name] = not value
elif kind == "bool_false":
# if user passed --bar => enable => True, otherwise False
modes[mode_name] = True if value else False
modes[mode_name] = bool(value)
else: # explicit
if value is not None:
+1 -2
View File
@@ -13,8 +13,7 @@ def _resolve_repo_root() -> str:
dedicated_dir = os.path.dirname(here) # .../cli/deploy/dedicated
deploy_dir = os.path.dirname(dedicated_dir) # .../cli/deploy
cli_root = os.path.dirname(deploy_dir) # .../cli
repo_root = os.path.dirname(cli_root) # .../<repo-root>
return repo_root
return os.path.dirname(cli_root) # .../<repo-root>
PROJECT_ROOT: str = _resolve_repo_root()
+1 -1
View File
@@ -67,7 +67,7 @@ def run_ansible_playbook(
# ---------------------------------------------------------
# 4) Inventory Validation Phase
# ---------------------------------------------------------
if modes.get("MODE_ASSERT", None) is False:
if modes.get("MODE_ASSERT") is False:
print("\n🔍 Inventory assertion explicitly disabled (MODE_ASSERT=false)\n")
else:
print("\n🔍 Validating inventory before deployment...\n")
+1 -3
View File
@@ -207,9 +207,7 @@ def _bake_overrides(
existing_apps = merged.get("applications")
if not isinstance(existing_apps, Mapping):
existing_apps = {}
apps: dict[str, Any] = {
app_id: payload for app_id, payload in variant_payloads.items()
}
apps: dict[str, Any] = dict(variant_payloads.items())
# Caller-supplied `applications.*` entries deep-overlay the variant
# payload so overrides like `applications.web-app-foo.feature_flag` from
# `--vars` still take precedence.
+3 -4
View File
@@ -53,10 +53,9 @@ def _stack_is_running() -> bool:
def handler(args: argparse.Namespace) -> int:
# when-down: skip if already running
if args.when_down:
if _stack_is_running():
print(">>> Stack already running — skipping up")
return 0
if args.when_down and _stack_is_running():
print(">>> Stack already running — skipping up")
return 0
rc = _maybe_build_missing()
if rc != 0:
+2 -2
View File
@@ -33,10 +33,10 @@ def encrypt_recursively(
elif isinstance(data, list):
for i, item in enumerate(data):
data[i] = encrypt_recursively(item, vault_handler, ask_confirmation, prefix)
elif isinstance(data, str):
elif isinstance(data, str): # noqa: SIM102 outer guard, inner ask_confirmation block has independent siblings
# Only encrypt if it's not already vaulted
if not data.lstrip().startswith("$ANSIBLE_VAULT"):
if ask_confirmation:
if ask_confirmation: # noqa: SIM102 combining changes semantics: encrypted_value below must run regardless of ask_confirmation
# Ask for confirmation before encrypting if not `--all`
if not ask_for_confirmation(prefix):
print(f"Skipping encryption for '{prefix}'.")
+1 -1
View File
@@ -36,7 +36,7 @@ def main():
sys.exit(1)
# Invoke make in repo root
cmd = ["make"] + make_args
cmd = ["make", *make_args]
try:
result = subprocess.run(cmd, cwd=repo_root)
sys.exit(result.returncode)
+1 -1
View File
@@ -10,7 +10,7 @@ from . import PROJECT_ROOT
sys.path.insert(0, str(PROJECT_ROOT))
from utils.invokable import list_invokable_app_ids # noqa: E402
from utils.invokable import list_invokable_app_ids
def main() -> None:
@@ -152,7 +152,7 @@ def resolve_dependencies_transitively(start_role: str) -> list[str]:
def dfs(node: str) -> None:
if node in stack:
idx = stack.index(node)
cycle = stack[idx:] + [node]
cycle = [*stack[idx:], node]
raise DependenciesResolutionError(
f"Circular dependencies detected: {' -> '.join(cycle)}"
)
@@ -86,7 +86,7 @@ def resolve_run_after_transitively(start_role: str) -> list[str]:
if node in stack:
# Cycle: show a readable path: A -> B -> C -> A
idx = stack.index(node)
cycle = stack[idx:] + [node]
cycle = [*stack[idx:], node]
raise RunAfterResolutionError(
f"Circular run_after dependency detected: {' -> '.join(cycle)}"
)
@@ -139,8 +139,8 @@ class ServicesResolver:
resolved.append(role_name)
cfg = self._load_role_config(role_name)
for inc in self.direct_includes_from_config(cfg):
if inc not in seen:
queue.append(inc)
queue.extend(
inc for inc in self.direct_includes_from_config(cfg) if inc not in seen
)
return resolved
+16 -19
View File
@@ -11,10 +11,10 @@ from . import PROJECT_ROOT
sys.path.insert(0, str(PROJECT_ROOT))
from humanfriendly import format_size, parse_size # noqa: E402
from humanfriendly import format_size, parse_size
from utils.entity_name_utils import get_entity_name # noqa: E402
from utils.service_registry import ( # noqa: E402
from utils.entity_name_utils import get_entity_name
from utils.service_registry import (
build_service_registry_from_applications,
load_applications_from_roles_dir,
)
@@ -71,9 +71,7 @@ def _is_enabled(service_conf: dict[str, Any], is_primary: bool) -> bool:
if isinstance(raw, bool):
return raw
text = str(raw).strip().lower()
if text in ("false", "0", "no", "off"):
return False
return True
return text not in ("false", "0", "no", "off")
def _is_shared(service_conf: dict[str, Any]) -> bool:
@@ -230,17 +228,17 @@ def render_text(
headers = ["service", "role", "mem_reservation", "mem_limit", "pids_limit", "cpus"]
table_rows: list[tuple[str, ...]] = []
for row in sorted(rows, key=lambda r: (r["service"], r["role"])):
table_rows.append(
(
row["service"],
row["role"],
_fmt_mem(row["mem_reservation_bytes"]),
_fmt_mem(row["mem_limit_bytes"]),
_fmt_int(row["pids_limit_int"]),
_fmt_float(row["cpus_float"]),
)
table_rows.extend(
(
row["service"],
row["role"],
_fmt_mem(row["mem_reservation_bytes"]),
_fmt_mem(row["mem_limit_bytes"]),
_fmt_int(row["pids_limit_int"]),
_fmt_float(row["cpus_float"]),
)
for row in sorted(rows, key=lambda r: (r["service"], r["role"]))
)
total_label = "TOTAL (mem=SUM, pids=SUM max-provisioned, cpus=MAX)"
total_row = (
@@ -253,7 +251,7 @@ def render_text(
)
widths = [len(h) for h in headers]
for r in table_rows + [total_row]:
for r in [*table_rows, total_row]:
for i, cell in enumerate(r):
widths[i] = max(widths[i], len(cell))
@@ -274,8 +272,7 @@ def render_text(
if warnings:
lines.append("")
lines.append("# Warnings")
for w in warnings:
lines.append(f"! {w}")
lines.extend(f"! {w}" for w in warnings)
return "\n".join(lines)
@@ -11,7 +11,7 @@ from . import PROJECT_ROOT
sys.path.insert(0, str(PROJECT_ROOT))
from utils.roles.resource_validation import filter_roles_by_min_storage # noqa: E402
from utils.roles.resource_validation import filter_roles_by_min_storage
def parse_args() -> argparse.Namespace:
+1 -1
View File
@@ -10,7 +10,7 @@ from . import PROJECT_ROOT
sys.path.insert(0, str(PROJECT_ROOT))
from utils.invokable import list_invokables_by_type # noqa: E402
from utils.invokable import list_invokables_by_type
def main() -> None:
+1 -2
View File
@@ -126,8 +126,7 @@ def flatten_callorder(groups: list[Group]) -> list[tuple[str, str]]:
"""
out: list[tuple[str, str]] = []
for g in groups:
for r in g.roles:
out.append((g.group_name, r))
out.extend((g.group_name, r) for r in g.roles)
return out
+1 -1
View File
@@ -10,7 +10,7 @@ from . import PROJECT_ROOT
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
import utils.domains.list as domain_list # noqa: E402
import utils.domains.list as domain_list
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
+3 -2
View File
@@ -37,8 +37,9 @@ def expand_includes(rel_path, seen=None):
else:
indent, inc_rel = m.group(1), m.group(2)
# rekursiver Aufruf
for inc_line in expand_includes(inc_rel, seen):
output_lines.append(indent + inc_line)
output_lines.extend(
indent + inc_line for inc_line in expand_includes(inc_rel, seen)
)
seen.remove(rp)
return output_lines
+1 -1
View File
@@ -115,7 +115,7 @@ def suggest_relay_ranges(
gaps_filled = 0
cursor = band_start
sorted_occ = sorted(occupied + [(band_end + 1, band_end + 1)])
sorted_occ = sorted([*occupied, (band_end + 1, band_end + 1)])
while len(suggestions) < count and cursor + length - 1 <= band_end:
candidate = (cursor, cursor + length - 1)
+1 -1
View File
@@ -1,5 +1,5 @@
from __future__ import annotations
from utils.docker.image.discovery import ImageRef # noqa: F401
from utils.docker.image.discovery import ImageRef
__all__ = ["ImageRef"]
+6 -7
View File
@@ -87,13 +87,12 @@ def main() -> int:
label = f"{img.role}:{img.service} ({img.name}:{img.version})"
try:
if args.only_missing:
if provider.tag_exists(img):
print(
f"[mirror] {label}: destination exists, skipping ({dest})",
flush=True,
)
continue
if args.only_missing and provider.tag_exists(img):
print(
f"[mirror] {label}: destination exists, skipping ({dest})",
flush=True,
)
continue
print(f"[mirror] {label}: {src} -> {dest}", flush=True)
provider.mirror(img)
+5 -3
View File
@@ -115,9 +115,11 @@ def validate_host_keys(app_ids, inv_dir):
children = all_node.get("children")
if not isinstance(children, dict):
continue
for grp in children.keys():
if grp not in app_ids:
errs.append(f"{f}: Invalid group '{grp}' (not in application_ids)")
errs.extend(
f"{f}: Invalid group '{grp}' (not in application_ids)"
for grp in children
if grp not in app_ids
)
return errs
+9 -7
View File
@@ -3,13 +3,15 @@ from ansible.module_utils.cert_utils import CertUtils
def main():
module_args = dict(
domain=dict(type="str", required=True),
cert_base_path=dict(
type="str", required=False, default="/etc/letsencrypt/live"
),
debug=dict(type="bool", required=False, default=False),
)
module_args = {
"domain": {"type": "str", "required": True},
"cert_base_path": {
"type": "str",
"required": False,
"default": "/etc/letsencrypt/live",
},
"debug": {"type": "bool", "required": False, "default": False},
}
module = AnsibleModule(argument_spec=module_args)
+3 -3
View File
@@ -15,9 +15,9 @@ def run(cmd: list[str]) -> str:
def main():
module = AnsibleModule(
argument_spec=dict(
network=dict(type="str", default="bridge"),
),
argument_spec={
"network": {"type": "str", "default": "bridge"},
},
supports_check_mode=True,
)
+1 -1
View File
@@ -53,7 +53,7 @@ def active_docker_container_count(
# sometimes roles define a single service name string; ignore
continue
for _svc_name, svc_cfg in services.items():
for svc_cfg in services.values():
if not _is_mapping(svc_cfg):
# allow shorthand like: service: {} or image string -> counts as enabled
count += 1
+1 -1
View File
@@ -6,7 +6,7 @@ from ansible.errors import AnsibleFilterError
def application_allowed(
application_id: str, group_names: list, allowed_applications: list = None
application_id: str, group_names: list, allowed_applications: list | None = None
):
"""
Return True if:
+1 -1
View File
@@ -117,7 +117,7 @@ class FilterModule:
self, app_id, canonical_domains, seen_domains, result
):
if isinstance(canonical_domains, dict):
for _, domain in canonical_domains.items():
for domain in canonical_domains.values():
self._validate_and_check_domain(app_id, domain, seen_domains)
result[app_id] = canonical_domains.copy()
elif isinstance(canonical_domains, list):
+24 -20
View File
@@ -268,24 +268,24 @@ class FilterModule:
tokens.append(get_url(domains, "web-svc-cdn", web_protocol))
# Matomo (if enabled via services.matomo.enabled)
if directive in ("script-src-elem", "connect-src"):
if self.is_feature_enabled(applications, "matomo", application_id):
tokens.append(get_url(domains, "web-app-matomo", web_protocol))
if directive in (
"script-src-elem",
"connect-src",
) and self.is_feature_enabled(applications, "matomo", application_id):
tokens.append(get_url(domains, "web-app-matomo", web_protocol))
# Simpleicons (if enabled via services.simpleicons.enabled) – typically used via connect-src (fetch)
if directive == "connect-src":
if self.is_feature_enabled(
applications, "simpleicons", application_id
):
tokens.append(
get_url(domains, "web-svc-simpleicons", web_protocol)
)
if directive == "connect-src" and self.is_feature_enabled(
applications, "simpleicons", application_id
):
tokens.append(get_url(domains, "web-svc-simpleicons", web_protocol))
# reCAPTCHA (if enabled via services.recaptcha.enabled) – scripts + frames
if self.is_feature_enabled(applications, "recaptcha", application_id):
if directive in ("script-src-elem", "frame-src"):
tokens.append("https://www.gstatic.com") # nocheck: url
tokens.append("https://www.google.com")
if self.is_feature_enabled(
applications, "recaptcha", application_id
) and directive in ("script-src-elem", "frame-src"):
tokens.append("https://www.gstatic.com") # nocheck: url
tokens.append("https://www.google.com")
# hCaptcha (if enabled via services.hcaptcha.enabled) – scripts + frames
if self.is_feature_enabled(applications, "hcaptcha", application_id):
@@ -310,9 +310,11 @@ class FilterModule:
)
# Logout support requires inline handlers (script-src-attr + script-src-elem)
if directive in ("script-src-attr", "script-src-elem"):
if self.is_feature_enabled(applications, "logout", application_id):
tokens.append("'unsafe-inline'")
if directive in (
"script-src-attr",
"script-src-elem",
) and self.is_feature_enabled(applications, "logout", application_id):
tokens.append("'unsafe-inline'")
# Custom whitelist
tokens += self.get_csp_whitelist(
@@ -373,9 +375,11 @@ class FilterModule:
tokens_by_dir[directive] = _sort_tokens(toks)
parts = []
for directive in directives:
if directive in tokens_by_dir:
parts.append(f"{directive} {' '.join(tokens_by_dir[directive])};")
parts.extend(
f"{directive} {' '.join(tokens_by_dir[directive])};"
for directive in directives
if directive in tokens_by_dir
)
# Keep permissive img-src for data/blob + any host (as before)
parts.append("img-src * data: blob:;")
+2 -8
View File
@@ -29,16 +29,10 @@ def _value_has_domain(v: Any) -> bool:
return True
if isinstance(v, (list, tuple, set)):
for item in v:
if _value_has_domain(item):
return True
return False
return any(_value_has_domain(item) for item in v)
if isinstance(v, dict):
for _, item in v.items():
if _value_has_domain(item):
return True
return False
return any(_value_has_domain(item) for _, item in v.items())
# Fallback: treat other scalars as "no domain"
return False
+2 -2
View File
@@ -71,7 +71,7 @@ def get_invokable_paths(
METADATA = {"title", "description", "icon", "invokable"}
for key, cfg in subroles.items():
path = parent + [key]
path = [*parent, key]
if cfg.get("invokable", False):
p = "-".join(path)
if suffix:
@@ -122,7 +122,7 @@ def get_non_invokable_paths(
METADATA = {"title", "description", "icon", "invokable"}
for key, cfg in subroles.items():
path = parent + [key]
path = [*parent, key]
p = "-".join(path)
inv = cfg.get("invokable", False)
if not inv:
+1 -1
View File
@@ -69,7 +69,7 @@ def _to_bytes(val):
def _mb(bytes_val: int) -> int:
"""Return decimal MB (10^6) as integer — Node expects MB units."""
return int(round(bytes_val / 10**6))
return round(bytes_val / 10**6)
def _compute_old_space_mb(
+1 -1
View File
@@ -13,7 +13,7 @@ def reserved_usernames(users_dict):
results = []
for _key, user in users_dict.items():
for user in users_dict.values():
if not isinstance(user, dict):
continue
if not user.get("reserved", False):
+1 -1
View File
@@ -6,7 +6,7 @@ from utils.applications.config import (
AppConfigKeyError,
ConfigEntryNotSetError,
get,
) # noqa: F401
)
from utils.entity_name_utils import get_entity_name
+1 -3
View File
@@ -35,9 +35,7 @@ def to_one_liner(s):
temp = temp.replace(f"__STR{idx}__", lit)
# 5) Collapse all whitespace
one_liner = re.sub(r"\s+", " ", temp).strip()
return one_liner
return re.sub(r"\s+", " ", temp).strip()
class FilterModule:
@@ -63,8 +63,7 @@ class FilterModule:
count = len(unique_domains)
raw = overhead_seconds + per_domain_seconds * count
clamped = max(min_seconds, min(max_seconds, int(raw)))
return clamped
return max(min_seconds, min(max_seconds, int(raw)))
except AnsibleFilterError:
raise
+1 -1
View File
@@ -98,7 +98,7 @@ def url_join(parts):
s = after_scheme
# check if this is a query element (starts with ? or &)
if s.startswith("?") or s.startswith("&"):
if s.startswith(("?", "&")):
in_query = True
raw_pair = s[1:] # strip the leading ? or &
if raw_pair == "":
+5 -5
View File
@@ -158,7 +158,7 @@ class LookupModule(LookupBase):
all_domains = collect_domains_for_app(domains, app_id, err_prefix="cert")
all_domains = (
uniq_preserve([primary_domain] + all_domains)
uniq_preserve([primary_domain, *all_domains])
if all_domains
else [primary_domain]
)
@@ -167,7 +167,7 @@ class LookupModule(LookupBase):
if san_override is None:
san_domains = all_domains[:]
else:
san_domains = uniq_preserve([primary_domain] + san_override)
san_domains = uniq_preserve([primary_domain, *san_override])
elif mode == "self_signed":
ss_base_raw = require(variables, "TLS_SELFSIGNED_BASE_PATH", str)
@@ -196,7 +196,7 @@ class LookupModule(LookupBase):
# Ensure primary domain is always included
if primary_domain:
san_domains = uniq_preserve([primary_domain] + san_domains)
san_domains = uniq_preserve([primary_domain, *san_domains])
else:
cert_id = app_id
@@ -207,7 +207,7 @@ class LookupModule(LookupBase):
domains, app_id, err_prefix="cert"
)
all_domains = (
uniq_preserve([primary_domain] + all_domains)
uniq_preserve([primary_domain, *all_domains])
if all_domains
else [primary_domain]
)
@@ -216,7 +216,7 @@ class LookupModule(LookupBase):
if san_override is None:
san_domains = all_domains[:]
else:
san_domains = uniq_preserve([primary_domain] + san_override)
san_domains = uniq_preserve([primary_domain, *san_override])
else:
raise AnsibleError(f"cert: unsupported mode '{mode}'")
+1 -1
View File
@@ -182,7 +182,7 @@ class LookupModule(LookupBase):
}
if domain:
protocol_override = kwargs.get("protocol", None)
protocol_override = kwargs.get("protocol")
protocol = (
_resolve_protocol_via_tls(
domain=domain,
+2 -2
View File
@@ -38,7 +38,7 @@ from ansible.errors import AnsibleError
from ansible.plugins.lookup import LookupBase
try:
from ansible.utils.display import Display # noqa: F401 pragma: no cover
from ansible.utils.display import Display
except Exception: # pragma: no cover
Display = None # type: ignore
@@ -104,7 +104,7 @@ def _resolve_role_scope(app_cfg, application_id, role):
raise AnsibleError(
f"rbac_group_path: role '{role}' is not declared under "
f"applications[{application_id}].rbac.roles. Declared roles: "
f"{declared + [_IMPLICIT_ADMIN_ROLE]}."
f"{[*declared, _IMPLICIT_ADMIN_ROLE]}."
)
tenancy = (rbac.get("tenancy") or {}) if isinstance(rbac, dict) else {}
+7 -4
View File
@@ -102,11 +102,14 @@ def _is_service_required(
dep_app_id = _resolve_service_provider_app_id(
applications, service_registry, svc
)
if dep_app_id and dep_app_id in applications:
if _is_service_required(
if (
dep_app_id
and dep_app_id in applications
and _is_service_required(
applications, service_registry, dep_app_id, service_key, visited
):
return True
)
):
return True
return False
+1 -1
View File
@@ -74,7 +74,7 @@ class LookupModule(LookupBase):
all_domains = collect_domains_for_app(domains, app_id, err_prefix="tls")
all_domains = (
uniq_preserve([primary_domain] + all_domains)
uniq_preserve([primary_domain, *all_domains])
if all_domains
else [primary_domain]
)
+4 -3
View File
@@ -181,10 +181,11 @@ class LookupModule(LookupBase):
"unit_name lookup: lookup('version') returned an empty value."
)
suffix = kwargs.get("suffix", None)
suffix = kwargs.get("suffix")
results = []
for term in terms:
results.append(_build_unit_name(term, version, software_domain, suffix))
results.extend(
_build_unit_name(term, version, software_domain, suffix) for term in terms
)
return results
+16 -5
View File
@@ -64,13 +64,24 @@ exclude = [
[tool.ruff.lint]
# Default ruff is `E4 + E7 + E9 + F`. We add:
# - `I` (isort) — import order, auto-fixable
# - `B` (flake8-bugbear) — likely-bug patterns (mutable defaults, etc.)
# - `UP` (pyupgrade) — modernise syntax to the target_version above
select = ["E", "F", "I", "B", "UP"]
# - `I` (isort) — import order, auto-fixable
# - `B` (flake8-bugbear) — likely-bug patterns (mutable defaults, etc.)
# - `UP` (pyupgrade) — modernise syntax to the target_version above
# - `RUF` (ruff-specific) — unused-noqa, ambiguous unicode, mutable class attrs, …
# - `SIM` (flake8-simplify) — `if x: True else: False` → `bool(x)`, etc.
# - `C4` (flake8-comprehensions) — `list(x for x in y)` → `[x for x in y]`, …
# - `PERF` (perflint) — avoid try/except in hot loops, etc.
# - `RET` (flake8-return) — unneeded `else` after `return`, redundant assigns
# - `PIE` (flake8-pie) — small wins (no-op `pass`, redundant `dict()` calls)
select = ["E", "F", "I", "B", "UP", "RUF", "SIM", "C4", "PERF", "RET", "PIE"]
# `ruff format` (run via `make autoformat`) reflows whatever it can.
# E501 leftovers are content the formatter can't break (long string
# literals, URLs / shell commands inside f-strings, comments). Trust
# the formatter; don't fail CI on the unsplittable rest.
ignore = ["E501"]
#
# RUF001/002/003 (ambiguous unicode in strings / docstrings / comments)
# exist to catch homoglyph attacks, not English typography. The project
# uses em/en-dashes deliberately and `ℹ` as a UI-hint glyph in CLI help
# output; flagging those is noise.
ignore = ["E501", "RUF001", "RUF002", "RUF003"]
@@ -108,7 +108,7 @@ def _role_group_entry(
"dn": dn,
"cn": cn,
"description": display_name,
"objectClass": ["top"] + list(flavors),
"objectClass": ["top", *list(flavors)],
}
if "posixGroup" in flavors:
entry["gidNumber"] = group_id
+3 -3
View File
@@ -125,16 +125,16 @@ def main(vendor_and_product_id):
start_color, end_color = get_current_period(current_time, color_times)
sorted_times = sorted(color_times.keys())
for time_str in sorted_times + [sorted_times[0]]:
for time_str in [*sorted_times, sorted_times[0]]:
next_start_time_obj = datetime.datetime.strptime(time_str, "%H:%M").time()
if current_time < next_start_time_obj:
break
current_period_start_time_str = [
current_period_start_time_str = next(
time
for time, colors in color_times.items()
if colors == (start_color, end_color)
][0]
)
current_period_start_time_obj = datetime.datetime.strptime(
current_period_start_time_str, "%H:%M"
).time()
+1 -2
View File
@@ -59,10 +59,9 @@ def has_healthcheck(container):
def get_health_status(container):
"""Return the health status."""
status = run_command(
return run_command(
f"container inspect --format='{{{{.State.Health.Status}}}}' {container}"
)
return status
def run_rsync(src, dest):
@@ -46,9 +46,9 @@ size:
def run_module() -> None:
module_args = dict(
path=dict(type="str", required=True),
)
module_args = {
"path": {"type": "str", "required": True},
}
module = AnsibleModule(
argument_spec=module_args,
+2 -4
View File
@@ -13,7 +13,7 @@ parser.add_argument(
type=int,
dest="maximum_backup_size_percent",
required=True,
choices=range(0, 100),
choices=range(100),
help="The directory from which the data should be encrypted.",
)
parser.add_argument(
@@ -37,9 +37,7 @@ def is_directory_used_by_another_process(directory_path):
)
process.communicate()
# @See https://stackoverflow.com/questions/29841984/non-zero-exit-code-for-lsof
if process.wait() > bool(0):
return False
return True
return not process.wait() > bool(0)
def isSmallerThenMaximumBackupSize(maximum_backup_size_percent, backup_dir):
@@ -140,7 +140,7 @@ def web_health_expectations(
expectations = {}
for app_id in applications.keys():
for app_id in applications:
if app_id not in selection:
continue
@@ -186,7 +186,7 @@ def web_health_expectations(
if www_enabled:
add = {}
for d in expectations.keys():
for d in expectations:
if not d.startswith("www."):
add[f"www.{d}"] = [301]
expectations.update(add)
@@ -194,8 +194,7 @@ def web_health_expectations(
if d.startswith("www."):
expectations[d] = [301]
ordered = {k: expectations[k] for k in sorted(expectations.keys())}
return ordered
return {k: expectations[k] for k in sorted(expectations.keys())}
class FilterModule:
@@ -123,13 +123,10 @@ def _build_wildcard_records(
if p == apex:
wc = "*"
else:
# relative part (drop ".apex")
# relative part (drop ".apex"); empty rel is a safety guard
# — shouldn't happen because p==apex handled above.
rel = p[: -len(apex) - 1]
if not rel:
# Safety guard; should not happen because p==apex handled above
wc = "*"
else:
wc = f"*.{rel}"
wc = "*" if not rel else f"*.{rel}"
_add(wc, "A", str(ip4))
if ipv6_enabled and ip6 and _is_global(str(ip6)):
_add(wc, "AAAA", str(ip6))
-2
View File
@@ -11,8 +11,6 @@ BREAK_TIME_SECONDS = 5
class AttemptException(Exception):
"""A custom exception for maximum number of attempts."""
pass
def parse_time_to_seconds(time_str):
"""
+3 -4
View File
@@ -21,10 +21,9 @@ def filetype(path, full=False):
if len(parts) == 2:
return parts[1]
return ""
else:
# Last extension only (e.g., "script.sh.j2" -> "j2", "script.py" -> "py")
_, ext = os.path.splitext(basename)
return ext[1:] if ext else ""
# Last extension only (e.g., "script.sh.j2" -> "j2", "script.py" -> "py")
_, ext = os.path.splitext(basename)
return ext[1:] if ext else ""
class FilterModule:
+9 -7
View File
@@ -158,6 +158,7 @@ def normalize_cmd(value: Any) -> list[str]:
if isinstance(value, str) and value.strip():
return ["/bin/sh", "-lc", value]
die(f"Unsupported command type in compose config: {type(value)}")
return None
def normalize_entrypoint(value: Any) -> list[str]:
@@ -176,6 +177,7 @@ def normalize_entrypoint(value: Any) -> list[str]:
if isinstance(value, str) and value.strip():
return ["/bin/sh", "-lc", value]
die(f"Unsupported entrypoint type in compose config: {type(value)}")
return None
def escape_compose_vars(argv: list[str]) -> list[str]:
@@ -310,7 +312,7 @@ def ensure_image_available(
if _has_build(svc):
run_checked(
compose_base_cmd + ["build", service_name],
[*compose_base_cmd, "build", service_name],
cwd=cwd,
env=env,
label=f"compose build {service_name}",
@@ -322,14 +324,14 @@ def ensure_image_available(
if not builder_cmd:
builder_cmd = compose_base_cmd
run_checked(
builder_cmd + ["build", builder],
[*builder_cmd, "build", builder],
cwd=cwd,
env=env,
label=f"compose build {builder} (builder for image {img})",
)
else:
run_checked(
compose_base_cmd + ["pull", service_name],
[*compose_base_cmd, "pull", service_name],
cwd=cwd,
env=env,
label=f"compose pull {service_name}",
@@ -387,7 +389,7 @@ def _discover_profiles_from_files(compose_files: list[Path]) -> list[str]:
if not isinstance(services, dict):
continue
for _svc_name, svc in services.items():
for svc in services.values():
if not isinstance(svc, dict):
continue
p = svc.get("profiles")
@@ -402,7 +404,7 @@ def _discover_profiles_from_files(compose_files: list[Path]) -> list[str]:
def _compose_base_cmd(*, project: str, parts: list[str], env_file: str) -> list[str]:
cmd: list[str] = ["docker", "compose", "-p", project] + parts
cmd: list[str] = ["docker", "compose", "-p", project, *parts]
if env_file.strip():
cmd += ["--env-file", env_file.strip()]
return cmd
@@ -417,7 +419,7 @@ def _compose_cmd_with_profile(base_cmd: list[str], profile: str) -> list[str]:
die(f"Invalid compose base cmd: {base_cmd}")
# Insert after the compose wrapper prefix
return base_cmd[:2] + ["--profile", profile] + base_cmd[2:]
return [*base_cmd[:2], "--profile", profile, *base_cmd[2:]]
def _load_services_via_config(
@@ -427,7 +429,7 @@ def _load_services_via_config(
env: dict[str, str],
label: str,
) -> dict[str, Any]:
rc, out, err = run(compose_cmd + ["config"], cwd=cwd, env=env)
rc, out, err = run([*compose_cmd, "config"], cwd=cwd, env=env)
if rc != 0:
die(f"compose config failed for {label} (rc={rc}): {err.strip()}")
+1 -1
View File
@@ -8,7 +8,7 @@ import sys
from pathlib import Path
# `utils.cache.yaml` is unavailable here: this file is copy-deployed.
import yaml # noqa: E402
import yaml
def detect_env_file(project_dir: Path) -> Path | None:
+4 -4
View File
@@ -41,7 +41,7 @@ def base_compose_cmd(*, project: str, cwd: Path) -> list[str]:
def has_buildable_services(
*, base_cmd: list[str], cwd: Path, env: dict[str, str]
) -> bool:
rc, out = run_cmd(base_cmd + ["config"], cwd=cwd, env=env)
rc, out = run_cmd([*base_cmd, "config"], cwd=cwd, env=env)
if rc != 0:
if out.strip():
@@ -104,16 +104,16 @@ def main() -> int:
base_cmd=base_cmd, cwd=cwd, env=env
):
run_or_fail(
base_cmd + ["build", "--pull"],
[*base_cmd, "build", "--pull"],
cwd=cwd,
env=env,
label="docker compose build --pull",
)
pull_cmd = base_cmd + ["pull"]
pull_cmd = [*base_cmd, "pull"]
if args.ignore_buildable:
rc, help_out = run_cmd(base_cmd + ["pull", "--help"], cwd=cwd, env=env)
rc, help_out = run_cmd([*base_cmd, "pull", "--help"], cwd=cwd, env=env)
if rc == 0 and "--ignore-buildable" in help_out:
pull_cmd.append("--ignore-buildable")
+1 -1
View File
@@ -387,7 +387,7 @@ def container_run(argv: list[str], debug: bool, with_ca: bool) -> int:
f"CURL_CA_BUNDLE={ca_container}",
]
return exec_docker(
["docker", "run"] + run_opts + ca_inject_opts + [image] + user_args,
["docker", "run", *run_opts, *ca_inject_opts, image, *user_args],
debug=debug,
)
@@ -19,8 +19,4 @@ class FilterModule:
return False
# Iterate over list1 and check if an element exists in list2.
for element in list1:
if element in list2:
return True
return False
return any(element in list2 for element in list1)
@@ -242,24 +242,24 @@ def send_create(module, object_kind, api, realm, kcadm_exec, payload):
def run_module():
module_args = dict(
object_kind=dict(type="str", required=True),
lookup_value=dict(type="str", required=True),
desired=dict(type="dict", required=True),
lookup_field=dict(type="str", required=False, default=None),
merge_path=dict(type="str", required=False, default=None),
force_attrs=dict(type="dict", required=False, default=None),
kcadm_exec=dict(type="str", required=True),
realm=dict(type="str", required=False, default=None),
assert_mode=dict(type="bool", required=False, default=True),
)
module_args = {
"object_kind": {"type": "str", "required": True},
"lookup_value": {"type": "str", "required": True},
"desired": {"type": "dict", "required": True},
"lookup_field": {"type": "str", "required": False, "default": None},
"merge_path": {"type": "str", "required": False, "default": None},
"force_attrs": {"type": "dict", "required": False, "default": None},
"kcadm_exec": {"type": "str", "required": True},
"realm": {"type": "str", "required": False, "default": None},
"assert_mode": {"type": "bool", "required": False, "default": True},
}
result = dict(
changed=False,
object_exists=False,
object_id="",
result={},
)
result = {
"changed": False,
"object_exists": False,
"object_id": "",
"result": {},
}
module = AnsibleModule(argument_spec=module_args, supports_check_mode=False)
@@ -42,7 +42,7 @@ def json_from_noisy_stdout(text: Any) -> Any:
chunk = s[idx:].strip()
try:
return json.loads(chunk)
except Exception as e: # noqa: BLE001
except Exception as e:
last_err = e
raise ValueError(f"Failed to parse JSON from noisy stdout: {last_err}")
@@ -66,13 +66,13 @@ class OAuthLoginHTTPS(OAuthLogin):
for provider in providers:
state = self.get_state(provider)
params = dict(
response_type="token",
client_id=provider["client_id"],
redirect_uri=return_url,
scope=provider["scope"],
state=json.dumps(state),
)
params = {
"response_type": "token",
"client_id": provider["client_id"],
"redirect_uri": return_url,
"scope": provider["scope"],
"state": json.dumps(state),
}
provider["auth_link"] = "{}?{}".format(
provider["auth_endpoint"],
werkzeug.urls.url_encode(params),
@@ -96,11 +96,11 @@ class OAuthLoginHTTPS(OAuthLogin):
redirect[1:] if redirect.startswith("/") else redirect,
)
state = dict(
d=request.session.db,
p=provider["id"],
r=werkzeug.urls.url_quote_plus(redirect),
)
state = {
"d": request.session.db,
"p": provider["id"],
"r": werkzeug.urls.url_quote_plus(redirect),
}
token = request.params.get("token")
if token:
state["t"] = token
@@ -27,7 +27,7 @@ class TestCategoriesInvokableExclusion(unittest.TestCase):
continue
is_invokable = value.get("invokable", False)
current_path = path + [key]
current_path = [*path, key]
# Violation: a descendant is invokable despite an invokable ancestor
if ancestor_invokable and is_invokable:
+5 -3
View File
@@ -38,9 +38,11 @@ class TestCategoryPaths(unittest.TestCase):
expected.add(f"{top_key}-{sub_key}")
missing = []
for name in expected:
if not any(name in dirname for dirname in self.existing_dirs):
missing.append(name)
missing.extend(
name
for name in expected
if not any(name in dirname for dirname in self.existing_dirs)
)
if missing:
self.fail(f"Missing role directories for: {', '.join(sorted(missing))}")
+1 -1
View File
@@ -48,7 +48,7 @@ class CLIHelpIntegrationTest(unittest.TestCase):
def test_all_cli_commands_help(self):
for segments in self._discover_command_dirs():
with self.subTest(command=" ".join(segments)):
cmd = [self.python, self.main_py] + segments + ["--help"]
cmd = [self.python, self.main_py, *segments, "--help"]
result = subprocess.run(cmd, capture_output=True, text=True)
self.assertEqual(
result.returncode,
@@ -70,11 +70,11 @@ class TestComposeBuildTemplateRequiresImageTag(unittest.TestCase):
continue
ind = TestComposeBuildTemplateRequiresImageTag._indent_len(line)
if ind < props_indent_len:
if line.rstrip().endswith(":") and not line.lstrip().startswith(
("-", "#")
):
return i
if ind < props_indent_len and (
line.rstrip().endswith(":")
and (not line.lstrip().startswith(("-", "#")))
):
return i
return None
def test_build_lookup_requires_image_or_merge_on_same_level(self):
@@ -186,8 +186,7 @@ def git_ls_files(root: Path) -> list[Path]:
for d in pruned:
dirs.remove(d)
for f in files:
results.append(Path(r) / f)
results.extend(Path(r) / f for f in files)
return results
@@ -202,10 +201,7 @@ def is_whitelisted(path: Path, root: Path) -> bool:
return True
rel_wrapped = f"/{rel}/"
if any(fragment in rel_wrapped for fragment in WHITELIST_PATH_FRAGMENTS):
return True
return False
return bool(any(fragment in rel_wrapped for fragment in WHITELIST_PATH_FRAGMENTS))
def is_probably_text(data: bytes) -> bool:
@@ -174,10 +174,10 @@ class TestComposeBuildRequiresImage(unittest.TestCase):
"",
"Offenders:",
]
for it in all_findings:
msg_lines.append(
f"- {it.file}:{it.build_line} (build indent={it.build_indent}) -> {it.note}"
)
msg_lines.extend(
f"- {it.file}:{it.build_line} (build indent={it.build_indent}) -> {it.note}"
for it in all_findings
)
msg_lines.append("")
msg_lines.append(
"Fix: for each service that has `build:`, add a stable `image:` name on the same level, e.g."
@@ -1,4 +1,5 @@
import unittest
from typing import ClassVar
from urllib.parse import urlparse
import yaml
@@ -19,7 +20,7 @@ class TestCspConfigurationConsistency(unittest.TestCase):
On error, include role name and file path for easier debugging.
"""
SUPPORTED_DIRECTIVES = {
SUPPORTED_DIRECTIVES: ClassVar[set[str]] = {
"default-src",
"connect-src",
"frame-ancestors",
@@ -36,7 +37,7 @@ class TestCspConfigurationConsistency(unittest.TestCase):
"script-src-attr",
}
SUPPORTED_FLAGS = {"unsafe-eval", "unsafe-inline"}
SUPPORTED_FLAGS: ClassVar[set[str]] = {"unsafe-eval", "unsafe-inline"}
def is_valid_whitelist_entry(self, entry: str) -> bool:
"""
@@ -175,11 +176,11 @@ class TestCspConfigurationConsistency(unittest.TestCase):
)
snippets = []
for snippet in snippets:
if not isinstance(snippet, str) or not snippet.strip():
errors.append(
f"{role_path.name}: hashes.{directive} contains empty or non-string snippet ({cfg_file})"
)
errors.extend(
f"{role_path.name}: hashes.{directive} contains empty or non-string snippet ({cfg_file})"
for snippet in snippets
if not isinstance(snippet, str) or not snippet.strip()
)
if errors:
self.fail(
+2 -2
View File
@@ -18,14 +18,14 @@ def find_none_values(data, prefix=None):
if isinstance(data, dict):
for key, value in data.items():
path = prefix + [str(key)]
path = [*prefix, str(key)]
if value is None:
errors.append((".".join(path), value))
elif isinstance(value, (dict, list)):
errors.extend(find_none_values(value, path))
elif isinstance(data, list):
for idx, item in enumerate(data):
path = prefix + [f"[{idx}]"]
path = [*prefix, f"[{idx}]"]
if item is None:
errors.append((".".join(path), item))
elif isinstance(item, (dict, list)):
@@ -1,5 +1,6 @@
import re
import unittest
from typing import ClassVar
from . import PROJECT_ROOT
@@ -9,7 +10,7 @@ class TestDockerComposeTemplates(unittest.TestCase):
TEMPLATE_PATTERN = "roles/*/templates/compose.yml.j2"
# Allowed lines before BASE_INCLUDE
ALLOWED_BEFORE_BASE = [
ALLOWED_BEFORE_BASE: ClassVar[list[re.Pattern]] = [
re.compile(r"^\s*$"), # empty line
re.compile(r"^\s*version:.*$"), # version: ...
re.compile(r"^\s*#.*$"), # YAML comment
+6 -5
View File
@@ -157,9 +157,11 @@ class _FiltersCollector(ast.NodeVisitor):
and isinstance(node.func, ast.Name)
and node.func.id == "dict"
):
for kw in node.keywords or []:
if kw.arg:
pairs.append((kw.arg, self._name_of(kw.value)))
pairs.extend(
(kw.arg, self._name_of(kw.value))
for kw in node.keywords or []
if kw.arg
)
return pairs
if isinstance(node, ast.Name):
return []
@@ -328,8 +330,7 @@ class TestAllUsedFiltersAreDefined(unittest.TestCase):
"These filters are used in templates/YAML but have no local definition "
"(and are not in BUILTIN_FILTERS):"
]
for f in unknown:
lines.append("- " + f)
lines.extend("- " + f for f in unknown)
self.fail("\n".join(lines))
+5 -3
View File
@@ -72,9 +72,11 @@ class _FiltersCollector(ast.NodeVisitor):
and node.func.id == "dict"
):
# keywords: dict(name=fn)
for kw in node.keywords or []:
if kw.arg:
pairs.append((kw.arg, self._name_of(kw.value)))
pairs.extend(
(kw.arg, self._name_of(kw.value))
for kw in node.keywords or []
if kw.arg
)
return pairs
# Name (variable) that might be a dict assembled earlier in the function
@@ -69,14 +69,13 @@ def build_edges(vars_dict):
def walk(node, path):
if isinstance(node, dict):
for k, v in node.items():
walk(v, path + [k])
walk(v, [*path, k])
elif isinstance(node, list):
for i, e in enumerate(node):
walk(e, path + [f"[{i}]"])
walk(e, [*path, f"[{i}]"])
else:
full_key = ".".join(path)
for ref in find_jinja_refs(node):
edges.append((full_key, ref))
edges.extend((full_key, ref) for ref in find_jinja_refs(node))
walk(vars_dict, [])
return edges
@@ -111,7 +110,7 @@ class TestNoJinjaReferenceCycles(unittest.TestCase):
def dfs(node, visited, stack):
if node in stack:
return stack[stack.index(node) :] + [node]
return [*stack[stack.index(node) :], node]
if node in visited:
return None
visited.add(node)
+1 -2
View File
@@ -285,8 +285,7 @@ class TestHandlersInvoked(unittest.TestCase):
if missing_groups:
representatives: list[str] = []
for grp in missing_groups:
representatives.append(sorted(grp)[0])
representatives.extend(sorted(grp)[0] for grp in missing_groups)
representatives = sorted(set(representatives))
msg = [
@@ -131,7 +131,7 @@ class TestVariableDefinitions(unittest.TestCase):
data = yaml.safe_load(inline_map)
if isinstance(data, dict):
self.defined.update(
k for k in data.keys() if isinstance(k, str)
k for k in data if isinstance(k, str)
)
except yaml.YAMLError as exc:
logging.debug(
@@ -273,7 +273,7 @@ class TestVariableDefinitions(unittest.TestCase):
if m_expr:
var = m_expr.group(1)
if var not in (
if var not in ( # noqa: SIM102 the long literal whitelist is more readable as a separate guard
"lookup",
"role_name",
"domains",
@@ -35,7 +35,7 @@ def match_wildcard_segment(mapping: Any, segment: str) -> bool:
return False
if "*" not in segment:
return segment in mapping
return any(fnmatch.fnmatchcase(k, segment) for k in mapping.keys())
return any(fnmatch.fnmatchcase(k, segment) for k in mapping)
def match_wildcard_path(mapping: Any, dotted: str) -> bool:
@@ -84,12 +84,11 @@ class TestVariablePaths(unittest.TestCase):
if isinstance(creds, Mapping) and key in creds:
return True
if dotted.startswith("images."):
if any(
isinstance(cfg.get("images"), Mapping)
for cfg in ctx.application_defaults.values()
):
return True
if dotted.startswith("images.") and any(
isinstance(cfg.get("images"), Mapping)
for cfg in ctx.application_defaults.values()
):
return True
if dotted.startswith("users."):
subpath = dotted.split(".", 1)[1]
@@ -92,11 +92,10 @@ class TestWildcardPaths(unittest.TestCase):
creds = schema.get("credentials") if isinstance(schema, Mapping) else None
if isinstance(creds, Mapping) and match_wildcard_segment(creds, sub):
return True
if wildcard_path.startswith("images.") and isinstance(
cfg.get("images"), Mapping
):
return True
return False
return bool(
wildcard_path.startswith("images.")
and isinstance(cfg.get("images"), Mapping)
)
if __name__ == "__main__":
@@ -60,12 +60,7 @@ def _iter_text_files(root):
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = [d for d in dirnames if d not in EXCLUDED_DIRS]
for filename in filenames:
if not (
filename.endswith(".yml")
or filename.endswith(".yaml")
or filename.endswith(".j2")
or filename.endswith(".py")
):
if not (filename.endswith((".yml", ".yaml", ".j2", ".py"))):
continue
yield os.path.join(dirpath, filename)
@@ -55,7 +55,7 @@ def _is_full_line_comment(line: str) -> bool:
def _is_jinja_control_line(line: str) -> bool:
s = line.lstrip()
return s.startswith("{%") or s.startswith("{#")
return s.startswith(("{%", "{#"))
class TestEnvPasswordsQuotedAndFiltered(unittest.TestCase):
@@ -27,9 +27,9 @@ class TestRunAfterRoles(unittest.TestCase):
continue
run_after = data.get("galaxy_info", {}).get("run_after", [])
for ref in run_after:
if ref not in self.valid_role_names:
invalid_refs.append((role, ref))
invalid_refs.extend(
(role, ref) for ref in run_after if ref not in self.valid_role_names
)
if invalid_refs:
msg = "\n".join(
@@ -7,7 +7,7 @@ def find_repo_root(start: Path) -> Path | None:
Walk up from `start` until we find a directory containing 'roles'.
Returns the repo root (the directory that contains 'roles') or None.
"""
for parent in [start] + list(start.parents):
for parent in [start, *list(start.parents)]:
if (parent / "roles").is_dir():
return parent
return None
@@ -49,9 +49,11 @@ class TestIncludeImportExistence(unittest.TestCase):
elif isinstance(val, dict) and value_key in val:
refs.append(val[value_key])
elif isinstance(val, list):
for item in val:
if isinstance(item, dict) and value_key in item:
refs.append(item[value_key])
refs.extend(
item[value_key]
for item in val
if isinstance(item, dict) and value_key in item
)
else:
refs.extend(
TestIncludeImportExistence._collect_refs(
@@ -93,7 +95,7 @@ class TestIncludeImportExistence(unittest.TestCase):
self.fail(
"Invalid include_role/import_role name detected.\n"
f" • File: {file_path}\n"
f" • Extracted name value: {repr(role_name)}\n"
f" • Extracted name value: {role_name!r}\n"
"The 'name:' field must contain a non-empty string.\n"
"Example:\n"
" include_role:\n"
@@ -15,8 +15,7 @@ def get_meta_info(role_path):
if not os.path.isfile(meta_file):
return []
meta_data = load_yaml_file(meta_file)
dependencies = meta_data.get("dependencies", [])
return dependencies
return meta_data.get("dependencies", [])
def resolve_dependencies(roles_dir):
@@ -57,7 +56,7 @@ def resolve_dependencies(roles_dir):
visit(role_path, []) # Start recursion from this role
except ValueError as e:
raise ValueError(
f"Error processing role '{role_name}' at path '{role_path}': {str(e)}"
f"Error processing role '{role_name}' at path '{role_path}': {e!s}"
) from e
@@ -117,8 +117,7 @@ def find_var_positions(text: str, varname: str) -> list[int]:
"""Return byte offsets for occurrences of varname (word-ish boundary)."""
positions: list[int] = []
pattern = re.compile(rf"(?<!\w){re.escape(varname)}(?!\w)")
for m in pattern.finditer(text):
positions.append(m.start())
positions.extend(m.start() for m in pattern.finditer(text))
return positions
@@ -22,7 +22,7 @@ class TestCircularDependencies(unittest.TestCase):
def test_no_circular_dependencies(self):
# Build the dependency graph using the real roles/
graph, in_degree, roles = build_dependency_graph(self.roles_dir)
_graph, _in_degree, roles = build_dependency_graph(self.roles_dir)
# Attempt to find a cycle in the run_after mapping
cycle = find_cycle(roles)
@@ -36,12 +36,11 @@ class TestRunAfterReferences(unittest.TestCase):
data = load_yaml_any(meta_path, default_if_missing={}) or {}
run_after = data.get("galaxy_info", {}).get("run_after", [])
for dep in run_after:
if dep not in self.existing_roles:
errors.append(
f"Role '{role}' declares run_after: '{dep}', "
f"but '{dep}' is not a directory under roles/"
)
errors.extend(
f"Role '{role}' declares run_after: '{dep}', but '{dep}' is not a directory under roles/"
for dep in run_after
if dep not in self.existing_roles
)
if errors:
self.fail(
@@ -162,16 +162,17 @@ class TestAuthVariantsCoverage(unittest.TestCase):
f"variant entry with both flags false."
)
if dynamic_auth and ldap_dynamic:
if not _has_ldap_only_variant(variants, dynamic_auth):
auth_list = " / ".join(f"services.{k}" for k in dynamic_auth)
offenders.append(
f"{role_name}: both ldap and {auth_list} are dynamic, "
f"but no variant pins ``ldap.enabled: true`` together "
f"with ``enabled: false`` on the auth service(s) — the "
f"LDAP-only branch is never exercised. See "
f"docs/requirements/018-playwright-ldap-coverage.md."
)
if (dynamic_auth and ldap_dynamic) and not _has_ldap_only_variant(
variants, dynamic_auth
):
auth_list = " / ".join(f"services.{k}" for k in dynamic_auth)
offenders.append(
f"{role_name}: both ldap and {auth_list} are dynamic, "
f"but no variant pins ``ldap.enabled: true`` together "
f"with ``enabled: false`` on the auth service(s) — the "
f"LDAP-only branch is never exercised. See "
f"docs/requirements/018-playwright-ldap-coverage.md."
)
if offenders:
self.fail(
@@ -53,9 +53,11 @@ def _dynamic_pairs(services: dict) -> list[tuple[str, str]]:
for key, entry in services.items():
if not isinstance(entry, dict):
continue
for flag in ("enabled", "shared"):
if _is_dynamic_flag(entry.get(flag)):
pairs.append((key, flag))
pairs.extend(
(key, flag)
for flag in ("enabled", "shared")
if _is_dynamic_flag(entry.get(flag))
)
return pairs
@@ -52,7 +52,7 @@ class TestVariantsServicesMatch(unittest.TestCase):
services = _load_yaml(role_dir / "meta" / "services.yml")
if not isinstance(services, dict):
continue
declared_keys = {k for k in services.keys() if isinstance(k, str)}
declared_keys = {k for k in services if isinstance(k, str)}
variants_raw = _load_yaml(role_dir / "meta" / "variants.yml")
if not isinstance(variants_raw, list):
@@ -64,7 +64,7 @@ class TestVariantsServicesMatch(unittest.TestCase):
variant_services = variant.get("services")
if not isinstance(variant_services, dict):
continue
for key in variant_services.keys():
for key in variant_services:
if not isinstance(key, str):
continue
if key in declared_keys:
@@ -120,7 +120,7 @@ def collect_set_fact_suffixes(obj, out_suffixes: set[str]):
elif isinstance(obj, dict):
sf = obj.get("set_fact") or obj.get("ansible.builtin.set_fact")
if isinstance(sf, dict):
for k in sf.keys():
for k in sf:
if isinstance(k, str):
m = RUN_ONCE_USAGE_RE.fullmatch(k.strip())
if m:
@@ -169,8 +169,7 @@ def role_defines_suffix_in_doc(doc, role_suffix: str) -> bool:
if isinstance(sf, dict) and target_var in sf:
return True
# Recurse
for v in node.values():
queue.append(v)
queue.extend(node.values())
elif isinstance(node, list):
queue.extend(node)
return False
@@ -258,26 +257,26 @@ class RunOnceGlobalUsageFastTest(unittest.TestCase):
offenders: list[tuple[str, str, str]] = []
# A) Unknown suffixes used (no corresponding role) must be globally defined
for suffix in sorted(used_suffixes):
if suffix not in known_suffixes and suffix not in global_defined_suffixes:
offenders.append(
(
"<no-role>",
f"run_once_{suffix}",
"<global usage without global set_fact>",
)
)
offenders.extend(
(
"<no-role>",
f"run_once_{suffix}",
"<global usage without global set_fact>",
)
for suffix in sorted(used_suffixes)
if suffix not in known_suffixes and suffix not in global_defined_suffixes
)
# B) Known role suffixes used must be defined either globally or in that exact role
for role in sorted(roles):
suffix = suffix_for_role[role]
if suffix in used_suffixes:
if (suffix not in global_defined_suffixes) and (
suffix not in role_defined_suffixes[role]
):
offenders.append(
(role, f"run_once_{suffix}", os.path.join(rroot, role, "tasks"))
)
if suffix in used_suffixes and (
suffix not in global_defined_suffixes
and suffix not in role_defined_suffixes[role]
):
offenders.append(
(role, f"run_once_{suffix}", os.path.join(rroot, role, "tasks"))
)
if offenders:
lines = [
@@ -77,9 +77,8 @@ def _iter_tasks(node: Any) -> Iterable[dict[str, Any]]:
yield from _iter_tasks(item)
# Also traverse other nested structures conservatively
for k, v in node.items():
if k not in ("block", "rescue", "always"):
if isinstance(v, (list, dict)):
yield from _iter_tasks(v)
if k not in ("block", "rescue", "always") and isinstance(v, (list, dict)):
yield from _iter_tasks(v)
def _load_yaml_documents(path: Path) -> list[Any]:
@@ -10,9 +10,8 @@ from utils.cache.files import read_text
def _safe_yaml_load(path):
try:
doc = yaml.safe_load(read_text(path))
return yaml.safe_load(read_text(path))
# A tasks file can be a list (usual) or a dict (blocks, etc.)
return doc
except Exception as e:
raise AssertionError(f"Failed to parse YAML: {path}\n{e}") from e
@@ -80,7 +79,7 @@ class TestSysServiceRequiresSystemServiceId(unittest.TestCase):
for bt in t["block"]:
if check_task(bt):
return True
elif isinstance(tasks_doc, dict):
elif isinstance(tasks_doc, dict): # noqa: SIM102 pairs with the for-list branch above; flat structure is clearer
# top-level block file (rare)
if "block" in tasks_doc and isinstance(tasks_doc["block"], list):
for bt in tasks_doc["block"]:
@@ -119,7 +119,7 @@ def _collect_defined_facts(task_files: list[Path]) -> dict[str, set[Path]]:
if not _is_set_fact_task(task):
continue
mapping = _get_set_fact_mapping(task)
for k in mapping.keys():
for k in mapping:
if not isinstance(k, str) or _looks_dynamic(k):
continue
facts.setdefault(k, set()).add(p)
@@ -143,7 +143,7 @@ def _collect_var_overrides(task_files: list[Path]) -> list[tuple[Path, str, str]
if not vmap:
continue
tname = str(task.get("name", "<unnamed task>"))
for k in vmap.keys():
for k in vmap:
if not isinstance(k, str) or _looks_dynamic(k):
continue
overrides.append((p, tname, k))
Loaded 100 of 182 files, more files were not shown because too many files have changed in this diff. Show more