Build hooks
Shell commands that run before and after a build. They are motabhai's extension mechanism for now: generate input before the build, or post-process the output after it.
The [hooks] table
[hooks]
before_build = ["./scripts/fetch-data.sh"]
after_build = [
"npx -y pagefind --site \"$MOTABHAI_OUTPUT\"",
]
| Key | Type | Meaning |
|---|---|---|
before_build | list of strings | Commands run before the site is built. |
after_build | list of strings | Commands run after the site is built, and before a deploy. |
Both keys are optional. Each is a list of commands, even for one command;
a plain string, or a misspelt key, is a config error (motabhai::toml).
How hooks run
-
motabhai buildandmotabhai deployrun hooks.motabhai servedoes not, so a hook that writes into the project cannot start an endless loop of rebuilds. -
Commands run one at a time, in the order listed, in the project root, whichever directory you ran motabhai from.
-
Each command runs through
sh -c(cmd /Con Windows), so pipes,&&, quoting and variables work as in a shell. -
motabhai prints
running <command>before each one. What the command prints goes to the terminal, and it has no standard input. -
Two environment variables are set:
Variable Value MOTABHAI_ROOTThe project root. MOTABHAI_OUTPUTThe absolute path of the output directory, public/or whatever--outputnames. -
A command that exits with a non-zero status, or that the shell cannot start, stops everything with
motabhai::hook::failed, naming the command and how it ended. A failingbefore_buildhook stops the build before anything is built, and the commands after it do not run. A failingafter_buildhook fails the command, and withmotabhai deploynothing is deployed.
Because after_build runs before a deploy, what it writes into the output
is deployed too.
Examples
Search with Pagefind
Pagefind indexes a built static site and writes a search index and UI beside it:
[hooks]
after_build = ["npx -y pagefind --site \"$MOTABHAI_OUTPUT\""]
Then add its UI to a template:
<link href="{{ '/pagefind/pagefind-ui.css'|url }}" rel="stylesheet">
<script src="{{ '/pagefind/pagefind-ui.js'|url }}"></script>
<div id="search"></div>
<script>
window.addEventListener("DOMContentLoaded", () => {
new PagefindUI({ element: "#search" });
});
</script>
The pagefind/ directory is written after the build, so motabhai serve,
which runs no hooks, does not have it. Run motabhai build once and serve
public/ with any static server to try search locally.
Generating a databag
A before_build hook can write files that the build then reads, such as a
databag made from an API or another repository:
[hooks]
before_build = ["curl -fsSL https://example.com/team.toml -o databags/team.toml"]
Since motabhai serve does not run it, run motabhai build (or the
command itself) when the data should be refreshed.
Checking the output
[hooks]
after_build = ["test -f \"$MOTABHAI_OUTPUT/404.html\""]
A failing check stops a deploy.