From 99088a5918591c1f08b31bd807a9529440ccdf20 Mon Sep 17 00:00:00 2001 From: Jeremy Lewi Date: Tue, 9 Apr 2024 07:20:35 -0700 Subject: [PATCH] Add configuration subcommand. --- app/cmd/config.go | 92 +++++++++++++++++++++++++++++++++++++++++++++++ app/cmd/root.go | 1 + 2 files changed, 93 insertions(+) create mode 100644 app/cmd/config.go diff --git a/app/cmd/config.go b/app/cmd/config.go new file mode 100644 index 00000000..188e34f3 --- /dev/null +++ b/app/cmd/config.go @@ -0,0 +1,92 @@ +package cmd + +import ( + "fmt" + "os" + "strings" + + "github.com/jlewi/foyle/app/pkg/config" + "github.com/pkg/errors" + "github.com/spf13/cobra" + "github.com/spf13/viper" + "gopkg.in/yaml.v3" +) + +// NewConfigCmd adds commands to deal with configuration +func NewConfigCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "config", + } + + cmd.AddCommand(NewGetConfigCmd()) + cmd.AddCommand(NewSetConfigCmd()) + return cmd +} + +// NewSetConfigCmd sets a key value pair in the configuration +func NewSetConfigCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "set =", + Args: cobra.ExactArgs(1), + Run: func(cmd *cobra.Command, args []string) { + + err := func() error { + if err := config.InitViper(cmd); err != nil { + return err + } + + pieces := strings.Split(args[0], "=") + if len(pieces) < 2 { + return errors.New("Invalid usage; set expects an argument in the form =") + } + cfgName := pieces[0] + cfgValue := pieces[1] + viper.Set(cfgName, cfgValue) + fConfig := config.GetConfig() + + file := viper.ConfigFileUsed() + if file == "" { + file = config.DefaultConfigFile() + } + // Persist the configuration + return fConfig.Write(file) + }() + + if err != nil { + fmt.Printf("Failed to set configuration;\n %+v\n", err) + os.Exit(1) + } + }, + } + + return cmd +} + +// NewGetConfigCmd prints out the configuration +func NewGetConfigCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "get", + Short: "Dump Foyle configuration as YAML", + Run: func(cmd *cobra.Command, args []string) { + err := func() error { + if err := config.InitViper(cmd); err != nil { + return err + } + fConfig := config.GetConfig() + + if err := yaml.NewEncoder(os.Stdout).Encode(fConfig); err != nil { + return err + } + + return nil + }() + + if err != nil { + fmt.Printf("Failed to get configuration;\n %+v\n", err) + os.Exit(1) + } + }, + } + + return cmd +} diff --git a/app/cmd/root.go b/app/cmd/root.go index 92301ba1..bd42febd 100644 --- a/app/cmd/root.go +++ b/app/cmd/root.go @@ -27,5 +27,6 @@ func NewRootCmd() *cobra.Command { rootCmd.AddCommand(NewAssetsCmd()) rootCmd.AddCommand(NewVersionCmd(appName, os.Stdout)) rootCmd.AddCommand(NewServeCmd()) + rootCmd.AddCommand(NewConfigCmd()) return rootCmd }