nix-amer/internal/instruction/cnf.go

84 lines
1.6 KiB
Go

package instruction
import (
"fmt"
"git.xdrm.io/go/nix-amer/internal/cnf"
"os"
"strings"
)
// ErrCannotSet is raised when there is an error trying to update
// a field
var ErrCannotSet = fmt.Errorf("cannot set the field")
type config struct {
raw string
// File is the path to the file
File string
// Path is the configuration field path
Path string
// Value if the value to add or update
Value string
// Format is the configuration format in use
Format *cnf.ConfigurationFormat
}
func (d *config) Raw() string { return d.raw }
func (d *config) Build(_args string) error {
// 1. extract action (sub command)
split := strings.Fields(_args)
// 2. check path
if len(split) < 2 {
return fmt.Errorf("missing configuration path")
}
path := split[0]
value := strings.Join(split[1:], "")
// 3. check path separator
splitPath := strings.Split(path, "@")
if len(splitPath) > 2 {
return fmt.Errorf("invalid path (additional '@'?)")
}
d.File = splitPath[0]
if len(splitPath) > 1 { // add field path only if set
d.Path = splitPath[1]
}
// add value
d.Value = value
d.raw = _args
return nil
}
func (d config) Exec(ctx ExecutionContext) ([]byte, error) {
// 1. try to load format
format, err := cnf.Load(d.File)
if err != nil {
return nil, err
}
// 2. try to update value
if !format.Set(d.Path, d.Value) {
return nil, ErrCannotSet
}
// 3. Update file
file, err := os.OpenFile(d.File, os.O_WRONLY, 0)
if err != nil {
return nil, err
}
defer file.Close()
if _, err = format.WriteTo(file); err != nil {
return nil, err
}
return nil, nil
}