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 { fmt.Println("No todo file found!") fmt.Println("You may run 'todo init' to initialize an empty repo in working directory.") os.Exit(1) return nil } } 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) } }