diff --git a/util.go b/util.go index 93a90d7..6a12d95 100644 --- a/util.go +++ b/util.go @@ -1,6 +1,7 @@ package main import ( + "bufio" "math/rand" "regexp" "strings" @@ -30,25 +31,32 @@ func RandStringBytes(n int) string { } func ParseLinks(content string) ([]ParsedLink, error) { - hrefRE := regexp.MustCompile(`(?m)^(.*(#?\[\[\s*([^\]]+)\s*\]\]).*)$`) + hrefRE := regexp.MustCompile(`(#?\[\[\s*([^\]]+)\s*\]\])`) - links := hrefRE.FindAllStringSubmatch(content, -1) + scanner := bufio.NewScanner(strings.NewReader(content)) + scanner.Split(bufio.ScanLines) var result []ParsedLink - for _, matches := range links { - link := matches[2] + for scanner.Scan() { + line := scanner.Text() - if link[0] == '#' { - link = strings.TrimPrefix(link, "#[[") - } else { - link = strings.TrimPrefix(link, "[[") + links := hrefRE.FindAllStringSubmatch(line, -1) + + for _, matches := range links { + link := matches[0] + + if link[0] == '#' { + link = strings.TrimPrefix(link, "#[[") + } else { + link = strings.TrimPrefix(link, "[[") + } + + link = strings.TrimSuffix(link, "]]") + link = strings.TrimSpace(link) + l := cleanNameURL(link) + result = append(result, ParsedLink{link, l, line}) } - - link = strings.TrimSuffix(link, "]]") - link = strings.TrimSpace(link) - l := cleanNameURL(link) - result = append(result, ParsedLink{link, l, matches[0]}) } return result, nil diff --git a/util_test.go b/util_test.go new file mode 100644 index 0000000..db1f762 --- /dev/null +++ b/util_test.go @@ -0,0 +1,29 @@ +package main + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestParseLinks(t *testing.T) { + example := "There are three types of notes and these should be kept seperate, because they have different goals. [[Fleeting notes]], [[Permanent notes]], [[Project notes]]." + + links, err := ParseLinks(example) + + if assert.NoError(t, err, "should parse example") { + assert.Len(t, links, 3, "should contain 3 links") + + assert.Equal(t, links[0].Line, "There are three types of notes and these should be kept seperate, because they have different goals. [[Fleeting notes]], [[Permanent notes]], [[Project notes]].") + assert.Equal(t, links[0].Name, "Fleeting notes") + assert.Equal(t, links[0].PageName, "Fleeting_notes") + + assert.Equal(t, links[1].Line, "There are three types of notes and these should be kept seperate, because they have different goals. [[Fleeting notes]], [[Permanent notes]], [[Project notes]].") + assert.Equal(t, links[1].Name, "Permanent notes") + assert.Equal(t, links[1].PageName, "Permanent_notes") + + assert.Equal(t, links[2].Line, "There are three types of notes and these should be kept seperate, because they have different goals. [[Fleeting notes]], [[Permanent notes]], [[Project notes]].") + assert.Equal(t, links[2].Name, "Project notes") + assert.Equal(t, links[2].PageName, "Project_notes") + } +}