0
# Configuration
1
2
Git configuration management for repository, global, and system settings. Provides type-safe access to Git configuration values with support for multiple configuration levels and data types.
3
4
## Capabilities
5
6
### Configuration Access
7
8
The Config class provides access to Git configuration at various levels with type-safe value retrieval.
9
10
```python { .api }
11
class Config:
12
# Value Access
13
def __getitem__(self, key: str):
14
"""Get configuration value"""
15
16
def __setitem__(self, key: str, value):
17
"""Set configuration value"""
18
19
def __delitem__(self, key: str):
20
"""Delete configuration key"""
21
22
def __contains__(self, key: str) -> bool:
23
"""Check if key exists"""
24
25
def __iter__(self):
26
"""Iterate over configuration entries"""
27
28
def get(self, key: str, default=None):
29
"""Get value with default fallback"""
30
31
# Typed Value Access
32
def get_bool(self, key: str) -> bool:
33
"""Get boolean value"""
34
35
def get_int(self, key: str) -> int:
36
"""Get integer value"""
37
38
def get_string(self, key: str) -> str:
39
"""Get string value"""
40
41
def get_multivar(self, key: str) -> list[str]:
42
"""Get multiple values for key"""
43
44
def set_multivar(self, key: str, pattern: str, value: str):
45
"""Set multiple values matching pattern"""
46
47
def delete_multivar(self, key: str, pattern: str):
48
"""Delete multiple values matching pattern"""
49
50
# Configuration Management
51
def add_file(self, path: str, level: int, force: bool = False):
52
"""Add configuration file"""
53
54
def snapshot(self) -> 'Config':
55
"""Create immutable snapshot"""
56
57
def parse_bool(self, value: str) -> bool:
58
"""Parse string as boolean"""
59
60
def parse_int32(self, value: str) -> int:
61
"""Parse string as 32-bit integer"""
62
63
def parse_int64(self, value: str) -> int:
64
"""Parse string as 64-bit integer"""
65
66
# Repository config access
67
class Repository:
68
@property
69
def config(self) -> Config:
70
"""Repository configuration (all levels)"""
71
72
@property
73
def config_snapshot(self) -> Config:
74
"""Immutable configuration snapshot"""
75
76
# Global config access
77
def config_global() -> Config:
78
"""Get global configuration"""
79
80
def config_system() -> Config:
81
"""Get system configuration"""
82
```
83
84
### Configuration Entries
85
86
ConfigEntry provides detailed information about individual configuration values.
87
88
```python { .api }
89
class ConfigEntry:
90
@property
91
def name(self) -> str:
92
"""Configuration key name"""
93
94
@property
95
def value(self) -> str:
96
"""Configuration value as string"""
97
98
@property
99
def level(self) -> int:
100
"""Configuration level"""
101
102
@property
103
def include_depth(self) -> int:
104
"""Include file depth"""
105
106
@property
107
def free(self):
108
"""Free entry resources"""
109
```
110
111
### Configuration Iteration
112
113
Iterate over configuration entries with filtering capabilities.
114
115
```python { .api }
116
class ConfigIterator:
117
def __init__(self, config: Config, pattern: str = None):
118
"""Create iterator for config entries"""
119
120
def __iter__(self):
121
"""Iterate over matching entries"""
122
123
def __next__(self) -> ConfigEntry:
124
"""Get next entry"""
125
126
class ConfigMultivarIterator:
127
def __init__(self, config: Config, name: str, pattern: str = None):
128
"""Create iterator for multivar entries"""
129
130
def __iter__(self):
131
"""Iterate over multivar values"""
132
133
def __next__(self) -> ConfigEntry:
134
"""Get next multivar entry"""
135
```
136
137
### Configuration Levels
138
139
Constants defining the hierarchy of configuration files.
140
141
```python { .api }
142
# Configuration Level Constants
143
GIT_CONFIG_LEVEL_SYSTEM: int # System-wide config (/etc/gitconfig)
144
GIT_CONFIG_LEVEL_XDG: int # User XDG config (~/.config/git/config)
145
GIT_CONFIG_LEVEL_GLOBAL: int # User global config (~/.gitconfig)
146
GIT_CONFIG_LEVEL_LOCAL: int # Repository config (.git/config)
147
GIT_CONFIG_LEVEL_WORKTREE: int # Worktree config (.git/config.worktree)
148
GIT_CONFIG_LEVEL_APP: int # Application-specific config
149
GIT_CONFIG_LEVEL_PROGRAMDATA: int # Windows program data config
150
GIT_CONFIG_HIGHEST_LEVEL: int # Highest priority level
151
```
152
153
### Global Configuration Functions
154
155
Access and modify Git configuration at specific levels.
156
157
```python { .api }
158
def config_find_global() -> str:
159
"""Find path to global config file"""
160
161
def config_find_system() -> str:
162
"""Find path to system config file"""
163
164
def config_find_xdg() -> str:
165
"""Find path to XDG config file"""
166
167
def config_find_programdata() -> str:
168
"""Find path to program data config file"""
169
```
170
171
### Usage Examples
172
173
#### Basic Configuration Access
174
175
```python
176
import pygit2
177
178
repo = pygit2.Repository('/path/to/repo')
179
config = repo.config
180
181
# Get configuration values
182
user_name = config['user.name']
183
user_email = config['user.email']
184
print(f"User: {user_name} <{user_email}>")
185
186
# Set configuration values
187
config['user.name'] = 'John Doe'
188
config['user.email'] = 'john@example.com'
189
190
# Check if key exists
191
if 'core.autocrlf' in config:
192
autocrlf = config['core.autocrlf']
193
print(f"Auto CRLF: {autocrlf}")
194
195
# Get with default
196
editor = config.get('core.editor', 'nano')
197
print(f"Editor: {editor}")
198
```
199
200
#### Type-Safe Value Access
201
202
```python
203
# Boolean values
204
bare = config.get_bool('core.bare')
205
ignore_case = config.get_bool('core.ignorecase')
206
207
# Integer values
208
abbrev = config.get_int('core.abbrev')
209
filemode = config.get_int('core.filemode')
210
211
# Handle missing keys with defaults
212
try:
213
push_default = config.get_string('push.default')
214
except KeyError:
215
push_default = 'simple'
216
217
print(f"Push default: {push_default}")
218
```
219
220
#### Working with Multi-Value Keys
221
222
```python
223
# Get all values for a key (like multiple remotes)
224
try:
225
remote_urls = config.get_multivar('remote.origin.url')
226
for url in remote_urls:
227
print(f"Origin URL: {url}")
228
except KeyError:
229
print("No origin remote configured")
230
231
# Set multiple values
232
config.set_multivar('remote.backup.url', '.*', 'https://backup1.com/repo.git')
233
config.set_multivar('remote.backup.url', '.*', 'https://backup2.com/repo.git')
234
235
# Delete specific multivar
236
config.delete_multivar('remote.backup.url', 'backup2')
237
```
238
239
#### Configuration Levels
240
241
```python
242
# Access different configuration levels
243
global_config = pygit2.config_global()
244
global_config['user.name'] = 'Global User'
245
246
system_config = pygit2.config_system()
247
# system_config is usually read-only
248
249
# Repository-specific config
250
repo.config['user.name'] = 'Repo Specific User'
251
252
# The effective value considers all levels
253
effective_name = repo.config['user.name'] # Will be 'Repo Specific User'
254
```
255
256
#### Iterating Over Configuration
257
258
```python
259
# Iterate over all configuration entries
260
print("All configuration:")
261
for entry in config:
262
print(f"{entry.name} = {entry.value} (level: {entry.level})")
263
264
# Iterate over specific pattern
265
print("\nUser configuration:")
266
for entry in pygit2.ConfigIterator(config, 'user.*'):
267
print(f"{entry.name} = {entry.value}")
268
269
# Iterate over multivar entries
270
for entry in pygit2.ConfigMultivarIterator(config, 'remote.origin.url'):
271
print(f"Origin URL: {entry.value}")
272
```
273
274
#### Configuration Snapshots
275
276
```python
277
# Create immutable snapshot
278
snapshot = config.snapshot()
279
280
# Snapshot values don't change even if config is modified
281
original_name = snapshot['user.name']
282
config['user.name'] = 'Changed Name'
283
snapshot_name = snapshot['user.name'] # Still original value
284
285
print(f"Original: {original_name}")
286
print(f"Current: {config['user.name']}")
287
print(f"Snapshot: {snapshot_name}")
288
```
289
290
#### Common Configuration Patterns
291
292
```python
293
# Set up user identity
294
config['user.name'] = 'Jane Developer'
295
config['user.email'] = 'jane@company.com'
296
config['user.signingkey'] = 'GPG_KEY_ID'
297
298
# Configure editor and diff tool
299
config['core.editor'] = 'code --wait'
300
config['merge.tool'] = 'vscode'
301
config['mergetool.vscode.cmd'] = 'code --wait $MERGED'
302
303
# Set up aliases
304
config['alias.st'] = 'status'
305
config['alias.co'] = 'checkout'
306
config['alias.br'] = 'branch'
307
config['alias.lg'] = 'log --oneline --graph --all'
308
309
# Configure line endings
310
config['core.autocrlf'] = 'input' # Linux/Mac
311
# config['core.autocrlf'] = 'true' # Windows
312
313
# Configure push behavior
314
config['push.default'] = 'simple'
315
config['push.followTags'] = 'true'
316
317
# Configure pull behavior
318
config['pull.rebase'] = 'false'
319
320
# Configure colors
321
config['color.ui'] = 'auto'
322
config['color.status'] = 'auto'
323
config['color.diff'] = 'auto'
324
config['color.branch'] = 'auto'
325
```
326
327
#### Repository-Specific Settings
328
329
```python
330
# Set up repository-specific hooks path
331
config['core.hooksPath'] = '.githooks'
332
333
# Configure repository-specific gitignore
334
config['core.excludesfile'] = '.gitignore_global'
335
336
# Set up work tree specific settings
337
config['core.worktree'] = '../working-directory'
338
339
# Configure sparse checkout
340
config['core.sparseCheckout'] = 'true'
341
342
# Set up Git LFS
343
config['filter.lfs.clean'] = 'git-lfs clean -- %f'
344
config['filter.lfs.smudge'] = 'git-lfs smudge -- %f'
345
config['filter.lfs.process'] = 'git-lfs filter-process'
346
config['filter.lfs.required'] = 'true'
347
```
348
349
#### Advanced Configuration
350
351
```python
352
# Working with included config files
353
config.add_file('/path/to/custom.config', pygit2.GIT_CONFIG_LEVEL_LOCAL)
354
355
# Parse configuration values
356
bool_val = config.parse_bool('true') # True
357
int_val = config.parse_int32('42') # 42
358
int_val = config.parse_int64('1000000') # 1000000
359
360
# Find config file paths
361
try:
362
global_path = pygit2.config_find_global()
363
print(f"Global config: {global_path}")
364
365
system_path = pygit2.config_find_system()
366
print(f"System config: {system_path}")
367
368
xdg_path = pygit2.config_find_xdg()
369
print(f"XDG config: {xdg_path}")
370
except OSError as e:
371
print(f"Config file not found: {e}")
372
373
# Delete configuration keys
374
del config['old.setting']
375
376
# Check configuration level priority
377
for entry in config:
378
level_names = {
379
pygit2.GIT_CONFIG_LEVEL_SYSTEM: 'system',
380
pygit2.GIT_CONFIG_LEVEL_GLOBAL: 'global',
381
pygit2.GIT_CONFIG_LEVEL_LOCAL: 'local',
382
pygit2.GIT_CONFIG_LEVEL_WORKTREE: 'worktree'
383
}
384
level_name = level_names.get(entry.level, f'level-{entry.level}')
385
print(f"{entry.name} = {entry.value} ({level_name})")
386
```