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 Oct 26, 2023
1 parent 89ebbe7 commit 88936f9
Show file tree
Hide file tree
Showing 3 changed files with 129 additions and 11 deletions.
78 changes: 78 additions & 0 deletions cmd/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
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) {
configDir, _ := os.Getwd()

configured := false
if len(args) > 0 {
for _, pair := range config.ParseConfig(args) {
err := config.WriteLocalConfigValue(configDir, pair.Key, pair.Value)
if err != nil {
panic(err)
}
}
configured = true
}

if !configured {
printLocalConfigHelp(cmd)
} else {
logger.Infof("set CLI config for: %s", configDir)
}
},
}

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 listSupportedLocalKeys() []string {
return []string{
"engine",
"version",
}
}
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 88936f9

Please sign in to comment.