2024-08-30 16:08:24 +00:00
|
|
|
package util
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2024-09-24 12:44:25 +00:00
|
|
|
"io/fs"
|
|
|
|
"path/filepath"
|
2024-09-24 12:49:47 +00:00
|
|
|
"strings"
|
2024-09-24 12:44:25 +00:00
|
|
|
|
2024-08-30 16:08:24 +00:00
|
|
|
"io"
|
|
|
|
"os"
|
|
|
|
)
|
|
|
|
|
2024-09-24 12:44:25 +00:00
|
|
|
func ReadConfigs(cfgPath string) ([]*Config, error) {
|
|
|
|
var configs []*Config
|
2024-08-30 16:08:24 +00:00
|
|
|
|
2024-09-24 12:44:25 +00:00
|
|
|
err := filepath.Walk(cfgPath, func(path string, info fs.FileInfo, err error) error {
|
2024-09-24 13:01:25 +00:00
|
|
|
name := info.Name()
|
|
|
|
isExample := strings.HasSuffix(name, ".example.json")
|
|
|
|
notJson := !strings.HasSuffix(name, ".json")
|
|
|
|
if info.IsDir() || isExample || notJson {
|
2024-09-24 12:44:25 +00:00
|
|
|
return nil
|
|
|
|
}
|
2024-08-30 16:08:24 +00:00
|
|
|
|
2024-09-24 12:44:25 +00:00
|
|
|
file, err := os.Open(path)
|
2024-08-30 16:08:24 +00:00
|
|
|
|
2024-09-24 12:44:25 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
defer file.Close()
|
2024-08-30 16:08:24 +00:00
|
|
|
|
2024-09-24 12:44:25 +00:00
|
|
|
bytes, err := io.ReadAll(file)
|
|
|
|
if err != nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
var config *Config
|
|
|
|
err = json.Unmarshal(bytes, &config)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
configs = append(configs, config)
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
|
|
|
|
return configs, err
|
2024-08-30 16:08:24 +00:00
|
|
|
}
|
2024-08-31 19:13:16 +00:00
|
|
|
|
2024-09-12 22:15:56 +00:00
|
|
|
func SaveConfig(name string, config Config) error {
|
|
|
|
configs, _ := ReadConfigs(name)
|
2024-08-31 19:13:16 +00:00
|
|
|
configs = append(configs, &config)
|
|
|
|
|
|
|
|
data, err := json.Marshal(configs)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2024-09-12 22:15:56 +00:00
|
|
|
err = os.WriteFile(name, data, 0666)
|
2024-08-31 19:13:16 +00:00
|
|
|
return err
|
|
|
|
}
|