/
command_runner.go
56 lines (49 loc) · 1.59 KB
/
command_runner.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
package cmdrunner
import (
"strings"
"github.com/jenkins-x/jx-helpers/v3/pkg/termcolor"
"github.com/jenkins-x/jx-logging/v3/pkg/log"
)
// CommandRunner represents a command runner so that it can be stubbed out for testing
type CommandRunner func(*Command) (string, error)
// DefaultCommandRunner default runner if none is set
func DefaultCommandRunner(c *Command) (string, error) {
if c.Dir == "" {
log.Logger().Infof("about to run: %s", termcolor.ColorInfo(CLI(c)))
} else {
log.Logger().Infof("about to run: %s in dir %s", termcolor.ColorInfo(CLI(c)), termcolor.ColorInfo(c.Dir))
}
result, err := c.RunWithoutRetry()
if result != "" {
log.Logger().Infof(termcolor.ColorStatus(result))
}
return result, err
}
// QuietCommandRunner uses debug level logging to output commands executed and results
func QuietCommandRunner(c *Command) (string, error) {
if c.Dir == "" {
log.Logger().Debugf("about to run: %s", termcolor.ColorInfo(CLI(c)))
} else {
log.Logger().Debugf("about to run: %s in dir %s", termcolor.ColorInfo(CLI(c)), termcolor.ColorInfo(c.Dir))
}
result, err := c.RunWithoutRetry()
if result != "" {
log.Logger().Debugf(termcolor.ColorStatus(result))
}
return result, err
}
// DryRunCommandRunner output the commands to be run
func DryRunCommandRunner(c *Command) (string, error) {
log.Logger().Infof(CLI(c))
return "", nil
}
// CLI returns the CLI string without the dir or env vars
func CLI(c *Command) string {
var builder strings.Builder
builder.WriteString(c.Name)
for _, arg := range c.Args {
builder.WriteString(" ")
builder.WriteString(arg)
}
return builder.String()
}