Skip to content

Commit 20e762c

Browse files
cfergeaupraveenkumar
authored andcommitted
Issue #990: os: Factor common code in os.Run*
RunWithPrivilege and RunWithDefaultLocale are running the command in almost the same way, so we can move this code to a generic function which can manage their specifities (one needs to prepend 'sudo' to the command, the other one needs to make some changes to the environment) This is related to #990
1 parent 420825c commit 20e762c

File tree

1 file changed

+19
-18
lines changed

1 file changed

+19
-18
lines changed

pkg/os/exec.go

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -8,33 +8,34 @@ import (
88
"strings"
99
)
1010

11+
func run(command string, args []string, env map[string]string) (string, string, error) {
12+
cmd := exec.Command(command, args...) // #nosec G204
13+
if len(env) != 0 {
14+
cmd.Env = os.Environ()
15+
for key, value := range env {
16+
cmd.Env = ReplaceEnv(cmd.Env, key, value)
17+
}
18+
}
19+
stdOut := new(bytes.Buffer)
20+
stdErr := new(bytes.Buffer)
21+
cmd.Stdout = stdOut
22+
cmd.Stderr = stdErr
23+
logging.Debugf("Running %s %s", command, strings.Join(args, " "))
24+
err := cmd.Run()
25+
return stdOut.String(), stdErr.String(), err
26+
}
27+
1128
// RunWithPrivilege executes a command using sudo
1229
// provide a reason why root is needed as the first argument
1330
func RunWithPrivilege(reason string, cmdAndArgs ...string) (string, string, error) {
1431
sudo, err := exec.LookPath("sudo")
1532
if err != nil {
1633
return "", "", err
1734
}
18-
cmd := exec.Command(sudo, cmdAndArgs...) // #nosec G204
19-
stdOut := new(bytes.Buffer)
20-
stdErr := new(bytes.Buffer)
21-
cmd.Stdout = stdOut
22-
cmd.Stderr = stdErr
2335
logging.Infof("Will use root access: %s", reason)
24-
logging.Debugf("Running %s with sudo", strings.Join(cmdAndArgs, " "))
25-
err = cmd.Run()
26-
return stdOut.String(), stdErr.String(), err
36+
return run(sudo, cmdAndArgs, map[string]string{})
2737
}
2838

2939
func RunWithDefaultLocale(command string, args ...string) (string, string, error) {
30-
cmd := exec.Command(command, args...) // #nosec G204
31-
cmd.Env = ReplaceEnv(os.Environ(), "LC_ALL", "C")
32-
cmd.Env = ReplaceEnv(cmd.Env, "LANG", "C")
33-
stdOut := new(bytes.Buffer)
34-
stdErr := new(bytes.Buffer)
35-
cmd.Stdout = stdOut
36-
cmd.Stderr = stdErr
37-
logging.Debugf("Running %s %s", command, strings.Join(args, " "))
38-
err := cmd.Run()
39-
return stdOut.String(), stdErr.String(), err
40+
return run(command, args, map[string]string{"LC_ALL": "C", "LANG": "C"})
4041
}

0 commit comments

Comments
 (0)