github.com/emcfarlane/larking@v0.0.0-20220605172417-1704b45ee6c3/starlib/starlarkrule/run.go (about) 1 package starlarkrule 2 3 import ( 4 "bytes" 5 "fmt" 6 "log" 7 "os" 8 "os/exec" 9 10 "github.com/emcfarlane/larking/starlib/starlarkthread" 11 "go.starlark.net/starlark" 12 ) 13 14 func run(thread *starlark.Thread, fnname string, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { 15 var ( 16 name string 17 dir string 18 argList *starlark.List 19 envList *starlark.List 20 ) 21 22 if err := starlark.UnpackArgs( 23 fnname, args, kwargs, 24 "name", &name, "dir", &dir, "args", &argList, "env?", &envList, 25 ); err != nil { 26 return nil, err 27 } 28 29 var ( 30 x starlark.Value 31 cmdArgs []string 32 cmdEnv []string 33 ) 34 35 iter := argList.Iterate() 36 for iter.Next(&x) { 37 s, ok := starlark.AsString(x) 38 if !ok { 39 return nil, fmt.Errorf("error: unexpected run arg: %v", x) 40 } 41 cmdArgs = append(cmdArgs, s) 42 } 43 iter.Done() 44 45 iter = envList.Iterate() 46 for iter.Next(&x) { 47 s, ok := starlark.AsString(x) 48 if !ok { 49 return nil, fmt.Errorf("error: unexpected run env: %v", x) 50 } 51 cmdEnv = append(cmdEnv, s) 52 } 53 iter.Done() 54 55 ctx := starlarkthread.GetContext(thread) 56 cmd := exec.CommandContext(ctx, name, cmdArgs...) 57 cmd.Dir = dir // TODO: filepath.ToSlash? 58 cmd.Env = append(os.Environ(), cmdEnv...) 59 60 var output bytes.Buffer 61 cmd.Stderr = &output 62 cmd.Stdout = &output 63 64 if err := cmd.Run(); err != nil { 65 //os.RemoveAll(tmpDir) 66 log.Printf("Unexpected error: %v\n%v", err, output.String()) 67 return nil, err 68 } 69 return starlark.None, nil 70 }