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
|
package todolist
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"os/user"
)
type FileStore struct {
FileLocation string
Loaded bool
}
func NewFileStore() *FileStore {
localrepo := ".todos.json"
usr, _ := user.Current()
homerepo := fmt.Sprintf("%s/.todos.json", usr.HomeDir)
_, err1 := os.Stat(localrepo)
_, err2 := os.Stat(homerepo)
if err1 == nil {
return &FileStore{FileLocation: localrepo, Loaded: false}
} else if err2 == nil {
return &FileStore{FileLocation: homerepo, Loaded: false}
} else {
return &FileStore{FileLocation: "", Loaded: false}
}
}
func (f *FileStore) Load() ([]*Todo, error) {
data, err := ioutil.ReadFile(f.FileLocation)
if err != nil {
fmt.Println("Error reading", f.FileLocation, "by", err)
return nil, err
os.Exit(1)
}
var todos []*Todo
jerr := json.Unmarshal(data, &todos)
if jerr != nil {
fmt.Println("Error reading", f.FileLocation, "by", jerr)
return nil, jerr
os.Exit(1)
}
f.Loaded = true
return todos, nil
}
func (f *FileStore) Initialize() {
_, err := ioutil.ReadFile(f.FileLocation)
if err == nil {
fmt.Println("It looks like a .todos.json file already exists! Doing nothing.")
os.Exit(0)
}
if err := ioutil.WriteFile(f.FileLocation, []byte("[]"), 0644); err != nil {
fmt.Println("Error writing json file", err)
os.Exit(1)
}
fmt.Println("Todo repo initialized.")
}
func (f *FileStore) Save(todos []*Todo) {
data, _ := json.Marshal(todos)
if err := ioutil.WriteFile(f.FileLocation, []byte(data), 0644); err != nil {
fmt.Println("Error writing json file", err)
}
}
|