// Command sitegen builds the static ArozOS website (os.aroz.org) into the
// docs/ folder of this repository.
//
// Everything the site says lives here: site.json holds the languages, the
// header, the footer and the shared interface strings, pages/*.json holds one
// page each, templates/ the HTML and static/ the style sheet and script. Every
// piece of text is either one string or an object with one entry per
// language, so a translation sits right next to the English it translates.
//
// Run it from this folder:
//
// go run .
//
// The generator only writes the files it owns (the pages, assets/ and the
// copied app icons). Screenshots are read from docs/img and never changed.
package main
import (
"bytes"
"crypto/sha1"
"encoding/binary"
"encoding/hex"
"encoding/json"
"errors"
"flag"
"fmt"
"html/template"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"os"
"path"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
)
// defaultLang is the language served from the site root. Every other
// language lives in a sub folder named after its Dir.
const defaultLang = "en"
// manifestName records the files the last run wrote, so pages that were
// removed from pages/ are removed from docs/ too.
const manifestName = ".sitegen-manifest.json"
// Text is a translatable piece of trusted HTML: either one string used for
// every language, or an object keyed by language code.
type Text map[string]string
// UnmarshalJSON accepts a plain string or a language map.
func (t *Text) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err == nil {
*t = Text{"*": s}
return nil
}
var m map[string]string
if err := json.Unmarshal(b, &m); err != nil {
return fmt.Errorf("text must be a string or a language map: %w", err)
}
*t = m
return nil
}
// get returns the text for lang, falling back to the shared value and then
// to English. ok is false when the language had to fall back to English.
func (t Text) get(lang string) (string, bool) {
if v, found := t[lang]; found {
return v, true
}
if v, found := t["*"]; found {
return v, true
}
return t[defaultLang], lang == defaultLang
}
// Language is one translation of the site.
type Language struct {
Code string `json:"code"` // key used in Text maps, e.g. "zh-tw"
Dir string `json:"dir"` // output folder, empty for the root
HTML string `json:"html"` // and hreflang, e.g. "zh-Hant"
Name string `json:"name"` // native name shown in the picker
Locale string `json:"locale"` // og:locale, e.g. "zh_TW"
}
// Link is a labelled link in the footer.
type Link struct {
Label Text `json:"label"`
Href string `json:"href"`
}
// FooterColumn is one column of footer links.
type FooterColumn struct {
Title Text `json:"title"`
Links []Link `json:"links"`
}
// App is an ArozOS WebApp whose icon the pages show. Icon is the path of the
// icon below src/web.
type App struct {
Name Text `json:"name"`
Icon string `json:"icon"`
}
// Site is site.json.
type Site struct {
BaseURL string `json:"baseURL"`
Downloads string `json:"downloads"`
OGImage string `json:"ogImage"`
Languages []Language `json:"languages"`
Nav []string `json:"nav"`
UI map[string]Text `json:"ui"`
Footer []FooterColumn `json:"footer"`
Apps map[string]App `json:"apps"`
}
// Button is a call to action. UI names a shared label in site.json instead
// of a label of its own.
type Button struct {
UI string `json:"ui"`
Label Text `json:"label"`
Href string `json:"href"`
Style string `json:"style"` // primary (default), secondary or link
Icon string `json:"icon"`
}
// Item is one entry of a section: a card, a tile, a step, a statistic.
type Item struct {
Eyebrow Text `json:"eyebrow"`
Title Text `json:"title"`
Text Text `json:"text"`
Value Text `json:"value"`
Note Text `json:"note"`
Image string `json:"image"`
Icon string `json:"icon"`
Apps []string `json:"apps"`
Link string `json:"link"`
Size string `json:"size"`
Accent string `json:"accent"`
Code string `json:"code"`
Bullets []Text `json:"bullets"`
Buttons []Button `json:"buttons"`
}
// Section is one block of a page. Type picks the template that draws it.
type Section struct {
Type string `json:"type"`
ID string `json:"id"`
Tone string `json:"tone"` // "", "alt" or "dark"
Layout string `json:"layout"` // feature: "stack" (default) or "split"
Flip bool `json:"flip"`
Eyebrow Text `json:"eyebrow"`
Title Text `json:"title"`
Text Text `json:"text"`
Note Text `json:"note"`
Alt Text `json:"alt"`
Image string `json:"image"`
Phones []string `json:"phones"` // feature: portrait phone screenshots shown side by side
Apps []string `json:"apps"`
Code string `json:"code"`
Bullets []Text `json:"bullets"`
Buttons []Button `json:"buttons"`
Items []Item `json:"items"`
}
// Page is one file of pages/.
type Page struct {
Slug string `json:"-"`
Nav Text `json:"nav"`
Title Text `json:"title"`
Description Text `json:"description"`
Accent string `json:"accent"`
Feature bool `json:"feature"`
OGImage string `json:"ogImage"`
Sections []Section `json:"sections"`
}
// View is the data a page template is executed with.
type View struct {
Site *Site
Page *Page
Lang Language
Root string
NavPages []*Page
Prev *Page
Next *Page
Year int
Version string
OGImage string
}
// Img is an image found below docs/img.
type Img struct {
Src string
W int
H int
}
// AppView is an app icon copied to docs/assets/apps.
type AppView struct {
Name template.HTML
Src string
}
type generator struct {
srcDir string // this folder
outDir string // docs/
webDir string // src/web, where the app icons come from
site Site
pages map[string]*Page
slugs []string
tpl *template.Template
icons map[string]template.HTML
appSrc map[string]string // app key -> path below outDir
imgs map[string]*Img
version string
written []string
missingImg map[string]bool
missingText map[string]map[string]bool
problems []string
// The page being rendered.
lang Language
page *Page
root string
}
func main() {
src := flag.String("src", ".", "folder holding site.json, pages/, templates/, icons/ and static/")
out := flag.String("out", filepath.Join("..", "..", "docs"), "output folder (the GitHub Pages root)")
web := flag.String("web", filepath.Join("..", "..", "src", "web"), "ArozOS web root, used for app icons")
flag.Parse()
g := &generator{
srcDir: *src,
outDir: *out,
webDir: *web,
pages: map[string]*Page{},
appSrc: map[string]string{},
imgs: map[string]*Img{},
missingImg: map[string]bool{},
missingText: map[string]map[string]bool{},
}
if err := g.run(); err != nil {
fmt.Fprintln(os.Stderr, "sitegen:", err)
os.Exit(1)
}
}
func (g *generator) run() error {
if _, err := os.Stat(filepath.Join(g.srcDir, "site.json")); err != nil {
return errors.New("site.json not found: run sitegen from scripts/sitegen or pass -src")
}
if err := readJSON(filepath.Join(g.srcDir, "site.json"), &g.site); err != nil {
return err
}
if err := g.loadPages(); err != nil {
return err
}
if err := g.loadIcons(); err != nil {
return err
}
if err := g.copyStatic(); err != nil {
return err
}
if err := g.copyAppIcons(); err != nil {
return err
}
if err := g.parseTemplates(); err != nil {
return err
}
for _, lang := range g.site.Languages {
for _, slug := range g.slugs {
if err := g.render(lang, g.pages[slug]); err != nil {
return fmt.Errorf("%s (%s): %w", slug, lang.Code, err)
}
}
}
if err := g.writeSitemap(); err != nil {
return err
}
if err := g.cleanStale(); err != nil {
return err
}
g.report()
return nil
}
func readJSON(file string, v any) error {
b, err := os.ReadFile(file)
if err != nil {
return err
}
if err := json.Unmarshal(b, v); err != nil {
return fmt.Errorf("%s: %w", file, err)
}
return nil
}
func (g *generator) loadPages() error {
files, err := filepath.Glob(filepath.Join(g.srcDir, "pages", "*.json"))
if err != nil {
return err
}
for _, f := range files {
p := &Page{}
if err := readJSON(f, p); err != nil {
return err
}
p.Slug = strings.TrimSuffix(filepath.Base(f), ".json")
g.pages[p.Slug] = p
g.slugs = append(g.slugs, p.Slug)
}
sort.Strings(g.slugs)
if g.pages["index"] == nil {
return errors.New("pages/index.json is missing")
}
for _, slug := range g.site.Nav {
if g.pages[slug] == nil {
return fmt.Errorf("site.json nav lists %q but pages/%s.json does not exist", slug, slug)
}
}
return nil
}
func (g *generator) loadIcons() error {
g.icons = map[string]template.HTML{}
files, err := filepath.Glob(filepath.Join(g.srcDir, "icons", "*.svg"))
if err != nil {
return err
}
for _, f := range files {
b, err := os.ReadFile(f)
if err != nil {
return err
}
name := strings.TrimSuffix(filepath.Base(f), ".svg")
g.icons[name] = template.HTML(strings.TrimSpace(string(b)))
}
return nil
}
// copyStatic copies static/ to docs/assets/ and derives the cache busting
// version from the contents.
func (g *generator) copyStatic() error {
files, err := filepath.Glob(filepath.Join(g.srcDir, "static", "*"))
if err != nil {
return err
}
sort.Strings(files)
h := sha1.New()
for _, f := range files {
b, err := os.ReadFile(f)
if err != nil {
return err
}
h.Write(b)
if err := g.write(path.Join("assets", filepath.Base(f)), b); err != nil {
return err
}
}
g.version = hex.EncodeToString(h.Sum(nil))[:8]
return nil
}
func (g *generator) copyAppIcons() error {
keys := make([]string, 0, len(g.site.Apps))
for k := range g.site.Apps {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
app := g.site.Apps[k]
b, err := os.ReadFile(filepath.Join(g.webDir, filepath.FromSlash(app.Icon)))
if err != nil {
g.problems = append(g.problems, fmt.Sprintf("app %q: icon %s not found", k, app.Icon))
continue
}
rel := path.Join("assets", "apps", k+strings.ToLower(path.Ext(app.Icon)))
if err := g.write(rel, b); err != nil {
return err
}
g.appSrc[k] = rel
}
return nil
}
func (g *generator) parseTemplates() error {
t := template.New("").Funcs(template.FuncMap{
"tr": g.tr,
"trs": g.trs,
"ui": g.ui,
"uis": g.uis,
"href": g.href,
"label": g.label,
"pageURL": g.pageURL,
"absURL": g.absURL,
"img": g.img,
"app": g.app,
"icon": g.icon,
"code": highlight,
"ext": isExternal,
"add": func(a, b int) int { return a + b },
"mod": func(a, b int) int { return a % b },
"fail": func(msg string) (string, error) { return "", errors.New(msg) },
})
t, err := t.ParseGlob(filepath.Join(g.srcDir, "templates", "*.html"))
if err != nil {
return err
}
g.tpl = t
return nil
}
func (g *generator) render(lang Language, p *Page) error {
g.lang, g.page = lang, p
g.root = ""
if lang.Dir != "" {
g.root = "../"
}
v := View{
Site: &g.site,
Page: p,
Lang: lang,
Root: g.root,
Year: time.Now().Year(),
Version: g.version,
OGImage: strings.TrimRight(g.site.BaseURL, "/") + "/" + strings.TrimPrefix(firstNonEmpty(p.OGImage, g.site.OGImage), "/"),
}
var features []*Page
for _, slug := range g.site.Nav {
np := g.pages[slug]
v.NavPages = append(v.NavPages, np)
if np.Feature {
features = append(features, np)
}
}
if p.Feature {
for i, fp := range features {
if fp != p {
continue
}
if i > 0 {
v.Prev = features[i-1]
}
if i+1 < len(features) {
v.Next = features[i+1]
}
}
}
var buf bytes.Buffer
if err := g.tpl.ExecuteTemplate(&buf, "layout", v); err != nil {
return err
}
// html/template drops comments, so the notice is added afterwards.
out := bytes.Replace(buf.Bytes(), []byte("\n"), []byte("\n"+generatedNotice+"\n"), 1)
return g.write(pageFile(lang, p.Slug), out)
}
const generatedNotice = ""
func firstNonEmpty(s ...string) string {
for _, v := range s {
if v != "" {
return v
}
}
return ""
}
// pageFile is the output path of a page, relative to docs/.
func pageFile(lang Language, slug string) string {
return path.Join(lang.Dir, slug+".html")
}
// write saves a file below docs/ and records it in the manifest.
func (g *generator) write(rel string, b []byte) error {
full := filepath.Join(g.outDir, filepath.FromSlash(rel))
if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
return err
}
if old, err := os.ReadFile(full); err != nil || !bytes.Equal(old, b) {
if err := os.WriteFile(full, b, 0o644); err != nil {
return err
}
}
g.written = append(g.written, rel)
return nil
}
// cleanStale removes the files the previous run wrote that this run did not.
func (g *generator) cleanStale() error {
manifest := filepath.Join(g.outDir, manifestName)
var old []string
if b, err := os.ReadFile(manifest); err == nil {
if err := json.Unmarshal(b, &old); err != nil {
return fmt.Errorf("%s: %w", manifest, err)
}
}
now := map[string]bool{}
for _, f := range g.written {
now[f] = true
}
for _, f := range old {
if now[f] || strings.Contains(f, "..") {
continue
}
full := filepath.Join(g.outDir, filepath.FromSlash(f))
if err := os.Remove(full); err == nil {
fmt.Println("removed stale", f)
}
}
sort.Strings(g.written)
b, err := json.MarshalIndent(g.written, "", " ")
if err != nil {
return err
}
return os.WriteFile(manifest, append(b, '\n'), 0o644)
}
func (g *generator) writeSitemap() error {
var b strings.Builder
b.WriteString(`` + "\n")
b.WriteString(`