spf13 / spf13/cobra

Hack to inject viper config into FlagSet bindings at startup

Open
#367 3 comments 8 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

area/flags-args area/lib
Dominant language
Go
Stars
44.6k
Forks
3.5k
PR merge metrics
No merged PRs in 30d

Description

For Apps that already use Cobra to set a config struct or vars, and do not want to change all accesses to that config to viper.Get(), the following hack worked for me when called in a PersistentPreRun hook of the root command. Foregoes dynamic reloading though. Perhaps this could be a utility function or integrated more cleanly somehow.

// Read explicitly set values from viper and override Flags
//  values with the same long-name if they were not explicitly set
// via cmd line
func injectViper(cmdViper *viper.Viper, cmd *cobra.Command) {
	cmd.Flags().VisitAll(func(f *pflag.Flag) {
		if !f.Changed {
			if cmdViper.IsSet(f.Name) {
				cmd.Flags().Set(f.Name, cmdViper.GetString(f.Name))
			}
		}
	})```

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with Cobra's PersistentPreRun hook and the cmd.Flags().VisitAll path shown in the issue. Review how explicitly changed flags and Viper values are expected to interact, then clarify whether the result should be a utility function or an integrated feature; done means an agreed scope and behavior, including the noted lack of dynamic reloading.

Written by the indexing model from the issue text.

Assessment

Tech stack
go
Domain
cli
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.