use a red colored stderr writer for the cobra cmd errors

This commit is contained in:
Gani Georgiev
2023-12-03 13:44:30 +02:00
parent 070a1cd6d9
commit 5b94aced3a
3 changed files with 37 additions and 16 deletions
+29 -3
View File
@@ -1,12 +1,14 @@
package pocketbase
import (
"io"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"github.com/fatih/color"
"github.com/pocketbase/pocketbase/cmd"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/list"
@@ -98,6 +100,9 @@ func NewWithConfig(config Config) *PocketBase {
hideStartBanner: config.HideStartBanner,
}
// replace with a colored stderr writer
pb.RootCmd.SetErr(newErrWriter())
// parse base flags
// (errors are ignored, since the full flags parsing happens on Execute())
pb.eagerParseFlags(&config)
@@ -152,9 +157,8 @@ func (pb *PocketBase) Execute() error {
// execute the root command
go func() {
if err := pb.RootCmd.Execute(); err != nil {
pb.Logger().Error("rootCmd.Execute error", "error", err)
}
// leave to the commands to decide whether to print their error or not
pb.RootCmd.Execute()
done <- true
}()
@@ -246,3 +250,25 @@ func inspectRuntime() (baseDir string, withGoRun bool) {
}
return
}
// newErrWriter returns a red colored stderr writter.
func newErrWriter() *coloredWriter {
return &coloredWriter{
w: os.Stderr,
c: color.New(color.FgRed),
}
}
// coloredWriter is a small wrapper struct to construct a [color.Color] writter.
type coloredWriter struct {
w io.Writer
c *color.Color
}
// Write writes the p bytes using the colored writer.
func (colored *coloredWriter) Write(p []byte) (n int, err error) {
colored.c.SetWriter(colored.w)
defer colored.c.UnsetWriter(colored.w)
return colored.c.Print(string(p))
}