htmgo/framework/config/project.go

83 lines
2.1 KiB
Go
Raw Normal View History

2024-10-13 21:33:08 +00:00
package config
import (
"gopkg.in/yaml.v3"
2024-10-14 14:58:37 +00:00
"log/slog"
2024-10-13 21:33:08 +00:00
"os"
"path"
"strings"
2024-10-13 21:33:08 +00:00
)
type ProjectConfig struct {
Tailwind bool `yaml:"tailwind"`
WatchIgnore []string `yaml:"watch_ignore"`
WatchFiles []string `yaml:"watch_files"`
AutomaticPageRoutingIgnore []string `yaml:"automatic_page_routing_ignore"`
AutomaticPartialRoutingIgnore []string `yaml:"automatic_partial_routing_ignore"`
2024-10-13 21:33:08 +00:00
}
func DefaultProjectConfig() *ProjectConfig {
return &ProjectConfig{
Tailwind: true,
WatchIgnore: []string{
"node_modules", ".git", ".idea", "assets/dist",
},
WatchFiles: []string{
2024-10-14 14:49:48 +00:00
"**/*.go", "**/*.html", "**/*.css", "**/*.js", "**/*.json", "**/*.yaml", "**/*.yml", "**/*.md",
2024-10-13 21:33:08 +00:00
},
}
}
func (cfg *ProjectConfig) Enhance() *ProjectConfig {
2024-10-13 21:33:08 +00:00
defaultCfg := DefaultProjectConfig()
if len(cfg.WatchFiles) == 0 {
cfg.WatchFiles = defaultCfg.WatchFiles
}
if len(cfg.WatchIgnore) == 0 {
cfg.WatchIgnore = defaultCfg.WatchIgnore
}
for i, s := range cfg.AutomaticPartialRoutingIgnore {
parts := strings.Split(s, string(os.PathSeparator))
if len(parts) == 0 {
continue
}
if parts[0] != "partials" {
cfg.AutomaticPartialRoutingIgnore[i] = path.Join("partials", s)
}
}
for i, s := range cfg.AutomaticPageRoutingIgnore {
parts := strings.Split(s, string(os.PathSeparator))
if len(parts) == 0 {
continue
}
if parts[0] != "pages" {
cfg.AutomaticPageRoutingIgnore[i] = path.Join("pages", s)
}
}
2024-10-13 21:33:08 +00:00
return cfg
}
func FromConfigFile(workingDir string) *ProjectConfig {
defaultCfg := DefaultProjectConfig()
names := []string{"htmgo.yaml", "htmgo.yml", "_htmgo.yaml", "_htmgo.yml"}
for _, name := range names {
filePath := path.Join(workingDir, name)
if _, err := os.Stat(filePath); err == nil {
cfg := &ProjectConfig{}
bytes, err := os.ReadFile(filePath)
if err == nil {
err = yaml.Unmarshal(bytes, cfg)
2024-10-14 14:58:37 +00:00
if err != nil {
slog.Error("Error parsing config file", slog.String("file", filePath), slog.String("error", err.Error()))
os.Exit(1)
2024-10-13 21:33:08 +00:00
}
return cfg.Enhance()
2024-10-13 21:33:08 +00:00
}
}
}
return defaultCfg
}