Add cleanup combinator

This commit is contained in:
Alex David 2025-06-14 22:11:21 -07:00
commit b10ff57b1e
2 changed files with 45 additions and 1 deletions

View file

@ -190,6 +190,9 @@
RUNTIME_ARGS+=(--bind /foo /foo) RUNTIME_ARGS+=(--bind /foo /foo)
fi fi
${"''"} ${"''"}
If you create any resources in add-runtime that you want to automatically
clean up when the jail exits use [add-cleanup](#add-cleanup).
``` ```
''; '';
__functor = _: __functor = _:
@ -197,6 +200,40 @@
; ;
}; };
add-cleanup = {
sig = "String -> Combinator";
doc = ''
Adds arbitrary logic to run when the jail exits.
This is designed to be an easy way to register cleanup actions for things
created in [add-runtime](#add-runtime). These scripts run in the same
scope as `add-runtime` so any shell variables defined there will be in
scope.
The cleanup actions may run even if the runtime doesn't— for example if a
previous runtime exits non-zero the jail will exit prematurely, but the
cleanup actions will still run.
Example:
```nix
compose [
(add-runtime ${"''"}
TMP_FILE=$(mktemp)
do-something "$TMP_FILE"
${"''"})
(add-cleanup ${"''"}
if [ -e "''${TMP_FILE-}" ]; then
rm "$TMP_FILE"
fi
${"''"})
]
```
'';
__functor = _:
cleanup: state: state // { cleanup = state.cleanup ++ [ cleanup ]; }
;
};
wrap-entry = { wrap-entry = {
sig = "(String -> String) -> Combinator"; sig = "(String -> String) -> Combinator";
doc = '' doc = ''

View file

@ -20,6 +20,7 @@
env = {}; env = {};
namespaces = {}; namespaces = {};
included-once = []; # See include-once combinator included-once = []; # See include-once combinator
cleanup = []; # See cleanup combinator
}; };
in lib.pipe initial-state ( in lib.pipe initial-state (
# apply pre-user combinators # apply pre-user combinators
@ -75,8 +76,14 @@ in lib.pipe initial-state (
++ [ ++ [
(state: '' (state: ''
RUNTIME_ARGS=() RUNTIME_ARGS=()
${if builtins.length state.cleanup > 0 then ''
function cleanup {
${lib.concatStringsSep "\n" state.cleanup}
}
trap cleanup EXIT
'' else ""}
${state.runtime} ${state.runtime}
exec ${state.cmd} "''${RUNTIME_ARGS[@]}" -- ${state.entry} ${state.argv} ${if builtins.length state.cleanup > 0 then "" else "exec "}${state.cmd} "''${RUNTIME_ARGS[@]}" -- ${state.entry} ${state.argv}
'') '')
(text: pkgs.writeShellApplication { inherit name text; }) (text: pkgs.writeShellApplication { inherit name text; })