Skip to content

Commit 0d31fc8

Browse files
committed
Merge pull request exercism#111 from jish/allow_additional_config
Allow setting additional configuration options.
2 parents a9ebe9f + c12cb2d commit 0d31fc8

2 files changed

Lines changed: 62 additions & 1 deletion

File tree

config/config.go

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,30 @@ func New(key, host, dir string) (*Config, error) {
8787
return c.configure()
8888
}
8989

90+
func AddValues(filename, key, host, dir string) (*Config, error) {
91+
c, err := Read(filename)
92+
if err != nil {
93+
return c, err
94+
}
95+
96+
if key != "" {
97+
c.APIKey = key
98+
}
99+
100+
if host != "" {
101+
c.API = host
102+
}
103+
104+
if dir != "" {
105+
err = c.setDir(dir)
106+
if err != nil {
107+
return c, err
108+
}
109+
}
110+
111+
return c, nil
112+
}
113+
90114
// Read loads the config from the stored JSON file.
91115
func (c *Config) Read(file string) error {
92116
renameLegacy()
@@ -187,10 +211,26 @@ func (c *Config) configure() (*Config, error) {
187211
if c.Dir == "" {
188212
c.Dir = filepath.Join(dir, DirExercises)
189213
}
190-
c.Dir = strings.Replace(c.Dir, "~/", fmt.Sprintf("%s/", dir), 1)
214+
215+
err = c.setDir(c.Dir)
216+
if err != nil {
217+
return c, err
218+
}
219+
191220
return c, nil
192221
}
193222

223+
func (c *Config) setDir(dir string) error {
224+
homeDir, err := c.homeDir()
225+
if err != nil {
226+
return err
227+
}
228+
229+
c.Dir = strings.Replace(dir, "~/", fmt.Sprintf("%s/", homeDir), 1)
230+
231+
return nil
232+
}
233+
194234
// FilePath returns the path to the config file.
195235
func FilePath(file string) (string, error) {
196236
if file != "" {

config/config_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,27 @@ func TestReadingWritingConfig(t *testing.T) {
9898
assert.Equal(t, c1.API, c2.API)
9999
}
100100

101+
func TestAddingNewValues(t *testing.T) {
102+
tmpDir, err := ioutil.TempDir("", "")
103+
assert.NoError(t, err)
104+
105+
filename := fmt.Sprintf("%s/%s", tmpDir, File)
106+
107+
c1 := &Config{
108+
APIKey: "MyKey",
109+
Dir: "/exercism/directory",
110+
API: "localhost",
111+
}
112+
c1.configure()
113+
c1.SavePath(filename)
114+
c1.Write()
115+
116+
c2, err := AddValues(filename, "NewKey", "", "")
117+
assert.Equal(t, "NewKey", c2.APIKey)
118+
assert.Equal(t, c1.API, c2.API)
119+
assert.Equal(t, c1.Dir, c2.Dir)
120+
}
121+
101122
func TestReadDefaultConfig(t *testing.T) {
102123
dir, err := filepath.Abs("../fixtures/home")
103124
assert.NoError(t, err)

0 commit comments

Comments
 (0)