all repos — vite @ 45310dfe7ecd7b5407640287e4e7069a53cf7100

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

commands/build.go (view raw)

 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
package commands

import (
	"fmt"
	"os"
	"path/filepath"
	"sort"
	"strings"
	"time"

	"git.icyphox.sh/vite/atom"
	"git.icyphox.sh/vite/config"
	"git.icyphox.sh/vite/formats"
	"git.icyphox.sh/vite/formats/markdown"
	"git.icyphox.sh/vite/formats/yaml"
	"git.icyphox.sh/vite/types"
	"git.icyphox.sh/vite/util"
)

type Dir struct {
	Name     string
	HasIndex bool
	Files    []types.File
}

type Pages struct {
	Dirs  []Dir
	Files []types.File
}

func NewPages() (*Pages, error) {
	pages := &Pages{}

	entries, err := os.ReadDir(types.PagesDir)
	if err != nil {
		return nil, err
	}

	for _, entry := range entries {
		if entry.IsDir() {
			thingsDir := filepath.Join(types.PagesDir, entry.Name())
			dir := Dir{Name: entry.Name()}
			things, err := os.ReadDir(thingsDir)
			if err != nil {
				return nil, err
			}

			for _, thing := range things {
				if thing.Name() == "_index.md" {
					dir.HasIndex = true
					continue
				}
				switch filepath.Ext(thing.Name()) {
				case ".md":
					path := filepath.Join(thingsDir, thing.Name())
					dir.Files = append(dir.Files, &markdown.Markdown{Path: path})
				case ".yaml":
					path := filepath.Join(thingsDir, thing.Name())
					dir.Files = append(dir.Files, &yaml.YAML{Path: path})
				default:
					fmt.Printf("warn: unrecognized filetype for file: %s\n", thing.Name())
				}
			}

			pages.Dirs = append(pages.Dirs, dir)
		} else {
			path := filepath.Join(types.PagesDir, entry.Name())
			switch filepath.Ext(entry.Name()) {
			case ".md":
				pages.Files = append(pages.Files, &markdown.Markdown{Path: path})
			case ".yaml":
				pages.Files = append(pages.Files, &yaml.YAML{Path: path})
			default:
				pages.Files = append(pages.Files, formats.Anything{Path: path})
			}
		}
	}

	return pages, nil
}

// Build is the core builder function. Converts markdown/yaml
// to html, copies over non-.md/.yaml files, etc.
func Build() error {
	if err := preBuild(); err != nil {
		return err
	}
	fmt.Println("vite: building")

	pages, err := NewPages()
	if err != nil {
		return fmt.Errorf("error: reading 'pages/' %w", err)
	}

	if err := util.Clean(types.BuildDir); err != nil {
		return err
	}

	if err := pages.ProcessFiles(); err != nil {
		return err
	}

	if err := pages.ProcessDirectories(); err != nil {
		return err
	}

	buildStatic := filepath.Join(types.BuildDir, types.StaticDir)
	if err := os.MkdirAll(buildStatic, 0755); err != nil {
		return err
	}
	if err := util.CopyDir(types.StaticDir, buildStatic); err != nil {
		return err
	}
	fmt.Println("done")

	return nil
}

// ProcessFiles handles root level files under 'pages',
// for example: 'pages/_index.md' or 'pages/about.md'.
func (p *Pages) ProcessFiles() error {
	for _, f := range p.Files {
		var htmlDir string
		if f.Basename() == "_index.md" {
			htmlDir = types.BuildDir
		} else {
			htmlDir = filepath.Join(types.BuildDir, strings.TrimSuffix(f.Basename(), f.Ext()))
		}

		destFile := filepath.Join(htmlDir, "index.html")
		if f.Ext() == "" {
			destFile = filepath.Join(types.BuildDir, f.Basename())
		} else {
			if err := os.MkdirAll(htmlDir, 0755); err != nil {
				return err
			}
		}
		if err := f.Render(destFile, nil); err != nil {
			return fmt.Errorf("error: failed to render %s: %w", destFile, err)
		}
	}
	return nil
}

// ProcessDirectories handles directories of posts under 'pages',
// for example: 'pages/photos/foo.md' or 'pages/blog/bar.md'.
func (p *Pages) ProcessDirectories() error {
	for _, dir := range p.Dirs {
		dstDir := filepath.Join(types.BuildDir, dir.Name)
		if err := os.MkdirAll(dstDir, 0755); err != nil {
			return fmt.Errorf("error: failed to create directory: %s: %w", dstDir, err)
		}

		posts := []types.Post{}

		for _, file := range dir.Files {
			post := types.Post{}
			// foo-bar.md -> foo-bar
			slug := strings.TrimSuffix(file.Basename(), file.Ext())
			dstFile := filepath.Join(dstDir, slug, "index.html")

			// ex: build/blog/foo-bar/
			if err := os.MkdirAll(filepath.Join(dstDir, slug), 0755); err != nil {
				return fmt.Errorf("error: failed to create directory: %s: %w", dstDir, err)
			}

			if err := file.Render(dstFile, nil); err != nil {
				return fmt.Errorf("error: failed to render %s: %w", dstFile, err)
			}

			post.Meta = file.Frontmatter()
			post.Body = file.Body()
			posts = append(posts, post)
		}

		sort.Slice(posts, func(i, j int) bool {
			dateStr1 := posts[j].Meta["date"]
			dateStr2 := posts[i].Meta["date"]
			date1, _ := time.Parse("2006-01-02", dateStr1)
			date2, _ := time.Parse("2006-01-02", dateStr2)
			return date1.Before(date2)
		})

		if dir.HasIndex {
			indexMd := filepath.Join(types.PagesDir, dir.Name, "_index.md")
			index := markdown.Markdown{Path: indexMd}
			dstFile := filepath.Join(dstDir, "index.html")
			if err := index.Render(dstFile, posts); err != nil {
				return fmt.Errorf("error: failed to render index %s: %w", dstFile, err)
			}
		}

		xml, err := atom.NewAtomFeed(filepath.Join(types.PagesDir, dir.Name), posts)
		if err != nil {
			return fmt.Errorf("error: failed to create atom feed for: %s: %w", dir.Name, err)
		}
		feedFile := filepath.Join(dstDir, "feed.xml")
		os.WriteFile(feedFile, xml, 0755)
	}

	return nil
}

func postBuild() error {
	for _, cmd := range config.Config.PostBuild {
		fmt.Println("vite: running post-build command:", cmd)
		if err := util.RunCmd(cmd); err != nil {
			return err
		}
	}
	return nil
}

func preBuild() error {
	for _, cmd := range config.Config.PreBuild {
		fmt.Println("vite: running pre-build command:", cmd)
		if err := util.RunCmd(cmd); err != nil {
			return err
		}
	}
	return nil
}