hugo-obsidian/main.go

102 lines
2.0 KiB
Go
Raw Normal View History

2021-07-17 06:26:40 +03:00
package main
import (
"fmt"
md "github.com/nikitavoloboev/markdown-parser"
"io/fs"
"io/ioutil"
"path/filepath"
2021-07-17 06:32:47 +03:00
"strings"
2021-07-17 06:26:40 +03:00
)
type Link struct {
Source string
Target string
Text string
}
2021-07-17 07:01:08 +03:00
type LinkTable = map[string][]Link
type Index struct {
Links LinkTable
Backlinks LinkTable
}
2021-07-17 06:32:47 +03:00
func trim(source, prefix, suffix string) string {
return strings.TrimPrefix(strings.TrimSuffix(source, suffix), prefix)
}
// parse single file for links
func parse(dir, pathPrefix string) []Link {
2021-07-17 06:26:40 +03:00
// read file
bytes, err := ioutil.ReadFile(dir)
if err != nil {
panic(err)
}
// parse md
var links []Link
2021-07-17 07:01:08 +03:00
//fmt.Printf("%s \n", trim(dir, pathPrefix, ".md"))
2021-07-17 06:26:40 +03:00
for text, target := range md.GetAllLinks(string(bytes)) {
2021-07-17 07:01:08 +03:00
//fmt.Printf(" %s -> %s \n", text, target)
2021-07-17 06:26:40 +03:00
links = append(links, Link{
2021-07-17 06:32:47 +03:00
Source: trim(dir, pathPrefix, ".md"),
2021-07-17 06:26:40 +03:00
Target: target,
Text: text,
})
}
return links
}
2021-07-17 06:32:47 +03:00
// recursively walk directory and return all files with given extension
2021-07-17 07:01:08 +03:00
func walk(root, ext string) (res []Link) {
err := filepath.WalkDir(root, func(s string, d fs.DirEntry, e error) error {
2021-07-17 06:26:40 +03:00
if e != nil {
return e
}
if filepath.Ext(d.Name()) == ext {
2021-07-17 07:01:08 +03:00
res = append(res, parse(s, root)...)
2021-07-17 06:26:40 +03:00
}
return nil
})
2021-07-17 07:01:08 +03:00
if err != nil {
panic(err)
}
return res
}
// constructs index from links
func index(links []Link) (index Index) {
linkMap := make(map[string][]Link)
backlinkMap := make(map[string][]Link)
for _, l := range links {
bl := Link{
Source: l.Target,
Target: l.Source,
Text: l.Text,
}
// map has link
if val, ok := backlinkMap[l.Target]; ok {
val = append(val, bl)
} else {
backlinkMap[l.Target] = []Link{bl}
}
if val, ok := linkMap[l.Source]; ok {
val = append(val, l)
} else {
linkMap[l.Target] = []Link{l}
}
}
index.Links = linkMap
index.Backlinks = backlinkMap
return index
2021-07-17 06:26:40 +03:00
}
func main() {
2021-07-17 07:01:08 +03:00
l := walk("../www/content", ".md")
i := index(l)
fmt.Printf("%+v", i.Links["/toc/cognitive-sciences"])
fmt.Printf("%+v", i.Backlinks["/toc/cognitive-sciences"])
2021-07-17 06:26:40 +03:00
}