1
0
mirror of https://github.com/osmarks/mycorrhiza.git synced 2024-10-30 03:36:16 +00:00

Categories: Save to disk after changes

This commit is contained in:
Timur Ismagilov 2022-03-20 14:48:16 +03:00
parent 9a60cc2386
commit cdeb378327
2 changed files with 28 additions and 0 deletions

View File

@ -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()
}

View File

@ -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()
}