polyctl 0.7.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.
- polyctl/__init__.py +7 -0
- polyctl/__main__.py +5 -0
- polyctl/a2a.py +226 -0
- polyctl/a2a_mcp.py +546 -0
- polyctl/acp.py +417 -0
- polyctl/adapters/README.md +101 -0
- polyctl/adapters/aider.json +32 -0
- polyctl/adapters/amazon-q.json +15 -0
- polyctl/adapters/amp.json +16 -0
- polyctl/adapters/antigravity.json +120 -0
- polyctl/adapters/claude-code.json +229 -0
- polyctl/adapters/cloud-generic.json +57 -0
- polyctl/adapters/codex.json +47 -0
- polyctl/adapters/command-code.json +45 -0
- polyctl/adapters/copilot.json +17 -0
- polyctl/adapters/cursor-agent.json +29 -0
- polyctl/adapters/deepseek.json +13 -0
- polyctl/adapters/droid.json +34 -0
- polyctl/adapters/gemini.json +30 -0
- polyctl/adapters/grok.json +22 -0
- polyctl/adapters/hermes.json +34 -0
- polyctl/adapters/kilocode.json +30 -0
- polyctl/adapters/kimi.json +23 -0
- polyctl/adapters/kiro.json +332 -0
- polyctl/adapters/ollama.json +29 -0
- polyctl/adapters/omp.json +34 -0
- polyctl/adapters/openai-api.json +68 -0
- polyctl/adapters/opencode.json +162 -0
- polyctl/adapters/pi.json +24 -0
- polyctl/adapters/pr-agent.json +54 -0
- polyctl/adapters/profiles.json +9 -0
- polyctl/adapters/qoder.json +163 -0
- polyctl/adapters/qwen.json +27 -0
- polyctl/adapters/reasonix.json +25 -0
- polyctl/adapters/rewriters/rtk.json +24 -0
- polyctl/adapters/trae.json +31 -0
- polyctl/adapters/vendors.json +42 -0
- polyctl/adapters/warp.json +88 -0
- polyctl/allowlist.py +1756 -0
- polyctl/api_review.py +920 -0
- polyctl/cli.py +835 -0
- polyctl/conformance_harness.py +9 -0
- polyctl/demo.py +503 -0
- polyctl/drivers.py +146 -0
- polyctl/email.py +160 -0
- polyctl/features.py +98 -0
- polyctl/journal.py +144 -0
- polyctl/language.py +945 -0
- polyctl/lib.py +1296 -0
- polyctl/matrix.py +660 -0
- polyctl/mcp.py +1362 -0
- polyctl/ntfy.py +169 -0
- polyctl/outbound.py +39 -0
- polyctl/parts/__init__.py +5 -0
- polyctl/parts/cli_authority.py +2615 -0
- polyctl/parts/cli_channels.py +1325 -0
- polyctl/parts/cli_checks.py +2293 -0
- polyctl/parts/cli_completion.py +686 -0
- polyctl/parts/cli_evidence.py +141 -0
- polyctl/parts/cli_gain.py +375 -0
- polyctl/parts/cli_harness.py +392 -0
- polyctl/parts/cli_hooks.py +1816 -0
- polyctl/parts/cli_install.py +638 -0
- polyctl/parts/cli_lanes.py +106 -0
- polyctl/parts/cli_maintenance.py +2536 -0
- polyctl/parts/cli_next.py +248 -0
- polyctl/parts/cli_pr.py +53 -0
- polyctl/parts/cli_project.py +2857 -0
- polyctl/parts/cli_review.py +5158 -0
- polyctl/parts/cli_status.py +898 -0
- polyctl/parts/lib_adapters.py +2933 -0
- polyctl/parts/lib_alarms.py +2106 -0
- polyctl/parts/lib_events.py +224 -0
- polyctl/parts/lib_evidence.py +412 -0
- polyctl/parts/lib_gates.py +2099 -0
- polyctl/parts/lib_lanes.py +829 -0
- polyctl/parts/lib_mail.py +1541 -0
- polyctl/parts/lib_next.py +652 -0
- polyctl/parts/lib_pr.py +331 -0
- polyctl/parts/lib_slices.py +3337 -0
- polyctl/parts/lib_state.py +2415 -0
- polyctl/parts/lib_transcript.py +4118 -0
- polyctl/pressure.py +325 -0
- polyctl/prices.json +47 -0
- polyctl/procs.py +1194 -0
- polyctl/settings.py +505 -0
- polyctl/skill/SKILL.md +365 -0
- polyctl/skillkit.py +503 -0
- polyctl/storage.py +2055 -0
- polyctl/telegram.py +327 -0
- polyctl/tiers.py +123 -0
- polyctl/verdicts.py +41 -0
- polyctl/watchdog.py +3887 -0
- polyctl/web.py +337 -0
- polyctl-0.7.0.dist-info/METADATA +235 -0
- polyctl-0.7.0.dist-info/RECORD +99 -0
- polyctl-0.7.0.dist-info/WHEEL +4 -0
- polyctl-0.7.0.dist-info/entry_points.txt +5 -0
- polyctl-0.7.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,1816 @@
|
|
|
1
|
+
"""Hooks: rendering, classifying, installing, probing and removing polyctl's git hooks, and push.
|
|
2
|
+
|
|
3
|
+
A part of src/polyctl/cli.py (#44): moved out byte for byte and run in its namespace by `_part`,
|
|
4
|
+
where it stood; it is not importable on its own.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
# Exact bodies emitted before AO53. They remain as a deliberately narrow legacy
|
|
9
|
+
# grammar: callers and old tests may still render them, but new installs never do.
|
|
10
|
+
PRE_COMMIT_HOOK = """#!/bin/sh
|
|
11
|
+
# polyctl: commit authority is bound to Git's exact active index.
|
|
12
|
+
exec {polyctl} -C {root} commit-check
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
PRE_PUSH_HOOK = """#!/bin/sh
|
|
16
|
+
# polyctl: push is a human decision. Allowed when a person ran
|
|
17
|
+
# `polyctl push allow` in the last 30 minutes for this repository; refused otherwise.
|
|
18
|
+
exec {polyctl} -C {root} push check
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
_HOOK_ROLES = ("pre-commit", "pre-push")
|
|
22
|
+
_HOOK_REPOSITORY_ENV = {
|
|
23
|
+
"GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_COMMON_DIR", "GIT_PREFIX",
|
|
24
|
+
"GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_CONFIG",
|
|
25
|
+
"GIT_CONFIG_PARAMETERS", "GIT_CONFIG_COUNT", "GIT_CONFIG_GLOBAL",
|
|
26
|
+
"GIT_CONFIG_SYSTEM", "GIT_CONFIG_NOSYSTEM", "GIT_CEILING_DIRECTORIES",
|
|
27
|
+
"GIT_DISCOVERY_ACROSS_FILESYSTEM", "GIT_LITERAL_PATHSPECS",
|
|
28
|
+
"GIT_GLOB_PATHSPECS", "GIT_NOGLOB_PATHSPECS", "GIT_ICASE_PATHSPECS",
|
|
29
|
+
}
|
|
30
|
+
_CURRENT_STATES = {
|
|
31
|
+
"current-local (behavior unverified)",
|
|
32
|
+
"current-scoped (behavior unverified)",
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class _HookResolutionError(RuntimeError):
|
|
37
|
+
pass
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _hook_git_env():
|
|
41
|
+
"""A copied environment without inherited repository/config/pathspec binding."""
|
|
42
|
+
env = os.environ.copy()
|
|
43
|
+
for key in list(env):
|
|
44
|
+
if key in _HOOK_REPOSITORY_ENV or key.startswith("GIT_CONFIG_KEY_") \
|
|
45
|
+
or key.startswith("GIT_CONFIG_VALUE_"):
|
|
46
|
+
env.pop(key, None)
|
|
47
|
+
return env
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _hook_git(cwd, *args, timeout=15, extra_env=None, bound=True):
|
|
51
|
+
"""Run one literal-path Git query without a shell; return the byte result.
|
|
52
|
+
|
|
53
|
+
Git leads a process group of its own, so a timeout stops it with whatever it started: the hook
|
|
54
|
+
`git hook run` runs for the execution proof ran on after Git alone was killed, and held the
|
|
55
|
+
pipes this reads (LEADS-GATE).
|
|
56
|
+
"""
|
|
57
|
+
env = _hook_git_env()
|
|
58
|
+
if bound:
|
|
59
|
+
env = A.bound_git_environment(env)
|
|
60
|
+
if extra_env:
|
|
61
|
+
env.update(extra_env)
|
|
62
|
+
try:
|
|
63
|
+
return A.run_as_group(
|
|
64
|
+
[A.git_binary(), "--literal-pathspecs", "-C", str(cwd), *args], timeout,
|
|
65
|
+
env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
|
66
|
+
)
|
|
67
|
+
except (OSError, subprocess.TimeoutExpired) as exc:
|
|
68
|
+
left, unasked = getattr(exc, "left", None), getattr(exc, "unasked", None)
|
|
69
|
+
raise _HookResolutionError(
|
|
70
|
+
f"git query failed: {exc}"
|
|
71
|
+
+ (f"; {len(left)} process(es) it started still run after it was stopped: {left}" if left else "")
|
|
72
|
+
+ (f"; {unasked}" if unasked else "")
|
|
73
|
+
) from exc
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _hook_output_path(result, label):
|
|
77
|
+
if result.returncode:
|
|
78
|
+
detail = result.stderr.decode(UTF8, "replace").strip()[:160]
|
|
79
|
+
raise _HookResolutionError(f"{label} failed: {detail or 'git exit ' + str(result.returncode)}")
|
|
80
|
+
raw = result.stdout[:-1] if result.stdout.endswith(b"\n") else result.stdout
|
|
81
|
+
if not raw:
|
|
82
|
+
raise _HookResolutionError(f"{label} returned an empty path")
|
|
83
|
+
return os.fsdecode(raw)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _hook_real(top, value):
|
|
87
|
+
value = os.path.expanduser(value)
|
|
88
|
+
if not os.path.isabs(value):
|
|
89
|
+
value = os.path.join(top, value)
|
|
90
|
+
return os.path.realpath(os.path.abspath(value))
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _hook_contains(parent, child):
|
|
94
|
+
try:
|
|
95
|
+
return os.path.commonpath([os.path.realpath(parent), os.path.realpath(child)]) \
|
|
96
|
+
== os.path.realpath(parent)
|
|
97
|
+
except (OSError, ValueError):
|
|
98
|
+
return False
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _parse_hooks_config(result):
|
|
102
|
+
"""Parse exactly scope/origin/value, preserving empty values and separators."""
|
|
103
|
+
if result.returncode == 1 and not result.stdout:
|
|
104
|
+
return {"set": False, "scope": None, "origin": None, "value": None}
|
|
105
|
+
if result.returncode:
|
|
106
|
+
detail = result.stderr.decode(UTF8, "replace").strip()[:160]
|
|
107
|
+
raise _HookResolutionError(
|
|
108
|
+
f"core.hooksPath query failed: {detail or 'git exit ' + str(result.returncode)}"
|
|
109
|
+
)
|
|
110
|
+
fields = result.stdout.split(b"\0")
|
|
111
|
+
if len(fields) != 4 or fields[-1] != b"":
|
|
112
|
+
raise _HookResolutionError("core.hooksPath output is not three NUL-terminated fields")
|
|
113
|
+
try:
|
|
114
|
+
scope, origin, value = (os.fsdecode(field) for field in fields[:3])
|
|
115
|
+
except UnicodeError as exc:
|
|
116
|
+
raise _HookResolutionError(f"core.hooksPath output is undecodable: {exc}") from exc
|
|
117
|
+
if not scope or not origin:
|
|
118
|
+
raise _HookResolutionError("core.hooksPath output has an empty scope/origin")
|
|
119
|
+
return {"set": True, "scope": scope, "origin": origin, "value": value}
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _hooks_config(top):
|
|
123
|
+
return _parse_hooks_config(_hook_git(
|
|
124
|
+
top, "config", "--null", "--show-origin", "--show-scope", "--get",
|
|
125
|
+
"core.hooksPath",
|
|
126
|
+
))
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _parse_worktrees(raw):
|
|
130
|
+
rows = []
|
|
131
|
+
for block in raw.decode(UTF8, "surrogateescape").strip().split("\n\n"):
|
|
132
|
+
if not block.strip():
|
|
133
|
+
continue
|
|
134
|
+
row = {"path": None, "bare": False, "porcelain_locked": False}
|
|
135
|
+
for line in block.splitlines():
|
|
136
|
+
key, _, value = line.partition(" ")
|
|
137
|
+
if key == "worktree":
|
|
138
|
+
row["path"] = value
|
|
139
|
+
elif key == "bare":
|
|
140
|
+
row["bare"] = True
|
|
141
|
+
elif key == "locked":
|
|
142
|
+
row["porcelain_locked"] = True
|
|
143
|
+
if row["path"]:
|
|
144
|
+
rows.append(row)
|
|
145
|
+
return rows
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _worktree_admins(common_dir):
|
|
149
|
+
"""Return regular admin records; a symlink/unreadable record is unknowable."""
|
|
150
|
+
base = os.path.join(common_dir, "worktrees")
|
|
151
|
+
records, unknown = [], []
|
|
152
|
+
if not os.path.isdir(base):
|
|
153
|
+
return records, unknown
|
|
154
|
+
try:
|
|
155
|
+
names = sorted(os.listdir(base))
|
|
156
|
+
except OSError:
|
|
157
|
+
return records, [base]
|
|
158
|
+
for name in names:
|
|
159
|
+
admin = os.path.join(base, name)
|
|
160
|
+
if os.path.islink(admin) or not os.path.isdir(admin):
|
|
161
|
+
unknown.append(admin)
|
|
162
|
+
continue
|
|
163
|
+
gitdir_file = os.path.join(admin, "gitdir")
|
|
164
|
+
try:
|
|
165
|
+
if os.path.islink(gitdir_file) or not os.path.isfile(gitdir_file):
|
|
166
|
+
raise OSError("gitdir is not a regular file")
|
|
167
|
+
marker = open(gitdir_file, "rb").read().decode(UTF8, "surrogateescape").strip()
|
|
168
|
+
except (OSError, UnicodeError):
|
|
169
|
+
unknown.append(admin)
|
|
170
|
+
continue
|
|
171
|
+
if not marker:
|
|
172
|
+
unknown.append(admin)
|
|
173
|
+
continue
|
|
174
|
+
marker = os.path.abspath(marker)
|
|
175
|
+
worktree = os.path.dirname(marker) if os.path.basename(marker) == ".git" else None
|
|
176
|
+
if not worktree:
|
|
177
|
+
unknown.append(admin)
|
|
178
|
+
continue
|
|
179
|
+
records.append({
|
|
180
|
+
"name": name,
|
|
181
|
+
"admin": os.path.realpath(admin),
|
|
182
|
+
"worktree": os.path.realpath(worktree),
|
|
183
|
+
"locked": os.path.isfile(os.path.join(admin, "locked"))
|
|
184
|
+
and not os.path.islink(os.path.join(admin, "locked")),
|
|
185
|
+
})
|
|
186
|
+
return records, unknown
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _worktree_facts(top, common_dir):
|
|
190
|
+
result = _hook_git(top, "worktree", "list", "--porcelain")
|
|
191
|
+
if result.returncode:
|
|
192
|
+
detail = result.stderr.decode(UTF8, "replace").strip()[:160]
|
|
193
|
+
raise _HookResolutionError(f"git worktree list failed: {detail or result.returncode}")
|
|
194
|
+
rows = _parse_worktrees(result.stdout)
|
|
195
|
+
admins, unknown = _worktree_admins(common_dir)
|
|
196
|
+
if unknown:
|
|
197
|
+
raise _HookResolutionError("unknown worktree admin: " + ", ".join(unknown[:3]))
|
|
198
|
+
by_path = {row["worktree"]: row for row in admins}
|
|
199
|
+
facts = []
|
|
200
|
+
for row in rows:
|
|
201
|
+
path = os.path.realpath(row["path"])
|
|
202
|
+
fact = {"path": path, "bare": row["bare"], "admin": None,
|
|
203
|
+
"status": "reachable", "effective_dir": None, "config": None}
|
|
204
|
+
if row["bare"]:
|
|
205
|
+
facts.append(fact)
|
|
206
|
+
continue
|
|
207
|
+
marker = os.path.join(path, ".git")
|
|
208
|
+
admin = by_path.get(path)
|
|
209
|
+
if os.path.isdir(path) and os.path.lexists(marker):
|
|
210
|
+
fact["status"] = "reachable"
|
|
211
|
+
if admin:
|
|
212
|
+
fact["admin"] = admin["admin"]
|
|
213
|
+
elif admin:
|
|
214
|
+
fact["admin"] = admin["admin"]
|
|
215
|
+
fact["status"] = "locked" if admin["locked"] else "stale"
|
|
216
|
+
else:
|
|
217
|
+
fact["status"] = "unknown"
|
|
218
|
+
facts.append(fact)
|
|
219
|
+
known = {fact["path"] for fact in facts}
|
|
220
|
+
for admin in admins:
|
|
221
|
+
if admin["worktree"] not in known:
|
|
222
|
+
facts.append({
|
|
223
|
+
"path": admin["worktree"], "bare": False,
|
|
224
|
+
"admin": admin["admin"],
|
|
225
|
+
"status": "locked" if admin["locked"] else "stale",
|
|
226
|
+
"effective_dir": None, "config": None,
|
|
227
|
+
})
|
|
228
|
+
if any(f["status"] == "unknown" for f in facts):
|
|
229
|
+
raise _HookResolutionError("unknown worktree record prevents safe hook mutation")
|
|
230
|
+
for fact in facts:
|
|
231
|
+
if fact["status"] != "reachable" or fact["bare"]:
|
|
232
|
+
continue
|
|
233
|
+
wt_top = _hook_output_path(
|
|
234
|
+
_hook_git(fact["path"], "rev-parse", "--show-toplevel"),
|
|
235
|
+
"worktree --show-toplevel",
|
|
236
|
+
)
|
|
237
|
+
wt_top = _hook_real(fact["path"], wt_top)
|
|
238
|
+
fact["effective_dir"] = _hook_real(
|
|
239
|
+
wt_top,
|
|
240
|
+
_hook_output_path(_hook_git(wt_top, "rev-parse", "--git-path", "hooks"),
|
|
241
|
+
"worktree --git-path hooks"),
|
|
242
|
+
)
|
|
243
|
+
fact["config"] = _hooks_config(wt_top)
|
|
244
|
+
return facts, admins
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _hook_directory_class(path, top, git_dir, common_dir, facts, config=None):
|
|
248
|
+
path = os.path.realpath(path)
|
|
249
|
+
hits = sum(
|
|
250
|
+
1 for fact in facts
|
|
251
|
+
if fact.get("effective_dir") and os.path.realpath(fact["effective_dir"]) == path
|
|
252
|
+
)
|
|
253
|
+
live_family = sum(1 for fact in facts if fact["status"] != "stale")
|
|
254
|
+
unavailable = any(fact["status"] in ("locked", "unknown") for fact in facts)
|
|
255
|
+
common_hooks = os.path.realpath(os.path.join(common_dir, "hooks"))
|
|
256
|
+
absolute_config = bool(config and config.get("set") and os.path.isabs(config.get("value") or ""))
|
|
257
|
+
if hits >= 2 or (path == common_hooks and live_family > 1) \
|
|
258
|
+
or (absolute_config and unavailable and hits):
|
|
259
|
+
return "shared"
|
|
260
|
+
if _hook_contains(top, path) or _hook_contains(git_dir, path):
|
|
261
|
+
return "project-local"
|
|
262
|
+
return "external"
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _structural_roots(path):
|
|
266
|
+
roots, current = [], os.path.abspath(os.path.dirname(path))
|
|
267
|
+
while True:
|
|
268
|
+
if os.path.lexists(os.path.join(current, ".git")):
|
|
269
|
+
roots.append(current)
|
|
270
|
+
parent = os.path.dirname(current)
|
|
271
|
+
if parent == current:
|
|
272
|
+
break
|
|
273
|
+
current = parent
|
|
274
|
+
return roots
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _hook_track_state(path):
|
|
278
|
+
"""Literal tracked/untracked measurement across every enclosing worktree."""
|
|
279
|
+
exists = os.path.lexists(path)
|
|
280
|
+
measured = []
|
|
281
|
+
seen = set()
|
|
282
|
+
for candidate in _structural_roots(path):
|
|
283
|
+
try:
|
|
284
|
+
result = _hook_git(candidate, "rev-parse", "--show-toplevel")
|
|
285
|
+
except _HookResolutionError:
|
|
286
|
+
measured.append("indeterminate")
|
|
287
|
+
continue
|
|
288
|
+
if result.returncode or not result.stdout:
|
|
289
|
+
measured.append("indeterminate")
|
|
290
|
+
continue
|
|
291
|
+
try:
|
|
292
|
+
top = _hook_real(candidate, _hook_output_path(result, "--show-toplevel"))
|
|
293
|
+
except _HookResolutionError:
|
|
294
|
+
measured.append("indeterminate")
|
|
295
|
+
continue
|
|
296
|
+
if top in seen or not _hook_contains(top, path):
|
|
297
|
+
continue
|
|
298
|
+
seen.add(top)
|
|
299
|
+
rel = os.path.relpath(path, top)
|
|
300
|
+
try:
|
|
301
|
+
result = _hook_git(top, "ls-files", "--error-unmatch", "--", rel)
|
|
302
|
+
except _HookResolutionError:
|
|
303
|
+
measured.append("indeterminate")
|
|
304
|
+
continue
|
|
305
|
+
if result.returncode == 0:
|
|
306
|
+
measured.append("tracked")
|
|
307
|
+
elif result.returncode == 1:
|
|
308
|
+
measured.append("untracked")
|
|
309
|
+
else:
|
|
310
|
+
measured.append("indeterminate")
|
|
311
|
+
if "tracked" in measured:
|
|
312
|
+
return "tracked"
|
|
313
|
+
if "indeterminate" in measured:
|
|
314
|
+
return "indeterminate"
|
|
315
|
+
if measured:
|
|
316
|
+
return "untracked"
|
|
317
|
+
return "indeterminate" if exists else "unobserved"
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _role_command(role):
|
|
321
|
+
return "commit-check" if role == "pre-commit" else "push check"
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def _render_v2_local_hook(role, root_rel):
|
|
325
|
+
"""Exact project-local body emitted before tracked project enrollment."""
|
|
326
|
+
import shlex
|
|
327
|
+
suffix = "" if root_rel in ("", ".") else "/" + shlex.quote(root_rel)
|
|
328
|
+
command = _role_command(role)
|
|
329
|
+
return (
|
|
330
|
+
"#!/bin/sh\n"
|
|
331
|
+
f"# polyctl: polyctl-hook-v2 role={role} binding=project-local\n"
|
|
332
|
+
"initial_cwd=$(CDPATH= cd -- . && pwd -P)\n"
|
|
333
|
+
f"root=\"$initial_cwd\"{suffix}\n"
|
|
334
|
+
"[ -d \"$root/.polyctl\" ] || exit 0\n"
|
|
335
|
+
"case ${GIT_INDEX_FILE-} in\n"
|
|
336
|
+
" \"\"|/*) ;;\n"
|
|
337
|
+
" *) GIT_INDEX_FILE=\"$initial_cwd/$GIT_INDEX_FILE\"; export GIT_INDEX_FILE ;;\n"
|
|
338
|
+
"esac\n"
|
|
339
|
+
"unset GIT_DIR GIT_WORK_TREE GIT_COMMON_DIR GIT_PREFIX "
|
|
340
|
+
"GIT_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES\n"
|
|
341
|
+
"polyctl=$(command -v polyctl) || { echo 'polyctl: polyctl not found' >&2; exit 1; }\n"
|
|
342
|
+
f"exec \"$polyctl\" -C \"$root\" {command}\n"
|
|
343
|
+
).encode(UTF8)
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def _render_v2_scoped_hook(role, root_rel, family, directory_class):
|
|
347
|
+
"""Exact shared/external body emitted before tracked project enrollment."""
|
|
348
|
+
import shlex
|
|
349
|
+
suffix = "" if root_rel in ("", ".") else "/" + shlex.quote(root_rel)
|
|
350
|
+
command = _role_command(role)
|
|
351
|
+
return (
|
|
352
|
+
"#!/bin/sh\n"
|
|
353
|
+
f"# polyctl: polyctl-hook-v2 role={role} binding={directory_class}\n"
|
|
354
|
+
"initial_cwd=$(CDPATH= cd -- . && pwd -P)\n"
|
|
355
|
+
"case ${GIT_INDEX_FILE-} in\n"
|
|
356
|
+
" \"\"|/*) ;;\n"
|
|
357
|
+
" *) GIT_INDEX_FILE=\"$initial_cwd/$GIT_INDEX_FILE\"; export GIT_INDEX_FILE ;;\n"
|
|
358
|
+
"esac\n"
|
|
359
|
+
"unset GIT_DIR GIT_WORK_TREE GIT_COMMON_DIR GIT_PREFIX "
|
|
360
|
+
"GIT_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES\n"
|
|
361
|
+
"common=$(git --literal-pathspecs rev-parse --git-common-dir 2>/dev/null) || exit 0\n"
|
|
362
|
+
"case $common in /*) ;; *) common=\"$initial_cwd/$common\" ;; esac\n"
|
|
363
|
+
"common=$(CDPATH= cd \"$common\" 2>/dev/null && pwd -P) || exit 0\n"
|
|
364
|
+
f"expected={shlex.quote(os.path.realpath(family))}\n"
|
|
365
|
+
"[ \"$common\" = \"$expected\" ] || exit 0\n"
|
|
366
|
+
"top=$(git --literal-pathspecs rev-parse --show-toplevel 2>/dev/null) || exit 0\n"
|
|
367
|
+
"case $top in /*) ;; *) top=\"$initial_cwd/$top\" ;; esac\n"
|
|
368
|
+
"top=$(CDPATH= cd \"$top\" 2>/dev/null && pwd -P) || exit 0\n"
|
|
369
|
+
f"root=\"$top\"{suffix}\n"
|
|
370
|
+
"[ -d \"$root/.polyctl\" ] || exit 0\n"
|
|
371
|
+
"polyctl=$(command -v polyctl) || { echo 'polyctl: polyctl not found' >&2; exit 1; }\n"
|
|
372
|
+
f"exec \"$polyctl\" -C \"$root\" {command}\n"
|
|
373
|
+
).encode(UTF8)
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _hook_repository_unset():
|
|
377
|
+
return (
|
|
378
|
+
"unset GIT_DIR GIT_WORK_TREE GIT_COMMON_DIR GIT_PREFIX "
|
|
379
|
+
"GIT_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES "
|
|
380
|
+
"GIT_CONFIG GIT_CONFIG_PARAMETERS GIT_CONFIG_COUNT GIT_CONFIG_GLOBAL "
|
|
381
|
+
"GIT_CONFIG_SYSTEM GIT_CONFIG_NOSYSTEM GIT_CEILING_DIRECTORIES "
|
|
382
|
+
"GIT_DISCOVERY_ACROSS_FILESYSTEM GIT_LITERAL_PATHSPECS GIT_GLOB_PATHSPECS "
|
|
383
|
+
"GIT_NOGLOB_PATHSPECS GIT_ICASE_PATHSPECS\n"
|
|
384
|
+
)
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def _hook_project_marker_guard():
|
|
388
|
+
"""The guard of a v3 and a v4 hook, kept so that each reads as legacy and `polyctl hooks install` replaces it (LEADS-GATE)."""
|
|
389
|
+
return (
|
|
390
|
+
"if ! git --literal-pathspecs -C \"$root\" ls-files --error-unmatch -- "
|
|
391
|
+
".polyctl-project >/dev/null 2>&1 &&\n"
|
|
392
|
+
" ! git --literal-pathspecs -C \"$root\" cat-file -e "
|
|
393
|
+
"HEAD:.polyctl-project 2>/dev/null; then\n"
|
|
394
|
+
" exit 0\n"
|
|
395
|
+
"fi\n"
|
|
396
|
+
)
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def _hook_enrollment_guard(top, root_rel, *, check_record=True):
|
|
400
|
+
"""The lines that let a hook stand aside: only where Git, asked at `top`, the shell variable naming the top of the
|
|
401
|
+
working tree, answers that the project's .polyctl-project is neither in the index nor in HEAD (LEADS-GATE).
|
|
402
|
+
|
|
403
|
+
The v4 guard stood aside whenever both its queries failed, and they fail for more than a marker
|
|
404
|
+
that is not there. A project in a subdirectory whose directory an agent moved away failed both,
|
|
405
|
+
and so did one whose marker's deletion was staged: `HEAD:.polyctl-project` names a marker at the top
|
|
406
|
+
of the repository, not in the project's directory. Either way the hook let the commit through
|
|
407
|
+
unchecked. The marker is now asked for by its path from the top, which is there whatever became
|
|
408
|
+
of the project's directory, and each answer is read for what it says: the index lists no marker and
|
|
409
|
+
HEAD holds none. A branch not born yet, which `rev-parse --verify -q` says by exit 1 alone, goes on to
|
|
410
|
+
polyctl: an orphan branch of an enrolled repository is not a new repository, and whether the repository
|
|
411
|
+
is one only polyctl can say, from its history and from this machine's record that the project was enrolled,
|
|
412
|
+
since an agent can delete every ref whose history tracked the marker. A born branch that tracks no
|
|
413
|
+
marker - one made from a commit before the marker's - goes on to polyctl too while any ref's history tracks
|
|
414
|
+
one or this machine holds an enrollment record (LEADS-GATE-HOOK). Any other answer goes on to polyctl,
|
|
415
|
+
which refuses what it cannot read; a hook that finds no polyctl refuses. Older renderers keep their exact
|
|
416
|
+
guard without the record check so installed hooks can be recognized and upgraded.
|
|
417
|
+
"""
|
|
418
|
+
import shlex
|
|
419
|
+
marker = shlex.quote(PROJECT_MARKER if root_rel in ("", ".") else f"{root_rel}/{PROJECT_MARKER}")
|
|
420
|
+
record_guard = (
|
|
421
|
+
"if [ -z \"$indexed$headed\" ]; then\n"
|
|
422
|
+
f" enrollment_common=$(git --literal-pathspecs -C \"{top}\" rev-parse --git-common-dir 2>/dev/null)"
|
|
423
|
+
" || headed=unread\n"
|
|
424
|
+
" [ -n \"$enrollment_common\" ] || headed=unread\n"
|
|
425
|
+
f" case $enrollment_common in /*|[A-Za-z]:[\\\\/]*) ;; *) enrollment_common=\"{top}/$enrollment_common\" ;; esac\n"
|
|
426
|
+
" if [ -e \"$enrollment_common/polyctl-enrolled.json\" ] || [ -L \"$enrollment_common/polyctl-enrolled.json\" ]; then\n"
|
|
427
|
+
" headed=recorded\n"
|
|
428
|
+
" fi\n"
|
|
429
|
+
"fi\n"
|
|
430
|
+
) if check_record else ""
|
|
431
|
+
return (
|
|
432
|
+
f"indexed=$(git --literal-pathspecs -C \"{top}\" ls-files -- {marker} 2>/dev/null) || indexed=unread\n"
|
|
433
|
+
"headed=\n"
|
|
434
|
+
f"git --literal-pathspecs -C \"{top}\" rev-parse --verify -q HEAD >/dev/null 2>&1 || headed=$?\n"
|
|
435
|
+
"case $headed in\n"
|
|
436
|
+
f" \"\") headed=$(git --literal-pathspecs -C \"{top}\" ls-tree --name-only HEAD -- {marker} 2>/dev/null)"
|
|
437
|
+
" || headed=unread ;;\n"
|
|
438
|
+
# Not born on this branch: polyctl is asked, which reads the repository's history and this machine's record of
|
|
439
|
+
# the project; Git alone cannot say, since an agent can delete every ref that tracked the marker (LEADS-GATE).
|
|
440
|
+
" 1) headed=unborn ;;\n"
|
|
441
|
+
"esac\n"
|
|
442
|
+
# Born, and tracking no marker: a branch made from a commit before the marker's is no new repository while any
|
|
443
|
+
# ref's history tracks one, and polyctl is asked. A project a person removed by hand, its hook left in place, asks
|
|
444
|
+
# polyctl too; `polyctl hooks uninstall` takes the hook (LEADS-GATE-HOOK).
|
|
445
|
+
"if [ -z \"$indexed$headed\" ]; then\n"
|
|
446
|
+
f" headed=$(git --literal-pathspecs -C \"{top}\" log --all -1 --format=%H -- {marker} 2>/dev/null)"
|
|
447
|
+
" || headed=unread\n"
|
|
448
|
+
"fi\n"
|
|
449
|
+
+ record_guard
|
|
450
|
+
+ "[ -n \"$indexed$headed\" ] || exit 0\n"
|
|
451
|
+
)
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
_POLYCTL_LOOKUP = "polyctl=$(command -v polyctl) || { echo 'polyctl: polyctl not found' >&2; exit 1; }\n"
|
|
455
|
+
HOOK_POLYCTL_NOT_FOUND = "/bin/sh finds no polyctl on PATH"
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def _polyctl_lookup(fallback=None):
|
|
459
|
+
"""How a hook finds polyctl: on PATH, else the polyctl that installed the hook, while that file is there (SAFE-REMOVE).
|
|
460
|
+
|
|
461
|
+
A hook runs under /bin/sh, which cannot see a shell alias, and the README's zero-install
|
|
462
|
+
path was an alias: every commit failed with "polyctl not found", and `polyctl prove` sent the person
|
|
463
|
+
back to `polyctl hooks install`, which found the hook current. The fallback is only used when
|
|
464
|
+
`command -v polyctl` finds nothing; without one the hook fails closed as before.
|
|
465
|
+
"""
|
|
466
|
+
if fallback is None:
|
|
467
|
+
return _POLYCTL_LOOKUP
|
|
468
|
+
import shlex
|
|
469
|
+
return (f"polyctl_fallback={shlex.quote(fallback)}\n"
|
|
470
|
+
"polyctl=$(command -v polyctl) || { polyctl=$polyctl_fallback; [ -f \"$polyctl\" ] && [ -x \"$polyctl\" ]; } "
|
|
471
|
+
"|| { echo 'polyctl: polyctl not found' >&2; exit 1; }\n")
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def _hook_fallback():
|
|
475
|
+
"""The absolute path of the polyctl running now, for a hook to fall back on; None when there is none to name.
|
|
476
|
+
|
|
477
|
+
The entry point this process started from is the polyctl the person runs: the script itself
|
|
478
|
+
when it is called polyctl, else the clone's bin/polyctl, else the console script beside this
|
|
479
|
+
interpreter. None on Windows, where Git's shell does not read a drive-letter path as
|
|
480
|
+
absolute (docs/windows.md), and for a path that one line of a hook cannot hold.
|
|
481
|
+
"""
|
|
482
|
+
if os.name == "nt":
|
|
483
|
+
return None
|
|
484
|
+
started = os.path.abspath(sys.argv[0]) if sys.argv and sys.argv[0] else ""
|
|
485
|
+
candidates = ([started] if os.path.basename(started) == "polyctl" else []) + [
|
|
486
|
+
os.path.join(A.REPO, "bin", "polyctl"), os.path.join(os.path.dirname(sys.executable or ""), "polyctl")]
|
|
487
|
+
return next((path for path in candidates if os.path.isabs(path) and os.path.isfile(path)
|
|
488
|
+
and os.access(path, os.X_OK) and not any(ch in path for ch in "\n\r\0")), None)
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def _hook_fallback_of(data):
|
|
492
|
+
"""The polyctl a hook body falls back on, when it carries exactly one well-formed fallback; else None."""
|
|
493
|
+
import shlex
|
|
494
|
+
try:
|
|
495
|
+
text = data.decode(UTF8)
|
|
496
|
+
except UnicodeError:
|
|
497
|
+
return None
|
|
498
|
+
lines = [line for line in text.split("\n") if line.startswith("polyctl_fallback=")]
|
|
499
|
+
if len(lines) != 1:
|
|
500
|
+
return None
|
|
501
|
+
try:
|
|
502
|
+
words = shlex.split(lines[0])
|
|
503
|
+
except ValueError:
|
|
504
|
+
return None
|
|
505
|
+
if len(words) != 1 or not words[0].startswith("polyctl_fallback="):
|
|
506
|
+
return None
|
|
507
|
+
path = words[0][len("polyctl_fallback="):]
|
|
508
|
+
if not path.startswith("/") or text.count(_polyctl_lookup(path)) != 1:
|
|
509
|
+
return None
|
|
510
|
+
return path
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
def _hook_portable(data):
|
|
514
|
+
"""A hook body with its polyctl fallback taken out: the bytes it was rendered from; None when it carries none."""
|
|
515
|
+
fallback = _hook_fallback_of(data)
|
|
516
|
+
if fallback is None:
|
|
517
|
+
return None
|
|
518
|
+
return data.decode(UTF8).replace(_polyctl_lookup(fallback), _POLYCTL_LOOKUP).encode(UTF8)
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
def _hook_may_name_this_machine(directory, top, git_dir, common_dir):
|
|
522
|
+
"""Whether a hook written here may carry a path of this machine.
|
|
523
|
+
|
|
524
|
+
Inside the working tree a hook can be committed and carried to another machine, so only
|
|
525
|
+
the repository's own git directories, and places outside the tree, get a fallback.
|
|
526
|
+
"""
|
|
527
|
+
return (_hook_contains(git_dir, directory) or _hook_contains(common_dir, directory)
|
|
528
|
+
or not _hook_contains(top, directory))
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
def _render_v3_local_hook(role, root_rel):
|
|
532
|
+
"""Exact project-local body emitted before the hook read a drive-letter index as absolute (HOOK-V4).
|
|
533
|
+
|
|
534
|
+
Kept so that an installed v3 hook reads as legacy and `polyctl hooks install` replaces it. A fallback
|
|
535
|
+
polyctl is taken out of a body before it is compared (SAFE-REMOVE), so none is rendered here.
|
|
536
|
+
"""
|
|
537
|
+
import shlex
|
|
538
|
+
suffix = "" if root_rel in ("", ".") else "/" + shlex.quote(root_rel)
|
|
539
|
+
command = _role_command(role)
|
|
540
|
+
return (
|
|
541
|
+
"#!/bin/sh\n"
|
|
542
|
+
f"# polyctl: polyctl-hook-v3 role={role} binding=project-local\n"
|
|
543
|
+
"initial_cwd=$(CDPATH= cd -- . && pwd -P)\n"
|
|
544
|
+
f"root=\"$initial_cwd\"{suffix}\n"
|
|
545
|
+
"case ${GIT_INDEX_FILE-} in\n"
|
|
546
|
+
" \"\"|/*) ;;\n"
|
|
547
|
+
" *) GIT_INDEX_FILE=\"$initial_cwd/$GIT_INDEX_FILE\"; export GIT_INDEX_FILE ;;\n"
|
|
548
|
+
"esac\n"
|
|
549
|
+
+ _hook_repository_unset()
|
|
550
|
+
+ _hook_project_marker_guard()
|
|
551
|
+
+ _POLYCTL_LOOKUP
|
|
552
|
+
+ f"exec \"$polyctl\" -C \"$root\" {command}\n"
|
|
553
|
+
).encode(UTF8)
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
def _render_v3_scoped_hook(role, root_rel, family, directory_class):
|
|
557
|
+
"""Exact shared/external body emitted before the hook read a drive-letter index as absolute (HOOK-V4)."""
|
|
558
|
+
import shlex
|
|
559
|
+
suffix = "" if root_rel in ("", ".") else "/" + shlex.quote(root_rel)
|
|
560
|
+
command = _role_command(role)
|
|
561
|
+
return (
|
|
562
|
+
"#!/bin/sh\n"
|
|
563
|
+
f"# polyctl: polyctl-hook-v3 role={role} binding={directory_class}\n"
|
|
564
|
+
"initial_cwd=$(CDPATH= cd -- . && pwd -P)\n"
|
|
565
|
+
"case ${GIT_INDEX_FILE-} in\n"
|
|
566
|
+
" \"\"|/*) ;;\n"
|
|
567
|
+
" *) GIT_INDEX_FILE=\"$initial_cwd/$GIT_INDEX_FILE\"; export GIT_INDEX_FILE ;;\n"
|
|
568
|
+
"esac\n"
|
|
569
|
+
+ _hook_repository_unset()
|
|
570
|
+
+ "common=$(git --literal-pathspecs rev-parse --git-common-dir 2>/dev/null) || exit 0\n"
|
|
571
|
+
+ "case $common in /*) ;; *) common=\"$initial_cwd/$common\" ;; esac\n"
|
|
572
|
+
+ "common=$(CDPATH= cd \"$common\" 2>/dev/null && pwd -P) || exit 0\n"
|
|
573
|
+
+ f"expected={shlex.quote(os.path.realpath(family))}\n"
|
|
574
|
+
+ "[ \"$common\" = \"$expected\" ] || exit 0\n"
|
|
575
|
+
+ "top=$(git --literal-pathspecs rev-parse --show-toplevel 2>/dev/null) || exit 0\n"
|
|
576
|
+
+ "case $top in /*) ;; *) top=\"$initial_cwd/$top\" ;; esac\n"
|
|
577
|
+
+ "top=$(CDPATH= cd \"$top\" 2>/dev/null && pwd -P) || exit 0\n"
|
|
578
|
+
+ f"root=\"$top\"{suffix}\n"
|
|
579
|
+
+ _hook_project_marker_guard()
|
|
580
|
+
+ _POLYCTL_LOOKUP
|
|
581
|
+
+ f"exec \"$polyctl\" -C \"$root\" {command}\n"
|
|
582
|
+
).encode(UTF8)
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
def _hook_index_case():
|
|
586
|
+
"""How a hook reads Git's index path: absolute as Git gave it, else joined to where Git ran the hook (HOOK-V4).
|
|
587
|
+
|
|
588
|
+
polyctl reads a relative index from the project root, which need not be where Git ran the hook, so
|
|
589
|
+
the hook joins it to that directory first. It told an absolute path by its leading slash alone:
|
|
590
|
+
under Git for Windows' shell a path that starts with a drive letter - the temporary index the
|
|
591
|
+
execution proof hands Git, or a linked worktree's index - was taken for a relative one and joined
|
|
592
|
+
too, polyctl read another index than the one Git commits and refused, and no proof passed on Windows.
|
|
593
|
+
One ASCII letter, a colon and a slash or a backslash start an absolute path as well.
|
|
594
|
+
"""
|
|
595
|
+
return (
|
|
596
|
+
"case ${GIT_INDEX_FILE-} in\n"
|
|
597
|
+
# In the hook this reads [\\/], a bracket holding a backslash and a slash: C:\... and C:/... alike (HOOK-V4).
|
|
598
|
+
" \"\"|/*|[A-Za-z]:[\\\\/]*) ;;\n"
|
|
599
|
+
" *) GIT_INDEX_FILE=\"$initial_cwd/$GIT_INDEX_FILE\"; export GIT_INDEX_FILE ;;\n"
|
|
600
|
+
"esac\n"
|
|
601
|
+
)
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
def _render_v4_local_hook(role, root_rel):
|
|
605
|
+
"""Exact project-local body emitted before the hook stood aside only on Git's answer that no marker is tracked
|
|
606
|
+
(LEADS-GATE). Kept so that an installed v4 hook reads as legacy; a fallback polyctl is taken out before comparing."""
|
|
607
|
+
import shlex
|
|
608
|
+
suffix = "" if root_rel in ("", ".") else "/" + shlex.quote(root_rel)
|
|
609
|
+
command = _role_command(role)
|
|
610
|
+
return (
|
|
611
|
+
"#!/bin/sh\n"
|
|
612
|
+
f"# polyctl: polyctl-hook-v4 role={role} binding=project-local\n"
|
|
613
|
+
"initial_cwd=$(CDPATH= cd -- . && pwd -P)\n"
|
|
614
|
+
f"root=\"$initial_cwd\"{suffix}\n"
|
|
615
|
+
+ _hook_index_case()
|
|
616
|
+
+ _hook_repository_unset()
|
|
617
|
+
+ _hook_project_marker_guard()
|
|
618
|
+
+ _POLYCTL_LOOKUP
|
|
619
|
+
+ f"exec \"$polyctl\" -C \"$root\" {command}\n"
|
|
620
|
+
).encode(UTF8)
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
def _render_v4_scoped_hook(role, root_rel, family, directory_class):
|
|
624
|
+
"""Exact shared/external body emitted before the hook stood aside only on Git's answer that no marker is tracked
|
|
625
|
+
(LEADS-GATE)."""
|
|
626
|
+
import shlex
|
|
627
|
+
suffix = "" if root_rel in ("", ".") else "/" + shlex.quote(root_rel)
|
|
628
|
+
command = _role_command(role)
|
|
629
|
+
return (
|
|
630
|
+
"#!/bin/sh\n"
|
|
631
|
+
f"# polyctl: polyctl-hook-v4 role={role} binding={directory_class}\n"
|
|
632
|
+
"initial_cwd=$(CDPATH= cd -- . && pwd -P)\n"
|
|
633
|
+
+ _hook_index_case()
|
|
634
|
+
+ _hook_repository_unset()
|
|
635
|
+
+ "common=$(git --literal-pathspecs rev-parse --git-common-dir 2>/dev/null) || exit 0\n"
|
|
636
|
+
+ "case $common in /*) ;; *) common=\"$initial_cwd/$common\" ;; esac\n"
|
|
637
|
+
+ "common=$(CDPATH= cd \"$common\" 2>/dev/null && pwd -P) || exit 0\n"
|
|
638
|
+
+ f"expected={shlex.quote(os.path.realpath(family))}\n"
|
|
639
|
+
+ "[ \"$common\" = \"$expected\" ] || exit 0\n"
|
|
640
|
+
+ "top=$(git --literal-pathspecs rev-parse --show-toplevel 2>/dev/null) || exit 0\n"
|
|
641
|
+
+ "case $top in /*) ;; *) top=\"$initial_cwd/$top\" ;; esac\n"
|
|
642
|
+
+ "top=$(CDPATH= cd \"$top\" 2>/dev/null && pwd -P) || exit 0\n"
|
|
643
|
+
+ f"root=\"$top\"{suffix}\n"
|
|
644
|
+
+ _hook_project_marker_guard()
|
|
645
|
+
+ _POLYCTL_LOOKUP
|
|
646
|
+
+ f"exec \"$polyctl\" -C \"$root\" {command}\n"
|
|
647
|
+
).encode(UTF8)
|
|
648
|
+
|
|
649
|
+
|
|
650
|
+
def _render_v5_local_hook(role, root_rel):
|
|
651
|
+
"""Exact project-local body emitted before the hook named the repository Git runs it in, so polyctl could not be
|
|
652
|
+
redirected (NESTED-GIT). Kept so that an installed v5 hook reads as legacy; a fallback polyctl is taken out before
|
|
653
|
+
comparing."""
|
|
654
|
+
import shlex
|
|
655
|
+
suffix = "" if root_rel in ("", ".") else "/" + shlex.quote(root_rel)
|
|
656
|
+
command = _role_command(role)
|
|
657
|
+
return (
|
|
658
|
+
"#!/bin/sh\n"
|
|
659
|
+
f"# polyctl: polyctl-hook-v5 role={role} binding=project-local\n"
|
|
660
|
+
"initial_cwd=$(CDPATH= cd -- . && pwd -P)\n"
|
|
661
|
+
f"root=\"$initial_cwd\"{suffix}\n"
|
|
662
|
+
+ _hook_index_case()
|
|
663
|
+
+ _hook_repository_unset()
|
|
664
|
+
+ _hook_enrollment_guard("$initial_cwd", root_rel, check_record=False)
|
|
665
|
+
+ _POLYCTL_LOOKUP
|
|
666
|
+
+ f"exec \"$polyctl\" -C \"$root\" {command}\n"
|
|
667
|
+
).encode(UTF8)
|
|
668
|
+
|
|
669
|
+
|
|
670
|
+
def _render_v5_scoped_hook(role, root_rel, family, directory_class):
|
|
671
|
+
"""Exact shared/external body emitted before the hook named the repository Git runs it in (NESTED-GIT)."""
|
|
672
|
+
import shlex
|
|
673
|
+
suffix = "" if root_rel in ("", ".") else "/" + shlex.quote(root_rel)
|
|
674
|
+
command = _role_command(role)
|
|
675
|
+
return (
|
|
676
|
+
"#!/bin/sh\n"
|
|
677
|
+
f"# polyctl: polyctl-hook-v5 role={role} binding={directory_class}\n"
|
|
678
|
+
"initial_cwd=$(CDPATH= cd -- . && pwd -P)\n"
|
|
679
|
+
+ _hook_index_case()
|
|
680
|
+
+ _hook_repository_unset()
|
|
681
|
+
+ "common=$(git --literal-pathspecs rev-parse --git-common-dir 2>/dev/null) || exit 0\n"
|
|
682
|
+
+ "case $common in /*) ;; *) common=\"$initial_cwd/$common\" ;; esac\n"
|
|
683
|
+
+ "common=$(CDPATH= cd \"$common\" 2>/dev/null && pwd -P) || exit 0\n"
|
|
684
|
+
+ f"expected={shlex.quote(os.path.realpath(family))}\n"
|
|
685
|
+
+ "[ \"$common\" = \"$expected\" ] || exit 0\n"
|
|
686
|
+
+ "top=$(git --literal-pathspecs rev-parse --show-toplevel 2>/dev/null) || exit 0\n"
|
|
687
|
+
+ "case $top in /*) ;; *) top=\"$initial_cwd/$top\" ;; esac\n"
|
|
688
|
+
+ "top=$(CDPATH= cd \"$top\" 2>/dev/null && pwd -P) || exit 0\n"
|
|
689
|
+
+ f"root=\"$top\"{suffix}\n"
|
|
690
|
+
+ _hook_enrollment_guard("$top", root_rel, check_record=False)
|
|
691
|
+
+ _POLYCTL_LOOKUP
|
|
692
|
+
+ f"exec \"$polyctl\" -C \"$root\" {command}\n"
|
|
693
|
+
).encode(UTF8)
|
|
694
|
+
|
|
695
|
+
|
|
696
|
+
def _render_local_hook(role, root_rel, fallback=None, *, version=7):
|
|
697
|
+
"""Portable bytes for one project-local hook; no machine/family binding unless a fallback polyctl is named.
|
|
698
|
+
|
|
699
|
+
The hook names, in POLYCTL_COMMIT_TOP, the top of the working tree Git set as its current directory to run it - the
|
|
700
|
+
repository whose commit it guards. polyctl holds its authority to that repository and refuses when `git -C <project>`
|
|
701
|
+
resolves to another, which a planted `.git` would do (NESTED-GIT). `$initial_cwd` is that top from `pwd -P`, not
|
|
702
|
+
from a Git query, so a `.git` an agent plants in the project cannot move it.
|
|
703
|
+
"""
|
|
704
|
+
import shlex
|
|
705
|
+
suffix = "" if root_rel in ("", ".") else "/" + shlex.quote(root_rel)
|
|
706
|
+
command = _role_command(role)
|
|
707
|
+
return (
|
|
708
|
+
"#!/bin/sh\n"
|
|
709
|
+
f"# polyctl: polyctl-hook-v{version} role={role} binding=project-local\n"
|
|
710
|
+
"initial_cwd=$(CDPATH= cd -- . && pwd -P)\n"
|
|
711
|
+
f"root=\"$initial_cwd\"{suffix}\n"
|
|
712
|
+
"POLYCTL_COMMIT_TOP=\"$initial_cwd\"; export POLYCTL_COMMIT_TOP\n"
|
|
713
|
+
+ _hook_index_case()
|
|
714
|
+
+ _hook_repository_unset()
|
|
715
|
+
+ _hook_enrollment_guard("$initial_cwd", root_rel, check_record=version >= 7)
|
|
716
|
+
+ _polyctl_lookup(fallback)
|
|
717
|
+
+ f"exec \"$polyctl\" -C \"$root\" {command}\n"
|
|
718
|
+
).encode(UTF8)
|
|
719
|
+
|
|
720
|
+
|
|
721
|
+
def _render_scoped_hook(role, root_rel, family, directory_class, fallback=None, *, version=7):
|
|
722
|
+
"""Family-bound bytes for a shared/external target; unknown routing is fail-open.
|
|
723
|
+
|
|
724
|
+
POLYCTL_COMMIT_TOP names the top of the working tree the committed repository resolved to from inside the family it is
|
|
725
|
+
bound to, so polyctl refuses when `git -C <project>` resolves elsewhere (NESTED-GIT).
|
|
726
|
+
"""
|
|
727
|
+
import shlex
|
|
728
|
+
suffix = "" if root_rel in ("", ".") else "/" + shlex.quote(root_rel)
|
|
729
|
+
command = _role_command(role)
|
|
730
|
+
return (
|
|
731
|
+
"#!/bin/sh\n"
|
|
732
|
+
f"# polyctl: polyctl-hook-v{version} role={role} binding={directory_class}\n"
|
|
733
|
+
"initial_cwd=$(CDPATH= cd -- . && pwd -P)\n"
|
|
734
|
+
+ _hook_index_case()
|
|
735
|
+
+ _hook_repository_unset()
|
|
736
|
+
+ "common=$(git --literal-pathspecs rev-parse --git-common-dir 2>/dev/null) || exit 0\n"
|
|
737
|
+
+ "case $common in /*) ;; *) common=\"$initial_cwd/$common\" ;; esac\n"
|
|
738
|
+
+ "common=$(CDPATH= cd \"$common\" 2>/dev/null && pwd -P) || exit 0\n"
|
|
739
|
+
+ f"expected={shlex.quote(os.path.realpath(family))}\n"
|
|
740
|
+
+ "[ \"$common\" = \"$expected\" ] || exit 0\n"
|
|
741
|
+
+ "top=$(git --literal-pathspecs rev-parse --show-toplevel 2>/dev/null) || exit 0\n"
|
|
742
|
+
+ "case $top in /*) ;; *) top=\"$initial_cwd/$top\" ;; esac\n"
|
|
743
|
+
+ "top=$(CDPATH= cd \"$top\" 2>/dev/null && pwd -P) || exit 0\n"
|
|
744
|
+
+ f"root=\"$top\"{suffix}\n"
|
|
745
|
+
+ "POLYCTL_COMMIT_TOP=\"$top\"; export POLYCTL_COMMIT_TOP\n"
|
|
746
|
+
+ _hook_enrollment_guard("$top", root_rel, check_record=version >= 7)
|
|
747
|
+
+ _polyctl_lookup(fallback)
|
|
748
|
+
+ f"exec \"$polyctl\" -C \"$root\" {command}\n"
|
|
749
|
+
).encode(UTF8)
|
|
750
|
+
|
|
751
|
+
|
|
752
|
+
def _legacy_hook_role(data):
|
|
753
|
+
"""Recognize only byte-exact generated bodies of every hook version, including stale bindings."""
|
|
754
|
+
import shlex
|
|
755
|
+
if b"\x00" in data:
|
|
756
|
+
return None
|
|
757
|
+
try:
|
|
758
|
+
text = data.decode(UTF8)
|
|
759
|
+
except UnicodeError:
|
|
760
|
+
return None
|
|
761
|
+
if not text.startswith("#!/bin/sh\n") or "# polyctl:" not in text:
|
|
762
|
+
return None
|
|
763
|
+
|
|
764
|
+
lines = text.splitlines()
|
|
765
|
+
exec_lines = [line for line in lines if line.startswith("exec ")]
|
|
766
|
+
if len(exec_lines) == 1:
|
|
767
|
+
try:
|
|
768
|
+
argv = shlex.split(exec_lines[0])
|
|
769
|
+
except ValueError:
|
|
770
|
+
argv = []
|
|
771
|
+
legacy = None
|
|
772
|
+
if len(argv) == 5 and argv[0] == "exec" and argv[2] == "-C" \
|
|
773
|
+
and argv[4] == "commit-check":
|
|
774
|
+
legacy = PRE_COMMIT_HOOK.format(
|
|
775
|
+
polyctl=shlex.quote(argv[1]), root=shlex.quote(argv[3])
|
|
776
|
+
).encode(UTF8)
|
|
777
|
+
role = "pre-commit"
|
|
778
|
+
elif len(argv) == 6 and argv[0] == "exec" and argv[2] == "-C" \
|
|
779
|
+
and argv[4:] == ["push", "check"]:
|
|
780
|
+
legacy = PRE_PUSH_HOOK.format(
|
|
781
|
+
polyctl=shlex.quote(argv[1]), root=shlex.quote(argv[3])
|
|
782
|
+
).encode(UTF8)
|
|
783
|
+
role = "pre-push"
|
|
784
|
+
if legacy is not None and data == legacy:
|
|
785
|
+
return role
|
|
786
|
+
|
|
787
|
+
marker_prefix = "# polyctl: polyctl-hook-v"
|
|
788
|
+
markers = [line for line in lines if line.startswith(marker_prefix)]
|
|
789
|
+
if len(markers) != 1 or " role=" not in markers[0] or " binding=" not in markers[0]:
|
|
790
|
+
return None
|
|
791
|
+
version, declaration = markers[0][len(marker_prefix):].split(" role=", 1)
|
|
792
|
+
# Each version renders its own exact bodies, so a hook an older polyctl installed reads as legacy and
|
|
793
|
+
# `polyctl hooks install` replaces it: a v3 hook took a drive-letter index for a relative one (HOOK-V4),
|
|
794
|
+
# a v4 hook stood aside when its marker queries failed (LEADS-GATE), and a v5 hook did not name the
|
|
795
|
+
# repository it guards, so a planted `.git` could move polyctl's authority to another (NESTED-GIT).
|
|
796
|
+
# A v6 hook skipped the machine enrollment record once every marker-bearing ref was deleted.
|
|
797
|
+
renderers = {
|
|
798
|
+
"2": (_render_v2_local_hook, _render_v2_scoped_hook),
|
|
799
|
+
"3": (_render_v3_local_hook, _render_v3_scoped_hook),
|
|
800
|
+
"4": (_render_v4_local_hook, _render_v4_scoped_hook),
|
|
801
|
+
"5": (_render_v5_local_hook, _render_v5_scoped_hook),
|
|
802
|
+
"6": (lambda role, rel: _render_local_hook(role, rel, version=6),
|
|
803
|
+
lambda role, rel, family, kind: _render_scoped_hook(role, rel, family, kind, version=6)),
|
|
804
|
+
"7": (_render_local_hook, _render_scoped_hook),
|
|
805
|
+
}
|
|
806
|
+
if version not in renderers:
|
|
807
|
+
return None
|
|
808
|
+
render_local, render_scoped = renderers[version]
|
|
809
|
+
role, binding = declaration.split(" binding=", 1)
|
|
810
|
+
if role not in _HOOK_ROLES or binding not in ("project-local", "shared", "external"):
|
|
811
|
+
return None
|
|
812
|
+
|
|
813
|
+
def assignment(name):
|
|
814
|
+
prefix = name + "="
|
|
815
|
+
matches = [line for line in lines if line.startswith(prefix)]
|
|
816
|
+
if len(matches) != 1:
|
|
817
|
+
return None
|
|
818
|
+
try:
|
|
819
|
+
words = shlex.split(matches[0])
|
|
820
|
+
except ValueError:
|
|
821
|
+
return None
|
|
822
|
+
if len(words) != 1 or not words[0].startswith(prefix):
|
|
823
|
+
return None
|
|
824
|
+
return words[0][len(prefix):]
|
|
825
|
+
|
|
826
|
+
root = assignment("root")
|
|
827
|
+
root_prefix = "$initial_cwd" if binding == "project-local" else "$top"
|
|
828
|
+
if root == root_prefix:
|
|
829
|
+
root_rel = "."
|
|
830
|
+
elif root is not None and root.startswith(root_prefix + "/"):
|
|
831
|
+
root_rel = root[len(root_prefix) + 1:]
|
|
832
|
+
else:
|
|
833
|
+
return None
|
|
834
|
+
|
|
835
|
+
if binding == "project-local":
|
|
836
|
+
rendered = render_local(role, root_rel)
|
|
837
|
+
else:
|
|
838
|
+
family = assignment("expected")
|
|
839
|
+
if not family:
|
|
840
|
+
return None
|
|
841
|
+
rendered = render_scoped(role, root_rel, family, binding)
|
|
842
|
+
prior = rendered.replace(
|
|
843
|
+
b"initial_cwd=$(CDPATH= cd -- . && pwd -P)\n",
|
|
844
|
+
b"initial_cwd=$PWD\n",
|
|
845
|
+
1,
|
|
846
|
+
)
|
|
847
|
+
if data == rendered or data == prior:
|
|
848
|
+
return role
|
|
849
|
+
return None
|
|
850
|
+
|
|
851
|
+
|
|
852
|
+
def _crlf_translation(data):
|
|
853
|
+
if b"\r\n" not in data:
|
|
854
|
+
return None
|
|
855
|
+
remainder = data.replace(b"\r\n", b"")
|
|
856
|
+
if b"\n" in remainder or b"\r" in remainder:
|
|
857
|
+
return None
|
|
858
|
+
return data.replace(b"\r\n", b"\n")
|
|
859
|
+
|
|
860
|
+
|
|
861
|
+
def _plausible_polyctl_role(data, role):
|
|
862
|
+
try:
|
|
863
|
+
text = data.decode(UTF8)
|
|
864
|
+
except UnicodeError:
|
|
865
|
+
return False
|
|
866
|
+
executable = "\n".join(
|
|
867
|
+
line for line in text.splitlines() if not line.lstrip().startswith("#")
|
|
868
|
+
)
|
|
869
|
+
command = _role_command(role)
|
|
870
|
+
return command in executable and ("polyctl" in executable or "polyctl" in text)
|
|
871
|
+
|
|
872
|
+
|
|
873
|
+
def _classify_hook(path, role, local_body=None, scoped_body=None):
|
|
874
|
+
if not os.path.lexists(path):
|
|
875
|
+
return "absent", False
|
|
876
|
+
if os.path.islink(path):
|
|
877
|
+
return "foreign", False
|
|
878
|
+
try:
|
|
879
|
+
with open(path, "rb") as fh:
|
|
880
|
+
data = fh.read()
|
|
881
|
+
mode = os.fstat(fh.fileno()).st_mode
|
|
882
|
+
data.decode(UTF8)
|
|
883
|
+
except (OSError, UnicodeError):
|
|
884
|
+
return "foreign", False
|
|
885
|
+
# A body that names the polyctl which installed it is the same intent as the portable one (SAFE-REMOVE).
|
|
886
|
+
portable = _hook_portable(data) or data
|
|
887
|
+
current = ("current-local (behavior unverified)" if local_body is not None and portable == local_body
|
|
888
|
+
else "current-scoped (behavior unverified)" if scoped_body is not None and portable == scoped_body
|
|
889
|
+
else None)
|
|
890
|
+
if current:
|
|
891
|
+
import stat
|
|
892
|
+
# Git runs a hook only with its owner's execute bit, and polyctl's exact bytes without it read as
|
|
893
|
+
# current: install left them, and Git ran nothing. They are polyctl's to replace, as an older body
|
|
894
|
+
# is (LEADS-GATE). Git for Windows runs a hook that starts with #!, as polyctl's do, whatever its mode.
|
|
895
|
+
if os.name != "nt" and not mode & stat.S_IXUSR:
|
|
896
|
+
return "legacy (not executable)", False
|
|
897
|
+
return current, False
|
|
898
|
+
translated = _crlf_translation(data)
|
|
899
|
+
for candidate in (data, translated):
|
|
900
|
+
if candidate is None:
|
|
901
|
+
continue
|
|
902
|
+
candidate = _hook_portable(candidate) or candidate
|
|
903
|
+
if (local_body is not None and candidate == local_body) \
|
|
904
|
+
or (scoped_body is not None and candidate == scoped_body) \
|
|
905
|
+
or _legacy_hook_role(candidate) == role:
|
|
906
|
+
return "legacy (behavior unverified)", translated is not None
|
|
907
|
+
if _plausible_polyctl_role(data, role):
|
|
908
|
+
return "ambiguous-polyctl", False
|
|
909
|
+
return "foreign", False
|
|
910
|
+
|
|
911
|
+
|
|
912
|
+
def _state_base(state):
|
|
913
|
+
return state.split(" ", 1)[0]
|
|
914
|
+
|
|
915
|
+
|
|
916
|
+
def _repo_source_roles(top):
|
|
917
|
+
result = _hook_git(
|
|
918
|
+
top, "ls-files", "-z", "--", ".githooks/pre-commit", ".githooks/pre-push"
|
|
919
|
+
)
|
|
920
|
+
if result.returncode:
|
|
921
|
+
return set()
|
|
922
|
+
return {os.path.basename(os.fsdecode(raw)) for raw in result.stdout.split(b"\0") if raw}
|
|
923
|
+
|
|
924
|
+
|
|
925
|
+
def _add_hook_dir(directories, path, source):
|
|
926
|
+
path = os.path.realpath(path)
|
|
927
|
+
row = directories.setdefault(path, {"path": path, "sources": set()})
|
|
928
|
+
row["sources"].add(source)
|
|
929
|
+
return row
|
|
930
|
+
|
|
931
|
+
|
|
932
|
+
def _polyctl_hook_inventory(root):
|
|
933
|
+
"""Resolve every active/legacy polyctl hook target from Git's measured topology."""
|
|
934
|
+
root = os.path.realpath(os.path.abspath(root))
|
|
935
|
+
empty = {
|
|
936
|
+
"root": root, "top": None, "git_dir": None, "common_dir": None,
|
|
937
|
+
"active_dir": None, "directory_class": None, "globally_configured": False,
|
|
938
|
+
"config": {"set": False, "scope": None, "origin": None, "value": None},
|
|
939
|
+
"family": None, "project_rel": None, "worktrees": [], "targets": [],
|
|
940
|
+
"error": None,
|
|
941
|
+
}
|
|
942
|
+
try:
|
|
943
|
+
top = _hook_real(
|
|
944
|
+
root,
|
|
945
|
+
_hook_output_path(_hook_git(root, "rev-parse", "--show-toplevel"),
|
|
946
|
+
"--show-toplevel"),
|
|
947
|
+
)
|
|
948
|
+
git_dir = _hook_real(
|
|
949
|
+
top, _hook_output_path(_hook_git(top, "rev-parse", "--git-dir"), "--git-dir")
|
|
950
|
+
)
|
|
951
|
+
common_dir = _hook_real(
|
|
952
|
+
top,
|
|
953
|
+
_hook_output_path(_hook_git(top, "rev-parse", "--git-common-dir"),
|
|
954
|
+
"--git-common-dir"),
|
|
955
|
+
)
|
|
956
|
+
active_dir = _hook_real(
|
|
957
|
+
top,
|
|
958
|
+
_hook_output_path(_hook_git(top, "rev-parse", "--git-path", "hooks"),
|
|
959
|
+
"--git-path hooks"),
|
|
960
|
+
)
|
|
961
|
+
config = _hooks_config(top)
|
|
962
|
+
facts, admins = _worktree_facts(top, common_dir)
|
|
963
|
+
except _HookResolutionError as exc:
|
|
964
|
+
empty["error"] = str(exc)
|
|
965
|
+
return empty
|
|
966
|
+
|
|
967
|
+
directory_class = _hook_directory_class(
|
|
968
|
+
active_dir, top, git_dir, common_dir, facts, config
|
|
969
|
+
)
|
|
970
|
+
globally_configured = config["scope"] in ("system", "global")
|
|
971
|
+
project_rel = os.path.relpath(root, top)
|
|
972
|
+
directories = {}
|
|
973
|
+
_add_hook_dir(directories, active_dir, "active")
|
|
974
|
+
_add_hook_dir(directories, os.path.join(git_dir, "hooks"), "current-private")
|
|
975
|
+
_add_hook_dir(directories, os.path.join(common_dir, "hooks"), "common-fallback")
|
|
976
|
+
for admin in admins:
|
|
977
|
+
_add_hook_dir(directories, os.path.join(admin["admin"], "hooks"),
|
|
978
|
+
"admin:" + admin["name"])
|
|
979
|
+
for fact in facts:
|
|
980
|
+
if fact.get("effective_dir"):
|
|
981
|
+
_add_hook_dir(directories, fact["effective_dir"], "effective:" + fact["path"])
|
|
982
|
+
|
|
983
|
+
repo_dir = os.path.realpath(os.path.join(top, ".githooks"))
|
|
984
|
+
repo_roles = _repo_source_roles(top)
|
|
985
|
+
if repo_roles or any(os.path.lexists(os.path.join(repo_dir, role)) for role in _HOOK_ROLES):
|
|
986
|
+
_add_hook_dir(directories, repo_dir, "repository-source")
|
|
987
|
+
|
|
988
|
+
effective_counts = {}
|
|
989
|
+
for fact in facts:
|
|
990
|
+
if fact.get("effective_dir"):
|
|
991
|
+
key = os.path.realpath(fact["effective_dir"])
|
|
992
|
+
effective_counts[key] = effective_counts.get(key, 0) + 1
|
|
993
|
+
locked_admins = {
|
|
994
|
+
os.path.realpath(admin["admin"])
|
|
995
|
+
for admin in admins if admin["locked"]
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
targets = []
|
|
999
|
+
fallback = _hook_fallback()
|
|
1000
|
+
ordered_dirs = sorted(directories.values(), key=lambda row: (row["path"] != active_dir, os.fsencode(row["path"])))
|
|
1001
|
+
for directory in ordered_dirs:
|
|
1002
|
+
path = directory["path"]
|
|
1003
|
+
sources = directory["sources"]
|
|
1004
|
+
cls = _hook_directory_class(path, top, git_dir, common_dir, facts,
|
|
1005
|
+
config if path == active_dir else None)
|
|
1006
|
+
potential = bool(effective_counts.get(path)) or "common-fallback" in sources
|
|
1007
|
+
if any(_hook_contains(admin, path) for admin in locked_admins):
|
|
1008
|
+
potential = True
|
|
1009
|
+
reachability = "potentially-effective" if potential else "dead-misplaced"
|
|
1010
|
+
legacy_location = "active" not in sources and not any(
|
|
1011
|
+
source.startswith("effective:") for source in sources
|
|
1012
|
+
) and "repository-source" not in sources
|
|
1013
|
+
for role in _HOOK_ROLES:
|
|
1014
|
+
target_path = os.path.join(path, role)
|
|
1015
|
+
active = path == active_dir
|
|
1016
|
+
repository_source = "repository-source" in sources and role in repo_roles
|
|
1017
|
+
if not active and not repository_source and not os.path.lexists(target_path):
|
|
1018
|
+
continue
|
|
1019
|
+
track = _hook_track_state(target_path)
|
|
1020
|
+
local_body = _render_local_hook(role, project_rel)
|
|
1021
|
+
scoped_body = _render_scoped_hook(role, project_rel, common_dir, cls)
|
|
1022
|
+
expected_local = repository_source or cls == "project-local"
|
|
1023
|
+
state, crlf_only = _classify_hook(
|
|
1024
|
+
target_path, role,
|
|
1025
|
+
local_body=local_body if expected_local else None,
|
|
1026
|
+
scoped_body=scoped_body if not expected_local else None,
|
|
1027
|
+
)
|
|
1028
|
+
base = _state_base(state)
|
|
1029
|
+
eligible = False
|
|
1030
|
+
if base in ("current-local", "current-scoped", "legacy") and track == "untracked":
|
|
1031
|
+
eligible = True
|
|
1032
|
+
elif base == "absent" and active:
|
|
1033
|
+
eligible = track == "untracked" or (
|
|
1034
|
+
track == "unobserved" and (cls in ("shared", "external") or globally_configured)
|
|
1035
|
+
)
|
|
1036
|
+
needs_auth = eligible and (
|
|
1037
|
+
cls in ("shared", "external") or (active and globally_configured)
|
|
1038
|
+
)
|
|
1039
|
+
# What install writes names the polyctl that installed it, where the hook cannot travel (SAFE-REMOVE).
|
|
1040
|
+
named = fallback if _hook_may_name_this_machine(path, top, git_dir, common_dir) else None
|
|
1041
|
+
targets.append({
|
|
1042
|
+
"role": role, "path": target_path, "directory": path,
|
|
1043
|
+
"directory_class": cls, "active": active,
|
|
1044
|
+
"globally_configured": bool(active and globally_configured),
|
|
1045
|
+
"reachability": reachability, "effective_count": effective_counts.get(path, 0),
|
|
1046
|
+
"repository_source": repository_source,
|
|
1047
|
+
"legacy_location": legacy_location,
|
|
1048
|
+
"static_state": state, "track_state": track,
|
|
1049
|
+
"protected": track in ("tracked", "indeterminate"),
|
|
1050
|
+
"eligible": eligible, "needs_authorization": needs_auth,
|
|
1051
|
+
"crlf_only": crlf_only, "sources": sorted(sources),
|
|
1052
|
+
"body": _render_local_hook(role, project_rel, named) if expected_local
|
|
1053
|
+
else _render_scoped_hook(role, project_rel, common_dir, cls, named),
|
|
1054
|
+
})
|
|
1055
|
+
|
|
1056
|
+
empty.update({
|
|
1057
|
+
"top": top, "git_dir": git_dir, "common_dir": common_dir,
|
|
1058
|
+
"active_dir": active_dir, "directory_class": directory_class,
|
|
1059
|
+
"globally_configured": globally_configured, "config": config,
|
|
1060
|
+
"family": common_dir, "project_rel": project_rel,
|
|
1061
|
+
"worktrees": facts, "targets": targets,
|
|
1062
|
+
})
|
|
1063
|
+
return empty
|
|
1064
|
+
|
|
1065
|
+
|
|
1066
|
+
def _polyctl_hook_paths(root):
|
|
1067
|
+
inv = _polyctl_hook_inventory(root)
|
|
1068
|
+
if inv["error"]:
|
|
1069
|
+
return {role: os.path.join(root, ".git", "hooks", role) for role in _HOOK_ROLES}
|
|
1070
|
+
return {role: os.path.join(inv["active_dir"], role) for role in _HOOK_ROLES}
|
|
1071
|
+
|
|
1072
|
+
|
|
1073
|
+
def _polyctl_hook_state(path):
|
|
1074
|
+
"""Compatibility classifier: marker-only files are foreign, old exact bodies legacy."""
|
|
1075
|
+
role = os.path.basename(path)
|
|
1076
|
+
if role not in _HOOK_ROLES:
|
|
1077
|
+
return "foreign"
|
|
1078
|
+
return _classify_hook(path, role)[0]
|
|
1079
|
+
|
|
1080
|
+
|
|
1081
|
+
def _active_hook_targets(inv):
|
|
1082
|
+
return {target["role"]: target for target in inv["targets"] if target["active"]}
|
|
1083
|
+
|
|
1084
|
+
|
|
1085
|
+
def _recorded_pre_push_paths(root):
|
|
1086
|
+
"""Paths where the enrollment record or the install manifest records that polyctl installed `pre-push` (INIT-OWN-PRE-PUSH-3)."""
|
|
1087
|
+
from . import storage
|
|
1088
|
+
polyctl_paths = set()
|
|
1089
|
+
docs = []
|
|
1090
|
+
enrolled = A.enrollment_record(root)
|
|
1091
|
+
if isinstance(enrolled, dict):
|
|
1092
|
+
docs.append(enrolled)
|
|
1093
|
+
try:
|
|
1094
|
+
raw = storage.read_in_tree(root, ".polyctl/init-manifest.json")
|
|
1095
|
+
if raw is not None:
|
|
1096
|
+
manifest = json.loads(raw.decode(UTF8))
|
|
1097
|
+
if isinstance(manifest, dict):
|
|
1098
|
+
docs.append(manifest)
|
|
1099
|
+
except (OSError, ValueError, UnicodeError):
|
|
1100
|
+
pass
|
|
1101
|
+
for doc in docs:
|
|
1102
|
+
if isinstance(doc.get("pre_push"), list):
|
|
1103
|
+
for entry in doc["pre_push"]:
|
|
1104
|
+
if isinstance(entry, str) and entry:
|
|
1105
|
+
polyctl_paths.add(os.path.realpath(entry))
|
|
1106
|
+
return polyctl_paths
|
|
1107
|
+
|
|
1108
|
+
|
|
1109
|
+
def _manifest_pre_push_fields(root, inv=None, final_inv=None):
|
|
1110
|
+
"""The `pre_push` list to persist in `.polyctl/init-manifest.json` and `polyctl-enrolled.json` (INIT-OWN-PRE-PUSH-3)."""
|
|
1111
|
+
polyctl_paths = _recorded_pre_push_paths(root)
|
|
1112
|
+
if inv is None:
|
|
1113
|
+
inv = _polyctl_hook_inventory(root)
|
|
1114
|
+
for current in (inv, final_inv):
|
|
1115
|
+
if not current or current.get("error"):
|
|
1116
|
+
continue
|
|
1117
|
+
for target in current.get("targets", []):
|
|
1118
|
+
if target.get("role") != "pre-push":
|
|
1119
|
+
continue
|
|
1120
|
+
real_path = os.path.realpath(target["path"])
|
|
1121
|
+
base = _state_base(target["static_state"])
|
|
1122
|
+
if base in ("current-local", "current-scoped", "legacy"):
|
|
1123
|
+
polyctl_paths.add(real_path)
|
|
1124
|
+
return {"pre_push": sorted(polyctl_paths)}
|
|
1125
|
+
|
|
1126
|
+
|
|
1127
|
+
def _record_pre_push_provenance(root, inv, final_inv=None, fields=None):
|
|
1128
|
+
"""Record where polyctl's pre-push stood in the enrollment record and install manifest (INIT-OWN-PRE-PUSH-3)."""
|
|
1129
|
+
from . import storage
|
|
1130
|
+
if fields is None:
|
|
1131
|
+
fields = _manifest_pre_push_fields(root, inv, final_inv)
|
|
1132
|
+
elif final_inv is not None and not final_inv.get("error"):
|
|
1133
|
+
polyctl_paths = set(fields.get("pre_push") or [])
|
|
1134
|
+
for target in final_inv.get("targets", []):
|
|
1135
|
+
if target.get("role") != "pre-push":
|
|
1136
|
+
continue
|
|
1137
|
+
real_path = os.path.realpath(target["path"])
|
|
1138
|
+
base = _state_base(target["static_state"])
|
|
1139
|
+
if base in ("current-local", "current-scoped", "legacy"):
|
|
1140
|
+
polyctl_paths.add(real_path)
|
|
1141
|
+
fields = {"pre_push": sorted(polyctl_paths)}
|
|
1142
|
+
top = _project_repository_top(root) or root
|
|
1143
|
+
enrolled = A.enrollment_record(top)
|
|
1144
|
+
if isinstance(enrolled, dict) and not enrolled.get("unreadable"):
|
|
1145
|
+
path, identity = A.enrollment_record_path(top)
|
|
1146
|
+
if path and identity and enrolled.get("repository") == identity:
|
|
1147
|
+
updated = dict(enrolled, **fields)
|
|
1148
|
+
updated.pop("own_pre_push", None)
|
|
1149
|
+
try:
|
|
1150
|
+
storage.replace_file_durably(
|
|
1151
|
+
path,
|
|
1152
|
+
(json.dumps(updated, ensure_ascii=False) + "\n").encode(UTF8),
|
|
1153
|
+
)
|
|
1154
|
+
except OSError:
|
|
1155
|
+
pass
|
|
1156
|
+
manifest_path = os.path.join(root, ".polyctl", "init-manifest.json")
|
|
1157
|
+
if os.path.isfile(manifest_path) and not os.path.islink(manifest_path):
|
|
1158
|
+
try:
|
|
1159
|
+
raw = storage.read_in_tree(root, ".polyctl/init-manifest.json")
|
|
1160
|
+
manifest = json.loads(raw.decode(UTF8)) if raw is not None else None
|
|
1161
|
+
if isinstance(manifest, dict) and (
|
|
1162
|
+
manifest.get("pre_push") != fields["pre_push"]
|
|
1163
|
+
or "own_pre_push" in manifest
|
|
1164
|
+
):
|
|
1165
|
+
manifest.update(fields)
|
|
1166
|
+
manifest.pop("own_pre_push", None)
|
|
1167
|
+
storage.replace_in_tree(
|
|
1168
|
+
root,
|
|
1169
|
+
".polyctl/init-manifest.json",
|
|
1170
|
+
json.dumps(manifest, indent=2).encode(UTF8),
|
|
1171
|
+
)
|
|
1172
|
+
except (OSError, ValueError, UnicodeError):
|
|
1173
|
+
pass
|
|
1174
|
+
|
|
1175
|
+
|
|
1176
|
+
def _own_pre_push_target(inv):
|
|
1177
|
+
"""The active pre-push target when the repository keeps its own tracked pre-push hook, else None (INIT-OWN-PRE-PUSH-3, PUSH-GUARD-MCP).
|
|
1178
|
+
|
|
1179
|
+
A pre-push counts as the repository's own only when it is foreign (not polyctl's or an
|
|
1180
|
+
ambiguous polyctl body) and is tracked in the tree core.hooksPath names (as in this repository).
|
|
1181
|
+
"""
|
|
1182
|
+
if inv.get("error"):
|
|
1183
|
+
return None
|
|
1184
|
+
target = _active_hook_targets(inv).get("pre-push")
|
|
1185
|
+
if not target or _state_base(target["static_state"]) != "foreign":
|
|
1186
|
+
return None
|
|
1187
|
+
if os.path.realpath(target["path"]) in _recorded_pre_push_paths(inv["root"]):
|
|
1188
|
+
return None
|
|
1189
|
+
if (
|
|
1190
|
+
target["track_state"] == "tracked"
|
|
1191
|
+
and inv.get("config", {}).get("set")
|
|
1192
|
+
and _hook_contains(inv["top"], target["directory"])
|
|
1193
|
+
):
|
|
1194
|
+
return target
|
|
1195
|
+
return None
|
|
1196
|
+
|
|
1197
|
+
|
|
1198
|
+
def _own_pre_push_line(target):
|
|
1199
|
+
"""One-line summary when a repository keeps its own tracked pre-push hook (INIT-OWN-PRE-PUSH)."""
|
|
1200
|
+
return (
|
|
1201
|
+
f"off — push guard not installed here: {target['path']} is the repository's own pre-push hook "
|
|
1202
|
+
f"({target['static_state']} / {target['track_state']}) and was left as it is; "
|
|
1203
|
+
f"to install polyctl's push guard, remove {target['path']} from the repository and run `polyctl hooks install`"
|
|
1204
|
+
)
|
|
1205
|
+
|
|
1206
|
+
|
|
1207
|
+
def _other_pre_push_line(inv):
|
|
1208
|
+
"""Yellow push-guard warning when an active pre-push is neither polyctl's nor the repository's tracked hook, else None (INIT-OWN-PRE-PUSH-3)."""
|
|
1209
|
+
if inv.get("error") or _own_pre_push_target(inv) is not None:
|
|
1210
|
+
return None
|
|
1211
|
+
target = _active_hook_targets(inv).get("pre-push")
|
|
1212
|
+
if not target or _state_base(target["static_state"]) in (
|
|
1213
|
+
"absent", "current-local", "current-scoped", "legacy"
|
|
1214
|
+
):
|
|
1215
|
+
return None
|
|
1216
|
+
replaced = os.path.realpath(target["path"]) in _recorded_pre_push_paths(inv["root"])
|
|
1217
|
+
what = (
|
|
1218
|
+
"polyctl's pre-push was replaced: the push guard is off"
|
|
1219
|
+
if replaced
|
|
1220
|
+
else "a pre-push polyctl did not install: the push guard is off"
|
|
1221
|
+
)
|
|
1222
|
+
return (
|
|
1223
|
+
f"{what} ({target['path']} — {target['static_state']} / {target['track_state']}); "
|
|
1224
|
+
"to have polyctl's guard, move that hook aside, then `polyctl hooks install`"
|
|
1225
|
+
)
|
|
1226
|
+
|
|
1227
|
+
|
|
1228
|
+
def _push_guard_status_line(inv):
|
|
1229
|
+
"""The `push_guard` line for `polyctl status`, `polyctl doctor`, and MCP `polyctl_status` when the push guard is off, else None (PUSH-GUARD-MCP)."""
|
|
1230
|
+
push_target = _own_pre_push_target(inv)
|
|
1231
|
+
if push_target is not None:
|
|
1232
|
+
return (
|
|
1233
|
+
f"off ({push_target['path']} is the repository's own pre-push hook — "
|
|
1234
|
+
f"{push_target['static_state']} / {push_target['track_state']})"
|
|
1235
|
+
)
|
|
1236
|
+
return _other_pre_push_line(inv)
|
|
1237
|
+
|
|
1238
|
+
|
|
1239
|
+
def _hook_execution_probe(inv):
|
|
1240
|
+
"""Prove that Git resolves and executes polyctl's active pre-commit hook.
|
|
1241
|
+
|
|
1242
|
+
Static classification is only a safety precondition: it prevents status and
|
|
1243
|
+
doctor from executing foreign hook content. The positive result comes only
|
|
1244
|
+
from ``git hook run pre-commit`` carrying a temporary synthetic index into
|
|
1245
|
+
``cmd_commit_check`` and receiving its nonce-bound refusal marker.
|
|
1246
|
+
"""
|
|
1247
|
+
failed = lambda detail, code=None: {
|
|
1248
|
+
"installed": False, "state": "not installed", "detail": detail,
|
|
1249
|
+
"exit": code,
|
|
1250
|
+
}
|
|
1251
|
+
if inv.get("error"):
|
|
1252
|
+
return failed("hook topology cannot be resolved: " + inv["error"])
|
|
1253
|
+
try:
|
|
1254
|
+
target = _active_hook_targets(inv)["pre-commit"]
|
|
1255
|
+
except KeyError:
|
|
1256
|
+
return failed("Git resolved no active pre-commit target")
|
|
1257
|
+
base = _state_base(target["static_state"])
|
|
1258
|
+
if base not in ("current-local", "current-scoped"):
|
|
1259
|
+
return failed(
|
|
1260
|
+
f"active pre-commit intent is {target['static_state']} / "
|
|
1261
|
+
f"{target['track_state']}"
|
|
1262
|
+
)
|
|
1263
|
+
enrollment = _project_enrollment(inv["root"])
|
|
1264
|
+
if enrollment["state"] == "uninitialized":
|
|
1265
|
+
return failed(enrollment["detail"])
|
|
1266
|
+
if enrollment["state"] in ("broken", "redirected"):
|
|
1267
|
+
return failed(enrollment["detail"])
|
|
1268
|
+
if enrollment["state"] == "legacy":
|
|
1269
|
+
# A current hook in a legacy project exits in its shell guard before polyctl
|
|
1270
|
+
# runs, so it governs nothing until the marker is adopted.
|
|
1271
|
+
return failed(enrollment["detail"])
|
|
1272
|
+
|
|
1273
|
+
head_result = _hook_git(inv["top"], "rev-parse", "--verify", "HEAD")
|
|
1274
|
+
if head_result.returncode:
|
|
1275
|
+
return failed("HEAD cannot supply the synthetic gitlink object")
|
|
1276
|
+
try:
|
|
1277
|
+
head = head_result.stdout.strip().decode("ascii", "strict")
|
|
1278
|
+
except UnicodeError:
|
|
1279
|
+
return failed("HEAD object id is not ASCII")
|
|
1280
|
+
if len(head) not in (40, 64) or any(ch not in "0123456789abcdef" for ch in head):
|
|
1281
|
+
return failed("HEAD returned an invalid object id")
|
|
1282
|
+
|
|
1283
|
+
import shutil
|
|
1284
|
+
import tempfile
|
|
1285
|
+
nonce = os.urandom(16).hex()
|
|
1286
|
+
path = ".polyctl-hook-probe-" + nonce
|
|
1287
|
+
marker = f"POLYCTL-HOOK-PROBE-REFUSED {nonce} {head} {path}".encode("ascii")
|
|
1288
|
+
# Removed without raising: a hook that runs past its timeout leaves children holding
|
|
1289
|
+
# the probe index, Windows cannot delete an open file, and the cleanup error replaced
|
|
1290
|
+
# the probe's own answer (#71). TemporaryDirectory can ignore that only from Python 3.10.
|
|
1291
|
+
temporary = tempfile.mkdtemp(prefix="polyctl-hook-probe-")
|
|
1292
|
+
try:
|
|
1293
|
+
index = os.path.abspath(os.path.join(temporary, "index"))
|
|
1294
|
+
extra = {"GIT_INDEX_FILE": index}
|
|
1295
|
+
prepared = _hook_git(inv["top"], "read-tree", "HEAD", extra_env=extra)
|
|
1296
|
+
if prepared.returncode:
|
|
1297
|
+
return failed("cannot initialize the temporary probe index")
|
|
1298
|
+
if enrollment["source"] == "index":
|
|
1299
|
+
project_marker = enrollment["marker"]
|
|
1300
|
+
carried = _hook_git(
|
|
1301
|
+
inv["top"], "update-index", "--add", "--cacheinfo",
|
|
1302
|
+
f"{project_marker['mode']},{project_marker['oid']},{PROJECT_MARKER}",
|
|
1303
|
+
extra_env=extra,
|
|
1304
|
+
)
|
|
1305
|
+
if carried.returncode:
|
|
1306
|
+
return failed("cannot carry the staged .polyctl-project into the probe index")
|
|
1307
|
+
staged = _hook_git(
|
|
1308
|
+
inv["top"], "update-index", "--add", "--cacheinfo",
|
|
1309
|
+
f"160000,{head},{path}", extra_env=extra,
|
|
1310
|
+
)
|
|
1311
|
+
if staged.returncode:
|
|
1312
|
+
return failed("cannot stage the synthetic probe candidate")
|
|
1313
|
+
extra.update({
|
|
1314
|
+
"POLYCTL_HOOK_PROBE_NONCE": nonce,
|
|
1315
|
+
"POLYCTL_HOOK_PROBE_PATH": path,
|
|
1316
|
+
"POLYCTL_HOOK_PROBE_HEAD": head,
|
|
1317
|
+
"POLYCTL_HOOK_PROBE_INDEX": index,
|
|
1318
|
+
})
|
|
1319
|
+
# The hook is polyctl itself, a Python start and a commit check: on a machine busy enough it ran past the 15
|
|
1320
|
+
# seconds this allowed, and an installed hook was reported unproven (HOOK-PROBE-TIME).
|
|
1321
|
+
result = _hook_git(
|
|
1322
|
+
inv["top"], "hook", "run", "pre-commit",
|
|
1323
|
+
timeout=S.get(None, "hooks.probe_timeout_seconds"), extra_env=extra,
|
|
1324
|
+
)
|
|
1325
|
+
except _HookResolutionError as exc:
|
|
1326
|
+
return failed(f"Git could not execute the pre-commit probe: {exc}")
|
|
1327
|
+
finally:
|
|
1328
|
+
shutil.rmtree(temporary, ignore_errors=True)
|
|
1329
|
+
|
|
1330
|
+
channels = result.stdout.splitlines() + result.stderr.splitlines()
|
|
1331
|
+
if result.returncode and marker in channels:
|
|
1332
|
+
return {
|
|
1333
|
+
"installed": True,
|
|
1334
|
+
"state": "installed",
|
|
1335
|
+
"detail": "Git executed pre-commit and polyctl refused the synthetic candidate",
|
|
1336
|
+
"exit": result.returncode,
|
|
1337
|
+
}
|
|
1338
|
+
if result.returncode == 0:
|
|
1339
|
+
return failed("Git or the resolved hook allowed the synthetic candidate", 0)
|
|
1340
|
+
# Said plainly: an alias is invisible to /bin/sh, and reinstalling the hook changes nothing (SAFE-REMOVE).
|
|
1341
|
+
cause = f": {HOOK_POLYCTL_NOT_FOUND}" if b"polyctl: polyctl not found" in result.stderr else ""
|
|
1342
|
+
return failed(
|
|
1343
|
+
f"the hook exited {result.returncode} without polyctl's nonce-bound refusal proof{cause}",
|
|
1344
|
+
result.returncode,
|
|
1345
|
+
)
|
|
1346
|
+
|
|
1347
|
+
|
|
1348
|
+
def _hook_probe_text(probe):
|
|
1349
|
+
if probe["installed"]:
|
|
1350
|
+
return "installed (execution proved)"
|
|
1351
|
+
return "not installed — " + probe["detail"]
|
|
1352
|
+
|
|
1353
|
+
|
|
1354
|
+
def _polyctl_link_fix():
|
|
1355
|
+
"""The command that puts this polyctl on PATH, where /bin/sh, a scheduler and every agent find it (SAFE-REMOVE)."""
|
|
1356
|
+
import shlex
|
|
1357
|
+
if os.name == "nt":
|
|
1358
|
+
return "put the Scripts directory pip installed polyctl.exe into on PATH"
|
|
1359
|
+
target = shlex.quote(_hook_fallback() or os.path.join(A.REPO, "bin", "polyctl"))
|
|
1360
|
+
link = os.path.join(A.HOME, ".local", "bin", "polyctl")
|
|
1361
|
+
on_path = any(os.path.realpath(d) == os.path.realpath(os.path.dirname(link))
|
|
1362
|
+
for d in os.environ.get("PATH", "").split(os.pathsep) if d)
|
|
1363
|
+
steps = [] if os.path.lexists(link) else [f"mkdir -p ~/.local/bin && ln -s {target} ~/.local/bin/polyctl"]
|
|
1364
|
+
if not on_path:
|
|
1365
|
+
steps.append("put ~/.local/bin on PATH")
|
|
1366
|
+
return " and ".join(steps) or f"~/.local/bin/polyctl does not run; point it at this polyctl: ln -sf {target} ~/.local/bin/polyctl"
|
|
1367
|
+
|
|
1368
|
+
|
|
1369
|
+
def _hook_polyctl_reach(inv):
|
|
1370
|
+
"""(what a hook's /bin/sh finds for polyctl, the fix) when polyctl is not on PATH; None when it is (SAFE-REMOVE).
|
|
1371
|
+
|
|
1372
|
+
On PATH as polyctl looks: its absolute entries, never the current directory (WINDOWS-NO-CWD-EXEC).
|
|
1373
|
+
"""
|
|
1374
|
+
if A.program_path("polyctl"):
|
|
1375
|
+
return None
|
|
1376
|
+
target = None if inv.get("error") else _active_hook_targets(inv).get("pre-commit")
|
|
1377
|
+
fallback = None
|
|
1378
|
+
if target and _state_base(target["static_state"]) in ("current-local", "current-scoped"):
|
|
1379
|
+
try:
|
|
1380
|
+
with open(target["path"], "rb") as fh:
|
|
1381
|
+
fallback = _hook_fallback_of(fh.read())
|
|
1382
|
+
except OSError:
|
|
1383
|
+
pass
|
|
1384
|
+
if fallback and os.path.isfile(fallback) and os.access(fallback, os.X_OK):
|
|
1385
|
+
told = f"{HOOK_POLYCTL_NOT_FOUND} (a shell alias is invisible to it); the hook falls back on {fallback}"
|
|
1386
|
+
else:
|
|
1387
|
+
told = f"{HOOK_POLYCTL_NOT_FOUND} (a shell alias is invisible to it); a commit fails with \"polyctl not found\""
|
|
1388
|
+
return told, _polyctl_link_fix()
|
|
1389
|
+
|
|
1390
|
+
|
|
1391
|
+
def _authorization_refusal(targets, allow):
|
|
1392
|
+
needed = [target for target in targets if target.get("needs_authorization")]
|
|
1393
|
+
if needed and os.name == "nt":
|
|
1394
|
+
# The shared hook compares Git's shell path, /c/..., with C:\..., never
|
|
1395
|
+
# matches, and lets every commit through (#71).
|
|
1396
|
+
print(f"{C['red']}refused{C['reset']} — a shared or external hook cannot recognise this "
|
|
1397
|
+
"repository on Windows, where Git's shell names it /c/... and polyctl names it C:\\...; "
|
|
1398
|
+
"install the hooks inside the repository")
|
|
1399
|
+
return True
|
|
1400
|
+
if needed and not allow:
|
|
1401
|
+
places = ", ".join(sorted({
|
|
1402
|
+
f"{target['directory_class']}:{target['directory']}"
|
|
1403
|
+
+ (" (global/system config)" if target["globally_configured"] else "")
|
|
1404
|
+
for target in needed
|
|
1405
|
+
}))
|
|
1406
|
+
print(f"{C['red']}refused{C['reset']} — shared/external/globally-configured hook mutation "
|
|
1407
|
+
f"needs --allow-shared-hooks: {places}")
|
|
1408
|
+
return True
|
|
1409
|
+
return False
|
|
1410
|
+
|
|
1411
|
+
|
|
1412
|
+
def _atomic_hook_write(path, data, role=None):
|
|
1413
|
+
"""Write one hook whole beside `path`, then put it there over nothing - or, with `role`, over polyctl's own hook for
|
|
1414
|
+
that role alone (LEADS-GATE).
|
|
1415
|
+
|
|
1416
|
+
Install reads each path, finds it free or holding polyctl's bytes, and wrote over whatever stood there
|
|
1417
|
+
by the time it wrote: a hook another tool put there in between was lost, though install keeps
|
|
1418
|
+
every hook it did not write. A free path is now taken only while it is free - a hard link on
|
|
1419
|
+
POSIX, a rename on Windows, neither of which writes over a file - and a path that held polyctl's hook
|
|
1420
|
+
is read again just before it is replaced, and replaced only while it still names the file read
|
|
1421
|
+
(LEADS-GATE-HOOK). No call replaces a file only while it is the file read, so a hook put there in
|
|
1422
|
+
the moment between that last look and the write is the one case left; taking polyctl's hook aside first
|
|
1423
|
+
would close it by leaving the path with no hook while a commit runs.
|
|
1424
|
+
"""
|
|
1425
|
+
import tempfile
|
|
1426
|
+
directory = os.path.dirname(path)
|
|
1427
|
+
fd, temporary = tempfile.mkstemp(prefix=".polyctl-hook-", dir=directory)
|
|
1428
|
+
try:
|
|
1429
|
+
with os.fdopen(fd, "wb") as fh:
|
|
1430
|
+
fh.write(data)
|
|
1431
|
+
fh.flush()
|
|
1432
|
+
os.fsync(fh.fileno())
|
|
1433
|
+
# os.fchmod exists on Windows only from Python 3.13 (#71).
|
|
1434
|
+
if hasattr(os, "fchmod"):
|
|
1435
|
+
os.fchmod(fh.fileno(), 0o755)
|
|
1436
|
+
if not hasattr(os, "fchmod"):
|
|
1437
|
+
os.chmod(temporary, 0o755)
|
|
1438
|
+
before = _file_identity(path) if role else None
|
|
1439
|
+
held = _state_base(_classify_hook(path, role)[0]) if role else "absent"
|
|
1440
|
+
if held == "legacy":
|
|
1441
|
+
# Only while the path still names the file classified: another tool's hook put there since - renamed
|
|
1442
|
+
# into place, or written over - is another file, and is left (LEADS-GATE-HOOK).
|
|
1443
|
+
if _file_identity(path) != before:
|
|
1444
|
+
raise FileExistsError(f"{path}: another hook was put there while install read it; it is left as it "
|
|
1445
|
+
"stands, and `polyctl hooks status` names it")
|
|
1446
|
+
os.replace(temporary, path)
|
|
1447
|
+
elif held != "absent":
|
|
1448
|
+
raise FileExistsError(f"{path}: a {held} hook was written there after install read it; it is left as "
|
|
1449
|
+
"it stands, and `polyctl hooks status` names it")
|
|
1450
|
+
else:
|
|
1451
|
+
_hook_put_on_free_path(temporary, path, data)
|
|
1452
|
+
finally:
|
|
1453
|
+
try:
|
|
1454
|
+
if os.path.lexists(temporary):
|
|
1455
|
+
os.remove(temporary) # still there after a link, or after a failure
|
|
1456
|
+
except OSError:
|
|
1457
|
+
pass
|
|
1458
|
+
|
|
1459
|
+
|
|
1460
|
+
def _file_identity(path):
|
|
1461
|
+
"""(device, inode, size, modified, changed, a digest of the bytes) of what `path` names, without following a link;
|
|
1462
|
+
None where nothing is there (LEADS-GATE-HOOK).
|
|
1463
|
+
|
|
1464
|
+
A rewrite in place keeps the inode, and another tool can keep the size and set the modified time back; it
|
|
1465
|
+
cannot set back the time the inode changed, and the bytes are read besides.
|
|
1466
|
+
"""
|
|
1467
|
+
import hashlib
|
|
1468
|
+
try:
|
|
1469
|
+
st = os.lstat(path)
|
|
1470
|
+
with open(path, "rb") as fh:
|
|
1471
|
+
digest = hashlib.sha256(fh.read()).hexdigest()
|
|
1472
|
+
except OSError:
|
|
1473
|
+
return None
|
|
1474
|
+
return st.st_dev, st.st_ino, st.st_size, st.st_mtime_ns, st.st_ctime_ns, digest
|
|
1475
|
+
|
|
1476
|
+
|
|
1477
|
+
def _hook_put_on_free_path(temporary, path, data):
|
|
1478
|
+
"""Put a written hook at `path` only while nothing is there (LEADS-GATE): Windows' rename writes over no file, and
|
|
1479
|
+
on POSIX a hard link does not either - or, on a file system that makes none, a file created only while the path
|
|
1480
|
+
is free, written and synced with no one's execute bit, and only then made executable. Created executable, it stood
|
|
1481
|
+
empty while it was written, and Git ran the empty hook, which lets every commit through; not yet executable, Git
|
|
1482
|
+
runs no hook there, as it ran none before install began."""
|
|
1483
|
+
try:
|
|
1484
|
+
if os.name == "nt":
|
|
1485
|
+
os.rename(temporary, path)
|
|
1486
|
+
return
|
|
1487
|
+
try:
|
|
1488
|
+
os.link(temporary, path)
|
|
1489
|
+
except FileExistsError:
|
|
1490
|
+
raise
|
|
1491
|
+
except OSError:
|
|
1492
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
1493
|
+
try:
|
|
1494
|
+
with os.fdopen(fd, "wb") as fh:
|
|
1495
|
+
fh.write(data)
|
|
1496
|
+
fh.flush()
|
|
1497
|
+
os.fsync(fh.fileno())
|
|
1498
|
+
os.fchmod(fh.fileno(), 0o755) # executable once whole, never before
|
|
1499
|
+
except BaseException:
|
|
1500
|
+
try:
|
|
1501
|
+
os.remove(path) # the file this created, half written
|
|
1502
|
+
except OSError:
|
|
1503
|
+
pass
|
|
1504
|
+
raise
|
|
1505
|
+
except FileExistsError:
|
|
1506
|
+
raise FileExistsError(f"{path}: a hook was written there after install found the path free; it is left "
|
|
1507
|
+
"as it stands, and `polyctl hooks status` names it") from None
|
|
1508
|
+
|
|
1509
|
+
|
|
1510
|
+
def _print_hook_status(inv):
|
|
1511
|
+
proof = _hook_execution_probe(inv)
|
|
1512
|
+
if inv["error"]:
|
|
1513
|
+
print(f"resolver failure: {inv['error']}")
|
|
1514
|
+
print(f"pre-commit execution: {_hook_probe_text(proof)}")
|
|
1515
|
+
return
|
|
1516
|
+
print(f"effective hooks: {inv['active_dir']}")
|
|
1517
|
+
facts = []
|
|
1518
|
+
for status in ("reachable", "locked", "stale"):
|
|
1519
|
+
count = sum(1 for row in inv["worktrees"] if row["status"] == status)
|
|
1520
|
+
if count:
|
|
1521
|
+
facts.append(f"{count} {status}")
|
|
1522
|
+
print(f"class: {inv['directory_class']}" + (f" ({'; '.join(facts)})" if facts else ""))
|
|
1523
|
+
config = inv["config"]
|
|
1524
|
+
if config["set"]:
|
|
1525
|
+
print(f"core.hooksPath: {config['scope']} {config['origin']} value={config['value']!r}")
|
|
1526
|
+
else:
|
|
1527
|
+
print("core.hooksPath: unset")
|
|
1528
|
+
active = _active_hook_targets(inv)
|
|
1529
|
+
for role in _HOOK_ROLES:
|
|
1530
|
+
target = active[role]
|
|
1531
|
+
note = ""
|
|
1532
|
+
if role == "pre-push" and _state_base(target["static_state"]) not in (
|
|
1533
|
+
"current-local", "current-scoped"
|
|
1534
|
+
):
|
|
1535
|
+
note = " — polyctl push-window hook unavailable"
|
|
1536
|
+
print(f"{role}: {target['static_state']} / {target['track_state']}{note}")
|
|
1537
|
+
print(f"pre-commit execution: {_hook_probe_text(proof)}")
|
|
1538
|
+
reach = _hook_polyctl_reach(inv)
|
|
1539
|
+
if reach:
|
|
1540
|
+
print(f"polyctl for hooks: {reach[0]}")
|
|
1541
|
+
print(f" fix: {reach[1]}")
|
|
1542
|
+
for target in inv["targets"]:
|
|
1543
|
+
if target["active"] or _state_base(target["static_state"]) in ("absent", "foreign"):
|
|
1544
|
+
continue
|
|
1545
|
+
print(f"misplaced {target['role']}: {target['static_state']} / "
|
|
1546
|
+
f"{target['track_state']} / {target['reachability']} / "
|
|
1547
|
+
f"{target['directory_class']} — {target['path']}")
|
|
1548
|
+
|
|
1549
|
+
|
|
1550
|
+
def _hook_removal_plan(inv):
|
|
1551
|
+
"""The hook files an uninstall takes: polyctl's exact bytes, current or legacy, untracked, at a target it may write.
|
|
1552
|
+
|
|
1553
|
+
One choice for `polyctl hooks uninstall` and `polyctl uninstall`, so what the machine-wide dry run lists is what goes.
|
|
1554
|
+
"""
|
|
1555
|
+
return [
|
|
1556
|
+
target for target in inv["targets"]
|
|
1557
|
+
if target["eligible"] and _state_base(target["static_state"])
|
|
1558
|
+
in ("current-local", "current-scoped", "legacy")
|
|
1559
|
+
]
|
|
1560
|
+
|
|
1561
|
+
|
|
1562
|
+
def _hooks_uninstall(inv, allow):
|
|
1563
|
+
plan = _hook_removal_plan(inv)
|
|
1564
|
+
if _authorization_refusal(plan, allow):
|
|
1565
|
+
return 1
|
|
1566
|
+
failed = False
|
|
1567
|
+
for target in plan:
|
|
1568
|
+
try:
|
|
1569
|
+
# A plan may precede other removal work. Re-read ownership and topology, then check that the
|
|
1570
|
+
# file read still stands there; unlink has no compare-and-remove operation (LEADS-OPEN).
|
|
1571
|
+
before = _file_identity(target["path"])
|
|
1572
|
+
fresh = _polyctl_hook_inventory(inv["root"])
|
|
1573
|
+
current = next((item for item in _hook_removal_plan(fresh)
|
|
1574
|
+
if item["path"] == target["path"] and item["role"] == target["role"]), None)
|
|
1575
|
+
if (fresh["error"] or current is None or before is None
|
|
1576
|
+
or _authorization_refusal([current], allow)
|
|
1577
|
+
or _file_identity(target["path"]) != before):
|
|
1578
|
+
failed = True
|
|
1579
|
+
print(f"left {A.shown_text(target['path'])}: its ownership, location or file changed; "
|
|
1580
|
+
"inspect polyctl hooks status before uninstalling again")
|
|
1581
|
+
continue
|
|
1582
|
+
os.remove(target["path"])
|
|
1583
|
+
print(f"removed {target['role']} — {target['path']}")
|
|
1584
|
+
except OSError as exc:
|
|
1585
|
+
failed = True
|
|
1586
|
+
print(f"{C['red']}failed to remove{C['reset']} {target['path']}: {exc}")
|
|
1587
|
+
if failed:
|
|
1588
|
+
return 1
|
|
1589
|
+
after = _polyctl_hook_inventory(inv["root"])
|
|
1590
|
+
if after["error"]:
|
|
1591
|
+
print(f"resolver failure after uninstall: {after['error']}")
|
|
1592
|
+
return 1
|
|
1593
|
+
blockers = []
|
|
1594
|
+
for target in after["targets"]:
|
|
1595
|
+
base = _state_base(target["static_state"])
|
|
1596
|
+
if base not in ("current-local", "current-scoped", "legacy", "ambiguous-polyctl"):
|
|
1597
|
+
continue
|
|
1598
|
+
if target["reachability"] == "dead-misplaced" and target["protected"]:
|
|
1599
|
+
print(f"preserved protected dead-misplaced {target['role']}: {target['path']}")
|
|
1600
|
+
continue
|
|
1601
|
+
if target["reachability"] == "potentially-effective":
|
|
1602
|
+
blockers.append(target)
|
|
1603
|
+
print(f"preserved potentially-effective {target['static_state']} {target['role']}: "
|
|
1604
|
+
f"{target['path']}")
|
|
1605
|
+
return 1 if blockers else 0
|
|
1606
|
+
|
|
1607
|
+
|
|
1608
|
+
def _hook_stands_aside(enrollment):
|
|
1609
|
+
"""Whether the hook has no marker, history or record that makes it ask polyctl.
|
|
1610
|
+
|
|
1611
|
+
Unknown enrollment cannot authorize installing a hook, regardless of its guard.
|
|
1612
|
+
"""
|
|
1613
|
+
return (not enrollment.get("unknown") and not enrollment.get("recordable")
|
|
1614
|
+
and enrollment["state"] in ("legacy", "broken"))
|
|
1615
|
+
|
|
1616
|
+
|
|
1617
|
+
def _stand_aside_repair(enrollment, said=None):
|
|
1618
|
+
"""What a person does in a project the current hook would stand aside in, where `polyctl hooks install` is refused: the
|
|
1619
|
+
adoption, after what polyctl cannot read there is made readable; `said`, a text already shown, is not repeated
|
|
1620
|
+
(TRIAGE-HIGHS).
|
|
1621
|
+
|
|
1622
|
+
A project set up before .polyctl-project whose config could not be read read as broken, not legacy: install went
|
|
1623
|
+
ahead there, and `polyctl doctor` and `polyctl prove` advised it."""
|
|
1624
|
+
if enrollment["state"] == "legacy" or enrollment.get("recordable"):
|
|
1625
|
+
return None if said == enrollment["detail"] else enrollment["detail"]
|
|
1626
|
+
step = f"make it readable, then {PROJECT_ADOPT_HINT}"
|
|
1627
|
+
return step if said == enrollment["detail"] else f"{enrollment['detail']} - {step}"
|
|
1628
|
+
|
|
1629
|
+
|
|
1630
|
+
def _hook_install_problem(enrollment, said=None):
|
|
1631
|
+
"""One decision for installation and its advice, from the complete enrollment reading.
|
|
1632
|
+
|
|
1633
|
+
Failed queries permit neither installation nor adoption. Positive marker/history/record evidence
|
|
1634
|
+
permits an enforcing hook; known pre-marker state needs adoption, even on an unborn or orphan HEAD.
|
|
1635
|
+
Omit detail already printed by an execution probe when composing its repair advice.
|
|
1636
|
+
"""
|
|
1637
|
+
if enrollment.get("unknown") or enrollment["state"] == "redirected":
|
|
1638
|
+
return None if said == enrollment["detail"] else enrollment["detail"]
|
|
1639
|
+
if _hook_stands_aside(enrollment):
|
|
1640
|
+
return _stand_aside_repair(enrollment, said=said)
|
|
1641
|
+
return None
|
|
1642
|
+
|
|
1643
|
+
|
|
1644
|
+
def _hooks_install(cfg, allow_shared_hooks=False):
|
|
1645
|
+
"""Install eligible hooks and return `(rc, problems)` keyed by role or `'install'` (INIT-OWN-PRE-PUSH-3)."""
|
|
1646
|
+
problems = {}
|
|
1647
|
+
root = cfg["root"]
|
|
1648
|
+
enrollment = _project_enrollment(root)
|
|
1649
|
+
redirected = (enrollment["detail"] if enrollment["state"] == "redirected"
|
|
1650
|
+
else _commit_repository_binding(root))
|
|
1651
|
+
if redirected:
|
|
1652
|
+
problems["install"] = redirected
|
|
1653
|
+
print(f"{C['red']}hooks install refused{C['reset']}: {redirected}")
|
|
1654
|
+
return 1, problems
|
|
1655
|
+
install_problem = _hook_install_problem(enrollment)
|
|
1656
|
+
if enrollment.get("unknown"):
|
|
1657
|
+
problems["install"] = install_problem
|
|
1658
|
+
print(f"{C['red']}hooks install refused{C['reset']}: {install_problem}")
|
|
1659
|
+
return 1, problems
|
|
1660
|
+
inv = _polyctl_hook_inventory(root)
|
|
1661
|
+
if inv["error"]:
|
|
1662
|
+
problems["install"] = inv["error"]
|
|
1663
|
+
print(f"{C['red']}hook resolver failed{C['reset']}: {inv['error']}")
|
|
1664
|
+
return 1, problems
|
|
1665
|
+
allow = bool(allow_shared_hooks)
|
|
1666
|
+
|
|
1667
|
+
if install_problem:
|
|
1668
|
+
problems["install"] = install_problem
|
|
1669
|
+
# The current hooks exit in their shell guard when no marker is tracked, so
|
|
1670
|
+
# installing them over a legacy project's enforcing hook would turn commit
|
|
1671
|
+
# authority off at exactly the moment someone meant to repair it. Adoption
|
|
1672
|
+
# stages the marker first and installs them after it (INIT-ADOPTION). A project
|
|
1673
|
+
# from before the marker whose state cannot be read is that project too: its
|
|
1674
|
+
# old hook refuses every commit, and the current one would let each through
|
|
1675
|
+
# (TRIAGE-HIGHS).
|
|
1676
|
+
print(f"{C['red']}hooks install refused{C['reset']}: {install_problem}")
|
|
1677
|
+
print(f" {C['dim']}the current hooks stand aside while no {PROJECT_MARKER} is tracked, so installing "
|
|
1678
|
+
f"them before it would switch commit authority off{C['reset']}")
|
|
1679
|
+
return 1, problems
|
|
1680
|
+
|
|
1681
|
+
pre_fields = _manifest_pre_push_fields(root, inv)
|
|
1682
|
+
if enrollment.get("recordable"):
|
|
1683
|
+
# Only positively established enrollment reaches this write. Legacy state
|
|
1684
|
+
# and unanswered queries must remain adoptable without an enrollment record.
|
|
1685
|
+
unkept = A.record_enrollment(_project_repository_top(root) or root)
|
|
1686
|
+
if unkept:
|
|
1687
|
+
problems["install"] = unkept
|
|
1688
|
+
print(f"{C['red']}hooks install refused{C['reset']}: this machine cannot record that the project is "
|
|
1689
|
+
f"enrolled: {unkept}")
|
|
1690
|
+
return 1, problems
|
|
1691
|
+
|
|
1692
|
+
active = _active_hook_targets(inv)
|
|
1693
|
+
plan, unavailable = [], []
|
|
1694
|
+
for role in _HOOK_ROLES:
|
|
1695
|
+
target = active[role]
|
|
1696
|
+
base = _state_base(target["static_state"])
|
|
1697
|
+
if base in ("current-local", "current-scoped"):
|
|
1698
|
+
continue
|
|
1699
|
+
if target["eligible"] and base in ("absent", "legacy"):
|
|
1700
|
+
plan.append(target)
|
|
1701
|
+
else:
|
|
1702
|
+
unavailable.append(target)
|
|
1703
|
+
problems[role] = f"{target['path']} is {target['static_state']} / {target['track_state']}"
|
|
1704
|
+
print(f"preserved {target['static_state']} {role} / {target['track_state']} — "
|
|
1705
|
+
f"polyctl {'commit authority' if role == 'pre-commit' else 'push-window'} hook unavailable")
|
|
1706
|
+
if _authorization_refusal(plan, allow):
|
|
1707
|
+
problems["install"] = "hook directory requires --allow-shared-hooks"
|
|
1708
|
+
return 1, problems
|
|
1709
|
+
if plan:
|
|
1710
|
+
if os.path.lexists(inv["active_dir"]) and not os.path.isdir(inv["active_dir"]):
|
|
1711
|
+
problems["install"] = f"effective hook path is not a directory: {inv['active_dir']}"
|
|
1712
|
+
print(f"{C['red']}effective hook path is not a directory{C['reset']}: {inv['active_dir']}")
|
|
1713
|
+
return 1, problems
|
|
1714
|
+
try:
|
|
1715
|
+
os.makedirs(inv["active_dir"], exist_ok=True)
|
|
1716
|
+
except OSError as exc:
|
|
1717
|
+
problems["install"] = f"cannot create hook directory: {exc}"
|
|
1718
|
+
print(f"{C['red']}cannot create hook directory{C['reset']}: {exc}")
|
|
1719
|
+
return 1, problems
|
|
1720
|
+
# Directory creation and another process can change classification. Re-read
|
|
1721
|
+
# once, then authorize the whole write set again before the first replace.
|
|
1722
|
+
fresh = _polyctl_hook_inventory(root)
|
|
1723
|
+
if fresh["error"] or fresh["active_dir"] != inv["active_dir"] \
|
|
1724
|
+
or fresh["directory_class"] != inv["directory_class"] \
|
|
1725
|
+
or fresh["globally_configured"] != inv["globally_configured"]:
|
|
1726
|
+
problems["install"] = "hook topology changed during install"
|
|
1727
|
+
print(f"{C['red']}hook topology changed during install; no hook written{C['reset']}")
|
|
1728
|
+
return 1, problems
|
|
1729
|
+
fresh_active = _active_hook_targets(fresh)
|
|
1730
|
+
fresh_plan = [fresh_active[target["role"]] for target in plan]
|
|
1731
|
+
if any(not target["eligible"] or _state_base(target["static_state"])
|
|
1732
|
+
not in ("absent", "legacy") for target in fresh_plan):
|
|
1733
|
+
problems["install"] = "hook target changed during install"
|
|
1734
|
+
print(f"{C['red']}hook target changed during install; no hook written{C['reset']}")
|
|
1735
|
+
return 1, problems
|
|
1736
|
+
if _authorization_refusal(fresh_plan, allow):
|
|
1737
|
+
problems["install"] = "hook directory requires --allow-shared-hooks"
|
|
1738
|
+
return 1, problems
|
|
1739
|
+
for target in fresh_plan:
|
|
1740
|
+
try:
|
|
1741
|
+
# polyctl's own hook is written over; a free path is taken only while it is still free (LEADS-GATE).
|
|
1742
|
+
_atomic_hook_write(target["path"], target["body"],
|
|
1743
|
+
target["role"] if _state_base(target["static_state"]) == "legacy" else None)
|
|
1744
|
+
print(f"installed {target['role']} — {target['path']}")
|
|
1745
|
+
except OSError as exc:
|
|
1746
|
+
problems[target["role"]] = str(exc)
|
|
1747
|
+
print(f"{C['red']}failed to install{C['reset']} {target['role']}: {exc}")
|
|
1748
|
+
return 1, problems
|
|
1749
|
+
final = _polyctl_hook_inventory(root)
|
|
1750
|
+
if final["error"]:
|
|
1751
|
+
problems["install"] = final["error"]
|
|
1752
|
+
return 1, problems
|
|
1753
|
+
_record_pre_push_provenance(root, inv, final, fields=pre_fields)
|
|
1754
|
+
final_active = _active_hook_targets(final)
|
|
1755
|
+
ok = all(_state_base(final_active[role]["static_state"])
|
|
1756
|
+
in ("current-local", "current-scoped") for role in _HOOK_ROLES)
|
|
1757
|
+
if ok:
|
|
1758
|
+
print(f"{C['green']}current (behavior unverified){C['reset']} — static hook intent installed; "
|
|
1759
|
+
"run `polyctl hooks status` for execution proof")
|
|
1760
|
+
return (0 if ok else 1), problems
|
|
1761
|
+
|
|
1762
|
+
|
|
1763
|
+
def cmd_hooks(cfg, args):
|
|
1764
|
+
"""Manage polyctl hook intent at Git's effective path without replacing user hooks."""
|
|
1765
|
+
action = args.action
|
|
1766
|
+
allow = bool(getattr(args, "allow_shared_hooks", False))
|
|
1767
|
+
if action == "install":
|
|
1768
|
+
return _hooks_install(cfg, allow_shared_hooks=allow)[0]
|
|
1769
|
+
root = cfg["root"]
|
|
1770
|
+
enrollment = _project_enrollment(root)
|
|
1771
|
+
# A .git can appear after enrollment was read, before inventory or the record's destination is selected.
|
|
1772
|
+
# Refuse it before either repository is changed, including on an orphan branch outside a hook (NESTED-GIT).
|
|
1773
|
+
redirected = (enrollment["detail"] if enrollment["state"] == "redirected"
|
|
1774
|
+
else _commit_repository_binding(root))
|
|
1775
|
+
if redirected:
|
|
1776
|
+
print(f"{C['red']}hooks {action} refused{C['reset']}: {redirected}")
|
|
1777
|
+
return 1
|
|
1778
|
+
install_problem = _hook_install_problem(enrollment)
|
|
1779
|
+
if enrollment.get("unknown"):
|
|
1780
|
+
print(f"{C['red']}hooks {action} refused{C['reset']}: {install_problem}")
|
|
1781
|
+
return 1
|
|
1782
|
+
inv = _polyctl_hook_inventory(root)
|
|
1783
|
+
if inv["error"]:
|
|
1784
|
+
print(f"{C['red']}hook resolver failed{C['reset']}: {inv['error']}")
|
|
1785
|
+
return 1
|
|
1786
|
+
if action == "status":
|
|
1787
|
+
_print_hook_status(inv)
|
|
1788
|
+
return 0
|
|
1789
|
+
return _hooks_uninstall(inv, allow)
|
|
1790
|
+
|
|
1791
|
+
|
|
1792
|
+
def cmd_push(cfg, args):
|
|
1793
|
+
"""`polyctl push allow [--minutes N]` opens a window for a person's push; `check` is what the hook runs."""
|
|
1794
|
+
root = cfg["root"]
|
|
1795
|
+
tok = A.project_file(root, "push-window")
|
|
1796
|
+
if args.action == "allow":
|
|
1797
|
+
os.makedirs(os.path.dirname(tok), exist_ok=True)
|
|
1798
|
+
json.dump({"at": int(time.time()), "minutes": args.minutes, "by": os.environ.get("USER", "human")}, open(tok, "w", encoding=UTF8))
|
|
1799
|
+
print(f"{C['green']}push allowed{C['reset']} for {args.minutes} minutes"); return 0
|
|
1800
|
+
if args.action == "check":
|
|
1801
|
+
if project_mode(dict(A.load_config(root), root=root)) == "lite":
|
|
1802
|
+
return 0
|
|
1803
|
+
try:
|
|
1804
|
+
t = json.load(open(tok, encoding=UTF8))
|
|
1805
|
+
if time.time() - t["at"] <= t.get("minutes", 30) * 60:
|
|
1806
|
+
return 0
|
|
1807
|
+
except (OSError, ValueError, KeyError):
|
|
1808
|
+
pass
|
|
1809
|
+
sys.stderr.write("polyctl: push refused — pushing is a human decision. Run `polyctl push allow` and push again.\n")
|
|
1810
|
+
return 1
|
|
1811
|
+
try:
|
|
1812
|
+
t = json.load(open(tok, encoding=UTF8)); left = t.get("minutes", 30) * 60 - (time.time() - t["at"])
|
|
1813
|
+
print(f"push window: {'open, ' + str(int(left // 60)) + 'm left' if left > 0 else 'closed'}")
|
|
1814
|
+
except (OSError, ValueError, KeyError):
|
|
1815
|
+
print("push window: closed")
|
|
1816
|
+
return 0
|