Skip to content

Commit

Permalink
Create a default config file if not exists (#1472)
Browse files Browse the repository at this point in the history
If the config file doesn't exist create one with default settings.
I used the settings that are given in this link:
https://github.com/knative/client/blob/main/docs/README.md#options

Signed-off-by: Boaz Shuster <[email protected]>
  • Loading branch information
boaz0 authored Nov 2, 2021
1 parent 7f0bc78 commit 09d48d5
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 7 deletions.
33 changes: 27 additions & 6 deletions pkg/kn/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,24 @@ type defaultConfig struct {
// Initialize defaults
var bootstrapDefaults = initDefaults()

const configContentDefaults = `# Taken from https://github.com/knative/client/blob/main/docs/README.md#options
#
#plugins:
# path-lookup: true
# directory: ~/.config/kn/plugins
#eventing:
# sink-mappings:
# - prefix: svc
# group: core
# version: v1
# resource: services
# channel-type-mappings:
# - alias: Kafka
# group: messaging.knative.dev
# version: v1alpha1
# kind: KafkaChannel
`

// config contains the variables for the Kn config
type config struct {
// configFile is the config file location
Expand Down Expand Up @@ -119,18 +137,21 @@ func BootstrapConfig() error {
return err
}

// Check if configfile exists. If not, just return
viper.SetConfigFile(GlobalConfig.ConfigFile())
configFile := GlobalConfig.ConfigFile()
_, err = os.Lstat(configFile)
if err != nil {
if os.IsNotExist(err) {
// No config file to read
return nil
if !os.IsNotExist(err) {
return fmt.Errorf("cannot stat configfile %s: %w", configFile, err)
}
if err := os.MkdirAll(filepath.Dir(viper.ConfigFileUsed()), 0775); err != nil {
return err
}
if err := os.WriteFile(viper.ConfigFileUsed(), []byte(configContentDefaults), 0600); err != nil {
fmt.Fprintf(os.Stderr, "WARNING: failed writing config file to %q: %s\n", configFile, err)
}
return fmt.Errorf("cannot stat configfile %s: %w", configFile, err)
}

viper.SetConfigFile(GlobalConfig.ConfigFile())
viper.AutomaticEnv() // read in environment variables that match

// Defaults are taken from the parsed flags, which in turn have bootstrap defaults
Expand Down
1 change: 0 additions & 1 deletion pkg/kn/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,6 @@ func TestBootstrapConfigWithoutConfigFile(t *testing.T) {
assert.Equal(t, GlobalConfig.ConfigFile(), bootstrapDefaults.configFile)
assert.Equal(t, GlobalConfig.PluginsDir(), bootstrapDefaults.pluginsDir)
assert.Equal(t, GlobalConfig.LookupPluginsInPath(), bootstrapDefaults.lookupPluginsInPath)
assert.Equal(t, len(GlobalConfig.SinkMappings()), 0)
}

func TestBootstrapLegacyConfigFields(t *testing.T) {
Expand Down

0 comments on commit 09d48d5

Please sign in to comment.