95 lines
1.8 KiB
Go
95 lines
1.8 KiB
Go
package commands
|
|
|
|
import (
|
|
"gopkg.in/yaml.v3"
|
|
"io/ioutil"
|
|
"os"
|
|
"os/user"
|
|
"path/filepath"
|
|
"strings"
|
|
)
|
|
|
|
const defaultCacheDirectory = "~/.cache/courgette"
|
|
|
|
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 (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: defaultCacheDirectory,
|
|
},
|
|
}
|
|
|
|
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.Cache.Dir, 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)
|
|
}
|