12 // WriteDemoConfig writes a toml file with the given values.
13 // It returns the RootDir the config.toml file is stored in,
14 // or an error if writing was impossible
15 func WriteDemoConfig(vals map[string]string) (string, error) {
16 cdir, err := ioutil.TempDir("", "test-cli")
21 for k, v := range vals {
22 data = data + fmt.Sprintf("%s = \"%s\"\n", k, v)
24 cfile := filepath.Join(cdir, "config.toml")
25 err = ioutil.WriteFile(cfile, []byte(data), 0666)
29 // RunWithArgs executes the given command with the specified command line args
30 // and environmental variables set. It returns any error returned from cmd.Execute()
31 func RunWithArgs(cmd Executable, args []string, env map[string]string) error {
33 oenv := map[string]string{}
34 // defer returns the environment back to normal
37 for k, v := range oenv {
42 // set the args and env how we want them
44 for k, v := range env {
45 // backup old value if there, to restore at end
46 oenv[k] = os.Getenv(k)
47 err := os.Setenv(k, v)
53 // and finally run the command
57 // RunCaptureWithArgs executes the given command with the specified command
58 // line args and environmental variables set. It returns string fields
59 // representing output written to stdout and stderr, additionally any error
60 // from cmd.Execute() is also returned
61 func RunCaptureWithArgs(cmd Executable, args []string, env map[string]string) (stdout, stderr string, err error) {
62 oldout, olderr := os.Stdout, os.Stderr // keep backup of the real stdout
63 rOut, wOut, _ := os.Pipe()
64 rErr, wErr, _ := os.Pipe()
65 os.Stdout, os.Stderr = wOut, wErr
67 os.Stdout, os.Stderr = oldout, olderr // restoring the real stdout
70 // copy the output in a separate goroutine so printing can't block indefinitely
71 copyStd := func(reader *os.File) *(chan string) {
72 stdC := make(chan string)
75 // io.Copy will end when we call reader.Close() below
84 // now run the command
85 err = RunWithArgs(cmd, args, env)
87 // and grab the stdout to return
92 return stdout, stderr, err