2 Copyright 2020 Huawei Technologies Co., Ltd.
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
8 http://www.apache.org/licenses/LICENSE-2.0
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
17 // runCommandWithShell executes the given command with "sh -c".
18 // It returns an error if the command outputs anything on the stderr.
31 //Command defines commands to be executed and captures std out and std error
38 func (cm Command) GetStdOutput() string {
39 if len(cm.StdOut) != 0 {
40 return strings.TrimRight(string(cm.StdOut), "\n")
45 //GetStdErr gets StdErr field
46 func (cm Command) GetStdErr() string {
47 if len(cm.StdErr) != 0 {
48 return strings.TrimRight(string(cm.StdErr), "\n")
53 //It helps in the commands where it takes some time for execution.
54 func (cm Command) ExecuteCmdShowOutput() error {
55 var stdoutBuf, stderrBuf bytes.Buffer
56 stdoutIn, _ := cm.Cmd.StdoutPipe()
57 stderrIn, _ := cm.Cmd.StderrPipe()
59 var errStdout, errStderr error
60 stdout := io.MultiWriter(os.Stdout, &stdoutBuf)
61 stderr := io.MultiWriter(os.Stderr, &stderrBuf)
64 return fmt.Errorf("failed to start '%s' because of error : %s", strings.Join(cm.Cmd.Args, " "), err.Error())
71 _, errStdout = io.Copy(stdout, stdoutIn)
75 _, errStderr = io.Copy(stderr, stderrIn)
80 return fmt.Errorf("failed to run '%s' because of error : %s", strings.Join(cm.Cmd.Args, " "), err.Error())
82 if errStdout != nil || errStderr != nil {
83 return fmt.Errorf("failed to capture stdout or stderr")
86 cm.StdOut, cm.StdErr = stdoutBuf.Bytes(), stderrBuf.Bytes()
90 func runCommandAtShell(command string) (string, error) {
91 cmd := &Command{Cmd: exec.Command("sh", "-c", command)}
92 err := cmd.ExecuteCmdShowOutput()
96 errout := cmd.GetStdErr()
98 return "", fmt.Errorf("%s", errout)
100 return cmd.GetStdOutput(), nil