forked from osuripple/hanayo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
loader.go
137 lines (113 loc) · 2.52 KB
/
loader.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
// Package doc handles documentation.
package doc
import (
"bufio"
"bytes"
"crypto/md5"
"fmt"
"io/ioutil"
"os"
"strings"
"gopkg.in/yaml.v2"
)
func init() {
// When we start the program, we should load the documentation files.
err := loadDocFiles()
if err != nil {
fmt.Println("error while loading documentation:", err)
}
}
// rawFile represents the data that may be provided at the top of files.
type rawFile struct {
Title string `yaml:"title"`
OldID int `yaml:"old_id"`
ReferenceVersion string `yaml:"reference_version"`
}
func loadDocFiles() error {
langs, err := loadLanguagesAvailable()
if err != nil {
return err
}
files, err := ioutil.ReadDir("website-docs/" + referenceLanguage)
if err != nil {
return err
}
for _, file := range files {
data, err := ioutil.ReadFile("website-docs/" + referenceLanguage + "/" + file.Name())
if err != nil {
return err
}
header := loadHeader(data)
md5sum := fmt.Sprintf("%x", md5.Sum(data))
doc := Document{
OldID: header.OldID,
Slug: strings.TrimSuffix(file.Name(), ".md"),
}
doc.Languages, err = loadLanguages(langs, file.Name(), md5sum)
if err != nil {
return err
}
docFiles = append(docFiles, doc)
}
return nil
}
func loadHeader(b []byte) rawFile {
s := bufio.NewScanner(bytes.NewReader(b))
var (
isConf bool
conf string
)
for s.Scan() {
line := s.Text()
if !isConf {
if line == "---" {
isConf = true
}
continue
}
if line == "---" {
break
}
conf += line + "\n"
}
var f rawFile
err := yaml.Unmarshal([]byte(conf), &f)
if err != nil {
fmt.Println("Error unmarshaling yaml:", err)
return rawFile{}
}
return f
}
func loadLanguagesAvailable() ([]string, error) {
files, err := ioutil.ReadDir("website-docs")
if err != nil {
return nil, err
}
langs := make([]string, 0, len(files))
for _, f := range files {
if !f.IsDir() {
continue
}
langs = append(langs, f.Name())
}
return langs, nil
}
func loadLanguages(langs []string, fname string, referenceMD5 string) (map[string]File, error) {
m := make(map[string]File, len(langs))
for _, lang := range langs {
data, err := ioutil.ReadFile("website-docs/" + lang + "/" + fname)
if err != nil {
if os.IsNotExist(err) {
continue
}
return nil, err
}
header := loadHeader(data)
m[lang] = File{
IsUpdated: lang == referenceLanguage || header.ReferenceVersion == referenceMD5,
Title: header.Title,
referencesFile: "website-docs/" + lang + "/" + fname,
}
}
return m, nil
}