Files
pkgmgr/src/pkgmgr/core/version/source.py
T
Kevin Veen-BirkenbachandClaude Opus 5.5 0f6583ca48 fix(security): close the 32 open CodeQL alerts
Critical #60/#61 untrusted checkout: publish-containers.yml prepare runs for workflow_run only when the triggering run succeeded, was a push and came from this repository; build and merge need prepare, so the guard covers both checkouts. Mark stable commit triggers only on push of v* tags, schedule and workflow_dispatch are unchanged. Medium #55/#56: update-flake-lock.yml pins nix-installer-action v23 and update-flake-lock v29 to commit SHAs. High: secret_service_token returns only the token and raises SecretServiceUnavailable with the same reasons, _forge_access builds the token/reason pair (#62); jinja2 select_autoescape for html/htm/xml only, scaffolding output byte-identical (#29); chmod 0o755 to 0o700 for owner-run scripts in ink.py and 7 test sites; exact URL equality in a mirror probe test. Error #33: raise unittest.SkipTest from exc. Notes: empty-except to contextlib.suppress, one import form per module, unused variable, commented-out code, assertNotIn.

| 🌿 Branch | 📊 Diff stat | 🎯 Fix | 💥 Break | 💸 Tokens | ⏱️ Velocity | 🛡️ Security | 🏆 Score | Gate |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| fix/codeql-alerts | 28 files +92/-81 | 90 % | 3 % | – | – | 100 % | 87 | ✅ 90/5, tokens and velocity <= 100, security 100 % |

Evidence: tests/unit + tests/integration 880 passed, 574 subtests; 2 test_publish_integration failures are identical on a clone without these changes (global tag.gpgsign, sandbox blocks gpg). ruff and actionlint clean, MEDUSA 100 % critical 0 (1 accepted keyword false positive). Operator choice 7589a6f1 (swarm), operator review dcc2f461.
Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 20:19:21 +00:00

326 lines
9.5 KiB
Python

