0
# Plugin API
1
2
Core API for developing autohooks plugins, providing configuration access, progress reporting, and terminal output utilities. This API enables plugins to integrate seamlessly with autohooks' execution framework.
3
4
## Capabilities
5
6
### Configuration Access
7
8
Access to hierarchical configuration from pyproject.toml with convenient key-based navigation and value retrieval.
9
10
```python { .api }
11
class Config:
12
"""
13
Config helper class for easier access to a tree of settings.
14
"""
15
16
def __init__(self, config_dict: Optional[Dict[str, Any]] = None) -> None:
17
"""
18
Create a new Config from a dictionary.
19
20
Args:
21
config_dict: Dictionary to be used for the Config
22
"""
23
24
def get(self, *keys: str) -> 'Config':
25
"""
26
Get a sub-config. If a sub-config with the passed keys does not exist,
27
an empty Config is returned.
28
29
Args:
30
*keys: Variable length of keys to resolve
31
32
Returns:
33
Sub-config for the specified key path
34
"""
35
36
def get_value(self, key: str, default: Any = None) -> Any:
37
"""
38
Get a config value.
39
40
Args:
41
key: Key to lookup in the config
42
default: Value to return if key is not in the config
43
44
Returns:
45
Configuration value or default
46
"""
47
48
def is_empty(self) -> bool:
49
"""
50
Returns True if the config has no data.
51
"""
52
53
def has_key(self, key: str) -> bool:
54
"""
55
Returns True if the key is in the config.
56
"""
57
```
58
59
**Usage Examples:**
60
61
```python
62
from autohooks.api import Config
63
64
def precommit(config: Config, report_progress, **kwargs):
65
# Access plugin-specific configuration
66
plugin_config = config.get("tool", "autohooks", "plugins", "my-plugin")
67
68
# Get configuration values with defaults
69
max_line_length = plugin_config.get_value("max-line-length", 88)
70
exclude_patterns = plugin_config.get_value("exclude", [])
71
72
# Check if configuration exists
73
if plugin_config.is_empty():
74
# Use default settings
75
pass
76
```
77
78
### Progress Reporting
79
80
Progress reporting interface for providing user feedback during plugin execution with initialization and update capabilities.
81
82
```python { .api }
83
class ReportProgress:
84
"""
85
A class to report progress of a plugin.
86
"""
87
88
def __init__(self, progress: Progress, task_id: int) -> None:
89
"""
90
Create progress reporter.
91
92
Args:
93
progress: Rich progress instance
94
task_id: Task identifier for this progress
95
"""
96
97
def init(self, total: int) -> None:
98
"""
99
Init the progress with the total number to process.
100
101
Args:
102
total: Most of the time this should be the number of files to process
103
"""
104
105
def update(self, advance: int = 1) -> None:
106
"""
107
Update the number of already processed steps/items/files.
108
This increases the progress indicator.
109
110
Args:
111
advance: Number of steps/items/files the progress advanced. Default: 1
112
"""
113
```
114
115
**Usage Examples:**
116
117
```python
118
from autohooks.api import ReportProgress
119
from autohooks.api.git import get_staged_status
120
121
def precommit(config, report_progress: ReportProgress, **kwargs):
122
# Get files to process
123
files = get_staged_status()
124
125
# Initialize progress with total count
126
report_progress.init(len(files))
127
128
# Process each file
129
for file_entry in files:
130
process_file(file_entry.absolute_path())
131
132
# Update progress
133
report_progress.update()
134
135
return 0
136
```
137
138
### Terminal Output
139
140
Terminal output functions for consistent messaging and user feedback with different severity levels.
141
142
```python { .api }
143
def error(message: str) -> None:
144
"""
145
Highlight message as an error in the terminal.
146
147
Args:
148
message: Message to print
149
"""
150
151
def fail(message: str) -> None:
152
"""
153
Highlight message as a failure in the terminal.
154
155
Args:
156
message: Message to print
157
"""
158
159
def info(message: str) -> None:
160
"""
161
Highlight message as an information in the terminal.
162
163
Args:
164
message: Message to print
165
"""
166
167
def bold_info(message: str) -> None:
168
"""
169
Highlight message as a strong information in the terminal.
170
171
Args:
172
message: Message to print
173
"""
174
175
def ok(message: str) -> None:
176
"""
177
Highlight message as a success/ok in the terminal.
178
179
Args:
180
message: Message to print
181
"""
182
183
def out(message: str):
184
"""
185
Print message to the terminal without highlighting.
186
187
Args:
188
message: Message to print
189
"""
190
191
def warning(message: str) -> None:
192
"""
193
Highlight message as a warning in the terminal.
194
195
Args:
196
message: Message to print
197
"""
198
```
199
200
**Usage Examples:**
201
202
```python
203
from autohooks.api import error, info, ok, warning
204
205
def precommit(config, report_progress, **kwargs):
206
info("Starting code formatting...")
207
208
try:
209
# Process files
210
result = format_files()
211
212
if result.errors:
213
for error_msg in result.errors:
214
error(f"Formatting error: {error_msg}")
215
return 1
216
elif result.warnings:
217
for warning_msg in result.warnings:
218
warning(f"Formatting warning: {warning_msg}")
219
220
ok(f"Successfully formatted {result.file_count} files")
221
return 0
222
223
except Exception as e:
224
error(f"Plugin execution failed: {e}")
225
return 1
226
```
227
228
## Plugin Development Guidelines
229
230
### Plugin Function Signature
231
232
Every autohooks plugin must implement a `precommit` function with the following signature:
233
234
```python { .api }
235
def precommit(config: Config, report_progress: ReportProgress, **kwargs):
236
"""
237
Main plugin entry point called during pre-commit hook execution.
238
239
Args:
240
config: Configuration object for accessing plugin settings
241
report_progress: Progress reporting interface for user feedback
242
**kwargs: Additional arguments for future compatibility
243
244
Returns:
245
int: 0 for success, non-zero for failure (stops commit process)
246
"""
247
```
248
249
### Plugin Structure Example
250
251
```python
252
from autohooks.api import Config, ReportProgress, error, info, ok
253
from autohooks.api.git import get_staged_status
254
from autohooks.api.path import is_python_path
255
256
def precommit(config: Config, report_progress: ReportProgress, **kwargs):
257
"""Example plugin that processes Python files."""
258
259
# Get staged files
260
status_entries = get_staged_status()
261
python_files = [entry for entry in status_entries
262
if is_python_path(entry.path)]
263
264
if not python_files:
265
info("No Python files to process")
266
return 0
267
268
# Initialize progress
269
report_progress.init(len(python_files))
270
271
# Get plugin configuration
272
plugin_config = config.get("tool", "my-plugin")
273
strict_mode = plugin_config.get_value("strict", False)
274
275
errors = 0
276
277
# Process each file
278
for file_entry in python_files:
279
try:
280
process_python_file(file_entry.absolute_path(), strict_mode)
281
report_progress.update()
282
except ProcessingError as e:
283
error(f"Error processing {file_entry.path}: {e}")
284
errors += 1
285
286
if errors:
287
error(f"Processing failed for {errors} files")
288
return 1
289
290
ok(f"Successfully processed {len(python_files)} Python files")
291
return 0
292
```
293
294
## Types
295
296
```python { .api }
297
from typing import Any, Dict, Optional
298
from rich.progress import Progress
299
```