Skip to content

Commit

Permalink
Update color options to enum (#45)
Browse files Browse the repository at this point in the history
  • Loading branch information
svix-frank committed Jul 6, 2021
1 parent a9e01ba commit 7f949ae
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 8 deletions.
22 changes: 18 additions & 4 deletions cmd/flags.go
Original file line number Diff line number Diff line change
@@ -1,19 +1,33 @@
package cmd

import (
"os"

"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/svix/svix-cli/pretty"
"github.com/svix/svix-cli/utils"
svix "github.com/svix/svix-libs/go"
)

func getPrinterOptions(cmd *cobra.Command) *pretty.PrinterOptions {
colorFlag := viper.GetBool("color")
if !colorFlag {
return nil
colorFlag := viper.GetString("color")
color := false
switch colorFlag {
case "always":
color = true
case "never":
color = false
default:
isTTY, _, err := utils.IsTTY(os.Stdout)
if err == nil {
// just defaults to false if an error occurs
color = isTTY
}
}

return &pretty.PrinterOptions{
Color: true,
Color: color,
}
}

Expand Down
10 changes: 6 additions & 4 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cmd

import (
"flag"
"fmt"
"net/url"
"os"
Expand All @@ -10,7 +11,7 @@ import (
"github.com/spf13/viper"

"github.com/svix/svix-cli/config"
"github.com/svix/svix-cli/utils"
"github.com/svix/svix-cli/flags"
"github.com/svix/svix-cli/version"
svix "github.com/svix/svix-libs/go"
)
Expand All @@ -36,9 +37,10 @@ func init() {
rootCmd.Flags().BoolP("version", "v", false, "Get the version of the Svix CLI") // overrides default msg

// Global Flags
isTTY, _, err := utils.IsTTY(os.Stdout)
cobra.CheckErr(err)
rootCmd.PersistentFlags().Bool("color", isTTY, "colorize output json") // on by default if TTY, off if not
color := "auto"
colorFlag := flags.NewEnum(&color, "auto", "always", "never")
flag.Var(colorFlag, "color", "auto|always|never")
rootCmd.PersistentFlags().AddGoFlag(flag.Lookup("color"))
cobra.CheckErr(viper.BindPFlag("color", rootCmd.PersistentFlags().Lookup("color"))) // allow color flag to be set in config

// Register Commands
Expand Down
27 changes: 27 additions & 0 deletions flags/enum.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package flags

import "fmt"

type enum struct {
target *string
options []string
}

func NewEnum(target *string, options ...string) *enum {
return &enum{target: target, options: options}
}

func (f *enum) String() string {
return *f.target
}

func (f *enum) Set(value string) error {
for _, v := range f.options {
if v == value {
*f.target = value
return nil
}
}

return fmt.Errorf("expected one of the following %q", f.options)
}

0 comments on commit 7f949ae

Please sign in to comment.