-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp_config.go
71 lines (56 loc) · 1.52 KB
/
app_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
package main
import (
"bytes"
"encoding/json"
"fmt"
"os"
"github.com/adrg/xdg"
)
type AppConfig struct {
Width int `json:"width"`
Height int `json:"height"`
DataBasePath string `json:"databasePath"`
ImageBasePath string `json:"imageBasePath"`
ImagePath string `json:"imagePath"`
}
func saveConfig(configPath string, appConfig AppConfig) error {
b, err := json.Marshal(appConfig)
if err != nil {
return fmt.Errorf("error marshalling config: %s", err)
}
buf := new(bytes.Buffer)
err = json.Indent(buf, b, "", " ")
if err != nil {
return fmt.Errorf("error indenting config: %s", err)
}
err = os.WriteFile(configPath, buf.Bytes(), 0644)
if err != nil {
return fmt.Errorf("error writing config: %s", err)
}
return nil
}
func loadConfig(configPath string) (*AppConfig, error) {
dataPath, err := xdg.DataFile("njournal/data")
if err != nil {
return nil, fmt.Errorf("error getting data path: %s", err)
}
imageBasePath := xdg.UserDirs.Pictures
imagePath := "njournal"
if _, err := os.Stat(fmt.Sprintf("%v/%v", imageBasePath, imagePath)); os.IsNotExist(err) {
err = os.MkdirAll(fmt.Sprintf("%v/%v", imageBasePath, imagePath), 0755)
if err != nil {
return nil, fmt.Errorf("error creating data directory: %s", err)
}
}
appConfig := AppConfig{
Width: 800,
Height: 600,
DataBasePath: dataPath,
ImageBasePath: imageBasePath,
ImagePath: imagePath,
}
if err := saveConfig(configPath, appConfig); err != nil {
return nil, err
}
return &appConfig, nil
}