raz / commit fe3051dc

commit
fe3051dcc617848a6022e85124c11a3f4104cfb6
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
d438392d
site: the builders are raz programs, no Python

Build, Source and Verify replace build.py, source.py and check.py;
Releases (releases.py), Site, Markup and Sha256 are their modules. The
Makefile builds them with ./raz into build/site/; make site-check runs
Verify. The pages are byte-identical to the Python's; the source
archives' gzip bytes now come from gzip -9n.

patch · log

17 files changed, +2567 -895

.gitignore (history) modified +0 -1

@@ -1,7 +1,6 @@
11 build/
22 .wrangler/
33 /site/public/source/
4-/site/__pycache__/
54 /raz
65 # Programs make check builds next to their sources
76 /examples/*

CLAUDE.md modified +5 -3

@@ -81,9 +81,11 @@
8181
8282 The website's `/source/` browser and releases are built by ladle,
8383 pinned with its checksum under `site/tools/`. `make site` builds the
84-main pages and then the source site. Wrangler runs `make site-source`
85-before uploading, so the generated Git store stays out of this
86-repository. `site/README.md` gives the build, release records and
84+main pages and then the source site, with raz programs, `site/Build.raz`,
85+`Source.raz` and `Verify.raz`, which the Makefile builds with this
86+repository's `./raz` into `build/site/`. Wrangler runs `make site-source`
87+(which builds `raz` first) before uploading, so the generated Git store
88+stays out of this repository. `site/README.md` gives the build, release records and
8789 checks. `site/releases` lists website releases whose tags aren't
8890 pushed yet (none now); it never makes a tag.
8991

Makefile (history) modified +20 -10

@@ -80,11 +80,11 @@
8080 build/Stress 40000 200
8181 (ulimit -v 60000; build/Stress fail)
8282
83-# the formatter, tools/Pretty.raz: the library, examples and tools are
83+# the formatter, tools/Pretty.raz: the library, examples, tools and site programs are
8484 # formatted already
8585 fmt: raz | build
8686 ./raz -o build/Pretty tools/Pretty.raz
87- @fail=0; for f in lib/*.raz examples/*.raz tools/*.raz src/*.raz src/test/*.raz; do \
87+ @fail=0; for f in lib/*.raz examples/*.raz tools/*.raz site/*.raz src/*.raz src/test/*.raz; do \
8888 build/Pretty $$f | cmp -s - $$f || { echo "not formatted: $$f"; fail=1; }; \
8989 done; test $$fail = 0
9090
@@ -147,7 +147,7 @@
147147 # formatter, Doc and the Scan they share, and raztest) and the manual
148148 # pages, V being what raz --version says. It is made of the commit
149149 # REV, HEAD unless given: CI packs the tag it checked out, and
150-# site/build.py each tag it lacks. A release whose tag isn't pushed yet
150+# site/Build.raz each tag it lacks. A release whose tag isn't pushed yet
151151 # is made with VERSION, its version without the v: the same tarball as
152152 # the tag's, once the tag is at REV.
153153 #
@@ -180,21 +180,31 @@
180180
181181 # The website, plain files in site/public/: its home page, the tour
182182 # "Raz, Set, Go" (whose programs are run here, so the output shown is
183-# real), the report and the latest release's tarball. site/build.py
184-# says how; it needs ./raz and pandoc. RELEASES, "vX.Y.Z=COMMIT ...",
183+# real), the report and the latest release's tarball. site/Build.raz
184+# says how; it needs ./raz, pandoc and pdfinfo. RELEASES, "vX.Y.Z=COMMIT ...",
185185 # adds release records to those kept in site/releases. site-source runs
186186 # ladle after the pages: its Git store and releases live under /source/,
187187 # with their headers merged at the upload's root. The pinned ladle is
188188 # bundled for Cloudflare; LADLE may name a locally built one instead.
189+# The site's programs are raz programs, site/Build.raz, Source.raz and
190+# Verify.raz, built by this raz into build/site/.
189191 LADLE ?=
190-site: raz pdf
191- python3 site/build.py $(RELEASES)
192+build/site/%: site/%.raz site/*.raz raz
193+ mkdir -p build/site
194+ ./raz -Werror -o $@ site/$*.raz
195+
196+site: raz pdf build/site/Build
197+ build/site/Build $(RELEASES)
192198 $(MAKE) site-source
193199
194200 # Wrangler runs this before deploying the committed pages. The generated
195201 # Git store must never be committed: otherwise later stores contain copies
196202 # of earlier ones. See site/README.md for the release and upload procedure.
197-site-source:
198- python3 site/source.py $(if $(LADLE),--ladle $(LADLE)) $(RELEASES)
203+site-source: build/site/Source
204+ build/site/Source $(if $(LADLE),--ladle $(LADLE)) $(RELEASES)
205+
206+# Checks the site's release selection against small real Git repositories.
207+site-check: build/site/Verify
208+ build/site/Verify
199209
200-.PHONY: prev-bench fixpoint check gdb bench kernels stress alpine fmt loc man pdf dist site site-source clean install uninstall
210+.PHONY: prev-bench fixpoint check gdb bench kernels stress alpine fmt loc man pdf dist site site-source site-check clean install uninstall

README.md (history) modified +4 -3

@@ -81,12 +81,13 @@
8181 make kernels # the code's speed against FPC -O2's (apt-get install fp-compiler)
8282 make stress # 40,000 threads, started and joined
8383 make gdb # gdb stops at a line of raz and names it
84- make fmt # the library, examples and tools are formatted
84+ make fmt # the library, examples, tools and site programs are formatted
8585 make loc # the compiler's lines
8686 make pdf # build/raz.pdf and build/raz-lib.pdf, the two volumes, by pandoc and Chromium
8787 make dist # build/raz-V-linux-x86_64.tar.gz, the release's tarball
88- make site # site/public/, the website, by pandoc and python3
89- make site-source # /source/, its releases and HTTP clone store, by git and Python 3
88+ make site # site/public/, the website, by site/Build.raz, pandoc and pdfinfo
89+ make site-source # /source/, its releases and HTTP clone store, by site/Source.raz, git and ladle
90+ make site-check # the site's release selection, against small real repositories
9091
9192 ## Using it
9293

site/Build.raz (history) added +806 -0

@@ -0,0 +1,806 @@
1+(* Build: the website, plain files in site/public/, made from
2+ site/content/ and the repository.
3+
4+ Build [vX.Y.Z=COMMIT ...]
5+
6+ Run from the repository root, by make site, with ./raz and the
7+ report's PDFs (make pdf) built, and pandoc and pdfinfo on PATH.
8+ site/releases records website distributions whose tags are not
9+ pushed yet. Each additional vX.Y.Z=COMMIT is another such
10+ distribution: it is offered as if the tag were at COMMIT, its
11+ tarball made by make dist with VERSION, the same tarball the tag
12+ will give.
13+
14+ The site is plain files: open public/index.html, or put the folder
15+ on any web server. Nothing runs in the reader's browser; the code on
16+ the tour's pages is run here, by ./raz, and the output shown is what
17+ it printed, so a lesson that stops working fails the build. The
18+ home page offers every release's tarball, made by make dist from
19+ its tag.
20+
21+ Lessons are site/content/<tour>/NN-name.txt, one folder to a tour
22+ (see Tours below):
23+
24+ title: Hello, world (the first lines are "key: value")
25+ part: Raz (the lessons are grouped in parts)
26+ summary: a line for the contents page
27+ ---
28+ Paragraphs, separated by blank lines. `code`, **bold**,
29+ [links](url), "- " lists and pipe tables are understood, and
30+ nothing else.
31+
32+ ```raz Name run
33+ ```
34+
35+ A fenced block "raz Name" is a module, written as Name.raz in a
36+ folder of its own for the lesson. "run" has the build run it and
37+ show what it printed; "fail" runs it and shows the failure it ends
38+ in. A block with nothing in it is taken from doc/raz-tutorial.7,
39+ whose programs make check already runs, by the module's name.
40+
41+ Two other blocks: "```text" is shown as written, and "```sh" is a
42+ shell session: each line that starts with "$ " is run in the
43+ lesson's folder, with raz on the path, and shown with what it
44+ printed.
45+
46+ It depends on Site, Releases, Markup and Sha256, and leaves out
47+ running anything in the reader's browser. *)
48+module Build;
49+import Sys, Files, Buf, Str, Heap, Fmt, Site, Releases, Markup, Sha256;
50+import Names := Vec([]const U8);
51+import Lessons := Vec(Lesson);
52+import Rels := Vec(Releases.Release);
53+import Tars := Vec(Tarball);
54+
55+const
56+ SiteUrl = "https://raz.lucelad.workers.dev"; (* where the pages live, for the preview image *)
57+ Usage = "usage: Build [vX.Y.Z=COMMIT ...]";
58+ (* the head of every page: the arguments are the title (twice), the
59+ site's address, then the way up to the root (six times), the
60+ navigation, the body and the way up again *)
61+ Page = `
62+ <!doctype html>
63+ <html lang="en">
64+ <head>
65+ <meta charset="utf-8">
66+ <meta name="viewport" content="width=device-width, initial-scale=1">
67+ <title>{}</title>
68+ <meta name="description" content="raz: a small systems language in Wirth's tradition, for x86-64 Linux.">
69+ <meta name="theme-color" content="#E07A5F">
70+ <meta property="og:title" content="{}">
71+ <meta property="og:description" content="A small systems language for x86-64 Linux. No run time, no GC, one report.">
72+ <meta property="og:image" content="{}/social.png">
73+ <meta name="twitter:card" content="summary_large_image">
74+ <link rel="icon" href="{}favicon.svg" type="image/svg+xml">
75+ <link rel="icon" href="{}favicon-32.png" type="image/png" sizes="32x32">
76+ <link rel="apple-touch-icon" href="{}apple-touch-icon.png">
77+ <link rel="stylesheet" href="{}style.css">
78+ </head>
79+ <body>
80+ <header><nav><a class="mark" href="{}index.html"><img src="{}logo.svg" width="26" height="26" alt="">raz</a>{}</nav></header>
81+ <main>
82+ {}
83+ </main>
84+ <footer>raz is under the ISC license. <a href="{}source/index.html">Source</a></footer>
85+ </body>
86+ </html>
87+ `;
88+
89+type
90+ (* A tour: a folder of lessons. *)
91+ Tour = record
92+ folder: []const U8; (* in site/content/ *)
93+ outDir: []const U8; (* in site/public/ *)
94+ name: []const U8; (* shown on its pages *)
95+ intro: []const U8; (* the file in site/content/ with the sentence under the name *)
96+ end;
97+
98+ (* A lesson, as its file says. *)
99+ Lesson = record
100+ title: []const U8;
101+ part: []const U8; (* the group it is listed in *)
102+ summary: []const U8; (* its line on the contents page *)
103+ slug: []const U8; (* its file name without number or .txt *)
104+ body: []const U8; (* what follows the --- line *)
105+ end;
106+
107+ (* A release's tarball: its version, file name and SHA-256 as hex. *)
108+ Tarball = record
109+ version: []const U8;
110+ name: []const U8;
111+ digest: []const U8;
112+ end;
113+
114+ (* A fenced block of a lesson, as places in its text: the line of its
115+ opening fence, its info line, its code and the end of its closing
116+ fence. *)
117+ Fence = record
118+ start: INT;
119+ infoLo, infoHi: INT;
120+ codeLo, codeHi: INT;
121+ stop: INT;
122+ end;
123+
124+ (* A program's output: what it wrote, and the status it ended with. *)
125+ Run = record
126+ out, err: Buf.Buf;
127+ status: INT;
128+ end;
129+
130+const
131+ Tours: [2]Tour = [
132+ {folder: "tour", outDir: "tour", name: "Raz, Set, Go", intro: "tour-intro.html"},
133+ {folder: "advanced", outDir: "advanced", name: "More Raz", intro: "advanced-intro.html"}];
134+
135+var
136+ root: []const U8; (* the repository, as an absolute path *)
137+ outDir: []const U8; (* site/public *)
138+ raz: []const U8; (* the compiler, ./raz *)
139+
140+(* ---- the tutorial's programs -------------------------------------- *)
141+
142+(* Adds line as roff wrote it with the escapes undone: a backslash is
143+ written \e, a backquote \(ga and a dot at a line's start \&. *)
144+proc unescape(var b: Buf.Buf; line: []const U8);
145+var a, c, d: Buf.Buf;
146+begin
147+ Buf.init(a, Heap.heap);
148+ Buf.init(c, Heap.heap);
149+ Buf.init(d, Heap.heap);
150+ Str.replace(a, line, "\\&", "");
151+ Str.replace(c, Buf.bytes(a), "\\(ga", "`");
152+ Str.replace(d, Buf.bytes(c), "\\e", "\\");
153+ Buf.str(b, Buf.bytes(d));
154+ Buf.done(a);
155+ Buf.done(c);
156+end;
157+
158+(* Whether the block text has a line that starts "module name" and goes
159+ on with something that isn't part of a word. *)
160+proc declares(block, name: []const U8): BOOL;
161+var all: [][]const U8; line: []const U8; head: []const U8; i: INT;
162+begin
163+ head := Site.cat(["module ", name]);
164+ all := Site.lines(block);
165+ for i := 0 to LEN(all) - 1 do
166+ line := all[i];
167+ if Str.hasPrefix(line, head) then
168+ line := line[LEN(head)..LEN(line)];
169+ if (LEN(line) = 0) or not (Str.isLetter(line[0]) or Str.isDigit(line[0]) or (line[0] = '_')) then
170+ return true;
171+ end;
172+ end;
173+ end;
174+ return false;
175+end;
176+
177+(* The first literal block of the manual page that declares module
178+ name, as raz source; the build stops if there is none. *)
179+proc tutorialModule(name: []const U8): []const U8;
180+var all: [][]const U8; block: Buf.Buf; inside: BOOL; i, n: INT;
181+begin
182+ all := Site.lines(Site.read(Site.cat([root, "/doc/raz-tutorial.7"])));
183+ for i := 0 to LEN(all) - 1 do
184+ if Str.hasPrefix(all[i], ".Bd -literal") then
185+ inside := true;
186+ n := 0;
187+ Buf.init(block, Heap.heap);
188+ elsif inside and (all[i] = ".Ed") then
189+ inside := false;
190+ Buf.add(block, '\n');
191+ if declares(Buf.bytes(block), name) then return Buf.bytes(block); end;
192+ elsif inside then
193+ if n > 0 then Buf.add(block, '\n'); end;
194+ INC(n);
195+ unescape(block, all[i]);
196+ end;
197+ end;
198+ Site.die("no program {} in the tutorial", [Fmt.str(name)]);
199+ return "";
200+end;
201+
202+(* ---- running ------------------------------------------------------ *)
203+
204+(* Compiles and runs the module name in dir with raz run -Werror, and
205+ says what it wrote and how it ended. *)
206+proc runModule(dir, name: []const U8): Run;
207+var r: Run;
208+begin
209+ Buf.init(r.out, Heap.heap);
210+ Buf.init(r.err, Heap.heap);
211+ r.status := Site.capture([raz, "run", "-Werror", Site.cat([name, ".raz"])], dir, [], false, r.out, r.err);
212+ if r.status < 0 then Site.die("can't run {}", [Fmt.str(raz)]); end;
213+ return r;
214+end;
215+
216+(* Adds a shell session: each "$ command" line of script run in dir,
217+ with raz on the path, and its output. *)
218+proc shellHtml(var b: Buf.Buf; dir, script: []const U8);
219+var
220+ bin, shortcut: []const U8; env: [2][]const U8; all: [][]const U8; out, err: Buf.Buf;
221+ text: []const U8; i: INT;
222+begin
223+ bin := Site.cat([dir, "/.bin"]);
224+ Site.makeDirs(bin);
225+ shortcut := Site.cat([bin, "/raz"]);
226+ if not Site.exists(shortcut) then _ := Sys.symlink(raz, shortcut); end; (* raz finds lib/ by its real path *)
227+ env[0] := Site.cat(["PATH=", bin, ":", Sys.env("PATH")]);
228+ env[1] := Site.cat(["RAZLIB=", root, "/lib"]);
229+ Buf.str(b, "<pre class=\"output term\"><code>");
230+ all := Site.lines(script);
231+ (* a final empty line is not a line *)
232+ i := LEN(all);
233+ while (i > 0) and (LEN(all[i - 1]) = 0) do DEC(i); end;
234+ all := all[0..i];
235+ for i := 0 to LEN(all) - 1 do
236+ if i > 0 then Buf.add(b, '\n'); end;
237+ if not Str.hasPrefix(all[i], "$ ") then
238+ Markup.escape(b, all[i], true);
239+ else
240+ Buf.str(b, "<span class=\"cmd\">");
241+ Markup.escape(b, all[i], true);
242+ Buf.str(b, "</span>");
243+ Buf.init(out, Heap.heap);
244+ Buf.init(err, Heap.heap);
245+ _ := Site.capture(["/bin/sh", "-c", all[i][2..LEN(all[i])]], dir, env, true, out, err);
246+ text := Buf.bytes(out);
247+ while (LEN(text) > 0) and (text[LEN(text) - 1] = '\n') do text := text[0..LEN(text) - 1]; end;
248+ if LEN(text) > 0 then
249+ Buf.add(b, '\n');
250+ Markup.escape(b, text, true);
251+ end;
252+ end;
253+ end;
254+ Buf.str(b, "</code></pre>");
255+end;
256+
257+(* Adds what a program wrote: its output, and its errors in a span. *)
258+proc outputHtml(var b: Buf.Buf; const r: Run);
259+begin
260+ Buf.str(b, "<pre class=\"output\"><code>");
261+ Markup.escape(b, Buf.bytes(r.out), true);
262+ if r.err.len > 0 then
263+ Buf.str(b, "<span class=\"err\">");
264+ Markup.escape(b, Buf.bytes(r.err), true);
265+ Buf.str(b, "</span>");
266+ end;
267+ Buf.str(b, "</code></pre>");
268+end;
269+
270+(* ---- lessons ------------------------------------------------------ *)
271+
272+(* s without the line feeds at its end. *)
273+proc chop(s: []const U8): []const U8;
274+begin
275+ while (LEN(s) > 0) and (s[LEN(s) - 1] = '\n') do s := s[0..LEN(s) - 1]; end;
276+ return s;
277+end;
278+
279+(* The lesson in the file at path. Its head is lines of "key: value"
280+ up to a line of ---; the rest is its body. *)
281+proc readLesson(path: []const U8): Lesson;
282+var head, name: []const U8; all: [][]const U8; l: Lesson; key, value: []const U8; found: BOOL; i: INT;
283+begin
284+ head, l.body, found := Str.cut(Site.read(path), "\n---\n");
285+ all := Site.lines(Str.trim(head));
286+ for i := 0 to LEN(all) - 1 do
287+ key, value, found := Str.cut(all[i], ": ");
288+ if not found then Site.die("{}: not \"key: value\": {}", [Fmt.str(path), Fmt.str(all[i])]); end;
289+ if key = "title" then l.title := value;
290+ elsif key = "part" then l.part := value;
291+ elsif key = "summary" then l.summary := value;
292+ end;
293+ end;
294+ name := path[Str.findLast(path, "/") + 1..LEN(path)];
295+ name := name[0..LEN(name) - 4]; (* without .txt *)
296+ i := 0;
297+ while (i < LEN(name)) and Str.isDigit(name[i]) do INC(i); end;
298+ if (i > 0) and (i < LEN(name)) and (name[i] = '-') then name := name[i + 1..LEN(name)]; end;
299+ l.slug := name;
300+ return l;
301+end;
302+
303+(* Finds the first fenced block of s that starts on a line after from (from the very start, if from is 0): a line of "```" and an info
304+ line ("raz Name flags", "text" or "sh"), the code, and a line of only
305+ "```". False if there is none. *)
306+proc nextFence(s: []const U8; from: INT; var f: Fence): BOOL;
307+var p, eol, q, next: INT; info: []const U8;
308+begin
309+ p := from;
310+ if from > 0 then
311+ p := Str.findFrom(s, "\n", from);
312+ if p < 0 then return false; end;
313+ INC(p);
314+ end;
315+ while p < LEN(s) do
316+ eol := Str.findFrom(s, "\n", p);
317+ if eol < 0 then return false; end;
318+ if (eol - p >= 3) and Str.hasPrefix(s[p..eol], "```") then
319+ info := s[p + 3..eol];
320+ q := eol + 1;
321+ while ((info = "text") or (info = "sh") or Str.hasPrefix(info, "raz ")) and (q < LEN(s)) do
322+ if Str.hasPrefix(s[q..LEN(s)], "```") and ((q + 3 = LEN(s)) or (s[q + 3] = '\n')) then
323+ f := {start: p, infoLo: p + 3, infoHi: eol, codeLo: eol + 1, codeHi: q, stop: q + 3};
324+ return true;
325+ end;
326+ next := Str.findFrom(s, "\n", q);
327+ if next < 0 then break; end;
328+ q := next + 1;
329+ end;
330+ end;
331+ p := eol + 1;
332+ end;
333+ return false;
334+end;
335+
336+(* Starts a new part of the lesson in b: after a line feed, unless it is
337+ the first. *)
338+proc newPart(var b: Buf.Buf);
339+begin
340+ if b.len > 0 then Buf.add(b, '\n'); end;
341+end;
342+
343+(* Adds a "raz Name flags" block of a lesson: its code, taken from the
344+ tutorial if it has none, written to dir as Name.raz, and, if flags
345+ say run or fail, the output of running it. *)
346+proc razBlock(var b: Buf.Buf; const l: Lesson; dir, info, written: []const U8);
347+var words: [][]const U8; name, source: []const U8; r: Run; run, fail: BOOL; i: INT;
348+begin
349+ words := Site.words(info);
350+ if LEN(words) < 2 then Site.die("{}: a raz block needs a name", [Fmt.str(l.slug)]); end;
351+ name := words[1];
352+ source := written;
353+ if LEN(Str.trim(source)) = 0 then source := tutorialModule(name); end;
354+ Site.write(Site.cat([dir, "/", name, ".raz"]), source);
355+ newPart(b);
356+ Buf.str(b, "<div class=\"file\"><span>"); Buf.str(b, name); Buf.str(b, ".raz</span></div>");
357+ Buf.str(b, "<pre class=\"code\"><code>");
358+ Markup.highlight(b, chop(source));
359+ Buf.str(b, "</code></pre>");
360+ for i := 2 to LEN(words) - 1 do
361+ run := run or (words[i] = "run");
362+ fail := fail or (words[i] = "fail");
363+ end;
364+ if run or fail then
365+ r := runModule(dir, name);
366+ if fail = (r.status = 0) then
367+ Site.die("{}: {} ended with status {}\n{}{}", [Fmt.str(l.slug), Fmt.str(name), Fmt.int(r.status),
368+ Fmt.str(Buf.bytes(r.out)), Fmt.str(Buf.bytes(r.err))]);
369+ end;
370+ newPart(b);
371+ outputHtml(b, r);
372+ end;
373+end;
374+
375+(* The lesson's page content, one part to a line; it runs its programs
376+ in a folder of its own. *)
377+proc lessonBody(const l: Lesson): []const U8;
378+var b: Buf.Buf; dir, info: []const U8; f: Fence; pos, textEnd: INT; found: BOOL;
379+begin
380+ Buf.init(b, Heap.heap);
381+ dir := Site.tempDir();
382+ pos := 0;
383+ repeat
384+ found := nextFence(l.body, pos, f);
385+ textEnd := LEN(l.body);
386+ if found then textEnd := f.start; end;
387+ if LEN(Str.trim(l.body[pos..textEnd])) > 0 then
388+ newPart(b);
389+ Markup.prose(b, l.body[pos..textEnd]);
390+ end;
391+ if found then
392+ info := l.body[f.infoLo..f.infoHi];
393+ if info = "text" then
394+ newPart(b);
395+ Buf.str(b, "<pre class=\"code\"><code>");
396+ Markup.escape(b, chop(l.body[f.codeLo..f.codeHi]), true);
397+ Buf.str(b, "</code></pre>");
398+ elsif info = "sh" then
399+ newPart(b);
400+ shellHtml(b, dir, l.body[f.codeLo..f.codeHi]);
401+ else
402+ razBlock(b, l, dir, info, l.body[f.codeLo..f.codeHi]);
403+ end;
404+ pos := f.stop;
405+ end;
406+ until not found;
407+ _ := Files.removeTree(dir);
408+ return Buf.bytes(b);
409+end;
410+
411+(* ---- pages -------------------------------------------------------- *)
412+
413+(* The way up from a page depth folders down: "../" depth times. *)
414+proc wayUp(depth: INT): []const U8;
415+var b: Buf.Buf; i: INT;
416+begin
417+ Buf.init(b, Heap.heap);
418+ for i := 1 to depth do Buf.str(b, "../"); end;
419+ return Buf.bytes(b);
420+end;
421+
422+(* Adds a link of the navigation bar, marked if it is the current one. *)
423+proc navLink(var b: Buf.Buf; up, key, current, href, label: []const U8);
424+begin
425+ Buf.str(b, "<a href=\""); Buf.str(b, up); Buf.str(b, href); Buf.str(b, "\"");
426+ if key = current then Buf.str(b, " aria-current=\"page\""); end;
427+ Buf.add(b, '>'); Buf.str(b, label); Buf.str(b, "</a>");
428+end;
429+
430+(* A whole page: title, body, how many folders down it is and which
431+ navigation entry it belongs to. *)
432+proc page(title, body: []const U8; depth: INT; current: []const U8): []const U8;
433+var b, nav: Buf.Buf; up, t: []const U8;
434+begin
435+ up := wayUp(depth);
436+ t := Markup.escaped(title, true);
437+ Buf.init(nav, Heap.heap);
438+ navLink(nav, up, "tour", current, "tour/index.html", "Raz, Set, Go");
439+ navLink(nav, up, "advanced", current, "advanced/index.html", "More Raz");
440+ navLink(nav, up, "spec", current, "spec.html", "Report");
441+ navLink(nav, up, "source", current, "source/index.html", "Source");
442+ navLink(nav, up, "get", current, "index.html#download", "Download");
443+ Buf.init(b, Heap.heap);
444+ Fmt.write(b, Page, [Fmt.str(t), Fmt.str(t), Fmt.str(SiteUrl), Fmt.str(up), Fmt.str(up), Fmt.str(up),
445+ Fmt.str(up), Fmt.str(up), Fmt.str(up), Fmt.str(Buf.bytes(nav)), Fmt.str(body), Fmt.str(up)]);
446+ Buf.done(nav);
447+ return Buf.bytes(b);
448+end;
449+
450+(* Writes text to path under site/public. *)
451+proc put(path, text: []const U8);
452+begin
453+ Site.write(Site.cat([outDir, "/", path]), text);
454+end;
455+
456+(* The parts the lessons are grouped in, in order of first appearance. *)
457+proc partsOf(lessons: []Lesson): [][]const U8;
458+var v: Names.Vec; i, k: INT; seen: BOOL;
459+begin
460+ Names.init(v, Heap.heap);
461+ for i := 0 to LEN(lessons) - 1 do
462+ seen := false;
463+ for k := 0 to v.len - 1 do seen := seen or (Names.all(v)[k] = lessons[i].part); end;
464+ if not seen then Names.push(v, lessons[i].part); end;
465+ end;
466+ return Names.all(v);
467+end;
468+
469+(* The number of the first lesson of part. *)
470+proc firstOf(lessons: []Lesson; part: []const U8): INT;
471+var i: INT;
472+begin
473+ for i := 0 to LEN(lessons) - 1 do
474+ if lessons[i].part = part then return i + 1; end;
475+ end;
476+ return 0;
477+end;
478+
479+(* Adds the side list of the lesson n: every part and its lessons, the
480+ one on show marked. *)
481+proc contents(var b: Buf.Buf; lessons: []Lesson; parts: [][]const U8; n: INT);
482+var p, i: INT;
483+begin
484+ for p := 0 to LEN(parts) - 1 do
485+ if p > 0 then Buf.add(b, '\n'); end;
486+ Fmt.write(b, "<h3>{}</h3><ol start='{}'>", [Fmt.str(parts[p]), Fmt.int(firstOf(lessons, parts[p]))]);
487+ for i := 0 to LEN(lessons) - 1 do
488+ if lessons[i].part = parts[p] then
489+ Buf.add(b, '\n');
490+ Fmt.write(b, "<li><a href=\"{}.html\"", [Fmt.str(lessons[i].slug)]);
491+ if i = n then Buf.str(b, " aria-current=\"page\""); end;
492+ Fmt.write(b, ">{}</a></li>", [Fmt.str(Markup.escaped(lessons[i].title, true))]);
493+ end;
494+ end;
495+ Buf.str(b, "\n</ol>");
496+ end;
497+end;
498+
499+(* Adds the links under lesson n: the one before, the contents, the one
500+ after, or, past the last, next, an (address, label) pair. *)
501+proc pager(var b: Buf.Buf; lessons: []Lesson; n: INT; nextHref, nextLabel: []const U8);
502+begin
503+ if n > 0 then
504+ Fmt.write(b, "<a href=\"{}.html\">&larr; {}</a>",
505+ [Fmt.str(lessons[n - 1].slug), Fmt.str(Markup.escaped(lessons[n - 1].title, true))]);
506+ end;
507+ Buf.str(b, "<a href=\"index.html\">Contents</a>");
508+ if n + 1 < LEN(lessons) then
509+ Fmt.write(b, "<a class=\"next\" href=\"{}.html\">{} &rarr;</a>",
510+ [Fmt.str(lessons[n + 1].slug), Fmt.str(Markup.escaped(lessons[n + 1].title, true))]);
511+ else
512+ Fmt.write(b, "<a class=\"next\" href=\"{}\">{} &rarr;</a>", [Fmt.str(nextHref), Fmt.str(nextLabel)]);
513+ end;
514+end;
515+
516+(* Writes the page of lesson n of a tour. *)
517+proc lessonPage(const t: Tour; lessons: []Lesson; parts: [][]const U8; n: INT; nextHref, nextLabel: []const U8);
518+var b, toc, pg: Buf.Buf; l: Lesson;
519+begin
520+ l := lessons[n];
521+ Buf.init(toc, Heap.heap);
522+ Buf.init(pg, Heap.heap);
523+ Buf.init(b, Heap.heap);
524+ contents(toc, lessons, parts, n);
525+ pager(pg, lessons, n, nextHref, nextLabel);
526+ Fmt.write(b, "<div class=\"tour\"><aside><h2>{}</h2>{}</aside><article><p class=\"kicker\">{} &middot; lesson {} of {}</p><h1>{}</h1>\n",
527+ [Fmt.str(t.name), Fmt.str(Buf.bytes(toc)), Fmt.str(l.part), Fmt.int(n + 1), Fmt.int(LEN(lessons)),
528+ Fmt.str(Markup.escaped(l.title, true))]);
529+ Buf.str(b, lessonBody(l));
530+ Buf.str(b, "<p class=\"tryit\">Save a program under its module&rsquo;s name and run it with <code>raz run Name.raz</code>.</p>");
531+ Fmt.write(b, "<div class=\"pager\">{}</div></article></div>", [Fmt.str(Buf.bytes(pg))]);
532+ put(Site.cat([t.outDir, "/", l.slug, ".html"]),
533+ page(Site.cat([l.title, " - ", t.name]), Buf.bytes(b), 1, t.folder));
534+ Buf.done(toc);
535+ Buf.done(pg);
536+end;
537+
538+(* Writes a tour's contents page. *)
539+proc contentsPage(const t: Tour; lessons: []Lesson; parts: [][]const U8);
540+var b: Buf.Buf; p, i: INT;
541+begin
542+ Buf.init(b, Heap.heap);
543+ Buf.str(b, "<div class=\"contents\">");
544+ Buf.str(b, Site.read(Site.cat([root, "/site/content/", t.intro])));
545+ for p := 0 to LEN(parts) - 1 do
546+ if p > 0 then Buf.add(b, '\n'); end;
547+ Fmt.write(b, "<h2>{}</h2><ol start='{}'>", [Fmt.str(parts[p]), Fmt.int(firstOf(lessons, parts[p]))]);
548+ for i := 0 to LEN(lessons) - 1 do
549+ if lessons[i].part = parts[p] then
550+ Fmt.write(b, "\n<li><a href=\"{}.html\">{}</a> <span>{}</span></li>",
551+ [Fmt.str(lessons[i].slug), Fmt.str(Markup.escaped(lessons[i].title, true)),
552+ Fmt.str(Markup.escaped(lessons[i].summary, true))]);
553+ end;
554+ end;
555+ Buf.str(b, "\n</ol>");
556+ end;
557+ Buf.str(b, "</div>");
558+ put(Site.cat([t.outDir, "/index.html"]), page(t.name, Buf.bytes(b), 1, t.folder));
559+end;
560+
561+(* Writes a tour's pages: a page to each lesson and a contents page.
562+ nextHref and nextLabel say what follows its last lesson. *)
563+proc buildTour(const t: Tour; lessons: []Lesson; nextHref, nextLabel: []const U8);
564+var parts: [][]const U8; n: INT;
565+begin
566+ parts := partsOf(lessons);
567+ for n := 0 to LEN(lessons) - 1 do lessonPage(t, lessons, parts, n, nextHref, nextLabel); end;
568+ contentsPage(t, lessons, parts);
569+end;
570+
571+(* Whether name is a lesson's file: digits, a dash, anything, .txt *)
572+proc isLesson(name: []const U8): BOOL;
573+var i: INT;
574+begin
575+ while (i < LEN(name)) and Str.isDigit(name[i]) do INC(i); end;
576+ return (i > 0) and (i < LEN(name)) and (name[i] = '-') and Str.hasSuffix(name, ".txt");
577+end;
578+
579+(* The lessons of a tour's folder, in the order of their file names. *)
580+proc readLessons(const t: Tour): []Lesson;
581+var v: Lessons.Vec; names: [][]const U8; dir: []const U8; i: INT;
582+begin
583+ Lessons.init(v, Heap.heap);
584+ dir := Site.cat([root, "/site/content/", t.folder]);
585+ names := Site.dirNames(dir);
586+ for i := 0 to LEN(names) - 1 do
587+ if isLesson(names[i]) then Lessons.push(v, readLesson(Site.cat([dir, "/", names[i]]))); end;
588+ end;
589+ return Lessons.all(v);
590+end;
591+
592+(* Writes the report's page, which pandoc makes of the two volumes. *)
593+proc buildSpec;
594+var out, body: Buf.Buf; status: INT;
595+begin
596+ Buf.init(out, Heap.heap);
597+ (* --columns is wide enough that no row of a table is "long": pandoc
598+ would otherwise give each column an equal share of the width *)
599+ status := Site.captureOut(["pandoc", Site.cat([root, "/doc/raz.md"]), Site.cat([root, "/doc/raz-lib.md"]),
600+ "-s", "--template", Site.cat([root, "/site/content/spec.tmpl"]), "--toc", "--toc-depth=1",
601+ "--shift-heading-level-by=-1", "--no-highlight", "-t", "html", "--columns=10000"], "", [], out);
602+ if status = Sys.errNoEntry then Site.die("pandoc makes the report's page: apt-get install pandoc", []); end;
603+ if status # 0 then Site.die("pandoc failed", []); end;
604+ Buf.init(body, Heap.heap);
605+ Buf.str(body, "<div class=\"spec\">");
606+ Buf.str(body, Buf.bytes(out));
607+ Buf.str(body, "</div>");
608+ put("spec.html", page("The raz report", Buf.bytes(body), 0, "spec"));
609+end;
610+
611+(* ---- releases ----------------------------------------------------- *)
612+
613+(* The SHA-256 of the file at path, as hex. *)
614+proc digestOf(path: []const U8): []const U8;
615+var b: Buf.Buf;
616+begin
617+ Buf.init(b, Heap.heap);
618+ Sha256.hex(Site.read(path), b);
619+ return Buf.bytes(b);
620+end;
621+
622+(* Makes the tarball of one release, if public/download/ lacks it, and
623+ its checksum file: a release's tarball is made of its tag by make
624+ dist, not of the tree at hand, and one already there is kept as it
625+ is, never made again. Those before 0.14.0 were made before make dist
626+ made the same tarball each time, so a new one would differ, and so
627+ its SHA-256, which a program's CI may check. *)
628+proc tarballOf(const r: Releases.Release): Tarball;
629+var t: Tarball; made, checksum: []const U8; expected: [][]const U8; v: []const U8;
630+begin
631+ v := r.tag[1..LEN(r.tag)];
632+ t.version := v;
633+ t.name := Site.cat(["raz-", v, "-linux-x86_64.tar.gz"]);
634+ made := Site.cat([outDir, "/download/", t.name]);
635+ if not Site.exists(made) then
636+ if Site.runQuiet(["make", "-s", "-C", root, "dist", Site.cat(["REV=", r.commit]), Site.cat(["VERSION=", v])]) # 0 then
637+ Site.die("make dist failed for {}", [Fmt.str(r.tag)]);
638+ end;
639+ Site.copy(Site.cat([root, "/build/", t.name]), made);
640+ end;
641+ t.digest := digestOf(made);
642+ checksum := Site.cat([made, ".sha256"]);
643+ if Site.exists(checksum) then
644+ expected := Site.words(Site.read(checksum));
645+ if (LEN(expected) = 0) or (expected[0] # t.digest) then
646+ Site.die("release archive does not match its published checksum: {}", [Fmt.str(made)]);
647+ end;
648+ end;
649+ put(Site.cat(["download/", t.name, ".sha256"]), Site.cat([t.digest, " ", t.name, "\n"]));
650+ return t;
651+end;
652+
653+(* Every release's tarball from v0.7.1 on, in public/download/ with its
654+ SHA-256, and /download/latest leading to the newest; oldest first. A
655+ program's CI can fetch the version it was written for by its name,
656+ so none is ever taken away. *)
657+proc buildDownloads(extra: []const Releases.Release): []Tarball;
658+var all: []Releases.Release; why: []const U8; v: Tars.Vec; i: INT;
659+begin
660+ all, why := Releases.refs(root, extra);
661+ if LEN(why) > 0 then Site.die("{}", [Fmt.str(why)]); end;
662+ Tars.init(v, Heap.heap);
663+ for i := 0 to LEN(all) - 1 do Tars.push(v, tarballOf(all[i])); end;
664+ (* Cloudflare reads _redirects from the root of what it serves *)
665+ put("_redirects", Site.cat(["/download/latest /download/", Tars.all(v)[v.len - 1].name, " 302\n"]));
666+ return Tars.all(v);
667+end;
668+
669+(* The number of pages of the PDF at path, as pdfinfo says. *)
670+proc pageCount(path: []const U8): []const U8;
671+var out: Buf.Buf; rest, text: []const U8; at: INT;
672+begin
673+ Buf.init(out, Heap.heap);
674+ if Site.captureOut(["pdfinfo", path], "", [], out) # 0 then Site.die("pdfinfo failed", []); end;
675+ at := Str.find(Buf.bytes(out), "Pages:");
676+ if at < 0 then Site.die("pdfinfo says no page count", []); end;
677+ text := Buf.bytes(out);
678+ rest := Str.trimLeft(text[at + 6..LEN(text)]);
679+ at := 0;
680+ while (at < LEN(rest)) and Str.isDigit(rest[at]) do INC(at); end;
681+ return rest[0..at];
682+end;
683+
684+(* Replaces each place in text, in b, where old stands by new. *)
685+proc replaceIn(var text: Buf.Buf; old, new: []const U8);
686+var b: Buf.Buf;
687+begin
688+ Buf.init(b, Heap.heap);
689+ Str.replace(b, Buf.bytes(text), old, new);
690+ Buf.done(text);
691+ text := b;
692+end;
693+
694+(* Writes the home page: home.html with the example's text and output,
695+ the page count and the downloads filled in. *)
696+proc buildHome(releases: []Tarball);
697+var
698+ dir: []const U8; r: Run; text, snippetHtml, earlier: Buf.Buf; snippet: []const U8; last: Tarball; i: INT;
699+begin
700+ snippet := Site.read(Site.cat([root, "/site/content/home.raz"]));
701+ dir := Site.tempDir();
702+ Site.write(Site.cat([dir, "/Taste.raz"]), snippet);
703+ r := runModule(dir, "Taste");
704+ if r.status # 0 then Site.die("Taste failed:\n{}", [Fmt.str(Buf.bytes(r.err))]); end;
705+ _ := Files.removeTree(dir);
706+ Buf.init(text, Heap.heap);
707+ Buf.str(text, Site.read(Site.cat([root, "/site/content/home.html"])));
708+ Buf.init(snippetHtml, Heap.heap);
709+ Markup.highlight(snippetHtml, chop(snippet));
710+ replaceIn(text, "@SNIPPET@", Buf.bytes(snippetHtml));
711+ replaceIn(text, "@OUTPUT@", Markup.escaped(chop(Buf.bytes(r.out)), true));
712+ last := releases[LEN(releases) - 1];
713+ Buf.init(earlier, Heap.heap);
714+ for i := LEN(releases) - 2 to 0 by -1 do
715+ if earlier.len > 0 then Buf.str(earlier, ", "); end;
716+ Fmt.write(earlier, "<a href=\"download/{}\">{}</a>", [Fmt.str(releases[i].name), Fmt.str(releases[i].version)]);
717+ end;
718+ replaceIn(text, "@EARLIER@", Buf.bytes(earlier));
719+ replaceIn(text, "@PAGES@", pageCount(Site.cat([root, "/build/raz.pdf"])));
720+ replaceIn(text, "@VERSION@", last.version);
721+ replaceIn(text, "@TARBALL@", last.name);
722+ replaceIn(text, "@DIR@", last.name[0..LEN(last.name) - LEN(".tar.gz")]);
723+ replaceIn(text, "@SHA256@", last.digest);
724+ put("index.html", page("raz: a small systems language", Buf.bytes(text), 0, "home"));
725+end;
726+
727+(* ---- the whole site ------------------------------------------------ *)
728+
729+(* Removes everything in public/ but the tarballs in download/, which
730+ are never made again. *)
731+proc clean;
732+var names: [][]const U8; path: []const U8; i: INT;
733+begin
734+ if not Site.isDir(outDir) then return; end;
735+ names := Site.dirNames(outDir);
736+ for i := 0 to LEN(names) - 1 do
737+ path := Site.cat([outDir, "/", names[i]]);
738+ if names[i] = "download" then
739+ elsif Site.isDir(path) then _ := Files.removeTree(path);
740+ else _ := Sys.remove(path);
741+ end;
742+ end;
743+end;
744+
745+(* Copies the style sheet, the logo and the icons into public/. *)
746+proc copyAssets;
747+var names: [][]const U8; i: INT;
748+begin
749+ Site.copy(Site.cat([root, "/site/style.css"]), Site.cat([outDir, "/style.css"]));
750+ names := Site.dirNames(Site.cat([root, "/site/assets"]));
751+ for i := 0 to LEN(names) - 1 do
752+ if (names[i] # "social.html") and (names[i] # "render.sh") then
753+ Site.copy(Site.cat([root, "/site/assets/", names[i]]), Site.cat([outDir, "/", names[i]]));
754+ end;
755+ end;
756+end;
757+
758+(* The vX.Y.Z=COMMIT arguments, as releases; the build stops at a
759+ mistake. *)
760+proc extraReleases(): []Releases.Release;
761+var v: Rels.Vec; tag, commit: []const U8; found, ok: BOOL; i: INT;
762+begin
763+ Rels.init(v, Heap.heap);
764+ for i := 1 to Files.argCount() - 1 do
765+ tag, commit, found := Str.cut(Files.arg(i), "=");
766+ _, _, _, ok := Releases.version(tag);
767+ if not found or not ok then Site.die(Usage, []); end;
768+ Rels.push(v, {tag: tag, commit: commit});
769+ end;
770+ return Rels.all(v);
771+end;
772+
773+proc main*;
774+var extra: []Releases.Release; why: []const U8; err: INT; i: INT; counts: Buf.Buf; lessons: []Lesson; downloads: []Tarball;
775+begin
776+ root, err := Sys.workDir();
777+ if err < 0 then Site.die("no working directory", []); end;
778+ root := Site.cat([root]);
779+ outDir := Site.cat([root, "/site/public"]);
780+ raz := Site.cat([root, "/raz"]);
781+ if not Site.exists(raz) then Site.die("make raz first", []); end;
782+ extra := extraReleases();
783+ _, why := Releases.refs(root, extra); (* validate the release records before removing old pages *)
784+ if LEN(why) > 0 then Site.die("{}", [Fmt.str(why)]); end;
785+ clean;
786+ Site.makeDirs(Site.cat([outDir, "/download"]));
787+ copyAssets;
788+ Buf.init(counts, Heap.heap);
789+ for i := 0 to LEN(Tours) - 1 do
790+ lessons := readLessons(Tours[i]);
791+ if i + 1 < LEN(Tours) then
792+ buildTour(Tours[i], lessons, Site.cat(["../", Tours[i + 1].outDir, "/index.html"]), Tours[i + 1].name);
793+ else
794+ buildTour(Tours[i], lessons, "../spec.html", "The report");
795+ end;
796+ if i > 0 then Buf.str(counts, " + "); end;
797+ Fmt.write(counts, "{}", [Fmt.int(LEN(lessons))]);
798+ end;
799+ buildSpec;
800+ Site.copy(Site.cat([root, "/build/raz.pdf"]), Site.cat([outDir, "/raz.pdf"])); (* made by make pdf *)
801+ Site.copy(Site.cat([root, "/build/raz-lib.pdf"]), Site.cat([outDir, "/raz-lib.pdf"]));
802+ downloads := buildDownloads(extra);
803+ buildHome(downloads);
804+ Fmt.print("site/public: {} lessons\n", [Fmt.str(Buf.bytes(counts))]);
805+end;
806+end Build.

site/Markup.raz (history) added +438 -0

@@ -0,0 +1,438 @@
1+(* Markup: the text of the site's pages as HTML: escaping, the colouring
2+ of raz source, and the little markup the lessons are written in
3+ (`code`, **bold**, [links](url), "- " lists and pipe tables). Each
4+ procedure adds to a Buf. It needs only Buf, Str and Site. It leaves
5+ out the rest of Markdown, and any letter but ASCII's in a word. *)
6+module Markup;
7+import Buf, Str, Heap, Site;
8+import Names := Vec([]const U8);
9+
10+const
11+ (* the reserved words that are coloured *)
12+ Keywords = "and begin break by code const defer div do else elsif end extern for forward if import in link match mod module not of or packed proc record repeat return set shl shr then to try type until var variant VOLATILE while xor";
13+ (* the predeclared names that are coloured *)
14+ Predeclared = "INT UINT I8 I16 I32 I64 U8 U16 U32 U64 F32 F64 BOOL ERROR true false nil LEN ADR NEW SIZE INC DEC MSG XADD CAS XCHG";
15+
16+(* ---- escaping ---------------------------------------------------- *)
17+
18+(* Adds s with &, < and > written as entities, and, if quote, " and ' too:
19+ the usual HTML escaping. *)
20+proc escape*(var b: Buf.Buf; s: []const U8; quote: BOOL);
21+var i: INT;
22+begin
23+ for i := 0 to LEN(s) - 1 do
24+ if s[i] = '&' then Buf.str(b, "&amp;");
25+ elsif s[i] = '<' then Buf.str(b, "&lt;");
26+ elsif s[i] = '>' then Buf.str(b, "&gt;");
27+ elsif quote and (s[i] = '"') then Buf.str(b, "&quot;");
28+ elsif quote and (s[i] = '\'') then Buf.str(b, "&#x27;");
29+ else Buf.add(b, s[i]);
30+ end;
31+ end;
32+end;
33+
34+(* s escaped as escape does, as a string. *)
35+proc escaped*(s: []const U8; quote: BOOL): []const U8;
36+var b: Buf.Buf;
37+begin
38+ Buf.init(b, Heap.heap);
39+ escape(b, s, quote);
40+ return Buf.bytes(b);
41+end;
42+
43+(* ---- raz source -------------------------------------------------- *)
44+
45+(* Whether c is a letter, a digit or an underscore. *)
46+proc isWord(c: U8): BOOL;
47+begin
48+ return Str.isLetter(c) or Str.isDigit(c) or (c = '_');
49+end;
50+
51+(* Whether c is a hexadecimal digit, capital or small. *)
52+proc isHex(c: U8): BOOL;
53+begin
54+ return Str.hexVal(c) >= 0;
55+end;
56+
57+(* Whether w is one of the words of list, which are separated by single
58+ spaces. *)
59+proc among(w, list: []const U8): BOOL;
60+var i, j: INT;
61+begin
62+ i := 0;
63+ while i < LEN(list) do
64+ j := i;
65+ while (j < LEN(list)) and (list[j] # ' ') do INC(j); end;
66+ if list[i..j] = w then return true; end;
67+ i := j + 1;
68+ end;
69+ return false;
70+end;
71+
72+(* Where the comment that starts at i ends, or -1 if it has no end. *)
73+proc commentEnd(s: []const U8; i: INT): INT;
74+var j: INT;
75+begin
76+ if (i + 1 >= LEN(s)) or (s[i] # '(') or (s[i + 1] # '*') then return -1; end;
77+ j := Str.findFrom(s, "*)", i + 2);
78+ if j < 0 then return -1; end;
79+ return j + 2;
80+end;
81+
82+(* Where the string or quoted text that starts at i ends, or -1 if it
83+ has none. A " or ' string stops at its line's end and takes a
84+ backslash and the byte after it as one; a backquoted one may run on
85+ over lines. *)
86+proc stringEnd(s: []const U8; i: INT): INT;
87+var q: U8; j: INT;
88+begin
89+ q := s[i];
90+ if q = '`' then
91+ j := Str.findFrom(s, "`", i + 1);
92+ if j < 0 then return -1; end;
93+ return j + 1;
94+ end;
95+ if (q # '"') and (q # '\'') then return -1; end;
96+ j := i + 1;
97+ while j < LEN(s) do
98+ if s[j] = q then return j + 1;
99+ elsif s[j] = '\\' then INC(j, 2);
100+ elsif s[j] = '\n' then return -1;
101+ else INC(j);
102+ end;
103+ end;
104+ return -1;
105+end;
106+
107+(* Whether a number may end at e: no letter, digit or underscore follows. *)
108+proc numberStops(s: []const U8; e: INT): BOOL;
109+begin
110+ return (e >= LEN(s)) or not isWord(s[e]);
111+end;
112+
113+(* Past the digits that start at p. *)
114+proc digitsEnd(s: []const U8; p: INT): INT;
115+begin
116+ while (p < LEN(s)) and Str.isDigit(s[p]) do INC(p); end;
117+ return p;
118+end;
119+
120+(* The end of a number's last part, an H, from p, or -1: an H after p is
121+ taken if the number can end past it, else the number ends at p. *)
122+proc hexSuffixEnd(s: []const U8; p: INT): INT;
123+begin
124+ if (p < LEN(s)) and (s[p] = 'H') and numberStops(s, p + 1) then return p + 1; end;
125+ if numberStops(s, p) then return p; end;
126+ return -1;
127+end;
128+
129+(* The end of a number from p with its exponent, E, a sign if any and
130+ digits, tried before the number ends without one; or -1. *)
131+proc exponentEnd(s: []const U8; p: INT): INT;
132+var q, e: INT;
133+begin
134+ if (p < LEN(s)) and (s[p] = 'E') then
135+ q := p + 1;
136+ if (q < LEN(s)) and ((s[q] = '-') or (s[q] = '+')) then INC(q); end;
137+ if (q < LEN(s)) and Str.isDigit(s[q]) then
138+ e := hexSuffixEnd(s, digitsEnd(s, q));
139+ if e >= 0 then return e; end;
140+ end;
141+ end;
142+ return hexSuffixEnd(s, p);
143+end;
144+
145+(* The end of a number from p with its fraction, a point and digits,
146+ tried before the number ends without one; or -1. *)
147+proc fractionEnd(s: []const U8; p: INT): INT;
148+var e: INT;
149+begin
150+ if (p + 1 < LEN(s)) and (s[p] = '.') and Str.isDigit(s[p + 1]) then
151+ e := exponentEnd(s, digitsEnd(s, p + 1));
152+ if e >= 0 then return e; end;
153+ end;
154+ return exponentEnd(s, p);
155+end;
156+
157+(* Where the number that starts at i ends, or -1. It starts with a digit
158+ not in the middle of a word; goes on over hexadecimal digits as far
159+ as that lets it end, as a regular expression would back off, then a
160+ fraction, an exponent and an H. *)
161+proc numberEnd(s: []const U8; i: INT): INT;
162+var q, e: INT;
163+begin
164+ if not Str.isDigit(s[i]) or ((i > 0) and isWord(s[i - 1])) then return -1; end;
165+ q := i + 1;
166+ while (q < LEN(s)) and isHex(s[q]) do INC(q); end;
167+ while q > i do
168+ e := fractionEnd(s, q);
169+ if e >= 0 then return e; end;
170+ DEC(q);
171+ end;
172+ return -1;
173+end;
174+
175+(* Where the word that starts at i ends, or -1 if none does. *)
176+proc wordEnd(s: []const U8; i: INT): INT;
177+begin
178+ if not (Str.isLetter(s[i]) or (s[i] = '_')) then return -1; end;
179+ while (i < LEN(s)) and isWord(s[i]) do INC(i); end;
180+ return i;
181+end;
182+
183+(* Adds src as HTML, its comments, strings, numbers and words in
184+ spans. A token is looked for at each place in turn: a comment, a
185+ string, a number, then a word. *)
186+proc highlight*(var b: Buf.Buf; src: []const U8);
187+var at, i, e: INT; class: []const U8;
188+begin
189+ at := 0;
190+ i := 0;
191+ while i < LEN(src) do
192+ class := "";
193+ e := commentEnd(src, i);
194+ if e >= 0 then class := "comment"; end;
195+ if e < 0 then e := stringEnd(src, i); if e >= 0 then class := "string"; end; end;
196+ if e < 0 then e := numberEnd(src, i); if e >= 0 then class := "number"; end; end;
197+ if e < 0 then
198+ e := wordEnd(src, i);
199+ if e >= 0 then
200+ if among(src[i..e], Keywords) then class := "kw";
201+ elsif among(src[i..e], Predeclared) then class := "ty";
202+ end;
203+ end;
204+ end;
205+ if e < 0 then
206+ INC(i);
207+ else
208+ if LEN(class) > 0 then
209+ escape(b, src[at..i], true);
210+ Buf.str(b, "<span class=\"");
211+ Buf.str(b, class);
212+ Buf.str(b, "\">");
213+ escape(b, src[i..e], true);
214+ Buf.str(b, "</span>");
215+ at := e;
216+ end;
217+ i := e;
218+ end;
219+ end;
220+ escape(b, src[at..LEN(src)], true);
221+end;
222+
223+(* ---- inline markup ----------------------------------------------- *)
224+
225+(* Adds s with each `text` made <code>text</code>. *)
226+proc codePass(var b: Buf.Buf; s: []const U8);
227+var i, j: INT;
228+begin
229+ i := 0;
230+ while i < LEN(s) do
231+ j := -1;
232+ if s[i] = '`' then j := Str.findFrom(s, "`", i + 1); end;
233+ if j > i + 1 then
234+ Buf.str(b, "<code>"); Buf.str(b, s[i + 1..j]); Buf.str(b, "</code>");
235+ i := j + 1;
236+ else
237+ Buf.add(b, s[i]);
238+ INC(i);
239+ end;
240+ end;
241+end;
242+
243+(* Adds s with each **text** made <strong>text</strong>; the text has
244+ no star in it. *)
245+proc strongPass(var b: Buf.Buf; s: []const U8);
246+var i, j: INT;
247+begin
248+ i := 0;
249+ while i < LEN(s) do
250+ j := -1;
251+ if (i + 1 < LEN(s)) and (s[i] = '*') and (s[i + 1] = '*') then
252+ j := i + 2;
253+ while (j < LEN(s)) and (s[j] # '*') do INC(j); end;
254+ if (j = i + 2) or (j + 1 >= LEN(s)) or (s[j + 1] # '*') then j := -1; end;
255+ end;
256+ if j >= 0 then
257+ Buf.str(b, "<strong>"); Buf.str(b, s[i + 2..j]); Buf.str(b, "</strong>");
258+ i := j + 2;
259+ else
260+ Buf.add(b, s[i]);
261+ INC(i);
262+ end;
263+ end;
264+end;
265+
266+(* The index of the first c in s from i, or -1. *)
267+proc indexOf(s: []const U8; c: U8; i: INT): INT;
268+begin
269+ while (i < LEN(s)) and (s[i] # c) do INC(i); end;
270+ if i >= LEN(s) then return -1; end;
271+ return i;
272+end;
273+
274+(* Adds s with each [text](url) made <a href="url">text</a>. *)
275+proc linkPass(var b: Buf.Buf; s: []const U8);
276+var i, j, k: INT;
277+begin
278+ i := 0;
279+ while i < LEN(s) do
280+ k := -1;
281+ if s[i] = '[' then
282+ j := indexOf(s, ']', i + 1);
283+ if (j > i + 1) and (j + 1 < LEN(s)) and (s[j + 1] = '(') then
284+ k := indexOf(s, ')', j + 2);
285+ if k <= j + 2 then k := -1; end;
286+ end;
287+ end;
288+ if k >= 0 then
289+ Buf.str(b, "<a href=\""); Buf.str(b, s[j + 2..k]); Buf.str(b, "\">");
290+ Buf.str(b, s[i + 1..j]); Buf.str(b, "</a>");
291+ i := k + 1;
292+ else
293+ Buf.add(b, s[i]);
294+ INC(i);
295+ end;
296+ end;
297+end;
298+
299+(* Adds s as HTML: escaped, then its `code`, **bold** and [links](url)
300+ made tags, one kind after the other over the whole text. *)
301+proc inline*(var b: Buf.Buf; s: []const U8);
302+var plain, coded, bold: Buf.Buf;
303+begin
304+ Buf.init(plain, Heap.heap);
305+ Buf.init(coded, Heap.heap);
306+ Buf.init(bold, Heap.heap);
307+ escape(plain, s, false);
308+ codePass(coded, Buf.bytes(plain));
309+ strongPass(bold, Buf.bytes(coded));
310+ linkPass(b, Buf.bytes(bold));
311+ Buf.done(plain);
312+ Buf.done(coded);
313+ Buf.done(bold);
314+end;
315+
316+(* ---- blocks ------------------------------------------------------ *)
317+
318+(* The cells of a table row: its white space and the bars at its ends
319+ cut, then split at the bars, each cell trimmed. *)
320+proc cells(row: []const U8): [][]const U8;
321+var v: Names.Vec; at, i: INT;
322+begin
323+ row := Str.trim(row);
324+ while (LEN(row) > 0) and (row[0] = '|') do row := row[1..LEN(row)]; end;
325+ while (LEN(row) > 0) and (row[LEN(row) - 1] = '|') do row := row[0..LEN(row) - 1]; end;
326+ Names.init(v, Heap.heap);
327+ at := 0;
328+ for i := 0 to LEN(row) - 1 do
329+ if row[i] = '|' then Names.push(v, Str.trim(row[at..i])); at := i + 1; end;
330+ end;
331+ Names.push(v, Str.trim(row[at..LEN(row)]));
332+ return Names.all(v);
333+end;
334+
335+(* Adds a pipe table (header, a |---| rule, rows) as HTML. Each cell
336+ carries its column's name, which the style sheet shows when the
337+ screen is too narrow for columns. *)
338+proc table(var b: Buf.Buf; rows: [][]const U8);
339+var head, row: [][]const U8; i, k: INT;
340+begin
341+ head := cells(rows[0]);
342+ Buf.str(b, "<table><thead><tr>");
343+ for k := 0 to LEN(head) - 1 do
344+ Buf.str(b, "<th>"); inline(b, head[k]); Buf.str(b, "</th>");
345+ end;
346+ Buf.str(b, "</tr></thead><tbody>");
347+ for i := 2 to LEN(rows) - 1 do
348+ row := cells(rows[i]);
349+ Buf.str(b, "<tr>");
350+ for k := 0 to LEN(head) - 1 do
351+ if k < LEN(row) then
352+ Buf.str(b, "<td data-label=\"");
353+ escape(b, head[k], true);
354+ Buf.str(b, "\">");
355+ inline(b, row[k]);
356+ Buf.str(b, "</td>");
357+ end;
358+ end;
359+ Buf.str(b, "</tr>");
360+ end;
361+ Buf.str(b, "</tbody></table>");
362+end;
363+
364+(* The paragraphs of text: it is cut at each line feed that ends a blank
365+ line, however many blank lines there are. *)
366+proc paragraphs(text: []const U8): [][]const U8;
367+var v: Names.Vec; start, i, k, last: INT;
368+begin
369+ Names.init(v, Heap.heap);
370+ start := 0;
371+ i := 0;
372+ while i < LEN(text) do
373+ last := -1;
374+ if text[i] = '\n' then
375+ k := i + 1;
376+ while (k < LEN(text)) and Str.isSpace(text[k]) do
377+ if text[k] = '\n' then last := k; end;
378+ INC(k);
379+ end;
380+ end;
381+ if last >= 0 then
382+ Names.push(v, text[start..i]);
383+ start := last + 1;
384+ i := last + 1;
385+ else
386+ INC(i);
387+ end;
388+ end;
389+ Names.push(v, text[start..LEN(text)]);
390+ return Names.all(v);
391+end;
392+
393+(* Whether every one of lines starts with prefix. *)
394+proc allStart(lines: [][]const U8; prefix: []const U8): BOOL;
395+var i: INT;
396+begin
397+ for i := 0 to LEN(lines) - 1 do
398+ if not Str.hasPrefix(lines[i], prefix) then return false; end;
399+ end;
400+ return true;
401+end;
402+
403+(* Adds a paragraph as HTML: a "## " heading, a table, a "- " list, or
404+ a paragraph of its lines joined by blanks. *)
405+proc paragraph(var b: Buf.Buf; para: []const U8);
406+var lines: [][]const U8; joined: Buf.Buf; i: INT;
407+begin
408+ lines := Site.lines(para);
409+ if Str.hasPrefix(para, "## ") then
410+ Buf.str(b, "<h2>"); inline(b, para[3..LEN(para)]); Buf.str(b, "</h2>");
411+ elsif allStart(lines, "|") then
412+ table(b, lines);
413+ elsif allStart(lines, "- ") then
414+ Buf.str(b, "<ul>");
415+ for i := 0 to LEN(lines) - 1 do
416+ Buf.str(b, "<li>"); inline(b, lines[i][2..LEN(lines[i])]); Buf.str(b, "</li>");
417+ end;
418+ Buf.str(b, "</ul>");
419+ else
420+ Buf.init(joined, Heap.heap);
421+ Str.join(joined, lines, " ");
422+ Buf.str(b, "<p>"); inline(b, Buf.bytes(joined)); Buf.str(b, "</p>");
423+ Buf.done(joined);
424+ end;
425+end;
426+
427+(* Adds the paragraphs of text as HTML, one to a line. *)
428+proc prose*(var b: Buf.Buf; text: []const U8);
429+var paras: [][]const U8; i: INT;
430+begin
431+ paras := paragraphs(Str.trim(text));
432+ for i := 0 to LEN(paras) - 1 do
433+ if i > 0 then Buf.add(b, '\n'); end;
434+ paragraph(b, paras[i]);
435+ end;
436+end;
437+
438+end Markup.

site/README.md (history) modified +24 -15

@@ -1,23 +1,26 @@
11 # Building raz's website
22
33 `make site` builds the pages, tours, reports and downloads with
4-`build.py`, then the source browser and release pages with `source.py`.
5-The latter needs git and Python 3 on x86-64 Linux. Its pinned static
6-ladle executable is kept compressed under `tools/`, with a checksum
7-and build instructions. The helper verifies the compressed bytes,
8-unpacks it into `build/site/ladle` and runs it. No compiler or network
4+`Build.raz`, then the source browser and release pages with `Source.raz`.
5+Both are raz programs, as are `Verify.raz` and the modules they share
6+(`Site`, `Releases`, `Markup` and `Sha256`): the Makefile builds them
7+with this repository's `./raz` into `build/site/`. `Source` needs git,
8+gzip and an x86-64 Linux; `Build` also pandoc, pdfinfo and make. Its
9+pinned static ladle executable is kept compressed under `tools/`, with
10+a checksum and build instructions. The helper verifies the compressed
11+bytes, unpacks it into `build/site/ladle` and runs it. No network
912 connection is needed with a full checkout. If a deployment service
1013 clones shallowly, the helper first fetches the full history and tags
1114 from that checkout's origin, using its existing repository access.
1215
1316 The existing `/download/` URLs and archives stay as they are. Before
14-attaching an archive to a release, `source.py` checks its bytes against
17+attaching an archive to a release, `Source.raz` checks its bytes against
1518 the published checksum beside it. It fails if either is missing or
1619 the sum differs; it never replaces that checksum to fit new bytes.
1720
1821 ## The source browser
1922
20-`source.py` makes a fresh bare clone of `main`, with its reachable
23+`Source.raz` makes a fresh bare clone of `main`, with its reachable
2124 tags, using `--single-branch --no-local`. Other branches, reflogs and
2225 unreachable tags are not published. The store is repacked with a
2326 20 MiB target, and `git update-server-info` prepares it for cloning
@@ -41,7 +44,7 @@
4144 make site-source
4245 ```
4346
44-Or run `python3 site/source.py` directly. `--ladle /path/to/ladle`
47+Or run `build/site/Source` directly. `--ladle /path/to/ladle`
4548 overrides the bundled executable for development. `--url` may give
4649 another absolute address ending in `/source/`, for
4750 previewing the feeds and clone line. `source.theme` starts from
@@ -67,7 +70,7 @@
6770 `release-notes/vX.Y.Z.md`, when present, supplies that version's notes.
6871 Otherwise an annotated tag supplies them.
6972
70-Both builders read this list through `releases.py`, so the home page
73+Both builders read this list through `Releases.raz`, so the home page
7174 and source browser offer the same versions. An existing distribution
7275 can also be given as `vX.Y.Z=COMMIT` on either helper's command line;
7376 `make site RELEASES='vX.Y.Z=COMMIT'` passes it to both. Permanent
@@ -79,7 +82,7 @@
7982 root `public/_headers` between marked comments. Rebuilding replaces
8083 that block, preserving other root rules. Its general security policy
8184 therefore applies only to `/source/*`, including raw files and git
82-objects. `source.py` never changes `_redirects`, so `/download/latest`
85+objects. `Source.raz` never changes `_redirects`, so `/download/latest`
8386 continues to work. Cloudflare reads the root header file; the nested
8487 one is not enough.
8588
@@ -96,13 +99,19 @@
9699 clone and download checks against the live address after deployment;
97100 a local file server does not test Cloudflare's headers.
98101
99-`python3 site/check.py` checks release identity and ordering against
100-small real Git repositories, including shallow deployment checkouts,
101-and rejects a damaged bundled builder. `make check` remains the
102+`make site-check` (`Verify.raz`) checks release identity and ordering
103+against small real Git repositories, including shallow deployment
104+checkouts, and rejects a damaged bundled builder. `make check` remains the
102105 compiler's required check before committing.
103106
104107 The Wrangler configuration runs `make site-source` before deployment.
105108 The usual `npx wrangler deploy` therefore generates the ignored source
106109 browser from the committed repository before uploading the assets.
107-It uses the already generated main pages and distributions; it does
108-not run the compiler, pandoc or the tours on the deployment machine.
110+It uses the already generated main pages and distributions; it builds
111+`raz` to compile `Source.raz` (`src/boot.sh` fetches the compiler
112+`BOOT` names, unless `build/boot/` has it), but does not run pandoc or
113+the tours on the deployment machine.
114+
115+The source archives' gzip bytes come from the `gzip` program (`gzip
116+-9n`, as `make dist` packs the tarballs), so their checksums depend on
117+its version.

site/Releases.raz (history) added +217 -0

@@ -0,0 +1,217 @@
1+(* Releases: the release commits the home page (Build) and ladle's
2+ download pages (Source) share. Tags supply the released versions;
3+ site/releases records website distributions whose tags have not
4+ been pushed. Both must name commits on main's first-parent line, and
5+ a later tag must agree with the record. No tags or archives are
6+ made here. It needs git, through Site. *)
7+module Releases;
8+import Site, Str, Heap, Buf, Fmt;
9+import Entries := Vec(Release);
10+import Commits := Map([]const U8, BOOL, Str.hash, Str.eq);
11+import ByVersion := Sort(Release, older);
12+
13+type
14+ (* A release: its version tag, vX.Y.Z, and the full commit hash. *)
15+ Release* = record
16+ tag*: []const U8;
17+ commit*: []const U8;
18+ end;
19+
20+ (* The state of one run of refs. *)
21+ Pick = record
22+ root: []const U8; (* the repository *)
23+ line: Commits.Map; (* the commits of main's first-parent line *)
24+ selected: Entries.Vec; (* the releases chosen so far *)
25+ tagged: Entries.Vec; (* every tag of the form vX.Y.Z, with its commit *)
26+ why: Buf.Buf; (* the message of the first mistake *)
27+ end;
28+
29+const
30+ OldestMinor = 7; (* the oldest release is v0.7.1 *)
31+ OldestPatch = 1;
32+
33+(* The number the digits of s make, and whether s is only digits. *)
34+proc number(s: []const U8): (I64, BOOL);
35+var i: INT;
36+begin
37+ if LEN(s) = 0 then return 0, false; end;
38+ for i := 0 to LEN(s) - 1 do
39+ if not Str.isDigit(s[i]) then return 0, false; end;
40+ end;
41+ return Str.toInt(s);
42+end;
43+
44+(* The three numbers of a tag vX.Y.Z, and whether it is one. *)
45+proc version*(tag: []const U8): (I64, I64, I64, BOOL);
46+var rest, x, y, z: []const U8; a, b, c: I64; found, ok: BOOL;
47+begin
48+ if not Str.hasPrefix(tag, "v") then return 0, 0, 0, false; end;
49+ x, rest, found := Str.cut(tag[1..LEN(tag)], ".");
50+ if not found then return 0, 0, 0, false; end;
51+ y, z, found := Str.cut(rest, ".");
52+ if not found then return 0, 0, 0, false; end;
53+ a, ok := number(x);
54+ if not ok then return 0, 0, 0, false; end;
55+ b, ok := number(y);
56+ if not ok then return 0, 0, 0, false; end;
57+ c, ok := number(z);
58+ if not ok then return 0, 0, 0, false; end;
59+ return a, b, c, true;
60+end;
61+
62+(* Whether the release a is older than b. *)
63+proc older(a, b: Release): BOOL;
64+var a1, a2, a3, b1, b2, b3: I64;
65+begin
66+ a1, a2, a3, _ := version(a.tag);
67+ b1, b2, b3, _ := version(b.tag);
68+ if a1 # b1 then return a1 < b1; end;
69+ if a2 # b2 then return a2 < b2; end;
70+ return a3 < b3;
71+end;
72+
73+(* Main locally, or the detached commit a deployment gives: "refs/heads/main"
74+ or "HEAD", or false if there is neither. A build never silently publishes another local branch. The
75+ publishing service selects main before checking out its commit. *)
76+proc mainRef*(root: []const U8): ([]const U8, BOOL);
77+begin
78+ if Site.runQuiet(["git", "-C", root, "show-ref", "--verify", "--quiet", "refs/heads/main"]) = 0 then
79+ return "refs/heads/main", true;
80+ end;
81+ if Site.runQuiet(["git", "-C", root, "symbolic-ref", "--quiet", "HEAD"]) # 0 then
82+ return "HEAD", true;
83+ end;
84+ return "", false;
85+end;
86+
87+(* The index of the release called tag in v, or -1. *)
88+proc find(const v: Entries.Vec; tag: []const U8): INT;
89+var i: INT;
90+begin
91+ for i := 0 to v.len - 1 do
92+ if Entries.all(v)[i].tag = tag then return i; end;
93+ end;
94+ return -1;
95+end;
96+
97+(* Says that the release tag is wrong, as why; false. *)
98+proc mistake(var p: Pick; tag: []const U8; what: []const U8): BOOL;
99+begin
100+ Fmt.write(p.why, "release {}: {}", [Fmt.str(tag), Fmt.str(what)]);
101+ return false;
102+end;
103+
104+(* Considers the release tag at rev: one before v0.7.1 is ignored; one
105+ not on main's line, or at odds with a tag or a record, is a mistake,
106+ false. *)
107+proc add(var p: Pick; tag, rev: []const U8): BOOL;
108+var commit: []const U8; a, b, c: I64; ok: BOOL; i: INT; text: Buf.Buf;
109+begin
110+ a, b, c, ok := version(tag);
111+ if not ok then
112+ Fmt.write(p.why, "release version must be vX.Y.Z: {}", [Fmt.str(tag)]);
113+ return false;
114+ end;
115+ if (a = 0) and ((b < OldestMinor) or ((b = OldestMinor) and (c < OldestPatch))) then return true; end;
116+ commit := Site.git(p.root, ["rev-parse", "--verify", "--end-of-options", Site.cat([rev, "^{commit}"])]);
117+ _, ok := Commits.get(p.line, commit);
118+ if not ok then
119+ Buf.init(text, Heap.heap);
120+ Fmt.write(text, "{} is not on main's first-parent line", [Fmt.str(commit)]);
121+ return mistake(p, tag, Buf.bytes(text));
122+ end;
123+ i := find(p.tagged, tag);
124+ if (i >= 0) and (Entries.all(p.tagged)[i].commit # commit) then
125+ return mistake(p, tag, "tag and recorded commits disagree");
126+ end;
127+ i := find(p.selected, tag);
128+ if i < 0 then
129+ Entries.push(p.selected, {tag: tag, commit: commit});
130+ elsif Entries.all(p.selected)[i].commit # commit then
131+ return mistake(p, tag, "tag and recorded commits disagree");
132+ end;
133+ return true;
134+end;
135+
136+(* Adds the tags of the repository, those on main's line as releases. *)
137+proc addTags(var p: Pick): BOOL;
138+var all: [][]const U8; tag, commit: []const U8; i: INT; ok: BOOL;
139+begin
140+ all := Site.lines(Site.git(p.root, ["tag", "-l", "v*"]));
141+ for i := 0 to LEN(all) - 1 do
142+ tag := all[i];
143+ _, _, _, ok := version(tag);
144+ if ok then
145+ (* Tags on another development line are not this site's releases. *)
146+ commit := Site.git(p.root, ["rev-parse", "--verify", Site.cat([tag, "^{commit}"])]);
147+ Entries.push(p.tagged, {tag: tag, commit: commit});
148+ _, ok := Commits.get(p.line, commit);
149+ if ok and not add(p, tag, commit) then return false; end;
150+ end;
151+ end;
152+ return true;
153+end;
154+
155+(* Adds the records of site/releases, one "vX.Y.Z FULL_COMMIT" a line,
156+ # starting a comment. *)
157+proc addManifest(var p: Pick): BOOL;
158+var
159+ path, line: []const U8; all, words: [][]const U8; i, j: INT; hash: BOOL;
160+begin
161+ path := Site.cat([p.root, "/site/releases"]);
162+ all := Site.lines(Site.read(path));
163+ for i := 0 to LEN(all) - 1 do
164+ line, _, _ := Str.cut(all[i], "#");
165+ words := Site.words(line);
166+ if LEN(words) > 0 then
167+ hash := (LEN(words) = 2) and (LEN(words[1]) = 40);
168+ if hash then
169+ for j := 0 to 39 do
170+ hash := hash and (Str.isDigit(words[1][j]) or ((words[1][j] >= 'a') and (words[1][j] <= 'f')));
171+ end;
172+ end;
173+ if not hash then
174+ Fmt.write(p.why, "{}:{}: expected vX.Y.Z and full commit hash", [Fmt.str(path), Fmt.int(i + 1)]);
175+ return false;
176+ end;
177+ if not add(p, words[0], words[1]) then return false; end;
178+ end;
179+ end;
180+ return true;
181+end;
182+
183+(* The (version tag, full commit) pairs, oldest first, of the tags on
184+ main's line and the records of site/releases, and of extra, the
185+ optional vX.Y.Z=COMMIT arguments of make site. Conflicting records
186+ are mistakes, so a build cannot quietly move an existing version to
187+ another commit: then the list is empty and the message, otherwise
188+ empty, says what is wrong. A shallow
189+ checkout, as a deployment service makes, is completed from its
190+ origin first, since the source browser needs the history and the
191+ tags. *)
192+proc refs*(root: []const U8; extra: []const Release): ([]Release, []const U8);
193+var p: Pick; all: [][]const U8; ref: []const U8; ok: BOOL; i: INT;
194+begin
195+ if Site.git(root, ["rev-parse", "--is-shallow-repository"]) = "true" then
196+ Fmt.print("site: fetching full history and tags from origin\n", []);
197+ Site.must(["git", "-C", root, "fetch", "--unshallow", "--tags", "origin"]);
198+ end;
199+ ref, ok := mainRef(root);
200+ if not ok then return [], "site build needs main or a detached deployment checkout"; end;
201+ p.root := root;
202+ Buf.init(p.why, Heap.heap);
203+ Commits.init(p.line, Heap.heap);
204+ Entries.init(p.selected, Heap.heap);
205+ Entries.init(p.tagged, Heap.heap);
206+ all := Site.lines(Site.git(root, ["rev-list", "--first-parent", ref]));
207+ for i := 0 to LEN(all) - 1 do _ := Commits.put(p.line, all[i], true); end;
208+ ok := addTags(p) and addManifest(p);
209+ for i := 0 to LEN(extra) - 1 do
210+ ok := ok and add(p, extra[i].tag, extra[i].commit);
211+ end;
212+ if not ok then return [], Buf.bytes(p.why); end;
213+ ByVersion.sort(Entries.all(p.selected));
214+ return Entries.all(p.selected), "";
215+end;
216+
217+end Releases.

site/Sha256.raz (history) added +98 -0

@@ -0,0 +1,98 @@
1+(* Sha256: the SHA-256 of some bytes, as 64 lower-case hex digits, to
2+ check the site's archives against the sums published beside them.
3+ It needs only Buf and Str. It leaves out a streaming interface: the
4+ whole message is given at once. *)
5+module Sha256;
6+import Buf, Str, Heap, Check;
7+
8+const
9+ BlockLen = 64; (* bytes in a block, the unit the hash works on *)
10+ Digits = "0123456789abcdef";
11+ (* the first 32 bits of the cube roots of the first 64 primes *)
12+ K: [64]U32 = [
13+ 0428A2F98H, 071374491H, 0B5C0FBCFH, 0E9B5DBA5H, 03956C25BH, 059F111F1H, 0923F82A4H, 0AB1C5ED5H,
14+ 0D807AA98H, 012835B01H, 0243185BEH, 0550C7DC3H, 072BE5D74H, 080DEB1FEH, 09BDC06A7H, 0C19BF174H,
15+ 0E49B69C1H, 0EFBE4786H, 00FC19DC6H, 0240CA1CCH, 02DE92C6FH, 04A7484AAH, 05CB0A9DCH, 076F988DAH,
16+ 0983E5152H, 0A831C66DH, 0B00327C8H, 0BF597FC7H, 0C6E00BF3H, 0D5A79147H, 006CA6351H, 014292967H,
17+ 027B70A85H, 02E1B2138H, 04D2C6DFCH, 053380D13H, 0650A7354H, 0766A0ABBH, 081C2C92EH, 092722C85H,
18+ 0A2BFE8A1H, 0A81A664BH, 0C24B8B70H, 0C76C51A3H, 0D192E819H, 0D6990624H, 0F40E3585H, 0106AA070H,
19+ 019A4C116H, 01E376C08H, 02748774CH, 034B0BCB5H, 0391C0CB3H, 04ED8AA4AH, 05B9CCA4FH, 0682E6FF3H,
20+ 0748F82EEH, 078A5636FH, 084C87814H, 08CC70208H, 090BEFFFAH, 0A4506CEBH, 0BEF9A3F7H, 0C67178F2H];
21+
22+type
23+ (* The eight words of the running hash. *)
24+ State = [8]U32;
25+
26+(* Mixes the 64 bytes p into the state h. *)
27+proc block(var h: State; p: []const U8);
28+var
29+ w: [64]U32; a, b, c, d, e, f, g, hh, t1, t2, s0, s1: U32; i: INT;
30+begin
31+ for i := 0 to 15 do w[i] := U32(Str.be(p[4 * i..4 * i + 4])); end;
32+ for i := 16 to 63 do
33+ s0 := ROR(w[i - 15], 7) xor ROR(w[i - 15], 18) xor (w[i - 15] shr 3);
34+ s1 := ROR(w[i - 2], 17) xor ROR(w[i - 2], 19) xor (w[i - 2] shr 10);
35+ w[i] := w[i - 16] + s0 + w[i - 7] + s1;
36+ end;
37+ a := h[0]; b := h[1]; c := h[2]; d := h[3];
38+ e := h[4]; f := h[5]; g := h[6]; hh := h[7];
39+ for i := 0 to 63 do
40+ s1 := ROR(e, 6) xor ROR(e, 11) xor ROR(e, 25);
41+ t1 := hh + s1 + ((e & f) xor (~e & g)) + K[i] + w[i];
42+ s0 := ROR(a, 2) xor ROR(a, 13) xor ROR(a, 22);
43+ t2 := s0 + ((a & b) xor (a & c) xor (b & c));
44+ hh := g; g := f; f := e; e := d + t1;
45+ d := c; c := b; b := a; a := t1 + t2;
46+ end;
47+ h[0] := h[0] + a; h[1] := h[1] + b; h[2] := h[2] + c; h[3] := h[3] + d;
48+ h[4] := h[4] + e; h[5] := h[5] + f; h[6] := h[6] + g; h[7] := h[7] + hh;
49+end;
50+
51+(* Adds the SHA-256 of data to b, as 64 hex digits. *)
52+proc hex*(data: []const U8; var b: Buf.Buf);
53+var
54+ h: State; tail: [2 * BlockLen]U8; whole, rest, n, i, j: INT; word: U32;
55+begin
56+ h := [06A09E667H, 0BB67AE85H, 03C6EF372H, 0A54FF53AH, 0510E527FH, 09B05688CH, 01F83D9ABH, 05BE0CD19H];
57+ whole := LEN(data) div BlockLen * BlockLen;
58+ for i := 0 to whole - 1 by BlockLen do block(h, data[i..i + BlockLen]); end;
59+ (* the rest, a 1 bit, zeros, and the length in bits, in one or two blocks *)
60+ rest := LEN(data) - whole;
61+ FILL(tail, 0);
62+ COPY(tail[0..rest], data[whole..LEN(data)]);
63+ tail[rest] := 80H;
64+ n := BlockLen;
65+ if rest >= BlockLen - 8 then n := 2 * BlockLen; end;
66+ Str.putBE(tail[n - 8..n], U64(LEN(data)) * 8);
67+ for i := 0 to n - 1 by BlockLen do block(h, tail[i..i + BlockLen]); end;
68+ for i := 0 to 7 do
69+ word := h[i];
70+ for j := 7 to 0 by -1 do
71+ Buf.add(b, Digits[INT(word shr U32(4 * j)) & 0FH]);
72+ end;
73+ end;
74+end;
75+
76+(* The module's test: the standard examples, one block, two blocks,
77+ and a message whose padding needs a second block. *)
78+proc main*;
79+var b: Buf.Buf; m: [1000]U8;
80+begin
81+ Buf.init(b, Heap.heap);
82+ hex("", b);
83+ Check.str("empty", Buf.bytes(b), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
84+ Buf.reset(b);
85+ hex("abc", b);
86+ Check.str("abc", Buf.bytes(b), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
87+ Buf.reset(b);
88+ hex("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", b);
89+ Check.str("two blocks", Buf.bytes(b), "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1");
90+ Buf.reset(b);
91+ FILL(m, 'a');
92+ hex(m[0..55], b);
93+ Check.str("55 bytes", Buf.bytes(b), "9f4390f8d30c2dd92ec9f095b65e2b9ae9b0a925a5258e241c9f1e910f734318");
94+ Buf.reset(b);
95+ hex(m[0..1000], b);
96+ Check.str("1000 bytes", Buf.bytes(b), "41edece42d63e8d9bf515a9ba6932e1c20cbc9f5a5d134645adb5db1b9737ea3");
97+end;
98+end Sha256.

site/Site.raz (history) added +335 -0

@@ -0,0 +1,335 @@
1+(* Site: what the website's builders (Build, Source, Verify) share:
2+ stopping with a message, reading and writing files and directories,
3+ and running the programs they call (git, pandoc, make, ladle, ...),
4+ with their output kept or left on the terminal. It needs only the
5+ library. It leaves out a shell: a program is run from its argument
6+ list, as the builders ask. *)
7+module Site;
8+import Sys, Files, Buf, Str, Heap, Fmt, Out, Rt;
9+import Names := Vec([]const U8);
10+import ByName := Sort([]const U8, nameLess);
11+
12+const Letters = "abcdefghijklmnopqrstuvwxyz0123456789_"; (* the letters of a temporary directory's name *)
13+
14+(* Whether the name a sorts before b: by bytes. *)
15+proc nameLess(a, b: []const U8): BOOL;
16+begin
17+ return Str.cmp(a, b) < 0;
18+end;
19+
20+(* ---- stopping ---------------------------------------------------- *)
21+
22+(* Stops with status 1 and the message f makes of args on standard
23+ error. *)
24+proc die*(f: []const U8; args: []const Fmt.Arg);
25+var b: Buf.Buf;
26+begin
27+ Buf.init(b, Heap.heap);
28+ Fmt.write(b, f, args);
29+ Buf.add(b, '\n');
30+ Fmt.eprint("{}", [Fmt.str(Buf.bytes(b))]);
31+ Rt.exit(1);
32+end;
33+
34+(* ---- text -------------------------------------------------------- *)
35+
36+(* The parts joined into one string, in memory that is never freed. *)
37+proc cat*(parts: [][]const U8): []const U8;
38+var b: Buf.Buf; i: INT;
39+begin
40+ Buf.init(b, Heap.heap);
41+ for i := 0 to LEN(parts) - 1 do Buf.str(b, parts[i]); end;
42+ return Buf.bytes(b);
43+end;
44+
45+(* The lines of s, split at each line feed: a final line feed ends an
46+ empty last line. *)
47+proc lines*(s: []const U8): [][]const U8;
48+var v: Names.Vec; at, i: INT;
49+begin
50+ Names.init(v, Heap.heap);
51+ at := 0;
52+ for i := 0 to LEN(s) - 1 do
53+ if s[i] = '\n' then Names.push(v, s[at..i]); at := i + 1; end;
54+ end;
55+ Names.push(v, s[at..LEN(s)]);
56+ return Names.all(v);
57+end;
58+
59+(* The words of s, split at white space, with no empty one. *)
60+proc words*(s: []const U8): [][]const U8;
61+var v: Names.Vec; rest, w: []const U8;
62+begin
63+ Names.init(v, Heap.heap);
64+ w, rest := Str.field(s);
65+ while LEN(w) > 0 do
66+ Names.push(v, w);
67+ w, rest := Str.field(rest);
68+ end;
69+ return Names.all(v);
70+end;
71+
72+(* ---- files ------------------------------------------------------- *)
73+
74+(* Whether path names something. *)
75+proc exists*(path: []const U8): BOOL;
76+var err: INT;
77+begin
78+ _, err := Sys.info(path);
79+ return err = 0;
80+end;
81+
82+(* Whether path names a directory. *)
83+proc isDir*(path: []const U8): BOOL;
84+var f: Sys.Info; err: INT;
85+begin
86+ f, err := Sys.info(path);
87+ return (err = 0) and f.dir;
88+end;
89+
90+(* The whole file at path, or the program stops. *)
91+proc read*(path: []const U8): []const U8;
92+var b: Buf.Buf; err: INT;
93+begin
94+ Buf.init(b, Heap.heap);
95+ err := Files.load(path, b);
96+ if err < 0 then die("can't read {}: {}", [Fmt.str(path), Fmt.str(Sys.errorText(err))]); end;
97+ return Buf.bytes(b);
98+end;
99+
100+(* Makes the directory dir and those it is in, as mkdir -p does. *)
101+proc makeDirs*(dir: []const U8);
102+var i, err: INT;
103+begin
104+ for i := 1 to LEN(dir) - 1 do
105+ if dir[i] = '/' then _ := Sys.makeDir(dir[0..i]); end;
106+ end;
107+ err := Sys.makeDir(dir);
108+ if (err < 0) and ((err # Sys.errExists) or not isDir(dir)) then
109+ die("can't make {}: {}", [Fmt.str(dir), Fmt.str(Sys.errorText(err))]);
110+ end;
111+end;
112+
113+(* Writes data to the file at path, in a directory made if need be. *)
114+proc write*(path, data: []const U8);
115+var slash: INT;
116+begin
117+ slash := Str.findLast(path, "/");
118+ if slash > 0 then makeDirs(path[0..slash]); end;
119+ if not Files.write(path, data) then die("can't write {}", [Fmt.str(path)]); end;
120+end;
121+
122+(* Copies the file source to the path target. *)
123+proc copy*(source, target: []const U8);
124+begin
125+ write(target, read(source));
126+end;
127+
128+(* The names in the directory dir, in byte order; the program stops if
129+ it can't be read. *)
130+proc dirNames*(dir: []const U8): [][]const U8;
131+var d: Sys.Dir; v: Names.Vec; name: []const U8; ok: BOOL; err: INT;
132+begin
133+ err := Sys.openDir(d, dir);
134+ if err < 0 then die("can't read {}: {}", [Fmt.str(dir), Fmt.str(Sys.errorText(err))]); end;
135+ Names.init(v, Heap.heap);
136+ name, ok := Sys.nextEntry(d);
137+ while ok do
138+ Names.push(v, cat([name])); (* a copy: nextEntry's is good only until the next call *)
139+ name, ok := Sys.nextEntry(d);
140+ end;
141+ Sys.closeDir(d);
142+ ByName.sort(Names.all(v));
143+ return Names.all(v);
144+end;
145+
146+(* A new directory in base, named tmp and eight random
147+ letters, digits and underscores. The length
148+ matters: a program built in it carries the path in its debugging
149+ information, and a lesson that prints its own size would print a
150+ different one for a longer name. *)
151+proc tempDirIn*(base: []const U8): []const U8;
152+var path: []const U8; r: [8]U8; name: [11]U8; i: INT;
153+begin
154+ name[0] := 't'; name[1] := 'm'; name[2] := 'p';
155+ repeat
156+ Sys.random(r);
157+ for i := 0 to 7 do name[3 + i] := Letters[INT(r[i]) mod LEN(Letters)]; end;
158+ path := cat([base, "/", name[0..LEN(name)]]);
159+ until Sys.makeDir(path) = 0;
160+ return path;
161+end;
162+
163+(* A new directory in $TMPDIR, or /tmp, as tempDirIn makes one. *)
164+proc tempDir*: []const U8;
165+var base: []const U8;
166+begin
167+ base := Sys.env("TMPDIR");
168+ if LEN(base) = 0 then base := "/tmp"; end;
169+ return tempDirIn(base);
170+end;
171+
172+(* ---- programs ---------------------------------------------------- *)
173+
174+(* Starts the program args[0] (found on PATH), in the directory dir
175+ unless that is empty, with the NAME=value pairs of env added to its
176+ environment, and standard output and error going to the fds out and
177+ err (0 for this program's own): its process id, or minus an errno
178+ if it can't start. *)
179+proc start*(args: [][]const U8; dir: []const U8; env: [][]const U8; out, err: INT): INT;
180+var p: Sys.Program;
181+begin
182+ Out.flush; (* what was printed comes before what the program prints *)
183+ p := {path: args[0], args: args, env: env, dir: dir};
184+ p.fds[1] := out;
185+ p.fds[2] := err;
186+ return Sys.spawn(p);
187+end;
188+
189+(* Waits for the program pid: its exit status, or 128 and the signal's
190+ number if a signal killed it. *)
191+proc finish*(pid: INT): INT;
192+var status: Sys.Status; value: INT;
193+begin
194+ _, status, value := Sys.waitExit(pid);
195+ if status = Sys.killed then return 128 + value; end;
196+ return value;
197+end;
198+
199+(* Runs args with its output and errors left where they are, or into
200+ the fd out if that isn't 0: its exit status, or minus an errno if it
201+ can't start. *)
202+proc run*(args: [][]const U8; out: INT): INT;
203+var pid: INT;
204+begin
205+ pid := start(args, "", [], out, 0);
206+ if pid < 0 then return pid; end;
207+ return finish(pid);
208+end;
209+
210+(* Runs args with its output thrown away: its exit status, or minus an
211+ errno if it can't start. *)
212+proc runQuiet*(args: [][]const U8): INT;
213+var null, status: INT;
214+begin
215+ null := Sys.open("/dev/null", {Sys.writing});
216+ status := run(args, null);
217+ Sys.close(null);
218+ return status;
219+end;
220+
221+(* Runs the program first with its output into the program second, whose
222+ own goes to the fd out: a shell's first | second > out. Their two
223+ exit statuses, or minus an errno for one that can't start. *)
224+proc pipeline*(first, second: [][]const U8; out: INT): (INT, INT);
225+var read, write, pid1, pid2: INT; p: Sys.Program;
226+begin
227+ Out.flush;
228+ read, write := Sys.pipe();
229+ pid1 := start(first, "", [], write, 0);
230+ p := {path: second[0], args: second};
231+ p.fds[0] := read;
232+ p.fds[1] := out;
233+ pid2 := Sys.spawn(p);
234+ Sys.close(read);
235+ Sys.close(write);
236+ if pid1 >= 0 then pid1 := finish(pid1); end;
237+ if pid2 >= 0 then pid2 := finish(pid2); end;
238+ return pid1, pid2;
239+end;
240+
241+(* Runs args and stops the program if it fails. *)
242+proc must*(args: [][]const U8);
243+begin
244+ if run(args, 0) # 0 then die("{} failed", [Fmt.str(args[0])]); end;
245+end;
246+
247+(* Reads what is ready of the fds in the pair of pipes, to out and err,
248+ until both ends are closed; an fd of -1 is already closed. *)
249+proc drain(outFd, errFd: INT; var out, err: Buf.Buf);
250+var pair: [2]Sys.Poll; fds: []Sys.Poll; i, n: INT;
251+begin
252+ fds := pair[0..2];
253+ fds[0] := {fd: outFd, read: true};
254+ fds[1] := {fd: errFd, read: true};
255+ while (fds[0].fd >= 0) or (fds[1].fd >= 0) do
256+ if Sys.poll(fds, -1) < 0 then continue; end;
257+ for i := 0 to 1 do
258+ if fds[i].ready then
259+ if i = 0 then n := Sys.read(fds[0].fd, Buf.spare(out, 65536));
260+ else n := Sys.read(fds[1].fd, Buf.spare(err, 65536));
261+ end;
262+ if n > 0 then
263+ if i = 0 then INC(out.len, n); else INC(err.len, n); end;
264+ elsif n # Sys.errIntr then
265+ Sys.close(fds[i].fd);
266+ fds[i].fd := -1;
267+ end;
268+ end;
269+ end;
270+ end;
271+end;
272+
273+(* Runs args in dir with env added, and adds what it writes to out and
274+ what it writes to err, or all of it to out if merge: its exit
275+ status, or minus an errno if it can't start. *)
276+proc capture*(args: [][]const U8; dir: []const U8; env: [][]const U8; merge: BOOL; var out, err: Buf.Buf): INT;
277+var outRead, outWrite, errRead, errWrite, pid: INT;
278+begin
279+ outRead, outWrite := Sys.pipe();
280+ errRead := -1;
281+ errWrite := outWrite;
282+ if not merge then errRead, errWrite := Sys.pipe(); end;
283+ pid := start(args, dir, env, outWrite, errWrite);
284+ Sys.close(outWrite);
285+ if not merge then Sys.close(errWrite); end;
286+ if pid < 0 then
287+ Sys.close(outRead);
288+ if not merge then Sys.close(errRead); end;
289+ return pid;
290+ end;
291+ drain(outRead, errRead, out, err);
292+ return finish(pid);
293+end;
294+
295+(* Runs args in dir with env added, and adds what it writes to
296+ standard output to out, leaving its errors where they are: its exit
297+ status, or minus an errno if it can't start. *)
298+proc captureOut*(args: [][]const U8; dir: []const U8; env: [][]const U8; var out: Buf.Buf): INT;
299+var r, w, pid, n: INT;
300+begin
301+ r, w := Sys.pipe();
302+ pid := start(args, dir, env, w, 0);
303+ Sys.close(w);
304+ if pid < 0 then Sys.close(r); return pid; end;
305+ repeat
306+ n := Sys.read(r, Buf.spare(out, 65536));
307+ if n > 0 then INC(out.len, n); end;
308+ until (n <= 0) and (n # Sys.errIntr);
309+ Sys.close(r);
310+ return finish(pid);
311+end;
312+
313+(* The arguments of a git command in the repository at dir. *)
314+proc gitArgs*(dir: []const U8; args: [][]const U8): [][]const U8;
315+var v: Names.Vec; i: INT;
316+begin
317+ Names.init(v, Heap.heap);
318+ Names.push(v, "git"); Names.push(v, "-C"); Names.push(v, dir);
319+ for i := 0 to LEN(args) - 1 do Names.push(v, args[i]); end;
320+ return Names.all(v);
321+end;
322+
323+(* What the git command args writes to standard output, with white
324+ space cut from its ends, or the program stops. *)
325+proc git*(dir: []const U8; args: [][]const U8): []const U8;
326+var out: Buf.Buf;
327+begin
328+ Buf.init(out, Heap.heap);
329+ if captureOut(gitArgs(dir, args), "", [], out) # 0 then
330+ die("git {} failed", [Fmt.str(args[0])]);
331+ end;
332+ return Str.trim(Buf.bytes(out));
333+end;
334+
335+end Site.

site/Source.raz (history) added +410 -0

@@ -0,0 +1,410 @@
1+(* Source: the static source browser and the releases, built by ladle
2+ after Build has made the pages.
3+
4+ Source [--ladle path] [--url address] [vX.Y.Z=COMMIT ...]
5+
6+ Run from the repository root, by make site-source. It reads
7+ committed main and the existing, checksummed compiler
8+ distributions, and writes only site/public/source/ and the header
9+ rules at its root. It does not build compilers, create tags, upload
10+ files or deploy the site. The layout and the publishing rules are in
11+ site/README.md. It needs git, gzip and ladle, which it runs, and
12+ Site, Releases and Sha256. *)
13+module Source;
14+import Sys, Files, Buf, Str, Heap, Fmt, Opt, Site, Releases, Sha256;
15+import Commits := Map([]const U8, BOOL, Str.hash, Str.eq);
16+import Rels := Vec(Releases.Release);
17+import Sizes := Vec(Sized);
18+
19+const
20+ Url = "https://raz.lucelad.workers.dev/source/"; (* where the browser is, unless --url says *)
21+ BeginHeaders = "# BEGIN ladle source\n"; (* the block of ladle's header rules in the root _headers *)
22+ EndHeaders = "# END ladle source\n";
23+ MaxFiles = 20000; (* files the host takes *)
24+ MaxFileBytes = 25 * 1024 * 1024; (* bytes of its largest file *)
25+ LadleKey = 1; (* the keys of --ladle and --url, which have no letter *)
26+ UrlKey = 2;
27+ Table: []Opt.Row = [
28+ Opt.usage("", "Source [--ladle path] [--url address] [vX.Y.Z=COMMIT ...]"),
29+ Opt.option("", LadleKey, "ladle", "path", "use this ladle instead of the checked-in static executable"),
30+ Opt.option("", UrlKey, "url", "address", "the site's absolute /source/ address")];
31+
32+type
33+ (* A file of the site and its size, for the host's limits. *)
34+ Sized = record
35+ path: []const U8;
36+ size: I64;
37+ end;
38+
39+(* ---- the clone ---------------------------------------------------- *)
40+
41+(* Adds the lines of text, none empty, to the set of commits m. *)
42+proc addAll(var m: Commits.Map; text: []const U8);
43+var all: [][]const U8; i: INT;
44+begin
45+ all := Site.lines(text);
46+ for i := 0 to LEN(all) - 1 do
47+ if LEN(all[i]) > 0 then _ := Commits.put(m, all[i], true); end;
48+ end;
49+end;
50+
51+(* Clones main of the repository at root independently into directory,
52+ keeping only the tags whose commits it reaches; the clone's path.
53+ A deployment checkout can be detached and have no local branch: its
54+ commit is named main only inside this temporary published store. *)
55+proc prepareStore*(root, directory: []const U8): []const U8;
56+var
57+ store, ref, tag, reached: []const U8; all: [][]const U8; known: Commits.Map;
58+ out, err: Buf.Buf; local, ok: BOOL; i: INT;
59+begin
60+ store := Site.cat([directory, "/raz.git"]);
61+ ref, ok := Releases.mainRef(root);
62+ if not ok then Site.die("site build needs main or a detached deployment checkout", []); end;
63+ local := ref # "HEAD";
64+ if local then
65+ Site.must(["git", "clone", "--quiet", "--bare", "--single-branch", "--no-local", "--branch", "main", root, store]);
66+ else
67+ Site.must(["git", "clone", "--quiet", "--bare", "--single-branch", "--no-local", root, store]);
68+ _ := Site.git(store, ["update-ref", "refs/heads/main", Site.git(store, ["rev-parse", "HEAD"])]);
69+ _ := Site.git(store, ["symbolic-ref", "HEAD", "refs/heads/main"]);
70+ end;
71+ Commits.init(known, Heap.heap);
72+ addAll(known, Site.git(store, ["rev-list", "main"]));
73+ all := Site.lines(Site.git(store, ["tag", "--list"]));
74+ for i := 0 to LEN(all) - 1 do
75+ tag := all[i];
76+ if LEN(tag) > 0 then
77+ (* Tags of trees or blobs are not cloneable releases. Ask quietly:
78+ such a tag is valid git, simply outside the published history. *)
79+ Buf.init(out, Heap.heap);
80+ Buf.init(err, Heap.heap);
81+ ok := Site.capture(Site.gitArgs(store, ["rev-parse", "--verify", Site.cat(["refs/tags/", tag, "^{commit}"])]),
82+ "", [], false, out, err) = 0;
83+ reached := Str.trim(Buf.bytes(out));
84+ if ok then _, ok := Commits.get(known, reached); end;
85+ if not ok then _ := Site.git(store, ["update-ref", "-d", Site.cat(["refs/tags/", tag])]); end;
86+ end;
87+ end;
88+ _ := Site.git(store, ["repack", "-a", "-d", "--max-pack-size=20m"]);
89+ _ := Site.git(store, ["update-server-info"]);
90+ return store;
91+end;
92+
93+(* ---- checksums ---------------------------------------------------- *)
94+
95+(* Where a file's published checksum is: its path and .sha256. *)
96+proc sumPath(path: []const U8): []const U8;
97+begin
98+ return Site.cat([path, ".sha256"]);
99+end;
100+
101+(* The SHA-256, as hex, of the file at path. *)
102+proc digest(path: []const U8): []const U8;
103+var b: Buf.Buf;
104+begin
105+ Buf.init(b, Heap.heap);
106+ Sha256.hex(Site.read(path), b);
107+ return Buf.bytes(b);
108+end;
109+
110+(* The published checksum of the file at path, never replaced to fit
111+ different bytes; the empty string and why if it isn't a SHA-256 and
112+ the file's name. *)
113+proc publishedSum(path: []const U8): ([]const U8, []const U8);
114+var words: [][]const U8; name: []const U8; i: INT; hex: BOOL;
115+begin
116+ name := path[Str.findLast(path, "/") + 1..LEN(path)];
117+ words := Site.words(Site.read(sumPath(path)));
118+ hex := (LEN(words) = 2) and (LEN(words[0]) = 64) and (words[1] = name);
119+ if hex then
120+ for i := 0 to 63 do
121+ hex := hex and (Str.isDigit(words[0][i]) or ((words[0][i] >= 'a') and (words[0][i] <= 'f')));
122+ end;
123+ end;
124+ if not hex then
125+ return "", Site.cat([sumPath(path), ": expected SHA-256 and ", name]);
126+ end;
127+ return words[0], "";
128+end;
129+
130+(* The static builder: the checked-in ladle.gz, whose bytes must have its
131+ recorded SHA-256, unpacked to executable, needing no compiler or
132+ network; the executable's path, or the empty string and why. It is
133+ renamed into place, a new inode: another build may still be running
134+ the previous executable, which can't be overwritten on Linux. *)
135+proc pinnedLadle*(archive, executable: []const U8): ([]const U8, []const U8);
136+var want, why, temporary: []const U8; slash, fd, status: INT;
137+begin
138+ want, why := publishedSum(archive);
139+ if LEN(why) > 0 then return "", why; end;
140+ if digest(archive) # want then return "", Site.cat([archive, ": differs from its recorded SHA-256"]); end;
141+ slash := Str.findLast(executable, "/");
142+ Site.makeDirs(executable[0..slash]);
143+ temporary := Site.cat([executable, ".new"]);
144+ fd := Sys.create(temporary);
145+ if fd < 0 then Site.die("can't make {}", [Fmt.str(temporary)]); end;
146+ status := Site.run(["gzip", "-dc", archive], fd);
147+ Sys.close(fd);
148+ if status # 0 then Site.die("gzip can't unpack {}", [Fmt.str(archive)]); end;
149+ if (Sys.chmod(temporary, 1EDH) < 0) or (Sys.rename(temporary, executable) < 0) then
150+ Site.die("can't install {}", [Fmt.str(executable)]);
151+ end;
152+ return executable, "";
153+end;
154+
155+(* ---- the releases ------------------------------------------------- *)
156+
157+(* Copies the compiler's distribution of version into directory from
158+ public/download, checking its published checksum; why, if it differs. *)
159+proc compilerArchive(root, version, directory: []const U8): []const U8;
160+var name, original, copied, want, why: []const U8;
161+begin
162+ name := Site.cat(["raz-", version[1..LEN(version)], "-linux-x86_64.tar.gz"]);
163+ original := Site.cat([root, "/site/public/download/", name]);
164+ want, why := publishedSum(original);
165+ if LEN(why) > 0 then return why; end;
166+ copied := Site.cat([directory, "/", name]);
167+ Site.copy(original, copied);
168+ if digest(copied) # want then return Site.cat([original, ": differs from its published SHA-256"]); end;
169+ return "";
170+end;
171+
172+(* Archives exactly the commit, with no wall-clock time or file name in
173+ gzip's header; why, if it can't. *)
174+proc sourceArchive(store, version, commit, directory: []const U8): []const U8;
175+var name, prefix: []const U8; fd, tar, zip: INT;
176+begin
177+ name := Site.cat([directory, "/raz-", version[1..LEN(version)], "-source.tar.gz"]);
178+ prefix := Site.cat(["--prefix=raz-", version[1..LEN(version)], "/"]);
179+ fd := Sys.create(name);
180+ if fd < 0 then Site.die("can't make {}", [Fmt.str(name)]); end;
181+ tar, zip := Site.pipeline(["git", "-C", store, "archive", "--format=tar", prefix, commit], ["gzip", "-9n"], fd);
182+ Sys.close(fd);
183+ if (tar # 0) or (zip # 0) then return Site.cat(["release ", version, ": git archive failed"]); end;
184+ return "";
185+end;
186+
187+(* Puts each selected release in directory/<version>/: its commit, its
188+ notes if site/release-notes has them, its compiler and its source;
189+ why, if one is wrong. *)
190+proc stageReleases(root, store, directory: []const U8; selected: []const Releases.Release): []const U8;
191+var line: Commits.Map; release, notes, why: []const U8; i: INT; ok: BOOL;
192+begin
193+ Commits.init(line, Heap.heap);
194+ addAll(line, Site.git(store, ["rev-list", "--first-parent", "main"]));
195+ Site.makeDirs(directory);
196+ for i := 0 to LEN(selected) - 1 do
197+ (* Ref resolution is shared with Build. Check against our snapshot
198+ too, so a commit made during the build cannot split their histories. *)
199+ _, ok := Commits.get(line, selected[i].commit);
200+ if not ok then
201+ return Site.cat(["release ", selected[i].tag, ": ", selected[i].commit, " is not in the cloned main history"]);
202+ end;
203+ release := Site.cat([directory, "/", selected[i].tag]);
204+ Site.makeDirs(release);
205+ Site.write(Site.cat([release, "/commit"]), Site.cat([selected[i].commit, "\n"]));
206+ notes := Site.cat([root, "/site/release-notes/", selected[i].tag, ".md"]);
207+ if Site.exists(notes) then Site.copy(notes, Site.cat([release, "/notes.md"])); end;
208+ why := compilerArchive(root, selected[i].tag, release);
209+ if LEN(why) > 0 then return why; end;
210+ why := sourceArchive(store, selected[i].tag, selected[i].commit, release);
211+ if LEN(why) > 0 then return why; end;
212+ end;
213+ return "";
214+end;
215+
216+(* Copies only the dumb-HTTP store into output, never configuration or
217+ local paths: HEAD, info/refs, objects/info/packs and objects/pack. *)
218+proc exportStore(store, output: []const U8);
219+var names: [][]const U8; i: INT;
220+begin
221+ Site.copy(Site.cat([store, "/HEAD"]), Site.cat([output, "/HEAD"]));
222+ Site.copy(Site.cat([store, "/info/refs"]), Site.cat([output, "/info/refs"]));
223+ Site.copy(Site.cat([store, "/objects/info/packs"]), Site.cat([output, "/objects/info/packs"]));
224+ names := Site.dirNames(Site.cat([store, "/objects/pack"]));
225+ Site.makeDirs(Site.cat([output, "/objects/pack"]));
226+ for i := 0 to LEN(names) - 1 do
227+ Site.copy(Site.cat([store, "/objects/pack/", names[i]]), Site.cat([output, "/objects/pack/", names[i]]));
228+ end;
229+end;
230+
231+(* ---- headers and limits ------------------------------------------- *)
232+
233+(* The root header file with our scoped block replaced by the rules ladle
234+ generated, prefixed with /source, keeping the host's other rules;
235+ and why, if the old block has no end. *)
236+proc mergedHeaders(path, generated: []const U8): ([]const U8, []const U8);
237+var existing, before, rest, after: []const U8; found: BOOL; b: Buf.Buf; all: [][]const U8; i: INT;
238+begin
239+ existing := "";
240+ if Site.exists(path) then existing := Site.read(path); end;
241+ if Str.find(existing, BeginHeaders) >= 0 then
242+ before, rest, found := Str.cut(existing, BeginHeaders);
243+ _, after, found := Str.cut(rest, EndHeaders);
244+ if not found then return "", Site.cat([path, ": source header block has no closing marker"]); end;
245+ existing := Site.cat([before, after]);
246+ end;
247+ Buf.init(b, Heap.heap);
248+ Buf.str(b, Str.trimRight(existing));
249+ Buf.str(b, "\n\n");
250+ Buf.str(b, BeginHeaders);
251+ all := Site.lines(generated);
252+ if (LEN(all) > 0) and (LEN(all[LEN(all) - 1]) = 0) then all := all[0..LEN(all) - 1]; end;
253+ for i := 0 to LEN(all) - 1 do
254+ if i > 0 then Buf.add(b, '\n'); end;
255+ if Str.hasPrefix(all[i], "/") then Buf.str(b, "/source"); end;
256+ Buf.str(b, all[i]);
257+ end;
258+ Buf.add(b, '\n');
259+ Buf.str(b, EndHeaders);
260+ return Buf.bytes(b), "";
261+end;
262+
263+(* Adds every file under dir to v with its size, skipping the top-level
264+ names in skip. *)
265+proc walk(dir: []const U8; skip: [][]const U8; var v: Sizes.Vec);
266+var names: [][]const U8; f: Sys.Info; path: []const U8; err, i, k: INT; skipped: BOOL;
267+begin
268+ names := Site.dirNames(dir);
269+ for i := 0 to LEN(names) - 1 do
270+ skipped := false;
271+ for k := 0 to LEN(skip) - 1 do skipped := skipped or (names[i] = skip[k]); end;
272+ if not skipped then
273+ path := Site.cat([dir, "/", names[i]]);
274+ f, err := Sys.info(path);
275+ if (err = 0) and f.dir then walk(path, [], v);
276+ elsif (err = 0) and f.file then Sizes.push(v, {path: path, size: f.size});
277+ end;
278+ end;
279+ end;
280+end;
281+
282+(* Measures the complete proposed output: the files of public/ but the
283+ old source tree and the root _headers, the new source tree, once,
284+ and the new headers. why if one is too big or there are too many;
285+ otherwise prints the totals for review against the hosting plan. *)
286+proc checkLimits(public, output: []const U8; headers: []const U8): []const U8;
287+var v: Sizes.Vec; all: []Sized; total, largest: I64; i: INT; b: Buf.Buf;
288+begin
289+ Sizes.init(v, Heap.heap);
290+ walk(public, ["source", "_headers"], v);
291+ walk(output, [], v);
292+ Sizes.push(v, {path: Site.cat([public, "/_headers"]), size: I64(LEN(headers))});
293+ all := Sizes.all(v);
294+ for i := 0 to LEN(all) - 1 do
295+ if all[i].size > MaxFileBytes then
296+ Buf.init(b, Heap.heap);
297+ Fmt.write(b, "{}: {} bytes exceeds the 25 MiB file limit", [Fmt.str(all[i].path), Fmt.int(all[i].size)]);
298+ return Buf.bytes(b);
299+ end;
300+ total := total + all[i].size;
301+ if all[i].size > largest then largest := all[i].size; end;
302+ end;
303+ if LEN(all) > MaxFiles then
304+ Buf.init(b, Heap.heap);
305+ Fmt.write(b, "site: {} files exceeds the {} file limit", [Fmt.int(LEN(all)), Fmt.int(MaxFiles)]);
306+ return Buf.bytes(b);
307+ end;
308+ Fmt.print("site/public: {} files, {} bytes; largest file {} bytes\n",
309+ [Fmt.int(LEN(all)), Fmt.int(total), Fmt.int(largest)]);
310+ return "";
311+end;
312+
313+(* ---- the build ---------------------------------------------------- *)
314+
315+(* Whether url is an HTTP(S) address ending in /source/ with no query or
316+ fragment. *)
317+proc validUrl(url: []const U8): BOOL;
318+var rest: []const U8; slash: INT;
319+begin
320+ if Str.hasPrefix(url, "https://") then rest := url[8..LEN(url)];
321+ elsif Str.hasPrefix(url, "http://") then rest := url[7..LEN(url)];
322+ else return false;
323+ end;
324+ slash := Str.find(rest, "/");
325+ return (slash > 0) and (rest[slash..LEN(rest)] = "/source/");
326+end;
327+
328+(* Builds the browser in a temporary directory of build/site/, then
329+ replaces public/source with it. A failed checksum, ladle run or
330+ host-limit check leaves the previous browser in place: nothing reads
331+ that output. The empty string, or why it failed. *)
332+proc build(root, ladle, url: []const U8; extra: []const Releases.Release): []const U8;
333+var
334+ public, work, store, releases, output, headers, why, exe: []const U8; selected: []Releases.Release;
335+begin
336+ if not validUrl(url) then return "--url must be an HTTP(S) address ending in /source/"; end;
337+ public := Site.cat([root, "/site/public"]);
338+ if not Site.isDir(public) then return "site/public is missing; run Build first"; end;
339+ selected, why := Releases.refs(root, extra); (* completes a shallow deployment checkout before cloning *)
340+ if LEN(why) > 0 then return why; end;
341+ exe := ladle;
342+ if LEN(exe) = 0 then
343+ exe, why := pinnedLadle(Site.cat([root, "/site/tools/ladle.gz"]), Site.cat([root, "/build/site/ladle"]));
344+ if LEN(why) > 0 then return why; end;
345+ end;
346+ Site.makeDirs(Site.cat([root, "/build/site"]));
347+ work := Site.tempDirIn(Site.cat([root, "/build/site"]));
348+ store := prepareStore(root, work);
349+ releases := Site.cat([work, "/releases"]);
350+ why := stageReleases(root, store, releases, selected);
351+ output := Site.cat([work, "/source"]);
352+ Site.makeDirs(output);
353+ if LEN(why) = 0 then
354+ exportStore(store, output);
355+ if Site.run([exe, "-u", url, "-r", releases, "-t", Site.cat([root, "/site/source.theme"]), "-o", output, store], 0) # 0 then
356+ why := "ladle failed";
357+ end;
358+ end;
359+ if LEN(why) = 0 then
360+ headers, why := mergedHeaders(Site.cat([public, "/_headers"]), Site.read(Site.cat([output, "/_headers"])));
361+ end;
362+ if LEN(why) = 0 then why := checkLimits(public, output, headers); end;
363+ if LEN(why) = 0 then
364+ _ := Files.removeTree(Site.cat([public, "/source"]));
365+ if Sys.rename(output, Site.cat([public, "/source"])) < 0 then Site.die("can't move {}", [Fmt.str(output)]); end;
366+ Site.write(Site.cat([public, "/_headers"]), headers);
367+ end;
368+ _ := Files.removeTree(work);
369+ return why;
370+end;
371+
372+(* The vX.Y.Z=COMMIT arguments given to Opt as releases; the empty
373+ string and the first wrong word, if one is. *)
374+proc readReleases(var p: Opt.Parser; var v: Rels.Vec): []const U8;
375+var arg, tag, commit: []const U8; more, found: BOOL;
376+begin
377+ arg, more := Opt.operand(p);
378+ while more do
379+ tag, commit, found := Str.cut(arg, "=");
380+ if not found or (LEN(commit) = 0) then return Site.cat([arg, ": expected vX.Y.Z=COMMIT"]); end;
381+ Rels.push(v, {tag: tag, commit: commit});
382+ arg, more := Opt.operand(p);
383+ end;
384+ return "";
385+end;
386+
387+proc main*;
388+var
389+ p: Opt.Parser; ladle, url, root, why: []const U8; extra: Rels.Vec; err: INT;
390+begin
391+ ladle := "";
392+ url := Url;
393+ Opt.init(p, "Source", Table);
394+ while Opt.next(p) do
395+ if p.letter = LadleKey then ladle := p.value;
396+ elsif p.letter = UrlKey then url := p.value;
397+ end;
398+ end;
399+ Rels.init(extra, Heap.heap);
400+ root, err := Sys.workDir();
401+ if err < 0 then Site.die("source: no working directory", []); end;
402+ root := Site.cat([root]);
403+ if LEN(ladle) > 0 then
404+ if ladle[0] # '/' then ladle := Site.cat([root, "/", ladle]); end; (* as Path.resolve would *)
405+ end;
406+ why := readReleases(p, extra);
407+ if LEN(why) = 0 then why := build(root, ladle, url, Rels.all(extra)); end;
408+ if LEN(why) > 0 then Site.die("source: {}", [Fmt.str(why)]); end;
409+end;
410+end Source.

site/Verify.raz (history) added +209 -0

@@ -0,0 +1,209 @@
1+(* Verify: checks release selection with real git histories, and the
2+ bundled builder's checksum:
3+
4+ raz run site/Verify.raz
5+
6+ Run from the repository root; it needs only the library, git and
7+ Source's procedures. Every repository and download is temporary: no
8+ release, working checkout or published file is changed. Each test
9+ makes a small repository of three tagged commits and a record of a
10+ fourth release in site/releases, and says its name, then what
11+ fails, as Check does. It leaves out the rest of the site: Build and
12+ Source are checked by building the site. *)
13+module Verify;
14+import Files, Buf, Str, Heap, Fmt, Check, Site, Releases, Source;
15+import Names := Vec([]const U8);
16+
17+const
18+ Versions: [3][]const U8 = ["v0.7.1", "v0.9.0", "v0.10.0"]; (* the tagged releases *)
19+ (* the settings of the git a test runs: a name, an address, no signing *)
20+ Identity: [6][]const U8 = ["-c", "user.name=Test", "-c", "user.email=test@example.org", "-c", "commit.gpgSign=false"];
21+
22+type
23+ (* A repository for a test: where it is, and its three tagged commits. *)
24+ Repo = record
25+ dir: []const U8; (* the temporary directory that holds everything *)
26+ path: []const U8; (* the repository, dir/repo *)
27+ manifest: []const U8; (* its site/releases *)
28+ commits: [3][]const U8; (* the commits of Versions *)
29+ end;
30+
31+(* The text git writes for the command args in the repository at path,
32+ run as a test user who signs nothing; the test stops if git fails. *)
33+proc git(path: []const U8; args: [][]const U8): []const U8;
34+var v: Names.Vec; out: Buf.Buf; i: INT;
35+begin
36+ Names.init(v, Heap.heap);
37+ Names.push(v, "git"); Names.push(v, "-C"); Names.push(v, path);
38+ for i := 0 to LEN(Identity) - 1 do Names.push(v, Identity[i]); end;
39+ for i := 0 to LEN(args) - 1 do Names.push(v, args[i]); end;
40+ Buf.init(out, Heap.heap);
41+ if Site.captureOut(Names.all(v), "", [], out) # 0 then Site.die("git {} failed", [Fmt.str(args[0])]); end;
42+ return Str.trim(Buf.bytes(out));
43+end;
44+
45+(* Makes the test repository: three commits tagged v0.7.1, v0.9.0 and
46+ v0.10.0, then a commit that records v0.20.0, not tagged yet, at the
47+ last of them. *)
48+proc setUp(var r: Repo);
49+var i: INT; number: [20]U8; len: INT;
50+begin
51+ r.dir := Site.tempDir();
52+ r.path := Site.cat([r.dir, "/repo"]);
53+ r.manifest := Site.cat([r.path, "/site/releases"]);
54+ Site.makeDirs(Site.cat([r.path, "/site"]));
55+ _ := git(r.path, ["init", "--quiet", "--initial-branch=main"]);
56+ for i := 0 to 2 do
57+ number, len := Str.fromInt(I64(i));
58+ Site.write(Site.cat([r.path, "/file"]), number[0..len]);
59+ _ := git(r.path, ["add", "."]);
60+ _ := git(r.path, ["commit", "--quiet", "-m", Versions[i]]);
61+ r.commits[i] := git(r.path, ["rev-parse", "HEAD"]);
62+ _ := git(r.path, ["tag", Versions[i]]);
63+ end;
64+ Site.write(r.manifest, Site.cat(["# not tagged yet\nv0.20.0 ", r.commits[2], "\n"]));
65+ _ := git(r.path, ["add", "site/releases"]);
66+ _ := git(r.path, ["commit", "--quiet", "-m", "record distribution"]);
67+end;
68+
69+(* Whether the two lists of releases are the same. *)
70+proc same(a, b: []const Releases.Release): BOOL;
71+var i: INT;
72+begin
73+ if LEN(a) # LEN(b) then return false; end;
74+ for i := 0 to LEN(a) - 1 do
75+ if (a[i].tag # b[i].tag) or (a[i].commit # b[i].commit) then return false; end;
76+ end;
77+ return true;
78+end;
79+
80+(* The releases of the repository at path; the test stops if they are
81+ a mistake. *)
82+proc releasesOf(path: []const U8): []Releases.Release;
83+var list: []Releases.Release; why: []const U8;
84+begin
85+ list, why := Releases.refs(path, []);
86+ Check.str("no mistake", why, "");
87+ return list;
88+end;
89+
90+(* Checks that refs of the repository at path is a mistake whose
91+ message holds word. *)
92+proc refuses(name, path, word: []const U8);
93+var why: []const U8;
94+begin
95+ _, why := Releases.refs(path, []);
96+ Check.ok(Str.find(why, word) >= 0, Site.cat([name, ": a mistake saying ", word, ", not \"", why, "\""]));
97+end;
98+
99+(* Tags, in order, and a record, make the numeric order of releases:
100+ v0.9.0 before v0.10.0, and the record last. *)
101+proc testNumericTagsAndManifest;
102+var r: Repo; want: [4]Releases.Release;
103+begin
104+ setUp(r);
105+ want := [{tag: "v0.7.1", commit: r.commits[0]}, {tag: "v0.9.0", commit: r.commits[1]},
106+ {tag: "v0.10.0", commit: r.commits[2]}, {tag: "v0.20.0", commit: r.commits[2]}];
107+ Check.ok(same(releasesOf(r.path), want), "numeric tags and manifest");
108+ _ := Files.removeTree(r.dir);
109+end;
110+
111+(* A record can't move a tag to another commit. *)
112+proc testManifestCannotMoveATag;
113+var r: Repo;
114+begin
115+ setUp(r);
116+ Site.write(r.manifest, Site.cat(["v0.9.0 ", r.commits[0], "\n"]));
117+ refuses("manifest cannot move a tag", r.path, "disagree");
118+ _ := Files.removeTree(r.dir);
119+end;
120+
121+(* A record can't publish a commit of another line, and a tag added
122+ later can't override a record. *)
123+proc testManifestCannotPublishAnotherLine;
124+var r: Repo; side: []const U8;
125+begin
126+ setUp(r);
127+ _ := git(r.path, ["checkout", "--quiet", "-b", "side", r.commits[0]]);
128+ Site.write(Site.cat([r.path, "/side"]), "a development branch\n");
129+ _ := git(r.path, ["add", "side"]);
130+ _ := git(r.path, ["commit", "--quiet", "-m", "side"]);
131+ side := git(r.path, ["rev-parse", "HEAD"]);
132+ _ := git(r.path, ["checkout", "--quiet", "main"]);
133+ Site.write(r.manifest, Site.cat(["v0.20.0 ", side, "\n"]));
134+ refuses("manifest cannot publish another line", r.path, "first-parent");
135+ (* A new tag must not override the recorded distribution, even when
136+ that tag would otherwise be skipped as off the main line. *)
137+ Site.write(r.manifest, Site.cat(["v0.20.0 ", r.commits[2], "\n"]));
138+ _ := git(r.path, ["tag", "v0.20.0", side]);
139+ refuses("a tag cannot override a record", r.path, "disagree");
140+ _ := Files.removeTree(r.dir);
141+end;
142+
143+(* A shallow clone, as a deployment service makes, gets its history and
144+ tags back from its origin. A file URL uses git's transport, so --depth
145+ really is shallow. *)
146+proc testShallowDeploy;
147+var r: Repo; clone: []const U8;
148+begin
149+ setUp(r);
150+ clone := Site.cat([r.dir, "/deploy"]);
151+ _ := git(r.path, ["clone", "--quiet", "--depth=1", "--branch=main", Site.cat(["file://", r.path]), clone]);
152+ Check.str("shallow before", git(clone, ["rev-parse", "--is-shallow-repository"]), "true");
153+ Check.ok(same(releasesOf(clone), releasesOf(r.path)), "shallow deploy recovers history and tags");
154+ Check.str("shallow after", git(clone, ["rev-parse", "--is-shallow-repository"]), "false");
155+ _ := Files.removeTree(r.dir);
156+end;
157+
158+(* A detached shallow checkout with no local main still has its releases,
159+ and the published store names its commit main. *)
160+proc testDetachedShallowDeploy;
161+var r: Repo; clone, store: []const U8;
162+begin
163+ setUp(r);
164+ clone := Site.cat([r.dir, "/deploy"]);
165+ _ := git(r.path, ["clone", "--quiet", "--depth=1", "--branch=main", Site.cat(["file://", r.path]), clone]);
166+ _ := git(clone, ["checkout", "--quiet", "--detach"]);
167+ _ := git(clone, ["branch", "-D", "main"]);
168+ Check.ok(same(releasesOf(clone), releasesOf(r.path)), "detached shallow deploy needs no local main");
169+ store := Source.prepareStore(clone, r.dir);
170+ Check.str("store's commit", git(store, ["rev-parse", "HEAD"]), git(clone, ["rev-parse", "HEAD"]));
171+ Check.str("store's branch", git(store, ["symbolic-ref", "HEAD"]), "refs/heads/main");
172+ _ := git(store, ["fsck", "--strict"]);
173+ Check.str("clone stays detached", git(clone, ["rev-parse", "--abbrev-ref", "HEAD"]), "HEAD");
174+ _ := Files.removeTree(r.dir);
175+end;
176+
177+(* A builder whose bytes are not the ones recorded is rejected before it
178+ is unpacked. *)
179+proc testModifiedBuilderIsRejected;
180+var dir, archive, why: []const U8;
181+begin
182+ dir := Site.tempDir();
183+ archive := Site.cat([dir, "/ladle.gz"]);
184+ Site.write(archive, "not the published executable");
185+ Site.write(Site.cat([archive, ".sha256"]), Site.cat(["0000000000000000000000000000000000000000000000000000000000000000", " ladle.gz\n"]));
186+ _, why := Source.pinnedLadle(archive, Site.cat([dir, "/ladle"]));
187+ Check.ok(Str.find(why, "recorded SHA-256") >= 0, "modified builder is rejected");
188+ Check.ok(not Site.exists(Site.cat([dir, "/ladle"])), "nothing is unpacked");
189+ _ := Files.removeTree(dir);
190+end;
191+
192+(* Says that the test t, which is called name, is running, and runs it:
193+ Check says what fails, and at the end how many checks did. *)
194+proc run(name: []const U8; t: proc);
195+begin
196+ Fmt.print("{}\n", [Fmt.str(name)]);
197+ t();
198+end;
199+
200+proc main*;
201+begin
202+ run("numeric tags and manifest", testNumericTagsAndManifest);
203+ run("manifest cannot move a tag", testManifestCannotMoveATag);
204+ run("manifest cannot publish another line", testManifestCannotPublishAnotherLine);
205+ run("shallow deploy recovers history and tags", testShallowDeploy);
206+ run("detached shallow deploy needs no local main", testDetachedShallowDeploy);
207+ run("modified builder is rejected before unpacking", testModifiedBuilderIsRejected);
208+end;
209+end Verify.

site/build.py deleted +0 -436

@@ -1,436 +0,0 @@
1-#!/usr/bin/env python3
2-"""Builds the website into site/public/ from site/content/ and the repository.
3-
4- python3 site/build.py [vX.Y.Z=COMMIT ...]
5-
6-site/releases records website distributions whose tags are not pushed
7-yet. Each additional vX.Y.Z=COMMIT is another such distribution: it is
8-offered as if the tag were at COMMIT, its tarball made by make dist
9-with VERSION, the same tarball the tag will give.
10-
11-The site is plain files: open public/index.html, or put the folder on
12-any web server. Nothing runs in the reader's browser; the code on the
13-tour's pages is run here, by ./raz, and the output shown is what it
14-printed, so a lesson that stops working fails the build. The home page
15-offers every release's tarball, made by make dist from its tag.
16-
17-Lessons are site/content/<tour>/NN-name.txt, one folder to a tour (see
18-TOURS below):
19-
20- title: Hello, world (the first lines are "key: value")
21- part: Raz (the lessons are grouped in parts)
22- summary: a line for the contents page
23- ---
24- Paragraphs, separated by blank lines. `code`, **bold**,
25- [links](url), "- " lists and pipe tables are understood, and nothing else.
26-
27- ```raz Name run
28- ```
29-
30-A fenced block "raz Name" is a module, written as Name.raz in a folder
31-of its own for the lesson. "run" has the build run it and show what it
32-printed; "fail" runs it and shows the failure it ends in. A block with
33-nothing in it is taken from doc/raz-tutorial.7, whose programs make
34-check already runs, by the module's name.
35-
36-Two other blocks: "```text" is shown as written, and "```sh" is a shell
37-session: each line that starts with "$ " is run in the lesson's folder,
38-with raz on the path, and shown with what it printed.
39-"""
40-import hashlib, html, os, re, shutil, subprocess, sys, tempfile
41-from releases import refs
42-
43-HERE = os.path.dirname(os.path.abspath(__file__))
44-ROOT = os.path.dirname(HERE)
45-OUT = os.path.join(HERE, "public")
46-RAZ = os.path.join(ROOT, "raz")
47-SITE = "https://raz.lucelad.workers.dev" # where the pages live, for the preview image
48-
49-# folder in content/, folder in public/, name, the sentence under the name
50-TOURS = [
51- ("tour", "tour", "Raz, Set, Go", "tour-intro.html"),
52- ("advanced", "advanced", "More Raz", "advanced-intro.html"),
53-]
54-
55-KEYWORDS = set("""and begin break by code const defer div do else elsif end
56-extern for forward if import in link match mod module not of or packed proc
57-record repeat return set shl shr then to try type until var variant VOLATILE
58-while xor""".split())
59-PREDECLARED = set("""INT UINT I8 I16 I32 I64 U8 U16 U32 U64 F32 F64 BOOL ERROR
60-true false nil LEN ADR NEW SIZE INC DEC MSG XADD CAS XCHG""".split())
61-
62-# ---- highlighting ------------------------------------------------------
63-
64-TOKEN = re.compile(r"""
65- (?P<comment>\(\*.*?\*\)) |
66- (?P<string>"(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*'|`[^`]*`) |
67- (?P<number>\b\d[0-9A-Fa-f]*(?:\.\d+)?(?:E[-+]?\d+)?H?\b) |
68- (?P<word>[A-Za-z_][A-Za-z_0-9]*)
69-""", re.X | re.S)
70-
71-def highlight(src):
72- """src as HTML, its comments, strings, numbers and words in spans."""
73- out, at = [], 0
74- for m in TOKEN.finditer(src):
75- out.append(html.escape(src[at:m.start()]))
76- text, kind = m.group(), m.lastgroup
77- if kind == "word":
78- kind = ("kw" if text in KEYWORDS else
79- "ty" if text in PREDECLARED else None)
80- if kind:
81- out.append('<span class="%s">%s</span>' % (kind, html.escape(text)))
82- else:
83- out.append(html.escape(text))
84- at = m.end()
85- out.append(html.escape(src[at:]))
86- return "".join(out)
87-
88-# ---- the tutorial's programs -------------------------------------------
89-
90-def tutorial_blocks():
91- """Every literal block of the manual page, as raz source."""
92- blocks, cur = [], None
93- for line in open(os.path.join(ROOT, "doc", "raz-tutorial.7"), encoding="utf-8"):
94- line = line.rstrip("\n")
95- if line.startswith(".Bd -literal"):
96- cur = []
97- elif line == ".Ed" and cur is not None:
98- blocks.append("\n".join(cur) + "\n")
99- cur = None
100- elif cur is not None:
101- # roff writes a backslash as \e, a backquote as \(ga and a dot
102- # at a line's start as \&.
103- cur.append(line.replace("\\&", "").replace("\\(ga", "`").replace("\\e", "\\"))
104- return blocks
105-
106-def tutorial_module(name):
107- for b in tutorial_blocks():
108- if re.search(r"^module %s\b" % re.escape(name), b, re.M):
109- return b
110- sys.exit("no program %s in the tutorial" % name)
111-
112-# ---- running -----------------------------------------------------------
113-
114-def run(directory, name):
115- """(stdout, stderr, status) of the module name, compiled and run."""
116- p = subprocess.run([RAZ, "run", "-Werror", name + ".raz"], cwd=directory,
117- capture_output=True, text=True, timeout=60)
118- return p.stdout, p.stderr, p.returncode
119-
120-def shell_html(directory, script):
121- """A session: each "$ command" line run in directory, with its output."""
122- bin = os.path.join(directory, ".bin")
123- os.makedirs(bin, exist_ok=True)
124- if not os.path.exists(os.path.join(bin, "raz")):
125- os.symlink(RAZ, os.path.join(bin, "raz")) # raz finds lib/ by its real path
126- env = dict(os.environ, PATH=bin + ":" + os.environ["PATH"],
127- RAZLIB=os.path.join(ROOT, "lib"))
128- out = []
129- for line in script.rstrip("\n").split("\n"):
130- if not line.startswith("$ "):
131- out.append(html.escape(line))
132- continue
133- out.append('<span class="cmd">%s</span>' % html.escape(line))
134- p = subprocess.run(line[2:], shell=True, cwd=directory, env=env,
135- stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
136- text=True, timeout=60)
137- text = p.stdout.rstrip("\n")
138- if text:
139- out.append(html.escape(text))
140- return '<pre class="output term"><code>%s</code></pre>' % "\n".join(out)
141-
142-def output_html(stdout, stderr):
143- out = html.escape(stdout)
144- if stderr:
145- out += '<span class="err">%s</span>' % html.escape(stderr)
146- return '<pre class="output"><code>%s</code></pre>' % out
147-
148-# ---- a little markup -----------------------------------------------------
149-
150-def inline(s):
151- s = html.escape(s, quote=False)
152- s = re.sub(r"`([^`]+)`", r"<code>\1</code>", s)
153- s = re.sub(r"\*\*([^*]+)\*\*", r"<strong>\1</strong>", s)
154- s = re.sub(r"\[([^\]]+)\]\(([^)]+)\)", r'<a href="\2">\1</a>', s)
155- return s
156-
157-def table(lines):
158- """A pipe table (header, a |---| rule, rows) as HTML. Each cell
159- carries its column's name, which the style sheet shows when the
160- screen is too narrow for columns."""
161- cells = lambda l: [c.strip() for c in l.strip().strip("|").split("|")]
162- head = cells(lines[0])
163- rows = "".join("<tr>%s</tr>" % "".join(
164- '<td data-label="%s">%s</td>' % (html.escape(h), inline(c))
165- for h, c in zip(head, cells(l))) for l in lines[2:])
166- return "<table><thead><tr>%s</tr></thead><tbody>%s</tbody></table>" % (
167- "".join("<th>%s</th>" % inline(h) for h in head), rows)
168-
169-def prose(text):
170- out = []
171- for para in re.split(r"\n\s*\n", text.strip()):
172- lines = para.split("\n")
173- if para.startswith("## "):
174- out.append("<h2>%s</h2>" % inline(para[3:]))
175- elif all(l.startswith("|") for l in lines):
176- out.append(table(lines))
177- elif all(l.startswith("- ") for l in lines):
178- out.append("<ul>%s</ul>" % "".join(
179- "<li>%s</li>" % inline(l[2:]) for l in lines))
180- else:
181- out.append("<p>%s</p>" % inline(" ".join(lines)))
182- return "\n".join(out)
183-
184-# ---- lessons -------------------------------------------------------------
185-
186-def read_lesson(path):
187- head, _, body = open(path, encoding="utf-8").read().partition("\n---\n")
188- meta = dict(l.split(": ", 1) for l in head.strip().split("\n"))
189- meta["slug"] = re.sub(r"^\d+-|\.txt$", "", os.path.basename(path))
190- meta["body"] = body
191- return meta
192-
193-def lesson_body(lesson):
194- """The lesson's page content; runs its programs."""
195- parts, tmp = [], tempfile.mkdtemp()
196- try:
197- chunks = re.split(r"^```(raz [^\n]*|text|sh)\n(.*?)^```$", lesson["body"],
198- flags=re.M | re.S)
199- # chunks: text, info, code, text, info, code, ..., text
200- for i in range(0, len(chunks), 3):
201- if chunks[i].strip():
202- parts.append(prose(chunks[i]))
203- if i + 1 >= len(chunks):
204- break
205- kind, code = chunks[i + 1], chunks[i + 2]
206- if kind == "text":
207- parts.append('<pre class="code"><code>%s</code></pre>'
208- % html.escape(code.rstrip("\n")))
209- continue
210- if kind == "sh":
211- parts.append(shell_html(tmp, code))
212- continue
213- info = kind.split()[1:]
214- name, flags = info[0], info[1:]
215- if not code.strip():
216- code = tutorial_module(name)
217- with open(os.path.join(tmp, name + ".raz"), "w", encoding="utf-8") as f:
218- f.write(code)
219- parts.append('<div class="file"><span>%s.raz</span></div>'
220- '<pre class="code"><code>%s</code></pre>'
221- % (name, highlight(code.rstrip("\n"))))
222- if "run" in flags or "fail" in flags:
223- stdout, stderr, status = run(tmp, name)
224- if ("fail" in flags) == (status == 0):
225- sys.exit("%s: %s ended with status %d\n%s%s" % (
226- lesson["slug"], name, status, stdout, stderr))
227- parts.append(output_html(stdout, stderr))
228- finally:
229- shutil.rmtree(tmp)
230- return "\n".join(parts)
231-
232-# ---- pages ---------------------------------------------------------------
233-
234-def page(title, body, depth=0, current=""):
235- up = "../" * depth
236- nav = "".join('<a href="%s%s"%s>%s</a>' % (
237- up, href, ' aria-current="page"' if key == current else "", label)
238- for key, href, label in [
239- ("tour", "tour/index.html", "Raz, Set, Go"),
240- ("advanced", "advanced/index.html", "More Raz"),
241- ("spec", "spec.html", "Report"),
242- ("source", "source/index.html", "Source"),
243- ("get", "index.html#download", "Download")])
244- return """<!doctype html>
245-<html lang="en">
246-<head>
247-<meta charset="utf-8">
248-<meta name="viewport" content="width=device-width, initial-scale=1">
249-<title>%s</title>
250-<meta name="description" content="raz: a small systems language in Wirth's tradition, for x86-64 Linux.">
251-<meta name="theme-color" content="#E07A5F">
252-<meta property="og:title" content="%s">
253-<meta property="og:description" content="A small systems language for x86-64 Linux. No run time, no GC, one report.">
254-<meta property="og:image" content="%s/social.png">
255-<meta name="twitter:card" content="summary_large_image">
256-<link rel="icon" href="%sfavicon.svg" type="image/svg+xml">
257-<link rel="icon" href="%sfavicon-32.png" type="image/png" sizes="32x32">
258-<link rel="apple-touch-icon" href="%sapple-touch-icon.png">
259-<link rel="stylesheet" href="%sstyle.css">
260-</head>
261-<body>
262-<header><nav><a class="mark" href="%sindex.html"><img src="%slogo.svg" width="26" height="26" alt="">raz</a>%s</nav></header>
263-<main>
264-%s
265-</main>
266-<footer>raz is under the ISC license. <a href="%ssource/index.html">Source</a></footer>
267-</body>
268-</html>
269-""" % (html.escape(title), html.escape(title), SITE, up, up, up, up, up, up, nav, body, up)
270-
271-def write(path, text):
272- path = os.path.join(OUT, path)
273- os.makedirs(os.path.dirname(path), exist_ok=True)
274- with open(path, "w", encoding="utf-8") as f:
275- f.write(text)
276-
277-def build_tour(tour, lessons, next_page):
278- """One tour's pages: a contents page and a page to each lesson.
279- next_page is (href, label) for what follows its last lesson."""
280- folder, outdir, name, intro_file = tour
281- parts = []
282- for l in lessons:
283- if l["part"] not in parts:
284- parts.append(l["part"])
285- first = lambda p: 1 + next(i for i, x in enumerate(lessons) if x["part"] == p)
286- for n, l in enumerate(lessons):
287- toc = []
288- for p in parts:
289- toc.append("<h3>%s</h3><ol start='%d'>" % (p, first(p)))
290- for i, x in enumerate(lessons):
291- if x["part"] == p:
292- cur = ' aria-current="page"' if i == n else ""
293- toc.append('<li><a href="%s.html"%s>%s</a></li>' % (
294- x["slug"], cur, html.escape(x["title"])))
295- toc.append("</ol>")
296- pager = '<a href="index.html">Contents</a>'
297- if n > 0:
298- pager = '<a href="%s.html">&larr; %s</a>' % (
299- lessons[n - 1]["slug"], html.escape(lessons[n - 1]["title"])) + pager
300- if n + 1 < len(lessons):
301- pager += '<a class="next" href="%s.html">%s &rarr;</a>' % (
302- lessons[n + 1]["slug"], html.escape(lessons[n + 1]["title"]))
303- else:
304- pager += '<a class="next" href="%s">%s &rarr;</a>' % next_page
305- body = ('<div class="tour"><aside><h2>%s</h2>%s</aside><article>'
306- '<p class="kicker">%s &middot; lesson %d of %d</p><h1>%s</h1>\n%s'
307- '<p class="tryit">Save a program under its module&rsquo;s name and run '
308- 'it with <code>raz run Name.raz</code>.</p>'
309- '<div class="pager">%s</div></article></div>') % (
310- name, "\n".join(toc), l["part"], n + 1, len(lessons),
311- html.escape(l["title"]), lesson_body(l), pager)
312- write("%s/%s.html" % (outdir, l["slug"]), page(
313- "%s - %s" % (l["title"], name), body, 1, folder))
314- cards = []
315- for p in parts:
316- cards.append("<h2>%s</h2><ol start='%d'>" % (p, first(p)))
317- for x in lessons:
318- if x["part"] == p:
319- cards.append('<li><a href="%s.html">%s</a> <span>%s</span></li>' % (
320- x["slug"], html.escape(x["title"]), html.escape(x["summary"])))
321- cards.append("</ol>")
322- intro = open(os.path.join(HERE, "content", intro_file), encoding="utf-8").read()
323- write("%s/index.html" % outdir, page(name,
324- '<div class="contents">%s%s</div>' % (intro, "\n".join(cards)), 1, folder))
325-
326-def build_spec():
327- if not shutil.which("pandoc"):
328- sys.exit("pandoc makes the report's page: apt-get install pandoc")
329- p = subprocess.run(
330- ["pandoc", os.path.join(ROOT, "doc", "raz.md"),
331- os.path.join(ROOT, "doc", "raz-lib.md"), "-s", "--template",
332- os.path.join(HERE, "content", "spec.tmpl"), "--toc", "--toc-depth=1",
333- "--shift-heading-level-by=-1", "--no-highlight", "-t", "html",
334- # wide enough that no row of a table is "long": pandoc would
335- # otherwise give each column an equal share of the width
336- "--columns=10000"],
337- capture_output=True, text=True, check=True)
338- body = '<div class="spec">%s</div>' % p.stdout
339- write("spec.html", page("The raz report", body, 0, "spec"))
340-
341-def build_download(untagged):
342- """Every release's tarball from v0.7.1 on, in public/download/
343- with its SHA-256, and /download/latest leading to the newest; a list
344- of (version, file name, SHA-256), oldest first. A program's CI can
345- fetch the version it was written for by its name, so none is ever
346- taken away. Each is made of its tag by make dist, not of the tree
347- at hand. One already in public/download/ is kept as it is, never
348- made again: those before 0.14.0 were made before make dist made the
349- same tarball each time, so a new one would differ, and so its
350- SHA-256, which a program's CI may check."""
351- releases = []
352- for tag, rev in refs(ROOT, untagged):
353- name = "raz-%s-linux-x86_64.tar.gz" % tag[1:]
354- made = os.path.join(OUT, "download", name)
355- if not os.path.exists(made):
356- subprocess.run(["make", "-s", "-C", ROOT, "dist", "REV=" + rev, "VERSION=" + tag[1:]],
357- stdout=subprocess.DEVNULL, check=True)
358- shutil.copy(os.path.join(ROOT, "build", name), made)
359- digest = hashlib.sha256(open(made, "rb").read()).hexdigest()
360- checksum = made + ".sha256"
361- if os.path.exists(checksum):
362- expected = open(checksum, encoding="utf-8").read().split()
363- if not expected or expected[0] != digest:
364- sys.exit("release archive does not match its published checksum: " + made)
365- write("download/%s.sha256" % name, "%s %s\n" % (digest, name))
366- releases.append((tag[1:], name, digest))
367- # Cloudflare reads _redirects from the root of what it serves
368- write("_redirects", "/download/latest /download/%s 302\n" % releases[-1][1])
369- return releases
370-
371-def build_home(releases):
372- snippet = open(os.path.join(HERE, "content", "home.raz"), encoding="utf-8").read()
373- tmp = tempfile.mkdtemp()
374- try:
375- with open(os.path.join(tmp, "Taste.raz"), "w", encoding="utf-8") as f:
376- f.write(snippet)
377- stdout, stderr, status = run(tmp, "Taste")
378- if status != 0:
379- sys.exit("Taste failed:\n" + stderr)
380- finally:
381- shutil.rmtree(tmp)
382- text = open(os.path.join(HERE, "content", "home.html"), encoding="utf-8").read()
383- text = text.replace("@SNIPPET@", highlight(snippet.rstrip("\n")))
384- text = text.replace("@OUTPUT@", html.escape(stdout.rstrip("\n")))
385- version, name, digest = releases[-1]
386- pages = re.search(r"Pages:\s+(\d+)", subprocess.run(
387- ["pdfinfo", os.path.join(ROOT, "build", "raz.pdf")],
388- capture_output=True, text=True, check=True).stdout).group(1)
389- earlier = ", ".join('<a href="download/%s">%s</a>' % (n, v)
390- for v, n, _ in reversed(releases[:-1]))
391- text = text.replace("@EARLIER@", earlier).replace("@PAGES@", pages)
392- text = text.replace("@VERSION@", version).replace("@TARBALL@", name)
393- text = text.replace("@DIR@", name[:-len(".tar.gz")]).replace("@SHA256@", digest)
394- write("index.html", page("raz: a small systems language", text, 0, "home"))
395-
396-def main():
397- if not os.path.exists(RAZ):
398- sys.exit("make raz first")
399- untagged = [a.split("=", 1) for a in sys.argv[1:]]
400- if not all(len(u) == 2 and re.fullmatch(r"v\d+\.\d+\.\d+", u[0]) for u in untagged):
401- sys.exit("usage: build.py [vX.Y.Z=COMMIT ...]")
402- refs(ROOT, untagged) # validate the release records before removing old pages
403- # everything is made again but the tarballs (see build_download)
404- for f in os.listdir(OUT) if os.path.exists(OUT) else []:
405- path = os.path.join(OUT, f)
406- if f == "download":
407- continue
408- elif os.path.isdir(path):
409- shutil.rmtree(path)
410- else:
411- os.remove(path)
412- os.makedirs(os.path.join(OUT, "download"), exist_ok=True)
413- shutil.copy(os.path.join(HERE, "style.css"), OUT)
414- for f in os.listdir(os.path.join(HERE, "assets")): # the logo and icons
415- if f not in ("social.html", "render.sh"):
416- shutil.copy(os.path.join(HERE, "assets", f), OUT)
417- names = sorted(f for f in os.listdir(os.path.join(HERE, "content"))
418- if re.match(r"\d+-.*\.txt$", f))
419- counts = []
420- for i, tour in enumerate(TOURS):
421- folder = os.path.join(HERE, "content", tour[0])
422- lessons = [read_lesson(os.path.join(folder, f))
423- for f in sorted(os.listdir(folder)) if re.match(r"\d+-.*\.txt$", f)]
424- if i + 1 < len(TOURS):
425- nxt = ("../%s/index.html" % TOURS[i + 1][1], TOURS[i + 1][2])
426- else:
427- nxt = ("../spec.html", "The report")
428- build_tour(tour, lessons, nxt)
429- counts.append(len(lessons))
430- build_spec()
431- for pdf in ("raz.pdf", "raz-lib.pdf"): # made by make pdf
432- shutil.copy(os.path.join(ROOT, "build", pdf), OUT)
433- build_home(build_download(untagged))
434- print("site/public: %s lessons" % " + ".join(map(str, counts)))
435-
436-main()

site/check.py deleted +0 -108

@@ -1,108 +0,0 @@
1-#!/usr/bin/env python3
2-"""Check release selection with real git histories: python3 site/check.py.
3-
4-Uses Python's standard library and git. All repositories and downloads
5-are temporary; no release, working checkout or published file is changed.
6-"""
7-
8-from pathlib import Path
9-import subprocess
10-import tempfile
11-import unittest
12-
13-from releases import refs
14-import source
15-
16-
17-class Releases(unittest.TestCase):
18- def setUp(self):
19- self.temporary = tempfile.TemporaryDirectory()
20- self.addCleanup(self.temporary.cleanup)
21- self.directory = Path(self.temporary.name)
22- self.repo = self.directory / "repo"
23- self.repo.mkdir()
24- self.git("init", "--quiet", "--initial-branch=main")
25- (self.repo / "site").mkdir()
26- self.manifest = self.repo / "site/releases"
27- self.manifest.write_text("# distributions\n")
28- self.commits = []
29- for number, version in enumerate(("v0.7.1", "v0.9.0", "v0.10.0")):
30- (self.repo / "file").write_text(str(number))
31- self.git("add", ".")
32- self.git("commit", "--quiet", "-m", version)
33- self.commits.append(self.git("rev-parse", "HEAD"))
34- self.git("tag", version)
35- self.manifest.write_text(f"# not tagged yet\nv0.20.0 {self.commits[-1]}\n")
36- self.git("add", "site/releases")
37- self.git("commit", "--quiet", "-m", "record distribution")
38-
39- def git(self, *args, repo=None):
40- return subprocess.check_output([
41- "git", "-C", str(repo or self.repo), "-c", "user.name=Test",
42- "-c", "user.email=test@example.org", "-c", "commit.gpgSign=false", *args,
43- ], text=True).strip()
44-
45- def test_numeric_tags_and_manifest(self):
46- self.assertEqual(refs(self.repo), list(zip(
47- ("v0.7.1", "v0.9.0", "v0.10.0", "v0.20.0"),
48- self.commits + [self.commits[-1]],
49- )))
50-
51- def test_manifest_cannot_move_a_tag(self):
52- self.manifest.write_text(f"v0.9.0 {self.commits[0]}\n")
53- with self.assertRaisesRegex(ValueError, "disagree"):
54- refs(self.repo)
55-
56- def test_manifest_cannot_publish_another_line(self):
57- self.git("checkout", "--quiet", "-b", "side", self.commits[0])
58- (self.repo / "side").write_text("a development branch\n")
59- self.git("add", "side")
60- self.git("commit", "--quiet", "-m", "side")
61- side = self.git("rev-parse", "HEAD")
62- self.git("checkout", "--quiet", "main")
63- self.manifest.write_text(f"v0.20.0 {side}\n")
64- with self.assertRaisesRegex(ValueError, "first-parent"):
65- refs(self.repo)
66- # A new tag must not override the recorded distribution, even
67- # when that tag would otherwise be skipped as off the main line.
68- self.manifest.write_text(f"v0.20.0 {self.commits[-1]}\n")
69- self.git("tag", "v0.20.0", side)
70- with self.assertRaisesRegex(ValueError, "disagree"):
71- refs(self.repo)
72-
73- def test_shallow_deploy_recovers_history_and_tags(self):
74- # A file URL uses git's transport, so --depth really is shallow.
75- clone = self.directory / "deploy"
76- self.git("clone", "--quiet", "--depth=1", "--branch=main", self.repo.as_uri(), str(clone))
77- self.assertEqual(self.git("rev-parse", "--is-shallow-repository", repo=clone), "true")
78- self.assertEqual(refs(clone), refs(self.repo))
79- self.assertEqual(self.git("rev-parse", "--is-shallow-repository", repo=clone), "false")
80-
81- def test_detached_shallow_deploy_needs_no_local_main(self):
82- clone = self.directory / "deploy"
83- self.git("clone", "--quiet", "--depth=1", "--branch=main", self.repo.as_uri(), str(clone))
84- self.git("checkout", "--quiet", "--detach", repo=clone)
85- self.git("branch", "-D", "main", repo=clone)
86- self.assertEqual(refs(clone), refs(self.repo))
87- original = source.ROOT
88- self.addCleanup(setattr, source, "ROOT", original)
89- source.ROOT = clone
90- store = source.prepare_store(self.directory)
91- self.assertEqual(self.git("rev-parse", "HEAD", repo=store), self.git("rev-parse", "HEAD", repo=clone))
92- self.assertEqual(self.git("symbolic-ref", "HEAD", repo=store), "refs/heads/main")
93- self.git("fsck", "--strict", repo=store)
94- self.assertEqual(self.git("rev-parse", "--abbrev-ref", "HEAD", repo=clone), "HEAD")
95-
96- def test_modified_builder_is_rejected_before_unpacking(self):
97- packed = self.directory / "ladle.gz"
98- packed.write_bytes(b"not the published executable")
99- packed.with_name("ladle.gz.sha256").write_text("0" * 64 + " ladle.gz\n")
100- original = source.LADLE
101- self.addCleanup(setattr, source, "LADLE", original)
102- source.LADLE = packed
103- with self.assertRaisesRegex(ValueError, "recorded SHA-256"):
104- source.pinned_ladle()
105-
106-
107-if __name__ == "__main__":
108- unittest.main()

site/releases.py deleted +0 -80

@@ -1,80 +0,0 @@
1-"""Release commits shared by the home page and ladle's download pages.
2-
3-Tags supply released versions. site/releases records existing website
4-distributions whose tags have not been pushed. Both must name commits
5-on main's first-parent line, and a later tag must agree with the record.
6-No tags or archives are created here.
7-"""
8-from pathlib import Path
9-import re
10-import subprocess
11-
12-
13-def main_ref(root):
14- """Use main locally, or the detached commit supplied to a deployment.
15-
16- A build never silently publishes a different local working branch.
17- The publishing service selects main before checking out its commit.
18- """
19- command = ['git', '-C', str(root)]
20- if subprocess.run(command + ['show-ref', '--verify', '--quiet', 'refs/heads/main']).returncode == 0:
21- return 'refs/heads/main'
22- if subprocess.run(command + ['symbolic-ref', '--quiet', 'HEAD'], stdout=subprocess.DEVNULL).returncode:
23- return 'HEAD'
24- raise ValueError('site build needs main or a detached deployment checkout')
25-
26-
27-def refs(root, extra=()):
28- """Return (version tag, full commit) pairs, oldest first.
29-
30- extra holds the optional vX.Y.Z=COMMIT arguments to make site,
31- already split into pairs. Conflicting records are errors, so a
32- build cannot quietly move an existing version to another commit.
33- """
34- root = Path(root)
35-
36- def git(*args):
37- return subprocess.check_output(['git', '-C', str(root), *args], text=True).strip()
38-
39- # Deployment services may give the build only one commit. The source
40- # browser needs the history, and the same origin supplies its tags.
41- if git('rev-parse', '--is-shallow-repository') == 'true':
42- print('site: fetching full history and tags from origin')
43- subprocess.run(['git', '-C', str(root), 'fetch', '--unshallow', '--tags', 'origin'], check=True)
44- line = set(git('rev-list', '--first-parent', main_ref(root)).splitlines())
45- selected = {}
46- tagged = {}
47-
48- def add(tag, rev):
49- if not re.fullmatch(r'v\d+\.\d+\.\d+', tag):
50- raise ValueError('release version must be vX.Y.Z: ' + tag)
51- if tuple(map(int, tag[1:].split('.'))) < (0, 7, 1):
52- return
53- commit = git('rev-parse', '--verify', '--end-of-options', rev + '^{commit}')
54- if commit not in line:
55- raise ValueError(f'release {tag}: {commit} is not on main\'s first-parent line')
56- if tag in tagged and tagged[tag] != commit:
57- raise ValueError(f'release {tag}: tag and recorded commits disagree')
58- if tag in selected and selected[tag] != commit:
59- raise ValueError(f'release {tag}: tag and recorded commits disagree')
60- selected[tag] = commit
61-
62- for tag in git('tag', '-l', 'v*').splitlines():
63- if re.fullmatch(r'v\d+\.\d+\.\d+', tag):
64- # Tags on another development line are not this site's releases.
65- commit = git('rev-parse', '--verify', tag + '^{commit}')
66- tagged[tag] = commit
67- if commit in line:
68- add(tag, commit)
69- manifest = root / 'site' / 'releases'
70- for number, text in enumerate(manifest.read_text().splitlines(), 1):
71- text = text.partition('#')[0].strip()
72- if not text:
73- continue
74- words = text.split()
75- if len(words) != 2 or not re.fullmatch(r'[0-9a-f]{40}', words[1]):
76- raise ValueError(f'{manifest}:{number}: expected vX.Y.Z and full commit hash')
77- add(*words)
78- for tag, rev in extra:
79- add(tag, rev)
80- return sorted(selected.items(), key=lambda item: tuple(map(int, item[0][1:].split('.'))))

site/source.py deleted +0 -238

@@ -1,238 +0,0 @@
1-#!/usr/bin/env python3
2-"""Build the static source browser and releases after site/build.py.
3-
4-Uses git, ladle and Python's standard library. Reads committed main and
5-the existing, checksummed compiler distributions; writes only the website.
6-It does not build compilers, create tags, upload files or deploy the site.
7-The layout and publishing rules are in site/README.md.
8-"""
9-
10-import argparse
11-import gzip
12-import hashlib
13-from pathlib import Path
14-import re
15-import shutil
16-import subprocess
17-import tempfile
18-from urllib.parse import urlsplit
19-
20-from releases import main_ref, refs
21-
22-
23-ROOT = Path(__file__).resolve().parent.parent
24-PUBLIC = ROOT / "site/public"
25-URL = "https://raz.lucelad.workers.dev/source/"
26-LADLE = ROOT / "site/tools/ladle.gz"
27-BEGIN_HEADERS = "# BEGIN ladle source\n"
28-END_HEADERS = "# END ladle source\n"
29-MAX_FILES = 20000
30-MAX_FILE_BYTES = 25 * 1024 * 1024
31-
32-
33-def git(repo, *args):
34- """Read git's text output, failing at the command that went wrong."""
35- return subprocess.check_output(
36- ["git", "-C", str(repo), *args], text=True
37- ).strip()
38-
39-
40-def prepare_store(directory):
41- """Clone main independently, keeping only tags whose commits it reaches."""
42- store = directory / "raz.git"
43- branch = ["--branch", "main"] if main_ref(ROOT) != "HEAD" else []
44- subprocess.run([
45- "git", "clone", "--quiet", "--bare", "--single-branch",
46- "--no-local", *branch, str(ROOT), str(store),
47- ], check=True)
48- # Deployment checkouts can be detached and have no local branch.
49- # Name their commit only inside this temporary published store.
50- if not branch:
51- git(store, "update-ref", "refs/heads/main", git(store, "rev-parse", "HEAD"))
52- git(store, "symbolic-ref", "HEAD", "refs/heads/main")
53- reachable = set(git(store, "rev-list", "main").splitlines())
54- for tag in git(store, "tag", "--list").splitlines():
55- # Tags of trees or blobs are not cloneable releases. Ask quietly:
56- # such a tag is valid git, simply outside the published history.
57- result = subprocess.run(
58- ["git", "-C", str(store), "rev-parse", "--verify", f"refs/tags/{tag}^{{commit}}"],
59- capture_output=True, text=True,
60- )
61- if result.returncode or result.stdout.strip() not in reachable:
62- git(store, "update-ref", "-d", f"refs/tags/{tag}")
63- git(store, "repack", "-a", "-d", "--max-pack-size=20m")
64- git(store, "update-server-info")
65- return store
66-
67-
68-def digest(path):
69- checksum = hashlib.sha256()
70- with path.open("rb") as stream:
71- for chunk in iter(lambda: stream.read(1024 * 1024), b""):
72- checksum.update(chunk)
73- return checksum.hexdigest()
74-
75-
76-def published_sum(path):
77- """Read the original checksum; never replace it to fit different bytes."""
78- checksum = path.with_name(path.name + ".sha256")
79- words = checksum.read_text().split()
80- if len(words) != 2 or not re.fullmatch(r"[0-9a-f]{64}", words[0]) or words[1] != path.name:
81- raise ValueError(f"{checksum}: expected SHA-256 and {path.name}")
82- return words[0]
83-
84-
85-def pinned_ladle():
86- """Unpack the checked-in static builder, needing no compiler or network."""
87- packed = LADLE.read_bytes()
88- if hashlib.sha256(packed).hexdigest() != published_sum(LADLE):
89- raise ValueError(f"{LADLE}: differs from its recorded SHA-256")
90- executable = ROOT / "build/site/ladle"
91- executable.parent.mkdir(parents=True, exist_ok=True)
92- # Rename a new inode into place: another build may still be running
93- # the previous executable, which cannot be overwritten on Linux.
94- with tempfile.NamedTemporaryFile(dir=executable.parent, delete=False) as output:
95- temporary = Path(output.name)
96- output.write(gzip.decompress(packed))
97- temporary.chmod(0o755)
98- temporary.replace(executable)
99- return executable
100-
101-
102-def compiler_archive(version, directory):
103- """Copy the distribution, checking its existing published checksum."""
104- name = f"raz-{version[1:]}-linux-x86_64.tar.gz"
105- original = PUBLIC / "download" / name
106- expected = published_sum(original)
107- copied = directory / name
108- shutil.copyfile(original, copied)
109- if digest(copied) != expected:
110- raise ValueError(f"{original}: differs from its published SHA-256")
111-
112-
113-def source_archive(store, version, commit, directory):
114- """Archive the exact commit, with no wall-clock time or filename in gzip."""
115- name = f"raz-{version[1:]}-source.tar.gz"
116- with (directory / name).open("wb") as output:
117- with gzip.GzipFile(filename="", mode="wb", fileobj=output, mtime=0) as compressed:
118- with subprocess.Popen([
119- "git", "-C", str(store), "archive", "--format=tar",
120- f"--prefix=raz-{version[1:]}/", commit,
121- ], stdout=subprocess.PIPE) as process:
122- shutil.copyfileobj(process.stdout, compressed)
123- if process.wait():
124- raise ValueError(f"release {version}: git archive failed")
125-
126-
127-def stage_releases(store, directory, selected):
128- line = set(git(store, "rev-list", "--first-parent", "main").splitlines())
129- for version, commit in selected:
130- # Ref resolution is shared with build.py. Check against our snapshot
131- # too, so a commit made during the build cannot split their histories.
132- if commit not in line:
133- raise ValueError(f"release {version}: {commit} is not in the cloned main history")
134- release = directory / version
135- release.mkdir(parents=True)
136- (release / "commit").write_text(commit + "\n")
137- notes = ROOT / "site/release-notes" / (version + ".md")
138- if notes.exists():
139- shutil.copyfile(notes, release / "notes.md")
140- compiler_archive(version, release)
141- source_archive(store, version, commit, release)
142-
143-
144-def export_store(store, output):
145- """Export only the dumb-HTTP store, never configuration or local paths."""
146- for name in ("HEAD", "info/refs", "objects/info/packs"):
147- destination = output / name
148- destination.parent.mkdir(parents=True, exist_ok=True)
149- shutil.copyfile(store / name, destination)
150- shutil.copytree(store / "objects/pack", output / "objects/pack")
151-
152-
153-def merged_headers(generated):
154- """Replace our scoped block while keeping the host's other header rules."""
155- path = PUBLIC / "_headers"
156- existing = path.read_text() if path.exists() else ""
157- if BEGIN_HEADERS in existing:
158- before, _, rest = existing.partition(BEGIN_HEADERS)
159- _, found, after = rest.partition(END_HEADERS)
160- if not found:
161- raise ValueError(f"{path}: source header block has no closing marker")
162- existing = before + after
163- scoped = "\n".join(
164- "/source" + line if line.startswith("/") else line
165- for line in generated.splitlines()
166- ) + "\n"
167- return existing.rstrip() + "\n\n" + BEGIN_HEADERS + scoped + END_HEADERS
168-
169-
170-def check_limits(source, headers):
171- """Measure the proposed complete output, counting the new source tree once."""
172- paths = [path for path in PUBLIC.rglob("*")
173- if path.is_file() and "source" != path.relative_to(PUBLIC).parts[0]
174- and path != PUBLIC / "_headers"]
175- paths.extend(path for path in source.rglob("*") if path.is_file())
176- sizes = [(str(path), path.stat().st_size) for path in paths]
177- sizes.append((str(PUBLIC / "_headers"), len(headers.encode())))
178- for name, size in sizes:
179- if size > MAX_FILE_BYTES:
180- raise ValueError(f"{name}: {size} bytes exceeds the 25 MiB file limit")
181- if len(sizes) > MAX_FILES:
182- raise ValueError(f"site: {len(sizes)} files exceeds the {MAX_FILES} file limit")
183- print(f"site/public: {len(sizes)} files, {sum(size for _, size in sizes)} bytes; "
184- f"largest file {max(size for _, size in sizes)} bytes")
185-
186-
187-def build(ladle=None, url=URL, extra=()):
188- address = urlsplit(url)
189- if address.scheme not in ("http", "https") or not address.netloc or address.path != "/source/" or address.query or address.fragment:
190- raise ValueError("--url must be an HTTP(S) address ending in /source/")
191- if not PUBLIC.is_dir():
192- raise ValueError("site/public is missing; run site/build.py first")
193- selected = refs(ROOT, extra) # complete a shallow deployment checkout before cloning
194- if ladle is None:
195- ladle = pinned_ladle()
196- # Build separately: a failed checksum, ladle run or host-limit check
197- # leaves the previous source browser in place. Nothing reads that output.
198- with tempfile.TemporaryDirectory(prefix="raz-source-") as temporary:
199- directory = Path(temporary)
200- store = prepare_store(directory)
201- releases = directory / "releases"
202- stage_releases(store, releases, selected)
203- output = directory / "source"
204- output.mkdir()
205- export_store(store, output)
206- subprocess.run([
207- str(ladle), "-u", url, "-r", str(releases),
208- "-t", str(ROOT / "site/source.theme"), "-o", str(output), str(store),
209- ], check=True)
210- headers = merged_headers((output / "_headers").read_text())
211- check_limits(output, headers)
212- destination = PUBLIC / "source"
213- if destination.exists():
214- shutil.rmtree(destination)
215- shutil.move(str(output), destination)
216- (PUBLIC / "_headers").write_text(headers)
217-
218-
219-def main():
220- parser = argparse.ArgumentParser(description=__doc__)
221- parser.add_argument("--ladle", type=Path, help="override the checked-in static ladle executable")
222- parser.add_argument("--url", default=URL, help="the site's absolute /source/ address")
223- parser.add_argument("releases", nargs="*", metavar="vX.Y.Z=COMMIT", help="additional existing distributions")
224- args = parser.parse_args()
225- try:
226- extra = []
227- for release in args.releases:
228- version, separator, commit = release.partition("=")
229- if not separator or not commit:
230- raise ValueError(f"{release}: expected vX.Y.Z=COMMIT")
231- extra.append((version, commit))
232- build(args.ladle.resolve() if args.ladle else None, args.url, extra)
233- except (OSError, ValueError, subprocess.CalledProcessError) as error:
234- parser.exit(1, f"source: {error}\n")
235-
236-
237-if __name__ == "__main__":
238- main()

site/tools/README.md (history) modified +1 -1

@@ -4,7 +4,7 @@
44 `ldiaz94/ladle` at `509b9d314f6161a7430b8dc1354ba4ebe203ddb8`.
55 Its pinned dependencies are sauce `35e0c186db6b8861745c25925ca5b2489219e48d`
66 and rflate `c55b37888b071e98f57dcf18b97ab31f85595e76`.
7-`ladle.gz.sha256` checks the compressed file; `source.py` verifies it
7+`ladle.gz.sha256` checks the compressed file; `Source.raz` verifies it
88 before unpacking the executable into `build/site/`.
99
1010 Keeping this small build tool with the site lets Cloudflare run the