This repository has been archived by the owner on May 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconfig.go
75 lines (59 loc) · 1.65 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package main
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"github.com/adrg/xdg"
)
type Config struct {
RecentProjects []string `json:"RecentProjects"`
Version string `json:"Version"`
}
func NewConfig() Config {
return Config{
RecentProjects: []string{},
Version: version,
}
}
var ConfigPath = filepath.Join(xdg.ConfigHome, "acdc", "config.json")
var ConfigDir = filepath.Dir(ConfigPath)
func (app *App) LoadConfig() (Config, error) {
// Create new config structure
c := NewConfig()
// Read Config File
bs, err := os.ReadFile(ConfigPath)
// If file doesn't exist, create it and return; otherwise, return error
if os.IsNotExist(err) {
if err := app.SaveConfig(c); err != nil {
return c, fmt.Errorf("error creating '%s': %w", ConfigPath, err)
}
return c, nil
} else if err != nil {
return c, fmt.Errorf("error reading '%s': %w", ConfigPath, err)
}
// Read file into structure
if err := json.Unmarshal(bs, &c); err != nil {
return c, fmt.Errorf("error parsing '%s': %w", ConfigPath, err)
}
// Set version
c.Version = version
return c, nil
}
// SaveConfig saves the config file
func (app *App) SaveConfig(c Config) error {
// Convert config into JSON
bs, err := json.MarshalIndent(c, "", "\t")
if err != nil {
return fmt.Errorf("error marshalling config: %w", err)
}
// Create config file directory
if err := os.MkdirAll(ConfigDir, 0777); err != nil {
return fmt.Errorf("error creating config dir '%s': %w", ConfigDir, err)
}
// Write config file
if err := os.WriteFile(ConfigPath, bs, 0777); err != nil {
return fmt.Errorf("error writing config file '%s': %w", ConfigPath, err)
}
return nil
}