diff --git a/hyphae/categories/categories.go b/hyphae/categories/categories.go index d46cc93..4ac180f 100644 --- a/hyphae/categories/categories.go +++ b/hyphae/categories/categories.go @@ -55,6 +55,7 @@ func AddHyphaToCategory(hyphaName, catName string) { categoryToHyphae[catName] = &categoryNode{hyphaList: []string{hyphaName}} } mutex.Unlock() + go saveToDisk() } // RemoveHyphaFromCategory removes the hypha from the category and updates the records on the disk. If the hypha is not in the category, nothing happens. @@ -68,4 +69,5 @@ func RemoveHyphaFromCategory(hyphaName, catName string) { node.removeHypha(hyphaName) } mutex.Unlock() + go saveToDisk() } diff --git a/hyphae/categories/files.go b/hyphae/categories/files.go index 0cf17a7..fd5c3df 100644 --- a/hyphae/categories/files.go +++ b/hyphae/categories/files.go @@ -6,6 +6,7 @@ import ( "github.com/bouncepaw/mycorrhiza/util" "log" "os" + "sync" ) var categoryToHyphae = map[string]*categoryNode{} @@ -119,3 +120,28 @@ func readCategoriesFromDisk() (catFileRecord, error) { return record, nil } + +var fileMutex sync.Mutex + +func saveToDisk() { + var ( + record catFileRecord + ) + for name, node := range categoryToHyphae { + record.Categories = append(record.Categories, catRecord{ + Name: name, + Hyphae: node.hyphaList, + }) + } + data, err := json.MarshalIndent(record, "", "\t") + if err != nil { + log.Fatalln(err) // Better fail now, than later + } + // TODO: make the data safer somehow?? Back it up before overwriting? + fileMutex.Lock() + err = os.WriteFile(files.CategoriesJSON(), data, 0666) + if err != nil { + log.Fatalln(err) + } + fileMutex.Unlock() +}