diff options
author | Andrei Miulescu <lusu777@gmail.com> | 2018-08-12 19:31:27 +1000 |
---|---|---|
committer | Andrei Miulescu <lusu777@gmail.com> | 2018-08-12 19:31:27 +1000 |
commit | dcd461d29f21a9626d5298a03283b6d8b46312c3 (patch) | |
tree | 42f43f27eb7403c60cc05805fc627debff76417b /pkg/commands/os.go | |
parent | 98c22a36fdaf8806f8fafe8f1e23e53f8e97658d (diff) |
Restrucure project in a way where it is more modular
Diffstat (limited to 'pkg/commands/os.go')
-rw-r--r-- | pkg/commands/os.go | 77 |
1 files changed, 77 insertions, 0 deletions
diff --git a/pkg/commands/os.go b/pkg/commands/os.go new file mode 100644 index 000000000..c36990aff --- /dev/null +++ b/pkg/commands/os.go @@ -0,0 +1,77 @@ +package commands + +import ( + "os/exec" + "runtime" + "strings" + + "github.com/Sirupsen/logrus" +) + +// Platform stores the os state +type platform struct { + os string + shell string + shellArg string + escapedQuote string +} + +// OSCommand holds all the os commands +type OSCommand struct { + Log *logrus.Logger + Platform platform +} + +// NewOSCommand os command runner +func NewOSCommand(log *logrus.Logger) (*OSCommand, error) { + osCommand := &OSCommand{ + Log: log, + Platform: getPlatform(), + } + return osCommand, nil +} + +// RunCommand wrapper around commands +func (c *OSCommand) RunCommand(command string) (string, error) { + c.Log.WithField("command", command).Info("RunCommand") + splitCmd := strings.Split(command, " ") + cmdOut, err := exec.Command(splitCmd[0], splitCmd[1:]...).CombinedOutput() + return sanitisedCommandOutput(cmdOut, err) +} + +// RunDirectCommand wrapper around direct commands +func (c *OSCommand) RunDirectCommand(command string) (string, error) { + c.Log.WithField("command", command).Info("RunDirectCommand") + + cmdOut, err := exec. + Command(c.Platform.shell, c.Platform.shellArg, command). + CombinedOutput() + return sanitisedCommandOutput(cmdOut, err) +} + +func sanitisedCommandOutput(output []byte, err error) (string, error) { + outputString := string(output) + if outputString == "" && err != nil { + return err.Error(), err + } + return outputString, err +} + +func getPlatform() platform { + switch runtime.GOOS { + case "windows": + return platform{ + os: "windows", + shell: "cmd", + shellArg: "/c", + escapedQuote: "\\\"", + } + default: + return platform{ + os: runtime.GOOS, + shell: "bash", + shellArg: "-c", + escapedQuote: "\"", + } + } +} |