Skip to content

Commit

Permalink
feat: adds local config writer command.
Browse files Browse the repository at this point in the history
  • Loading branch information
outofcoffee committed Nov 18, 2023
1 parent 457f7dc commit b1a247d
Show file tree
Hide file tree
Showing 4 changed files with 189 additions and 11 deletions.
81 changes: 81 additions & 0 deletions cmd/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/*
Copyright © 2021-2023 Pete Cornish <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package cmd

import (
"fmt"
"os"
"strings"

"gatehill.io/imposter/config"
"github.com/spf13/cobra"
)

// localConfigCmd represents the localConfig command
var localConfigCmd = &cobra.Command{
Use: "config [key=value]",
Short: "Set CLI config for working directory",
Long: `Sets CLI configuration for the working directory.`,
Args: cobra.MinimumNArgs(0),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
var formattedKeys []string
for _, k := range listSupportedLocalKeys() {
formattedKeys = append(formattedKeys, k+"=VAL")
}
return formattedKeys, cobra.ShellCompDirectiveNoFileComp
},
Run: func(cmd *cobra.Command, args []string) {
if len(args) > 0 {
configDir, _ := os.Getwd()
setLocalConfig(cmd, args, configDir)
} else {
printLocalConfigHelp(cmd)
}
},
}

func init() {
rootCmd.AddCommand(localConfigCmd)
}

func printLocalConfigHelp(cmd *cobra.Command) {
supported := strings.Join(listSupportedLocalKeys(), ", ")
fmt.Fprintf(os.Stderr, "%v\nSupported config keys: %s\n", cmd.UsageString(), supported)
os.Exit(1)
}

func setLocalConfig(cmd *cobra.Command, args []string, configDir string) {
parsed := config.ParseConfig(args)
if len(parsed) == 0 {
printLocalConfigHelp(cmd)
} else {
for _, pair := range parsed {
err := config.WriteLocalConfigValue(configDir, pair.Key, pair.Value)
if err != nil {
panic(err)
}
}
logger.Infof("set CLI config for: %s", configDir)
}
}

func listSupportedLocalKeys() []string {
return []string{
"engine",
"version",
}
}
57 changes: 57 additions & 0 deletions cmd/config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package cmd

import (
"gatehill.io/imposter/config"
"github.com/spf13/cobra"
"os"
"path"
"testing"
)

func Test_setLocalConfig(t *testing.T) {
type args struct {
cmd *cobra.Command
args []string
}
tests := []struct {
name string
args args
wantErr bool
fileShouldExist bool
want string
}{
{
name: "set local config",
args: args{
cmd: &cobra.Command{},
args: []string{"foo=bar"},
},
wantErr: false,
fileShouldExist: true,
want: "foo: bar\n",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tempDir, err := os.MkdirTemp(os.TempDir(), "imposter-cli")
if err != nil {
panic(err)
}

setLocalConfig(tt.args.cmd, tt.args.args, tempDir)
cfg, err := os.ReadFile(path.Join(tempDir, config.LocalDirConfigFileName+".yaml"))
if (err != nil) != tt.wantErr {
t.Errorf("setLocalConfig() error = %v, wantErr %v", err, tt.wantErr)
return
}
if tt.fileShouldExist && err != nil {
t.Errorf("setLocalConfig() file should exist but does not")
return
}
if tt.want != string(cfg) {
t.Errorf("file contents do not match expected - got %s, want %s", string(cfg), tt.want)
return
}
})
}
}
15 changes: 6 additions & 9 deletions cmd/remote_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,12 @@ package cmd

import (
"fmt"
"gatehill.io/imposter/remote"
"github.com/spf13/cobra"
"os"
"strings"

"gatehill.io/imposter/config"
"gatehill.io/imposter/remote"
"github.com/spf13/cobra"
)

// remoteConfigCmd represents the remoteConfig command
Expand All @@ -42,13 +44,8 @@ var remoteConfigCmd = &cobra.Command{

configured := false
if len(args) > 0 {
for _, arg := range args {
if !strings.Contains(arg, "=") {
logger.Warnf("invalid config item: %s", arg)
continue
}
splitArgs := strings.Split(arg, "=")
setRemoteConfigItem(dir, splitArgs[0], strings.Trim(splitArgs[1], `"`))
for _, pair := range config.ParseConfig(args) {
setRemoteConfigItem(dir, pair.Key, pair.Value)
}
configured = true
}
Expand Down
47 changes: 45 additions & 2 deletions config/cli_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,25 @@ package config

import (
"fmt"
"gatehill.io/imposter/logging"
"github.com/spf13/viper"
"os"
"path"
"path/filepath"
"strings"

"gatehill.io/imposter/logging"
"github.com/spf13/viper"
)

type CliConfig struct {
Version string
LogLevel string
}

type ConfigPair struct {
Key string
Value string
}

// The GlobalConfigFileName is the file name without the file extension.
const GlobalConfigFileName = "config"

Expand Down Expand Up @@ -74,3 +82,38 @@ func MergeCliConfigIfExists(configDir string) {
logger.Tracef("using local CLI config file: %v", viper.ConfigFileUsed())
}
}

func ParseConfig(args []string) []ConfigPair {
var pairs []ConfigPair
for _, arg := range args {
if !strings.Contains(arg, "=") {
logger.Warnf("invalid config item: %s", arg)
continue
}
splitArgs := strings.Split(arg, "=")
pairs = append(pairs, ConfigPair{
Key: splitArgs[0],
Value: strings.Trim(splitArgs[1], `"`),
})
}
return pairs
}

func WriteLocalConfigValue(configDir string, key string, value string) error {
v := viper.New()

localConfig := path.Join(configDir, LocalDirConfigFileName+".yaml")
v.SetConfigFile(localConfig)

// sink if does not exist
_ = v.ReadInConfig()

v.Set(key, value)
err := v.WriteConfig()
if err != nil {
return fmt.Errorf("failed to write config file: %s: %v", localConfig, err)
}

logger.Tracef("wrote CLI config to: %s", localConfig)
return nil
}

0 comments on commit b1a247d

Please sign in to comment.