forked from jackyzha0/hugo-obsidian
-
Notifications
You must be signed in to change notification settings - Fork 0
/
write.go
95 lines (83 loc) · 2.04 KB
/
write.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"bufio"
"encoding/json"
"io/ioutil"
"os"
"path"
)
func write(links []Link, contentIndex ContentIndex, toIndex bool, out string, root string) error {
index := index(links)
resStruct := struct {
Index Index `json:"index"`
Links []Link `json:"links"`
}{
Index: index,
Links: links,
}
marshalledIndex, mErr := json.MarshalIndent(&resStruct, "", " ")
if mErr != nil {
return mErr
}
writeErr := ioutil.WriteFile(path.Join(out, "linkIndex.json"), marshalledIndex, 0644)
if writeErr != nil {
return writeErr
}
// check whether to index content
if toIndex {
marshalledContentIndex, mcErr := json.MarshalIndent(&contentIndex, "", " ")
if mcErr != nil {
return mcErr
}
writeErr = ioutil.WriteFile(path.Join(out, "contentIndex.json"), marshalledContentIndex, 0644)
if writeErr != nil {
return writeErr
}
// write linkmap
writeErr = writeLinkMap(&contentIndex, root)
if writeErr != nil {
return writeErr
}
}
return nil
}
func writeLinkMap(contentIndex *ContentIndex, root string) error {
fp := path.Join(root, "static", "linkmap")
file, err := os.OpenFile(fp, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
datawriter := bufio.NewWriter(file)
for path := range *contentIndex {
if path == "/" {
_, _ = datawriter.WriteString("/index.html /\n")
} else {
_, _ = datawriter.WriteString(path + "/index.{html} " + path + "/\n")
}
}
datawriter.Flush()
file.Close()
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
}