You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
smug/commander.go

58 lines
1.0 KiB
Go

3 years ago
package main
import (
"fmt"
"log"
3 years ago
"os/exec"
"strings"
)
type ShellError struct {
Command string
Err error
}
func (e *ShellError) Error() string {
return fmt.Sprintf("Cannot run %q. Error %v", e.Command, e.Err)
}
3 years ago
type Commander interface {
Exec(cmd *exec.Cmd) (string, error)
ExecSilently(cmd *exec.Cmd) error
}
type DefaultCommander struct {
logger *log.Logger
3 years ago
}
func (c DefaultCommander) Exec(cmd *exec.Cmd) (string, error) {
if c.logger != nil {
c.logger.Println(strings.Join(cmd.Args, " "))
}
3 years ago
output, err := cmd.CombinedOutput()
3 years ago
if err != nil {
if c.logger != nil {
c.logger.Println(err, string(output))
}
3 years ago
return "", &ShellError{strings.Join(cmd.Args, " "), err}
3 years ago
}
return strings.TrimSuffix(string(output), "\n"), nil
}
func (c DefaultCommander) ExecSilently(cmd *exec.Cmd) error {
if c.logger != nil {
c.logger.Println(strings.Join(cmd.Args, " "))
}
3 years ago
err := cmd.Run()
if err != nil {
if c.logger != nil {
c.logger.Println(err)
}
3 years ago
return &ShellError{strings.Join(cmd.Args, " "), err}
}
return nil
3 years ago
}