diff --git a/cmd/root.go b/cmd/root.go index 7c3947a8..e7fe016d 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -363,6 +363,7 @@ Environment: rootCmd.AddCommand(newRunCmd()) rootCmd.AddCommand(newReportCmd()) rootCmd.AddCommand(newConfigCmd()) + rootCmd.AddCommand(newThemeCmd()) rootCmd.AddCommand(newCleanCmd()) rootCmd.AddCommand(newCompletionCmd()) rootCmd.AddCommand(newKeysCmd()) diff --git a/cmd/theme.go b/cmd/theme.go new file mode 100644 index 00000000..d43d4060 --- /dev/null +++ b/cmd/theme.go @@ -0,0 +1,43 @@ +package cmd + +import ( + "encoding/json" + "fmt" + + "github.com/jongio/grut/internal/theme" + "github.com/spf13/cobra" +) + +type themeListFunc func() []string + +func newThemeCmd() *cobra.Command { + themeCmd := &cobra.Command{ + Use: "theme", + Short: "Inspect grut themes", + } + themeCmd.AddCommand(newThemeListCmd(theme.ListThemes)) + return themeCmd +} + +func newThemeListCmd(list themeListFunc) *cobra.Command { + var asJSON bool + + listCmd := &cobra.Command{ + Use: cmdList, + Short: "List available themes", + RunE: func(cmd *cobra.Command, args []string) error { + themes := list() + if asJSON { + enc := json.NewEncoder(cmd.OutOrStdout()) + enc.SetIndent("", " ") + return enc.Encode(themes) + } + for _, name := range themes { + _, _ = fmt.Fprintln(cmd.OutOrStdout(), name) + } + return nil + }, + } + listCmd.Flags().BoolVar(&asJSON, "json", false, "Print theme names as JSON") + return listCmd +} diff --git a/cmd/theme_test.go b/cmd/theme_test.go new file mode 100644 index 00000000..91fef375 --- /dev/null +++ b/cmd/theme_test.go @@ -0,0 +1,45 @@ +package cmd + +import ( + "bytes" + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestThemeListCommandPrintsNames(t *testing.T) { + cmd := newThemeListCmd(func() []string { return []string{"catppuccin", "custom"} }) + var out bytes.Buffer + cmd.SetOut(&out) + + err := cmd.Execute() + + require.NoError(t, err) + assert.Equal(t, "catppuccin\ncustom\n", out.String()) +} + +func TestThemeListCommandPrintsJSON(t *testing.T) { + cmd := newThemeListCmd(func() []string { return []string{"default", "gruvbox"} }) + cmd.SetArgs([]string{"--json"}) + var out bytes.Buffer + cmd.SetOut(&out) + + err := cmd.Execute() + + require.NoError(t, err) + var names []string + require.NoError(t, json.Unmarshal(out.Bytes(), &names)) + assert.Equal(t, []string{"default", "gruvbox"}, names) +} + +func TestRootRegistersThemeListCommand(t *testing.T) { + root, cleanup := newRootCommand() + defer cleanup() + + themeCmd, _, err := root.Find([]string{"theme", "list"}) + require.NoError(t, err) + require.NotNil(t, themeCmd) + assert.Equal(t, cmdList, themeCmd.Name()) +}