diff --git a/cmd/cmd.go b/cmd/cmd.go index 0a95a00..75faf00 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -13,7 +13,6 @@ import ( "github.com/clevyr/yampl/internal/colorize" "github.com/clevyr/yampl/internal/config" - "github.com/clevyr/yampl/internal/config/flags" "github.com/clevyr/yampl/internal/util" "github.com/clevyr/yampl/internal/visitor" "github.com/rs/zerolog" @@ -36,57 +35,13 @@ func NewCommand() *cobra.Command { DisableAutoGenTag: true, ValidArgsFunction: validArgs, Version: buildVersion(version), - PreRunE: preRun, RunE: run, } conf := config.New() - - registerCompletionFlag(cmd) - registerLogFlags(cmd) - registerValuesFlag(cmd, conf) - - cmd.Flags().BoolVarP(&conf.Inplace, "inplace", "i", conf.Inplace, "Edit files in place") - if err := cmd.RegisterFlagCompletionFunc("inplace", util.BoolCompletion); err != nil { - panic(err) - } - - cmd.Flags().BoolVarP(&conf.Recursive, "recursive", "r", conf.Recursive, "Recursively update yaml files in the given directory") - if err := cmd.RegisterFlagCompletionFunc("recursive", util.BoolCompletion); err != nil { - panic(err) - } - - cmd.Flags().StringVarP(&conf.Prefix, "prefix", "p", conf.Prefix, "Template comments must begin with this prefix. The beginning '#' is implied.") - if err := cmd.RegisterFlagCompletionFunc("prefix", cobra.NoFileCompletions); err != nil { - panic(err) - } - - cmd.Flags().StringVar(&conf.LeftDelim, "left-delim", conf.LeftDelim, "Override template left delimiter") - if err := cmd.RegisterFlagCompletionFunc("left-delim", cobra.NoFileCompletions); err != nil { - panic(err) - } - - cmd.Flags().StringVar(&conf.RightDelim, "right-delim", conf.RightDelim, "Override template right delimiter") - if err := cmd.RegisterFlagCompletionFunc("right-delim", cobra.NoFileCompletions); err != nil { - panic(err) - } - - cmd.Flags().IntVarP(&conf.Indent, "indent", "I", conf.Indent, "Override output indentation") - if err := cmd.RegisterFlagCompletionFunc("indent", cobra.NoFileCompletions); err != nil { - panic(err) - } - - cmd.Flags().BoolVarP(&conf.Fail, "fail", "f", conf.Fail, `Exit with an error if a template variable is not set`) - if err := cmd.RegisterFlagCompletionFunc("fail", util.BoolCompletion); err != nil { - panic(err) - } - - cmd.Flags().BoolVarP(&conf.Strip, "strip", "s", conf.Strip, "Strip template comments from output") - if err := cmd.RegisterFlagCompletionFunc("strip", util.BoolCompletion); err != nil { - panic(err) - } - + conf.RegisterFlags(cmd) cmd.InitDefaultVersionFlag() - + conf.RegisterCompletions(cmd) + visitor.RegisterCompletion(cmd, conf) cmd.SetContext(config.WithContext(context.Background(), conf)) return cmd } @@ -95,62 +50,28 @@ func validArgs(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCom return []string{"yaml", "yml"}, cobra.ShellCompDirectiveFilterFileExt } -var ( - ErrNoFiles = errors.New("no input files") - ErrMissingConfig = errors.New("missing config") -) - -func preRun(cmd *cobra.Command, args []string) error { - completionFlag, err := cmd.Flags().GetString(CompletionFlag) - if err != nil { - panic(err) - } - if completionFlag != "" { - return nil - } - - initLog(cmd) - - cmd.SilenceUsage = true +var ErrNoFiles = errors.New("no input files") +func run(cmd *cobra.Command, args []string) error { conf, ok := config.FromContext(cmd.Context()) if !ok { - return ErrMissingConfig - } - - if !strings.HasPrefix(conf.Prefix, "#") { - conf.Prefix = "#" + conf.Prefix - } - - if len(args) == 0 && (conf.Inplace || conf.Recursive) { - return ErrNoFiles - } - - rawValues, err := cmd.Flags().GetStringToString(flags.ValueFlag) - if err != nil { - panic(err) + panic("config missing from command context") } - conf.Values.Fill(rawValues) - - return nil -} - -func run(cmd *cobra.Command, args []string) error { - completionFlag, err := cmd.Flags().GetString(CompletionFlag) - if err != nil { - panic(err) - } - if completionFlag != "" { - return completion(cmd, args) + if err := conf.Load(cmd); err != nil { + return err } - conf, ok := config.FromContext(cmd.Context()) - if !ok { - return ErrMissingConfig + if conf.Completion != "" { + return completion(cmd, conf.Completion) } if len(args) == 0 { + if conf.Inplace || conf.Recursive { + return ErrNoFiles + } + cmd.SilenceUsage = true + s, err := templateReader(conf, os.Stdin, log.Logger) if err != nil { return err @@ -161,6 +82,8 @@ func run(cmd *cobra.Command, args []string) error { } } + cmd.SilenceUsage = true + for i, p := range args { if err := openAndTemplate(conf, cmd.OutOrStdout(), p); err != nil { return fmt.Errorf("%s: %w", p, err) diff --git a/cmd/cmd_test.go b/cmd/cmd_test.go index e7e6fe0..0d5379f 100644 --- a/cmd/cmd_test.go +++ b/cmd/cmd_test.go @@ -13,16 +13,15 @@ import ( "github.com/stretchr/testify/require" ) -func Test_preRun(t *testing.T) { +func Test_run(t *testing.T) { t.Run("silent usage", func(t *testing.T) { cmd := NewCommand() - _ = preRun(cmd, []string{}) + _ = run(cmd, []string{}) assert.True(t, cmd.SilenceUsage) }) t.Run("no error", func(t *testing.T) { - err := preRun(NewCommand(), []string{}) - require.NoError(t, err) + require.NoError(t, run(NewCommand(), []string{})) }) t.Run("invalid prefix", func(t *testing.T) { @@ -30,11 +29,7 @@ func Test_preRun(t *testing.T) { conf, ok := config.FromContext(cmd.Context()) require.True(t, ok) conf.Prefix = "tmpl" - - if err := preRun(cmd, []string{}); !assert.NoError(t, err) { - return - } - + require.NoError(t, run(cmd, []string{})) want := "#tmpl" assert.Equal(t, want, conf.Prefix) }) @@ -44,9 +39,7 @@ func Test_preRun(t *testing.T) { conf, ok := config.FromContext(cmd.Context()) require.True(t, ok) conf.Inplace = true - - err := preRun(cmd, []string{}) - require.Error(t, err) + require.Error(t, run(cmd, []string{})) }) t.Run("recursive no files", func(t *testing.T) { @@ -54,18 +47,15 @@ func Test_preRun(t *testing.T) { conf, ok := config.FromContext(cmd.Context()) require.True(t, ok) conf.Recursive = true - - err := preRun(cmd, []string{}) - require.Error(t, err) + require.Error(t, run(cmd, []string{})) }) t.Run("completion flag enabled", func(t *testing.T) { cmd := NewCommand() - if err := cmd.Flags().Set(CompletionFlag, "zsh"); !assert.NoError(t, err) { + if err := cmd.Flags().Set(config.CompletionFlag, "zsh"); !assert.NoError(t, err) { return } - err := preRun(cmd, []string{}) - require.NoError(t, err) + require.NoError(t, run(cmd, []string{})) }) } diff --git a/cmd/completion.go b/cmd/completion.go new file mode 100644 index 0000000..f77c84a --- /dev/null +++ b/cmd/completion.go @@ -0,0 +1,25 @@ +package cmd + +import ( + "errors" + "fmt" + + "github.com/spf13/cobra" +) + +var ErrInvalidShell = errors.New("invalid shell") + +func completion(cmd *cobra.Command, shell string) error { + switch shell { + case "bash": + return cmd.Root().GenBashCompletion(cmd.OutOrStdout()) + case "zsh": + return cmd.Root().GenZshCompletion(cmd.OutOrStdout()) + case "fish": + return cmd.Root().GenFishCompletion(cmd.OutOrStdout(), true) + case "powershell": + return cmd.Root().GenPowerShellCompletionWithDesc(cmd.OutOrStdout()) + default: + return fmt.Errorf("%w: %s", ErrInvalidShell, shell) + } +} diff --git a/cmd/completion_test.go b/cmd/completion_test.go new file mode 100644 index 0000000..5ae0784 --- /dev/null +++ b/cmd/completion_test.go @@ -0,0 +1,48 @@ +package cmd + +import ( + "io" + "testing" + + "github.com/clevyr/yampl/internal/config" + "github.com/spf13/cobra" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func Test_completion(t *testing.T) { + r, w := io.Pipe() + _ = r.Close() + + type args struct { + cmd *cobra.Command + shell string + } + tests := []struct { + name string + w io.Writer + args args + wantErr require.ErrorAssertionFunc + }{ + {"bash", io.Discard, args{NewCommand(), "bash"}, require.NoError}, + {"bash error", w, args{NewCommand(), "bash"}, require.Error}, + {"zsh", io.Discard, args{NewCommand(), "zsh"}, require.NoError}, + {"zsh error", w, args{NewCommand(), "zsh"}, require.Error}, + {"fish", io.Discard, args{NewCommand(), "fish"}, require.NoError}, + {"fish error", w, args{NewCommand(), "fish"}, require.Error}, + {"powershell", io.Discard, args{NewCommand(), "powershell"}, require.NoError}, + {"powershell error", w, args{NewCommand(), "powershell"}, require.Error}, + {"other", io.Discard, args{NewCommand(), "other"}, require.Error}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.args.cmd.SetOut(tt.w) + + if err := tt.args.cmd.Flags().Set(config.CompletionFlag, tt.args.shell); !assert.NoError(t, err) { + return + } + err := completion(tt.args.cmd, tt.args.shell) + tt.wantErr(t, err) + }) + } +} diff --git a/cmd/flag_completion.go b/cmd/flag_completion.go deleted file mode 100644 index 2ce571a..0000000 --- a/cmd/flag_completion.go +++ /dev/null @@ -1,53 +0,0 @@ -package cmd - -import ( - "errors" - "fmt" - - "github.com/spf13/cobra" -) - -const CompletionFlag = "completion" - -func registerCompletionFlag(cmd *cobra.Command) { - cmd.Flags().String(CompletionFlag, "", "Output command-line completion code for the specified shell. Can be 'bash', 'zsh', 'fish', or 'powershell'.") - err := cmd.RegisterFlagCompletionFunc(CompletionFlag, completionCompletion) - if err != nil { - panic(err) - } -} - -func completionCompletion(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) { - return []string{"bash", "zsh", "fish", "powershell"}, cobra.ShellCompDirectiveNoFileComp -} - -var ErrInvalidShell = errors.New("invalid shell") - -func completion(cmd *cobra.Command, _ []string) error { - completionFlag, err := cmd.Flags().GetString(CompletionFlag) - if err != nil { - panic(err) - } - - switch completionFlag { - case "bash": - if err := cmd.Root().GenBashCompletion(cmd.OutOrStdout()); err != nil { - return err - } - case "zsh": - if err := cmd.Root().GenZshCompletion(cmd.OutOrStdout()); err != nil { - return err - } - case "fish": - if err := cmd.Root().GenFishCompletion(cmd.OutOrStdout(), true); err != nil { - return err - } - case "powershell": - if err := cmd.Root().GenPowerShellCompletionWithDesc(cmd.OutOrStdout()); err != nil { - return err - } - default: - return fmt.Errorf("%w: %s", ErrInvalidShell, completionFlag) - } - return nil -} diff --git a/cmd/flag_completion_test.go b/cmd/flag_completion_test.go deleted file mode 100644 index 3d350f8..0000000 --- a/cmd/flag_completion_test.go +++ /dev/null @@ -1,71 +0,0 @@ -package cmd - -import ( - "io" - "testing" - - "github.com/spf13/cobra" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func Test_completion(t *testing.T) { - r, w := io.Pipe() - _ = r.Close() - - type args struct { - cmd *cobra.Command - args []string - shell string - } - tests := []struct { - name string - w io.Writer - args args - wantErr require.ErrorAssertionFunc - }{ - {"bash", io.Discard, args{NewCommand(), []string{}, "bash"}, require.NoError}, - {"bash error", w, args{NewCommand(), []string{}, "bash"}, require.Error}, - {"zsh", io.Discard, args{NewCommand(), []string{}, "zsh"}, require.NoError}, - {"zsh error", w, args{NewCommand(), []string{}, "zsh"}, require.Error}, - {"fish", io.Discard, args{NewCommand(), []string{}, "fish"}, require.NoError}, - {"fish error", w, args{NewCommand(), []string{}, "fish"}, require.Error}, - {"powershell", io.Discard, args{NewCommand(), []string{}, "powershell"}, require.NoError}, - {"powershell error", w, args{NewCommand(), []string{}, "powershell"}, require.Error}, - {"other", io.Discard, args{NewCommand(), []string{}, "other"}, require.Error}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - tt.args.cmd.SetOut(tt.w) - - if err := tt.args.cmd.Flags().Set(CompletionFlag, tt.args.shell); !assert.NoError(t, err) { - return - } - err := completion(tt.args.cmd, tt.args.args) - tt.wantErr(t, err) - }) - } -} - -func Test_completionCompletion(t *testing.T) { - type args struct { - cmd *cobra.Command - args []string - toComplete string - } - tests := []struct { - name string - args args - want []string - want1 cobra.ShellCompDirective - }{ - {"default", args{}, []string{"bash", "zsh", "fish", "powershell"}, cobra.ShellCompDirectiveNoFileComp}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got, got1 := completionCompletion(tt.args.cmd, tt.args.args, tt.args.toComplete) - assert.Equal(t, tt.want, got) - assert.Equal(t, tt.want1, got1) - }) - } -} diff --git a/internal/config/completions.go b/internal/config/completions.go new file mode 100644 index 0000000..686b41e --- /dev/null +++ b/internal/config/completions.go @@ -0,0 +1,38 @@ +package config + +import ( + "github.com/clevyr/yampl/internal/util" + "github.com/spf13/cobra" +) + +func (c *Config) RegisterCompletions(cmd *cobra.Command) { + util.Must( + cmd.RegisterFlagCompletionFunc(InplaceFlag, BoolCompletion), + cmd.RegisterFlagCompletionFunc(RecursiveFlag, BoolCompletion), + cmd.RegisterFlagCompletionFunc(PrefixFlag, cobra.NoFileCompletions), + cmd.RegisterFlagCompletionFunc(LeftDelimFlag, cobra.NoFileCompletions), + cmd.RegisterFlagCompletionFunc(RightDelimFlag, cobra.NoFileCompletions), + cmd.RegisterFlagCompletionFunc(IndentFlag, cobra.NoFileCompletions), + cmd.RegisterFlagCompletionFunc(FailFlag, BoolCompletion), + cmd.RegisterFlagCompletionFunc(StripFlag, BoolCompletion), + cmd.RegisterFlagCompletionFunc(LogLevelFlag, + func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) { + return []string{"trace", "debug", "info", "warning", "error", "fatal", "panic"}, cobra.ShellCompDirectiveNoFileComp + }, + ), + cmd.RegisterFlagCompletionFunc(LogFormatFlag, + func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) { + return []string{"auto", "color", "plain", "json"}, cobra.ShellCompDirectiveNoFileComp + }, + ), + cmd.RegisterFlagCompletionFunc(CompletionFlag, + func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) { + return []string{"bash", "zsh", "fish", "powershell"}, cobra.ShellCompDirectiveNoFileComp + }, + ), + ) +} + +func BoolCompletion(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) { + return []string{"true", "false"}, cobra.ShellCompDirectiveNoFileComp +} diff --git a/internal/config/config.go b/internal/config/config.go index dcaea91..e5bd833 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -1,5 +1,7 @@ package config +import "github.com/rs/zerolog" + type Config struct { Values Values Inplace bool @@ -10,6 +12,11 @@ type Config struct { Indent int Fail bool Strip bool + + LogLevel string + LogFormat string + + Completion string } func New() *Config { @@ -19,5 +26,8 @@ func New() *Config { LeftDelim: "{{", RightDelim: "}}", Indent: 2, + + LogLevel: zerolog.InfoLevel.String(), + LogFormat: "color", } } diff --git a/internal/config/flags.go b/internal/config/flags.go new file mode 100644 index 0000000..574957a --- /dev/null +++ b/internal/config/flags.go @@ -0,0 +1,40 @@ +package config + +import ( + "github.com/spf13/cobra" +) + +const ( + InplaceFlag = "inplace" + ValueFlag = "value" + ValueFlagShort = "v" + RecursiveFlag = "recursive" + PrefixFlag = "prefix" + LeftDelimFlag = "left-delim" + RightDelimFlag = "right-delim" + IndentFlag = "indent" + FailFlag = "fail" + StripFlag = "strip" + + LogLevelFlag = "log-level" + LogFormatFlag = "log-format" + + CompletionFlag = "completion" +) + +func (c *Config) RegisterFlags(cmd *cobra.Command) { + cmd.Flags().BoolVarP(&c.Inplace, InplaceFlag, "i", c.Inplace, "Edit files in place") + cmd.Flags().StringToStringP(ValueFlag, ValueFlagShort, map[string]string{}, "Define a template variable. Can be used more than once.") + cmd.Flags().BoolVarP(&c.Recursive, RecursiveFlag, "r", c.Recursive, "Recursively update yaml files in the given directory") + cmd.Flags().StringVarP(&c.Prefix, PrefixFlag, "p", c.Prefix, "Template comments must begin with this prefix. The beginning '#' is implied.") + cmd.Flags().StringVar(&c.LeftDelim, LeftDelimFlag, c.LeftDelim, "Override template left delimiter") + cmd.Flags().StringVar(&c.RightDelim, RightDelimFlag, c.RightDelim, "Override template right delimiter") + cmd.Flags().IntVarP(&c.Indent, IndentFlag, "I", c.Indent, "Override output indentation") + cmd.Flags().BoolVarP(&c.Fail, FailFlag, "f", c.Fail, `Exit with an error if a template variable is not set`) + cmd.Flags().BoolVarP(&c.Strip, StripFlag, "s", c.Strip, "Strip template comments from output") + + cmd.Flags().StringVarP(&c.LogLevel, LogLevelFlag, "l", c.LogLevel, "Log level (trace, debug, info, warn, error, fatal, panic)") + cmd.Flags().StringVar(&c.LogFormat, LogFormatFlag, c.LogFormat, "Log format (auto, color, plain, json)") + + cmd.Flags().StringVar(&c.Completion, CompletionFlag, c.Completion, "Output command-line completion code for the specified shell. Can be 'bash', 'zsh', 'fish', or 'powershell'.") +} diff --git a/internal/config/flags/flags.go b/internal/config/flags/flags.go deleted file mode 100644 index f5b2d39..0000000 --- a/internal/config/flags/flags.go +++ /dev/null @@ -1,6 +0,0 @@ -package flags - -const ( - ValueFlag = "value" - ValueFlagShort = "v" -) diff --git a/internal/config/load.go b/internal/config/load.go new file mode 100644 index 0000000..708a97d --- /dev/null +++ b/internal/config/load.go @@ -0,0 +1,48 @@ +package config + +import ( + "errors" + "os" + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" +) + +const EnvPrefix = "YAMPL_" + +func (c *Config) Load(cmd *cobra.Command) error { + var errs []error + cmd.Flags().VisitAll(func(f *pflag.Flag) { + if !f.Changed { + if val, ok := os.LookupEnv(EnvName(f.Name)); ok { + if err := f.Value.Set(val); err != nil { + errs = append(errs, err) + } + } + } + }) + if len(errs) != 0 { + return errors.Join(errs...) + } + + initLog(cmd) + + if !strings.HasPrefix(c.Prefix, "#") { + c.Prefix = "#" + c.Prefix + } + + rawValues, err := cmd.Flags().GetStringToString(ValueFlag) + if err != nil { + return err + } + c.Values.Fill(rawValues) + + return nil +} + +func EnvName(name string) string { + name = strings.ToUpper(name) + name = strings.ReplaceAll(name, "-", "_") + return EnvPrefix + name +} diff --git a/cmd/flag_log.go b/internal/config/log.go similarity index 65% rename from cmd/flag_log.go rename to internal/config/log.go index c0c2e27..770837c 100644 --- a/cmd/flag_log.go +++ b/internal/config/log.go @@ -1,4 +1,4 @@ -package cmd +package config import ( "fmt" @@ -12,32 +12,6 @@ import ( "github.com/spf13/cobra" ) -func registerLogFlags(cmd *cobra.Command) { - var err error - - cmd.Flags().StringP("log-level", "l", "info", "Log level (trace, debug, info, warn, error, fatal, panic)") - err = cmd.RegisterFlagCompletionFunc( - "log-level", - func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) { - return []string{"trace", "debug", "info", "warning", "error", "fatal", "panic"}, cobra.ShellCompDirectiveNoFileComp - }, - ) - if err != nil { - panic(err) - } - - cmd.Flags().String("log-format", "color", "Log format (auto, color, plain, json)") - err = cmd.RegisterFlagCompletionFunc( - "log-format", - func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) { - return []string{"auto", "color", "plain", "json"}, cobra.ShellCompDirectiveNoFileComp - }, - ) - if err != nil { - panic(err) - } -} - func logLevel(level string) zerolog.Level { parsedLevel, err := zerolog.ParseLevel(level) if err != nil || parsedLevel == zerolog.NoLevel { diff --git a/cmd/flag_log_test.go b/internal/config/log_test.go similarity index 99% rename from cmd/flag_log_test.go rename to internal/config/log_test.go index 58acc8a..98e5d94 100644 --- a/cmd/flag_log_test.go +++ b/internal/config/log_test.go @@ -1,4 +1,4 @@ -package cmd +package config import ( "io" diff --git a/internal/config/values.go b/internal/config/values.go index f60bb22..bd16e3b 100644 --- a/internal/config/values.go +++ b/internal/config/values.go @@ -1,6 +1,8 @@ package config -import "strings" +import ( + "strings" +) type Values map[string]any diff --git a/internal/util/flags.go b/internal/config/values_hack.go similarity index 82% rename from internal/util/flags.go rename to internal/config/values_hack.go index 7861b69..119cf82 100644 --- a/internal/util/flags.go +++ b/internal/config/values_hack.go @@ -1,10 +1,8 @@ -package util +package config import ( "bufio" "strings" - - "github.com/clevyr/yampl/internal/config/flags" ) func FixStringToStringNewlines(s []string) []string { @@ -35,10 +33,10 @@ func FixStringToStringNewlines(s []string) []string { } func hasValueFlag(s string) bool { - return s == "-"+flags.ValueFlagShort || - s == "--"+flags.ValueFlag || - strings.HasPrefix(s, "-"+flags.ValueFlagShort+"=") || - strings.HasPrefix(s, "--"+flags.ValueFlag+"=") + return s == "-"+ValueFlagShort || + s == "--"+ValueFlag || + strings.HasPrefix(s, "-"+ValueFlagShort+"=") || + strings.HasPrefix(s, "--"+ValueFlag+"=") } func fixArgNewlines(arg string) []string { diff --git a/internal/util/flags_test.go b/internal/config/values_hack_test.go similarity index 99% rename from internal/util/flags_test.go rename to internal/config/values_hack_test.go index b6c885a..9fb8322 100644 --- a/internal/util/flags_test.go +++ b/internal/config/values_hack_test.go @@ -1,4 +1,4 @@ -package util +package config import ( "testing" diff --git a/internal/util/completion.go b/internal/util/completion.go deleted file mode 100644 index 396ff96..0000000 --- a/internal/util/completion.go +++ /dev/null @@ -1,7 +0,0 @@ -package util - -import "github.com/spf13/cobra" - -func BoolCompletion(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) { - return []string{"true", "false"}, cobra.ShellCompDirectiveNoFileComp -} diff --git a/internal/util/error.go b/internal/util/error.go new file mode 100644 index 0000000..4531398 --- /dev/null +++ b/internal/util/error.go @@ -0,0 +1,9 @@ +package util + +func Must(errs ...error) { + for _, err := range errs { + if err != nil { + panic(err) + } + } +} diff --git a/cmd/flag_values.go b/internal/visitor/find_args_completion.go similarity index 72% rename from cmd/flag_values.go rename to internal/visitor/find_args_completion.go index 1530631..94bccf8 100644 --- a/cmd/flag_values.go +++ b/internal/visitor/find_args_completion.go @@ -1,4 +1,4 @@ -package cmd +package visitor import ( "errors" @@ -9,19 +9,13 @@ import ( "strings" "github.com/clevyr/yampl/internal/config" - "github.com/clevyr/yampl/internal/config/flags" "github.com/clevyr/yampl/internal/util" - "github.com/clevyr/yampl/internal/visitor" "github.com/spf13/cobra" "gopkg.in/yaml.v3" ) -func registerValuesFlag(cmd *cobra.Command, conf *config.Config) { - cmd.Flags().StringToStringP(flags.ValueFlag, flags.ValueFlagShort, map[string]string{}, "Define a template variable. Can be used more than once.") - err := cmd.RegisterFlagCompletionFunc("value", valueCompletion(conf)) - if err != nil { - panic(err) - } +func RegisterCompletion(cmd *cobra.Command, conf *config.Config) { + util.Must(cmd.RegisterFlagCompletionFunc(config.ValueFlag, valueCompletion(conf))) } func valueCompletion(conf *config.Config) func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { @@ -30,7 +24,7 @@ func valueCompletion(conf *config.Config) func(cmd *cobra.Command, args []string conf.Prefix = "#" + conf.Prefix } - v := visitor.NewFindArgs(conf) + v := NewFindArgs(conf) for _, path := range args { stat, err := os.Stat(path) @@ -60,7 +54,7 @@ func valueCompletion(conf *config.Config) func(cmd *cobra.Command, args []string } } -func valueCompletionFile(path string, v *visitor.FindArgs) error { +func valueCompletionFile(path string, v *FindArgs) error { f, err := os.Open(path) if err != nil { return err diff --git a/main.go b/main.go index 1e244c8..c74d344 100644 --- a/main.go +++ b/main.go @@ -4,11 +4,11 @@ import ( "os" "github.com/clevyr/yampl/cmd" - "github.com/clevyr/yampl/internal/util" + "github.com/clevyr/yampl/internal/config" ) func main() { - os.Args = util.FixStringToStringNewlines(os.Args) + os.Args = config.FixStringToStringNewlines(os.Args) rootCmd := cmd.NewCommand() if err := rootCmd.Execute(); err != nil { os.Exit(1)