-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnoteSave.go
88 lines (73 loc) · 1.61 KB
/
noteSave.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
package main
import (
"bytes"
"encoding/json"
"os"
"sort"
"strings"
"sync"
)
func loadNotes() {
noteLock.Lock()
defer noteLock.Unlock()
contents, err := os.ReadDir(DATA_DIR + NOTES_DIR)
if err != nil {
critLog("Unable to read notes directory.")
return
}
for _, item := range contents {
if item.IsDir() {
continue
}
if strings.HasSuffix(item.Name(), ".json") {
readNoteFile(item.Name())
}
}
//Sort by name
sort.Slice(noteTypes, func(i, j int) bool {
return noteTypes[i].Name < noteTypes[j].Name
})
}
func readNoteFile(fileName string) {
filePath := DATA_DIR + NOTES_DIR + fileName
data, err := readFile(filePath)
if err != nil {
return
}
new := noteTypeData{File: filePath}
err = json.Unmarshal(data, &new)
if err != nil {
critLog("readNote: Unable to unmarshal note file: %v", filePath)
}
noteTypes = append(noteTypes, new)
errLog("Loaded note type %v", new.Name)
}
var noteLock sync.Mutex
func saveNotes(force bool) {
noteLock.Lock()
defer noteLock.Unlock()
for _, item := range noteTypes {
if !item.dirty && !force {
continue
}
tempList := item
item.dirty = false
go func(tempList noteTypeData) {
tempList.Version = NOTES_VERSION
filePath := DATA_DIR + NOTES_DIR + tempList.File + ".json"
outbuf := new(bytes.Buffer)
enc := json.NewEncoder(outbuf)
enc.SetIndent("", "\t")
err := enc.Encode(&tempList)
if err != nil {
critLog("saveNotes: enc.Encode: %v", err.Error())
return
}
err = saveFile(filePath, outbuf.Bytes())
if err != nil {
critLog("saveNotes: saveFile failed %v", err.Error())
return
}
}(tempList)
}
}