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 todolist
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"os/user"
)
type FileStore struct {
FileLocation string
Data []Todo
}
func NewFileStore() *FileStore {
usr, _ := user.Current()
return &FileStore{FileLocation: usr.HomeDir + "/.todos.json"}
}
func (f *FileStore) Add(todo *Todo) {
todo.Id = f.NextId()
f.Data = append(f.Data, *todo)
}
func (f *FileStore) FindById(id int) *Todo {
for _, todo := range f.Data {
if todo.Id == id {
return &todo
}
}
return nil
}
func (f *FileStore) Delete(id int) {
i := -1
for index, todo := range f.Data {
if todo.Id == id {
i = index
}
}
f.Data = append(f.Data[:i], f.Data[i+1:]...)
}
func (f *FileStore) IndexOf(todoToFind *Todo) int {
for i, todo := range f.Data {
if todo.Id == todoToFind.Id {
return i
}
}
return -1
}
func (f *FileStore) Load() {
data, err := ioutil.ReadFile(f.FileLocation)
if err != nil {
fmt.Println("Error reading file", err)
os.Exit(1)
}
jerr := json.Unmarshal(data, &f.Data)
if jerr != nil {
fmt.Println("Error reading json data", jerr)
os.Exit(1)
}
}
func (f *FileStore) Save() {
data, _ := json.Marshal(f.Data)
if err := ioutil.WriteFile(f.FileLocation, []byte(data), 0644); err != nil {
fmt.Println("Error writing json file", err)
}
}
func (f *FileStore) Todos() []Todo {
return f.Data
}
func (f *FileStore) NextId() int {
maxId := 0
for _, todo := range f.Data {
if todo.Id > maxId {
maxId = todo.Id
}
}
return maxId + 1
}
|