@@ -70,30 +70,42 @@ var ConfigKeys = []string{
7070 SKECustomEndpointKey ,
7171}
7272
73+ var folderPath string
74+
7375func InitConfig () {
7476 home , err := os .UserHomeDir ()
7577 cobra .CheckErr (err )
7678 configFolderPath := filepath .Join (home , configFolder )
7779 configFilePath := filepath .Join (configFolderPath , fmt .Sprintf ("%s.%s" , configFileName , configFileExtension ))
7880
79- viper .SetConfigName (configFileName )
80- viper .SetConfigType (configFileExtension )
81- viper .AddConfigPath (configFolderPath )
81+ // Write config dir path to global variable
82+ folderPath = configFolderPath
8283
83- err = createFolderIfNotExists (configFolderPath )
84- cobra .CheckErr (err )
85- err = createFileIfNotExists (configFilePath )
86- cobra .CheckErr (err )
84+ // This hack is required to allow creating the config file with `viper.WriteConfig`
85+ // see https://github.com/spf13/viper/issues/851#issuecomment-789393451
86+ viper .SetConfigFile (configFilePath )
87+
88+ f , err := os .Open (configFilePath )
89+ if ! os .IsNotExist (err ) {
90+ if err := viper .ReadConfig (f ); err != nil {
91+ cobra .CheckErr (err )
92+ }
93+ }
94+ defer func () {
95+ if f != nil {
96+ if err := f .Close (); err != nil {
97+ cobra .CheckErr (err )
98+ }
99+ }
100+ }()
87101
88- err = viper .ReadInConfig ()
89- cobra .CheckErr (err )
90102 setConfigDefaults ()
91103
92104 viper .AutomaticEnv ()
93105 viper .SetEnvPrefix ("stackit" )
94106}
95107
96- func createFolderIfNotExists (folderPath string ) error {
108+ func createFolderIfNotExists () error {
97109 _ , err := os .Stat (folderPath )
98110 if os .IsNotExist (err ) {
99111 err := os .MkdirAll (folderPath , os .ModePerm )
@@ -106,17 +118,12 @@ func createFolderIfNotExists(folderPath string) error {
106118 return nil
107119}
108120
109- func createFileIfNotExists (filePath string ) error {
110- _ , err := os .Stat (filePath )
111- if os .IsNotExist (err ) {
112- err := viper .SafeWriteConfigAs (filePath )
113- if err != nil {
114- return err
115- }
116- } else if err != nil {
117- return err
121+ // Write saves the config file (wrapping `viper.WriteConfig`) and ensures that its directory exists
122+ func Write () error {
123+ if err := createFolderIfNotExists (); err != nil {
124+ return fmt .Errorf ("create config directory: %w" , err )
118125 }
119- return nil
126+ return viper . WriteConfig ()
120127}
121128
122129// All config keys should be set to a default value so that they can be set as an environment variable
0 commit comments