From 28bed07694d16685ecf8d2e179222b3d4920611d Mon Sep 17 00:00:00 2001 From: Profpatsch Date: Sun, 1 Aug 2021 18:41:18 +0200 Subject: feat(users/Profpatsch): add atomically-write A little shell script to atomically write stdout to a file. Change-Id: Icca58909c9ad3f92d69af2f5e20c08d69878a77c Reviewed-on: https://cl.tvl.fyi/c/depot/+/3264 Tested-by: BuildkiteCI Reviewed-by: Profpatsch --- users/Profpatsch/atomically-write.nix | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 users/Profpatsch/atomically-write.nix (limited to 'users/Profpatsch') diff --git a/users/Profpatsch/atomically-write.nix b/users/Profpatsch/atomically-write.nix new file mode 100644 index 000000000000..d5039d3e46b9 --- /dev/null +++ b/users/Profpatsch/atomically-write.nix @@ -0,0 +1,28 @@ +{ depot, pkgs, ... }: +# Atomically write a file (just `>` redirection in bash +# empties a file even if the command crashes). +# +# Maybe there is an existing tool for that? +# But it’s easy enough to implement. +# +# Example: +# atomically-write +# ./to +# echo "foo" +# +# will atomically write the string "foo" into ./to +let + atomically-write = pkgs.writers.writeDash "atomically-write" '' + set -e + to=$1 + shift + # assumes that the tempfile is on the same file system, (or in memory) + # for the `mv` at the end to be more-or-less atomic. + tmp=$(${pkgs.coreutils}/bin/mktemp -d) + trap 'rm -r "$tmp"' EXIT + "$@" \ + > "$tmp/out" + mv "$tmp/out" "$to" + ''; + +in atomically-write -- cgit 1.4.1