voohook 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
voohook/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ """voohook — git hooks that keep your version and your submodule pins honest.
2
+
3
+ A merger of auto-version-hook and auto-submodule over one env.yml.
4
+ """
voohook/__main__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Allow `python -m voohook`."""
2
+
3
+ import sys
4
+
5
+ from .cli import main
6
+
7
+ if __name__ == "__main__": # pragma: no cover
8
+ sys.exit(main())
voohook/cli.py ADDED
@@ -0,0 +1,121 @@
1
+ """voohook command line: `voohook version`, `voohook submodule`,
2
+ the umbrella entries `voohook pre-commit` / `voohook pre-push`,
3
+ and the combined CI validator `voohook --check`.
4
+
5
+ The umbrella is the install target: `.git/hooks/pre-commit` runs
6
+ `exec voohook pre-commit "$@"`, `.git/hooks/pre-push` runs
7
+ `exec voohook pre-push "$@"` — both scripts never need rewriting.
8
+ """
9
+
10
+ import argparse
11
+ import sys
12
+ from pathlib import Path
13
+ from typing import Callable, Optional, Sequence
14
+
15
+ from .core import git as core_git
16
+ from .core.exitcodes import EXIT_CONFIG_ERROR, EXIT_OK
17
+ from .core.output import configure_logging, prefixed
18
+ from .submodule import cli as submodule_cli
19
+ from .submodule import pre_commit as submodule_pre_commit
20
+ from .submodule import pre_push as submodule_pre_push
21
+ from .submodule.config import ConfigError as SubmoduleConfigError
22
+ from .submodule.config import load_config as load_submodule_config
23
+ from .version import cli as version_cli
24
+ from .version import pre_commit as version_pre_commit
25
+
26
+
27
+ def build_parser() -> argparse.ArgumentParser:
28
+ parser = argparse.ArgumentParser(
29
+ prog="voohook",
30
+ description="Git hooks that keep your version and your submodule pins honest.",
31
+ )
32
+ parser.add_argument(
33
+ "--check",
34
+ action="store_true",
35
+ help="CI validator: run both checks, exit 0 only when both pass",
36
+ )
37
+ parser.add_argument(
38
+ "--repo", default=".", help="path inside the target repository (used by --check)"
39
+ )
40
+ parser.add_argument("-v", "--verbose", action="count", default=0, help="debug output")
41
+ parser.add_argument("-q", "--quiet", action="store_true", help="warnings only")
42
+ sub = parser.add_subparsers(dest="command")
43
+ version_parser = sub.add_parser(
44
+ "version", help="branch-driven semver bump (pre-commit)"
45
+ )
46
+ version_cli.add_arguments(version_parser)
47
+ submodule_parser = sub.add_parser(
48
+ "submodule", help="submodule pin enforcement (pre-commit / --push)"
49
+ )
50
+ submodule_cli.add_arguments(submodule_parser)
51
+ sub.add_parser(
52
+ "pre-commit", help="the pre-commit hook: version bump, then submodule verdicts"
53
+ )
54
+ pre_push_parser = sub.add_parser(
55
+ "pre-push", help="the pre-push hook: no dangling submodule commits reach the remote"
56
+ )
57
+ # git passes the destination remote name and URL; accepted, not used
58
+ pre_push_parser.add_argument("push_remote", nargs="*", help=argparse.SUPPRESS)
59
+ return parser
60
+
61
+
62
+ def _first_nonzero(stages: Sequence[Callable[[], int]]) -> int:
63
+ """Run stages in order; the first nonzero exit wins, the rest are skipped."""
64
+ for stage in stages:
65
+ code = stage()
66
+ if code != EXIT_OK:
67
+ return code
68
+ return EXIT_OK
69
+
70
+
71
+ def main(argv: Optional[Sequence[str]] = None) -> int:
72
+ args = build_parser().parse_args(argv)
73
+ configure_logging(quiet=args.quiet, verbose=args.verbose)
74
+
75
+ if args.command == "version":
76
+ return version_cli.run(args)
77
+ if args.command == "submodule":
78
+ return submodule_cli.run(args)
79
+ if args.command == "pre-commit":
80
+ # version first: it writes (bump + git add) — the read-only submodule
81
+ # verdicts must see the index exactly as this commit will carry it
82
+ return _first_nonzero([version_pre_commit, submodule_pre_commit])
83
+ if args.command == "pre-push":
84
+ return _first_nonzero([submodule_pre_push])
85
+
86
+ if args.command is None and not args.check:
87
+ build_parser().print_help()
88
+ return EXIT_CONFIG_ERROR
89
+
90
+ return _combined_check(Path(args.repo))
91
+
92
+
93
+ def _combined_check(repo: Path) -> int:
94
+ """`voohook --check`: the version check, then the submodule check —
95
+ exit 0 only when both pass (the first failure wins, like the umbrella)."""
96
+ try:
97
+ root = core_git.repo_root(repo.resolve())
98
+ except core_git.GitError as exc:
99
+ print(prefixed("voohook", str(exc)), file=sys.stderr)
100
+ return EXIT_CONFIG_ERROR
101
+
102
+ code = version_cli.check_flow(root)
103
+ if code != EXIT_OK:
104
+ return code
105
+
106
+ try:
107
+ sub_cfg = load_submodule_config(None, repo_root=root)
108
+ except (SubmoduleConfigError, core_git.GitError) as exc:
109
+ print(prefixed("voohook", str(exc)), file=sys.stderr)
110
+ return EXIT_CONFIG_ERROR
111
+ if sub_cfg is None:
112
+ return EXIT_OK # nothing pinned: the submodule check passes quietly
113
+ from .submodule.hook import Reporter
114
+
115
+ return submodule_cli.pre_commit_flow(
116
+ sub_cfg, repo=root, reporter=Reporter(quiet=True), check=True
117
+ )
118
+
119
+
120
+ if __name__ == "__main__": # pragma: no cover
121
+ sys.exit(main())
@@ -0,0 +1,20 @@
1
+ """Shared plumbing for both subcommands: git wrappers, config discovery
2
+ and validation helpers, exit codes, logging conventions.
3
+
4
+ Nothing hook-specific lives here: no branch_flow, no submodule verdicts —
5
+ policy belongs to voohook.version and voohook.submodule.
6
+ """
7
+
8
+ from .config import ConfigError, find_config, load_section
9
+ from .exitcodes import EXIT_BLOCKED, EXIT_CONFIG_ERROR, EXIT_OK
10
+ from .git import GitError
11
+
12
+ __all__ = [
13
+ "ConfigError",
14
+ "GitError",
15
+ "find_config",
16
+ "load_section",
17
+ "EXIT_OK",
18
+ "EXIT_BLOCKED",
19
+ "EXIT_CONFIG_ERROR",
20
+ ]
voohook/core/config.py ADDED
@@ -0,0 +1,91 @@
1
+ """Shared configuration plumbing.
2
+
3
+ Both subcommands keep their own schema and validation; what they share is
4
+ the mechanics: the ConfigError type, config-file discovery
5
+ (--config flag → environment variable → well-known names in the repo root),
6
+ dataclass section loading, and the small field validators.
7
+ Everything here is schema-agnostic.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import re
14
+ from dataclasses import fields
15
+ from pathlib import Path
16
+ from typing import Optional, Sequence
17
+
18
+
19
+ class ConfigError(ValueError):
20
+ """Raised on an invalid or missing configuration file."""
21
+
22
+
23
+ VALID_ON_ERROR = ("fail", "warn")
24
+
25
+
26
+ def find_config(
27
+ explicit: Optional[str],
28
+ env_var: str,
29
+ candidates: Sequence[str],
30
+ repo_root: Path,
31
+ ) -> Optional[Path]:
32
+ """Locate a config file: the --config flag, then $env_var, then the
33
+ well-known names in the repository root (first match wins).
34
+
35
+ None means "no file found" — what that implies (run with defaults?
36
+ nothing to do?) is deliberately the caller's decision: the version hook
37
+ falls back to built-in defaults, the submodule hook quietly exits.
38
+ """
39
+ explicit_or_env = explicit or os.environ.get(env_var)
40
+ if explicit_or_env:
41
+ path = Path(explicit_or_env)
42
+ if not path.is_file():
43
+ raise ConfigError(f"config file not found: {path}")
44
+ return path
45
+ for name in candidates:
46
+ path = repo_root / name
47
+ if path.is_file():
48
+ return path
49
+ return None
50
+
51
+
52
+ def load_section(target: object, name: str, raw: dict, where: str) -> None:
53
+ """Fill the dataclass instance ``target`` from the mapping ``raw[name]``.
54
+
55
+ Unknown keys are rejected (config rot must be loud); a non-mapping
56
+ section is an error. Type validation of individual fields stays with the
57
+ caller — the schemas differ per subcommand.
58
+ """
59
+ section = raw.get(name)
60
+ if section is None:
61
+ return
62
+ if not isinstance(section, dict):
63
+ raise ConfigError(f"{where}: {name} must be a mapping")
64
+ known = {f.name for f in fields(target)}
65
+ for key, value in section.items():
66
+ if key not in known:
67
+ raise ConfigError(f"{where}: unknown option '{name}.{key}'")
68
+ setattr(target, key, value)
69
+
70
+
71
+ def require_non_empty_str(value: object, option: str, where: str) -> None:
72
+ if not isinstance(value, str) or not value:
73
+ raise ConfigError(f"{where}: {option} must be a non-empty string")
74
+
75
+
76
+ def require_bool(value: object, option: str, where: str) -> None:
77
+ if not isinstance(value, bool):
78
+ raise ConfigError(f"{where}: {option} must be a boolean")
79
+
80
+
81
+ def require_regex(value: object, option: str, where: str) -> None:
82
+ require_non_empty_str(value, option, where)
83
+ try:
84
+ re.compile(value) # type: ignore[arg-type]
85
+ except re.error as exc:
86
+ raise ConfigError(f"{where}: {option}: {exc}") from exc
87
+
88
+
89
+ def validate_on_error(value: object, option: str, where: str) -> None:
90
+ if value not in VALID_ON_ERROR:
91
+ raise ConfigError(f"{where}: {option} must be one of {list(VALID_ON_ERROR)}")
@@ -0,0 +1,12 @@
1
+ """The exit-code contract shared by every voohook entry point.
2
+
3
+ 0 — fine (warnings allowed);
4
+ 1 — blocked: the hook would rewrite the file, the pin diverged, the branch
5
+ is unknown, or dangling submodule commits would be pushed;
6
+ 2 — usage or configuration problems (bad arguments, not a git repository,
7
+ broken config).
8
+ """
9
+
10
+ EXIT_OK = 0
11
+ EXIT_BLOCKED = 1
12
+ EXIT_CONFIG_ERROR = 2
voohook/core/git.py ADDED
@@ -0,0 +1,230 @@
1
+ """Thin wrappers around the git CLI, shared by both subcommands.
2
+
3
+ Everything here is a faithful subprocess wrapper: no policy, no config
4
+ knowledge, no printing. Errors surface as GitError and the caller decides
5
+ whether that means "block" (exit 1) or "config problem" (exit 2).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import subprocess
11
+ from pathlib import Path
12
+ from typing import List, Optional, Sequence, Tuple
13
+
14
+
15
+ class GitError(RuntimeError):
16
+ """Raised when a git command fails."""
17
+
18
+
19
+ def _git(args: Sequence[str], cwd: Path) -> subprocess.CompletedProcess:
20
+ try:
21
+ return subprocess.run(
22
+ ["git", *args], cwd=str(cwd), capture_output=True, text=True
23
+ )
24
+ except FileNotFoundError as exc: # pragma: no cover - git is virtually always there
25
+ raise GitError("git executable not found") from exc
26
+
27
+
28
+ def git(args: Sequence[str], cwd: Path) -> str:
29
+ """Run git, return stdout, raise GitError with stderr on failure."""
30
+ proc = _git(args, cwd)
31
+ if proc.returncode != 0:
32
+ message = proc.stderr.strip() or proc.stdout.strip() or f"exit code {proc.returncode}"
33
+ raise GitError(f"git {' '.join(args)}: {message}")
34
+ return proc.stdout
35
+
36
+
37
+ # --- repository ---------------------------------------------------------------
38
+
39
+
40
+ def repo_root(cwd: Path) -> Path:
41
+ return Path(git(["rev-parse", "--show-toplevel"], cwd).strip())
42
+
43
+
44
+ def has_remote(cwd: Path, remote: str) -> bool:
45
+ """Whether the remote name exists in this repository."""
46
+ proc = _git(["remote", "get-url", remote], cwd)
47
+ return proc.returncode == 0
48
+
49
+
50
+ def current_branch(cwd: Path) -> Optional[str]:
51
+ """The checked-out branch name, or None for a detached HEAD."""
52
+ proc = _git(["symbolic-ref", "--quiet", "--short", "HEAD"], cwd)
53
+ if proc.returncode != 0:
54
+ return None
55
+ return proc.stdout.strip() or None
56
+
57
+
58
+ def ref_exists(cwd: Path, ref: str) -> bool:
59
+ return _git(["rev-parse", "-q", "--verify", f"{ref}^{{commit}}"], cwd).returncode == 0
60
+
61
+
62
+ def is_merge_in_progress(cwd: Path) -> bool:
63
+ """True while MERGE_HEAD exists — the hooks' skip_merges signal."""
64
+ return _git(["rev-parse", "-q", "--verify", "MERGE_HEAD"], cwd).returncode == 0
65
+
66
+
67
+ # --- remote branches ------------------------------------------------------------
68
+
69
+
70
+ def fetch(cwd: Path, remote: str, branch: str) -> None:
71
+ """Update the remote-tracking ref of the given branch; raises GitError
72
+ when offline or when the remote has no such branch."""
73
+ git(["fetch", "--quiet", remote, branch], cwd)
74
+
75
+
76
+ def ls_remote_heads(cwd: Path, remote: str) -> List[str]:
77
+ """Branch names that exist on the remote right now (one network call)."""
78
+ out = git(["ls-remote", "--heads", remote], cwd)
79
+ return [line.split("refs/heads/", 1)[1] for line in out.splitlines() if "refs/heads/" in line]
80
+
81
+
82
+ def remote_heads_local(cwd: Path, remote: str) -> List[str]:
83
+ """Branch names known from the last fetch (remote-tracking refs), offline mode."""
84
+ out = git(["for-each-ref", "--format=%(refname:short)", f"refs/remotes/{remote}/"], cwd)
85
+ prefix = f"{remote}/"
86
+ return [
87
+ line[len(prefix):]
88
+ for line in out.splitlines()
89
+ if line.startswith(prefix) and line != f"{remote}/HEAD"
90
+ ]
91
+
92
+
93
+ # --- file content at refs and in the index --------------------------------------
94
+
95
+
96
+ def read_file_from_ref(cwd: Path, ref: str, path: str) -> Optional[str]:
97
+ """File content at ``ref:path``, or None if the file does not exist there."""
98
+ proc = _git(["show", f"{ref}:{path}"], cwd)
99
+ if proc.returncode == 0:
100
+ return proc.stdout
101
+ error = proc.stderr or ""
102
+ if "does not exist" in error or "exists on disk, but not in" in error:
103
+ return None
104
+ raise GitError(f"git show {ref}:{path}: {error.strip()}")
105
+
106
+
107
+ def staged_text(cwd: Path, path: str) -> Optional[str]:
108
+ """Content of ``path`` in the index, or None if the path is not tracked."""
109
+ if not git(["ls-files", "--", path], cwd).strip():
110
+ return None
111
+ return git(["show", f":{path}"], cwd)
112
+
113
+
114
+ def stage(cwd: Path, path: str) -> None:
115
+ git(["add", "--", path], cwd)
116
+
117
+
118
+ # --- submodule plumbing -----------------------------------------------------------
119
+
120
+
121
+ def index_gitlink(cwd: Path, path: str) -> Optional[Tuple[str, str]]:
122
+ """(mode, sha) of the stage-0 index entry at exactly ``path``, or None."""
123
+ out = git(["ls-files", "-s", "--", path], cwd)
124
+ for line in out.splitlines():
125
+ meta, _, entry_path = line.partition("\t")
126
+ if entry_path != path:
127
+ continue
128
+ parts = meta.split()
129
+ if len(parts) == 3 and parts[2] == "0":
130
+ return parts[0], parts[1]
131
+ return None
132
+
133
+
134
+ def tree_gitlink(cwd: Path, ref: str, path: str) -> Optional[Tuple[str, str]]:
135
+ """(mode, sha) of the entry at ``path`` in the tree of ``ref``, or None."""
136
+ out = git(["ls-tree", ref, "--", path], cwd)
137
+ for line in out.splitlines():
138
+ meta, _, entry_path = line.partition("\t")
139
+ if entry_path != path:
140
+ continue
141
+ parts = meta.split()
142
+ if len(parts) == 3:
143
+ return parts[0], parts[2]
144
+ return None
145
+
146
+
147
+ def submodule_checkout(cwd: Path, path: str) -> Optional[Tuple[str, str]]:
148
+ """(status_char, sha) from `git submodule status`, or None when unavailable.
149
+
150
+ status_char: ' ' in sync with the index, '+' checkout differs,
151
+ '-' not initialized, 'U' in conflict.
152
+ """
153
+ proc = _git(["submodule", "status", "--", path], cwd)
154
+ if proc.returncode != 0:
155
+ return None
156
+ lines = proc.stdout.splitlines()
157
+ if not lines or not lines[0].strip():
158
+ return None
159
+ line = lines[0]
160
+ if line[0] in (" ", "+", "-", "U"):
161
+ flag, rest = line[0], line[1:]
162
+ else: # no prefix character: in sync
163
+ flag, rest = " ", line
164
+ parts = rest.split()
165
+ if not parts:
166
+ return None
167
+ return flag, parts[0]
168
+
169
+
170
+ def rev_list_touching(cwd: Path, base: Optional[str], tip: str, path: str) -> List[str]:
171
+ """Commits in `base..tip` whose trees change `path`; with base=None the
172
+ range is `tip --not --remotes` (commits no remote-tracking ref knows)."""
173
+ args = ["rev-list", tip]
174
+ if base is not None:
175
+ args.append(f"^{base}")
176
+ else:
177
+ args += ["--not", "--remotes"]
178
+ args += ["--", path]
179
+ return [line for line in git(args, cwd).splitlines() if line]
180
+
181
+
182
+ def sub_fetch(repo: Path, folder: str) -> Optional[bool]:
183
+ """Fetch the submodule's own remote to refresh its remote-tracking refs.
184
+
185
+ True: fetched; False: fetch failed (offline); None: the submodule is not
186
+ initialized or has no remotes at all — nothing to verify against.
187
+ """
188
+ sub = repo / folder
189
+ if not (sub / ".git").exists():
190
+ return None
191
+ try:
192
+ remotes = git(["remote"], sub).split()
193
+ except GitError:
194
+ return None
195
+ if not remotes:
196
+ return None
197
+ remote = "origin" if "origin" in remotes else remotes[0]
198
+ try:
199
+ git(["fetch", "--quiet", remote], sub)
200
+ return True
201
+ except GitError:
202
+ return False
203
+
204
+
205
+ def sub_remote_contains(
206
+ repo: Path, folder: str, sha: str, fetched: Optional[bool]
207
+ ) -> Optional[bool]:
208
+ """Does any remote branch of the submodule contain `sha`?
209
+
210
+ None means "cannot determine" (uninitialized submodule, or offline with
211
+ no usable refs) — the caller fails open with a warning.
212
+ """
213
+ if fetched is None:
214
+ return None
215
+ sub = repo / folder
216
+ if not (sub / ".git").exists():
217
+ return None
218
+ known = _git(["rev-parse", "-q", "--verify", f"{sha}^{{commit}}"], sub).returncode == 0
219
+ if not known:
220
+ # after a successful fetch an unknown sha is genuinely not on the remote
221
+ return False if fetched else None
222
+ try:
223
+ out = git(["branch", "-r", "--contains", sha], sub)
224
+ except GitError:
225
+ return None
226
+ if out.strip():
227
+ return True
228
+ if not fetched and not git(["for-each-ref", "refs/remotes/"], sub).strip():
229
+ return None # no remote refs at all: nothing to judge by
230
+ return False
voohook/core/output.py ADDED
@@ -0,0 +1,23 @@
1
+ """Consistent human-facing output across both subcommands.
2
+
3
+ Human logs go to stderr (stdout stays clean for --json and --graph output);
4
+ messages are prefixed with the subcommand name ("voohook: …") so hook output
5
+ is attributable when several hooks run in one commit.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+
12
+
13
+ def configure_logging(quiet: bool, verbose: int) -> None:
14
+ """INFO by default, DEBUG with -v, WARNING with -q; plain messages."""
15
+ level = logging.WARNING if quiet else (logging.DEBUG if verbose else logging.INFO)
16
+ # force=True: the last word is ours even when pytest or another hook
17
+ # configured the root logger first
18
+ logging.basicConfig(level=level, format="%(message)s", force=True)
19
+
20
+
21
+ def prefixed(prog: str, message: str) -> str:
22
+ """The one-line message shape every voohook entry point uses."""
23
+ return f"{prog}: {message}"
@@ -0,0 +1,64 @@
1
+ """Submodule pin enforcement (port of submodule-hook onto voohook.core).
2
+
3
+ Read-only: verifies env.yml pins against the index and the remote,
4
+ blocks on divergence, never rewrites anything. Surfaces as
5
+ `voohook submodule` and as the second stage of the `voohook pre-commit`
6
+ umbrella (plus the whole `voohook pre-push` umbrella).
7
+ """
8
+
9
+ import logging
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ from ..core import git as gittools
14
+ from ..core.exitcodes import EXIT_CONFIG_ERROR, EXIT_OK
15
+ from .cli import pre_commit_flow, push_flow
16
+ from .config import AppConfig, ConfigError, load_config
17
+ from .hook import Reporter, run_hook, run_push_hook # noqa: F401 (re-exports)
18
+
19
+ log = logging.getLogger("voohook")
20
+
21
+ __all__ = [
22
+ "AppConfig",
23
+ "ConfigError",
24
+ "Reporter",
25
+ "load_config",
26
+ "pre_commit",
27
+ "pre_push",
28
+ "run_hook",
29
+ "run_push_hook",
30
+ ]
31
+
32
+
33
+ def _load(repo_cwd: Path):
34
+ """(root, cfg|None) for the umbrella; config problems exit 2."""
35
+ root = gittools.repo_root(repo_cwd)
36
+ return root, load_config(None, repo_root=root)
37
+
38
+
39
+ def pre_commit() -> int:
40
+ """The submodule stage of the pre-commit umbrella: read-only pin verdicts.
41
+
42
+ No config / no submodules section is a quiet 0 — the umbrella must not
43
+ punish repositories that simply pin nothing.
44
+ """
45
+ try:
46
+ root, cfg = _load(Path("."))
47
+ except (ConfigError, gittools.GitError) as exc:
48
+ print(f"voohook: {exc}", file=sys.stderr)
49
+ return EXIT_CONFIG_ERROR
50
+ if cfg is None:
51
+ return EXIT_OK
52
+ return pre_commit_flow(cfg, repo=root, reporter=Reporter())
53
+
54
+
55
+ def pre_push() -> int:
56
+ """The pre-push umbrella: no dangling submodule commits reach the remote."""
57
+ try:
58
+ root, cfg = _load(Path("."))
59
+ except (ConfigError, gittools.GitError) as exc:
60
+ print(f"voohook: {exc}", file=sys.stderr)
61
+ return EXIT_CONFIG_ERROR
62
+ if cfg is None:
63
+ return EXIT_OK
64
+ return push_flow(cfg, repo=root, reporter=Reporter())