0
# Configuration Management
1
2
Configuration system for reading and writing autohooks settings in pyproject.toml with support for different dependency modes and plugin management. This API provides comprehensive configuration handling for both internal use and plugin development.
3
4
## Capabilities
5
6
### Configuration Loading
7
8
Load and parse autohooks configuration from pyproject.toml files with support for various input formats and validation.
9
10
```python { .api }
11
class AutohooksConfig:
12
"""
13
Main autohooks configuration class providing access to settings and plugin configuration.
14
"""
15
16
def __init__(self, *, settings: Optional[AutohooksSettings] = None, config: Optional[Config] = None) -> None:
17
"""
18
Create AutohooksConfig instance.
19
20
Args:
21
settings: Optional AutohooksSettings instance
22
config: Optional Config instance for raw configuration access
23
"""
24
25
@staticmethod
26
def from_dict(config_dict: Dict[str, Any]) -> 'AutohooksConfig':
27
"""
28
Create a new AutohooksConfig from a dictionary.
29
30
Args:
31
config_data: A dictionary containing the config data
32
33
Returns:
34
A new AutohooksConfig
35
"""
36
37
@staticmethod
38
def from_string(content: str) -> 'AutohooksConfig':
39
"""
40
Load an AutohooksConfig from a string.
41
42
Args:
43
content: The content of the config
44
45
Returns:
46
A new AutohooksConfig
47
"""
48
49
@staticmethod
50
def from_toml(toml_file: Path) -> 'AutohooksConfig':
51
"""
52
Load an AutohooksConfig from a TOML file.
53
54
Args:
55
toml_file: Path for the toml file to load
56
57
Returns:
58
A new AutohooksConfig
59
"""
60
61
def load_config_from_pyproject_toml(pyproject_toml: Optional[Path] = None) -> AutohooksConfig:
62
"""
63
Load an AutohooksConfig from a pyproject.toml file.
64
65
If no path to the pyproject.toml file is passed the path will be determined
66
from the current working directory and the project.
67
68
Args:
69
pyproject_toml: Path to the pyproject.toml file
70
71
Returns:
72
A new AutohooksConfig
73
"""
74
```
75
76
**Usage Examples:**
77
78
```python
79
from autohooks.config import load_config_from_pyproject_toml, AutohooksConfig
80
from pathlib import Path
81
82
# Load from default pyproject.toml location
83
config = load_config_from_pyproject_toml()
84
85
# Load from specific file
86
config = load_config_from_pyproject_toml(Path("custom/pyproject.toml"))
87
88
# Load from string content
89
toml_content = """
90
[tool.autohooks]
91
mode = "poetry"
92
pre-commit = ["autohooks.plugins.black", "autohooks.plugins.ruff"]
93
"""
94
config = AutohooksConfig.from_string(toml_content)
95
96
# Load from dictionary
97
config_dict = {"tool": {"autohooks": {"mode": "poetry", "pre-commit": ["black"]}}}
98
config = AutohooksConfig.from_dict(config_dict)
99
```
100
101
### Configuration Access
102
103
Access autohooks-specific settings and plugin configuration with validation and default handling.
104
105
```python { .api }
106
class AutohooksConfig:
107
def get_config(self) -> Config:
108
"""
109
Get raw configuration object for advanced access.
110
111
Returns:
112
Config instance providing key-based access to all settings
113
"""
114
115
def has_autohooks_config(self) -> bool:
116
"""
117
Check if autohooks configuration section exists.
118
119
Returns:
120
True if [tool.autohooks] section exists, False otherwise
121
"""
122
123
def get_pre_commit_script_names(self) -> List[str]:
124
"""
125
Get list of configured pre-commit plugin names.
126
127
Returns:
128
List of plugin names from pre-commit setting
129
"""
130
131
def get_mode(self) -> Mode:
132
"""
133
Get configured dependency management mode.
134
135
Returns:
136
Mode enum value for dependency management
137
"""
138
```
139
140
**Usage Examples:**
141
142
```python
143
from autohooks.config import load_config_from_pyproject_toml
144
145
def precommit(config, report_progress, **kwargs):
146
# Access autohooks configuration
147
autohooks_config = load_config_from_pyproject_toml()
148
149
# Check if autohooks is configured
150
if not autohooks_config.has_autohooks_config():
151
error("Autohooks not configured in pyproject.toml")
152
return 1
153
154
# Get plugin list
155
plugins = autohooks_config.get_pre_commit_script_names()
156
info(f"Configured plugins: {', '.join(plugins)}")
157
158
# Get dependency mode
159
mode = autohooks_config.get_mode()
160
info(f"Using dependency mode: {mode}")
161
162
# Access raw configuration for plugin-specific settings
163
raw_config = autohooks_config.get_config()
164
plugin_config = raw_config.get("tool", "my-plugin")
165
166
return 0
167
```
168
169
### Settings Management
170
171
Structured settings management with support for different dependency modes and plugin configuration.
172
173
```python { .api }
174
class AutohooksSettings:
175
"""
176
Autohooks configuration settings dataclass.
177
"""
178
mode: Mode = Mode.UNDEFINED
179
pre_commit: Iterable[str] = field(default_factory=list)
180
181
def write(self, filename: Path) -> None:
182
"""
183
Write the current AutohooksSettings to a TOML file.
184
185
If the TOML file already exists only the [tool.autohooks] section is overridden.
186
187
Args:
188
filename: Path to pyproject.toml file to write/update
189
"""
190
191
class Mode(Enum):
192
"""
193
Dependency management modes for hook execution.
194
"""
195
PIPENV = 1
196
PYTHONPATH = 2
197
POETRY = 3
198
PIPENV_MULTILINE = 4
199
POETRY_MULTILINE = 5
200
UNDEFINED = -1
201
UNKNOWN = -2
202
203
def get_effective_mode(self):
204
"""
205
Get the effective mode for execution, handling multiline variants.
206
207
Returns:
208
Effective Mode for hook execution
209
"""
210
211
@staticmethod
212
def from_string(modestring: Optional[str]) -> 'Mode':
213
"""
214
Convert string to Mode enum.
215
216
Args:
217
modestring: String representation of mode
218
219
Returns:
220
Mode enum value
221
"""
222
```
223
224
**Usage Examples:**
225
226
```python
227
from autohooks.settings import AutohooksSettings, Mode
228
from pathlib import Path
229
230
# Create new settings
231
settings = AutohooksSettings(
232
mode=Mode.POETRY,
233
pre_commit=["autohooks.plugins.black", "autohooks.plugins.ruff"]
234
)
235
236
# Write settings to pyproject.toml
237
pyproject_path = Path("pyproject.toml")
238
settings.write(pyproject_path)
239
240
# Work with modes
241
mode = Mode.from_string("poetry")
242
effective_mode = mode.get_effective_mode()
243
244
# Check mode types
245
if mode == Mode.POETRY:
246
print("Using Poetry for dependency management")
247
elif mode == Mode.PIPENV:
248
print("Using Pipenv for dependency management")
249
elif mode == Mode.PYTHONPATH:
250
print("Using system Python path")
251
```
252
253
### Configuration Constants
254
255
Constants for configuration section identification and validation.
256
257
```python { .api }
258
AUTOHOOKS_SECTION = "tool.autohooks"
259
```
260
261
**Usage Examples:**
262
263
```python
264
from autohooks.config import AUTOHOOKS_SECTION
265
import tomlkit
266
267
# Check for autohooks section in TOML
268
def has_autohooks_section(toml_content: str) -> bool:
269
doc = tomlkit.loads(toml_content)
270
return AUTOHOOKS_SECTION in doc
271
272
# Add autohooks section to existing TOML
273
def add_autohooks_section(toml_path: Path):
274
doc = tomlkit.loads(toml_path.read_text())
275
if AUTOHOOKS_SECTION not in doc:
276
doc[AUTOHOOKS_SECTION] = {"mode": "poetry", "pre-commit": []}
277
toml_path.write_text(tomlkit.dumps(doc))
278
```
279
280
## Configuration File Format
281
282
The autohooks configuration is stored in `pyproject.toml` under the `[tool.autohooks]` section:
283
284
```toml
285
[tool.autohooks]
286
mode = "poetry" # or "pipenv", "pythonpath"
287
pre-commit = [
288
"autohooks.plugins.black",
289
"autohooks.plugins.ruff",
290
"autohooks.plugins.mypy"
291
]
292
293
# Plugin-specific configuration
294
[tool.autohooks.plugins.black]
295
line-length = 88
296
297
[tool.autohooks.plugins.ruff]
298
line-length = 88
299
target-version = "py39"
300
```
301
302
## Types
303
304
```python { .api }
305
from dataclasses import dataclass, field
306
from enum import Enum
307
from pathlib import Path
308
from typing import Any, Dict, Iterable, List, Optional
309
```