mirror of
https://github.com/cupcakearmy/autorestic.git
synced 2026-04-02 20:05:23 +00:00
stream the output (#186)
This commit is contained in:
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
"github.com/cupcakearmy/autorestic/internal/colors"
|
||||
"github.com/cupcakearmy/autorestic/internal/flags"
|
||||
"github.com/fatih/color"
|
||||
)
|
||||
|
||||
var RESTIC_BIN string
|
||||
@@ -26,6 +27,18 @@ type ExecuteOptions struct {
|
||||
Command string
|
||||
Envs map[string]string
|
||||
Dir string
|
||||
Silent bool
|
||||
}
|
||||
|
||||
type ColoredWriter struct {
|
||||
target io.Writer
|
||||
color *color.Color
|
||||
}
|
||||
|
||||
func (w ColoredWriter) Write(p []byte) (n int, err error) {
|
||||
colored := []byte(w.color.Sprint(string(p)))
|
||||
w.target.Write(colored)
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func ExecuteCommand(options ExecuteOptions, args ...string) (int, string, error) {
|
||||
@@ -43,15 +56,24 @@ func ExecuteCommand(options ExecuteOptions, args ...string) (int, string, error)
|
||||
|
||||
var out bytes.Buffer
|
||||
var error bytes.Buffer
|
||||
cmd.Stdout = &out
|
||||
if flags.VERBOSE && !options.Silent {
|
||||
var colored ColoredWriter = ColoredWriter{
|
||||
target: os.Stdout,
|
||||
color: colors.Faint,
|
||||
}
|
||||
mw := io.MultiWriter(colored, &out)
|
||||
cmd.Stdout = mw
|
||||
} else {
|
||||
cmd.Stdout = &out
|
||||
}
|
||||
cmd.Stderr = &error
|
||||
err := cmd.Run()
|
||||
if err != nil {
|
||||
code := -1
|
||||
if exitError, ok := err.(*exec.ExitError); ok {
|
||||
return exitError.ExitCode(), error.String(), err
|
||||
} else {
|
||||
return -1, error.String(), err
|
||||
code = exitError.ExitCode()
|
||||
}
|
||||
return code, error.String(), err
|
||||
}
|
||||
return 0, out.String(), nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user