-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01-basic-read.go
More file actions
95 lines (80 loc) · 2.24 KB
/
01-basic-read.go
File metadata and controls
95 lines (80 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
//go:build examples
// +build examples
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"github.com/gopasspw/gitconfig"
)
// Example 1: Basic Read
//
// This example demonstrates how to read configuration values from a git config file.
// It shows:
// - Loading a config file
// - Reading string values
// - Handling missing keys
func main() {
// Create a temporary git config file for this example
tmpDir, err := os.MkdirTemp("", "gitconfig-example-")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(tmpDir)
configPath := filepath.Join(tmpDir, ".git", "config")
if err := os.MkdirAll(filepath.Dir(configPath), 0o755); err != nil {
log.Fatal(err)
}
// Write a sample config file
sampleConfig := `[user]
name = John Doe
email = john@example.com
[core]
editor = vim
pager = less
[branch "main"]
remote = origin
merge = refs/heads/main
`
err = os.WriteFile(configPath, []byte(sampleConfig), 0o644)
if err != nil {
log.Fatal(err)
}
fmt.Println("=== Example 1: Basic Read ===\n")
// Load the config file
cfg, err := gitconfig.LoadConfig(configPath)
if err != nil {
log.Fatal(err)
}
// Read simple values
fmt.Println("Reading simple values:")
if name, ok := cfg.Get("user.name"); ok {
fmt.Printf(" user.name = %s\n", name)
}
if email, ok := cfg.Get("user.email"); ok {
fmt.Printf(" user.email = %s\n", email)
}
if editor, ok := cfg.Get("core.editor"); ok {
fmt.Printf(" core.editor = %s\n", editor)
}
// Try to read a non-existent key
fmt.Println("\nAttempting to read non-existent key:")
if value, ok := cfg.Get("nonexistent.key"); ok {
fmt.Printf(" nonexistent.key = %s\n", value)
} else {
fmt.Println(" nonexistent.key not found (this is expected)")
}
// Read values from subsections (branch)
fmt.Println("\nReading from subsections (branch.main.*):")
if remote, ok := cfg.Get("branch.main.remote"); ok {
fmt.Printf(" branch.main.remote = %s\n", remote)
}
if merge, ok := cfg.Get("branch.main.merge"); ok {
fmt.Printf(" branch.main.merge = %s\n", merge)
}
fmt.Println("\n=== Summary ===")
fmt.Println("Config file loaded and values read successfully.")
fmt.Println("Use cfg.Get(key) to retrieve values.")
fmt.Println("Returns (value, ok) - check ok to see if key exists.")
}