mirror of
https://github.com/kevinveenbirkenbach/computer-playbook.git
synced 2026-11-06 19:01:54 +00:00
TC (flake8-type-checking): typing-only imports moved into
``if TYPE_CHECKING:`` blocks across 8 source files via auto-fix
(117 hits). Reduces runtime import surface and rules out circular
imports for type-only deps. Project-wide ``from __future__ import
annotations`` (FA, already enabled) keeps annotations as strings,
so the moved imports never need to load at runtime.
N (pep8-naming): 32 hits handled.
Renames (semantic + lint):
- ``isSmallerThenMaximumBackupSize`` -> ``is_larger_than_maximum_backup_size``
(snake_case + fixes both the typo "Then -> Than" and the
semantic mismatch: the function returns ``current > maximum``)
- ``isDirectoryDeletable`` / ``deleteVersion`` /
``getAmountOfIteration`` / ``deleteIteration`` -> snake_case
- 8 test functions with ALL-CAPS env-var fragments
(``test_..._DOMAIN_PRIMARY_...`` etc.) -> snake_case
- Mock alias ``VH`` -> ``vh`` in test_host_vars.py
Exception class renames (``N818`` Error suffix):
- ``TimeLimitExceededException`` -> ``TimeLimitExceededError``
- ``AttemptException`` -> ``AttemptError``
- ``PathNotFound`` -> ``PathNotFoundError`` (propagated across
4 callers under tests/integration/lookups/config/)
- ``_ExitJson`` / ``_FailJson`` -> ``*_Error``
Refactor:
- ``METADATA = {...}`` local constant in two functions of
``plugins/filter/invokable_paths.py`` lifted to module-level
``_METADATA_KEYS``.
- ``from typing import TYPE_CHECKING`` in
``tasks/utils/migrate_meta_layout/__main__.py`` moved above
the ``sys.path.insert`` hack to satisfy E402 (collateral from
the TC auto-fix that landed it after the path mutation).
Per-file ignores in pyproject.toml for the legitimate cases the
rule cannot accept:
- ``pull-specific-host.py`` -> ``N999`` (Ansible-invoked role-level
script, hyphenated filename pinned by the surrounding stack).
- 4 matrix-deploy files -> ``N806`` for the ``include_R`` /
``raw_include_R`` round-index notation; the uppercase ``R``
here mirrors the formula in the docstring rather than naming
a constant.
- ``plugins/filter/value_generator.py`` -> ``N806`` for the
lazy-loaded class binding ``ValueGenerator =
_value_generator_cls()``, which retains the imported class
identifier per PEP 8.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
84 lines
2.3 KiB
Python
84 lines
2.3 KiB
Python
from __future__ import annotations
|
|
|
|
import contextlib
|
|
import os
|
|
import pty
|
|
import subprocess
|
|
from dataclasses import dataclass
|
|
from datetime import UTC, datetime
|
|
from typing import TYPE_CHECKING, TextIO
|
|
|
|
from cli.core.colors import Fore, color_text
|
|
|
|
if TYPE_CHECKING:
|
|
from pathlib import Path
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class RunConfig:
|
|
log_enabled: bool
|
|
|
|
|
|
def open_log_file(log_dir: Path) -> tuple[TextIO, Path]:
|
|
"""
|
|
Create/open a timestamped log file inside log_dir.
|
|
|
|
- log_dir is mandatory (provided via --log <LOG_DIR>)
|
|
- log_dir is created with parents=True if missing
|
|
"""
|
|
log_dir = log_dir.expanduser()
|
|
log_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
# Best-effort permission hardening (ignore failures on non-POSIX / special FS).
|
|
with contextlib.suppress(Exception):
|
|
log_dir.chmod(0o700)
|
|
|
|
timestamp = datetime.now(tz=UTC).strftime("%Y%m%dT%H%M%S")
|
|
log_file_path = log_dir / f"{timestamp}.log"
|
|
fd = os.open(str(log_file_path), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
|
|
return os.fdopen(fd, "a", encoding="utf-8"), log_file_path
|
|
|
|
|
|
def run_command_once(
|
|
full_cmd: list[str], cfg: RunConfig, log_file: TextIO | None
|
|
) -> bool:
|
|
try:
|
|
if cfg.log_enabled and log_file is not None:
|
|
master_fd, slave_fd = pty.openpty()
|
|
proc = subprocess.Popen(
|
|
full_cmd,
|
|
stdin=slave_fd,
|
|
stdout=slave_fd,
|
|
stderr=slave_fd,
|
|
text=True,
|
|
)
|
|
os.close(slave_fd)
|
|
|
|
import errno
|
|
|
|
with os.fdopen(master_fd) as master:
|
|
try:
|
|
for line in master:
|
|
ts = datetime.now(tz=UTC).strftime("%Y-%m-%dT%H:%M:%S")
|
|
log_file.write(f"{ts} {line}")
|
|
log_file.flush()
|
|
print(line, end="")
|
|
except OSError as e:
|
|
if e.errno != errno.EIO:
|
|
raise
|
|
|
|
proc.wait()
|
|
rc = proc.returncode
|
|
else:
|
|
proc = subprocess.Popen(full_cmd)
|
|
proc.wait()
|
|
rc = proc.returncode
|
|
|
|
except Exception as e:
|
|
print(color_text(f"Exception running command: {e}", Fore.RED))
|
|
raise SystemExit(1) from e
|
|
|
|
if rc != 0:
|
|
raise SystemExit(rc)
|
|
return True
|