func main() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "%s", Help) os.Exit(1) } flag.Parse() if *version { fmt.Printf("%s", Version) os.Exit(0) } if *unset != "" { os.Unsetenv(*unset) } cmd := new(exec.Cmd) cmd.Env = env // Check for "-" as an argument, because it means the same as "-i" if flag.Arg(0) == "-" { cmd.Env = make([]string, 0) } for i, arg := range flag.Args() { if strings.Index(arg, delim) > 0 { cmd.Env = append(cmd.Env, arg) } else if arg != "-" { if *nullEol { fatal.Fatalln("cannot specify --null (-0) with command") } cmd.Path = arg cmd.Args = append(cmd.Args, flag.Args()[i:]...) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr err := execvp(cmd) if err != nil { fatal.Fatalln(err) } return } i++ } eol := '\n' if *nullEol { eol = '\x00' } for _, e := range env { fmt.Printf("%s%c", e, eol) } return }
// stem words and add them to vocabulary func (vocabulary Dictionary) add(words []string, mode string) (wordIDs []int) { var lemma string wordIDs = make([]int, len(words)) for idx, word := range words { if _, ok := vocabulary.Vtoi[word]; ok { wordIDs[idx] = vocabulary.Vtoi[word] } else { python := new(exec.Cmd) args := []string{"lemmatizer.py", "--vocabulary"} args = append(args, word) args = append(args, "--pos") args = append(args, mode) python.Args = args // python.Path = "/home/lea/Code/Python/lemmatizer.py" python.Path = "/local/lea/thesis/python/lemmatizer.py" out, _ := python.Output() lemma = strings.Trim(string(out), "\n") if _, ok := vocabulary.Vtoi[lemma]; !ok { vocabulary.VList[vocabIdx] = lemma vocabulary.Vtoi[lemma] = vocabIdx vocabulary.Itov[vocabIdx] = lemma vocabulary.POSList[vocabIdx] = mode vocabIdx++ } wordIDs[idx] = vocabulary.Vtoi[lemma] } } return wordIDs }
func RunWithEnvAndWd(command string, args []string, env []string, wd string) (proc *exec.Cmd, err error) { //log.Println(command, args) //hho := exec.PassThrough args = prepend(args, command) env = mergeEnv(os.Environ(), env) binpath, err := findCmd(findEnv(env, "PATH"), command) if err != nil { return nil, err } cmd := new(exec.Cmd) cmd.Path = binpath cmd.Args = args cmd.Env = env cmd.Dir = wd cmd.Stderr = os.Stderr cmd.Stdout = os.Stdout err = cmd.Start() if err != nil { log.Print("Error running command ", command, ": ", err, "\n") return nil, err } return cmd, nil }
// Launch creates and begins debugging a new process. First entry in // `cmd` is the program to run, and then rest are the arguments // to be supplied to that process. func Launch(cmd []string) (*Process, error) { var ( proc *exec.Cmd err error ) // check that the argument to Launch is an executable file if fi, staterr := os.Stat(cmd[0]); staterr == nil && (fi.Mode()&0111) == 0 { return nil, NotExecutableErr } dbp := New(0) dbp.execPtraceFunc(func() { proc = exec.Command(cmd[0]) proc.Args = cmd proc.Stdout = os.Stdout proc.Stderr = os.Stderr proc.SysProcAttr = &syscall.SysProcAttr{Ptrace: true, Setpgid: true} err = proc.Start() }) if err != nil { return nil, err } dbp.Pid = proc.Process.Pid _, _, err = dbp.wait(proc.Process.Pid, 0) if err != nil { return nil, fmt.Errorf("waiting for target execve failed: %s", err) } return initializeDebugProcess(dbp, proc.Path, false) }
func pluginInfo(name string) (ver, short, long string) { if os.Getenv("HKPLUGINMODE") == "info" { return "", "plugin exec loop", "plugin exec loop" } short = "no description" long = name + ": unknown description" var cmd exec.Cmd cmd.Args = []string{name} cmd.Path = lookupPlugin(name) cmd.Env = append([]string{"HKPLUGINMODE=info"}, os.Environ()...) buf, err := cmd.Output() if err != nil { return } info := string(buf) if !strings.HasPrefix(info, name+" ") { return } info = info[len(name)+1:] i := strings.Index(info, ": ") if i < 0 { return } ver, info = info[:i], info[i+2:] i = strings.Index(info, "\n\n") if i < 0 || 50 < i || strings.Contains(info[:i], "\n") { return } short, long = info[:i], info[i+2:] return ver, strings.TrimSpace(short), strings.TrimSpace(long) }
func pluginInfo(name string) (ver, short, long string) { if os.Getenv("HKPLUGINMODE") == "info" { return "", "[plugin exec loop]", "[plugin exec loop]\n" } var cmd exec.Cmd cmd.Args = []string{name} cmd.Path = lookupPlugin(name) cmd.Env = append([]string{"HKPLUGINMODE=info"}, os.Environ()...) buf, err := cmd.Output() if err != nil { fmt.Fprintln(os.Stderr, err) return "", "[unknown description]", "[unknown description]\n" } info := string(buf) if !strings.HasPrefix(info, name+" ") { return "", "[unknown description]", "[unknown description]\n" } info = info[len(name)+1:] i := strings.Index(info, ": ") ver, info = info[:i], info[i+2:] i = strings.Index(info, "\n\n") short, long = info[:i], info[i+2:] if len(short) > 50 || strings.Contains(short, "\n") { return "", "[unknown description]", "[unknown description]\n" } return ver, short, long }
func runScript(watcher *fsnotify.Watcher, interval int, command string) { for { now := time.Now() select { case event := <-watcher.Events: if time.Since(now) > time.Duration(interval)*time.Millisecond { if event.Op >= 1 && !strings.HasPrefix(event.Name, ".") { clear() var cmd *exec.Cmd commands := strings.Split(command, " ") // TODO: windows support name := commands[0] cmd = exec.Command(name) cmd.Args = commands cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr err := cmd.Run() if err != nil { log.Println("error:", err) } } now = time.Now() } case err := <-watcher.Errors: log.Println("error:", err) } } }
// Initialize a new ExecutablePlugin from path to executable and daemon mode (true or false) func NewExecutablePlugin(a Arg, path string) (*ExecutablePlugin, error) { jsonArgs, err := json.Marshal(a) if err != nil { return nil, err } // Init the cmd cmd := new(exec.Cmd) cmd.Path = path cmd.Args = []string{path, string(jsonArgs)} // Link the stdout for response reading stdout, err := cmd.StdoutPipe() if err != nil { return nil, err } stderr, err := cmd.StderrPipe() if err != nil { return nil, err } // Init the ExecutablePlugin and return ePlugin := new(ExecutablePlugin) ePlugin.cmd = cmd ePlugin.stdout = stdout ePlugin.args = a ePlugin.stderr = stderr return ePlugin, nil }
func execute(path string, vcs string, vcs_verb string) { if vcs_verb == "" { return } a := func(wd string, vcs string, vcs_verb string, seq bool) { msg := "=== @{!" + vcs_color[vcs] + "} " msg += filepath.Base(path) msg += "@| (@!" + vcs + "@|) ===" var cmd exec.Cmd cmd.Dir = wd cmd.Args = strings.Split(vcs_verb, " ") path, err := exec.LookPath(cmd.Args[0]) if err != nil { path = cmd.Args[0] } cmd.Path = path out, err := cmd.CombinedOutput() if err != nil { br := color.Colorize("!r") rst := color.Colorize("|") fmt.Printf(color.Sprint(msg)+"\n%s\n%s%s%s\n\n", out, br, err, rst) } else { fmt.Printf(color.Sprint(msg)+"\n%s\n", out) } if !seq { quit <- 0 } } if *sequential { a(path, vcs, vcs_verb, *sequential) } else { count += 1 go a(path, vcs, vcs_verb, *sequential) } }
func main() { flag.Parse() data := Data{ "SVG -> PDF", time.Now().Format("_2 Jan 2006 15:04:05"), 20150803, "Строка кириллицей", true, } var err error // Load template from file template, err := template.ParseFiles(*inputFile) chk(err) // Store template to buffer buf := new(bytes.Buffer) err = template.Execute(buf, data) chk(err) // Convert via external application // Install before use // # apt-get install librsvg2-bin // or // # apt-get install inkscape var cmd *exec.Cmd if *converter == "inkscape" { fmt.Println("Generate via inkscape") cmd = exec.Command("inkscape", "--without-gui", "/dev/stdin", "--export-pdf=/dev/stdout") if *outputPng != "" { cmd.Args = append(cmd.Args, "--export-png", *outputPng) } } else { fmt.Println("Generate via rsvg-convert") cmd = exec.Command("rsvg-convert", "-f", "pdf") } cmd.Stdin = bytes.NewReader(buf.Bytes()) // Write pdf to file out, err := os.OpenFile(*outputFile, os.O_CREATE|os.O_WRONLY, 0666) chk(err) defer out.Close() cmd.Stdout = out timeStart := time.Now().UnixNano() err = cmd.Run() // Syncronous run external application chk(err) timeEnd := time.Now().UnixNano() fmt.Println("Conversion time (ms)", (timeEnd-timeStart)/1000000) // Open output file using the OS's default application open.Run(*outputFile) }
// Output runs p4 and captures stdout. func (p *Conn) Output(args []string) ([]byte, error) { b := p.opts.Binary if !strings.Contains(b, "/") { b, _ = exec.LookPath(b) } cmd := exec.Cmd{ Path: b, Args: []string{p.opts.Binary}, } if p.opts.Address != "" { cmd.Args = append(cmd.Args, "-p", p.opts.Address) } cmd.Args = append(cmd.Args, args...) log.Println("running", cmd.Args) return cmd.Output() }
func makeArgs(cmd *exec.Cmd, tagBuffer []*PackageInfo, count int) { cmd.Args = make([]string, 3+count) cmd.Args[0] = "--qf" cmd.Args[1] = rpmFormat cmd.Args[2] = "-q" for i := 0; i < count; i++ { cmd.Args[3+i] = tagBuffer[i].Name } }
func (mp *CustomMediaPlayer) PlayFile(file string) error { var command exec.Cmd command.Path = mp.Executable mp.Args[len(mp.Args)-1] = file command.Args = mp.Args command.Start() return nil }
func (r *RealCommandRunner) resolve(cmd *exec.Cmd) *exec.Cmd { originalPath := cmd.Path path, err := exec.LookPath(cmd.Path) if err != nil { path = cmd.Path } cmd.Path = path cmd.Args = append([]string{originalPath}, cmd.Args...) return cmd }
func generateTags(cmd *exec.Cmd) int { color.NoColor = (optionIndex(cmd.Args, "--nocolor") > 0) cmd.Args = append(cmd.Args, "--null") stdout, err := cmd.StdoutPipe() check(err) scanner := bufio.NewScanner(stdout) scanner.Split(scanLinesAndNulls) var ( line []byte curPath string groupIdxs []int ) aliasFile := NewAliasFile() defer aliasFile.WriteFile() aliasIndex := 1 err = cmd.Start() check(err) for scanner.Scan() { line = scanner.Bytes() if groupIdxs = lineNumberRe.FindSubmatchIndex(line); len(groupIdxs) > 0 { // Extract and tagged match aliasFile.WriteAlias(aliasIndex, curPath, string(line[groupIdxs[2]:groupIdxs[3]])) fmt.Printf("%s %s\n", tagPrefix(aliasIndex), string(line)) aliasIndex++ } else if groupIdxs = pathRe.FindSubmatchIndex(line); len(groupIdxs) > 0 { // Extract and print path curPath = string(line[groupIdxs[2]:groupIdxs[3]]) curPath, err = filepath.Abs(curPath) check(err) fmt.Println(string(line[:groupIdxs[1]])) } else { fmt.Println(string(line)) } } err = cmd.Wait() if err != nil { return 1 } return 0 }
func (vocabulary *Vocabulary) CreateCovarianceMatrix() { vocabulary.Covariances = new(CovarianceStruct) args := []string{"wnCovarianceSvsH.py", "--vocabulary"} args = append(args, vocabulary.Dictionary.VList...) args = append(args, "--pos") args = append(args, vocabulary.Dictionary.POSList...) cmd := new(exec.Cmd) cmd.Args = args // cmd.Path = "/home/lea/Code/Python/wnCovariance.py" cmd.Path = "/local/lea/thesis/python/wnCovarianceSvsH.py" out, err := cmd.Output() if err != nil { fmt.Println(err) } vocabulary.parse(string(out)) }
func main() { args := parseFlags(os.Args) if unset != "" { os.Unsetenv(unset) } cmd := exec.Cmd{Env: env} // Check for "-" as an argument, because it means the same as "-i" if flag.Arg(0) == "-" { cmd.Env = []string{} } for i, arg := range args { if strings.Index(arg, "=") > 0 { cmd.Env = append(cmd.Env, arg) } else if arg != "-" { if nullEol { fatal.Fatalln("cannot specify --null (-0) with command") } cmd.Path = arg cmd.Args = append(cmd.Args, args[i:]...) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := execvp(cmd); err != nil { fatal.Fatalln(err) } return } } eol := '\n' if nullEol { eol = '\x00' } for _, e := range env { fmt.Printf("%s%c", e, eol) } return }
func (e *execIn) goServe(lc *longCall, wsData *webserverData) { var cmd *exec.Cmd var err error cmd = exec.Command(e.Program) cmd.Args = e.Args if len(e.Input) != 0 { cmd.Stdin = strings.NewReader(e.Input) } var stdout bytes.Buffer cmd.Stdout = &stdout var stderr bytes.Buffer cmd.Stderr = &stderr if err = cmd.Start(); err != nil { lc.Response <- jsonResponseError("Unable to start: " + e.Program) return } var exitStatus int = 0 // assume success unless error if err = cmd.Wait(); err != nil { // exit status from http://stackoverflow.com/questions/10385551/get-exit-code-go if exiterr, ok := err.(*exec.ExitError); ok { if status, ok := exiterr.Sys().(syscall.WaitStatus); ok { exitStatus = status.ExitStatus() } else { lc.Response <- jsonResponseError("Unable to to determine exit status") return } } else { lc.Response <- jsonResponseError("Error with program: " + err.Error()) return } } lc.Response <- jsonResponse{ "state": "done", "exitStatus": exitStatus, "stdout": stdout.String(), "stderr": stderr.String(), } }
func main() { if len(os.Args) < 3 { fmt.Fprintln(os.Stderr, "Usage: aroc DIRECTORY|FILE COMMAND [ARGS…]") os.Exit(1) } ch := fsevents.WatchPaths([]string{os.Args[1]}) var cmd *exec.Cmd go func() { for _ = range ch { WAIT: // Wait 1 second in case multiple events occur in quick succession for { select { case <-ch: case <-time.After(1 * time.Second): break WAIT } } log.Println("Changes detected, restarting") cmd.Process.Signal(os.Interrupt) } }() for { cmd = exec.Command(os.Args[2]) cmd.Args = os.Args[2:] cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr err := cmd.Run() if err != nil { if _, ok := err.(*exec.ExitError); !ok { log.Fatal(err) } } } }
func cmd_to_channel(argv []string, name string, out chan string) { var cmd exec.Cmd cmd.Path = argv[0] cmd.Args = argv log.Printf("starting '%s'\n", name) stdout, err := cmd.StdoutPipe() if err != nil { log.Println(err) } stderr, err := cmd.StderrPipe() if err != nil { log.Println(err) } if err := cmd.Start(); err != nil { log.Fatal(err) } mux_readers_into_channel(stdout, stderr, out) cmd.Wait() log.Printf("'%s' finished\n", name) }
// Create and begin debugging a new process. First entry in // `cmd` is the program to run, and then rest are the arguments // to be supplied to that process. func Launch(cmd []string) (*Process, error) { var ( proc *exec.Cmd err error ) dbp := New(0) dbp.execPtraceFunc(func() { proc = exec.Command(cmd[0]) proc.Args = cmd proc.Stdout = os.Stdout proc.Stderr = os.Stderr proc.SysProcAttr = &syscall.SysProcAttr{Ptrace: true, Setpgid: true} err = proc.Start() }) if err != nil { return nil, err } dbp.Pid = proc.Process.Pid _, _, err = wait(proc.Process.Pid, proc.Process.Pid, 0) if err != nil { return nil, fmt.Errorf("waiting for target execve failed: %s", err) } return initializeDebugProcess(dbp, proc.Path, false) }
// Pipe mail to an external command (E.g. sendmail -t) func execSend(payload []byte, execCmd string) { sendmail := new(exec.Cmd) sendmail.Args = strings.Fields(execCmd) sendmail.Path = sendmail.Args[0] stdin, err := sendmail.StdinPipe() if err != nil { panic(err) } defer stdin.Close() sendmail.Stdout = os.Stdout sendmail.Stderr = os.Stderr err = sendmail.Start() if err != nil { panic(err) } stdin.Write(payload) stdin.Close() err = sendmail.Wait() if err != nil { //Warn.Printf("%s: %s", execCmd, err) panic(err) } }
It("sources them before executing", func() { Eventually(session).Should(gexec.Exit(0)) Eventually(session).Should(gbytes.Say("sourcing a")) Eventually(session).Should(gbytes.Say("sourcing b")) Eventually(session).Should(gbytes.Say("A=1")) Eventually(session).Should(gbytes.Say("B=1")) Eventually(session).Should(gbytes.Say("running app")) }) }) } Context("when a start command is given", func() { BeforeEach(func() { launcherCmd.Args = []string{ "launcher", appDir, "env; echo running app", `{ "start_command": "echo should not run this" }`, } }) ItExecutesTheCommandWithTheRightEnvironment() }) Context("when no start command is given", func() { BeforeEach(func() { launcherCmd.Args = []string{ "launcher", appDir, "", `{ "start_command": "env; echo running app" }`, }
func PrepareCmd(cmd *exec.Cmd, workingDirectory string, args []string, env []string, isVeryVerbose bool) error { cmd.Args = append(cmd.Args, args...) cmd.Dir = workingDirectory cmd.Env = CombineActualEnv(append(cmd.Env, env...), isVeryVerbose) return nil }
if err == nil { syscall.Kill(pid, syscall.SIGKILL) } Eventually(redisSession, "20s").Should(gexec.Exit(0)) }) Describe("common to plans", func() { BeforeEach(func() { config = loadRestoreConfig(sharedPlan) redisSession = startRedisSession(config, instanceID, sharedPlan) restoreCommand = buildRestoreCommand(sourceRdbPath, monitLogFile, instanceID, sharedPlan) }) It("exits with a non zero status if no arguments are provided", func() { restoreCommand.Args = []string{} session, err := gexec.Start(restoreCommand, GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) Eventually(session, "20s").Should(gexec.Exit(1)) Eventually(session.Err).Should(gbytes.Say("usage: restore <instance_id> <rdb_path>")) }) It("exits with a non zero status if the RDB file does not exist", func() { restoreCommand.Args = []string{restoreCommand.Args[0], instanceID, "bar"} session, err := gexec.Start(restoreCommand, GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) Eventually(session.Err).Should(gbytes.Say("RDB file not found")) Eventually(session, "20s").Should(gexec.Exit(1)) })
{Contents: "platform", Color: color.New(color.Bold)}, {Contents: "tags", Color: color.New(color.Bold)}, }, Data: []ui.TableRow{ {{Contents: "worker-1"}, {Contents: "1"}, {Contents: "platform1"}, {Contents: "tag1"}}, {{Contents: "worker-2"}, {Contents: "0"}, {Contents: "platform2"}, {Contents: "tag2, tag3"}}, {{Contents: "worker-3"}, {Contents: "10"}, {Contents: "platform3"}, {Contents: "none", Color: color.New(color.Faint)}}, }, })) Expect(flyCmd).To(HaveExited(0)) }) Context("when --details is given", func() { BeforeEach(func() { flyCmd.Args = append(flyCmd.Args, "--details") }) It("lists them to the user, ordered by name", func() { Expect(flyCmd).To(PrintTable(ui.Table{ Headers: ui.TableRow{ {Contents: "name", Color: color.New(color.Bold)}, {Contents: "containers", Color: color.New(color.Bold)}, {Contents: "platform", Color: color.New(color.Bold)}, {Contents: "tags", Color: color.New(color.Bold)}, {Contents: "garden address", Color: color.New(color.Bold)}, {Contents: "baggageclaim url", Color: color.New(color.Bold)}, {Contents: "resource types", Color: color.New(color.Bold)}, }, Data: []ui.TableRow{ {{Contents: "worker-1"}, {Contents: "1"}, {Contents: "platform1"}, {Contents: "tag1"}, {Contents: "2.2.3.4:7777"}, {Contents: "http://2.2.3.4:7788"}, {Contents: "resource-1, resource-2"}},
// collectGitInfo runs several git commands to compose a Git object. func collectGitInfo() *Git { gitCmds := map[string][]string{ "id": {"git", "rev-parse", "HEAD"}, "branch": {"git", "rev-parse", "--abbrev-ref", "HEAD"}, "aname": {"git", "log", "-1", "--pretty=%aN"}, "aemail": {"git", "log", "-1", "--pretty=%aE"}, "cname": {"git", "log", "-1", "--pretty=%cN"}, "cemail": {"git", "log", "-1", "--pretty=%cE"}, "message": {"git", "log", "-1", "--pretty=%s"}, "remotes": {"git", "remote", "-v"}, } results := map[string]string{} remotes := map[string]Remote{} gitPath, err := exec.LookPath("git") if err != nil { log.Fatal(err) } for key, args := range gitCmds { cmd := exec.Cmd{} cmd.Path = gitPath cmd.Args = args cmd.Stderr = os.Stderr ret, err := cmd.Output() if err != nil { log.Fatal(err) } s := string(ret) s = strings.TrimRight(s, "\n") results[key] = s } for _, line := range strings.Split(results["remotes"], "\n") { matches := remotesRE.FindAllStringSubmatch(line, -1) if len(matches) != 1 { continue } if len(matches[0]) != 3 { continue } name := matches[0][1] url := matches[0][2] r := Remote{ Name: name, Url: url, } remotes[name] = r } h := Head{} h.Id = results["id"] h.AuthorName = results["aname"] h.AuthorEmail = results["aemail"] h.CommitterName = results["cname"] h.CommitterEmail = results["cemail"] h.Message = results["message"] g := Git{} g.Head = h g.Branch = results["branch"] for _, r := range remotes { g.Remotes = append(g.Remotes, &r) } return &g }
err := json.Unmarshal(vcapApplicationBytes, &vcapApplication) Expect(err).NotTo(HaveOccurred()) Expect(vcapApplication["host"]).To(Equal("0.0.0.0")) Expect(vcapApplication["port"]).To(Equal(float64(8080))) Expect(vcapApplication["instance_index"]).To(Equal(float64(123))) Expect(vcapApplication["instance_id"]).To(Equal("some-instance-guid")) Expect(vcapApplication["foo"]).To(Equal(float64(1))) }) } Context("when a start command is given", func() { BeforeEach(func() { launcherCmd.Args = []string{ "launcher", appDir, "env; echo running app", `{ "cmd": ["echo should not run this"] }`, } }) ItExecutesTheCommandWithTheRightEnvironment() }) Context("when a start command is given with a workdir", func() { BeforeEach(func() { workdir = "/bin" launcherCmd.Args = []string{ "launcher", appDir, "env; echo running app", fmt.Sprintf(`{ "cmd" : ["echo should not run this"],
// Info runs several git commands to compose a Git object. func Info() *Git { gitCmds := map[string][]string{ "id": {"git", "rev-parse", "HEAD"}, "branch": {"git", "rev-parse", "--abbrev-ref", "HEAD"}, "aname": {"git", "log", "-1", "--pretty=%aN"}, "aemail": {"git", "log", "-1", "--pretty=%aE"}, "cname": {"git", "log", "-1", "--pretty=%cN"}, "cemail": {"git", "log", "-1", "--pretty=%cE"}, "message": {"git", "log", "-1", "--pretty=%s"}, "remotes": {"git", "remote", "-v"}, } results := map[string]string{} remotes := map[string]Remote{} gitPath, err := exec.LookPath("git") if err != nil { log.Fatal(err) } for key, args := range gitCmds { if key == "branch" { if envBranch := os.Getenv("GIT_BRANCH"); envBranch != "" { results[key] = envBranch continue } } cmd := exec.Cmd{} cmd.Path = gitPath cmd.Args = args cmd.Stderr = os.Stderr ret, err := cmd.Output() if err != nil { log.Fatal(err) } s := string(ret) s = strings.TrimRight(s, "\n") results[key] = s } for _, line := range strings.Split(results["remotes"], "\n") { matches := remotesRE.FindAllStringSubmatch(line, -1) if len(matches) != 1 { continue } if len(matches[0]) != 3 { continue } name := matches[0][1] url := matches[0][2] r := Remote{ Name: name, URL: url, } remotes[name] = r } h := Head{ ID: results["id"], AuthorName: results["aname"], AuthorEmail: results["aemail"], CommitterName: results["cname"], CommitterEmail: results["cemail"], Message: results["message"], } g := &Git{ Head: h, Branch: results["branch"], } for _, r := range remotes { g.Remotes = append(g.Remotes, &r) } return g }
Expect(os.RemoveAll(cniConfigDir)).To(Succeed()) Expect(os.RemoveAll(fakeLogDir)).To(Succeed()) Expect(fakeProcess.Kill()).To(Succeed()) }) Describe("CNI plugin lifecycle events", func() { var upCommand, downCommand *exec.Cmd BeforeEach(func() { upCommand = exec.Command(pathToAdapter) upCommand.Env = []string{"FAKE_LOG_DIR=" + fakeLogDir} upCommand.Stdin = strings.NewReader(fmt.Sprintf(`{ "pid": %d }`, fakePid)) upCommand.Args = []string{ pathToAdapter, "--configFile", fakeConfigFilePath, "--action", "up", "--handle", "some-container-handle", "--network", "garden-network-spec", } downCommand = exec.Command(pathToAdapter) downCommand.Env = []string{"FAKE_LOG_DIR=" + fakeLogDir} downCommand.Stdin = strings.NewReader(`{}`) downCommand.Args = []string{ pathToAdapter, "--action", "down", "--handle", "some-container-handle", "--configFile", fakeConfigFilePath, "--network", "garden-network-spec", } })