Skip to content

Commit 63049a9

Browse files
committed
Merge pull request #151 from lcowell/master
Expand '~' to user home in config file path
2 parents b45a695 + fad1195 commit 63049a9

3 files changed

Lines changed: 53 additions & 12 deletions

File tree

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
----------------
44

5+
* [#151](https://github.com/exercism/cli/pull/151): Expand '~' in config path to home directory - @lcowell
56
* Your contribution here
67

78
## v1.9.2 (Jan 11, 2015)

config/config.go

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -110,32 +110,43 @@ func (c *Config) Update(key, host, dir, xapi string) {
110110
c.configure()
111111
}
112112

113+
// Expand takes inputs for a config file location and builds an absolute path.
114+
func Expand(path, env, home string) string {
115+
if path == "" {
116+
path = env
117+
}
118+
119+
if path != "" && path[0] == '~' {
120+
path = strings.Replace(path, "~/", fmt.Sprintf("%s/", home), 1)
121+
}
122+
123+
if path == "" {
124+
path = filepath.Join(home, File)
125+
}
126+
127+
return path
128+
}
129+
113130
// Read loads the config from the stored JSON file.
114131
func (c *Config) Read(file string) error {
115132
renameLegacy()
116133

117-
if file == "" {
118-
file = os.Getenv(fileEnvKey)
134+
home, err := c.homeDir()
135+
if err != nil {
136+
return err
119137
}
120138

121-
if file == "" {
122-
home, err := c.homeDir()
123-
if err != nil {
124-
return err
125-
}
126-
file = filepath.Join(home, File)
127-
}
139+
c.File = Expand(file, os.Getenv(fileEnvKey), home)
128140

129-
c.File = file
130-
if _, err := os.Stat(file); err != nil {
141+
if _, err := os.Stat(c.File); err != nil {
131142
if os.IsNotExist(err) {
132143
c.configure()
133144
return nil
134145
}
135146
return err
136147
}
137148

138-
f, err := os.Open(file)
149+
f, err := os.Open(c.File)
139150
if err != nil {
140151
return err
141152
}

config/config_test.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,35 @@ func TestExpandHomeDir(t *testing.T) {
4242
assert.Equal(t, "/home/alice/practice", c.Dir)
4343
}
4444

45+
func TestExpandConfigPath(t *testing.T) {
46+
testCases := []struct {
47+
path string
48+
env string
49+
result string
50+
}{
51+
{
52+
"path/to/config.json",
53+
"",
54+
"path/to/config.json",
55+
},
56+
{
57+
"",
58+
"~/config.json",
59+
"/home/alice/config.json",
60+
},
61+
{
62+
"",
63+
"",
64+
"/home/alice/.exercism.json",
65+
},
66+
}
67+
home := "/home/alice"
68+
69+
for _, tt := range testCases {
70+
assert.Equal(t, Expand(tt.path, tt.env, home), tt.result)
71+
}
72+
}
73+
4574
func TestSanitizeWhitespace(t *testing.T) {
4675
c := &Config{
4776
APIKey: " abc123\n\r\n ",

0 commit comments

Comments
 (0)