wiki/util.go
Peter Stuifzand 86f4d68d9c
Some checks failed
continuous-integration/drone/push Build is failing
Show more information in back references
2020-05-16 21:02:19 +02:00

65 lines
1.2 KiB
Go

package main
import (
"log"
"math/rand"
"regexp"
"strings"
"time"
)
type ParsedLink struct {
Name string
PageName string
Line string
}
var random *rand.Rand
func init() {
random = rand.New(rand.NewSource(time.Now().UnixNano()))
}
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
func RandStringBytes(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))]
}
return string(b)
}
func ParseLinks(content string) ([]ParsedLink, error) {
hrefRE := regexp.MustCompile(`(?m)^(.*(#?\[\[\s*([^\]]+)\s*\]\]).*)$`)
links := hrefRE.FindAllStringSubmatch(content, -1)
var result []ParsedLink
for _, matches := range links {
link := matches[2]
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, matches[0]})
}
return result, nil
}
func cleanNameURL(name string) string {
return strings.Replace(name, " ", "_", -1)
}
func cleanTitle(name string) string {
return strings.Replace(name, "_", " ", -1)
}