Improve config file parsing

This commit is contained in:
Mislav Marohnić 2019-10-17 14:34:55 +02:00
parent c09eb742c3
commit 74c637fec8
2 changed files with 53 additions and 15 deletions

View file

@ -1,6 +1,7 @@
package context
import (
"fmt"
"io"
"io/ioutil"
"os"
@ -32,11 +33,18 @@ func parseConfig(r io.Reader) (*configEntry, error) {
if err != nil {
return nil, err
}
var entries []configEntry
// TODO: this will panic if the config is malformed
err = config.Content[0].Content[1].Decode(&entries)
if err != nil {
return nil, err
if len(config.Content) < 1 {
return nil, fmt.Errorf("malformed config")
}
return &entries[0], nil
for i := 0; i < len(config.Content[0].Content)-1; i = i + 2 {
if config.Content[0].Content[i].Value == defaultHostname {
var entries []configEntry
err = config.Content[0].Content[i+1].Decode(&entries)
if err != nil {
return nil, err
}
return &entries[0], nil
}
}
return nil, fmt.Errorf("could not find config entry for %q", defaultHostname)
}

View file

@ -1,24 +1,54 @@
package context
import (
"errors"
"reflect"
"strings"
"testing"
)
func eq(t *testing.T, got interface{}, expected interface{}) {
if !reflect.DeepEqual(got, expected) {
t.Errorf("expected: %v, got: %v", expected, got)
}
}
func Test_parseConfig(t *testing.T) {
c := strings.NewReader(`---
github.com:
- user: monalisa
oauth_token: OTOKEN
protocol: https
- user: wronguser
oauth_token: NOTTHIS
`)
entry, err := parseConfig(c)
if err != nil {
t.Error(err)
}
if entry.User != "monalisa" {
t.Errorf("got User: %q", entry.User)
}
if entry.Token != "OTOKEN" {
t.Errorf("got User: %q", entry.Token)
}
eq(t, err, nil)
eq(t, entry.User, "monalisa")
eq(t, entry.Token, "OTOKEN")
}
func Test_parseConfig_multipleHosts(t *testing.T) {
c := strings.NewReader(`---
example.com:
- user: wronguser
oauth_token: NOTTHIS
github.com:
- user: monalisa
oauth_token: OTOKEN
`)
entry, err := parseConfig(c)
eq(t, err, nil)
eq(t, entry.User, "monalisa")
eq(t, entry.Token, "OTOKEN")
}
func Test_parseConfig_notFound(t *testing.T) {
c := strings.NewReader(`---
example.com:
- user: wronguser
oauth_token: NOTTHIS
`)
_, err := parseConfig(c)
eq(t, err, errors.New(`could not find config entry for "github.com"`))
}