// Compile compiles and links sourcefile and atomically renames the // resulting binary to runfile. func Compile(sourcefile, runfile string, useGd bool) (err os.Error) { pid := strconv.Itoa(os.Getpid()) content, err := ioutil.ReadFile(sourcefile) if len(content) > 2 && content[0] == '#' && content[1] == '!' { content[0] = '/' content[1] = '/' sourcefile = runfile + "." + pid + ".go" ioutil.WriteFile(sourcefile, content, 0600) defer os.Remove(sourcefile) } bindir := filepath.Join(runtime.GOROOT(), "bin") if useGd { gd := filepath.Join(bindir, "mgd") if _, err := os.Stat(gd); err != nil { if gd, err = exec.LookPath("mgd"); err != nil { return os.NewError("can't find mgd") } } err = Exec([]string{gd, "-L", "_obj", ".", "-q", "-o", runfile}) return err } else { n := TheChar() gc := filepath.Join(bindir, n+"g") ld := filepath.Join(bindir, n+"l") if _, err := os.Stat(gc); err != nil { if gc, err = exec.LookPath(n + "g"); err != nil { return os.NewError("can't find " + n + "g") } } if _, err := os.Stat(ld); err != nil { if ld, err = exec.LookPath(n + "l"); err != nil { return os.NewError("can't find " + n + "l") } } gcout := runfile + "." + pid + "." + n ldout := runfile + "." + pid err = Exec([]string{gc, "-o", gcout, sourcefile}) if err != nil { return err } defer os.Remove(gcout) err = Exec([]string{ld, "-o", ldout, gcout}) if err != nil { return err } return os.Rename(ldout, runfile) } panic("Unreachable code") }
func main() { flag.Parse() cwd, _ := os.Getwd() binary, _ := exec.LookPath(flag.Args()[0]) for { cmd, _ := exec.Run(binary, flag.Args(), nil, cwd, exec.PassThrough, exec.PassThrough, exec.PassThrough) pid := cmd.Process.Pid extras := make(ABC, 0) if *httpTimeoutUrl != "" { extras = append(extras, setupHttpTimeoutCheck(pid)) } if *httpStatusUrl != "" { extras = append(extras, setupHttpStatusCheck(pid)) } if *maxMemory > 0 { extras = append(extras, setupMaxMemoryCheck(pid)) } cmd.Wait(os.WSTOPPED) println("Process died, restarting.") extras.closeAll() } }
func envOrDefault(cmd, dfl string) string { p, err := exec.LookPath(cmd) if err != nil { return dfl } return p }
func ExecRead(cmd string, args ...string) (out []byte, err os.Error) { abscmd, err := exec.LookPath(cmd) if err != nil { return out, os.NewError("Couldn't find " + cmd + ": " + err.String()) } cmdargs := make([]string, len(args)+1) cmdargs[0] = cmd for i, a := range args { cmdargs[i+1] = a } printexec(cmd, args) pid, err := exec.Run(abscmd, cmdargs, nil, "", exec.PassThrough, exec.Pipe, exec.PassThrough) if err != nil { return } out, err = ioutil.ReadAll(pid.Stdout) if err != nil { return } ws, err := pid.Wait(0) // could have been os.WRUSAGE if err != nil { return } if ws.ExitStatus() != 0 { err = os.NewError(cmd + " exited with status " + strconv.Itoa(ws.ExitStatus())) } return out, nil }
// run runs the command argv, resolving argv[0] if necessary by searching $PATH. // It provides input on standard input to the command. func run(argv []string, input []byte) (out string, err os.Error) { if len(argv) < 1 { err = os.EINVAL goto Error } prog, ok := lookPathCache[argv[0]] if !ok { prog, err = exec.LookPath(argv[0]) if err != nil { goto Error } lookPathCache[argv[0]] = prog } cmd := exec.Command(prog, argv[1:]...) if len(input) > 0 { cmd.Stdin = bytes.NewBuffer(input) } bs, err := cmd.CombinedOutput() if err == nil { return string(bs), nil } Error: err = &runError{dup(argv), err} return }
func diff(b1, b2 []byte) (data []byte, err os.Error) { f1, err := ioutil.TempFile("", "gofix") if err != nil { return nil, err } defer os.Remove(f1.Name()) defer f1.Close() f2, err := ioutil.TempFile("", "gofix") if err != nil { return nil, err } defer os.Remove(f2.Name()) defer f2.Close() f1.Write(b1) f2.Write(b2) diffcmd, err := exec.LookPath("diff") if err != nil { return nil, err } c, err := exec.Run(diffcmd, []string{"diff", f1.Name(), f2.Name()}, nil, "", exec.DevNull, exec.Pipe, exec.MergeWithStdout) if err != nil { return nil, err } defer c.Close() return ioutil.ReadAll(c.Stdout) }
// genRun implements run and tryRun. func genRun(dir string, stdin []byte, cmd []string, quiet bool) os.Error { bin, err := exec.LookPath(cmd[0]) if err != nil { return err } p, err := exec.Run(bin, cmd, os.Environ(), dir, exec.Pipe, exec.Pipe, exec.MergeWithStdout) if *verbose { fmt.Fprintf(os.Stderr, "%s: %s; %s %s\n", argv0, dir, bin, strings.Join(cmd[1:], " ")) } if err != nil { return err } go func() { p.Stdin.Write(stdin) p.Stdin.Close() }() var buf bytes.Buffer io.Copy(&buf, p.Stdout) io.Copy(&buf, p.Stdout) w, err := p.Wait(0) p.Close() if !w.Exited() || w.ExitStatus() != 0 { if !quiet || *verbose { if dir != "" { dir = "cd " + dir + "; " } fmt.Fprintf(os.Stderr, "%s: === %s%s\n", argv0, dir, strings.Join(cmd, " ")) os.Stderr.Write(buf.Bytes()) fmt.Fprintf(os.Stderr, "--- %s\n", w) } return os.ErrorString("running " + cmd[0] + ": " + w.String()) } return nil }
// run executes the specified command and returns its output and an error. func run(cmd ...string) ([]byte, os.Error) { // find the specified binary bin, err := exec.LookPath(cmd[0]) if err != nil { // report binary as well as the error return nil, os.NewError(cmd[0] + ": " + err.String()) } // run the binary and read its combined stdout and stderr into a buffer p, err := exec.Run(bin, cmd, os.Environ(), "", exec.DevNull, exec.Pipe, exec.MergeWithStdout) if err != nil { return nil, err } var buf bytes.Buffer io.Copy(&buf, p.Stdout) w, err := p.Wait(0) p.Close() if err != nil { return nil, err } // set the error return value if the program had a non-zero exit status if !w.Exited() || w.ExitStatus() != 0 { err = os.ErrorString("running " + cmd[0] + ": " + w.String()) } return buf.Bytes(), err }
func mustRunDoozer(listen, web, attach string) *exec.Cmd { exe, err := exec.LookPath("doozerd") if err != nil { panic(err) } args := []string{ "doozerd", "-l=127.0.0.1:" + listen, "-w=127.0.0.1:" + web, } if attach != "" { args = append(args, "-a", "127.0.0.1:"+attach) } cmd, err := exec.Run( exe, args, nil, ".", exec.PassThrough, exec.PassThrough, exec.PassThrough, ) if err != nil { panic(err) } return cmd }
func TestRmRf(t *testing.T) { t.Log("TestRmRf") wd, clean := setupUfs(t) defer clean() err := os.MkdirAll(wd+"/ro/dir/subdir", 0755) CheckSuccess(err) contents := "hello" fn := wd + "/ro/dir/subdir/y" err = ioutil.WriteFile(fn, []byte(contents), 0644) CheckSuccess(err) bin, err := exec.LookPath("rm") CheckSuccess(err) cmd := exec.Command(bin, "-rf", wd+"/mount/dir") err = cmd.Run() if err != nil { t.Fatal("rm -rf returned error:", err) } for _, f := range []string{"dir/subdir/y", "dir/subdir", "dir"} { if fi, _ := os.Lstat(filepath.Join(wd, "mount", f)); fi != nil { t.Errorf("file %s should have disappeared: %v", f, fi) } } names, err := Readdirnames(wd + "/rw/DELETIONS") CheckSuccess(err) if len(names) != 3 { t.Fatal("unexpected names", names) } }
func run(name string, args ...string) string { path, err := exec.LookPath(name) if err != nil { panic(err) } cwd, err := os.Getwd() if err != nil { panic(err) } p, err := exec.Run(path, append([]string{name}, args...), os.Environ(), cwd, exec.Pipe, exec.Pipe, exec.Pipe) if err != nil { panic(err) } defer p.Close() data, err := ioutil.ReadAll(p.Stdout) if err != nil { panic(err) } return strings.TrimSpace(string(data)) }
func getProgramPath() (string, os.Error) { program := os.Args[0] dir, _ := path.Split(program) if dir == "" { binPath, pathError := exec.LookPath(program) if pathError != nil { if syscall.Access(program, syscall.O_RDONLY) != 0 { return "", os.NewError("Path to " + program + " couldn't be found") } cwd, cwdError := os.Getwd() if cwdError != nil { return "", cwdError } return cwd, nil } binPath, _ = path.Split(binPath) return binPath, nil } dir, _ = abspath(dir) return dir, nil }
func main() { commands := []string{ `ls /home`, `ls '/home'`, `ls -l /home`, `echo 'Hello, one and all!'`, `which python`, // Outputs "hello, world\n" instead of "\n" `python -c print 'hello, world'`, // Outputs "\n" instead of "hello, world\n" `python -c "print 'hello, world'"`, } for ndx, c := range commands { fmt.Printf("Command %d of %d: %s\n", ndx+1, len(commands), c) // When I replace 3 with -1, the last 2 commands produce a Python error argv := strings.Split(c, " ", 3) bin, err := exec.LookPath(argv[0]) if cmd, e := exec.Run(bin, argv, nil, "", exec.DevNull, exec.Pipe, exec.MergeWithStdout); e == nil && err == nil { body, _ := ioutil.ReadAll(cmd.Stdout) fmt.Printf("%s\n", string(body)) } else { fmt.Printf("e: %v", e) fmt.Printf("err: %v", err) } } }
func CreateTestArgv() []string { pwd, e := os.Getwd() if e != nil { log.Fatal("[ERROR] could not locate working directory\n") } argv := make([]string, 0) if global.GetString("-backend") == "express" { vmrun, e := exec.LookPath("vmrun") if e != nil { log.Fatalf("[ERROR] %s\n", e) } argv = append(argv, vmrun) } argv = append(argv, filepath.Join(pwd, global.GetString("-test-bin"))) if global.GetString("-bench") != "" { argv = append(argv, "-test.bench") argv = append(argv, global.GetString("-bench")) } if global.GetString("-match") != "" { argv = append(argv, "-test.run") argv = append(argv, global.GetString("-match")) } if global.GetBool("-verbose") { argv = append(argv, "-test.v") } return argv }
// Format takes a markdown-formatted string and returns an equivalent // HTML-formatted string. // // TODO write built-in markdown implementation, to avoid forking for every // post func Format(md string) (html string, err os.Error) { cmdName, err := exec.LookPath("markdown") if err != nil { return } cmd, err := exec.Run( cmdName, []string{}, os.Environ(), ".", exec.Pipe, exec.Pipe, exec.PassThrough, ) if err != nil { return } cmd.Stdin.WriteString(md) cmd.Stdin.Close() b, err := ioutil.ReadAll(cmd.Stdout) if err != nil { return } html = string(b) err = cmd.Close() return }
func WriteReadS(arg1 string, inp string, args []string) (output string, e os.Error) { debug.Println("calling git",arg1,args) args = stringslice.Cat([]string{"git", arg1}, args) output = "" // empty output if we have an error... git, e := exec.LookPath("git") if e != nil { e = explain("exec.LookPath",e); return } pid,e := exec.Run(git, args, os.Environ(), ".", exec.Pipe, exec.Pipe, exec.PassThrough) if e != nil { announce(e); return } _,e = fmt.Fprint(pid.Stdin, inp) if e != nil { announce(e); return } e = pid.Stdin.Close() if e != nil { announce(e); return } o,e := ioutil.ReadAll(pid.Stdout) output = string(o) if e != nil { announce(e); return } ws,e := pid.Wait(0) // could have been os.WRUSAGE if e != nil { announce(e); return } if ws.ExitStatus() != 0 { e = os.NewError(fmt.Sprintf("git exited with '%v'",ws.ExitStatus())) announce(e) return } return }
func init() { cache := make(map[string]string) translations := make(map[string]string) for i := '1'; i < '7'; i++ { for sv := 0; sv <= bridge.NoTrump; sv++ { stringi := string([]byte{byte(i)}) spoken := stringi + " " + bridge.SuitName[sv] + "." translations[stringi+bridge.SuitHTML[sv]] = spoken translations[stringi+bridge.SuitLetter[sv]] = spoken translations[stringi+bridge.SuitColorHTML[sv]] = spoken } } translations[" P"] = "Pass." translations["P"] = "Pass." translations[" X"] = "Double!" translations["X"] = "Double!" translations["XX"] = "Redouble!" espeak, err := exec.LookPath("espeak") if err == nil { go func() { for { req := <-seek_speech bid := req.bid if sp, ok := translations[bid]; ok { bid = sp } fmt.Println("I am speaking:", bid) if s, ok := cache[req.bid]; ok { req.answer <- answertype{s, nil} } else { c, err := exec.Run(espeak, []string{"espeak", "--stdout"}, nil, "", exec.Pipe, exec.Pipe, exec.PassThrough) if err != nil { req.answer <- answertype{"", err} continue } defer c.Close() fmt.Fprintln(c.Stdin, bid) c.Stdin.Close() o, err := ioutil.ReadAll(c.Stdout) if err != nil { req.answer <- answertype{"", err} continue } out := string(o) cache[req.bid] = out req.answer <- answertype{out, nil} } } }() } else { go func() { fmt.Println("We won't be able to speak, since I can't find espeak!", err) for { req := <-seek_speech req.answer <- answertype{"", os.NewError("Cannot find espeak in path.")} } }() } }
func GetPath() string { file, _ := exec.LookPath(os.Args[0]) dir, _ := path.Split(file) os.Chdir(dir) path, _ := os.Getwd() return path + "/" }
/* This function does exactly the same as "make clean". */ func clean() { bashBin, err := exec.LookPath("bash") if err != nil { logger.Error("Need bash to clean.\n") os.Exit(127) } argv := []string{bashBin, "-c", "commandhere"} if *flagVerboseMode { argv[2] = "rm -rfv *.[568]" } else { argv[2] = "rm -rf *.[568]" } logger.Info("Running: %v\n", argv[2:]) cmd, err := exec.Run(bashBin, argv, os.Environ(), rootPath, exec.DevNull, exec.PassThrough, exec.PassThrough) if err != nil { logger.Error("%s\n", err) os.Exit(1) } waitmsg, err := cmd.Wait(0) if err != nil { logger.Error("Couldn't delete files: %s\n", err) os.Exit(1) } if waitmsg.ExitStatus() != 0 { logger.Error("rm returned with errors.\n") os.Exit(waitmsg.ExitStatus()) } }
func run(argv []string) os.Error { cmd, err := exec.LookPath(argv[0]) if err != nil { return err } var stdin *os.File if syscall.OS == "windows" { stdin, _ = os.Open("CONIN$") } else { stdin = os.Stdin } p, err := os.StartProcess(cmd, argv, &os.ProcAttr{Files: []*os.File{stdin, os.Stdout, os.Stderr}}) if err != nil { return err } defer p.Release() w, err := p.Wait(0) if err != nil { return err } if !w.Exited() || w.ExitStatus() != 0 { return os.NewError("failed to execute text editor") } return nil }
func TestEnvOverride(t *testing.T) { cgifile, _ := filepath.Abs("testdata/test.cgi") var perl string var err os.Error perl, err = exec.LookPath("perl") if err != nil { return } perl, _ = filepath.Abs(perl) cwd, _ := os.Getwd() h := &Handler{ Path: perl, Root: "/test.cgi", Dir: cwd, Args: []string{cgifile}, Env: []string{ "SCRIPT_FILENAME=" + cgifile, "REQUEST_URI=/foo/bar"}, } expectedMap := map[string]string{ "cwd": cwd, "env-SCRIPT_FILENAME": cgifile, "env-REQUEST_URI": "/foo/bar", } runCgiTest(t, h, "GET /test.cgi HTTP/1.0\nHost: example.com\n\n", expectedMap) }
func justrun(cmd string, args ...string) os.Error { abscmd, err := exec.LookPath(cmd) if err != nil { return os.NewError("Couldn't find " + cmd + ": " + err.String()) } cmdargs := make([]string, len(args)+1) cmdargs[0] = cmd for i, a := range args { cmdargs[i+1] = a } pid, err := exec.Run(abscmd, cmdargs, nil, "", exec.PassThrough, exec.PassThrough, exec.PassThrough) if err != nil { return err } wmsg, err := pid.Wait(0) if err != nil { return err } if wmsg.ExitStatus() != 0 { return os.NewError(cmd + " exited with status " + fmt.Sprint(wmsg.ExitStatus())) } return nil }
func FindGobinExternal(name string) (path string, err error) { path, err = exec.LookPath(name) if err != nil { path = filepath.Join(GOBIN, name) _, err = os.Stat(path) } return }
func (r *Request) GetPIN() (pin string, outerr os.Error) { defer catch(&outerr) bin, err := exec.LookPath("pinentry") if err != nil { return r.getPINNaïve() } cmd := exec.Command(bin) stdin, _ := cmd.StdinPipe() stdout, _ := cmd.StdoutPipe() check(cmd.Start()) defer cmd.Wait() defer stdin.Close() br := bufio.NewReader(stdout) lineb, _, err := br.ReadLine() if err != nil { return "", fmt.Errorf("Failed to get getpin greeting") } line := string(lineb) if !strings.HasPrefix(line, "OK") { return "", fmt.Errorf("getpin greeting said %q", line) } set := func(cmd string, val string) { if val == "" { return } fmt.Fprintf(stdin, "%s %s\n", cmd, val) line, _, err := br.ReadLine() if err != nil { panic("Failed to " + cmd) } if string(line) != "OK" { panic("Response to " + cmd + " was " + string(line)) } } set("SETPROMPT", r.Prompt) set("SETDESC", r.Desc) set("SETOK", r.OK) set("SETCANCEL", r.Cancel) set("SETERROR", r.Error) set("OPTION", "ttytype="+os.Getenv("TERM")) tty, err := os.Readlink("/proc/self/fd/0") if err == nil { set("OPTION", "ttyname="+tty) } fmt.Fprintf(stdin, "GETPIN\n") lineb, _, err = br.ReadLine() if err != nil { return "", fmt.Errorf("Failed to read line after GETPIN: %v", err) } line = string(lineb) if strings.HasPrefix(line, "D ") { return line[2:], nil } if strings.HasPrefix(line, "ERR 83886179 ") { return "", ErrCancel } return "", fmt.Errorf("GETPIN response didn't start with D; got %q", line) }
func gc(arch string) { var A string // a:architecture var err os.Error if arch == "" { A = os.Getenv("GOARCH") } else { A = arch } var S, C, L string // S:suffix, C:compiler, L:linker switch A { case "arm": S = ".5" C = "5g" L = "5l" case "amd64": S = ".6" C = "6g" L = "6l" case "386": S = ".8" C = "8g" L = "8l" default: log.Fatalf("[ERROR] unknown architecture: %s\n", A) } pathCompiler, err = exec.LookPath(C) if err != nil { log.Fatalf("[ERROR] could not find compiler: %s\n", C) } pathLinker, err = exec.LookPath(L) if err != nil { log.Fatalf("[ERROR] could not find linker: %s\n", L) } suffix = S }
func express() { var err os.Error pathCompiler, err = exec.LookPath("vmgc") if err != nil { log.Fatalf("[ERROR] could not find compiler: %s\n", pathCompiler) } pathLinker, err = exec.LookPath("vmld") if err != nil { log.Fatalf("[ERROR] could not find linker: %s\n", pathLinker) } suffix = ".vmo" }
func runSystemCommand(argv []string, dir string) string { lookedPath, _ := exec.LookPath(argv[0]) r, w, _ := os.Pipe() pid, _ := os.ForkExec(lookedPath, argv, nil, dir, []*os.File{nil, w, w}) w.Close() os.Wait(pid, 0) var b bytes.Buffer io.Copy(&b, r) return b.String() }
func main() { bin, err := exec.LookPath("python") if cmd, e := exec.Run(bin, []string{"", "-c", `print 'hello world'`}, nil, "", exec.DevNull, exec.Pipe, exec.MergeWithStdout); e == nil && err == nil { b, _ := ioutil.ReadAll(cmd.Stdout) fmt.Printf("output: %s\n", string(b)) } else { fmt.Printf("e: %v\n", e) fmt.Printf("err: %v\n", err) } }
func (d Dag) External() { var err os.Error var argv []string var tmp string var set *stringset.StringSet var i int = 0 set = stringset.New() for _, v := range d { for dep := range v.dependencies.Iter() { if !d.localDependency(dep) { set.Add(dep) } } } for u := range set.Iter() { if !seemsExternal(u) { set.Remove(u) } } argv = make([]string, 0) tmp, err = exec.LookPath("goinstall") if err != nil { log.Fatalf("[ERROR] %s\n", err) } argv = append(argv, tmp) if global.GetBool("-verbose") { argv = append(argv, "-v=true") } argv = append(argv, "-u=true") argv = append(argv, "-clean=true") i = len(argv) argv = append(argv, "dummy") for u := range set.Iter() { argv[i] = u if global.GetBool("-dryrun") { fmt.Printf("%s || exit 1\n", strings.Join(argv, " ")) } else { say.Printf("goinstall: %s\n", u) handy.StdExecve(argv, true) } } }
// // Copy the big database into the data/ dir, bzip2recover to split it into // rec#####dbname.bz2, and move the big database back to the drop dir. // func splitBz2File(recent string) { // Be user friendly: Alert the user and wait a few seconds." fmt.Println("I will be using bzip2recover to split", recent, "into many smaller files.") time.Sleep(3000000000) // Move the recent db over to the data dir since bzip2recover extracts // to the same directory the db exists in, and we don't want to pollute // drop_dir with the rec*.xml.bz2 files. newpath := filepath.Join(conf["data_dir"], basename(recent)) err := os.Rename(recent, newpath) if err != nil { if e, ok := err.(*os.LinkError); ok && e.Error == os.EXDEV { panic(GracefulError("Your source file must be on the same partition as your target dir. Sorry.")) } else { panic(fmt.Sprintf("rename: %T %#v\n", err, err)) } } // Make sure that we move it _back_ to drop dir, no matter what happens. defer os.Rename(newpath, recent) args := []string{"bzip2recover", newpath} executable, patherr := exec.LookPath("bzip2recover") if patherr != nil { fmt.Println("bzip2recover not found anywhere in your path, making wild guess") executable = "/usr/bin/bzip2recover" } environ := os.ProcAttr{ Dir: ".", Env: os.Environ(), Files: []*os.File{os.Stdin, os.Stdout, os.Stderr}, } bz2recover, err := os.StartProcess(executable, args, &environ) if err != nil { switch t := err.(type) { case *os.PathError: if err.(*os.PathError).Error == os.ENOENT { panic(GracefulError("bzip2recover not found. Giving up.")) } else { fmt.Printf("err is: %T: %#v\n", err, err) panic("Unable to run bzip2recover? err is ") } default: fmt.Printf("err is: %T: %#v\n", err, err) panic("Unable to run bzip2recover? err is ") } } bz2recover.Wait(0) }