# pragma-jennifer-version: >=0.27.0# pragma-jennifer-capability: exec/**
* A complete preprocessor for Grimoire and Cantrip, small enough to read in
* one sitting: every `shout` fence is handed to an external program (`awk` by
* default), and its output replaces the fence as a `text` fence.
*
* It speaks the plugin contract, api 1, without Grimoire's plugin kit, so each
* step is visible: read the request, check it, read the settings, find the
* fences, run the program with caps and a timeout, reply with the chapters it
* changed.
* @module shout
*/use io;
use os;
use fs;
use path;
use json;
use strings;
use convert;
use regex;
use time;
use encoding;
defconstAPIasintinit1;
defconstNAMEasstringinit"grimoire-shout";
# The fence language this plugin rewrites.defconstLANGUAGEasstringinit"shout";
# Caps: one fence's text, the program's output for it, and fences per chapter.defconstMAX_SOURCEasintinit65536;
defconstMAX_OUTPUTasintinit1048576;
defconstMAX_FENCESasintinit200;
# The timeout a book may set, in milliseconds, and the default.defconstDEFAULT_TIMEOUTasintinit10000;
defconstMAX_TIMEOUTasintinit60000;
# The settings this plugin reads, and the keys the host itself uses.defconstSETTINGSaslistofstringinit ["program", "timeout"];
defconstHOST_KEYSaslistofstringinit ["command", "args"];
# --- errors ------------------------------------------------------------funcfail(message asstring) {
throw Error{kind: "plugin", message: $message};
}
funcfailAt(kind asstring, chapter asstring, line asint, message asstring) {
throw Error{kind: $kind, message: "{$chapter}:{$line}: {$message}"};
}
# --- the request -------------------------------------------------------/**
* Decode a request and check that this plugin can answer it.
* @param text {string} what arrived on stdin
* @return {json.Value} the request
* @throws {Error} kind "plugin" for an empty request, another api or kind
*/exportfuncrequest(text asstring) {
if (strings.trim($text) == "") {
fail("no request on stdin; grimoire or cantrip runs this program");
}
def req asjson.Value initjson.decode($text);
if (json.typeOf($req, "/api") != "int"orjson.asInt($req, "/api") != API) {
fail("this plugin speaks api 1 only");
}
if (json.typeOf($req, "/kind") != "string"orjson.asString($req, "/kind") != "preprocessor") {
fail("this is a preprocessor");
}
return$req;
}
/**
* What the plugin's table says, checked.
* @field program {string} the program each fence is handed to
* @field timeout {int} milliseconds one run may take
*/exportdefstruct Settings {
program asstring,
timeout asint
};
/**
* Read the settings: an unknown key or a value of the wrong type is an error,
* never ignored.
* @param req {json.Value} the request
* @return {Settings} the settings, defaults filled in
* @throws {Error} kind "plugin" for a bad setting
*/exportfuncsettingsOf(req asjson.Value) {
def out as Settings init Settings{program: "awk", timeout: DEFAULT_TIMEOUT};
def at asstringinit"/plugin/settings";
if (json.typeOf($req, $at) != "map") {
return$out;
}
for (def key injson.keys($req, $at)) {
if (not (inList(SETTINGS, $key) orinList(HOST_KEYS, $key))) {
fail("unknown setting `{$key}`; the settings are program, timeout");
}
}
if (json.has($req, $at + "/program")) {
if (json.typeOf($req, $at + "/program") != "string") {
fail("setting `program` must be a string");
}
$out.program = json.asString($req, $at + "/program");
}
if (json.has($req, $at + "/timeout")) {
if (json.typeOf($req, $at + "/timeout") != "int") {
fail("setting `timeout` must be a whole number of milliseconds");
}
$out.timeout = json.asInt($req, $at + "/timeout");
}
if ($out.program == "") {
fail("setting `program` is empty");
}
if ($out.timeout < 1or$out.timeout > MAX_TIMEOUT) {
fail("setting `timeout` must be 1 to {MAX_TIMEOUT} milliseconds");
}
return$out;
}
funcinList(items aslistofstring, item asstring) {
for (def x in$items) {
if ($x == $item) {
returntrue;
}
}
returnfalse;
}
# --- fences ------------------------------------------------------------/**
* One `shout` fence.
* @field first {int} the index of the opening line
* @field last {int} the index of the closing line
* @field indent {string} the opener's indentation
* @field body {string} the text between, indentation removed
*/exportdefstruct Fence {
first asint,
last asint,
indent asstring,
body asstring
};
/**
* Every `shout` fence in a chapter. Fences of other languages are skipped as
* a whole, so a page can show the syntax inside a longer fence.
* @param chapter {string} the chapter's `src`, for errors
* @param content {string} the chapter's Markdown
* @return {list of Fence} the fences, in order
* @throws {Error} kind "plugin" for an unclosed `shout` fence; "limit" over a cap
*/exportfuncfencesIn(chapter asstring, content asstring) {
def out aslistof Fence;
def lines aslistofstringinitstrings.split($content, "\n");
def i asintinit0;
while ($i < len($lines)) {
def open asregex.Match initregex.find('^( {0,3})(`{3,}|~{3,})\s*([^`\s]*)', $lines[$i]);
if ($open.start < 0) {
$i = $i + 1;
continue;
}
def mark asstringinit$open.groups[1];
def close asstringinit'^ {0,3}' + regex.escape($mark) + regex.escape($mark[..1]) +
'*\s*$';
def j asintinit$i + 1;
while ($j < len($lines) andnotregex.matches($close, $lines[$j])) {
$j = $j + 1;
}
if ($open.groups[2] == LANGUAGE) {
if ($j == len($lines)) {
failAt("plugin", $chapter, $i + 1, "the shout fence is never closed");
}
if (len($out) == MAX_FENCES) {
failAt("limit", $chapter, $i + 1, "more than {MAX_FENCES} shout fences");
}
def body aslistofstring;
for (def line in$lines[$i + 1..$j]) {
$body[] = strings.trimPrefix($line, $open.groups[0]);
}
def text asstringinitstrings.join($body, "\n");
if (encoding.lenBytes($text) > MAX_SOURCE) {
failAt("limit", $chapter, $i + 1, "the fence is over {MAX_SOURCE} bytes");
}
$out[] = Fence{first: $i, last: $j, indent: $open.groups[0], body: $text};
}
$i = $j + 1;
}
return$out;
}
# --- running the program -----------------------------------------------/**
* Run a program, and stop it when it takes longer than `ms` milliseconds.
* `os.spawn` takes no stdin, so the input travels as a file named in `argv`.
* @param argv {list of string} the program and its arguments
* @param ms {int} the timeout
* @return {os.Result} what it printed, and its exit status
* @throws {Error} kind "timeout" when it ran too long; "plugin" when it cannot start
*/exportfuncrunBounded(argv aslistofstring, ms asint) {
def p asos.Process;
try {
$p = os.spawn($argv);
} catch (e) {
fail("cannot run {$argv[0]} ({$e.message}); install it, or set `program`");
}
def started astime.Time inittime.now();
while (notos.poll($p)) {
if (time.milliseconds(time.sub(time.now(), $started)) >= $ms) {
os.kill($p);
os.wait($p);
os.release($p);
throw Error{kind: "timeout", message: "{$argv[0]} did not finish within {$ms} ms"};
}
time.sleep(time.fromMilliseconds(10));
}
def r asos.Result initos.wait($p);
os.release($p);
return$r;
}
# The first line of a message that has text on it.funcfirstLine(text asstring) {
for (def line instrings.split($text, "\n")) {
if (strings.trim($line) != "") {
returnstrings.trim($line);
}
}
return"";
}
/**
* Hand one fence to the program and return what it printed.
* @param s {Settings} the settings
* @param dir {string} a private directory for the input file
* @param chapter {string} the chapter, for errors
* @param f {Fence} the fence
* @return {string} the program's output
*/funcshout(s as Settings, dir asstring, chapter asstring, f as Fence) {
def input asstringinitpath.join($dir, "fence.txt");
fs.writeString($input, $f.body + "\n");
def r asos.Result;
try {
$r = runBounded([$s.program, '{ print toupper($0) }', $input], $s.timeout);
} catch (e) {
failAt($e.kind, $chapter, $f.first + 1, $e.message);
}
if ($r.exitCode != 0) {
failAt("plugin", $chapter, $f.first + 1, $s.program + ": " + firstLine($r.stderr));
}
if (encoding.lenBytes($r.stdout) > MAX_OUTPUT) {
failAt("limit", $chapter, $f.first + 1, "the output is over {MAX_OUTPUT} bytes");
}
returnstrings.trimSuffix($r.stdout, "\n");
}
# --- the reply ---------------------------------------------------------# A fence one backtick longer than any run of backticks in the text, so the# program's output cannot close it early.funcfenceFor(text asstring) {
def longest asintinit2;
for (def m inregex.findAll('`+', $text)) {
if (len($m.text) > $longest) {
$longest = len($m.text);
}
}
returnstrings.replicate("`", $longest + 1);
}
/**
* A chapter with each fence replaced by the program's output.
* @param content {string} the chapter
* @param fences {list of Fence} its `shout` fences
* @param outputs {list of string} the output for each, in the same order
* @return {string} the new chapter
*/exportfuncrewrite(content asstring, fences aslistof Fence, outputs aslistofstring) {
def lines aslistofstringinitstrings.split($content, "\n");
def out aslistofstring;
def i asintinit0;
def k asintinit0;
while ($i < len($lines)) {
if ($k < len($fences) and$fences[$k].first == $i) {
def f as Fence init$fences[$k];
def mark asstringinitfenceFor($outputs[$k]);
$out[] = $f.indent + $mark + "text";
for (def line instrings.split($outputs[$k], "\n")) {
$out[] = $f.indent + $line;
}
$out[] = $f.indent + $mark;
$i = $f.last + 1;
$k = $k + 1;
continue;
}
$out[] = $lines[$i];
$i = $i + 1;
}
returnstrings.join($out, "\n");
}
/**
* Answer one request: the reply lists only the chapters that changed.
* @param req {json.Value} the checked request
* @return {string} the reply, as JSON
*/exportfuncreplyFor(req asjson.Value) {
def s as Settings initsettingsOf($req);
def dir asstringinitfs.makeTempDir(os.tempDir(), "grimoire-shout-");
deferfs.removeAll($dir);
def changed aslistofstring;
for (def i in0..json.length($req, "/chapters")) {
def at asstringinit"/chapters/" + convert.toString($i);
def src asstringinitjson.asString($req, $at + "/src");
def content asstringinitjson.asString($req, $at + "/content");
def fences aslistof Fence initfencesIn($src, $content);
if (len($fences) == 0) {
continue;
}
def outputs aslistofstring;
for (def f in$fences) {
$outputs[] = shout($s, $dir, $src, $f);
}
$changed[] = '{"src":' + json.encode($src) + ',"content":' +
json.encode(rewrite($content, $fences, $outputs)) + '}';
}
return'{"api":1,"chapters":[' + strings.join($changed, ",") + ']}';
}
/**
* Run the plugin over one request: the reply on stdout, or the reason on
* stderr and status 1, which stops the build.
* @param text {string} the request from stdin
* @return {int} the exit status
*/exportfuncrun(text asstring) {
try {
io.printf("%s", replyFor(request($text)));
return0;
} catch (e) {
io.eprintf("%s: %s\n", NAME, $e.message);
return1;
}
}