1
0
mirror of https://github.com/osmarks/mycorrhiza.git synced 2024-10-30 11:46:16 +00:00

Implement wikilink util function and test it

This commit is contained in:
Timur Ismagilov 2020-07-04 18:35:06 +05:00
parent e2e25a05e7
commit fcd60f3ecb
10 changed files with 68 additions and 2 deletions

44
util/url.go Normal file
View File

@ -0,0 +1,44 @@
/* This file implements things defined by Wikilink RFC. See :main/help/wikilink
*/
package util
import (
"path"
"regexp"
"strings"
)
// `name` must be non-empty.
func sections(name string) (mycel, hyphaName string) {
mycelRe := regexp.MustCompile(`^:.*/`)
loc := mycelRe.FindIndex([]byte(name))
if loc != nil { // if has mycel
mycel = name[:loc[1]]
name = name[loc[1]:]
}
return mycel, name
}
// Wikilink processes `link` as defined by :main/help/wikilink assuming that `atHypha` is current hypha name.
func Wikilink(link, atHypha string) string {
mycel, hyphaName := sections(atHypha)
urlProtocolRe := regexp.MustCompile(`^[a-zA-Z]+:`)
switch {
case strings.HasPrefix(link, "::"):
return "/" + mycel + link[2:]
case strings.HasPrefix(link, ":"):
return "/" + link
case strings.HasPrefix(link, "../") && strings.Count(hyphaName, "/") > 0:
return "/" + path.Dir(atHypha) + "/" + link[3:]
case strings.HasPrefix(link, "../"):
return "/" + mycel + link[3:]
case strings.HasPrefix(link, "/"):
return "/" + atHypha + link
case strings.HasPrefix(link, "./"):
return "/" + atHypha + link[1:]
case urlProtocolRe.MatchString(link):
return link
default:
return "/" + link
}
}

22
util/util_test.go Normal file
View File

@ -0,0 +1,22 @@
package util
import (
"testing"
)
func TestWikilink(t *testing.T) {
atHypha := ":example/test"
results := map[string]string{
"foo": "/foo",
"::foo": "/:example/foo",
":bar/foo": "/:bar/foo",
"/baz": "/:example/test/baz",
"./baz": "/:example/test/baz",
"../qux": "/:example/qux",
}
for link, expect := range results {
if res := Wikilink(link, atHypha); expect != res {
t.Errorf("%s → %s; expected %s", link, res, expect)
}
}
}

View File

@ -40,7 +40,7 @@ wikilink actual path
foo == /foo
::foo == /:example/foo
:bar/foo == /:bar/foo
/baz == /:example/baz
./baz == /:example/baz
/baz == /:example/test/baz
./baz == /:example/test/baz
../qux == /:example/qux
```