Skip to content

Commit

Permalink
Add configuration subcommand. (#35)
Browse files Browse the repository at this point in the history
  • Loading branch information
jlewi authored Apr 9, 2024
1 parent 595738d commit 63562a4
Show file tree
Hide file tree
Showing 2 changed files with 93 additions and 0 deletions.
92 changes: 92 additions & 0 deletions app/cmd/config.go
Original file line number Diff line number Diff line change
@@ -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 <name>=<value>",
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 <NAME>=<VALUE>")
}
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
}
1 change: 1 addition & 0 deletions app/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

0 comments on commit 63562a4

Please sign in to comment.