jx/internal/resource/command.go

81 lines
1.7 KiB
Go
Raw Normal View History

2024-04-05 17:22:17 +00:00
// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
package resource
import (
_ "context"
"fmt"
"gopkg.in/yaml.v3"
_ "log"
_ "net/url"
_ "os"
"os/exec"
"strings"
"text/template"
"io"
"encoding/json"
)
type CommandArg string
type Command struct {
Path string `json:"path" yaml:"path"`
Args []CommandArg `json:"args" yaml:"args"`
}
func NewCommand() *Command {
return &Command{}
}
func (c *Command) Load(r io.Reader) error {
decoder := NewYAMLDecoder(r)
return decoder.Decode(c)
}
func (c *Command) LoadDecl(yamlResourceDeclaration string) error {
decoder := NewYAMLStringDecoder(yamlResourceDeclaration)
return decoder.Decode(c)
}
func (c *Command) Template(value any) ([]string, error) {
var args []string = make([]string, len(c.Args))
for i, arg := range c.Args {
var commandLineArg strings.Builder
err := template.Must(template.New(fmt.Sprintf("arg%d", i)).Parse(string(arg))).Execute(&commandLineArg, value)
if err != nil {
return nil, err
}
args[i] = commandLineArg.String()
}
return args, nil
}
func (c *Command) Execute(value any) ([]byte, error) {
args, err := c.Template(value)
if err != nil {
return nil, err
}
return exec.Command(c.Path, args...).Output()
}
func (c *CommandArg) UnmarshalValue(value string) error {
*c = CommandArg(value)
return nil
}
func (c *CommandArg) UnmarshalJSON(data []byte) error {
var s string
if unmarshalRouteTypeErr := json.Unmarshal(data, &s); unmarshalRouteTypeErr != nil {
return unmarshalRouteTypeErr
}
return c.UnmarshalValue(s)
}
func (c *CommandArg) UnmarshalYAML(value *yaml.Node) error {
var s string
if err := value.Decode(&s); err != nil {
return err
}
return c.UnmarshalValue(s)
}