summaryrefslogtreecommitdiff
path: root/transformations.go
blob: aa2fc305ab5b6da1132fa64aedb9c7fbf4646a51 (plain)
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
// Copyright (c) 2023 Nicolas Paul All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"log"
	"os"

	"github.com/gomarkdown/markdown"
	"github.com/gomarkdown/markdown/html"
	"github.com/gomarkdown/markdown/parser"
)

// TransformMarkdownFile simply copy a non-markdown file to the output
// directory.
func TransformNonMarkdownFile(i, o string) error {
	input, err := os.ReadFile(i)
	if err != nil {
		return err
	}

	if err := os.WriteFile(o, input, 0666); err != nil {
		return err
	}

	log.Printf("copied file %q to %q", i, o)

	return nil
}

// TransformDirectory creates a directory in the output directory.
func TransformDirectory(o string) error {
	if err := os.MkdirAll(o, 0777); err != nil {
		return err
	}

	log.Printf("created directory %q", o)
	return nil
}

// TransformMarkdownFile generates the corresponding HTML document from a
// Markdown file.
// s corresponds to the slug of the document.
func TransformMarkdownFile(i, o, s string) error {
	raw, err := os.ReadFile(i)
	if err != nil {
		return err
	}

	// Parse front matter
	fm, md, err := ParseFrontMatter(raw)
	if err != nil {
		return err
	}

	// Skip hidden files unless -hidden is specified
	if fm.Hide && !*generateHidden {
		log.Printf("skipped hidden file %q", i)
		return nil
	}

	// Render Markdown to HTML
	pExtensions := parser.Tables | parser.FencedCode |
		parser.Autolink | parser.Strikethrough | parser.SpaceHeadings |
		parser.HeadingIDs | parser.BackslashLineBreak |
		parser.AutoHeadingIDs | parser.Footnotes | parser.SuperSubscript |
		parser.NoIntraEmphasis
	p := parser.NewWithExtensions(pExtensions)
	ast := p.Parse(md)

	htmlFlags := html.Smartypants | html.SmartypantsFractions |
		html.SmartypantsDashes | html.SmartypantsLatexDashes |
		html.HrefTargetBlank | html.LazyLoadImages
	renderer := html.NewRenderer(html.RendererOptions{Flags: htmlFlags})
	html := markdown.Render(ast, renderer)

	c, err := GenerateHTML(fm, s, string(html))
	if err != nil {
		return err
	}

	if err := os.WriteFile(o, c, 0666); err != nil {
		return err
	}

	log.Printf("generated file %q", o)
	return nil
}