Skip to content

Commit e0819ed

Browse files
committedOct 16, 2018
Refactor ExecCommand to cache stdout/stderr
This commits doesn't change the functionality of ExecCommand EXCEPT for programs that show progress bars or similar. For this kind of utilities, please use Stream "type"
1 parent f9d69df commit e0819ed

File tree

1 file changed

+17
-7
lines changed

1 file changed

+17
-7
lines changed
 

‎utils/utils.go

+17-7
Original file line numberDiff line numberDiff line change
@@ -281,27 +281,28 @@ func PrintableCommand(parts []string) string {
281281

282282
const (
283283
Ignore = 0 // Redirect to null
284-
Show = 1 // Show on stdout/stderr as normal
285-
ShowIfVerbose = 2 // Show if verbose is set, Ignore otherwise
286-
Capture = 3 // Capture into buffer
284+
Show = 1 // Capture and print the stream
285+
ShowIfVerbose = 2 // Capture and print the stream only if verbose
286+
Capture = 3 // Capture into buffer and don't print
287+
Stream = 4 // Stream data as it comes in, no capture
287288
)
288289

289290
func ExecCommand(ctx *types.Context, command *exec.Cmd, stdout int, stderr int) ([]byte, []byte, error) {
290291
if ctx.Verbose {
291292
ctx.GetLogger().UnformattedFprintln(os.Stdout, PrintableCommand(command.Args))
292293
}
293294

294-
if stdout == Capture {
295+
if stdout != Stream {
295296
buffer := &bytes.Buffer{}
296297
command.Stdout = buffer
297-
} else if stdout == Show || stdout == ShowIfVerbose && ctx.Verbose {
298+
} else {
298299
command.Stdout = os.Stdout
299300
}
300301

301-
if stderr == Capture {
302+
if stderr != Stream {
302303
buffer := &bytes.Buffer{}
303304
command.Stderr = buffer
304-
} else if stderr == Show || stderr == ShowIfVerbose && ctx.Verbose {
305+
} else {
305306
command.Stderr = os.Stderr
306307
}
307308

@@ -313,13 +314,22 @@ func ExecCommand(ctx *types.Context, command *exec.Cmd, stdout int, stderr int)
313314
err = command.Wait()
314315

315316
var outbytes, errbytes []byte
317+
// this operation is a no-op in case of streaming
316318
if buf, ok := command.Stdout.(*bytes.Buffer); ok {
317319
outbytes = buf.Bytes()
318320
}
319321
if buf, ok := command.Stderr.(*bytes.Buffer); ok {
320322
errbytes = buf.Bytes()
321323
}
322324

325+
if stdout == Show || (stdout == ShowIfVerbose && ctx.Verbose) {
326+
ctx.GetLogger().UnformattedWrite(os.Stdout, outbytes)
327+
}
328+
329+
if stderr == Show || (stderr == ShowIfVerbose && ctx.Verbose) {
330+
ctx.GetLogger().UnformattedWrite(os.Stderr, errbytes)
331+
}
332+
323333
return outbytes, errbytes, i18n.WrapError(err)
324334
}
325335

0 commit comments

Comments
 (0)