forked from Onyx-Protocol/Onyx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
422 lines (355 loc) · 9.09 KB
/
main.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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"github.com/russross/blackfriday"
)
var layoutPlaceholder = []byte("{{Body}}")
var documentNamePlaceholder = []byte("{{Filename}}")
func main() {
var dest = ":8080"
if len(os.Args) > 2 {
log.Fatal("usage: md2html [dest]")
}
if len(os.Args) == 2 {
dest = os.Args[1]
}
if !strings.Contains(dest, ":") {
printe(convert(dest))
os.Exit(0)
}
serve(dest)
}
func serve(addr string) {
fmt.Printf("serving at: http://localhost%s\n", addr)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
path := "." + r.URL.Path
if filepath.Ext(path) != "" {
http.ServeFile(w, r, path)
return
}
paths := []string{
path + ".md",
path + ".partial.html",
strings.TrimSuffix(path, "/") + "/index.html",
strings.TrimSuffix(path, "/") + "/index.partial.html",
}
var (
b []byte
err error
)
for _, p := range paths {
if strings.HasSuffix(p, ".md") {
b, err = renderMarkdown(p)
} else if strings.HasSuffix(p, ".partial.html") {
b, err = renderHTML(p)
} else {
b, err = ioutil.ReadFile(p)
}
if err == nil {
break
}
if err != nil && !os.IsNotExist(err) {
http.Error(w, err.Error(), 500)
return
}
}
if err != nil {
http.NotFound(w, r)
return
}
w.Write(b)
})
log.Fatal(http.ListenAndServe(addr, nil))
}
func convert(dest string) error {
fmt.Printf("Converting markdown to: %s\n", dest)
return filepath.Walk(".", func(path string, f os.FileInfo, err error) error {
if err != nil {
return err
}
if f.IsDir() {
return nil
}
var (
destFile = filepath.Join(dest, path)
output []byte
)
if strings.HasSuffix(f.Name(), ".md") {
destFile = strings.TrimSuffix(destFile, ".md")
output, err = renderMarkdown(path)
} else if strings.HasSuffix(f.Name(), ".partial.html") {
destFile = strings.TrimSuffix(destFile, ".partial.html")
output, err = renderHTML(path)
} else if strings.HasSuffix(f.Name(), ".html") {
destFile = strings.TrimSuffix(destFile, ".html")
output, err = ioutil.ReadFile(path)
} else {
output, err = ioutil.ReadFile(path)
}
if err != nil {
return err
}
// For serving index files in S3, we need the .html extension.
if f.Name() == "index.html" || f.Name() == "index.partial.html" {
destFile += ".html"
}
err = os.MkdirAll(filepath.Dir(destFile), 0777)
if err != nil {
return err
}
err = ioutil.WriteFile(destFile, output, 0644)
if err != nil {
return err
}
fmt.Printf("converted: %s\n", path)
return nil
})
}
func renderHTML(path string) ([]byte, error) {
content, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
html, err := layout(path)
if err != nil {
return nil, err
}
html = bytes.Replace(html, layoutPlaceholder, content, 1)
return html, nil
}
func printe(err error) {
if err != nil {
fmt.Println(err)
}
}
func renderMarkdown(f string) ([]byte, error) {
src, err := ioutil.ReadFile(f)
if err != nil {
return nil, err
}
src = interpolateCode(src, path.Dir(f))
html, err := layout(f)
if err != nil {
return nil, err
}
src = preprocessLocalLinks(src)
src = markdown(src)
src = formatSidenotes(src)
html = bytes.Replace(html, layoutPlaceholder, src, 1)
pathClass := strings.Replace(strings.TrimSuffix(strings.TrimPrefix(strings.TrimPrefix(f, "./"), "../"), ".md"), "/", "_", -1)
html = bytes.Replace(html, documentNamePlaceholder, []byte(pathClass), -1)
return html, nil
}
// Returns the contents of a layout.html file
// starting in the directory of p and ending at the command's
// working directory.
// If no layout.html file is found layoutPlaceholder is returned
// as a default layout.
func layout(p string) ([]byte, error) {
// Don't search for layouts beyond the working dir
wd, err := os.Getwd()
if err != nil {
return nil, err
}
for {
p = path.Dir(p)
l, err := ioutil.ReadFile(p + "/layout.html")
if err == nil {
return l, nil
}
if !os.IsNotExist(err) {
return nil, err
}
if wd == p {
break
}
}
return layoutPlaceholder, nil
}
func interpolateCode(md []byte, hostPath string) []byte {
const pat = `$code `
w := new(bytes.Buffer)
scanner := bufio.NewScanner(bytes.NewBuffer(md))
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, pat) {
var snippath, snippet string
fields := strings.Fields(line)
if len(fields) >= 2 {
snippath = fields[1]
}
if len(fields) >= 3 {
snippet = fields[2]
}
if path.IsAbs(snippath) {
snippath = path.Join(os.Getenv("CHAIN"), snippath)
} else {
snippath = path.Join(hostPath, snippath)
}
writeCode(w, snippath, snippet)
continue
}
fmt.Fprintln(w, line)
}
return w.Bytes()
}
func writeCode(w io.Writer, path, snippet string) {
s, err := readSnippet(path, snippet)
if err != nil {
s = err.Error()
} else {
s = removeCommonIndent(s)
}
fmt.Fprintln(w, "```\n"+s+"\n```")
}
func readSnippet(path, snippet string) (string, error) {
b, err := ioutil.ReadFile(path)
if err != nil {
return "", fmt.Errorf("Unable to read source file: %s\n", path)
}
src := string(b)
// If the snippet is unset, return everything, omitting snippet definitions.
if snippet == "" {
var res string
for _, line := range strings.SplitAfter(src, "\n") {
if strings.Contains(line, "snippet") {
continue
}
res += line
}
return res, nil
}
if !strings.Contains(src, "snippet "+snippet) {
return "", fmt.Errorf("Snippet %q is not in %q", snippet, path)
}
var (
res []string
found bool
)
for _, line := range strings.Split(src, "\n") {
if !found && strings.Contains(line, "snippet "+snippet) {
found = true
continue
}
if found && strings.Contains(line, "endsnippet") {
break
}
if found {
res = append(res, line)
}
}
return strings.Join(res, "\n"), nil
}
func removeCommonIndent(s string) string {
lines := strings.Split(s, "\n")
ci := commonIndent(lines)
for i, line := range lines {
lines[i] = strings.TrimPrefix(line, ci)
}
return strings.Join(lines, "\n")
}
// commonIndent returns the longest indentation shared by all non-empty lines
// in the input.
func commonIndent(lines []string) string {
var (
indent = regexp.MustCompile(`^[ \t]+`)
res string
resSet bool
)
for _, line := range lines {
// blank lines should not influence the common indentation
if strings.TrimSpace(line) == "" {
continue
}
if !resSet {
res = indent.FindString(line)
resSet = true
continue
}
res = commonPrefix(res, indent.FindString(line))
if res == "" {
break
}
}
return res
}
// commonPrefix returns the longest shared prefix between two strings. It
// assumes the characters can be represented by a single byte.
func commonPrefix(a, b string) string {
var res []byte
for i := range a {
if i >= len(b) || a[i] != b[i] {
break
}
res = append(res, a[i])
}
return string(res)
}
func markdown(source []byte) []byte {
htmlFlags := 0
htmlFlags |= blackfriday.HTML_USE_XHTML
htmlFlags |= blackfriday.HTML_USE_SMARTYPANTS
htmlFlags |= blackfriday.HTML_SMARTYPANTS_FRACTIONS
htmlFlags |= blackfriday.HTML_SMARTYPANTS_LATEX_DASHES
htmlFlags |= blackfriday.HTML_SMARTYPANTS_DASHES
htmlFlags |= blackfriday.HTML_FOOTNOTE_RETURN_LINKS
renderer := blackfriday.HtmlRenderer(htmlFlags, "", "")
extensions := 0
extensions |= blackfriday.EXTENSION_FOOTNOTES
extensions |= blackfriday.EXTENSION_NO_INTRA_EMPHASIS
extensions |= blackfriday.EXTENSION_TABLES
extensions |= blackfriday.EXTENSION_FENCED_CODE
extensions |= blackfriday.EXTENSION_AUTOLINK
extensions |= blackfriday.EXTENSION_STRIKETHROUGH
extensions |= blackfriday.EXTENSION_SPACE_HEADERS
extensions |= blackfriday.EXTENSION_HEADER_IDS
extensions |= blackfriday.EXTENSION_LAX_HTML_BLOCKS
extensions |= blackfriday.EXTENSION_AUTO_HEADER_IDS
return blackfriday.Markdown(source, renderer, extensions)
}
// Very rude, but compatible with our code rewrite of local .md links to their post-processed URLs.
// The intention is to process only local links to .md files into non-.md files:
// [Foo](foo.md) -> [Foo](foo)
// [Bar](../bar.md) -> [Bar](../bar)
// [Global](https://github.com/.../global.md) -> [Global](https://github.com/.../global.md) <- .md must be preserved here!
func preprocessLocalLinks(source []byte) []byte {
// We use a simple rule - local URLs are those without ":" in them.
var localMdLink = regexp.MustCompile(`(\]\([^:)#]+)\.md([)#])`)
w := new(bytes.Buffer)
scanner := bufio.NewScanner(bytes.NewBuffer(source))
for scanner.Scan() {
line := scanner.Text()
fmt.Fprintln(w, localMdLink.ReplaceAllString(line, "$1$2"))
}
return w.Bytes()
}
func formatSidenotes(source []byte) []byte {
const openTag = `<p>[sidenote]</p>`
const closeTag = `<p>[/sidenote]</p>`
w := new(bytes.Buffer)
scanner := bufio.NewScanner(bytes.NewBuffer(source))
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, closeTag) {
fmt.Fprintln(w, `</div>`)
continue
}
if strings.HasPrefix(line, openTag) {
fmt.Fprintln(w, `<div class="sidenote">`)
continue
}
fmt.Fprintln(w, line)
}
return w.Bytes()
}