Debian Codegraph @

examples/02-write-persist.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 2: Write and Persist
16 //
17 // This example demonstrates how to modify configuration values and persist
18 // those changes back to the config file.
19 // It shows:
20 // - Setting configuration values
21 // - Persisting changes to disk
22 // - Verifying changes
23 func main() {
24 // Create a temporary git config file for this example
25 tmpDir, err := os.MkdirTemp("", "gitconfig-example-")
26 if err != nil {
27 log.Fatal(err)
28 }
29 defer os.RemoveAll(tmpDir)
30
31 configPath := filepath.Join(tmpDir, ".git", "config")
32 if err := os.MkdirAll(filepath.Dir(configPath), 0o755); err != nil {
33 log.Fatal(err)
34 }
35
36 // Write initial config
37 initialConfig := `[user]
38 name = John Doe
39 [core]
40 editor = vim
41 `
42 err = os.WriteFile(configPath, []byte(initialConfig), 0o644)
43 if err != nil {
44 log.Fatal(err)
45 }
46
47 fmt.Println("=== Example 2: Write and Persist ===\n")
48
49 // Load the config file
50 cfg, err := gitconfig.LoadConfig(configPath)
51 if err != nil {
52 log.Fatal(err)
53 }
54
55 fmt.Println("Initial config:")
56 printValues(cfg, []string{"user.name", "user.email", "core.editor", "core.pager"})
57
58 // Modify values
59 fmt.Println("\nModifying configuration...")
60 if err := cfg.Set("user.email", "[email protected]"); err != nil {
61 log.Fatal(err)
62 }
63 if err := cfg.Set("core.pager", "less -R"); err != nil {
64 log.Fatal(err)
65 }
66 if err := cfg.Set("core.autocrlf", "false"); err != nil {
67 log.Fatal(err)
68 }
69
70 fmt.Println("After modifications (in memory):")
71 printValues(cfg, []string{"user.name", "user.email", "core.editor", "core.pager", "core.autocrlf"})
72
73 // Set automatically persists to disk when the config has a path
74 fmt.Println("\nChanges persisted to disk.")
75
76 // Reload from disk to verify
77 fmt.Println("\nReloading config from disk...")
78 cfg2, err := gitconfig.LoadConfig(configPath)
79 if err != nil {
80 log.Fatal(err)
81 }
82
83 fmt.Println("Config after reload (verifying persistence):")
84 printValues(cfg2, []string{"user.name", "user.email", "core.editor", "core.pager", "core.autocrlf"})
85
86 // Print the actual file contents
87 fmt.Println("\nActual file contents:")
88 content, err := os.ReadFile(configPath)
89 if err != nil {
90 log.Fatal(err)
91 }
92 fmt.Println(string(content))
93
94 fmt.Println("=== Summary ===")
95 fmt.Println("Configuration values can be modified and persisted using Set().")
96 fmt.Println("The library preserves formatting of the original file.")
97 }
98
99 func printValues(cfg *gitconfig.Config, keys []string) {
100 for _, key := range keys {
101 if value, ok := cfg.Get(key); ok {
102 fmt.Printf(" %s = %s\n", key, value)
103 }
104 }
105 }