courgette/internal/commands/configuration.go

100 lines
2 KiB
Go
Raw Permalink Normal View History

package commands
import (
2024-09-01 17:31:30 +00:00
metadata "courgette/metadata"
"gopkg.in/yaml.v3"
"io/ioutil"
"os"
"os/user"
"path/filepath"
"strings"
)
type CacheConfiguration struct {
Dir string `yaml:"dir"`
}
type RunnerConfiguration struct {
Labels map[string]string `yaml:"labels"`
}
type ContainerConfiguration struct {
Driver string `yaml:"driver"`
}
type Configuration struct {
Containers ContainerConfiguration `yaml:"containers"`
Runner RunnerConfiguration `yaml:"runner"`
Cache CacheConfiguration `yaml:"cache"`
}
func getDefaultCacheDirectory() string {
dir, _ := os.UserCacheDir()
return filepath.Join(dir, metadata.APPLICATION_NAME)
}
func (c Configuration) GetCacheDir() string {
currentUser, _ := user.Current()
homeDir := currentUser.HomeDir
cacheDir := c.Cache.Dir
if filepath.HasPrefix(cacheDir, "~") {
parts := strings.Split(cacheDir, "/")
finalParts := []string{homeDir}
finalParts = append(finalParts, parts[1:]...)
cacheDir = filepath.Join(finalParts...)
}
return cacheDir
}
func applyConfigDefaults(config Configuration) Configuration {
defaults := Configuration{
Containers: ContainerConfiguration{
Driver: "podman",
},
Cache: CacheConfiguration{
Dir: getDefaultCacheDirectory(),
},
}
if config.Containers.Driver == "" {
config.Containers.Driver = defaults.Containers.Driver
}
if config.Cache.Dir == "" {
config.Cache.Dir = defaults.Cache.Dir
}
return config
}
func NewConfigFromYamlBytes(configRaw []byte) (*Configuration, error) {
var config Configuration
if yamlError := yaml.Unmarshal(configRaw, &config); yamlError != nil {
return nil, yamlError
}
config = applyConfigDefaults(config)
if err := os.MkdirAll(config.GetCacheDir(), 0755); err != nil {
return nil, err
}
return &config, nil
}
func NewConfigFromFile(configPath string) (*Configuration, error) {
configRaw, err := ioutil.ReadFile(configPath)
if err != nil {
return nil, err
}
return NewConfigFromYamlBytes(configRaw)
}