raz / site / Site.raz

335 lines · 10.7 KiB · raw · history · last change fe3051dc

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. *)
7module Site;
8import Sys, Files, Buf, Str, Heap, Fmt, Out, Rt;
9import Names := Vec([]const U8);
10import ByName := Sort([]const U8, nameLess);
11
12const Letters = "abcdefghijklmnopqrstuvwxyz0123456789_"; (* the letters of a temporary directory's name *)
13
14(* Whether the name a sorts before b: by bytes. *)
15proc nameLess(a, b: []const U8): BOOL;
16begin
17 return Str.cmp(a, b) < 0;
18end;
19
20(* ---- stopping ---------------------------------------------------- *)
21
22(* Stops with status 1 and the message f makes of args on standard
23 error. *)
24proc die*(f: []const U8; args: []const Fmt.Arg);
25var b: Buf.Buf;
26begin
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);
32end;
33
34(* ---- text -------------------------------------------------------- *)
35
36(* The parts joined into one string, in memory that is never freed. *)
37proc cat*(parts: [][]const U8): []const U8;
38var b: Buf.Buf; i: INT;
39begin
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);
43end;
44
45(* The lines of s, split at each line feed: a final line feed ends an
46 empty last line. *)
47proc lines*(s: []const U8): [][]const U8;
48var v: Names.Vec; at, i: INT;
49begin
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);
57end;
58
59(* The words of s, split at white space, with no empty one. *)
60proc words*(s: []const U8): [][]const U8;
61var v: Names.Vec; rest, w: []const U8;
62begin
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);
70end;
71
72(* ---- files ------------------------------------------------------- *)
73
74(* Whether path names something. *)
75proc exists*(path: []const U8): BOOL;
76var err: INT;
77begin
78 _, err := Sys.info(path);
79 return err = 0;
80end;
81
82(* Whether path names a directory. *)
83proc isDir*(path: []const U8): BOOL;
84var f: Sys.Info; err: INT;
85begin
86 f, err := Sys.info(path);
87 return (err = 0) and f.dir;
88end;
89
90(* The whole file at path, or the program stops. *)
91proc read*(path: []const U8): []const U8;
92var b: Buf.Buf; err: INT;
93begin
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);
98end;
99
100(* Makes the directory dir and those it is in, as mkdir -p does. *)
101proc makeDirs*(dir: []const U8);
102var i, err: INT;
103begin
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;
111end;
112
113(* Writes data to the file at path, in a directory made if need be. *)
114proc write*(path, data: []const U8);
115var slash: INT;
116begin
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;
120end;
121
122(* Copies the file source to the path target. *)
123proc copy*(source, target: []const U8);
124begin
125 write(target, read(source));
126end;
127
128(* The names in the directory dir, in byte order; the program stops if
129 it can't be read. *)
130proc dirNames*(dir: []const U8): [][]const U8;
131var d: Sys.Dir; v: Names.Vec; name: []const U8; ok: BOOL; err: INT;
132begin
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);
144end;
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. *)
151proc tempDirIn*(base: []const U8): []const U8;
152var path: []const U8; r: [8]U8; name: [11]U8; i: INT;
153begin
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;
161end;
162
163(* A new directory in $TMPDIR, or /tmp, as tempDirIn makes one. *)
164proc tempDir*: []const U8;
165var base: []const U8;
166begin
167 base := Sys.env("TMPDIR");
168 if LEN(base) = 0 then base := "/tmp"; end;
169 return tempDirIn(base);
170end;
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. *)
179proc start*(args: [][]const U8; dir: []const U8; env: [][]const U8; out, err: INT): INT;
180var p: Sys.Program;
181begin
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);
187end;
188
189(* Waits for the program pid: its exit status, or 128 and the signal's
190 number if a signal killed it. *)
191proc finish*(pid: INT): INT;
192var status: Sys.Status; value: INT;
193begin
194 _, status, value := Sys.waitExit(pid);
195 if status = Sys.killed then return 128 + value; end;
196 return value;
197end;
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. *)
202proc run*(args: [][]const U8; out: INT): INT;
203var pid: INT;
204begin
205 pid := start(args, "", [], out, 0);
206 if pid < 0 then return pid; end;
207 return finish(pid);
208end;
209
210(* Runs args with its output thrown away: its exit status, or minus an
211 errno if it can't start. *)
212proc runQuiet*(args: [][]const U8): INT;
213var null, status: INT;
214begin
215 null := Sys.open("/dev/null", {Sys.writing});
216 status := run(args, null);
217 Sys.close(null);
218 return status;
219end;
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. *)
224proc pipeline*(first, second: [][]const U8; out: INT): (INT, INT);
225var read, write, pid1, pid2: INT; p: Sys.Program;
226begin
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;
239end;
240
241(* Runs args and stops the program if it fails. *)
242proc must*(args: [][]const U8);
243begin
244 if run(args, 0) # 0 then die("{} failed", [Fmt.str(args[0])]); end;
245end;
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. *)
249proc drain(outFd, errFd: INT; var out, err: Buf.Buf);
250var pair: [2]Sys.Poll; fds: []Sys.Poll; i, n: INT;
251begin
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;
271end;
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. *)
276proc capture*(args: [][]const U8; dir: []const U8; env: [][]const U8; merge: BOOL; var out, err: Buf.Buf): INT;
277var outRead, outWrite, errRead, errWrite, pid: INT;
278begin
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);
293end;
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. *)
298proc captureOut*(args: [][]const U8; dir: []const U8; env: [][]const U8; var out: Buf.Buf): INT;
299var r, w, pid, n: INT;
300begin
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);
311end;
312
313(* The arguments of a git command in the repository at dir. *)
314proc gitArgs*(dir: []const U8; args: [][]const U8): [][]const U8;
315var v: Names.Vec; i: INT;
316begin
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);
321end;
322
323(* What the git command args writes to standard output, with white
324 space cut from its ends, or the program stops. *)
325proc git*(dir: []const U8; args: [][]const U8): []const U8;
326var out: Buf.Buf;
327begin
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));
333end;
334
335end Site.