Skip to content

Commit

Permalink
Consistency between config help and function
Browse files Browse the repository at this point in the history
  • Loading branch information
ChrisFriesen committed Apr 19, 2023
1 parent 829c912 commit 6d0bccf
Show file tree
Hide file tree
Showing 3 changed files with 137 additions and 13 deletions.
16 changes: 5 additions & 11 deletions cmd/cape/cmd/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@ import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"

"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)

Expand All @@ -26,14 +25,9 @@ func init() {

func Config(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
// No args, so print current config values
fmt.Println("Here are the configurable options and their values:")
cmd.Flags().VisitAll(func(f *pflag.Flag) {
// Print all non hidden flags
if !f.Hidden {
fmt.Printf("Name: %s, Value: %s, Default: %s\n", f.Name, f.Value, f.DefValue)
}
})
// No args, so print current config options
cmd.Println("Here are the configurable options:")
cmd.Println(strings.Join(viper.AllKeys(), ", "))
return nil
}

Expand All @@ -49,7 +43,7 @@ func Config(cmd *cobra.Command, args []string) error {
return fmt.Errorf("not a valid key: %s.\n Valid keys are: %+v", key, viper.AllKeys())
}

configFile := filepath.Join(viper.GetString("LOCAL_CONFIG_DIR"), viper.GetString("LOCAL_PRESETS_FILE_NAME"))
configFile := viper.GetString("LOCAL_PRESETS_FILE")

if !fileExists(configFile) {
var file, err = os.Create(configFile)
Expand Down
120 changes: 120 additions & 0 deletions cmd/cape/cmd/config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
package cmd

import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
)

func TestConfigNoArgs(t *testing.T) {
cmd, stdout, stderr := getCmd()
cmd.SetArgs([]string{"config"})

want := "Here are the configurable options"

if err := cmd.Execute(); err != nil {
t.Fatalf("received unexpected error: %s", err)
}

if got, want := stderr.String(), ""; got != want {
t.Fatalf("didn't get expected stderr, got %s, wanted %s", got, want)
}

if !strings.Contains(stdout.String(), want) {
t.Fatalf("stdout did not contain configurable options")
}
}

func TestConfigFileNotExist(t *testing.T) {
dir, err := os.MkdirTemp("", "cfgTest")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)

cfgFile := filepath.Join(dir, "presets.json")
os.Setenv("LOCAL_PRESETS_FILE", cfgFile)
defer os.Unsetenv("LOCAL_PRESETS_FILE")

cmd, _, stderr := getCmd()
cmd.SetArgs([]string{"config", "dev_disable_ssl", "true"})

if err := cmd.Execute(); err != nil {
t.Fatalf("received unexpected error: %s", err)
}

if got, want := stderr.String(), ""; got != want {
t.Fatalf("didn't get expected stderr, got %s, wanted %s", got, want)
}

b, err := os.ReadFile(cfgFile)
if err != nil {
t.Fatal(err)
}

cfg := struct {
DevDisableSSL string `json:"dev_disable_ssl"`
}{}
if err := json.Unmarshal(b, &cfg); err != nil {
t.Fatalf("function stored invalid json")
}

// Check new value has been added
if got, want := cfg.DevDisableSSL, "true"; got != want {
t.Errorf("didn't get expected value got: %s, want: %s", got, want)
}
}

func TestConfigFileExists(t *testing.T) {
f, err := os.CreateTemp("", "cfgTest")
if err != nil {
t.Errorf("unable to create temp config file: %s", err)
}
defer os.Remove(f.Name())
os.Setenv("LOCAL_PRESETS_FILE", f.Name())
defer os.Unsetenv("LOCAL_PRESETS_FILE")

err = os.WriteFile(
f.Name(),
[]byte(`{"auth_host":"www.auth.com"}`),
0600)
if err != nil {
t.Errorf("unable to set up config file: %s", err)
}

cmd, _, stderr := getCmd()
cmd.SetArgs([]string{"config", "dev_disable_ssl", "true"})

if err := cmd.Execute(); err != nil {
t.Fatalf("received unexpected error: %s", err)
}

if got, want := stderr.String(), ""; got != want {
t.Fatalf("didn't get expected stderr, got %s, wanted %s", got, want)
}

b, err := os.ReadFile(f.Name())
if err != nil {
t.Fatal(err)
}

cfg := struct {
AuthHost string `json:"auth_host"`
DevDisableSSL string `json:"dev_disable_ssl"`
}{}
if err := json.Unmarshal(b, &cfg); err != nil {
t.Fatalf("function stored invalid json")
}

// Check existing value isn't overwritten
if got, want := cfg.AuthHost, "www.auth.com"; got != want {
t.Errorf("didn't get expected value got: %s, want: %s", got, want)
}

// Check new value has been added
if got, want := cfg.DevDisableSSL, "true"; got != want {
t.Errorf("didn't get expected value got: %s, want: %s", got, want)
}
}
14 changes: 12 additions & 2 deletions cmd/cape/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io/fs"
"net/http"
"os"
"strings"
Expand Down Expand Up @@ -167,6 +169,14 @@ func init() {
log.Error("failed to bind cli argument.")
cobra.CheckErr(err)
}
if err := viper.BindPFlag("CAPE_VERBOSE", rootCmd.PersistentFlags().Lookup("verbose")); err != nil {
log.Error("failed to bind cli argument.")
cobra.CheckErr(err)
}
if err := viper.BindPFlag("CAPE_OUTPUT_FMT", rootCmd.PersistentFlags().Lookup("output")); err != nil {
log.Error("failed to bind cli argument.")
cobra.CheckErr(err)
}
if err := viper.BindPFlag("LOCAL_PRESETS_FILE", rootCmd.PersistentFlags().Lookup("config")); err != nil {
log.Error("failed to bind cli argument.")
cobra.CheckErr(err)
Expand All @@ -191,12 +201,12 @@ func initConfig() {
viper.SetDefault("LOCAL_PRESETS_FILE", cfgDir+"/presets.json")

// Read in config parameters from file
// viper.AddConfigPath(viper.GetString("LOCAL_CONFIG_DIR"))
viper.SetConfigFile(viper.GetString("LOCAL_PRESETS_FILE"))
viper.SetConfigType("json")

fileNotExist := &fs.PathError{}
if err := readConfFile(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
if !errors.Is(err, viper.ConfigFileNotFoundError{}) && !errors.As(err, &fileNotExist) {
// Config file found but not valid
log.Error("failed to read config params.")
cobra.CheckErr(err)
Expand Down

0 comments on commit 6d0bccf

Please sign in to comment.