# src/pkgmgr/core/version/source.py
from __future__ import annotations
import contextlib
import os
import re
import yaml
from pkgmgr.core.repository.paths import resolve_repo_paths
def version_literal(name: str) -> re.Pattern[str]:
"""
Args:
name: the module attribute holding the version, e.g. __version__.
Returns:
A pattern whose groups are the assignment up to the opening quote, the
version and the closing quote of `name = "X.Y.Z"`.
"""
return re.compile(rf"""(?m)^(\s*{re.escape(name)}\s*=\s*["'])([^"']+)(["'])""")
def dynamic_version_source(pyproject_path: str, data: dict) -> tuple[str, str] | None:
"""
Args:
pyproject_path: the pyproject.toml file.
data: its parsed content.
Returns:
(module file, attribute name) that setuptools reads the version from
when [project].dynamic lists version and [tool.setuptools.dynamic]
sets version = {attr = "pkg.module.NAME"}, with
[tool.setuptools].package-dir applied; None otherwise.
"""
project = data.get("project") or {}
if "version" not in project.get("dynamic", []):
return None
setuptools = (data.get("tool") or {}).get("setuptools") or {}
attr = ((setuptools.get("dynamic") or {}).get("version") or {}).get("attr")
if not isinstance(attr, str) or "." not in attr:
return None
module, _, name = attr.rpartition(".")
parts = module.split(".")
dirs = setuptools.get("package-dir") or {}
if parts[0] in dirs:
base = os.path.join(dirs[parts[0]], *parts[1:])
else:
base = os.path.join(dirs.get("", ""), *parts)
root = os.path.dirname(os.path.abspath(pyproject_path))
for candidate in (f"{base}.py", os.path.join(base, "__init__.py")):
path = os.path.join(root, candidate)
if os.path.isfile(path):
return path, name
return None
def read_pyproject_version(repo_dir: str) -> str | None:
"""
Read the version from pyproject.toml in repo_dir, if present.
Expects a PEP 621-style [project] table with a 'version' field, or a
dynamic version that setuptools reads from a module attribute
(dynamic_version_source()).
"""
paths = resolve_repo_paths(repo_dir)
path = paths.pyproject_toml
if not os.path.isfile(path):
return None
try:
import tomllib # Python 3.11+
except ImportError:
import tomli as tomllib # type: ignore
try:
with open(path, "rb") as f:
data = tomllib.load(f)
project = data.get("project") or {}
version = project.get("version")
if version:
return str(version).strip()
source = dynamic_version_source(path, data)
if source is None:
return None
with open(source[0], encoding="utf-8") as f:
match = version_literal(source[1]).search(f.read())
return match.group(2).strip() if match else None
except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError):
return None
def read_pyproject_project_name(repo_dir: str) -> str | None:
"""
Read distribution name from pyproject.toml ([project].name).
This is required to correctly resolve installed Python package
versions via importlib.metadata.
"""
paths = resolve_repo_paths(repo_dir)
path = paths.pyproject_toml
if not os.path.isfile(path):
return None
try:
import tomllib # Python 3.11+
except ImportError:
import tomli as tomllib # type: ignore
try:
with open(path, "rb") as f:
data = tomllib.load(f)
project = data.get("project") or {}
name = project.get("name")
return str(name).strip() if name else None
except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError):
return None
def read_flake_version(repo_dir: str) -> str | None:
"""
Read the version from flake.nix in repo_dir, if present.
Looks for:
version = "X.Y.Z";
"""
paths = resolve_repo_paths(repo_dir)
path = paths.flake_nix
if not os.path.isfile(path):
return None
try:
with open(path, encoding="utf-8") as f:
text = f.read()
except (OSError, UnicodeDecodeError):
return None
match = re.search(r'version\s*=\s*"([^"]+)"', text)
if not match:
return None
return match.group(1).strip() or None
def read_pkgbuild_version(repo_dir: str) -> str | None:
"""
Read the version from PKGBUILD (preferring packaging/arch/PKGBUILD).
Combines pkgver and pkgrel if both exist:
pkgver=1.2.3
pkgrel=1
-> 1.2.3-1
"""
paths = resolve_repo_paths(repo_dir)
path = paths.arch_pkgbuild
if not path or not os.path.isfile(path):
return None
try:
with open(path, encoding="utf-8") as f:
text = f.read()
except (OSError, UnicodeDecodeError):
return None
ver_match = re.search(r"^pkgver\s*=\s*(.+)$", text, re.MULTILINE)
if not ver_match:
return None
pkgver = ver_match.group(1).strip()
rel_match = re.search(r"^pkgrel\s*=\s*(.+)$", text, re.MULTILINE)
if rel_match:
pkgrel = rel_match.group(1).strip()
if pkgrel:
return f"{pkgver}-{pkgrel}"
return pkgver or None
def read_debian_changelog_version(repo_dir: str) -> str | None:
"""
Read the latest version from debian changelog.
Preferred path:
packaging/debian/changelog
Fallback:
debian/changelog
Expected format:
package (1.2.3-1) unstable; urgency=medium
"""
paths = resolve_repo_paths(repo_dir)
path = paths.debian_changelog
if not path or not os.path.isfile(path):
return None
try:
with open(path, encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
match = re.search(r"\(([^)]+)\)", line)
if match:
return match.group(1).strip() or None
break
except (OSError, UnicodeDecodeError):
return None
return None
def read_spec_version(repo_dir: str) -> str | None:
"""
Read the version from an RPM spec file.
Preferred paths:
packaging/fedora/package-manager.spec
packaging/fedora/*.spec
repo_root/*.spec
Combines:
Version: 1.2.3
Release: 1%{?dist}
-> 1.2.3-1
"""
paths = resolve_repo_paths(repo_dir)
path = paths.rpm_spec
if not path or not os.path.isfile(path):
return None
try:
with open(path, encoding="utf-8") as f:
text = f.read()
except (OSError, UnicodeDecodeError):
return None
ver_match = re.search(r"^Version:\s*(.+)$", text, re.MULTILINE)
if not ver_match:
return None
version = ver_match.group(1).strip()
rel_match = re.search(r"^Release:\s*(.+)$", text, re.MULTILINE)
if rel_match:
release_raw = rel_match.group(1).strip()
release = release_raw.split("%", 1)[0].split(" ", 1)[0].strip()
if release:
return f"{version}-{release}"
return version or None
def read_ansible_galaxy_version(repo_dir: str) -> str | None:
"""
Read the version from Ansible Galaxy metadata.
Supported:
- galaxy.yml
- meta/main.yml (galaxy_info.version or version)
"""
galaxy_yml = os.path.join(repo_dir, "galaxy.yml")
if os.path.isfile(galaxy_yml):
with contextlib.suppress(OSError, UnicodeDecodeError, yaml.YAMLError):
with open(galaxy_yml, encoding="utf-8") as f:
data = yaml.safe_load(f) or {}
version = data.get("version")
if isinstance(version, str) and version.strip():
return version.strip()
meta_yml = os.path.join(repo_dir, "meta", "main.yml")
if os.path.isfile(meta_yml):
try:
with open(meta_yml, encoding="utf-8") as f:
data = yaml.safe_load(f) or {}
galaxy_info = data.get("galaxy_info") or {}
if isinstance(galaxy_info, dict):
version = galaxy_info.get("version")
if isinstance(version, str) and version.strip():
return version.strip()
version = data.get("version")
if isinstance(version, str) and version.strip():
return version.strip()
except (OSError, UnicodeDecodeError, yaml.YAMLError):
return None
return None
def read_cargo_version(repo_dir: str) -> str | None:
"""
Read [package].version from Cargo.toml in repo_dir, if present.
"""
path = os.path.join(repo_dir, "Cargo.toml")
if not os.path.isfile(path):
return None
try:
import tomllib
except ImportError:
import tomli as tomllib # type: ignore
try:
with open(path, "rb") as f:
version = (tomllib.load(f).get("package") or {}).get("version")
except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError):
return None
return version.strip() if isinstance(version, str) and version.strip() else None
def read_changelog_version(repo_dir: str) -> str | None:
"""
Read the newest release from CHANGELOG.md ("## [X.Y.Z] - date").
"""
path = os.path.join(repo_dir, "CHANGELOG.md")
if not os.path.isfile(path):
return None
try:
with open(path, encoding="utf-8") as f:
match = re.search(r"(?m)^##\s+\[(v?\d+\.\d+\.\d+)\]", f.read())
except (OSError, UnicodeDecodeError):
return None
return match.group(1).strip() if match else None