(* Site: what the website's builders (Build, Source, Verify) share: stopping with a message, reading and writing files and directories, and running the programs they call (git, pandoc, make, ladle, ...), with their output kept or left on the terminal. It needs only the library. It leaves out a shell: a program is run from its argument list, as the builders ask. *) module Site; import Sys, Files, Buf, Str, Heap, Fmt, Out, Rt; import Names := Vec([]const U8); import ByName := Sort([]const U8, nameLess); const Letters = "abcdefghijklmnopqrstuvwxyz0123456789_"; (* the letters of a temporary directory's name *) (* Whether the name a sorts before b: by bytes. *) proc nameLess(a, b: []const U8): BOOL; begin return Str.cmp(a, b) < 0; end; (* ---- stopping ---------------------------------------------------- *) (* Stops with status 1 and the message f makes of args on standard error. *) proc die*(f: []const U8; args: []const Fmt.Arg); var b: Buf.Buf; begin Buf.init(b, Heap.heap); Fmt.write(b, f, args); Buf.add(b, '\n'); Fmt.eprint("{}", [Fmt.str(Buf.bytes(b))]); Rt.exit(1); end; (* ---- text -------------------------------------------------------- *) (* The parts joined into one string, in memory that is never freed. *) proc cat*(parts: [][]const U8): []const U8; var b: Buf.Buf; i: INT; begin Buf.init(b, Heap.heap); for i := 0 to LEN(parts) - 1 do Buf.str(b, parts[i]); end; return Buf.bytes(b); end; (* The lines of s, split at each line feed: a final line feed ends an empty last line. *) proc lines*(s: []const U8): [][]const U8; var v: Names.Vec; at, i: INT; begin Names.init(v, Heap.heap); at := 0; for i := 0 to LEN(s) - 1 do if s[i] = '\n' then Names.push(v, s[at..i]); at := i + 1; end; end; Names.push(v, s[at..LEN(s)]); return Names.all(v); end; (* The words of s, split at white space, with no empty one. *) proc words*(s: []const U8): [][]const U8; var v: Names.Vec; rest, w: []const U8; begin Names.init(v, Heap.heap); w, rest := Str.field(s); while LEN(w) > 0 do Names.push(v, w); w, rest := Str.field(rest); end; return Names.all(v); end; (* ---- files ------------------------------------------------------- *) (* Whether path names something. *) proc exists*(path: []const U8): BOOL; var err: INT; begin _, err := Sys.info(path); return err = 0; end; (* Whether path names a directory. *) proc isDir*(path: []const U8): BOOL; var f: Sys.Info; err: INT; begin f, err := Sys.info(path); return (err = 0) and f.dir; end; (* The whole file at path, or the program stops. *) proc read*(path: []const U8): []const U8; var b: Buf.Buf; err: INT; begin Buf.init(b, Heap.heap); err := Files.load(path, b); if err < 0 then die("can't read {}: {}", [Fmt.str(path), Fmt.str(Sys.errorText(err))]); end; return Buf.bytes(b); end; (* Makes the directory dir and those it is in, as mkdir -p does. *) proc makeDirs*(dir: []const U8); var i, err: INT; begin for i := 1 to LEN(dir) - 1 do if dir[i] = '/' then _ := Sys.makeDir(dir[0..i]); end; end; err := Sys.makeDir(dir); if (err < 0) and ((err # Sys.errExists) or not isDir(dir)) then die("can't make {}: {}", [Fmt.str(dir), Fmt.str(Sys.errorText(err))]); end; end; (* Writes data to the file at path, in a directory made if need be. *) proc write*(path, data: []const U8); var slash: INT; begin slash := Str.findLast(path, "/"); if slash > 0 then makeDirs(path[0..slash]); end; if not Files.write(path, data) then die("can't write {}", [Fmt.str(path)]); end; end; (* Copies the file source to the path target. *) proc copy*(source, target: []const U8); begin write(target, read(source)); end; (* The names in the directory dir, in byte order; the program stops if it can't be read. *) proc dirNames*(dir: []const U8): [][]const U8; var d: Sys.Dir; v: Names.Vec; name: []const U8; ok: BOOL; err: INT; begin err := Sys.openDir(d, dir); if err < 0 then die("can't read {}: {}", [Fmt.str(dir), Fmt.str(Sys.errorText(err))]); end; Names.init(v, Heap.heap); name, ok := Sys.nextEntry(d); while ok do Names.push(v, cat([name])); (* a copy: nextEntry's is good only until the next call *) name, ok := Sys.nextEntry(d); end; Sys.closeDir(d); ByName.sort(Names.all(v)); return Names.all(v); end; (* A new directory in base, named tmp and eight random letters, digits and underscores. The length matters: a program built in it carries the path in its debugging information, and a lesson that prints its own size would print a different one for a longer name. *) proc tempDirIn*(base: []const U8): []const U8; var path: []const U8; r: [8]U8; name: [11]U8; i: INT; begin name[0] := 't'; name[1] := 'm'; name[2] := 'p'; repeat Sys.random(r); for i := 0 to 7 do name[3 + i] := Letters[INT(r[i]) mod LEN(Letters)]; end; path := cat([base, "/", name[0..LEN(name)]]); until Sys.makeDir(path) = 0; return path; end; (* A new directory in $TMPDIR, or /tmp, as tempDirIn makes one. *) proc tempDir*: []const U8; var base: []const U8; begin base := Sys.env("TMPDIR"); if LEN(base) = 0 then base := "/tmp"; end; return tempDirIn(base); end; (* ---- programs ---------------------------------------------------- *) (* Starts the program args[0] (found on PATH), in the directory dir unless that is empty, with the NAME=value pairs of env added to its environment, and standard output and error going to the fds out and err (0 for this program's own): its process id, or minus an errno if it can't start. *) proc start*(args: [][]const U8; dir: []const U8; env: [][]const U8; out, err: INT): INT; var p: Sys.Program; begin Out.flush; (* what was printed comes before what the program prints *) p := {path: args[0], args: args, env: env, dir: dir}; p.fds[1] := out; p.fds[2] := err; return Sys.spawn(p); end; (* Waits for the program pid: its exit status, or 128 and the signal's number if a signal killed it. *) proc finish*(pid: INT): INT; var status: Sys.Status; value: INT; begin _, status, value := Sys.waitExit(pid); if status = Sys.killed then return 128 + value; end; return value; end; (* Runs args with its output and errors left where they are, or into the fd out if that isn't 0: its exit status, or minus an errno if it can't start. *) proc run*(args: [][]const U8; out: INT): INT; var pid: INT; begin pid := start(args, "", [], out, 0); if pid < 0 then return pid; end; return finish(pid); end; (* Runs args with its output thrown away: its exit status, or minus an errno if it can't start. *) proc runQuiet*(args: [][]const U8): INT; var null, status: INT; begin null := Sys.open("/dev/null", {Sys.writing}); status := run(args, null); Sys.close(null); return status; end; (* Runs the program first with its output into the program second, whose own goes to the fd out: a shell's first | second > out. Their two exit statuses, or minus an errno for one that can't start. *) proc pipeline*(first, second: [][]const U8; out: INT): (INT, INT); var read, write, pid1, pid2: INT; p: Sys.Program; begin Out.flush; read, write := Sys.pipe(); pid1 := start(first, "", [], write, 0); p := {path: second[0], args: second}; p.fds[0] := read; p.fds[1] := out; pid2 := Sys.spawn(p); Sys.close(read); Sys.close(write); if pid1 >= 0 then pid1 := finish(pid1); end; if pid2 >= 0 then pid2 := finish(pid2); end; return pid1, pid2; end; (* Runs args and stops the program if it fails. *) proc must*(args: [][]const U8); begin if run(args, 0) # 0 then die("{} failed", [Fmt.str(args[0])]); end; end; (* Reads what is ready of the fds in the pair of pipes, to out and err, until both ends are closed; an fd of -1 is already closed. *) proc drain(outFd, errFd: INT; var out, err: Buf.Buf); var pair: [2]Sys.Poll; fds: []Sys.Poll; i, n: INT; begin fds := pair[0..2]; fds[0] := {fd: outFd, read: true}; fds[1] := {fd: errFd, read: true}; while (fds[0].fd >= 0) or (fds[1].fd >= 0) do if Sys.poll(fds, -1) < 0 then continue; end; for i := 0 to 1 do if fds[i].ready then if i = 0 then n := Sys.read(fds[0].fd, Buf.spare(out, 65536)); else n := Sys.read(fds[1].fd, Buf.spare(err, 65536)); end; if n > 0 then if i = 0 then INC(out.len, n); else INC(err.len, n); end; elsif n # Sys.errIntr then Sys.close(fds[i].fd); fds[i].fd := -1; end; end; end; end; end; (* Runs args in dir with env added, and adds what it writes to out and what it writes to err, or all of it to out if merge: its exit status, or minus an errno if it can't start. *) proc capture*(args: [][]const U8; dir: []const U8; env: [][]const U8; merge: BOOL; var out, err: Buf.Buf): INT; var outRead, outWrite, errRead, errWrite, pid: INT; begin outRead, outWrite := Sys.pipe(); errRead := -1; errWrite := outWrite; if not merge then errRead, errWrite := Sys.pipe(); end; pid := start(args, dir, env, outWrite, errWrite); Sys.close(outWrite); if not merge then Sys.close(errWrite); end; if pid < 0 then Sys.close(outRead); if not merge then Sys.close(errRead); end; return pid; end; drain(outRead, errRead, out, err); return finish(pid); end; (* Runs args in dir with env added, and adds what it writes to standard output to out, leaving its errors where they are: its exit status, or minus an errno if it can't start. *) proc captureOut*(args: [][]const U8; dir: []const U8; env: [][]const U8; var out: Buf.Buf): INT; var r, w, pid, n: INT; begin r, w := Sys.pipe(); pid := start(args, dir, env, w, 0); Sys.close(w); if pid < 0 then Sys.close(r); return pid; end; repeat n := Sys.read(r, Buf.spare(out, 65536)); if n > 0 then INC(out.len, n); end; until (n <= 0) and (n # Sys.errIntr); Sys.close(r); return finish(pid); end; (* The arguments of a git command in the repository at dir. *) proc gitArgs*(dir: []const U8; args: [][]const U8): [][]const U8; var v: Names.Vec; i: INT; begin Names.init(v, Heap.heap); Names.push(v, "git"); Names.push(v, "-C"); Names.push(v, dir); for i := 0 to LEN(args) - 1 do Names.push(v, args[i]); end; return Names.all(v); end; (* What the git command args writes to standard output, with white space cut from its ends, or the program stops. *) proc git*(dir: []const U8; args: [][]const U8): []const U8; var out: Buf.Buf; begin Buf.init(out, Heap.heap); if captureOut(gitArgs(dir, args), "", [], out) # 0 then die("git {} failed", [Fmt.str(args[0])]); end; return Str.trim(Buf.bytes(out)); end; end Site.