Skip to content

Commit

Permalink
Typemap reader refactored + unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
chsc committed Nov 22, 2011
1 parent ce10943 commit 3c41569
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 11 deletions.
30 changes: 19 additions & 11 deletions tmreader.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ import (
"io"
"bufio"
"regexp"
"strings"
"fmt"
)

var (
tmEmptyRE = regexp.MustCompile("^\n")
tmCommentRE = regexp.MustCompile("^#.*")
tmTypePairRE = regexp.MustCompile("^(.+),\\*,\\*,[\\t ]*(.+),\\*,\\*")
tmEmptyOrCommentRE = regexp.MustCompile("^[ \\t]*(#.*)?$")
tmTypePairRE = regexp.MustCompile("^([A-Za-z0-9]+),\\*,\\*,[\\t ]*([A-Za-z0-9]+),\\*,\\*")
)

func ReadTypeMapFromFile(name string) (TypeMap, os.Error) {
Expand All @@ -26,18 +26,26 @@ func ReadTypeMapFromFile(name string) (TypeMap, os.Error) {
func ReadTypeMap(r io.Reader) (TypeMap, os.Error) {
tm := make(TypeMap)
br := bufio.NewReader(r)
for line, rerr := br.ReadString('\n'); rerr == nil; line, rerr = br.ReadString('\n') {
if tmEmptyRE.MatchString(line) {
continue

for {
line, err := br.ReadString('\n')
if err == os.EOF {
break
}
if tmCommentRE.FindStringSubmatch(line) != nil { // use matchstring?
continue
if err != nil {
return nil, err
}
if typePair := tmTypePairRE.FindStringSubmatch(line); typePair != nil {
line = strings.TrimRight(line, "\n")
//fmt.Println(line)

if tmEmptyOrCommentRE.MatchString(line) {
// skip
} else if typePair := tmTypePairRE.FindStringSubmatch(line); typePair != nil {
tm[typePair[1]] = typePair[2]
continue
} else {
fmt.Fprintf(os.Stderr, "Unable to parse line: %v", line)
}
fmt.Fprintf(os.Stderr, "Unable to parse line: "+line)
}

return tm, nil
}
40 changes: 40 additions & 0 deletions tmreader_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package main

import (
"testing"
"strings"
)

var testTypeMapStr =
"Test1,*,*, GLType1,*,*\n" +
"Test2,*,*, GLType2,*,*\n" +
"Test3,*,*, GLType3,*,*\n"

func checkType(tn, gltype string, tm TypeMap, t *testing.T) {
if ty, ok := tm[tn]; ok {
if ty == gltype {
t.Logf("Type found: %v::%v", tn, gltype)
return
}
t.Errorf("Type not found: %v::%v", tn, gltype)
return
}
t.Errorf("Type not found: %v", tn)
}

func TestTypeMapReader(t *testing.T) {
r := strings.NewReader(testTypeMapStr)
tm, err := ReadTypeMap(r)
if err != nil {
t.Fatalf("Read type map failed: %v", err)
}
t.Logf("%v", tm)

if len(tm) != 3 {
t.Errorf("Wrong number of types.")
}

checkType("Test1", "GLType1", tm, t)
checkType("Test2", "GLType2", tm, t)
checkType("Test3", "GLType3", tm, t)
}

0 comments on commit 3c41569

Please sign in to comment.