Debian Codegraph @

examples/05-error-handling.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 5: Error Handling
16 //
17 // This example demonstrates proper error handling patterns when working
18 // with gitconfig. Common errors include:
19 // - File not found
20 // - Permission errors
21 // - Parse errors
22 // - Invalid key formats
23 func main() {
24 fmt.Println("=== Example 5: Error Handling ===\n")
25
26 // Error 1: File not found
27 fmt.Println("Error 1: File not found")
28 cfg, err := gitconfig.LoadConfig("/nonexistent/path/.git/config")
29 if err != nil {
30 fmt.Printf(" Expected error: %v\n", err)
31 }
32
33 // Error 2: Permission denied
34 fmt.Println("\nError 2: Permission denied")
35 tmpDir, _ := os.MkdirTemp("", "gitconfig-example-")
36 defer os.RemoveAll(tmpDir)
37
38 restrictedPath := filepath.Join(tmpDir, "restricted-config")
39 os.WriteFile(restrictedPath, []byte("[user]\n name = Test"), 0o644)
40 os.Chmod(restrictedPath, 0o000) // Remove all permissions
41
42 cfg, err = gitconfig.LoadConfig(restrictedPath)
43 if err != nil {
44 fmt.Printf(" Expected error: %v\n", err)
45 }
46 os.Chmod(restrictedPath, 0o644) // Restore permissions for cleanup
47
48 // Error 3: Parse error
49 fmt.Println("\nError 3: Parse error (invalid config syntax)")
50 badConfigPath := filepath.Join(tmpDir, "bad-config")
51 os.WriteFile(badConfigPath, []byte(`[user
52 name = John
53 `), 0o644) // Missing closing bracket
54
55 cfg, err = gitconfig.LoadConfig(badConfigPath)
56 if err != nil {
57 fmt.Printf(" Parse error detected: %v\n", err)
58 }
59
60 // Error 4: Write error (permission denied)
61 fmt.Println("\nError 4: Write error (permission denied)")
62 writePath := filepath.Join(tmpDir, "write-test")
63 os.WriteFile(writePath, []byte("[user]\n name = Test"), 0o644)
64
65 cfg, err = gitconfig.LoadConfig(writePath)
66 if err == nil {
67 os.Chmod(tmpDir, 0o000) // Remove write permissions
68 err = cfg.Set("user.email", "[email protected]")
69 if err != nil {
70 fmt.Printf(" Expected write error: %v\n", err)
71 }
72 os.Chmod(tmpDir, 0o755) // Restore permissions
73 }
74
75 // Error 5: Graceful error handling pattern
76 fmt.Println("\nError 5: Graceful error handling pattern")
77 goodConfigPath := filepath.Join(tmpDir, "good-config")
78 os.WriteFile(goodConfigPath, []byte(`[user]
79 name = John Doe
80 email = [email protected]
81 [core]
82 editor = vim
83 `), 0o644)
84
85 // Pattern: Load with error checking
86 cfg, err = gitconfig.LoadConfig(goodConfigPath)
87 if err != nil {
88 fmt.Printf(" Failed to load config: %v\n", err)
89 fmt.Println(" Continuing with fallback...")
90 return
91 }
92
93 // Pattern: Read with existence check
94 name, ok := cfg.Get("user.name")
95 if !ok {
96 fmt.Println(" user.name not found, using default")
97 name = "Unknown"
98 }
99 fmt.Printf(" user.name = %s\n", name)
100
101 // Pattern: Write with error checking
102 if err := cfg.Set("user.email", "[email protected]"); err != nil {
103 fmt.Printf(" Failed to write config: %v\n", err)
104 log.Printf("Warning: Could not persist changes")
105 } else {
106 fmt.Println(" Changes persisted successfully")
107 }
108
109 // Error 6: Multi-scope errors
110 fmt.Println("\nError 6: Multi-scope errors (Configs)")
111 configs := gitconfig.New()
112 if err := os.Setenv("GOPASS_HOMEDIR", tmpDir); err != nil {
113 log.Fatal(err)
114 }
115 defer func() {
116 _ = os.Unsetenv("GOPASS_HOMEDIR")
117 }()
118
119 // Set paths to non-existent files (this is okay for Configs)
120 configs.LocalConfig = filepath.Join(".git", "config")
121 configs.GlobalConfig = "nonexistent-global"
122
123 // LoadAll handles missing files gracefully
124 configs.LoadAll(tmpDir)
125 fmt.Println(" LoadAll succeeded (skipped missing files)")
126
127 fmt.Println("\n=== Common Error Patterns ===")
128 fmt.Println("1. Check errors after LoadConfig() and LoadAll()")
129 fmt.Println("2. Use if ok := cfg.Get(key) pattern for optional values")
130 fmt.Println("3. Check Set() errors when persisting changes")
131 fmt.Println("4. Handle permission errors gracefully")
132 fmt.Println("5. Provide fallback values for critical config")
133
134 fmt.Println("\n=== Summary ===")
135 fmt.Println("Always check errors when:")
136 fmt.Println(" - Loading config files (might not exist or be unreadable)")
137 fmt.Println(" - Updating config files (might lose permissions)")
138 fmt.Println(" - Parsing config (malformed files)")
139 fmt.Println("Use (value, ok) pattern for optional config values.")
140 }