diff --git a/combinators.nix b/combinators.nix index ac8b5e1..5b00ed5 100644 --- a/combinators.nix +++ b/combinators.nix @@ -190,6 +190,9 @@ RUNTIME_ARGS+=(--bind /foo /foo) 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 = _: @@ -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 = { sig = "(String -> String) -> Combinator"; doc = '' diff --git a/lib.nix b/lib.nix index 079abf0..9035b64 100644 --- a/lib.nix +++ b/lib.nix @@ -20,6 +20,7 @@ env = {}; namespaces = {}; included-once = []; # See include-once combinator + cleanup = []; # See cleanup combinator }; in lib.pipe initial-state ( # apply pre-user combinators @@ -75,8 +76,14 @@ in lib.pipe initial-state ( ++ [ (state: '' RUNTIME_ARGS=() + ${if builtins.length state.cleanup > 0 then '' + function cleanup { + ${lib.concatStringsSep "\n" state.cleanup} + } + trap cleanup EXIT + '' else ""} ${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; })