wasi-module-sdk-go/exec/command.go

88 lines
1.5 KiB
Go
Raw Normal View History

2023-06-29 19:55:40 +00:00
package exec
import (
"fmt"
"io"
2023-08-15 19:46:02 +00:00
2023-09-05 20:06:42 +00:00
wasiv1 "code.icb4dc0.de/buildr/api/generated/wasi/v1"
2023-08-15 19:46:02 +00:00
"code.icb4dc0.de/buildr/wasi-module-sdk-go/mem"
2023-06-29 19:55:40 +00:00
)
func NewCommand(name string, args ...string) *Command {
return &Command{
Name: name,
Args: args,
}
}
type Command struct {
Name string
Args []string
WorkingDir string
Env map[string]string
StdIn io.Reader
}
func (c *Command) AddEnv(envToAdd map[string]string) {
2023-08-15 19:46:02 +00:00
if envToAdd == nil {
return
}
if c.Env == nil {
c.Env = make(map[string]string)
}
for k, v := range envToAdd {
c.Env[k] = v
}
}
2023-06-29 19:55:40 +00:00
func (c *Command) Run() error {
2023-09-05 20:06:42 +00:00
execReq := &wasiv1.ProcessStartRequest{
2023-06-29 19:55:40 +00:00
Command: c.Name,
Args: c.Args,
WorkingDirectory: c.WorkingDir,
Environment: c.Env,
}
if c.StdIn != nil {
if stdInData, err := io.ReadAll(c.StdIn); err != nil {
return err
} else {
execReq.Stdin = stdInData
}
}
data, err := execReq.MarshalVT()
if err != nil {
return err
}
result := _exec(mem.DataToManagedPtr(data))
if result == 0 {
return fmt.Errorf("failed to execute command: %s", c.Name)
}
resultPtr := uint32(result >> 32)
resultSize := uint32(result)
if resultSize == 0 {
return nil
}
2023-09-05 20:06:42 +00:00
execResp := new(wasiv1.ProcessStartResponse)
2023-06-29 19:55:40 +00:00
if err := execResp.UnmarshalVT(mem.PtrToData(resultPtr, resultSize)); err != nil {
return err
}
if execResp.ExitCode != 0 {
return &Error{
ExitCode: int(execResp.ExitCode),
Message: execResp.Error,
StdErr: execResp.Stderr,
}
}
return nil
}