Skip to content

Commit 3977a47

Browse files
committed
Change how config file path is initialized
1 parent 90300e9 commit 3977a47

File tree

6 files changed

+89
-50
lines changed

6 files changed

+89
-50
lines changed

cli/config/dump.go

-17
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ package config
1818
import (
1919
"os"
2020

21-
"github.com/arduino/arduino-cli/cli/errorcodes"
2221
"github.com/arduino/arduino-cli/cli/feedback"
2322
"github.com/sirupsen/logrus"
2423
"github.com/spf13/cobra"
@@ -60,21 +59,5 @@ func (dr dumpResult) String() string {
6059

6160
func runDumpCommand(cmd *cobra.Command, args []string) {
6261
logrus.Info("Executing `arduino config dump`")
63-
64-
configFlag := cmd.InheritedFlags().Lookup("config-file")
65-
configFile := ""
66-
if configFlag != nil {
67-
configFile = configFlag.Value.String()
68-
}
69-
70-
if configFile != "" {
71-
viper.SetConfigFile(configFile)
72-
err := viper.MergeInConfig()
73-
if err != nil {
74-
feedback.Errorf("Error reading config file: %s", configFile)
75-
os.Exit(errorcodes.ErrBadArgument)
76-
}
77-
}
78-
7962
feedback.PrintResult(dumpResult{viper.AllSettings()})
8063
}

cli/config/init.go

+13-14
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,11 @@ import (
2626
"github.com/spf13/viper"
2727
)
2828

29-
var destDir string
30-
var overwrite bool
29+
var (
30+
destDir string
31+
destFile string
32+
overwrite bool
33+
)
3134

3235
const defaultFileName = "arduino-cli.yaml"
3336

@@ -38,25 +41,21 @@ func initInitCommand() *cobra.Command {
3841
Long: "Creates or updates the configuration file in the data directory or custom directory with the current configuration settings.",
3942
Example: "" +
4043
" # Writes current configuration to the configuration file in the data directory.\n" +
41-
" " + os.Args[0] + " config init",
44+
" " + os.Args[0] + " config init" +
45+
" " + os.Args[0] + " config init --dest-dir /home/user/MyDirectory" +
46+
" " + os.Args[0] + " config init --dest-file /home/user/MyDirectory/my_settings.yaml",
4247
Args: cobra.NoArgs,
4348
Run: runInitCommand,
4449
}
4550
initCommand.Flags().StringVar(&destDir, "dest-dir", "", "Sets where to save the configuration file.")
51+
initCommand.Flags().StringVar(&destFile, "dest-file", "", "Sets where to save the configuration file.")
4652
initCommand.Flags().BoolVar(&overwrite, "overwrite", false, "Overwrite existing config file.")
4753
return initCommand
4854
}
4955

5056
func runInitCommand(cmd *cobra.Command, args []string) {
51-
configFlag := cmd.InheritedFlags().Lookup("config-file")
52-
configFilePath := ""
53-
54-
if configFlag != nil {
55-
configFilePath = configFlag.Value.String()
56-
}
57-
58-
if configFilePath != "" && destDir != "" {
59-
feedback.Errorf("Can't use both --config-file and --dest-dir flags at the same time.")
57+
if destFile != "" && destDir != "" {
58+
feedback.Errorf("Can't use both --dest-file and --dest-dir flags at the same time.")
6059
os.Exit(errorcodes.ErrGeneric)
6160
}
6261

@@ -65,8 +64,8 @@ func runInitCommand(cmd *cobra.Command, args []string) {
6564
var err error
6665

6766
switch {
68-
case configFilePath != "":
69-
configFileAbsPath, err = paths.New(configFilePath).Abs()
67+
case destFile != "":
68+
configFileAbsPath, err = paths.New(destFile).Abs()
7069
if err != nil {
7170
feedback.Errorf("Cannot find absolute path: %v", err)
7271
os.Exit(errorcodes.ErrGeneric)

configuration/configuration.go

+29-9
Original file line numberDiff line numberDiff line change
@@ -35,15 +35,21 @@ import (
3535
func Init(configPath string) {
3636
// Config file metadata
3737
jww.SetStdoutThreshold(jww.LevelFatal)
38-
viper.SetConfigName("arduino-cli")
38+
39+
configDir := paths.New(configPath)
40+
if configDir != nil && !configDir.IsDir() {
41+
viper.SetConfigName(strings.TrimSuffix(configDir.Base(), configDir.Ext()))
42+
} else {
43+
viper.SetConfigName("arduino-cli")
44+
}
3945

4046
// Get default data path if none was provided
4147
if configPath == "" {
4248
configPath = getDefaultArduinoDataDir()
4349
}
4450

4551
// Add paths where to search for a config file
46-
viper.AddConfigPath(configPath)
52+
viper.AddConfigPath(filepath.Dir(configPath))
4753

4854
// Bind env vars
4955
viper.SetEnvPrefix("ARDUINO")
@@ -185,23 +191,37 @@ func IsBundledInDesktopIDE() bool {
185191
}
186192

187193
// FindConfigFile returns the config file path using the argument '--config-file' if specified or via the current working dir
188-
func FindConfigFile() string {
189-
194+
func FindConfigFile(args []string) string {
190195
configFile := ""
191-
for i, arg := range os.Args {
196+
for i, arg := range args {
192197
// 0 --config-file ss
193198
if arg == "--config-file" {
194-
if len(os.Args) > i+1 {
195-
configFile = os.Args[i+1]
199+
if len(args) > i+1 {
200+
configFile = args[i+1]
196201
}
197202
}
198203
}
199204

200205
if configFile != "" {
201-
return filepath.Dir(configFile)
206+
return configFile
207+
}
208+
209+
return searchCwdForConfig()
210+
}
211+
212+
func searchCwdForConfig() string {
213+
cwd, err := os.Getwd()
214+
215+
if err != nil {
216+
return ""
217+
}
218+
219+
configFile := searchConfigTree(cwd)
220+
if configFile == "" {
221+
return configFile
202222
}
203223

204-
return ""
224+
return configFile + string(os.PathSeparator) + "arduino-cli.yaml"
205225
}
206226

207227
func searchConfigTree(cwd string) string {

configuration/configuration_test.go

+37
Original file line numberDiff line numberDiff line change
@@ -71,3 +71,40 @@ func BenchmarkSearchConfigTree(b *testing.B) {
7171
}
7272
result = s
7373
}
74+
75+
func TestFindConfigFile(t *testing.T) {
76+
configFile := FindConfigFile([]string{"--config-file"})
77+
require.Equal(t, "", configFile)
78+
79+
configFile = FindConfigFile([]string{"--config-file", "some/path/to/config"})
80+
require.Equal(t, "some/path/to/config", configFile)
81+
82+
configFile = FindConfigFile([]string{"--config-file", "some/path/to/config/arduino-cli.yaml"})
83+
require.Equal(t, "some/path/to/config/arduino-cli.yaml", configFile)
84+
85+
configFile = FindConfigFile([]string{})
86+
require.Equal(t, "", configFile)
87+
88+
// Create temporary directories
89+
tmp := tmpDirOrDie()
90+
defer os.RemoveAll(tmp)
91+
target := filepath.Join(tmp, "foo", "bar", "baz")
92+
os.MkdirAll(target, os.ModePerm)
93+
require.Nil(t, os.Chdir(target))
94+
95+
// Create a config file
96+
f, err := os.Create(filepath.Join(target, "..", "..", "arduino-cli.yaml"))
97+
require.Nil(t, err)
98+
f.Close()
99+
100+
configFile = FindConfigFile([]string{})
101+
require.Equal(t, filepath.Join(tmp, "foo", "arduino-cli.yaml"), configFile)
102+
103+
// Create another config file
104+
f, err = os.Create(filepath.Join(target, "arduino-cli.yaml"))
105+
require.Nil(t, err)
106+
f.Close()
107+
108+
configFile = FindConfigFile([]string{})
109+
require.Equal(t, filepath.Join(target, "arduino-cli.yaml"), configFile)
110+
}

main.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ import (
2525
)
2626

2727
func main() {
28-
configuration.Init(configuration.FindConfigFile())
28+
configuration.Init(configuration.FindConfigFile(os.Args))
2929
i18n.Init()
3030
arduinoCmd := cli.NewCommand()
3131
if err := arduinoCmd.Execute(); err != nil {

test/test_config.py

+9-9
Original file line numberDiff line numberDiff line change
@@ -62,15 +62,15 @@ def test_init_dest_flag_with_overwrite_flag(run_command, working_dir):
6262

6363

6464
def test_init_dest_and_config_file_flags(run_command, working_dir):
65-
result = run_command('config init --config-file "some_other_path" --dest-dir "some_path"')
65+
result = run_command('config init --dest-file "some_other_path" --dest-dir "some_path"')
6666
assert result.failed
67-
assert "Can't use both --config-file and --dest-dir flags at the same time." in result.stderr
67+
assert "Can't use both --dest-file and --dest-dir flags at the same time." in result.stderr
6868

6969

7070
def test_init_config_file_flag_absolute_path(run_command, working_dir):
7171
config_file = Path(working_dir) / "config" / "test" / "config.yaml"
7272
assert not config_file.exists()
73-
result = run_command(f'config init --config-file "{config_file}"')
73+
result = run_command(f'config init --dest-file "{config_file}"')
7474
assert result.ok
7575
assert str(config_file) in result.stdout
7676
assert config_file.exists()
@@ -79,7 +79,7 @@ def test_init_config_file_flag_absolute_path(run_command, working_dir):
7979
def test_init_config_file_flag_relative_path(run_command, working_dir):
8080
config_file = Path(working_dir) / "config.yaml"
8181
assert not config_file.exists()
82-
result = run_command('config init --config-file "config.yaml"')
82+
result = run_command('config init --dest-file "config.yaml"')
8383
assert result.ok
8484
assert str(config_file) in result.stdout
8585
assert config_file.exists()
@@ -89,15 +89,15 @@ def test_init_config_file_flag_with_overwrite_flag(run_command, working_dir):
8989
config_file = Path(working_dir) / "config" / "test" / "config.yaml"
9090
assert not config_file.exists()
9191

92-
result = run_command(f'config init --config-file "{config_file}"')
92+
result = run_command(f'config init --dest-file "{config_file}"')
9393
assert result.ok
9494
assert config_file.exists()
9595

96-
result = run_command(f'config init --config-file "{config_file}"')
96+
result = run_command(f'config init --dest-file "{config_file}"')
9797
assert result.failed
9898
assert "Config file already exists, use --overwrite to discard the existing one." in result.stderr
9999

100-
result = run_command(f'config init --config-file "{config_file}" --overwrite')
100+
result = run_command(f'config init --dest-file "{config_file}" --overwrite')
101101
assert result.ok
102102
assert str(config_file) in result.stdout
103103

@@ -106,7 +106,7 @@ def test_dump(run_command, working_dir):
106106
# Create a config file first
107107
config_file = Path(working_dir) / "config" / "test" / "config.yaml"
108108
assert not config_file.exists()
109-
result = run_command(f'config init --config-file "{config_file}"')
109+
result = run_command(f'config init --dest-file "{config_file}"')
110110
assert result.ok
111111
assert config_file.exists()
112112

@@ -120,7 +120,7 @@ def test_dump_with_config_file_flag(run_command, working_dir):
120120
# Create a config file first
121121
config_file = Path(working_dir) / "config" / "test" / "config.yaml"
122122
assert not config_file.exists()
123-
result = run_command(f'config init --config-file "{config_file}" --additional-urls=https://example.com')
123+
result = run_command(f'config init --dest-file "{config_file}" --additional-urls=https://example.com')
124124
assert result.ok
125125
assert config_file.exists()
126126

0 commit comments

Comments
 (0)