A helper to ignore os.Exit(1) errors when running a cobra Command
(root *cobra.Command, args ...string)
| 149 | |
| 150 | // A helper to ignore os.Exit(1) errors when running a cobra Command |
| 151 | func executeCommandC(root *cobra.Command, args ...string) (stdout string, output string, err error) { |
| 152 | buf := new(bytes.Buffer) |
| 153 | root.SetOutput(buf) |
| 154 | root.SetArgs(args) |
| 155 | |
| 156 | // see https://stackoverflow.com/questions/10473800/in-go-how-do-i-capture-stdout-of-a-function-into-a-string |
| 157 | old := os.Stdout // keep backup of the real stdout |
| 158 | r, w, _ := os.Pipe() |
| 159 | os.Stdout = w |
| 160 | |
| 161 | _, err = root.ExecuteC() |
| 162 | |
| 163 | outC := make(chan string) |
| 164 | // copy the output in a separate goroutine so printing can't block indefinitely |
| 165 | go func() { |
| 166 | var buf bytes.Buffer |
| 167 | if _, err := io.Copy(&buf, r); err != nil { |
| 168 | panic(err) |
| 169 | } |
| 170 | outC <- buf.String() |
| 171 | }() |
| 172 | |
| 173 | // back to normal state |
| 174 | if err := w.Close(); err != nil { |
| 175 | tInfo(err) |
| 176 | } |
| 177 | os.Stdout = old // restoring the real stdout |
| 178 | stdout = <-outC |
| 179 | |
| 180 | return stdout, buf.String(), err |
| 181 | } |
| 182 | |
| 183 | func printFlagsTable(flagsMap map[string]string, c string) string { |
| 184 | buff := new(bytes.Buffer) |
no test coverage detected