impr: modular sandbox configs
This commit is contained in:
@@ -4,12 +4,15 @@ import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/nalgeon/codapi/internal/fileio"
|
||||
)
|
||||
|
||||
const (
|
||||
configFilename = "config.json"
|
||||
boxesFilename = "boxes.json"
|
||||
commandsFilename = "commands.json"
|
||||
configFilename = "config.json"
|
||||
boxesFilename = "boxes.json"
|
||||
commandsDirname = "commands"
|
||||
)
|
||||
|
||||
// Read reads application config from JSON files.
|
||||
@@ -24,7 +27,7 @@ func Read(path string) (*Config, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cfg, err = ReadCommands(cfg, filepath.Join(path, commandsFilename))
|
||||
cfg, err = ReadCommands(cfg, filepath.Join(path, commandsDirname))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -71,31 +74,36 @@ func ReadBoxes(cfg *Config, path string) (*Config, error) {
|
||||
|
||||
// ReadCommands reads commands config from a JSON file.
|
||||
func ReadCommands(cfg *Config, path string) (*Config, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
fnames, err := filepath.Glob(filepath.Join(path, "*.json"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
commands := make(map[string]SandboxCommands)
|
||||
err = json.Unmarshal(data, &commands)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, playCmds := range commands {
|
||||
for _, cmd := range playCmds {
|
||||
if cmd.Before != nil {
|
||||
setStepDefaults(cmd.Before, cfg.Step)
|
||||
}
|
||||
for _, step := range cmd.Steps {
|
||||
setStepDefaults(step, cfg.Step)
|
||||
}
|
||||
if cmd.After != nil {
|
||||
setStepDefaults(cmd.After, cfg.Step)
|
||||
}
|
||||
cfg.Commands = make(map[string]SandboxCommands, len(fnames))
|
||||
for _, fname := range fnames {
|
||||
sandbox := strings.TrimSuffix(filepath.Base(fname), ".json")
|
||||
commands, err := fileio.ReadJson[SandboxCommands](fname)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
setCommandDefaults(commands, cfg)
|
||||
cfg.Commands[sandbox] = commands
|
||||
}
|
||||
|
||||
cfg.Commands = commands
|
||||
return cfg, err
|
||||
}
|
||||
|
||||
// setCommandDefaults applies global defaults to sandbox commands.
|
||||
func setCommandDefaults(commands SandboxCommands, cfg *Config) {
|
||||
for _, cmd := range commands {
|
||||
if cmd.Before != nil {
|
||||
setStepDefaults(cmd.Before, cfg.Step)
|
||||
}
|
||||
for _, step := range cmd.Steps {
|
||||
setStepDefaults(step, cfg.Step)
|
||||
}
|
||||
if cmd.After != nil {
|
||||
setStepDefaults(cmd.After, cfg.Step)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user