Debian Codegraph @

examples/01-basic-read.go

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