-
Notifications
You must be signed in to change notification settings - Fork 2
/
environment.go
113 lines (92 loc) · 2.45 KB
/
environment.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package main
import (
"crypto/md5"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
log "golang.org/x/exp/slog"
)
// NOTE: ClientVersion is set via build flags
var ClientVersion = "dev"
// write buffered data to the users cache directory
// used to store unsent data in the case of an unexpected shutdown
func toUserCache(data sendDataJob) {
cache, err := os.UserCacheDir()
if err != nil {
log.Error("$HOME is likely undefined", "error", err)
}
targetDir := filepath.Join(cache, "imup")
if err := os.MkdirAll(targetDir, 0755); err != nil {
log.Error("cannot create directory in user cache", "error", err)
}
b, err := json.Marshal(data)
if err != nil {
log.Error("cannot marshal data", "error", err)
}
h := md5.New()
_, err = io.WriteString(h, string(b))
if err != nil {
log.Error("cannot hash data", "error", err)
}
if err := os.WriteFile(fmt.Sprintf("%s/%x.json", targetDir, h.Sum(nil)), b, 0666); err != nil {
log.Error("cannot write data to disk", "error", err)
}
}
func fromCacheDir() ([]sendDataJob, bool) {
data := []sendDataJob{}
cache, err := os.UserCacheDir()
if err != nil {
log.Error("$HOME is likely undefined", "error", err)
return data, false
}
targetDir := filepath.Join(cache, "imup")
// check to see if path exists before reading
if _, err := os.Stat(targetDir); err != nil {
log.Debug("path may not exist", "error", err)
return data, false
}
files, err := os.ReadDir(targetDir)
if err != nil {
log.Error("cannot read from targetDir", "error", err)
return data, false
}
for _, f := range files {
if job, ok := fromCache(fmt.Sprintf("%s/%s", targetDir, f.Name())); ok {
data = append(data, job)
}
}
return data, len(data) > 0
}
// read imup data from users cache directory
func fromCache(name string) (sendDataJob, bool) {
data := sendDataJob{}
var err error
var file *os.File
if file, err = os.Open(name); err != nil {
log.Error("cannot open file", "error", err)
return data, false
}
defer file.Close()
if err := json.NewDecoder(file).Decode(&data); err != nil {
return data, false
}
return data, true
}
func clearCache() {
cache, err := os.UserCacheDir()
if err != nil {
log.Error("$HOME is likely undefined", "error", err)
return
}
targetDir := filepath.Join(cache, "imup")
files, err := os.ReadDir(targetDir)
if err != nil {
log.Error("cannot read from targetDir", "error", err)
return
}
for _, f := range files {
os.Remove(fmt.Sprintf("%s/%s", targetDir, f.Name()))
}
}