From 652a3b06b9de39e147168525c9e90c49760f11da Mon Sep 17 00:00:00 2001 From: Quey-Liang Kao Date: Wed, 8 Mar 2017 10:42:38 +0800 Subject: Global repo as the back-up plan This patch implements the logic discussed at #31, in which the program still tries to find a repo file in the working directory first, and it tries the global one in the home directory if no one is found. --- todolist/file_store.go | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/todolist/file_store.go b/todolist/file_store.go index 5413295..a6fa0d7 100644 --- a/todolist/file_store.go +++ b/todolist/file_store.go @@ -5,6 +5,7 @@ import ( "fmt" "io/ioutil" "os" + "os/user" ) type FileStore struct { @@ -13,10 +14,27 @@ type FileStore struct { } func NewFileStore() *FileStore { - return &FileStore{FileLocation: ".todos.json", Loaded: false} + return &FileStore{FileLocation: "", Loaded: false} +} + +func getLocation() string { + localrepo := ".todos.json" + usr, _ := user.Current() + homerepo := fmt.Sprintf("%s/.todos.json", usr.HomeDir) + _, ferr := os.Stat(localrepo) + + if ferr == nil { + return localrepo + } else { + return homerepo + } } func (f *FileStore) Load() ([]*Todo, error) { + if f.FileLocation == "" { + f.FileLocation = getLocation() + } + data, err := ioutil.ReadFile(f.FileLocation) if err != nil { fmt.Println("No todo file found!") @@ -38,6 +56,10 @@ func (f *FileStore) Load() ([]*Todo, error) { } func (f *FileStore) Initialize() { + if f.FileLocation == "" { + f.FileLocation = ".todos.json" + } + _, err := ioutil.ReadFile(f.FileLocation) if err == nil { fmt.Println("It looks like a .todos.json file already exists! Doing nothing.") -- cgit v1.3