build.go (view raw)
1package main
2
3import (
4 "io/ioutil"
5 "os"
6 "path/filepath"
7 "strings"
8 "text/template"
9 "github.com/cross-cpm/go-shutil"
10)
11
12func processTemplate(tmplPath string) *template.Template {
13 tmplFile := filepath.Join("templates", tmplPath)
14 tmpl, err := template.ParseFiles(tmplFile)
15 if err != nil {
16 printErr(err)
17 }
18
19 return tmpl
20}
21
22func handleMd(mdPath string) {
23 content, err := ioutil.ReadFile(mdPath)
24 if err != nil {
25 printErr(err)
26 }
27
28 restContent, fm := parseFrontmatter(content)
29 bodyHtml := mdRender(restContent)
30 relPath, _ := filepath.Rel("pages/", mdPath)
31
32 var buildPath string
33 if strings.HasSuffix(relPath, "_index.md") {
34 dir, _ := filepath.Split(relPath)
35 buildPath = filepath.Join("build", dir)
36 } else {
37 buildPath = filepath.Join(
38 "build",
39 strings.TrimSuffix(relPath, filepath.Ext(relPath)),
40 )
41 }
42
43 os.MkdirAll(buildPath, 0755)
44 fm.Body = string(bodyHtml)
45
46 htmlFile, err := os.Create(filepath.Join(buildPath, "index.html"))
47 if err != nil {
48 printErr(err)
49 return
50 }
51 if fm.Template == "" {
52 fm.Template = "text.html"
53 }
54 tmpl := processTemplate(fm.Template)
55 err = tmpl.Execute(htmlFile, fm)
56 if err != nil {
57 printErr(err)
58 return
59 }
60 htmlFile.Close()
61}
62
63func viteBuild() {
64 err := filepath.Walk("./pages", func(path string, info os.FileInfo, err error) error {
65 if err != nil {
66 printErr(err)
67 return err
68 }
69 if filepath.Ext(path) == ".md" {
70 handleMd(path)
71 } else {
72 f, err := os.Stat(path)
73 if err != nil {
74 printErr(err)
75 }
76 mode := f.Mode()
77 if mode.IsRegular() {
78 options := shutil.CopyOptions{}
79 relPath, _ := filepath.Rel("pages/", path)
80 options.FollowSymlinks = true
81 shutil.CopyFile(
82 path,
83 filepath.Join("build", relPath),
84 &options,
85 )
86 }
87 }
88 return nil
89 })
90 if err != nil {
91 printErr(err)
92 }
93
94 _, err = shutil.CopyTree("static", filepath.Join("build", "static"), nil)
95 if err != nil {
96 printErr(err)
97 }
98}