Exec executes a system command and redirects the commands output to debug
(path string, args ...string)
| 105 | |
| 106 | // Exec executes a system command and redirects the commands output to debug |
| 107 | func Exec(path string, args ...string) error { |
| 108 | if cmd != nil { |
| 109 | return NewErrorf("Child process is aleady running (%s:%d)", cmd.Path, cmd.Process.Pid) |
| 110 | } |
| 111 | |
| 112 | cmd = exec.Command(path, args...) |
| 113 | defer func() { |
| 114 | cmd = nil |
| 115 | }() |
| 116 | |
| 117 | // parse stdout async |
| 118 | stdout, err := cmd.StdoutPipe() |
| 119 | if err != nil { |
| 120 | return err |
| 121 | } |
| 122 | |
| 123 | go func() { |
| 124 | scanner := bufio.NewScanner(stdout) |
| 125 | for scanner.Scan() { |
| 126 | Dprintf("%s: %s\n", cmd.Path, scanner.Text()) |
| 127 | } |
| 128 | }() |
| 129 | |
| 130 | // attach to stderr |
| 131 | stderr, err := cmd.StderrPipe() |
| 132 | if err != nil { |
| 133 | return err |
| 134 | } |
| 135 | |
| 136 | go func() { |
| 137 | scanner := bufio.NewScanner(stderr) |
| 138 | for scanner.Scan() { |
| 139 | Dprintf("%s: %s\n", cmd.Path, scanner.Text()) |
| 140 | } |
| 141 | }() |
| 142 | |
| 143 | // execute |
| 144 | Dprintf("exec: %s %s\n", path, strings.Join(args, " ")) |
| 145 | err = cmd.Start() |
| 146 | if err != nil { |
| 147 | return err |
| 148 | } |
| 149 | Dprintf("exec: started with PID: %d\n", cmd.Process.Pid) |
| 150 | |
| 151 | // wait for process to finish |
| 152 | err = cmd.Wait() |
| 153 | if err != nil { |
| 154 | return err |
| 155 | } |
| 156 | Dprintf("exec: finished\n") |
| 157 | cmd = nil |
| 158 | |
| 159 | return nil |
| 160 | } |
no test coverage detected