all repos — vite @ a741d82fd6191ccfbf8e9a480f8def8f170831da

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

build.go (view raw)

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