-
Notifications
You must be signed in to change notification settings - Fork 47
/
output.go
74 lines (65 loc) · 1.97 KB
/
output.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
Copyright (c) 2021 - Present. Blend Labs, Inc. All rights reserved
Use of this source code is governed by a MIT license that can be found in the LICENSE file.
*/
package sh
import (
"bytes"
"context"
"os"
"os/exec"
)
// OutputParsed parses a command as binary and arguments.
// It resolves the command name in your $PATH list for you.
// It captures combined output and returns it as bytes.
func OutputParsed(statement string) ([]byte, error) {
cmd, err := CmdParsed(statement)
if err != nil {
return nil, err
}
cmd.Env = os.Environ()
return OutputCmd(cmd)
}
// OutputParsedContext parses a command as binary and arguments with a given context.
// It resolves the command name in your $PATH list for you.
// It captures combined output and returns it as bytes.
func OutputParsedContext(ctx context.Context, statement string) ([]byte, error) {
cmd, err := CmdParsedContext(ctx, statement)
if err != nil {
return nil, err
}
cmd.Env = os.Environ()
return OutputCmd(cmd)
}
// Output runs a command with a given list of arguments.
// It resolves the command name in your $PATH list for you.
// It captures combined output and returns it as bytes.
func Output(command string, args ...string) ([]byte, error) {
cmd, err := Cmd(command, args...)
if err != nil {
return nil, err
}
cmd.Env = os.Environ()
return OutputCmd(cmd)
}
// OutputContext runs a command with a given list of arguments.
// It resolves the command name in your $PATH list for you.
// It captures combined output and returns it as bytes.
func OutputContext(ctx context.Context, command string, args ...string) ([]byte, error) {
cmd, err := Cmd(command, args...)
if err != nil {
return nil, err
}
cmd.Env = os.Environ()
return OutputCmd(cmd)
}
// OutputCmd captures the output of a given command.
func OutputCmd(cmd *exec.Cmd) ([]byte, error) {
output := new(bytes.Buffer)
cmd.Stdout = output
cmd.Stderr = output
if err := cmd.Run(); err != nil {
return output.Bytes(), err
}
return output.Bytes(), nil
}