// 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(`` + "\n") for _, lang := range g.site.Languages { for _, slug := range g.slugs { fmt.Fprintf(&b, " \n %s\n", g.absURL(slug, lang)) for _, alt := range g.site.Languages { fmt.Fprintf(&b, " \n", alt.HTML, g.absURL(slug, alt)) } b.WriteString(" \n") } } b.WriteString("\n") if err := g.write("sitemap.xml", []byte(b.String())); err != nil { return err } robots := "User-agent: *\nAllow: /\n\nSitemap: " + strings.TrimRight(g.site.BaseURL, "/") + "/sitemap.xml\n" return g.write("robots.txt", []byte(robots)) } func (g *generator) report() { fmt.Printf("sitegen: wrote %d pages in %d languages to %s\n", len(g.slugs), len(g.site.Languages), g.outDir) for _, p := range g.problems { fmt.Println(" warning:", p) } if len(g.missingImg) > 0 { names := make([]string, 0, len(g.missingImg)) for n := range g.missingImg { names = append(names, n) } sort.Strings(names) fmt.Println(" screenshots still to add (their sections render without an image):") for _, n := range names { fmt.Println(" docs/img/" + n + ".webp") } } for _, lang := range g.site.Languages { miss := g.missingText[lang.Code] if len(miss) == 0 { continue } fmt.Printf(" %s: %d strings fall back to English, e.g.:\n", lang.Code, len(miss)) n := 0 for s := range miss { if n == 5 { break } fmt.Printf(" %q\n", s) n++ } } } // ---- template functions ---- func (g *generator) text(t Text) string { s, ok := t.get(g.lang.Code) if !ok && s != "" { if g.missingText[g.lang.Code] == nil { g.missingText[g.lang.Code] = map[string]bool{} } key := stripTags(s) if len(key) > 60 { key = key[:60] } g.missingText[g.lang.Code][key] = true } return s } // tr renders translated HTML. func (g *generator) tr(t Text) template.HTML { return template.HTML(g.text(t)) } // trs renders translated plain text, for attributes and the . func (g *generator) trs(t Text) string { return stripTags(g.text(t)) } func (g *generator) ui(key string) (template.HTML, error) { t, ok := g.site.UI[key] if !ok { return "", fmt.Errorf("site.json ui has no %q", key) } return g.tr(t), nil } func (g *generator) uis(key string) (string, error) { t, ok := g.site.UI[key] if !ok { return "", fmt.Errorf("site.json ui has no %q", key) } return g.trs(t), nil } var tagRe = regexp.MustCompile(`<[^>]*>`) func stripTags(s string) string { s = tagRe.ReplaceAllString(s, "") s = strings.NewReplacer("&", "&", " ", " ", "<", "<", ">", ">").Replace(s) return strings.Join(strings.Fields(s), " ") } // href resolves the link forms pages use: // // @slug or @slug#id a page in the current language // dl:file a file of the latest GitHub release // /path a file at the site root (docs/) // anything else used as written (https:, mailto:, #id) func (g *generator) href(h string) (string, error) { switch { case strings.HasPrefix(h, "@"): slug, frag, _ := strings.Cut(h[1:], "#") if g.pages[slug] == nil { return "", fmt.Errorf("link to unknown page %q", slug) } u := g.pageURL(slug, g.lang) if frag != "" { u += "#" + frag } return u, nil case strings.HasPrefix(h, "dl:"): return strings.TrimRight(g.site.Downloads, "/") + "/" + h[3:], nil case strings.HasPrefix(h, "/") && !strings.HasPrefix(h, "//"): return g.root + h[1:], nil } return h, nil } // label is a link's text: its own label, or the nav name of the page an // "@slug" link points to when the label is left out. func (g *generator) label(l Link) (template.HTML, error) { if len(l.Label) > 0 { return g.tr(l.Label), nil } slug, _, _ := strings.Cut(strings.TrimPrefix(l.Href, "@"), "#") p := g.pages[slug] if !strings.HasPrefix(l.Href, "@") || p == nil { return "", fmt.Errorf("link %q needs a label", l.Href) } return g.tr(p.Nav), nil } // pageURL links from the page being rendered to slug in lang. func (g *generator) pageURL(slug string, lang Language) string { file := slug + ".html" if slug == "index" { file = "" } if lang.Code == g.lang.Code { if file == "" { return "./" } return file } prefix := g.root if lang.Dir != "" { prefix += lang.Dir + "/" } if prefix == "" && file == "" { return "./" } return prefix + file } // absURL is the canonical address of slug in lang. func (g *generator) absURL(slug string, lang Language) string { u := strings.TrimRight(g.site.BaseURL, "/") + "/" if lang.Dir != "" { u += lang.Dir + "/" } if slug != "index" { u += slug + ".html" } return u } // img finds docs/img/.{webp,png,jpg,jpeg,svg}. It returns nil (and // notes the name) when the screenshot has not been added yet. func (g *generator) img(name string) *Img { if name == "" { return nil } if im, ok := g.imgs[name]; ok { if im == nil { return nil } c := *im c.Src = g.root + c.Src return &c } candidates := []string{name} if path.Ext(name) == "" { candidates = []string{name + ".webp", name + ".png", name + ".jpg", name + ".jpeg", name + ".svg"} } for _, c := range candidates { full := filepath.Join(g.outDir, "img", filepath.FromSlash(c)) f, err := os.Open(full) if err != nil { continue } w, h := imageSize(f, path.Ext(c)) f.Close() g.imgs[name] = &Img{Src: "img/" + c, W: w, H: h} return g.img(name) } g.imgs[name] = nil g.missingImg[name] = true return nil } // imageSize reads the pixel size of a WebP, PNG or JPEG without decoding it. // It returns zeros for formats it cannot read (SVG). func imageSize(r io.Reader, ext string) (int, int) { if strings.EqualFold(ext, ".webp") { head := make([]byte, 30) if _, err := io.ReadFull(r, head); err != nil { return 0, 0 } w, h, _ := webpSize(head) return w, h } cfg, _, err := image.DecodeConfig(r) if err != nil { return 0, 0 } return cfg.Width, cfg.Height } // webpSize parses the canvas size from the first 30 bytes of a WebP file. func webpSize(b []byte) (int, int, bool) { if len(b) < 30 || string(b[0:4]) != "RIFF" || string(b[8:12]) != "WEBP" { return 0, 0, false } switch string(b[12:16]) { case "VP8X": w := 1 + (int(b[24]) | int(b[25])<<8 | int(b[26])<<16) h := 1 + (int(b[27]) | int(b[28])<<8 | int(b[29])<<16) return w, h, true case "VP8 ": w := int(binary.LittleEndian.Uint16(b[26:28]) & 0x3fff) h := int(binary.LittleEndian.Uint16(b[28:30]) & 0x3fff) return w, h, true case "VP8L": bits := binary.LittleEndian.Uint32(b[21:25]) return int(bits&0x3fff) + 1, int((bits>>14)&0x3fff) + 1, true } return 0, 0, false } func (g *generator) app(key string) (*AppView, error) { a, ok := g.site.Apps[key] if !ok { return nil, fmt.Errorf("site.json apps has no %q", key) } src, ok := g.appSrc[key] if !ok { return nil, nil } return &AppView{Name: g.tr(a.Name), Src: g.root + src}, nil } func (g *generator) icon(name string) (template.HTML, error) { s, ok := g.icons[name] if !ok { return "", fmt.Errorf("icons/%s.svg does not exist", name) } return s, nil } func isExternal(h string) bool { return strings.HasPrefix(h, "http://") || strings.HasPrefix(h, "https://") } // ---- code highlighting ---- var codeRe = regexp.MustCompile(`(//[^\n]*)|("(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*')|\b(var|function|return|if|else|for|new|true|false|null)\b|\b([A-Za-z_][\w]*)\(`) // highlight escapes a JavaScript snippet and marks comments, strings, // keywords and called functions with spans the style sheet colours. func highlight(src string) template.HTML { var b strings.Builder last := 0 for _, m := range codeRe.FindAllStringSubmatchIndex(src, -1) { b.WriteString(template.HTMLEscapeString(src[last:m[0]])) switch { case m[2] >= 0: wrap(&b, "c", src[m[2]:m[3]]) case m[4] >= 0: wrap(&b, "s", src[m[4]:m[5]]) case m[6] >= 0: wrap(&b, "k", src[m[6]:m[7]]) case m[8] >= 0: wrap(&b, "f", src[m[8]:m[9]]) b.WriteString("(") } last = m[1] } b.WriteString(template.HTMLEscapeString(src[last:])) return template.HTML(b.String()) } func wrap(b *strings.Builder, class, s string) { b.WriteString(``) b.WriteString(template.HTMLEscapeString(s)) b.WriteString("") }