0
# Hook Management
1
2
Git hook installation, validation, and management with support for different execution modes and template rendering. This API provides comprehensive hook lifecycle management for autohooks integration.
3
4
## Capabilities
5
6
### Hook Installation and Management
7
8
Install, validate, and manage pre-commit hooks with support for different dependency modes and version tracking.
9
10
```python { .api }
11
class PreCommitHook:
12
"""
13
Pre-commit hook management class for installation, validation, and execution.
14
"""
15
16
def __init__(self, pre_commit_hook_path: Optional[Path] = None) -> None:
17
"""
18
Create PreCommitHook manager.
19
20
Args:
21
pre_commit_hook_path: Optional custom path to pre-commit hook file.
22
If None, uses default git hooks directory.
23
"""
24
25
def exists(self) -> bool:
26
"""
27
Check if pre-commit hook file exists.
28
29
Returns:
30
True if hook file exists, False otherwise
31
"""
32
33
def is_autohooks_pre_commit_hook(self) -> bool:
34
"""
35
Check if the existing hook is an autohooks-generated hook.
36
37
Returns:
38
True if hook is autohooks-generated, False otherwise
39
"""
40
41
def is_current_autohooks_pre_commit_hook(self) -> bool:
42
"""
43
Check if the hook is the current version of autohooks hook.
44
45
Returns:
46
True if hook is current version, False if outdated
47
"""
48
49
def read_mode(self) -> Mode:
50
"""
51
Read the dependency management mode from the hook file.
52
53
Returns:
54
Mode enum indicating how dependencies are managed
55
"""
56
57
def read_version(self) -> int:
58
"""
59
Read the template version from the hook file.
60
61
Returns:
62
Template version number, -1 if not found
63
"""
64
65
def write(self, *, mode: Mode) -> None:
66
"""
67
Write/install the pre-commit hook with specified mode.
68
69
Args:
70
mode: Dependency management mode for hook execution
71
"""
72
73
def get_pre_commit_hook_path():
74
"""
75
Get the standard path to the pre-commit hook file.
76
77
Returns:
78
Path to the pre-commit hook in the git hooks directory
79
"""
80
```
81
82
**Usage Examples:**
83
84
```python
85
from autohooks.hooks import PreCommitHook, get_pre_commit_hook_path
86
from autohooks.settings import Mode
87
88
# Create hook manager
89
hook = PreCommitHook()
90
91
# Check hook status
92
if hook.exists():
93
if hook.is_autohooks_pre_commit_hook():
94
if hook.is_current_autohooks_pre_commit_hook():
95
print("Hook is installed and current")
96
else:
97
print("Hook is installed but outdated")
98
else:
99
print("Different hook is installed")
100
else:
101
print("No pre-commit hook installed")
102
103
# Install/update hook
104
hook.write(mode=Mode.POETRY)
105
106
# Check hook configuration
107
current_mode = hook.read_mode()
108
version = hook.read_version()
109
print(f"Hook mode: {current_mode}, version: {version}")
110
111
# Get hook path
112
hook_path = get_pre_commit_hook_path()
113
print(f"Hook installed at: {hook_path}")
114
```
115
116
### Template Management
117
118
Hook template rendering with support for different execution modes and shebang generation.
119
120
```python { .api }
121
class PreCommitTemplate:
122
"""
123
Template manager for generating pre-commit hook files.
124
"""
125
126
def __init__(self, template_path: Optional[Path] = None) -> None:
127
"""
128
Create template manager.
129
130
Args:
131
template_path: Optional custom template path. If None, uses default template.
132
"""
133
134
def render(self, *, mode: Mode) -> str:
135
"""
136
Render the pre-commit hook template with specified mode.
137
138
Args:
139
mode: Dependency management mode for hook execution
140
141
Returns:
142
Rendered hook script content
143
"""
144
145
def get_pre_commit_hook_template_path() -> Path:
146
"""
147
Get path to the pre-commit hook template file.
148
149
Returns:
150
Path to template file
151
"""
152
```
153
154
**Usage Examples:**
155
156
```python
157
from autohooks.template import PreCommitTemplate, get_pre_commit_hook_template_path
158
from autohooks.settings import Mode
159
160
# Create template manager
161
template = PreCommitTemplate()
162
163
# Render hook for different modes
164
poetry_hook = template.render(mode=Mode.POETRY)
165
pipenv_hook = template.render(mode=Mode.PIPENV)
166
pythonpath_hook = template.render(mode=Mode.PYTHONPATH)
167
168
# Use custom template
169
custom_template_path = get_pre_commit_hook_template_path()
170
custom_template = PreCommitTemplate(custom_template_path)
171
hook_content = custom_template.render(mode=Mode.POETRY)
172
173
# Write rendered hook to file
174
from autohooks.hooks import get_pre_commit_hook_path
175
hook_path = get_pre_commit_hook_path()
176
hook_path.write_text(hook_content)
177
hook_path.chmod(0o775)
178
```
179
180
### Template Constants
181
182
Shebang and template constants for different execution modes.
183
184
```python { .api }
185
PYTHON3_SHEBANG = "/usr/bin/env python3"
186
PIPENV_SHEBANG = "/usr/bin/env -S pipenv run python3"
187
POETRY_SHEBANG = "/usr/bin/env -S poetry run python"
188
189
# For OS's that don't support '/usr/bin/env -S'
190
PIPENV_MULTILINE_SHEBANG = (
191
"/bin/sh\n"
192
"\"true\" ''':'\n"
193
'pipenv run python3 "$0" "$@"\n'
194
'exit "$?"\n'
195
"'''"
196
)
197
198
POETRY_MULTILINE_SHEBANG = (
199
"/bin/sh\n"
200
"\"true\" ''':'\n"
201
'poetry run python "$0" "$@"\n'
202
'exit "$?"\n'
203
"'''"
204
)
205
206
TEMPLATE_VERSION = 1
207
```
208
209
**Usage Examples:**
210
211
```python
212
from autohooks.template import (
213
PYTHON3_SHEBANG, POETRY_SHEBANG, PIPENV_SHEBANG,
214
POETRY_MULTILINE_SHEBANG, PIPENV_MULTILINE_SHEBANG,
215
TEMPLATE_VERSION
216
)
217
from autohooks.settings import Mode
218
219
def get_shebang_for_mode(mode: Mode) -> str:
220
"""Get appropriate shebang for execution mode."""
221
if mode == Mode.POETRY:
222
return POETRY_SHEBANG
223
elif mode == Mode.POETRY_MULTILINE:
224
return POETRY_MULTILINE_SHEBANG
225
elif mode == Mode.PIPENV:
226
return PIPENV_SHEBANG
227
elif mode == Mode.PIPENV_MULTILINE:
228
return PIPENV_MULTILINE_SHEBANG
229
else:
230
return PYTHON3_SHEBANG
231
232
# Check template version compatibility
233
def is_compatible_version(hook_version: int) -> bool:
234
return hook_version == TEMPLATE_VERSION
235
```
236
237
### Hook Validation
238
239
Comprehensive hook validation including version checking, mode validation, and compatibility assessment.
240
241
```python { .api }
242
def check_hook_is_current(term: Terminal, pre_commit_hook: PreCommitHook) -> None:
243
"""
244
Check if the installed hook is the current version.
245
246
Args:
247
term: Terminal interface for output
248
pre_commit_hook: Hook instance to check
249
"""
250
251
def check_hook_mode(term: Terminal, config_mode: Mode, hook_mode: Mode) -> None:
252
"""
253
Check if hook mode matches configuration mode.
254
255
Args:
256
term: Terminal interface for output
257
config_mode: Mode from configuration
258
hook_mode: Mode from installed hook
259
"""
260
```
261
262
**Usage Examples:**
263
264
```python
265
from autohooks.precommit.run import check_hook_is_current, check_hook_mode
266
from autohooks.hooks import PreCommitHook
267
from autohooks.config import load_config_from_pyproject_toml
268
from autohooks.terminal import Terminal
269
270
# Validate hook installation
271
term = Terminal()
272
hook = PreCommitHook()
273
config = load_config_from_pyproject_toml()
274
275
# Check if hook is current
276
check_hook_is_current(term, hook)
277
278
# Check if modes match
279
if config.has_autohooks_config():
280
config_mode = config.get_mode()
281
hook_mode = hook.read_mode()
282
check_hook_mode(term, config_mode, hook_mode)
283
```
284
285
## Hook Execution Flow
286
287
1. **Installation**: `PreCommitHook.write()` creates executable hook script
288
2. **Git Trigger**: Git executes hook on commit attempt
289
3. **Mode Detection**: Hook reads shebang to determine execution mode
290
4. **Dependency Resolution**: Mode determines how to load autohooks and plugins
291
5. **Plugin Execution**: Autohooks loads and executes configured plugins
292
6. **Result Processing**: Hook returns status to git (0 = success, non-zero = failure)
293
294
## Dependency Modes
295
296
### PYTHONPATH Mode
297
- Uses system Python and PYTHONPATH
298
- Fastest execution, requires autohooks in system/virtual environment
299
- Shebang: `#!/usr/bin/env python3`
300
301
### POETRY Mode
302
- Uses `poetry run python` for execution
303
- Handles dependencies via Poetry
304
- Shebang: `#!/usr/bin/env -S poetry run python`
305
306
### PIPENV Mode
307
- Uses `pipenv run python3` for execution
308
- Handles dependencies via Pipenv
309
- Shebang: `#!/usr/bin/env -S pipenv run python3`
310
311
### Multiline Modes
312
- For systems not supporting `env -S` flag
313
- Uses shell script wrapper for dependency management
314
- Maintains compatibility across different Unix systems
315
316
## Types
317
318
```python { .api }
319
from pathlib import Path
320
from typing import Optional
321
from autohooks.settings import Mode
322
from autohooks.terminal import Terminal
323
```