From 71dfc5a10e9afa04e71111424d0fa11bdf7e9fb8 Mon Sep 17 00:00:00 2001 From: koki-develop Date: Fri, 11 Oct 2024 11:11:06 +0900 Subject: [PATCH] --list-themes output now has color disabled when redirecting --- cmd/root.go | 5 +++-- internal/gat/gat.go | 52 +++++++++++++++++++++++++-------------------- 2 files changed, 32 insertions(+), 25 deletions(-) diff --git a/cmd/root.go b/cmd/root.go index 4ffc47d..2fb10a2 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -14,17 +14,18 @@ var rootCmd = &cobra.Command{ Short: "cat alternative written in Go", Long: "cat alternative written in Go.", RunE: func(cmd *cobra.Command, args []string) error { + ist := term.IsTerminal(int(os.Stdout.Fd())) + switch { case flagListLangs: return gat.PrintLanguages(os.Stdout) case flagListFormats: return gat.PrintFormats(os.Stdout) case flagListThemes: - return gat.PrintThemes(os.Stdout) + return gat.PrintThemes(os.Stdout, ist) } if strings.HasPrefix(flagFormat, "terminal") { - ist := term.IsTerminal(int(os.Stdout.Fd())) if !ist { if !flagForceColor { flagTheme = "noop" diff --git a/internal/gat/gat.go b/internal/gat/gat.go index 60bf7ad..e58e23a 100644 --- a/internal/gat/gat.go +++ b/internal/gat/gat.go @@ -287,8 +287,9 @@ func PrintFormats(w io.Writer) error { return tw.Flush() } -func PrintThemes(w io.Writer) error { - src := `package main +func PrintThemes(w io.Writer, withColor bool) error { + if withColor { + src := `package main import "fmt" @@ -296,33 +297,38 @@ func main() { fmt.Println("hello world") }` - for _, t := range styles.List() { - fmt.Fprintf(w, "\x1b[1m%s\x1b[0m\n\n", t) + for _, t := range styles.List() { + fmt.Fprintf(w, "\x1b[1m%s\x1b[0m\n\n", t) - g, err := New(&Config{ - Language: "go", - Theme: t, - Format: "terminal256", - }) - if err != nil { - return err - } + g, err := New(&Config{ + Language: "go", + Theme: t, + Format: "terminal256", + }) + if err != nil { + return err + } - buf := new(bytes.Buffer) - if err := g.Print(buf, strings.NewReader(src)); err != nil { - return err - } + buf := new(bytes.Buffer) + if err := g.Print(buf, strings.NewReader(src)); err != nil { + return err + } - // indent source - sc := bufio.NewScanner(buf) - for sc.Scan() { - if _, err := fmt.Fprintf(w, "\t%s\n", sc.Text()); err != nil { + // indent source + sc := bufio.NewScanner(buf) + for sc.Scan() { + if _, err := fmt.Fprintf(w, "\t%s\n", sc.Text()); err != nil { + return err + } + } + + if _, err := fmt.Fprintln(w); err != nil { return err } } - - if _, err := fmt.Fprintln(w); err != nil { - return err + } else { + for _, t := range styles.List() { + fmt.Fprintln(w, t) } }