Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

enable color by default if stdout is a TTY #9

Merged
merged 3 commits into from
Jun 2, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/spf13/viper"

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

// Global Flags
rootCmd.PersistentFlags().Bool("color", false, "colorize output json")
isTTY, _, err := utils.IsTTY(os.Stdout)
fmt.Fprintln(os.Stderr, isTTY)
cobra.CheckErr(err)
rootCmd.PersistentFlags().Bool("color", isTTY, "colorize output json") // on by default if TTY, off if not
cobra.CheckErr(viper.BindPFlag("color", rootCmd.PersistentFlags().Lookup("color"))) // allow color flag to be set in config

// Register Commands
Expand Down
20 changes: 13 additions & 7 deletions utils/pipe.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,11 @@ import (
)

func IsPipeWithData(f *os.File) (bool, error) {
info, err := f.Stat()
isTTY, hasData, err := IsTTY(f)
if err != nil {
return false, err
}

if info.Mode()&os.ModeCharDevice != 0 || // stdin is not a Unix character device
info.Size() <= 0 { // stdin has no bytes
return false, nil
}
return true, nil
return !isTTY && hasData, nil
}

func ReadPipe() ([]byte, error) {
Expand All @@ -33,3 +28,14 @@ func ReadPipe() ([]byte, error) {
}
return []byte{}, nil
}

func IsTTY(f *os.File) (isTTY bool, hasBytes bool, err error) {
info, err := f.Stat()
if err != nil {
return false, false, err
}

isTTY = info.Mode()&os.ModeCharDevice != 0
hasBytes = info.Size() > 0
return isTTY, hasBytes, nil
}