impr: modular sandbox configs

This commit is contained in:
Anton
2023-12-05 00:53:50 +05:00
parent 07b523cd4d
commit cfe8970ebf
9 changed files with 113 additions and 62 deletions

View File

@@ -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)
}
}
}