GoBroke/tplCmd/funcs_templatecmd.go
2024-12-17 17:39:10 -05:00

74 lines
1.4 KiB
Go

package tplCmd
import (
`bytes`
`os`
`os/exec`
`text/template`
)
// ToCmd returns an (os/)exec.Cmd from a TemplateCmd. t should be a tunnelbroker.FetchedTunnel, generally.
func (c *TemplateCmd) ToCmd(t any) (cmd *exec.Cmd, err error) {
var progName string
var envs []string
var tpl *template.Template
var args []string
var buf *bytes.Buffer = new(bytes.Buffer)
buf.Reset()
if tpl, err = template.New("").Parse(c.Program); err != nil {
return
}
if err = tpl.Execute(buf, t); err != nil {
return
}
progName = buf.String()
if c.Args != nil && len(c.Args) > 0 {
args = make([]string, len(c.Args))
for idx, arg := range c.Args {
buf.Reset()
if tpl, err = template.New("").Parse(arg); err != nil {
return
}
if err = tpl.Execute(buf, t); err != nil {
return
}
args[idx] = buf.String()
}
}
if c.EnvVars != nil && len(c.EnvVars) > 0 {
envs = make([]string, len(c.EnvVars))
for idx, env := range c.EnvVars {
buf.Reset()
if tpl, err = template.New("").Parse(env); err != nil {
return
}
if err = tpl.Execute(buf, t); err != nil {
return
}
envs[idx] = buf.String()
}
}
if !c.IsolateEnv {
if envs != nil && len(envs) > 0 {
envs = append(os.Environ(), envs...)
} else {
envs = os.Environ()
}
}
if args != nil && len(args) > 0 {
cmd = exec.Command(progName, args...)
} else {
cmd = exec.Command(progName)
}
cmd.Env = envs
return
}