hugo-obsidian/write.go

69 lines
1.4 KiB
Go
Raw Permalink Normal View History

2021-12-28 00:19:05 +03:00
package main
import (
2022-02-16 03:36:14 +03:00
"encoding/json"
2021-12-28 00:19:05 +03:00
"io/ioutil"
"path"
)
func write(links []Link, contentIndex ContentIndex, toIndex bool, out string) error {
index := index(links)
resStruct := struct {
2022-02-16 03:36:14 +03:00
Index Index `json:"index"`
Links []Link `json:"links"`
2021-12-28 00:19:05 +03:00
}{
Index: index,
Links: links,
}
2022-02-16 03:36:14 +03:00
marshalledIndex, mErr := json.MarshalIndent(&resStruct, "", " ")
2021-12-28 00:19:05 +03:00
if mErr != nil {
return mErr
}
2022-02-16 03:36:14 +03:00
writeErr := ioutil.WriteFile(path.Join(out, "linkIndex.json"), marshalledIndex, 0644)
2021-12-28 00:19:05 +03:00
if writeErr != nil {
return writeErr
}
if toIndex {
2022-02-16 03:36:14 +03:00
marshalledContentIndex, mcErr := json.MarshalIndent(&contentIndex, "", " ")
2021-12-28 00:19:05 +03:00
if mcErr != nil {
return mcErr
}
2022-02-16 03:36:14 +03:00
writeErr = ioutil.WriteFile(path.Join(out, "contentIndex.json"), marshalledContentIndex, 0644)
2021-12-28 00:19:05 +03:00
if writeErr != nil {
return writeErr
}
}
return nil
}
// constructs index from links
func index(links []Link) (index Index) {
linkMap := make(map[string][]Link)
backlinkMap := make(map[string][]Link)
for _, l := range links {
// backlink (only if internal)
if _, ok := backlinkMap[l.Target]; ok {
backlinkMap[l.Target] = append(backlinkMap[l.Target], l)
} else {
backlinkMap[l.Target] = []Link{l}
}
// regular link
if _, ok := linkMap[l.Source]; ok {
linkMap[l.Source] = append(linkMap[l.Source], l)
} else {
linkMap[l.Source] = []Link{l}
}
}
index.Links = linkMap
index.Backlinks = backlinkMap
return index
}