-
-
Notifications
You must be signed in to change notification settings - Fork 50
/
state.go
54 lines (46 loc) · 939 Bytes
/
state.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
package main
import (
"encoding/json"
"errors"
"io/fs"
"os"
"github.com/adrg/xdg"
)
// State is application state between runs
type State struct {
CurrentFolder string
CurrentSnippet string
}
// Save saves the state of the application
func (s State) Save() error {
fi, err := os.Create(defaultState())
if err != nil {
return err
}
defer fi.Close()
return json.NewEncoder(fi).Encode(s)
}
// defaultState returns the default state path
func defaultState() string {
if c := os.Getenv("NAP_STATE"); c != "" {
return c
}
statePath, err := xdg.StateFile("nap/state.json")
if err != nil {
return "state.json"
}
return statePath
}
// readState returns the application state
func readState() State {
var s State
fi, err := os.Open(defaultState())
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return s
}
defer fi.Close()
if err := json.NewDecoder(fi).Decode(&s); err != nil {
return s
}
return s
}