diff --git a/CHANGELOG.md b/CHANGELOG.md index fec6199..ff37ba8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes are documented here. This project follows [Semantic Versioni ## [Unreleased] +### Changed +- `--version` from a source checkout now reports a git-derived version such as + `0.1.0.dev3+g19a5373` instead of `0.0.0.dev0`. Release binaries are unchanged. + ### Added - `scripts/migrate_zshrc.py`: one-off migration of zshrc exports into OpenBao KV (`env/shell/`), with digest verification and generation of the EnvBao config and a read-only token. diff --git a/src/envbao/cli.py b/src/envbao/cli.py index 020225e..1144fb1 100644 --- a/src/envbao/cli.py +++ b/src/envbao/cli.py @@ -14,7 +14,6 @@ import sys from collections.abc import Sequence from pathlib import Path -from envbao import __version__ from envbao.client import BaoClient from envbao.config import Config, load_config, resolve_config_path from envbao.errors import EXIT_FAILURE, EXIT_OK, EnvBaoError, PermissionPolicyError @@ -22,6 +21,7 @@ from envbao.logging_setup import add_file_logging, setup_stderr_logging from envbao.render import SHELLS, detect_shell, render from envbao.resolve import resolve, validate_queries from envbao.security import check_config_dir +from envbao.version import get_version log = logging.getLogger("envbao") @@ -46,6 +46,17 @@ path = "myapp/prod" """ +class _VersionAction(argparse.Action): + """``--version`` that resolves the version lazily (git is never run otherwise).""" + + def __init__(self, option_strings: Sequence[str], dest: str, **kwargs: object) -> None: + super().__init__(option_strings, dest, nargs=0, help="show version and exit") + + def __call__(self, parser: argparse.ArgumentParser, *args: object, **kwargs: object) -> None: + sys.stdout.write(f"envbao {get_version()}\n") + parser.exit() + + def build_parser() -> argparse.ArgumentParser: """Create the argument parser.""" parser = argparse.ArgumentParser( @@ -74,7 +85,7 @@ def build_parser() -> argparse.ArgumentParser: help="create ~/.envbao with safe permissions and a template config.toml", ) parser.add_argument("-v", "--verbose", action="count", default=0, help="log more to stderr") - parser.add_argument("--version", action="version", version=f"envbao {__version__}") + parser.add_argument("--version", action=_VersionAction) return parser diff --git a/src/envbao/version.py b/src/envbao/version.py new file mode 100644 index 0000000..cdcb3a3 --- /dev/null +++ b/src/envbao/version.py @@ -0,0 +1,66 @@ +"""Version reporting. + +Release binaries carry the version stamped into ``_version.py`` from the git tag. When +running from a source checkout (stamp is the placeholder) the version is derived from +``git describe`` so a development build never masquerades as a release, e.g. +``0.1.0.dev3+g19a5373`` (3 commits after ``v0.1.0``), with ``.dirty`` appended if the +working tree has uncommitted changes. + +git is only consulted lazily (``--version``), never during normal shell start-up. +""" + +from __future__ import annotations + +import re +import shutil +import subprocess # noqa: S404 +import sys +from pathlib import Path + +from envbao._version import __version__ as STAMPED + +PLACEHOLDER = "0.0.0.dev0" +_DESCRIBE_RE = re.compile(r"^v(?P.+?)-(?P\d+)-g(?P[0-9a-f]+)(?P-dirty)?$") + + +def format_describe(described: str) -> str | None: + """Convert ``git describe --long --dirty`` output to a PEP 440 style version. + + ``v0.1.0-0-gabc1234`` -> ``0.1.0``; + ``v0.1.0-3-gabc1234-dirty`` -> ``0.1.0.dev3+gabc1234.dirty``. + Returns None if the text is not from a ``v*`` tag. + """ + match = _DESCRIBE_RE.match(described.strip()) + if not match: + return None + tag, count, sha, dirty = match["tag"], int(match["n"]), match["sha"], bool(match["dirty"]) + if count == 0 and not dirty: + return tag + local = f"g{sha}.dirty" if dirty else f"g{sha}" + return f"{tag}.dev{count}+{local}" + + +def _git_version(root: Path) -> str | None: + git = shutil.which("git") + if not git or not (root / ".git").exists(): + return None + try: + proc = subprocess.run( # noqa: S603 + [git, "describe", "--tags", "--long", "--dirty", "--match", "v[0-9]*"], + cwd=root, + capture_output=True, + text=True, + timeout=5, + check=False, + ) + except (OSError, subprocess.SubprocessError): + return None + return format_describe(proc.stdout) if proc.returncode == 0 else None + + +def get_version() -> str: + """Return the stamped release version, or a git-derived one for source checkouts.""" + if STAMPED != PLACEHOLDER or getattr(sys, "frozen", False): + return STAMPED + root = Path(__file__).resolve().parents[2] + return _git_version(root) or STAMPED diff --git a/tests/test_cli.py b/tests/test_cli.py index 7c195dd..a4a69df 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -6,9 +6,9 @@ from pathlib import Path import pytest -from envbao import __version__ from envbao.cli import init_config, main from envbao.errors import EXIT_AUTH, EXIT_CONFIG, EXIT_FAILURE, EXIT_OK, EXIT_UNAVAILABLE +from envbao.version import get_version from .conftest import TOKEN, FakeBao, write_config @@ -171,7 +171,7 @@ def test_version(capsys: pytest.CaptureFixture[str]) -> None: with pytest.raises(SystemExit) as exc: main(["--version"]) assert exc.value.code == 0 - assert __version__ in capsys.readouterr().out + assert get_version() in capsys.readouterr().out # ---- init ----------------------------------------------------------------------------- @@ -221,4 +221,4 @@ def test_python_dash_m(tmp_path: Path) -> None: check=True, env={**os.environ}, ) - assert __version__ in result.stdout + assert get_version() in result.stdout diff --git a/tests/test_version.py b/tests/test_version.py new file mode 100644 index 0000000..aedf906 --- /dev/null +++ b/tests/test_version.py @@ -0,0 +1,87 @@ +import subprocess +from pathlib import Path + +import pytest + +from envbao import version + + +@pytest.mark.parametrize( + "described, expected", + [ + ("v0.1.0-0-g19a5373", "0.1.0"), + ("v0.1.0-3-g19a5373", "0.1.0.dev3+g19a5373"), + ("v1.2.3-rc.1-0-gabc1234", "1.2.3-rc.1"), + ("v0.1.0-0-g19a5373-dirty", "0.1.0.dev0+g19a5373.dirty"), + ("v0.1.0-3-g19a5373-dirty\n", "0.1.0.dev3+g19a5373.dirty"), + ("19a5373", None), + ("", None), + ("release-1-g123", None), + ], +) +def test_format_describe(described: str, expected: str | None) -> None: + assert version.format_describe(described) == expected + + +def test_stamped_release_version_wins(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(version, "STAMPED", "2.0.0") + monkeypatch.setattr(version, "_git_version", lambda root: pytest.fail("git must not run")) + assert version.get_version() == "2.0.0" + + +def test_frozen_never_uses_git(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(version.sys, "frozen", True, raising=False) + monkeypatch.setattr(version, "_git_version", lambda root: pytest.fail("git must not run")) + assert version.get_version() == version.STAMPED + + +def test_source_checkout_uses_git(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(version, "STAMPED", version.PLACEHOLDER) + monkeypatch.setattr(version, "_git_version", lambda root: "0.1.0.dev3+gabc") + assert version.get_version() == "0.1.0.dev3+gabc" + + +def test_falls_back_to_placeholder(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(version, "STAMPED", version.PLACEHOLDER) + monkeypatch.setattr(version, "_git_version", lambda root: None) + assert version.get_version() == version.PLACEHOLDER + + +def test_git_version_no_repo(tmp_path: Path) -> None: + assert version._git_version(tmp_path) is None # noqa: SLF001 + + +def test_git_version_real_repo(tmp_path: Path) -> None: + def git(*a: str) -> None: + subprocess.run( # noqa: S603 + ["git", "-c", "user.name=t", "-c", "user.email=t@t", *a], # noqa: S607 + cwd=tmp_path, check=True, capture_output=True, + ) # fmt: skip + + git("init", "-q") + (tmp_path / "f").write_text("1") + git("add", "f") + git("commit", "-qm", "one") + git("tag", "v1.0.0") + assert version._git_version(tmp_path) == "1.0.0" # noqa: SLF001 + (tmp_path / "f").write_text("2") + git("commit", "-qam", "two") + assert version._git_version(tmp_path).startswith("1.0.0.dev1+g") # type: ignore[union-attr] # noqa: SLF001 + (tmp_path / "f").write_text("3") + assert version._git_version(tmp_path).endswith(".dirty") # type: ignore[union-attr] # noqa: SLF001 + + +def test_git_missing(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + (tmp_path / ".git").mkdir() + monkeypatch.setattr(version.shutil, "which", lambda name: None) + assert version._git_version(tmp_path) is None # noqa: SLF001 + + +def test_git_failure(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + (tmp_path / ".git").mkdir() + + def boom(*a: object, **k: object) -> None: + raise OSError + + monkeypatch.setattr(version.subprocess, "run", boom) + assert version._git_version(tmp_path) is None # noqa: SLF001