This is an overly elaborate example of building a ‘Hello World’ package with Nix flakes, OCaml, and Dune. The following things are demonstrated:
- A library and an executable that depends on that library
- Building documentation
- Expect tests and Cram tests
I'm not a Nix expert, nor am I an OCaml expert so there might be better approaches to some of the things demonstrated here! That said, I thought I'd share this in the off-chance it is useful to somebody else.
Sometimes it can be useful to run commands such as dune
directly from your
shell. To do this you can call nix develop
in your shell, which will load a
new bash
shell with the appropriate tools in your $PATH
:
nix develop
Alternatively you can use direnv
or nix-direnv
to load the development
tools automatically in the current shell. Direnv can also be extremely useful
for setting up your editor, for example with vscode-direnv.
You can enable direnv
to load the development tools onto your $PATH
by
running:
echo "use flake" > .envrc
direnv allow
If you decide to use direnv
you'll probably want to add .direnv
and .envrc
to your global gitignore or local excludes in order to avoid committing
these files to git.
The hello
executable can be run with the nix
command with:
nix run
This should print Hello, World!
in your shell.
The hello
package can be built with the nix
command with:
nix build
This should create a result
symlink in the current directory, which will
contain the hello
executable and library.
The tests can be run using the nix
command with:
nix flake check --print-build-logs
This will also check that flake.nix
conforms to the expected flake schema,
and will run formatting tests for the Nix files.
Expect test failures can be promoted in a development shell with:
dune promote
This will update the tests to their current expected output.