Skip to content

Commit

Permalink
fix(internal): Attribute CLI flags after reading config (#856)
Browse files Browse the repository at this point in the history
Reviewed-by: Alexander Jung <alex@unikraft.io>
Approved-by: Alexander Jung <alex@unikraft.io>
  • Loading branch information
nderjung committed Oct 6, 2023
2 parents d59cd89 + 01c6eaf commit 2828af2
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
22 changes: 22 additions & 0 deletions config/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,28 @@ func AllowedValues(key string) []string {
return []string{}
}

// FetchConfigDirFromArgs returns the path to the alternate config directory
// that can be set via the --config-dir flag. This needs to be fetched before flags
// are populated with AttributeFlags to ensure that the function is called only once.
func FetchConfigDirFromArgs(args []string) (path string) {
for idx, arg := range args {
if !strings.HasPrefix(arg, "--config-dir") {
continue
}
if strings.Contains(arg, "=") {
if split := strings.Split(arg, "="); len(split) == 2 {
path = split[1]
}
} else {
if !strings.HasPrefix(args[idx+1], "-") {
path = args[idx+1]
}
}
break
}
return
}

func Default[C any](key string) string {
found, _, def, _, err := findConfigDefault[C](key, "", "", reflect.ValueOf(new([0]C)))
if err != nil || found != key {
Expand Down
12 changes: 7 additions & 5 deletions internal/cli/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,20 +126,18 @@ func WithDefaultConfigManager(cmd *cobra.Command) CliOption {
if err != nil {
return err
}
if err := cmdfactory.AttributeFlags(cmd, cfg, args...); err != nil {
return err
}
configDir := config.FetchConfigDirFromArgs(args)

// Did the user specify a non-standard config directory? The following
// check is possible thanks to the attribution of flags to the config file.
// If a flag specifies changing the config directory, we must
// re-instantiate the ConfigManager with the configuration from that
// directory.
var cfgm *config.ConfigManager[config.KraftKit]
if cpath := cfg.Paths.Config; cpath != "" && cpath != config.ConfigDir() {
if configDir != "" && configDir != config.ConfigDir() {
cfgm, err = config.NewConfigManager(
cfg,
config.WithFile[config.KraftKit](filepath.Join(cpath, "config.yaml"), true),
config.WithFile[config.KraftKit](filepath.Join(configDir, "config.yaml"), true),
)
if err != nil {
return err
Expand All @@ -154,6 +152,10 @@ func WithDefaultConfigManager(cmd *cobra.Command) CliOption {
}
}

if err := cmdfactory.AttributeFlags(cmd, cfg, args...); err != nil {
return err
}

copts.ConfigManager = cfgm

return nil
Expand Down

0 comments on commit 2828af2

Please sign in to comment.