update recipe now can select recipe file

This commit is contained in:
Kenta420 2023-10-03 15:06:50 +07:00
parent b25c836f0c
commit b5cb469a30
11 changed files with 209 additions and 236173 deletions

View file

@ -4,11 +4,14 @@ import (
"encoding/json"
"log"
"os"
"path/filepath"
"recipe-manager/models"
"sort"
)
func readFile() *models.Recipe {
file, err := os.Open("data/data.json")
func readFile(version string) *models.Recipe {
path := filepath.Join("cofffeemachineConfig", version)
file, err := os.Open(path)
if err != nil {
log.Fatalf("Error when open file: %s", err)
@ -30,16 +33,56 @@ func readFile() *models.Recipe {
}
type Data struct {
recipe *models.Recipe
CurrentVersion string
AllVersions []string
recipe *models.Recipe
}
func NewData() *Data {
files, err := filepath.Glob("cofffeemachineConfig/coffeethai02_*.json")
if err != nil {
log.Panic("Error when scan recipe files:", err)
}
sort.Slice(files, func(i, j int) bool {
file1, err := os.Stat(files[i])
if err != nil {
log.Panic("Error when get file info:", err)
}
file2, err := os.Stat(files[j])
if err != nil {
log.Panic("Error when get file info:", err)
}
return file1.ModTime().After(file2.ModTime())
})
for i := 0; i < len(files); i++ {
files[i] = filepath.Base(files[i])
}
return &Data{
recipe: readFile(),
CurrentVersion: "coffeethai02_580.json",
AllVersions: files,
recipe: readFile("coffeethai02_580.json"),
}
}
func (d *Data) GetRecipe() models.Recipe {
func (d *Data) GetRecipe(version string) models.Recipe {
if version == "" || version == d.CurrentVersion {
return *d.recipe
}
log.Println("Change recipe to version:", version)
// change current version and read new recipe
d.CurrentVersion = version
d.recipe = readFile(version)
return *d.recipe
}

File diff suppressed because one or more lines are too long