Debian Codegraph @

internal/cli/config.go

raw symbols SCIP
1 package cli
2
3 import (
4 "errors"
5 "fmt"
6 "io"
7 "os"
8 "os/user"
9 "strings"
10
11 "go.yaml.in/yaml/v4"
12 )
13
14 // Config holds the contents of a config file.
15 type Config struct {
16 DefaultFormat string `yaml:"default_format"`
17 }
18
19 var cfg = Config{
20 DefaultFormat: "json",
21 }
22 var cfgLoaded = false
23
24 // LoadConfig loads the config from the given path.
25 // If already loaded, returned previously loaded config.
26 func LoadConfig(path string) (Config, error) {
27 if cfgLoaded {
28 return cfg, nil
29 }
30
31 if strings.HasPrefix(path, "~/") {
32 usr, err := user.Current()
33 if err != nil {
34 return cfg, fmt.Errorf("error getting current user: %v", err)
35 }
36 path = usr.HomeDir + path[1:]
37 }
38
39 f, err := os.Open(path)
40 if errors.Is(err, os.ErrNotExist) {
41 cfgLoaded = true
42 return cfg, nil
43 }
44 if err != nil {
45 return cfg, fmt.Errorf("error opening config file at path %q: %w", path, err)
46 }
47 defer func() {
48 _ = f.Close()
49 }()
50 decoder := yaml.NewDecoder(f)
51 err = decoder.Decode(&cfg)
52 if err != nil && !errors.Is(err, io.EOF) {
53 return cfg, fmt.Errorf("error parsing config file: %w", err)
54 }
55 cfgLoaded = true
56 return cfg, nil
57 }