nix-amer/internal/instruction/common.go

77 lines
2.0 KiB
Go

package instruction
import (
"fmt"
"github.com/xdrm-brackets/nix-amer/internal/exec"
"github.com/xdrm-brackets/nix-amer/internal/pkg"
"github.com/xdrm-brackets/nix-amer/internal/ser"
)
// T is the instruction common interface
type T interface {
// Raw input line
Raw() string
// Build the instruction with input arguments
Build(string) error
// Exec the given instruction
Exec(ExecutionContext) ([]byte, error)
// DryRun checks the success of the given instruction without actually running it (non-destructive)
DryRun(ExecutionContext) ([]byte, error)
}
// ExecutionContext contains system-specific drivers to manage the host
type ExecutionContext struct {
PackageManager pkg.PackageManager
ServiceManager ser.ServiceManager
Executor exec.Executor
Alias map[string]string
}
// CreateContext creates an execution contet with the given package-manager and service-manager
// default values are taken from each go package (pkg, ser)
// if _exec is set, it will override the default (os) executor
func CreateContext(_pkg, _ser string, _exec ...exec.Executor) (*ExecutionContext, error) {
// 1. fail if no value and no defaults
if len(_pkg)+len(pkg.DefaultManager) < 1 {
return nil, fmt.Errorf("missing package manager")
}
if len(_ser)+len(ser.DefaultManager) < 1 {
return nil, fmt.Errorf("missing service manager")
}
// 2. set default
if len(_pkg) < 1 {
_pkg = pkg.DefaultManager
}
if len(_ser) < 1 {
_ser = ser.DefaultManager
}
var executor exec.Executor = new(exec.Default)
// 3. load custom executor (optional)
if len(_exec) > 0 && _exec[0] != nil {
executor = _exec[0]
}
// 4. load managers
pkg, err := pkg.Load(_pkg, executor)
if err != nil {
return nil, fmt.Errorf("package manager: %s", err)
}
ser, err := ser.Load(_ser, executor)
if err != nil {
return nil, fmt.Errorf("service manager: %s", err)
}
// 4. build context
return &ExecutionContext{
PackageManager: pkg,
ServiceManager: ser,
Executor: executor,
Alias: make(map[string]string),
}, nil
}