RoadSign/pkg/sign/configurator.go

60 lines
1.1 KiB
Go
Raw Normal View History

2023-11-17 17:42:04 +00:00
package sign
2023-11-16 15:06:59 +00:00
import (
"io"
"os"
"path/filepath"
"strings"
2023-12-10 03:30:31 +00:00
"gopkg.in/yaml.v2"
2023-11-16 15:06:59 +00:00
)
2023-11-18 06:30:35 +00:00
var App *AppConfig
2023-11-16 15:06:59 +00:00
func ReadInConfig(root string) error {
cfg := &AppConfig{
2023-12-10 03:30:31 +00:00
Sites: []*SiteConfig{},
2023-11-16 15:06:59 +00:00
}
if err := filepath.Walk(root, func(fp string, info os.FileInfo, err error) error {
var site SiteConfig
if info.IsDir() {
return nil
} else if file, err := os.OpenFile(fp, os.O_RDONLY, 0755); err != nil {
return err
} else if data, err := io.ReadAll(file); err != nil {
return err
2023-12-10 03:30:31 +00:00
} else if err := yaml.Unmarshal(data, &site); err != nil {
2023-11-16 15:06:59 +00:00
return err
} else {
// Extract file name as site id
site.ID = strings.SplitN(filepath.Base(fp), ".", 2)[0]
2023-12-10 03:30:31 +00:00
cfg.Sites = append(cfg.Sites, &site)
2023-11-16 15:06:59 +00:00
}
return nil
}); err != nil {
return err
}
2023-11-18 06:30:35 +00:00
App = cfg
2023-11-16 15:06:59 +00:00
return nil
}
func SaveInConfig(root string, cfg *AppConfig) error {
for _, site := range cfg.Sites {
2023-12-10 03:30:31 +00:00
data, _ := yaml.Marshal(site)
2023-11-16 15:06:59 +00:00
fp := filepath.Join(root, site.ID)
if file, err := os.OpenFile(fp, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755); err != nil {
return err
} else if _, err := file.Write(data); err != nil {
return err
}
}
return nil
}