claude-dev-env 8.115.0 → 8.116.1

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.
Files changed (44) hide show
  1. package/bin/install.prompt-context.test.mjs +5 -6
  2. package/docs/rule-guides/verified-work.md +1 -1
  3. package/hooks/advisory/commit_and_pull_request_words.py +346 -0
  4. package/hooks/advisory/piece_clauses.py +248 -0
  5. package/hooks/advisory/pieces_per_level_analysis.py +192 -0
  6. package/hooks/advisory/pieces_per_level_note.py +265 -0
  7. package/hooks/advisory/test_commit_and_pull_request_words.py +126 -0
  8. package/hooks/advisory/test_piece_clauses.py +183 -0
  9. package/hooks/advisory/test_pieces_per_level_note.py +389 -0
  10. package/hooks/advisory/test_pieces_per_level_note_bounds.py +215 -0
  11. package/hooks/advisory/test_pieces_per_level_note_deadline.py +282 -0
  12. package/hooks/blocking/final_reply_gate.py +7 -29
  13. package/hooks/blocking/test_final_reply_gate.py +4 -196
  14. package/hooks/features/README.md +1 -1
  15. package/hooks/features/conduct-gates.md +5 -12
  16. package/hooks/features/session-context.md +4 -1
  17. package/hooks/hooks.json +10 -41
  18. package/hooks/hooks_constants/background_silence_prompt_constants.py +2 -0
  19. package/hooks/hooks_constants/pieces_per_level_note_constants.py +255 -0
  20. package/hooks/hooks_constants/resolve_thread_reply_gate_constants.py +0 -8
  21. package/hooks/hooks_constants/shell_command_wrappers.py +20 -8
  22. package/hooks/hooks_constants/test_shell_command_wrappers.py +7 -0
  23. package/hooks/session/background_silence_prompt.py +1 -1
  24. package/hooks/test_context_budget_hooks.py +0 -1
  25. package/package.json +1 -1
  26. package/scripts/durable_post_lint.py +0 -12
  27. package/scripts/durable_post_lint_config/config/constants.py +1 -2
  28. package/scripts/policy_lint/adapter_configuration.py +0 -2
  29. package/scripts/policy_lint/config/constants.py +0 -2
  30. package/scripts/test_durable_post_lint.py +0 -53
  31. package/scripts/tests/test_adapter_configuration.py +0 -16
  32. package/scripts/tests/test_verified_work_rule.py +13 -0
  33. package/hooks/blocking/chat_reply_gate.py +0 -260
  34. package/hooks/blocking/reply_length_gate.py +0 -804
  35. package/hooks/blocking/test_chat_reply_gate.py +0 -302
  36. package/hooks/blocking/test_reply_length_gate.py +0 -1324
  37. package/hooks/hooks_constants/chat_reply_gate_constants.py +0 -60
  38. package/hooks/hooks_constants/reply_length_gate_constants.py +0 -203
  39. package/hooks/hooks_constants/test_reply_length_gate_constants.py +0 -81
  40. package/hooks/hooks_constants/test_visual_reply_rules_constants.py +0 -50
  41. package/hooks/hooks_constants/visual_reply_rules_constants.py +0 -106
  42. package/hooks/test_visual_reply_rules.py +0 -362
  43. package/hooks/visual_reply_rules.py +0 -478
  44. package/rules/visual-reply-rules.json +0 -56
