0
# Configuration Management
1
2
Configuration loading, validation, and schema definitions for pre-commit configuration files. Pre-commit uses YAML-based configuration files to define hooks and their settings.
3
4
## Capabilities
5
6
### Configuration Loading
7
8
Functions for loading and parsing pre-commit configuration files with automatic validation.
9
10
```python { .api }
11
load_config: functools.partial[dict[str, Any]]
12
# Partial function for loading .pre-commit-config.yaml files
13
# Usage: config = load_config(filename)
14
# Raises InvalidConfigError if configuration is invalid
15
16
load_manifest: functools.partial[list[dict[str, Any]]]
17
# Partial function for loading .pre-commit-hooks.yaml files
18
# Usage: hooks = load_manifest(filename)
19
# Raises InvalidManifestError if manifest is invalid
20
```
21
22
### Configuration Validation Functions
23
24
Utility functions for validating configuration elements.
25
26
```python { .api }
27
def check_type_tag(tag: str) -> None:
28
"""Validate file type tag is recognized"""
29
30
def parse_version(s: str) -> tuple[int, ...]:
31
"""Parse version string for comparison"""
32
33
def check_min_version(version: str) -> None:
34
"""Check minimum pre-commit version requirement"""
35
36
def transform_stage(stage: str) -> str:
37
"""Transform legacy stage names to current format"""
38
```
39
40
### Schema Constants
41
42
JSON schemas used for validating configuration and manifest files.
43
44
```python { .api }
45
CONFIG_SCHEMA: cfgv.Map
46
"""Schema for .pre-commit-config.yaml validation"""
47
48
MANIFEST_SCHEMA: cfgv.Array
49
"""Schema for .pre-commit-hooks.yaml validation"""
50
51
MINIMAL_MANIFEST_SCHEMA: cfgv.Array
52
"""Minimal schema for manifest validation"""
53
```
54
55
## Configuration File Formats
56
57
### Pre-commit Configuration (.pre-commit-config.yaml)
58
59
Main configuration file format for defining repositories and hooks:
60
61
```yaml
62
# .pre-commit-config.yaml example
63
repos:
64
- repo: https://github.com/psf/black
65
rev: 22.3.0
66
hooks:
67
- id: black
68
args: [--line-length=88]
69
files: \.py$
70
- repo: https://github.com/pycqa/flake8
71
rev: 4.0.1
72
hooks:
73
- id: flake8
74
additional_dependencies: [flake8-docstrings]
75
```
76
77
#### Configuration Schema Properties
78
79
```python { .api }
80
class ConfigRepo:
81
"""Configuration repository definition"""
82
repo: str # Repository URL or 'local'
83
rev: str # Git revision (tag, commit, branch)
84
hooks: list[ConfigHook] # List of hooks from this repo
85
86
class ConfigHook:
87
"""Hook configuration in .pre-commit-config.yaml"""
88
id: str # Hook identifier
89
alias: str | None = None # Alternative name
90
name: str | None = None # Display name override
91
language_version: str | None = None # Language version
92
files: str | None = None # File pattern regex
93
exclude: str | None = None # Exclusion pattern
94
types: list[str] | None = None # File types to include
95
types_or: list[str] | None = None # Alternative file types
96
exclude_types: list[str] | None = None # File types to exclude
97
args: list[str] | None = None # Additional arguments
98
stages: list[str] | None = None # Git hook stages
99
additional_dependencies: list[str] | None = None # Extra deps
100
always_run: bool | None = None # Run even without files
101
verbose: bool | None = None # Verbose output
102
log_file: str | None = None # Log file path
103
```
104
105
### Hook Manifest (.pre-commit-hooks.yaml)
106
107
Manifest file format for defining available hooks in a repository:
108
109
```yaml
110
# .pre-commit-hooks.yaml example
111
- id: black
112
name: black
113
description: "The uncompromising Python code formatter"
114
entry: black
115
language: python
116
require_serial: false
117
types_or: [python, pyi]
118
minimum_pre_commit_version: 2.9.2
119
```
120
121
#### Manifest Schema Properties
122
123
```python { .api }
124
class ManifestHook:
125
"""Hook definition in .pre-commit-hooks.yaml"""
126
id: str # Unique identifier
127
name: str # Display name
128
entry: str # Command to execute
129
language: str # Programming language
130
description: str | None = None # Hook description
131
alias: str | None = None # Alternative name
132
files: str | None = None # File pattern regex
133
exclude: str | None = None # Exclusion pattern
134
types: list[str] | None = None # File types
135
types_or: list[str] | None = None # Alternative file types
136
exclude_types: list[str] | None = None # Excluded file types
137
always_run: bool = False # Always execute
138
fail_fast: bool = False # Stop on first failure
139
pass_filenames: bool = True # Pass filenames to hook
140
require_serial: bool = False # Serial execution required
141
stages: list[str] | None = None # Applicable stages
142
args: list[str] | None = None # Default arguments
143
verbose: bool = False # Verbose output
144
language_version: str = 'default' # Language version
145
log_file: str | None = None # Log file path
146
minimum_pre_commit_version: str = '0.15.0' # Version requirement
147
additional_dependencies: list[str] = [] # Extra dependencies
148
```
149
150
## File Type Detection
151
152
### Supported File Types
153
154
Pre-commit includes built-in file type detection for various programming languages and file formats:
155
156
```python { .api }
157
FILE_TYPES = [
158
'bash', 'batch', 'c', 'c++', 'csharp', 'css', 'dart', 'dockerfile',
159
'elixir', 'go', 'haskell', 'html', 'java', 'javascript', 'json',
160
'jsx', 'kotlin', 'lua', 'markdown', 'perl', 'php', 'python', 'r',
161
'ruby', 'rust', 'scala', 'shell', 'sql', 'swift', 'text', 'toml',
162
'tsx', 'typescript', 'xml', 'yaml'
163
]
164
```
165
166
## Configuration Examples
167
168
### Loading Configuration
169
170
```python
171
from pre_commit.clientlib import load_config, InvalidConfigError
172
173
try:
174
config = load_config('.pre-commit-config.yaml')
175
print(f"Found {len(config['repos'])} repositories")
176
177
for repo in config['repos']:
178
print(f"Repository: {repo['repo']}")
179
print(f"Hooks: {[hook['id'] for hook in repo['hooks']]}")
180
181
except InvalidConfigError as e:
182
print(f"Configuration error: {e}")
183
```
184
185
### Loading Manifest
186
187
```python
188
from pre_commit.clientlib import load_manifest, InvalidManifestError
189
190
try:
191
manifest = load_manifest('.pre-commit-hooks.yaml')
192
print(f"Found {len(manifest)} hook definitions")
193
194
for hook in manifest:
195
print(f"Hook: {hook['id']} ({hook['language']})")
196
197
except InvalidManifestError as e:
198
print(f"Manifest error: {e}")
199
```
200
201
### Configuration Validation Functions
202
203
```python
204
from pre_commit.clientlib import check_type_tag, parse_version, check_min_version
205
206
# Validate file type tags
207
try:
208
check_type_tag('python') # Valid tag
209
check_type_tag('invalid') # Would raise ValidationError
210
except cfgv.ValidationError as e:
211
print(f"Invalid type tag: {e}")
212
213
# Parse and compare versions
214
version_tuple = parse_version('1.2.3') # Returns (1, 2, 3)
215
216
# Check minimum version requirement
217
try:
218
check_min_version('2.0.0')
219
except cfgv.ValidationError as e:
220
print(f"Version too old: {e}")
221
```
222
223
## Constants
224
225
### Configuration File Names
226
227
```python { .api }
228
CONFIG_FILE: str = '.pre-commit-config.yaml'
229
"""Default configuration file name"""
230
231
MANIFEST_FILE: str = '.pre-commit-hooks.yaml'
232
"""Default manifest file name"""
233
```
234
235
### Validation Settings
236
237
```python { .api }
238
DEFAULT_LANGUAGE_VERSION: cfgv.Map
239
"""Schema for default language version configuration"""
240
```