templatefile/pkg/templater/main.go

107 lines
2.6 KiB
Go
Raw Permalink Normal View History

package templater
import (
"fmt"
"io/ioutil"
"log"
"os"
2022-07-01 15:44:07 +02:00
"forge.cadoles.com/pcaseiro/templatefile/pkg/utils"
"github.com/imdario/mergo"
)
var CacheFilePath = "/var/cache/templater.db"
type TemplaterConfig struct {
Name string `json:"Name"`
TemplateDirectory string `json:"TemplateDirectory"`
RootDirectory string `json:"RootDirectory"`
Services map[string]Service `json:"Services"`
GlobalService Service `json:"Globals"`
}
func (tc *TemplaterConfig) loadCache() error {
// Load globals from cache
var cache Service
err := Load(CacheFilePath, &cache)
if err != nil {
fmt.Printf("Warning: No globals to load\n")
}
err = mergo.Merge(&tc.GlobalService, cache)
if err != nil {
return err
}
return nil
}
// Create new configuration "object"
func (tc *TemplaterConfig) New(confpath string, templateDir string, rootDir string) error {
// Load stored globals if needed
lerr := tc.loadCache()
if lerr != nil {
return lerr
}
// Check if the configuration path is a Directory or a file
fileInfo, err := os.Stat(confpath)
if err != nil {
return err
}
if fileInfo.IsDir() {
// The conf path is a directory we load all the files and merge data
files, err := ioutil.ReadDir(confpath)
if err != nil {
return fmt.Errorf("Templater configuration load failed with error: %v", err)
}
for _, file := range files {
fname := fmt.Sprintf("%s/%s", confpath, file.Name())
var ntc TemplaterConfig
err := Load(fname, &ntc)
if err != nil {
return fmt.Errorf("Templater configuration load failed with error: %v", err)
}
err = mergo.Merge(tc, ntc)
if err != nil {
return fmt.Errorf("Templater configuration load failed with error: %v", err)
}
}
} else {
// The conf path is a file we only load this file (of course)
err = Load(confpath, tc)
if err != nil {
return fmt.Errorf("Confiuration read failed with error: %v", err)
}
}
tc.TemplateDirectory = templateDir
tc.RootDirectory = rootDir
return nil
}
// Process the services contained in the configuration "object"
2022-07-01 15:44:07 +02:00
func (tc *TemplaterConfig) ManageServices(dryRun bool) error {
// Get global vars to add on each service
gbls := tc.GlobalService.Vars
2022-07-01 15:44:07 +02:00
if dryRun {
utils.DryRun = dryRun
}
for name, svr := range tc.Services {
err := mergo.Merge(&svr.Vars, gbls)
if err != nil {
return err
}
log.Printf("=== Working on service %s", name)
if err := svr.Manage(tc.TemplateDirectory, tc.RootDirectory); err != nil {
return err
}
log.Printf("=== Service %s processed", name)
log.Printf("")
}
return nil
}