Skip to content

Commit

Permalink
feat: allow to run shell commands
Browse files Browse the repository at this point in the history
In addition to user inputs and environment variables, allow to run shell
commands and pass them to the command.

Signed-off-by: Yves Brissaud <[email protected]>
  • Loading branch information
eunomie committed Oct 9, 2024
1 parent 8ee3421 commit cde7e53
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 7 deletions.
4 changes: 3 additions & 1 deletion examples/alpine-hello.runx.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ actions:
type: run
env:
- USER
cmd: --rm {{.Ref}} echo hello {{env "USER"}}
shell:
uname: uname
cmd: --rm {{.Ref}} echo hello {{env "USER"}} from {{sh "uname"}}

- id: hello
desc: Say hello!
Expand Down
25 changes: 25 additions & 0 deletions runkit/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,13 @@ func (r *Runnable) compute() error {
"opt": func(optName string) string {
return r.data.Opts[optName]
},
"sh": func(cmdName string) (string, error) {
cmd, ok := r.Action.Shell[cmdName]
if !ok {
return "", fmt.Errorf("shell command %q not found", cmdName)
}
return sh(context.Background(), cmd)
},
}).Parse(r.Action.Command)
if err != nil {
return err
Expand Down Expand Up @@ -113,3 +120,21 @@ func (r *Runnable) Run(ctx context.Context) error {
}
return runner.Run(ctx, parsedCmd)
}

func sh(ctx context.Context, cmd string) (string, error) {
parseCmd, err := syntax.NewParser().Parse(strings.NewReader(cmd), "")
if err != nil {
return "", err
}

var osOut, osErr strings.Builder
runner, err := interp.New(interp.Env(expand.ListEnviron(os.Environ()...)), interp.StdIO(nil, &osOut, &osErr))
if err != nil {
return "", err
}
if err = runner.Run(ctx, parseCmd); err != nil {
return "", err
}

return osOut.String(), nil
}
13 changes: 7 additions & 6 deletions runkit/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,13 @@ type (
}

Action struct {
ID string `yaml:"id" json:"id"`
Desc string `yaml:"desc,omitempty" json:"desc,omitempty"`
Type ActionType `yaml:"type" json:"type"`
Command string `yaml:"cmd" json:"cmd,omitempty"`
Env []string `yaml:"env,omitempty" json:"env,omitempty"`
Options []Opt `yaml:"opts,omitempty" json:"opts,omitempty"`
ID string `yaml:"id" json:"id"`
Desc string `yaml:"desc,omitempty" json:"desc,omitempty"`
Type ActionType `yaml:"type" json:"type"`
Command string `yaml:"cmd" json:"cmd,omitempty"`
Env []string `yaml:"env,omitempty" json:"env,omitempty"`
Options []Opt `yaml:"opts,omitempty" json:"opts,omitempty"`
Shell map[string]string `yaml:"shell,omitempty" json:"shell,omitempty"`
}

Opt struct {
Expand Down

0 comments on commit cde7e53

Please sign in to comment.