Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 41 additions & 1 deletion config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,30 @@ func New(key, host, dir string) (*Config, error) {
return c.configure()
}

func AddValues(filename, key, host, dir string) (*Config, error) {
c, err := Read(filename)
if err != nil {
return c, err
}

if key != "" {
c.APIKey = key
}

if host != "" {
c.API = host
}

if dir != "" {
err = c.setDir(dir)
if err != nil {
return c, err
}
}

return c, nil
}

// Read loads the config from the stored JSON file.
func (c *Config) Read(file string) error {
renameLegacy()
Expand Down Expand Up @@ -187,10 +211,26 @@ func (c *Config) configure() (*Config, error) {
if c.Dir == "" {
c.Dir = filepath.Join(dir, DirExercises)
}
c.Dir = strings.Replace(c.Dir, "~/", fmt.Sprintf("%s/", dir), 1)

err = c.setDir(c.Dir)
if err != nil {
return c, err
}

return c, nil
}

func (c *Config) setDir(dir string) error {
homeDir, err := c.homeDir()
if err != nil {
return err
}

c.Dir = strings.Replace(dir, "~/", fmt.Sprintf("%s/", homeDir), 1)

return nil
}

// FilePath returns the path to the config file.
func FilePath(file string) (string, error) {
if file != "" {
Expand Down
21 changes: 21 additions & 0 deletions config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,27 @@ func TestReadingWritingConfig(t *testing.T) {
assert.Equal(t, c1.API, c2.API)
}

func TestAddingNewValues(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "")
assert.NoError(t, err)

filename := fmt.Sprintf("%s/%s", tmpDir, File)

c1 := &Config{
APIKey: "MyKey",
Dir: "/exercism/directory",
API: "localhost",
}
c1.configure()
c1.SavePath(filename)
c1.Write()

c2, err := AddValues(filename, "NewKey", "", "")
assert.Equal(t, "NewKey", c2.APIKey)
assert.Equal(t, c1.API, c2.API)
assert.Equal(t, c1.Dir, c2.Dir)
}

func TestReadDefaultConfig(t *testing.T) {
dir, err := filepath.Abs("../fixtures/home")
assert.NoError(t, err)
Expand Down