run-liquid.lua: Add error checking and file output parameter

When running `make epub`, Make would try to satisfy the target
'src/plfa/acknowledgements_epub.md' by calling run-liquid.lua.  But due
to the use of shell redirection, Make would always create the file
acknowledgements_epub.md, even if run-liquid.lua failed, in which case
acknowledgements_epub.md would be empty.  This empty file would still
satisfy the 'src/plfa/acknowledgements_epub.md' target, allowing the
pandoc command line in the 'out/plfa.epub' target to proceed---and later
fail.

To avoid this, we now (a) add a bunch of error checking to run-liquid.lua,
and (b) write directly to acknowledgements_epub.md instead of relying on
shell redirection, so that acknowledgements_epub.md will only be created
(or modified) if run-liquid.lua succeeds.
This commit is contained in:
Michael Reed 2020-07-01 17:08:19 -04:00
parent 2e6e53d60a
commit 4e837c0975
2 changed files with 39 additions and 6 deletions

View file

@ -70,7 +70,7 @@ out/plfa.epub: out/ $(AGDA) $(LUA) epub/main.css src/plfa/acknowledgements_epub.
epub/index.md
src/plfa/acknowledgements_epub.md: src/plfa/acknowledgements.md _config.yml
lua epub/run-liquid.lua _config.yml $< > $@
lua epub/run-liquid.lua _config.yml $< $@
# Convert literal Agda to Markdown

View file

@ -1,19 +1,52 @@
local yaml = require 'tinyyaml'
local liquid = require 'liquid'
if #arg ~= 2 then
print('usage: ' .. arg[0] .. ' [yaml_file] [markdown_file]')
-- Given a file name, return its file descriptor.
-- Throws an error on failure.
local function errOpen (fname, mode)
local fd = io.open(fname, mode)
if fd == nil then
error('could not open file: ' .. fname)
end
return fd
end
-- Given a file name and some data, overwrite the file with the data.
-- Throws an error on failure.
local function errWrite (fname, data)
local fd = errOpen(fname, 'w')
local status, errstr = fd:write(data)
if status == nil then
error(fname .. ': ' .. errstr)
end
end
-- Given a file name, return that file's entire contents.
-- Throws an error on failure.
local function errReadAll (fname)
local data = errOpen(fname, 'r'):read('a')
if data == nil then
error('could not read from open file: ' .. fname)
end
return data
end
-- We must have exactly three arguments.
if #arg ~= 3 then
print('usage: ' .. arg[0] .. ' [yaml_file] [markdown_in_file] [markdown_out_file]')
os.exit(1)
end
-- 1. Read YAML metadata from file, which we nest under the key 'site'.
local metadata = { ['site'] = yaml.parse(io.open(arg[1]):read('a')) }
local metadata = { ['site'] = yaml.parse(errReadAll(arg[1])) }
-- 2. Read markdown document from file.
local document = io.open(arg[2]):read('a')
local document = errReadAll(arg[2])
-- 3. Render the markdown document with the YAML metadata as context.
local template = liquid.Template:parse(document)
local result = template:render(liquid.InterpreterContext:new(metadata))
print(result)
-- 4. Write rendered document to output file.
errWrite(arg[3], result)