Debian Codegraph @

ARCHITECTURE.md

raw
1 # Architecture
2
3 This document describes the architecture and design of the gitconfig library.
4
5 ## Overview
6
7 gitconfig is a Go library for parsing and manipulating git configuration files without depending on the git CLI tool. The library maintains the structure of the original config file (including comments and whitespace) while allowing programmatic access and modification.
8
9 ## Core Concepts
10
11 ### Configuration Scopes
12
13 Git config has a hierarchical scope system. Each scope corresponds to a different level of configuration:
14
15 ```text
16 Priority (highest to lowest):
17
18 Environment Variables (GIT_CONFIG_*)
19 ↓
20 Per-Worktree Config (.git/config.worktree)
21 ↓
22 Local/Repository Config (.git/config)
23 ↓
24 Global/User Config (~/.gitconfig or ~/.config/git/config)
25 ↓
26 System-wide Config (/etc/gitconfig)
27 ↓
28 Presets (built-in defaults)
29 ```
30
31 When a key is requested, the library searches through scopes in priority order and returns the first match found. This allows settings at higher-priority scopes to override lower ones.
32
33 ### Key Structure
34
35 Git config keys follow a hierarchical structure:
36
37 ```text
38 section.key → Simple value
39 section.subsection.key → Value in a subsection
40 ```
41
42 Keys are normalized according to git rules:
43
44 - Section names: case-insensitive, typically lowercase
45 - Subsection names: case-sensitive
46 - Key names: case-insensitive, typically lowercase
47
48 ### Configuration Format
49
50 Git config files follow an INI-like format:
51
52 ```ini
53 [section]
54 key = value
55
56 [section "subsection"]
57 key = value
58
59 ; Comments
60 # Another comment
61
62 [section]
63 multivalue = first
64 multivalue = second
65 ```
66
67 Special considerations:
68
69 - Subsections in quotes preserve case
70 - Multiple values for same key are supported
71 - Comments and whitespace are preserved during modifications
72 - Boolean values can be implicit (presence indicates true)
73
74 ## Architecture Components
75
76 ### 1. Config Structure
77
78 **Purpose:** Represents a single configuration file (one scope)
79
80 **File:** `config.go`
81
82 **Key Responsibilities:**
83
84 - Parse a single config file
85 - Maintain both parsed representation (`vars` map) and raw text representation
86 - Support reading (Get, GetAll, IsSet)
87 - Support writing (Set, Unset)
88 - Preserve formatting during modifications
89
90 **Design Pattern: Round-Trip Preservation**
91
92 The Config struct maintains two parallel representations:
93
94 1. **Parsed representation** (`vars map[string][]string`)
95 - Fast lookups: O(1)
96 - Ordered values for multi-value keys
97 - Structure: `section.subsection.key` → `[]string`
98
99 2. **Raw text representation** (strings.Builder)
100 - Original file content
101 - Preserves comments and whitespace
102 - Modified in-place on write operations
103
104 When reading, the library uses the parsed `vars` map. When writing, it modifies the raw text representation to maintain the original file structure.
105
106 ```go
107 type Config struct {
108 vars raw string // Original file content
109 // Internal parsed structure
110 }
111 ```
112
113 **Write Algorithm:**
114
115 1. Find existing key location in raw text
116 2. Update value in-place if exists, append if new
117 3. Reconstruct raw text preserving all other content
118 4. Flush to disk
119
120 **Complexity Analysis:**
121
122 - Get: O(1)
123 - Set: O(n) where n = file size (due to raw text rewriting)
124 - Unset: O(n)
125
126 ### 2. Configs Structure
127
128 **Purpose:** Unified interface for all configuration scopes
129
130 **File:** `configs.go`
131
132 **Key Responsibilities:**
133
134 - Load and manage multiple Config objects (one per scope)
135 - Implement scope precedence/priority
136 - Provide unified Get/Set/Unset interface
137 - Route writes to specific scopes
138 - Handle scope-aware operations
139
140 **Design Pattern: Scope Delegation**
141
142 Configs acts as a facade over multiple Config objects:
143
144 ```go
145 type Configs struct {
146 env Config // Environment variables
147 worktree Config // Worktree-specific
148 local Config // Repository-specific
149 global Config // User-specific
150 system Config // System-wide
151 preset Config // Built-in defaults
152 }
153 ```
154
155 **Hierarchy Implementation:**
156
157 When calling `Get(key)`:
158
159 1. Check environment variables
160 2. Check worktree config
161 3. Check local config
162 4. Check global config
163 5. Check system config
164 6. Check presets
165 7. Return first match or error
166
167 This is implemented as a simple linear search with early termination. Optimization considerations were examined but deemed unnecessary given typical config module sizes (< 10KB).
168
169 **Write API:**
170
171 - `SetLocal()` → writes to local scope
172 - `SetGlobal()` → writes to global scope
173 - `SetWorktree()` → writes to worktree scope
174 - `Set()` → writes to local scope (default)
175
176 This prevents silent surprises where Set() might write to unexpected scope based on environment state.
177
178 ### 3. Utility Functions
179
180 **Purpose:** Common parsing and matching operations
181
182 **File:** `utils.go`
183
184 **Key Functions:**
185
186 | Function | Purpose | Implementation |
187 |----------|---------|-----------------|
188 | `splitKey()` | Parse key into section, subsection, key | String splitting logic |
189 | `canonicalizeKey()` | Normalize key per git rules | Case normalization |
190 | `globMatch()` | Pattern matching for includes | gobwas/glob wrapper |
191 | `parseLineForComment()` | Handle quoted strings in values | State machine parser |
192 | `trim()` | Whitespace handling | Standard library wrapper |
193
194 ### 4. Platform-Specific Code
195
196 **Purpose:** Handle differences between operating systems
197
198 **Files:**
199
200 - `gitconfig.go` - Common functions
201 - `gitconfig_windows.go` - Windows-specific paths
202 - `gitconfig_others.go` - Unix/Linux/macOS paths
203
204 **Key Differences:**
205
206 - Home directory detection (environment variables)
207 - Path separators (\ vs /)
208 - Config file locations (Windows vs Unix conventions)
209 - Permission handling
210
211 ## Design Decisions
212
213 ### 1. No External Dependencies (Except gobwas/glob)
214
215 **Decision:** Minimize external dependencies
216
217 **Reasoning:**
218
219 - Improves portability and cross-compilation
220 - Reduces build complexity
221 - Avoids dependency version conflicts
222 - Easier to maintain long-term
223
224 **Exception - gobwas/glob:**
225
226 - Required for include conditional pattern matching
227 - Minimal pure-Go library
228 - No dependencies of its own
229
230 ### 2. Round-Trip Preservation
231
232 **Decision:** Maintain original file formatting during modifications
233
234 **Reasoning:**
235
236 - Preserves user formatting intentions
237 - Retains comments which may contain important notes
238 - Matches git behavior of preserving structure
239 - Enables collaborative workflows where formatting matters
240
241 **Trade-off:**
242
243 - File write is O(n) instead of O(1) (n = file size)
244 - Acceptable because: config files are small (< 10KB typical), write frequency is low
245
246 ### 3. Scope Separation in API
247
248 **Decision:** Separate local/global/worktree in public API
249
250 **Reasoning:**
251
252 - Makes scope explicit (no hidden behavior)
253 - Prevents bugs where wrong scope is written
254 - Self-documenting code (SetLocal() clearly means local)
255 - Aligns with git subcommands (git config --local vs --global)
256
257 **Trade-off:**
258
259 - Slightly more verbose API
260 - Benefit: correctness and clarity outweigh verbosity
261
262 ### 4. Single String per Get()
263
264 **Decision:** Get() returns single string, GetAll() for multiple values
265
266 **Reasoning:**
267
268 - Simpler common case (most keys have one value)
269 - Clear distinction between single and multi-value patterns
270 - Prevents accidental data loss
271
272 **Trade-off:**
273
274 - Extra method for multi-value keys
275 - Benefit: prevents silent data truncation bugs
276
277 ### 5. Parsed Map with String Keys
278
279 **Decision:** Store parsed config as `map[string][]string`
280
281 **Reasoning:**
282
283 - Fast lookups: O(1)
284 - Simple structure
285 - Easy to reason about
286 - Compatible with standard library patterns
287
288 **Trade-off:**
289
290 - Loses structural hierarchy (flat namespace)
291 - Benefit: simplicity and performance
292
293 ## Thread Safety
294
295 **Current:** The library is NOT thread-safe by default.
296
297 **Reason:**
298
299 - Config file format is relatively simple
300 - Most applications load config once at startup
301 - Proper synchronization is application responsibility
302 - Adds complexity for uncommon use case
303
304 **Recommendation for concurrent use:**
305
306 - Use sync.RWMutex to protect Config/Configs objects
307 - Serialize writes to prevent corruption
308 - Example:
309
310 ```go
311 type ThreadSafeConfig struct {
312 mu sync.RWMutex
313 cfg *gitconfig.Config
314 }
315
316 func (tc *ThreadSafeConfig) Get(key string) (string, bool) {
317 tc.mu.RLock()
318 defer tc.mu.RUnlock()
319 return tc.cfg.Get(key)
320 }
321 ```
322
323 ## Performance Characteristics
324
325 ### Time Complexity
326
327 | Operation | Complexity | Notes |
328 |-----------|-------------|-------|
329 | Get(key) | O(1) | Map lookup |
330 | GetAll(key) | O(1) | Map lookup |
331 | Set(key) | O(n) | n = file size (rewrite required) |
332 | Unset(key) | O(n) | n = file size |
333 | IsSet(key) | O(1) | Map lookup |
334 | LoadAll() | O(m) | m = number of config files |
335
336 ### Space Complexity
337
338 - **Parsed representation:** O(k) where k = number of keys
339 - **Raw representation:** O(f) where f = file size
340 - **Total:** O(k + f)
341
342 For typical git configs: < 10KB, so negligible impact.
343
344 ### Real-world Performance
345
346 On typical systems:
347
348 - Loading a config: < 1ms
349 - Reading a value: < 0.1ms
350 - Writing a value: 1-5ms
351 - Loading all scopes: 5-10ms
352
353 Performance is not a bottleneck for config operations since they typically happen at application startup.
354
355 ## Include File Handling
356
357 gitconfig supports the `[include]` directive:
358
359 ```ini
360 [include]
361 path = /path/to/common.conf
362 ```
363
364 **Implementation:**
365
366 1. Parser detects include directives
367 2. Recursively loads included files
368 3. Values from includes are merged into the same Config object
369 4. Later values override earlier ones (path order matters)
370
371 **Use Cases:**
372
373 - Base configurations (DRY principle)
374 - Environment-specific overrides
375 - Team shared settings
376 - Machine-specific secrets (with .gitignore)
377
378 ## Conditional Includes
379
380 Git also supports conditional includes (gitconfig 2.13+):
381
382 ```ini
383 [includeIf "gitdir:~/work/"]
384 path = ~/.gitconfig-work
385 ```
386
387 **Implementation:**
388
389 - Uses glob pattern matching (globMatch)
390 - Conditional evaluated at load time
391 - Only matching includes are processed
392
393 ## Future Extensibility
394
395 ### Design Stability
396
397 The core API is stable and unlikely to change significantly because:
398
399 - Strongly tied to git config semantics
400 - Already covers primary use cases
401 - Simple, minimal API reduces change surface area
402
403 ## Testing Strategy
404
405 Unit tests with a target coverage: > 80%