@@ -47,45 +47,57 @@ func InitFromPath(path string) error {
4747}
4848
4949func Init () error {
50- // Reuse the same ordered path resolution used by ConfigFilePath.
51- existingPath , found , err := firstExistingConfigPath ()
50+ viper .Reset ()
51+ setDefaults ()
52+ viper .SetConfigName (configName )
53+ viper .SetConfigType (configType )
54+
55+ dirs , err := configSearchDirs ()
5256 if err != nil {
5357 return err
5458 }
55- if found {
56- return loadConfig ( existingPath )
59+ for _ , dir := range dirs {
60+ viper . AddConfigPath ( dir )
5761 }
5862
59- // No config found anywhere, create one using creation policy.
60- creationDir , err := configCreationDir ()
61- if err != nil {
62- return err
63- }
63+ if err := viper . ReadInConfig (); err != nil {
64+ var notFoundErr viper. ConfigFileNotFoundError
65+ if ! errors . As ( err , & notFoundErr ) {
66+ return fmt . Errorf ( "failed to read config file: %w" , err )
67+ }
6468
65- if err := os .MkdirAll (creationDir , 0755 ); err != nil {
66- return fmt .Errorf ("failed to create config directory: %w" , err )
67- }
69+ // No config found anywhere, create one using creation policy.
70+ creationDir , err := configCreationDir ()
71+ if err != nil {
72+ return err
73+ }
6874
69- configPath := filepath .Join (creationDir , userConfigFileName )
70- f , err := os .OpenFile (configPath , os .O_WRONLY | os .O_CREATE | os .O_EXCL , 0644 )
71- if err != nil {
72- if errors .Is (err , os .ErrExist ) {
73- return loadConfig (configPath )
75+ if err := os .MkdirAll (creationDir , 0755 ); err != nil {
76+ return fmt .Errorf ("failed to create config directory: %w" , err )
77+ }
78+
79+ configPath := filepath .Join (creationDir , configFileName )
80+ f , err := os .OpenFile (configPath , os .O_WRONLY | os .O_CREATE | os .O_EXCL , 0644 )
81+ if err != nil {
82+ if errors .Is (err , os .ErrExist ) {
83+ return loadConfig (configPath )
84+ }
85+ return fmt .Errorf ("failed to create config file: %w" , err )
86+ }
87+ _ , writeErr := f .WriteString (defaultConfigTemplate )
88+ closeErr := f .Close ()
89+ if writeErr != nil {
90+ _ = os .Remove (configPath )
91+ return fmt .Errorf ("failed to write config file: %w" , writeErr )
92+ }
93+ if closeErr != nil {
94+ _ = os .Remove (configPath )
95+ return fmt .Errorf ("failed to close config file: %w" , closeErr )
7496 }
75- return fmt .Errorf ("failed to create config file: %w" , err )
76- }
77- _ , writeErr := f .WriteString (defaultConfigTemplate )
78- closeErr := f .Close ()
79- if writeErr != nil {
80- _ = os .Remove (configPath )
81- return fmt .Errorf ("failed to write config file: %w" , writeErr )
82- }
83- if closeErr != nil {
84- _ = os .Remove (configPath )
85- return fmt .Errorf ("failed to close config file: %w" , closeErr )
86- }
8797
88- return loadConfig (configPath )
98+ return loadConfig (configPath )
99+ }
100+ return nil
89101}
90102
91103func resolvedConfigPath () string {
0 commit comments