all repos — www @ 2a22eb258e2ba3214509c41d66999af575dbd4b1

deserthorns.net content + generator

build/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
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
// https://gobyexample.com/

package main

import (
	"bufio"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"text/template"
	"time"
)

type PageProperties struct {
	Title       string
	StylePath   string
	HeaderLinks [][]*HeaderLink
}

type HeaderLink struct {
	Name   string
	Active bool
}

type Page struct {
	Name     string
	Parent   *Page
	Children []*Page
}

var rootPath = "."
var now = time.Now()

func main() {
	serve := false
	args := os.Args[1:]
	if len(args) != 0 {
		rootPath = args[0]
		if len(args) == 2 {
			flag := args[1]
			switch flag {
			case "--serve":
			case "-s":
				serve = true

			default:
				fmt.Println(flag + " is not a recognized flag.")
				os.Exit(1)
			}
		}
	}
	fmt.Println("Starting build...")
	os.RemoveAll(filepath.Join("out"))
	os.Mkdir(filepath.Join("out"), 0777)

	fmt.Print("Building pages...")
	buildSite(buildSiteLinkedList())
	fmt.Println("Done")

	fmt.Print("Copying assets...")
	copyDir(
		filepath.Join(rootPath, "assets"),
		filepath.Join("out", "assets"),
	)

	cssOutPath := filepath.Join("out", "assets", "css")
	os.Rename(
		filepath.Join(cssOutPath, "style.css"),
		filepath.Join(cssOutPath, "style."+strconv.FormatInt(now.Unix(), 10)+".css"),
	)
	fmt.Println("Done")

	fmt.Println("Build complete.")
	if serve {
		http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("out"))))
		http.HandleFunc("GET /{page}", pageHandler("out"))
		fmt.Println("Serving on http://localhost:8000")
		log.Fatal(http.ListenAndServe(":8000", nil))
	}
}

func pageHandler(rootPath string) func(http.ResponseWriter, *http.Request) {
	return func(responseWriter http.ResponseWriter, request *http.Request) {
		pageName := request.PathValue("page")
		pageFile, err := os.ReadFile(filepath.Join(rootPath, pageName+".html"))
		if err == nil {
			responseWriter.Write(pageFile)
			return
		}
		http.NotFound(responseWriter, request)
	}
}

func buildSiteLinkedList() *Page {
	rootNode := &Page{
		Name:   "index",
		Parent: nil,
	}
	parentNode := rootNode
	tailNode := rootNode
	currentDepth := 0
	siteFile, _ := os.Open(filepath.Join(rootPath, ".site"))
	scanner := bufio.NewScanner(siteFile)
	scanner.Split(bufio.ScanLines)
	for scanner.Scan() {
		depth := strings.Count(strings.TrimRight(scanner.Text(), " "), " ")
		pageName := strings.TrimLeft(scanner.Text(), " ")
		if len(pageName) > 0 {
			if depth > currentDepth {
				currentDepth = depth
				parentNode = tailNode
			} else if depth < currentDepth {
				unwind := (currentDepth - depth) + 1
				currentDepth = depth
				for range unwind {
					tailNode = tailNode.Parent
				}
				parentNode = tailNode
			}
			newNode := &Page{
				Name:   pageName,
				Parent: parentNode,
			}
			parentNode.Children = append(parentNode.Children, newNode)
			tailNode = newNode
		}
	}
	return rootNode
}

func parentLinks(page *Page) []*HeaderLink {
	if page.Parent == nil {
		return nil
	}
	if page.Parent.Parent == nil {
		return nil
	}
	parentPages := page.Parent.Parent.Children
	parentLinks := make([]*HeaderLink, len(parentPages))
	for i, parentPage := range parentPages {
		parentLinks[i] = &HeaderLink{
			Name:   parentPage.Name,
			Active: page.Parent == parentPage,
		}
	}
	return parentLinks
}

func siblingLinks(page *Page) []*HeaderLink {
	if page.Parent == nil {
		return nil
	}
	siblingPages := page.Parent.Children
	siblingLinks := make([]*HeaderLink, len(siblingPages))
	for i, siblingPage := range siblingPages {
		siblingLinks[i] = &HeaderLink{
			Name:   siblingPage.Name,
			Active: page == siblingPage,
		}
	}
	return siblingLinks
}

func childLinks(page *Page) []*HeaderLink {
	childPages := page.Children
	childLinks := make([]*HeaderLink, len(childPages))
	for i, childPage := range childPages {
		childLinks[i] = &HeaderLink{
			Name:   childPage.Name,
			Active: false,
		}
	}
	return childLinks
}

func buildSite(page *Page) {
	outDir := filepath.Join("out")
	pageSrcDir := filepath.Join(rootPath, "pages")
	templateSrcDir := filepath.Join(rootPath, "templates")
	parents := parentLinks(page)
	siblings := siblingLinks(page)
	children := childLinks(page)
	headerLinks := [][]*HeaderLink{parents, siblings, children}
	// https://abhinavg.net/2019/07/11/zero-alloc-slice-filter/
	filteredHeaderLinks := headerLinks[:0]
	for _, headerLink := range headerLinks {
		if headerLink != nil {
			filteredHeaderLinks = append(filteredHeaderLinks, headerLink)
		}
	}
	pageFilePath := filepath.Join(pageSrcDir, page.Name+".html")
	pageFileInfo, _ := os.Stat(pageFilePath)
	if pageFileInfo == nil {
		copyFile(
			filepath.Join(templateSrcDir, "page.html"),
			pageFilePath,
		)
	}
	os.Mkdir(outDir, 0777)
	outfile, _ := os.Create(filepath.Join(outDir, page.Name+".html"))
	template, err := template.ParseFiles(
		filepath.Join(templateSrcDir, "document.html"),
		filepath.Join(templateSrcDir, "header.html"),
		filepath.Join(pageSrcDir, page.Name+".html"),
	)
	__(err)
	template.Execute(
		outfile,
		&PageProperties{
			Title:       page.Name,
			StylePath:   "/assets/css/style." + strconv.FormatInt(now.Unix(), 10) + ".css",
			HeaderLinks: filteredHeaderLinks,
		},
	)
	for _, child := range page.Children {
		buildSite(child)
	}
}

func copyFile(srcPath string, dstPath string) {
	dst, _ := os.Create(dstPath)
	src, _ := os.Open(srcPath)
	io.Copy(dst, src)
	dst.Sync()
}

func copyDir(srcPath string, dstPath string) {
	srcFS := os.DirFS(srcPath)
	os.CopyFS(dstPath, srcFS)
}

func __(foo any) {}