Parse multiple links from one line
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Peter Stuifzand 2020-05-16 22:15:36 +02:00
parent 3301732248
commit 465ebcb8cb
2 changed files with 50 additions and 13 deletions

34
util.go
View File

@ -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

29
util_test.go Normal file
View File

@ -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")
}
}