LoadConfig loads the config from the given path. If already loaded, returned previously loaded config.
(path string)
| 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 | } |