-
Notifications
You must be signed in to change notification settings - Fork 0
/
grafe.go
339 lines (273 loc) · 7.89 KB
/
grafe.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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
package main
import (
"bytes"
"flag"
"fmt"
"html/template"
"io"
"log"
"net/http"
"os"
"os/signal"
"path/filepath"
"strings"
"sync"
"syscall"
"github.com/yuin/goldmark"
meta "github.com/yuin/goldmark-meta"
"github.com/yuin/goldmark/extension"
"github.com/yuin/goldmark/parser"
"github.com/yuin/goldmark/renderer"
"github.com/yuin/goldmark/renderer/html"
"github.com/yuin/goldmark/util"
fences "github.com/stefanfritsch/goldmark-fences"
wikitable "github.com/movsb/goldmark-wiki-table"
"go.abhg.dev/goldmark/wikilink"
mathjax "github.com/litao91/goldmark-mathjax"
"github.com/clarkmcc/go-typescript"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func walk(dir string, fileFunction func(filePath string)) {
items, _ := os.ReadDir(dir)
for _, item := range items {
if !item.IsDir() {
fileFunction(dir + "/" + item.Name())
} else {
walk(dir+"/"+item.Name(), fileFunction)
}
}
}
func getExtension(filePath string) string {
filePathParts := strings.Split(strings.TrimSpace(filePath), "/")
fileName := filePathParts[len(filePathParts)-1]
fileNameElems := strings.Split(strings.TrimSpace(fileName), ".")
extension := strings.TrimPrefix(fileName, fileNameElems[0])
return extension
}
func removeExtension(filePath string) string {
return strings.TrimSuffix(strings.TrimSpace(filePath), getExtension(filePath))
}
func addExtension(filePath string, newExtension string) string {
return filePath + newExtension
}
func changeExtension(filePath string, newExtension string) string {
return addExtension(removeExtension(filePath), newExtension)
}
func createDirectoryPath(path string) {
err := os.MkdirAll(filepath.Dir(path), 0770)
check(err)
}
func copyFile(sourcePath string, destinationPath string) {
source, err := os.Open(sourcePath)
check(err)
defer source.Close()
destination, err := os.Create(destinationPath)
check(err)
defer destination.Close()
_, err = io.Copy(destination, source)
check(err)
}
func generateHtmlFile(templates map[string]*template.Template, markdownWriter goldmark.Markdown, sourceMd string, outputFile string, config map[string]interface{}) {
var buf bytes.Buffer
var err error
context := parser.NewContext()
err = markdownWriter.Convert([]byte(sourceMd), &buf, parser.WithContext(context))
check(err)
metaData := meta.Get(context)
if metaData["draft"] == true {
return
}
createDirectoryPath(outputFile)
file, err := os.Create(outputFile)
check(err)
defer file.Close()
params := metaData["params"]
if params == nil {
params = *new(map[any]any)
}
data := struct {
Title string
Summary string
Body template.HTML
PageParams any
SiteParams any
}{
Body: template.HTML(buf.String()),
PageParams: metaData,
SiteParams: config,
}
pageTemplateFile := addExtension(metaData["template"].(string), ".html")
pageTemplate, ok := templates[pageTemplateFile]
if !ok {
log.Fatalf("The template %s does not exist.\n", pageTemplateFile)
}
err = pageTemplate.ExecuteTemplate(file, pageTemplateFile, data)
check(err)
}
func transpileTypescriptFile(tsFilePath string, jsOutputPath string) {
tsCode, err := os.ReadFile(tsFilePath)
check(err)
transpiled, err := typescript.TranspileString(string(tsCode))
check(err)
outputFile, err := os.Create(jsOutputPath)
check(err)
_, err = outputFile.WriteString(transpiled)
check(err)
}
func generateTemplates(directory string) map[string]*template.Template {
templates := make(map[string]*template.Template)
templatesDir := directory
layouts, err := filepath.Glob(templatesDir + "layouts/*")
check(err)
includes, err := filepath.Glob(templatesDir + "includes/*")
check(err)
for _, layout := range layouts {
files := append(includes, layout)
templates[filepath.Base(layout)] = template.Must(template.ParseFiles(files...))
}
return templates
}
func convertContentDirectory(templates map[string]*template.Template, markdownWriter goldmark.Markdown, config map[string]interface{}) {
walk("content", func(fileName string) {
if getExtension(fileName) == ".md" {
fileData, err := os.ReadFile(fileName)
check(err)
generateHtmlFile(
templates,
markdownWriter,
string(fileData),
"public/"+strings.TrimPrefix(
changeExtension(fileName, ".html"),
"content/",
),
config,
)
} else {
if !strings.Contains(fileName, ".git") {
newFileName := strings.TrimPrefix(fileName, "content/")
createDirectoryPath("public/" + newFileName)
copyFile(
fileName,
"public/"+newFileName,
)
}
}
})
}
func readConfigFile(markdownWriter goldmark.Markdown, configFile string) map[string]interface{} {
var buf bytes.Buffer
fileData, err := os.ReadFile(configFile)
check(err)
context := parser.NewContext()
err = markdownWriter.Convert([]byte(string(fileData)), &buf, parser.WithContext(context))
check(err)
return meta.Get(context)
}
func copyDirectoryFiles(directoryToCopy string, newDirectoryPath string) {
walk(directoryToCopy, func(fileName string) {
newFileName := strings.TrimPrefix(fileName, directoryToCopy)
createDirectoryPath(newDirectoryPath + newFileName)
copyFile(
fileName,
newDirectoryPath+newFileName,
)
})
}
func transpileTypescript(directory string) {
walk(directory, func(fileName string) {
if getExtension(fileName) != ".ts" {
return
}
newFileName := changeExtension(fileName, ".js")
createDirectoryPath(directory + "/" + newFileName)
transpileTypescriptFile(fileName, newFileName)
err := os.Remove(fileName)
check(err)
})
}
func startHTTPServer(directory string, port int) {
fmt.Printf("Started server at http://localhost:%d/\n", port)
http.Handle("/", http.FileServer(http.Dir(directory)))
httpServerExitDone := &sync.WaitGroup{}
httpServerExitDone.Add(1)
closeHTTPServer := func() {
httpServerExitDone.Done()
httpServerExitDone.Wait()
fmt.Println("\nClosed server\n")
}
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
closeHTTPServer()
os.Exit(1)
}()
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
}
func pruneDirectory(directory string) {
err := os.RemoveAll(directory)
check(err)
}
func main() {
var err error
enableTypeScriptTranspilationPtr := flag.Bool("transpile-ts", true, "Transpile all TypeScript in the `public` directory.")
createNoJekyllFilePtr := flag.Bool("nojekyll", true, "Create `public/.nojekyll`; required to host static site on GitHub pages.")
enableHttpServerPtr := flag.Bool("server", false, "Start HTTP server of `public` directory.")
httpServerPortPtr := flag.Int("port", 8081, "Port at which to host HTTP server.")
flag.Parse()
pruneDirectory("public-generator")
createDirectoryPath("public-generator/templates")
copyDirectoryFiles("theme/templates", "public-generator/templates")
copyDirectoryFiles("templates", "public-generator/templates")
templates := generateTemplates("public-generator/templates/")
configMarkdown := goldmark.New(
goldmark.WithExtensions(
meta.Meta,
),
)
config := readConfigFile(configMarkdown, "config.md")
markdownWriter := goldmark.New(
goldmark.WithParserOptions(
parser.WithAutoHeadingID(),
parser.WithAttribute(),
),
goldmark.WithExtensions(
meta.Meta,
extension.Table,
&wikilink.Extender{},
mathjax.MathJax,
extension.TaskList,
extension.Table,
&fences.Extender{},
wikitable.New(),
),
goldmark.WithRendererOptions(
renderer.WithNodeRenderers(
util.Prioritized(
extension.NewTableHTMLRenderer(),
500,
),
),
html.WithUnsafe(),
),
)
pruneDirectory("public")
copyDirectoryFiles("theme/static", "public")
copyDirectoryFiles("static", "public")
convertContentDirectory(templates, markdownWriter, config)
pruneDirectory("public-generator")
if *enableTypeScriptTranspilationPtr {
transpileTypescript("public")
}
if *createNoJekyllFilePtr {
_, err = os.Create("public/.nojekyll")
check(err)
}
if *enableHttpServerPtr {
startHTTPServer("public", *httpServerPortPtr)
}
}