@@ -20,6 +20,8 @@ package config
20
20
import (
21
21
"fmt"
22
22
23
+ "github.com/arduino/arduino-cloud-cli/arduino"
24
+ "github.com/arduino/go-paths-helper"
23
25
"github.com/spf13/viper"
24
26
)
25
27
@@ -33,16 +35,50 @@ type Config struct {
33
35
// Retrieve returns the actual parameters contained in the
34
36
// configuration file, if any. Returns error if no config file is found.
35
37
func Retrieve () (* Config , error ) {
36
- conf := & Config {}
38
+ configDir , err := searchConfigDir ()
39
+ if err != nil {
40
+ return nil , fmt .Errorf ("can't get config directory: %w" , err )
41
+ }
42
+
37
43
v := viper .New ()
38
44
v .SetConfigName (Filename )
39
- v .AddConfigPath ("." )
40
- err : = v .ReadInConfig ()
45
+ v .AddConfigPath (configDir )
46
+ err = v .ReadInConfig ()
41
47
if err != nil {
42
48
err = fmt .Errorf ("%s: %w" , "retrieving config file" , err )
43
49
return nil , err
44
50
}
45
51
52
+ conf := & Config {}
46
53
v .Unmarshal (conf )
47
54
return conf , nil
48
55
}
56
+
57
+ func searchConfigDir () (string , error ) {
58
+ // Search in current directory and its parents.
59
+ cwd , err := paths .Getwd ()
60
+ if err != nil {
61
+ return "" , err
62
+ }
63
+ // Don't let bad naming mislead you, cwd.Parents()[0] is cwd itself so
64
+ // we look in the current directory first and then on its parents.
65
+ for _ , path := range cwd .Parents () {
66
+ if path .Join (Filename + ".yaml" ).Exist () || path .Join (Filename + ".json" ).Exist () {
67
+ return path .String (), nil
68
+ }
69
+ }
70
+
71
+ // Search in arduino's default data directory.
72
+ arduino15 , err := arduino .DataDir ()
73
+ if err != nil {
74
+ return "" , err
75
+ }
76
+ if arduino15 .Join (Filename + ".yaml" ).Exist () || arduino15 .Join (Filename + ".json" ).Exist () {
77
+ return arduino15 .String (), nil
78
+ }
79
+
80
+ return "" , fmt .Errorf (
81
+ "didn't find config file in the current directory, its parents or in %s." ,
82
+ arduino15 .String (),
83
+ )
84
+ }
0 commit comments