Skip to content

Commit ad2598e

Browse files
committed
Inline encode/decode in config
1 parent 451b4a1 commit ad2598e

2 files changed

Lines changed: 5 additions & 59 deletions

File tree

‎config/config.go‎

Lines changed: 5 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import (
44
"encoding/json"
55
"errors"
66
"fmt"
7-
"io"
87
"os"
98
"path/filepath"
109
"runtime"
@@ -102,11 +101,8 @@ func (c *Config) Write() error {
102101
}
103102
defer f.Close()
104103

105-
err = c.Encode(f)
106-
if err != nil {
107-
return err
108-
}
109-
return nil
104+
e := json.NewEncoder(f)
105+
return e.Encode(c)
110106
}
111107

112108
// Read loads the config from the stored JSON file.
@@ -131,28 +127,13 @@ func Read(file string) (*Config, error) {
131127
}
132128
defer f.Close()
133129

134-
c, err := Decode(f)
135-
if err != nil {
136-
return nil, err
137-
}
138-
c.SavePath(file)
139-
return c, nil
140-
}
141-
142-
// Encode writes a Config into JSON format.
143-
func (c *Config) Encode(w io.Writer) error {
144-
e := json.NewEncoder(w)
145-
return e.Encode(c)
146-
}
147-
148-
// Decode loads a Config from JSON format.
149-
func Decode(r io.Reader) (*Config, error) {
150-
d := json.NewDecoder(r)
151130
var c *Config
152-
err := d.Decode(&c)
131+
d := json.NewDecoder(f)
132+
err = d.Decode(&c)
153133
if err != nil {
154134
return c, err
155135
}
136+
c.SavePath(file)
156137
c.configure()
157138
return c, nil
158139
}

‎config/config_test.go‎

Lines changed: 0 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package config
22

33
import (
4-
"bytes"
54
"fmt"
65
"io/ioutil"
76
"strings"
@@ -96,37 +95,3 @@ func TestReadingWritingConfig(t *testing.T) {
9695
assert.Equal(t, c1.Dir, c2.Dir)
9796
assert.Equal(t, c1.Hostname, c2.Hostname)
9897
}
99-
100-
func TestDecodingConfig(t *testing.T) {
101-
unsanitizedJSON := `{"apiKey":"MyKey ","exercismDirectory":"/exercism/directory\r\n","hostname":"localhost \r\n"}`
102-
c1 := &Config{
103-
APIKey: "MyKey",
104-
Dir: "/exercism/directory",
105-
Hostname: "localhost",
106-
}
107-
b := bytes.NewBufferString(unsanitizedJSON)
108-
c2, err := Decode(b)
109-
assert.NoError(t, err)
110-
111-
assert.Equal(t, c1.APIKey, c2.APIKey)
112-
assert.Equal(t, c1.Dir, c2.Dir)
113-
assert.Equal(t, c1.Hostname, c2.Hostname)
114-
}
115-
116-
func TestEncodingConfig(t *testing.T) {
117-
c := Config{
118-
APIKey: "MyKey ",
119-
Dir: "/home/user name ",
120-
Hostname: "localhost ",
121-
ProblemsHost: " localhost:9292 ",
122-
}
123-
c.configure()
124-
sanitizedJSON := `{"apiKey":"MyKey","exercismDirectory":"/home/user name","hostname":"localhost","problemsHost":"localhost:9292"}
125-
`
126-
127-
buf := new(bytes.Buffer)
128-
err := c.Encode(buf)
129-
130-
assert.NoError(t, err)
131-
assert.Equal(t, sanitizedJSON, buf.String())
132-
}

0 commit comments

Comments
 (0)