From 8a3cd12cadd10ea7c2eefa3a38015f6afb23c683 Mon Sep 17 00:00:00 2001 From: Chris Laprun Date: Wed, 9 Oct 2019 15:26:09 +0200 Subject: [PATCH] feat: intercept and output any error from kubectl calls MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Better error reporting, yay! 🎉 --- pkg/k8s/kubectl.go | 5 +++++ pkg/log/status.go | 39 +++++++++++++++++++++++++-------------- 2 files changed, 30 insertions(+), 14 deletions(-) diff --git a/pkg/k8s/kubectl.go b/pkg/k8s/kubectl.go index 178a006..312fb85 100644 --- a/pkg/k8s/kubectl.go +++ b/pkg/k8s/kubectl.go @@ -36,8 +36,13 @@ func Apply(path, namespace string) error { func runKubectl(args ...string) error { command := exec.Command(kubectl, args...) + interceptor := log.GetErrorInterceptor() + command.Stderr = interceptor err := command.Run() if err != nil { + if len(interceptor.ErrorMsg) > 0 { + return fmt.Errorf("%v: %s", err, interceptor.ErrorMsg) + } return err } return nil diff --git a/pkg/log/status.go b/pkg/log/status.go index 4beaa3f..63e7e25 100644 --- a/pkg/log/status.go +++ b/pkg/log/status.go @@ -40,6 +40,22 @@ import ( const suffixSpacing = " " const prefixSpacing = " " +var ( + stdErr = colorable.NewColorableStderr() + stdOut = colorable.NewColorableStdout() + errInterceptor = &ErrorInterceptor{stdErr: stdErr} +) + +type ErrorInterceptor struct { + stdErr io.Writer + ErrorMsg string +} + +func (l *ErrorInterceptor) Write(p []byte) (n int, err error) { + l.ErrorMsg = string(p) + return len(p), nil +} + // Status is used to track ongoing status in a CLI, with a nice loading spinner // when attached to a terminal type Status struct { @@ -55,6 +71,7 @@ func NewStatus(w io.Writer) *Status { spinner: spin, writer: w, } + s.MaybeWrapWriter(w) return s } @@ -238,24 +255,18 @@ func IsDebug() bool { return false } -// GetStdout gets the appropriate stdout from the OS. If it's Linux, it will use -// the go-colorable library in order to fix any and all color ASCII issues. -// TODO: Test needs to be added once we get Windows testing available on TravisCI / CI platform. +// GetStdout gets the appropriate stdout from the OS. func GetStdout() io.Writer { - if runtime.GOOS == "windows" { - return colorable.NewColorableStdout() - } - return os.Stdout + return stdOut } -// GetStderr gets the appropriate stderrfrom the OS. If it's Linux, it will use -// the go-colorable library in order to fix any and all color ASCII issues. -// TODO: Test needs to be added once we get Windows testing available on TravisCI / CI platform. +// GetStderr gets the appropriate stderr from the OS. func GetStderr() io.Writer { - if runtime.GOOS == "windows" { - return colorable.NewColorableStderr() - } - return os.Stderr + return stdErr +} + +func GetErrorInterceptor() *ErrorInterceptor { + return errInterceptor } // getErrString returns a certain string based upon the OS.