all repos — vite @ d0c288a583189c3efbe0bc1e387c726578dcfb38

a fast (this time, actually) and minimal static site generator

build.go (view raw)

  1package main
  2
  3import (
  4	"fmt"
  5	"github.com/cross-cpm/go-shutil"
  6	"io/ioutil"
  7	"os"
  8	"os/exec"
  9	"path/filepath"
 10	"strings"
 11	"text/template"
 12)
 13
 14var cfg = parseConfig()
 15
 16func execute(cmds []string) {
 17	for _, cmd := range cmds {
 18		out, err := exec.Command(cmd).Output()
 19		printMsg("running:", cmd)
 20		if err != nil {
 21			printErr(err)
 22			fmt.Println(string(out))
 23		}
 24	}
 25}
 26
 27func processTemplate(tmplPath string) *template.Template {
 28	tmplFile := filepath.Join("templates", tmplPath)
 29	tmpl, err := template.ParseFiles(tmplFile)
 30	if err != nil {
 31		printErr(err)
 32	}
 33
 34	return tmpl
 35}
 36
 37func handleMd(mdPath string) {
 38	content, err := ioutil.ReadFile(mdPath)
 39	if err != nil {
 40		printErr(err)
 41	}
 42
 43	restContent, fm := parseFrontmatter(content)
 44	bodyHtml := mdRender(restContent)
 45	relPath, _ := filepath.Rel("pages/", mdPath)
 46
 47	var buildPath string
 48	if strings.HasSuffix(relPath, "_index.md") {
 49		dir, _ := filepath.Split(relPath)
 50		buildPath = filepath.Join("build", dir)
 51	} else {
 52		buildPath = filepath.Join(
 53			"build",
 54			strings.TrimSuffix(relPath, filepath.Ext(relPath)),
 55		)
 56	}
 57
 58	os.MkdirAll(buildPath, 0755)
 59
 60	fm.Body = string(bodyHtml)
 61
 62	// combine config and matter structs
 63	combined := struct {
 64		Cfg Config
 65		Fm  Matter
 66	}{cfg, fm}
 67
 68	htmlFile, err := os.Create(filepath.Join(buildPath, "index.html"))
 69	if err != nil {
 70		printErr(err)
 71		return
 72	}
 73	if fm.Template == "" {
 74		fm.Template = "text.html"
 75	}
 76	tmpl := processTemplate(fm.Template)
 77	err = tmpl.Execute(htmlFile, combined)
 78	if err != nil {
 79		printErr(err)
 80		return
 81	}
 82	htmlFile.Close()
 83}
 84
 85func viteBuild() {
 86	printMsg("executing pre-build actions...")
 87	execute(cfg.Prebuild)
 88	err := filepath.Walk("./pages", func(path string, info os.FileInfo, err error) error {
 89		if err != nil {
 90			printErr(err)
 91			return err
 92		}
 93		if filepath.Ext(path) == ".md" {
 94			handleMd(path)
 95		} else {
 96			f, err := os.Stat(path)
 97			if err != nil {
 98				printErr(err)
 99			}
100			mode := f.Mode()
101			if mode.IsRegular() {
102				options := shutil.CopyOptions{}
103				relPath, _ := filepath.Rel("pages/", path)
104				options.FollowSymlinks = true
105				shutil.CopyFile(
106					path,
107					filepath.Join("build", relPath),
108					&options,
109				)
110			}
111		}
112		return nil
113	})
114	if err != nil {
115		printErr(err)
116	}
117
118	_, err = shutil.CopyTree("static", filepath.Join("build", "static"), nil)
119	if err != nil {
120		printErr(err)
121	}
122	printMsg("site build complete")
123	printMsg("executing post-build actions...")
124	execute(cfg.Postbuild)
125}