xmnt/util/command.go

40 lines
845 B
Go
Raw Normal View History

2022-10-07 02:19:04 +09:00
package util
import (
"fmt"
"io"
"os"
"os/exec"
"github.com/go-errors/errors"
"gensokyo.cafe/xmnt/msg"
)
func RunCommand(cmd string, input io.Reader, args ...string) ([]byte, error) {
command := exec.Command(cmd, args...)
if input != nil {
command.Stdin = input
} else {
command.Stdin = os.Stdin
}
command.Stderr = os.Stderr
byt, err := command.Output()
if err != nil {
if e, ok := err.(*exec.ExitError); ok {
return nil, errors.New(
fmt.Sprintf("command %q %q failed with exit status %d", cmd, args, e.ExitCode()),
)
}
return nil, errors.New(err)
}
return byt, nil
}
func RunPrivilegedCommand(cmd string, input io.Reader, args ...string) ([]byte, error) {
realArgs := append([]string{cmd}, args...)
msg.Infof("Running command with sudo: %q", realArgs)
return RunCommand("sudo", input, realArgs...)
}