@@ -0,0 +1,192 @@
1
+ """Find the pieces a commit or pull request create names, and build the context note.
2
+
3
+ This module holds the analysis only: ``decide_hook_output`` maps a PreToolUse
4
+ payload to the note, or to None. ``pieces_per_level_note.py`` runs it in a child
5
+ process under a wall-clock deadline. The signals, all from the author's own
6
+ words:
7
+
8
+ - A conventional subject or title whose description joins two or more
9
+ verb-led clauses with commas, semicolons, or "and".
10
+ - A pull request body whose "Proof in practice" section holds more than one
11
+ without/with pair.
12
+ - A pull request body whose "What this does" section holds more than one
13
+ bold-led topic bullet.
14
+
15
+ A single behaviour with a compound object or an alternative stays silent, and
16
+ so does a message or body the analysis cannot read. A command longer than
17
+ ``MAXIMUM_COMMAND_CHARACTERS`` gets no note, and a message or body file is read
18
+ only when it is a regular file, and only up to ``MAXIMUM_FILE_BYTES`` bytes. A
19
+ title, a body, and a line of a body are read only up to their character caps.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import sys
25
+ from pathlib import Path
26
+
27
+ hooks_root_directory = str(Path(__file__).resolve().parent.parent)
28
+ if hooks_root_directory not in sys.path:
29
+ sys.path.insert(0, hooks_root_directory)
30
+ advisory_directory = str(Path(__file__).resolve().parent)
31
+ if advisory_directory not in sys.path:
32
+ sys.path.insert(0, advisory_directory)
33
+
34
+ import commit_and_pull_request_words
35
+ import piece_clauses
36
+ from hooks_constants.followup_pr_dedupe_constants import CREATE_PULL_REQUEST_TOOL_SUFFIX
37
+ from hooks_constants.hook_specific_output_keys import (
38
+ HOOK_EVENT_NAME_KEY,
39
+ HOOK_SPECIFIC_OUTPUT_KEY,
40
+ )
41
+ from hooks_constants.pieces_per_level_note_constants import (
42
+ ADDITIONAL_CONTEXT_KEY,
43
+ ALL_NEXT_COMMAND_BY_KIND,
44
+ ALL_QUICK_SCAN_WORDS,
45
+ BODY_INPUT_KEY,
46
+ COMMAND_INPUT_KEY,
47
+ COMMIT_KIND,
48
+ MAXIMUM_COMMAND_CHARACTERS,
49
+ MAXIMUM_NAMED_PIECES,
50
+ MINIMUM_PROOF_PAIR_COUNT,
51
+ MORE_PIECES_TEMPLATE,
52
+ NOTE_TEMPLATE,
53
+ PIECE_SEPARATOR,
54
+ PRE_TOOL_USE_EVENT_NAME,
55
+ PROOF_PAIRS_PIECE_TEMPLATE,
56
+ PULL_REQUEST_KIND,
57
+ QUOTED_PIECE_TEMPLATE,
58
+ TITLE_INPUT_KEY,
59
+ TOOL_INPUT_KEY,
60
+ TOOL_NAME_KEY,
61
+ WORKING_DIRECTORY_KEY,
62
+ )
63
+ from hooks_constants.pre_tool_use_context_runner import run_context_hook
64
+ from hooks_constants.pr_lifecycle_skill_gate_constants import SHELL_TOOL_NAMES
65
+
66
+
67
+ def _capped(all_pieces: list[str]) -> list[str]:
68
+ if len(all_pieces) <= MAXIMUM_NAMED_PIECES:
69
+ return all_pieces
70
+ all_hidden_count = len(all_pieces) - MAXIMUM_NAMED_PIECES
71
+ return [*all_pieces[:MAXIMUM_NAMED_PIECES], MORE_PIECES_TEMPLATE.format(count=all_hidden_count)]
72
+
73
+
74
+ def _quoted(all_pieces: list[str]) -> list[str]:
75
+ return [QUOTED_PIECE_TEMPLATE.format(piece=each_piece) for each_piece in all_pieces]
76
+
77
+
78
+ def commit_pieces(command: str, working_directory: str) -> list[str]:
79
+ """Return the quoted pieces the first several-piece commit subject names, else an empty list.
80
+
81
+ Args:
82
+ command: The shell command text the agent ran.
83
+ working_directory: The folder a relative ``-F`` path resolves against.
84
+ """
85
+ for each_subject in commit_and_pull_request_words.commit_subjects(command, working_directory):
86
+ all_pieces = piece_clauses.subject_pieces(each_subject)
87
+ if all_pieces:
88
+ return _capped(_quoted(all_pieces))
89
+ return []
90
+
91
+
92
+ def pull_request_pieces(title: str | None, body: str | None) -> list[str]:
93
+ """Return what a pull request's title and body name as several pieces, else an empty list.
94
+
95
+ The title's verb-led clauses come first, or the body's bold-led topics
96
+ when the title names one piece. A body with more than one without/with
97
+ proof pair adds that count.
98
+
99
+ Args:
100
+ title: The pull request title, or None.
101
+ body: The pull request body, or None.
102
+ """
103
+ all_title_pieces = _quoted(piece_clauses.subject_pieces(title or ""))
104
+ all_topics = piece_clauses.topic_bullets(body) if body else []
105
+ all_topic_pieces = _quoted(all_topics) if len(all_topics) >= MINIMUM_PROOF_PAIR_COUNT else []
106
+ pair_count = piece_clauses.proof_pair_count(body) if body else 0
107
+ all_pair_pieces = (
108
+ [PROOF_PAIRS_PIECE_TEMPLATE.format(count=pair_count)]
109
+ if pair_count >= MINIMUM_PROOF_PAIR_COUNT
110
+ else []
111
+ )
112
+ return [*_capped(all_title_pieces or all_topic_pieces), *all_pair_pieces]
113
+
114
+
115
+ def _note_output(kind: str, all_pieces: list[str]) -> dict[str, object]:
116
+ note_text = NOTE_TEMPLATE.format(
117
+ kind=kind,
118
+ pieces=PIECE_SEPARATOR.join(all_pieces),
119
+ next_command=ALL_NEXT_COMMAND_BY_KIND[kind],
120
+ )
121
+ return {
122
+ HOOK_SPECIFIC_OUTPUT_KEY: {
123
+ HOOK_EVENT_NAME_KEY: PRE_TOOL_USE_EVENT_NAME,
124
+ ADDITIONAL_CONTEXT_KEY: note_text,
125
+ }
126
+ }
127
+
128
+
129
+ def _is_scannable_command(command: object) -> bool:
130
+ return (
131
+ isinstance(command, str)
132
+ and len(command) <= MAXIMUM_COMMAND_CHARACTERS
133
+ and any(each_word in command for each_word in ALL_QUICK_SCAN_WORDS)
134
+ )
135
+
136
+
137
+ def _shell_note(command: object, working_directory: str) -> dict[str, object] | None:
138
+ if not isinstance(command, str) or not _is_scannable_command(command):
139
+ return None
140
+ all_commit_pieces = commit_pieces(command, working_directory)
141
+ if all_commit_pieces:
142
+ return _note_output(COMMIT_KIND, all_commit_pieces)
143
+ for each_title, each_body in commit_and_pull_request_words.pull_request_words(
144
+ command, working_directory
145
+ ):
146
+ all_pieces = pull_request_pieces(each_title, each_body)
147
+ if all_pieces:
148
+ return _note_output(PULL_REQUEST_KIND, all_pieces)
149
+ return None
150
+
151
+
152
+ def _text_field(all_fields: dict[str, object], field_name: str) -> str | None:
153
+ field_text = all_fields.get(field_name)
154
+ return field_text if isinstance(field_text, str) else None
155
+
156
+
157
+ def decide_hook_output(all_hook_fields: dict[str, object]) -> dict[str, object] | None:
158
+ """Return the note as additionalContext output, or None to stay quiet.
159
+
160
+ Args:
161
+ all_hook_fields: The parsed PreToolUse payload.
162
+
163
+ Returns:
164
+ The ``hookSpecificOutput`` object with the note, or None when the call
165
+ is no commit or pull request create, or its words name one piece.
166
+ The output never carries a permission decision.
167
+ """
168
+ all_tool_input = all_hook_fields.get(TOOL_INPUT_KEY)
169
+ tool_name = all_hook_fields.get(TOOL_NAME_KEY)
170
+ if not isinstance(all_tool_input, dict) or not isinstance(tool_name, str):
171
+ return None
172
+ working_directory = all_hook_fields.get(WORKING_DIRECTORY_KEY)
173
+ if tool_name in SHELL_TOOL_NAMES:
174
+ return _shell_note(
175
+ all_tool_input.get(COMMAND_INPUT_KEY),
176
+ working_directory if isinstance(working_directory, str) else "",
177
+ )
178
+ if not tool_name.endswith(CREATE_PULL_REQUEST_TOOL_SUFFIX):
179
+ return None
180
+ all_pieces = pull_request_pieces(
181
+ _text_field(all_tool_input, TITLE_INPUT_KEY), _text_field(all_tool_input, BODY_INPUT_KEY)
182
+ )
183
+ return _note_output(PULL_REQUEST_KIND, all_pieces) if all_pieces else None
184
+
185
+
186
+ def main() -> int:
187
+ """Read the PreToolUse payload and print the note when the words name several pieces.
188
+
189
+ Returns:
190
+ 0 in every case; the note travels in the JSON output.
191
+ """
192
+ return run_context_hook(decide_hook_output)
@@ -0,0 +1,265 @@
1
+ #!/usr/bin/env python3
2
+ """PreToolUse context note: several pieces in one commit or pull request get one level each.
3
+
4
+ This hook never blocks, denies, or exits non-zero. It reads the author's own
5
+ words when an agent runs ``git commit`` (the subject from ``-m``, ``--message``,
6
+ or the file ``-F`` names) or opens a pull request (``gh pr create``,
7
+ ``pull_request.py create``, a ``create_pull_request`` tool). When those words
8
+ name several pieces, it adds one short note as ``additionalContext``::
9
+
10
+ Your own words name several pieces in this commit: "always publish drawn
11
+ icons"; "put Tips on the tray". Each piece gets its own commit and its own
12
+ stack level ... The commit that is running holds every piece. To split it,
13
+ run `git reset --soft HEAD~1` ...
14
+
15
+ The analysis lives in ``pieces_per_level_analysis.py``. This script is the
16
+ parent that runs it:
17
+
18
+ 1. A cheap linear check on the raw payload. The call must hold a ``git commit``
19
+ with a message flag, or a pull request create, as whole words, and its text
20
+ must hold a clause separator (a comma, a semicolon, "and") or a body option.
21
+ The MCP create tool needs a separator in its title or a body. Any other call
22
+ gets no note, and no child process starts.
23
+ 2. The analysis runs in a child process (this script with ``--analyze``) under
24
+ one wall-clock deadline for the whole child, from start to exit:
25
+ ``TOTAL_DEADLINE_SECONDS``, with at most ``EXIT_WAIT_SECONDS`` of it spent
26
+ waiting for the exit after the output ends. A child that is not done by then
27
+ is killed, and the hook prints nothing and exits 0. A child process bounds it,
28
+ not a thread: a regular expression holds the interpreter lock, so a thread
29
+ could not give control back to a timer. The parent imports none of the
30
+ analysis modules, so a call that is no candidate pays only for this file.
31
+ 3. Any error in the parent gives no output and exit 0.
32
+
33
+ The environment variable ``PIECES_NOTE_TEST_DEADLINE_SECONDS`` sets the
34
+ deadline. It is for tests only, so that a loaded machine does not cost a test
35
+ its note. Hook settings never set it.
36
+
37
+ The command or tool call runs with its normal permission flow.
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ import importlib
43
+ import json
44
+ import os
45
+ import subprocess
46
+ import sys
47
+ import threading
48
+ import time
49
+ from collections.abc import Mapping
50
+ from math import isfinite
51
+ from pathlib import Path
52
+ from typing import IO
53
+
54
+ hooks_root_directory = str(Path(__file__).resolve().parent.parent)
55
+ if hooks_root_directory not in sys.path:
56
+ sys.path.insert(0, hooks_root_directory)
57
+ advisory_directory = str(Path(__file__).resolve().parent)
58
+ if advisory_directory not in sys.path:
59
+ sys.path.insert(0, advisory_directory)
60
+
61
+ from hooks_constants.followup_pr_dedupe_constants import CREATE_PULL_REQUEST_TOOL_SUFFIX
62
+ from hooks_constants.pieces_per_level_note_constants import (
63
+ ANALYSIS_MODULE_NAME,
64
+ ANALYZE_FLAG,
65
+ BODY_INPUT_KEY,
66
+ BODY_OPTION_PATTERN,
67
+ CLAUSE_SEPARATOR_PRECHECK_PATTERN,
68
+ COMMAND_INPUT_KEY,
69
+ COMMIT_MESSAGE_FLAG_PATTERN,
70
+ COMMIT_WORD_PATTERN,
71
+ CREATE_NO_WINDOW_ATTRIBUTE,
72
+ DEADLINE_ENVIRONMENT_VARIABLE,
73
+ EXIT_WAIT_SECONDS,
74
+ GH_PROGRAM_NAME,
75
+ GIT_WORD_PATTERN,
76
+ MAXIMUM_COMMAND_CHARACTERS,
77
+ PULL_REQUEST_CREATE_PATTERN,
78
+ PULL_REQUEST_SCRIPT_CREATE_PATTERN,
79
+ TITLE_INPUT_KEY,
80
+ TOOL_INPUT_KEY,
81
+ TOOL_NAME_KEY,
82
+ TOTAL_DEADLINE_SECONDS,
83
+ )
84
+ from hooks_constants.pr_lifecycle_skill_gate_constants import SHELL_TOOL_NAMES
85
+
86
+
87
+ def deadline_seconds(all_environment: Mapping[str, str]) -> float:
88
+ """Return the total child deadline, or the default for a missing or bad test override.
89
+
90
+ Args:
91
+ all_environment: The process environment.
92
+ """
93
+ try:
94
+ override_seconds = float(all_environment.get(DEADLINE_ENVIRONMENT_VARIABLE, ""))
95
+ except ValueError:
96
+ return TOTAL_DEADLINE_SECONDS
97
+ is_usable = isfinite(override_seconds) and override_seconds > 0
98
+ return override_seconds if is_usable else TOTAL_DEADLINE_SECONDS
99
+
100
+
101
+ def _is_commit_with_message(command: str) -> bool:
102
+ git_match = GIT_WORD_PATTERN.search(command)
103
+ if git_match is None:
104
+ return False
105
+ commit_match = COMMIT_WORD_PATTERN.search(command, git_match.end())
106
+ if commit_match is None:
107
+ return False
108
+ return COMMIT_MESSAGE_FLAG_PATTERN.search(command, commit_match.end()) is not None
109
+
110
+
111
+ def _is_pull_request_create(command: str) -> bool:
112
+ is_gh_create = (
113
+ GH_PROGRAM_NAME in command and PULL_REQUEST_CREATE_PATTERN.search(command) is not None
114
+ )
115
+ return is_gh_create or PULL_REQUEST_SCRIPT_CREATE_PATTERN.search(command) is not None
116
+
117
+
118
+ def _could_name_several_pieces_in_command(command: object) -> bool:
119
+ if not isinstance(command, str) or len(command) > MAXIMUM_COMMAND_CHARACTERS:
120
+ return False
121
+ if not (_is_commit_with_message(command) or _is_pull_request_create(command)):
122
+ return False
123
+ return (
124
+ CLAUSE_SEPARATOR_PRECHECK_PATTERN.search(command) is not None
125
+ or BODY_OPTION_PATTERN.search(command) is not None
126
+ )
127
+
128
+
129
+ def could_hold_a_note(all_hook_fields: dict[str, object]) -> bool:
130
+ """Return whether a PreToolUse call could name several pieces, by a cheap linear check.
131
+
132
+ Args:
133
+ all_hook_fields: The parsed PreToolUse payload.
134
+ """
135
+ all_tool_input = all_hook_fields.get(TOOL_INPUT_KEY)
136
+ tool_name = all_hook_fields.get(TOOL_NAME_KEY)
137
+ if not isinstance(all_tool_input, dict) or not isinstance(tool_name, str):
138
+ return False
139
+ if tool_name in SHELL_TOOL_NAMES:
140
+ return _could_name_several_pieces_in_command(all_tool_input.get(COMMAND_INPUT_KEY))
141
+ if not tool_name.endswith(CREATE_PULL_REQUEST_TOOL_SUFFIX):
142
+ return False
143
+ title = all_tool_input.get(TITLE_INPUT_KEY)
144
+ body = all_tool_input.get(BODY_INPUT_KEY)
145
+ has_separator = isinstance(title, str) and CLAUSE_SEPARATOR_PRECHECK_PATTERN.search(title)
146
+ return bool(has_separator or (isinstance(body, str) and body))
147
+
148
+
149
+ def _pump_child_output(
150
+ stream: IO[bytes], finished_signal: threading.Event, all_chunks: list[bytes]
151
+ ) -> None:
152
+ try:
153
+ all_chunks.append(stream.read())
154
+ except (OSError, ValueError):
155
+ pass
156
+ finally:
157
+ finished_signal.set()
158
+
159
+
160
+ def _send_payload(stream: IO[bytes], payload: bytes) -> None:
161
+ try:
162
+ stream.write(payload)
163
+ stream.close()
164
+ except (OSError, ValueError):
165
+ pass
166
+
167
+
168
+ def _start_child(all_arguments: list[str]) -> subprocess.Popen[bytes] | None:
169
+ try:
170
+ return subprocess.Popen(
171
+ all_arguments,
172
+ stdin=subprocess.PIPE,
173
+ stdout=subprocess.PIPE,
174
+ stderr=subprocess.DEVNULL,
175
+ creationflags=getattr(subprocess, CREATE_NO_WINDOW_ATTRIBUTE, 0),
176
+ )
177
+ except OSError:
178
+ return None
179
+
180
+
181
+ def _start_io_threads(
182
+ child: subprocess.Popen[bytes], payload: bytes
183
+ ) -> tuple[threading.Event, list[bytes]]:
184
+ finished_signal = threading.Event()
185
+ all_chunks: list[bytes] = []
186
+ threading.Thread(
187
+ target=_pump_child_output, args=(child.stdout, finished_signal, all_chunks), daemon=True
188
+ ).start()
189
+ threading.Thread(target=_send_payload, args=(child.stdin, payload), daemon=True).start()
190
+ return finished_signal, all_chunks
191
+
192
+
193
+ def _kill(child: subprocess.Popen[bytes]) -> None:
194
+ try:
195
+ child.kill()
196
+ except OSError:
197
+ pass
198
+
199
+
200
+ def _remaining_seconds(deadline_at: float) -> float:
201
+ return max(0.0, deadline_at - time.monotonic())
202
+
203
+
204
+ def analysis_output(payload: bytes, all_arguments: list[str], total_seconds: float) -> bytes:
205
+ """Run the analysis as a child process and return what it printed, or nothing.
206
+
207
+ Starting, writing the payload, reading the output, and waiting for the exit
208
+ all happen inside ``total_seconds``. The payload goes in from a thread, so a
209
+ child that never reads cannot hold the caller. A child not done by then is killed.
210
+
211
+ Args:
212
+ payload: The raw PreToolUse payload the child reads on standard input.
213
+ all_arguments: The child command line.
214
+ total_seconds: The wall-clock time for the whole child, start to exit.
215
+
216
+ Returns:
217
+ The child's standard output when it exits 0 in time, else empty bytes.
218
+ """
219
+ deadline_at = time.monotonic() + total_seconds
220
+ child = _start_child(all_arguments)
221
+ if child is None or child.stdin is None or child.stdout is None:
222
+ return b""
223
+ finished_signal, all_chunks = _start_io_threads(child, payload)
224
+ try:
225
+ is_finished = finished_signal.wait(_remaining_seconds(deadline_at))
226
+ exit_wait = min(EXIT_WAIT_SECONDS, _remaining_seconds(deadline_at))
227
+ return all_chunks[0] if is_finished and child.wait(exit_wait) == 0 else b""
228
+ except subprocess.TimeoutExpired:
229
+ return b""
230
+ finally:
231
+ _kill(child)
232
+
233
+
234
+ def _child_arguments() -> list[str]:
235
+ return [sys.executable, str(Path(__file__).resolve()), ANALYZE_FLAG]
236
+
237
+
238
+ def _run_within_deadline() -> int:
239
+ payload = sys.stdin.buffer.read()
240
+ all_hook_fields = json.loads(payload)
241
+ if not isinstance(all_hook_fields, dict) or not could_hold_a_note(all_hook_fields):
242
+ return 0
243
+ output = analysis_output(payload, _child_arguments(), deadline_seconds(os.environ))
244
+ if output:
245
+ sys.stdout.buffer.write(output)
246
+ sys.stdout.buffer.flush()
247
+ return 0
248
+
249
+
250
+ def main() -> int:
251
+ """Print the note when the words name several pieces, inside the wall-clock deadline.
252
+
253
+ Returns:
254
+ 0 in every case; the note travels in the JSON output.
255
+ """
256
+ if ANALYZE_FLAG in sys.argv[1:]:
257
+ return importlib.import_module(ANALYSIS_MODULE_NAME).main()
258
+ try:
259
+ return _run_within_deadline()
260
+ except Exception:
261
+ return 0
262
+
263
+
264
+ if __name__ == "__main__":
265
+ sys.exit(main())
@@ -0,0 +1,126 @@
1
+ """Behavior tests for the commit and pull request words reader."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import stat
7
+ import sys
8
+ import time
9
+ from pathlib import Path
10
+
11
+ import pytest
12
+
13
+ advisory_directory = str(Path(__file__).resolve().parent)
14
+ if advisory_directory not in sys.path:
15
+ sys.path.insert(0, advisory_directory)
16
+
17
+ import commit_and_pull_request_words
18
+ from hooks_constants.pieces_per_level_note_constants import MAXIMUM_FILE_BYTES
19
+
20
+ SUBJECT = "fix(x): publish icons, draw the label"
21
+
22
+
23
+ def test_the_first_message_is_the_subject() -> None:
24
+ command = f'git commit -m "{SUBJECT}" -m "body paragraph"'
25
+ assert commit_and_pull_request_words.commit_subjects(command, "") == [SUBJECT]
26
+
27
+
28
+ @pytest.mark.parametrize(
29
+ "command",
30
+ [
31
+ f'git commit -am "{SUBJECT}"',
32
+ f'git commit --message="{SUBJECT}"',
33
+ f"git -C repo commit -m '{SUBJECT}'",
34
+ f"pwsh -Command \"git commit -m '{SUBJECT}'\"",
35
+ f'git add . && git commit -m "{SUBJECT}" && git push',
36
+ ],
37
+ )
38
+ def test_each_message_option_shape_gives_the_subject(command: str) -> None:
39
+ assert SUBJECT in commit_and_pull_request_words.commit_subjects(command, "")
40
+
41
+
42
+ def test_a_heredoc_message_with_a_double_quote_gives_its_subject() -> None:
43
+ command = f'git commit -m "$(cat <<\'EOF\'\n{SUBJECT}\n\nHe said "stop".\nEOF\n)"'
44
+ assert SUBJECT in commit_and_pull_request_words.commit_subjects(command, "")
45
+
46
+
47
+ def test_a_message_file_resolves_against_the_working_directory(tmp_path: Path) -> None:
48
+ (tmp_path / "message.txt").write_text(f"\n{SUBJECT}\n\nbody\n", encoding="utf-8")
49
+ command = "git commit -F message.txt"
50
+ assert commit_and_pull_request_words.commit_subjects(command, str(tmp_path)) == [SUBJECT]
51
+
52
+
53
+ @pytest.mark.parametrize(
54
+ "command",
55
+ [
56
+ "git commit --amend",
57
+ "git commit -F -",
58
+ "git commit -F absent.txt",
59
+ "git status",
60
+ "git commit -m 'open",
61
+ ],
62
+ )
63
+ def test_a_command_with_no_readable_message_gives_no_subject(command: str) -> None:
64
+ assert commit_and_pull_request_words.commit_subjects(command, "") == []
65
+
66
+
67
+ def test_a_gh_create_call_gives_its_title_and_body_file(tmp_path: Path) -> None:
68
+ (tmp_path / "body.md").write_text("## What this does\nOne.\n", encoding="utf-8")
69
+ command = 'gh pr create --title "fix: a, b" --body-file body.md'
70
+ assert commit_and_pull_request_words.pull_request_words(command, str(tmp_path)) == [
71
+ ("fix: a, b", "## What this does\nOne.\n")
72
+ ]
73
+
74
+
75
+ def test_the_pull_request_script_create_call_gives_its_title_and_inline_body() -> None:
76
+ command = "python pull_request.py create --repo a/b --title=t --body inline"
77
+ assert commit_and_pull_request_words.pull_request_words(command, "") == [("t", "inline")]
78
+
79
+
80
+ def test_a_missing_body_file_gives_a_title_and_no_body(tmp_path: Path) -> None:
81
+ command = "gh pr create --title t --body-file absent.md"
82
+ assert commit_and_pull_request_words.pull_request_words(command, str(tmp_path)) == [("t", None)]
83
+
84
+
85
+ @pytest.mark.parametrize(
86
+ "command", ["gh pr view 3", "gh pr edit 3 --title t", "git commit -m x", ""]
87
+ )
88
+ def test_a_command_that_creates_no_pull_request_gives_no_words(command: str) -> None:
89
+ assert commit_and_pull_request_words.pull_request_words(command, "") == []
90
+
91
+
92
+ def test_a_body_file_is_read_up_to_the_byte_limit_only(tmp_path: Path) -> None:
93
+ (tmp_path / "body.md").write_text("a" * (MAXIMUM_FILE_BYTES * 3), encoding="utf-8")
94
+ command = "gh pr create --title t --body-file body.md"
95
+ all_words = commit_and_pull_request_words.pull_request_words(command, str(tmp_path))
96
+ assert all_words[0][1] == "a" * MAXIMUM_FILE_BYTES
97
+
98
+
99
+ def test_a_message_file_that_is_a_directory_gives_no_subject(tmp_path: Path) -> None:
100
+ (tmp_path / "folder").mkdir()
101
+ assert commit_and_pull_request_words.commit_subjects("git commit -F folder", str(tmp_path)) == []
102
+
103
+
104
+ def test_a_message_file_that_is_not_a_regular_file_is_never_opened(
105
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
106
+ ) -> None:
107
+ (tmp_path / "message.txt").write_text("fix(x): a, b\n", encoding="utf-8")
108
+ real_stat_result = os.stat(tmp_path / "message.txt")
109
+ device_stat_result = os.stat_result((stat.S_IFCHR, *real_stat_result[1:]))
110
+ monkeypatch.setattr(os, "stat", lambda *_all_arguments, **_all_keywords: device_stat_result)
111
+ all_subjects = commit_and_pull_request_words.commit_subjects(
112
+ "git commit -F message.txt", str(tmp_path)
113
+ )
114
+ assert all_subjects == []
115
+
116
+
117
+ def test_the_null_device_gives_no_subject(tmp_path: Path) -> None:
118
+ command = f"git commit -F {os.devnull}"
119
+ assert commit_and_pull_request_words.commit_subjects(command, str(tmp_path)) == []
120
+
121
+
122
+ def test_repeated_commit_words_are_read_within_the_time_bound() -> None:
123
+ started_at = time.perf_counter()
124
+ all_subjects = commit_and_pull_request_words.commit_subjects("git commit " * 1000, "")
125
+ assert time.perf_counter() - started_at < 1.0
126
+ assert all_subjects == []