commit 825b5dc807ddda56605800ee8f89852ced5b1307 Author: Foil-hat-guy Date: Tue Apr 15 00:10:39 2025 +0300 First commit. diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..193b419 --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module code.foilhatguy.casa/ui + +go 1.19 + +require github.com/spf13/pflag v1.0.6 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..7cf1763 --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= +github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= diff --git a/ui.go b/ui.go new file mode 100644 index 0000000..ced148d --- /dev/null +++ b/ui.go @@ -0,0 +1,58 @@ +// This package provides --quiet and --verbose flags for cli and corresponding output print functions PrintOut and PrintVerbose. + +package ui + +import ( + "fmt" + "io" + "os" + + "github.com/spf13/pflag" +) + +var stdOutput io.Writer +var verboseOutput io.Writer + +func init() { + outputFlagSet := pflag.NewFlagSet("output", pflag.ContinueOnError) + outputFlagSet.ParseErrorsWhitelist.UnknownFlags = true + outputFlagSet.SetOutput(nil) + + isVerbose := outputFlagSet.BoolP("verbose", "V", false, "If set adds additional details to output.") + isQuiet := outputFlagSet.BoolP("quiet", "q", false, "If set makes no output at all.") + + err := outputFlagSet.Parse(os.Args) + if err != nil { + fmt.Println(err) + os.Exit(1) + } + + SetupOutputMode(*isQuiet, *isVerbose) +} + +func SetupOutputMode(isQuiet bool, isVerbose bool) { + if isQuiet { + stdOutput = io.Discard + verboseOutput = io.Discard + return + } + + if isVerbose { + stdOutput = os.Stdout + verboseOutput = os.Stdout + return + } + + stdOutput = os.Stdout + verboseOutput = io.Discard +} + +func PrintOut(a ...any) (n int, err error) { + n, err = fmt.Fprintln(stdOutput, a...) + return +} + +func PrintVerbose(a ...any) (n int, err error) { + n, err = fmt.Fprintln(verboseOutput, a...) + return +}