ccl/internal/pkg/command/command.go

133 lines
3.0 KiB
Go
Raw Normal View History

/*
Copyright © 2022 Joel D. Elkins <joel@elkins.co>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package command
import (
"fmt"
"io"
"os/exec"
)
type CommandType int
func (ct CommandType) String() string {
switch ct {
case CT_SH:
return "SHELL"
case CT_REF:
return "FUNC"
case CT_INDIRECT:
return "INDIRECT"
case CT_SET:
return "SET"
case CT_DEBUG:
return "DEBUG"
default:
return "UNKOWN"
}
}
const (
CT_SH CommandType = iota
CT_REF
CT_INDIRECT
CT_SET
CT_DEBUG
)
type Command struct {
Type CommandType
Command interface{}
}
func NewShell(cmd string) Command {
return Command{CT_SH, cmd}
}
func NewFunc(f func() string) Command {
return Command{CT_REF, f}
}
func NewIndirect(c Command) Command {
return Command{CT_INDIRECT, c}
}
func NewSet(cs []Command) Command {
return Command{CT_SET, cs}
}
func NewDebug(msg string) Command {
return Command{CT_DEBUG, msg}
}
func (c Command) GetShell() (string, error) {
s, ok := c.Command.(string)
if ok {
return s, nil
}
return s, fmt.Errorf("Problem extracting shell command: CommandType = %d", c.Type)
}
func (c Command) CallRef() (string, error) {
f, ok := c.Command.(func() string)
if ok {
s := f()
return s, nil
}
return "", fmt.Errorf("Type error. Requested = %d, Type = %d", CT_REF, c.Type)
}
func (c Command) Execute(output io.Writer) error {
switch c.Type {
case CT_SH:
cmd, err := c.GetShell()
if err != nil {
return err
}
out, err := exec.Command("sh", "-c", cmd).CombinedOutput()
fmt.Fprintln(output, out)
return err
case CT_REF:
s, err := c.CallRef()
fmt.Println(s)
return err
case CT_INDIRECT:
ct, ok := c.Command.(Command)
if !ok {
return fmt.Errorf("Type error: Requested = %d, Type = %d", CT_INDIRECT, c.Type)
}
return ct.Execute(output)
case CT_SET:
cs, ok := c.Command.([]Command)
if !ok {
return fmt.Errorf("Type error: Requested = %d, Type = %d", CT_SET, c.Type)
}
for i := range cs {
err := cs[i].Execute(output)
if err != nil {
return err
}
}
}
return nil
}