diff --git a/parser/parser.go b/parser/parser.go new file mode 100644 index 0000000..4e4f655 --- /dev/null +++ b/parser/parser.go @@ -0,0 +1,42 @@ +package parser + +import ( + "bufio" + "encoding/csv" + "io" + "os" +) + +type Site struct { + Name string + URL string +} + +func Parse(file string) ([]*Site, error) { + f, err := os.Open(file) + if err != nil { + return nil, err + } + + r := csv.NewReader(bufio.NewReader(f)) + return parse(r) +} + +func parse(r *csv.Reader) ([]*Site, error) { + var sites []*Site + + for { + line, err := r.Read() + if err == io.EOF { + break + } + + if err != nil { + return nil, err + } + + sites = append(sites, &Site{Name: line[0], URL: line[1]}) + } + + return sites, nil +} diff --git a/parser/parser_test.go b/parser/parser_test.go new file mode 100644 index 0000000..f782a63 --- /dev/null +++ b/parser/parser_test.go @@ -0,0 +1,73 @@ +package parser + +import ( + "encoding/csv" + "strings" + "testing" +) + +func TestParse(t *testing.T) { + tt := []struct { + name string + input string + expectedResult []*Site + }{ + { + name: "one line", + input: "500px,https://500px.com/", + expectedResult: []*Site{ + { + Name: "500px", + URL: "https://500px.com/", + }, + }, + }, + { + name: "multiple lines", + input: "500px,https://500px.com/\nGoogle,https://google.com\nGitHub,https://github.com", + expectedResult: []*Site{ + { + Name: "500px", + URL: "https://500px.com/", + }, + { + Name: "Google", + URL: "https://google.com", + }, + { + Name: "GitHub", + URL: "https://github.com", + }, + }, + }, + { + name: "empty", + input: "", + expectedResult: []*Site{}, + }, + } + + for _, tc := range tt { + t.Run(tc.name, func(t *testing.T) { + r := csv.NewReader(strings.NewReader(tc.input)) + sites, err := parse(r) + if err != nil { + t.Fatalf("while parsing csv input: %v", err) + } + + if len(sites) != len(tc.expectedResult) { + t.Fatalf("expected len of parsed sites to be %v. got=%v", len(tc.expectedResult), len(sites)) + } + + for i, es := range tc.expectedResult { + if sites[i].Name != es.Name { + t.Fatalf("expected a parsed site called %q. got a site called %q", es.Name, sites[i].Name) + } + + if sites[i].URL != es.URL { + t.Fatalf("expected a parsed site with URL %q. got a site with URL %q", es.URL, sites[i].URL) + } + } + }) + } +}