Skip to content

Commit

Permalink
refactor: ensure Viper is initialized only once
Browse files Browse the repository at this point in the history
Before this change we have two separate methods, one for initializing
Viper - InitViper, and another to retrieve it - GetViper. This may lead
to either Viper not being initiated, thus leading to nil pointer
dereference error or initializing more than once.

After this change, we will ensure Viper is initialized only once.

Signed-off-by: Maciej Szulik <[email protected]>
  • Loading branch information
soltysh committed Dec 18, 2024
1 parent d090622 commit 6e1e271
Show file tree
Hide file tree
Showing 4 changed files with 9 additions and 10 deletions.
13 changes: 6 additions & 7 deletions src/cmd/common/viper.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,13 +116,8 @@ var (
vConfigError error
)

// InitViper initializes the viper singleton for the CLI
func InitViper() *viper.Viper {
// Already initialized by some other command
if v != nil {
return v
}

// initializes the viper singleton for the CLI
func initViper() *viper.Viper {
v = viper.New()

// Skip for vendor-only commands or the version command
Expand Down Expand Up @@ -159,6 +154,10 @@ func InitViper() *viper.Viper {

// GetViper returns the viper singleton
func GetViper() *viper.Viper {
if v == nil {
v = initViper()
}

return v
}

Expand Down
2 changes: 1 addition & 1 deletion src/cmd/initialize.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func NewInitCommand() *cobra.Command {
RunE: o.Run,
}

v := common.InitViper()
v := common.GetViper()

// Init package variable defaults that are non-zero values
// NOTE: these are not in common.setDefaults so that zarf tools update-creds does not erroneously update values back to the default
Expand Down
2 changes: 1 addition & 1 deletion src/cmd/package.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func NewPackageCommand() *cobra.Command {
Short: lang.CmdPackageShort,
}

v := common.InitViper()
v := common.GetViper()

persistentFlags := cmd.PersistentFlags()
persistentFlags.IntVar(&config.CommonOptions.OCIConcurrency, "oci-concurrency", v.GetInt(common.VPkgOCIConcurrency), lang.CmdPackageFlagConcurrency)
Expand Down
2 changes: 1 addition & 1 deletion src/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ func init() {
return
}

v := common.InitViper()
v := common.GetViper()

// Logs
rootCmd.PersistentFlags().StringVarP(&LogLevelCLI, "log-level", "l", v.GetString(common.VLogLevel), lang.RootCmdFlagLogLevel)
Expand Down

0 comments on commit 6e1e271

Please sign in to comment.