@@ -19,7 +19,12 @@ package config
19
19
20
20
import (
21
21
"fmt"
22
+ "os"
23
+ "path/filepath"
24
+ "runtime"
22
25
26
+ "github.com/arduino/go-paths-helper"
27
+ "github.com/arduino/go-win32-utils"
23
28
"github.com/spf13/viper"
24
29
)
25
30
@@ -33,16 +38,61 @@ type Config struct {
33
38
// Retrieve returns the actual parameters contained in the
34
39
// configuration file, if any. Returns error if no config file is found.
35
40
func Retrieve () (* Config , error ) {
36
- conf := & Config {}
41
+ configDir , err := searchConfigDir ()
42
+ if err != nil {
43
+ return nil , fmt .Errorf ("can't get config directory: %w" , err )
44
+ }
45
+
37
46
v := viper .New ()
38
47
v .SetConfigName (Filename )
39
- v .AddConfigPath ("." )
40
- err : = v .ReadInConfig ()
48
+ v .AddConfigPath (configDir )
49
+ err = v .ReadInConfig ()
41
50
if err != nil {
42
51
err = fmt .Errorf ("%s: %w" , "retrieving config file" , err )
43
52
return nil , err
44
53
}
45
54
55
+ conf := & Config {}
46
56
v .Unmarshal (conf )
47
57
return conf , nil
48
58
}
59
+
60
+ func searchConfigDir () (string , error ) {
61
+ // Search in current directory and its parents.
62
+ if cwd , err := paths .Getwd (); err == nil {
63
+ for _ , path := range cwd .Parents () {
64
+ if path .Join (Filename + ".yaml" ).Exist () || path .Join (Filename + ".json" ).Exist () {
65
+ return path .String (), nil
66
+ }
67
+ }
68
+ }
69
+
70
+ // Search in arduino-cli's default config directory.
71
+ userHomeDir , err := os .UserHomeDir ()
72
+ if err != nil {
73
+ return "" , fmt .Errorf ("unable to get user home dir: %w" , err )
74
+ }
75
+
76
+ var path * paths.Path
77
+ switch runtime .GOOS {
78
+ case "darwin" :
79
+ path = paths .New (filepath .Join (userHomeDir , "Library" , "Arduino15" ))
80
+ case "windows" :
81
+ localAppDataPath , err := win32 .GetLocalAppDataFolder ()
82
+ if err != nil {
83
+ return "" , fmt .Errorf ("unable to get local app data folder: %w" , err )
84
+ }
85
+ path = paths .New (filepath .Join (localAppDataPath , "Arduino15" ))
86
+ default : // linux, android, *bsd, plan9 and other Unix-like systems
87
+ path = paths .New (filepath .Join (userHomeDir , ".arduino15" ))
88
+ }
89
+
90
+ if path .Join (Filename + ".yaml" ).Exist () || path .Join (Filename + ".json" ).Exist () {
91
+ return path .String (), nil
92
+ }
93
+
94
+ return "" , fmt .Errorf (
95
+ "didn't find config file in the current directory, its parents or in %s." ,
96
+ path .String (),
97
+ )
98
+ }
0 commit comments