From 1490b9cb5334b1b1704005884a6a4880ed51afc9 Mon Sep 17 00:00:00 2001 From: Gregor Kleen Date: Wed, 18 Apr 2018 14:28:15 +0200 Subject: rolling-directory --- nix/default.nix | 1 + nix/rolling-directory.nix | 25 ++++++++++++++++++++ rolling-directory | 58 +++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 84 insertions(+) create mode 100644 nix/rolling-directory.nix create mode 100644 rolling-directory diff --git a/nix/default.nix b/nix/default.nix index 1c0105f..a40d8f6 100644 --- a/nix/default.nix +++ b/nix/default.nix @@ -7,4 +7,5 @@ in rec { rebuild-system = pkgs.callPackage ./rebuild-system.nix {}; pulseaudio-ctl = pkgs.callPackage ./pulseaudio-ctl.nix {}; monitor-uucp = pkgs.callPackage ./monitor-uucp.nix {}; + rolling-directory = pkgs.callPackage ./rolling-directory.nix {}; } diff --git a/nix/rolling-directory.nix b/nix/rolling-directory.nix new file mode 100644 index 0000000..bb5dd53 --- /dev/null +++ b/nix/rolling-directory.nix @@ -0,0 +1,25 @@ +{ stdenv +, zsh, coreutils, findutils, gawk, inotify-tools +}: + +stdenv.mkDerivation rec { + name = "rolling-directory-${version}"; + version = "0.2"; + src = ../rolling-directory; + + phases = [ "buildPhase" "installPhase" ]; + + inherit zsh coreutils findutils gawk; + inotify = inotify-tools; + + buildPhase = '' + substituteAll $src rolling-directory + ''; + + installPhase = '' + mkdir -p $out/bin + + install -m 755 -t $out/bin \ + rolling-directory + ''; +} diff --git a/rolling-directory b/rolling-directory new file mode 100644 index 0000000..d85f8b7 --- /dev/null +++ b/rolling-directory @@ -0,0 +1,58 @@ +#!@zsh@/bin/zsh + +set -e + +PATH=@coreutils@/bin:@findutils@/bin:@gawk@/bin:@inotify@/bin:$PATH + +dir=${1:A} +maxSize=$(numfmt --from=auto --to=none -- $2) +shift 2 + +[[ -d "${dir}" ]] || exit 2 +[[ "${maxSize}" = <-> ]] || exit 2 + +typeset -a findExtra +findExtra=(-not -path ${dir}/CACHEDIR.TAG) + +resize() { + echo "Resizing ${dir} to below $(numfmt --to=iec-i --suffix=B -- ${maxSize})..." >&2 + + while [[ $(du -xbs ${dir} | awk '{ print $1; }') -gt $maxSize ]]; do + find ${dir} -xdev -type f \( ${findExtra} \) -print0 | \ + xargs -r0 -- stat --printf '%W %Y %Z %X %n\0' | \ + sort -t '\0' -z | \ + awk -F '\0' '{ gsub("^\\S+\\s+\\S+\\s+\\S+\\s+\\S+\\s+", "", $1); printf "%s\0", $1; }' | \ + xargs -r0 -- rm -v + done + + find ${dir} -xdev -xtype l -print0 | xargs -r0 -- rm -v + find ${dir} -xdev -type d \( -not -path ${dir} \) -empty -print0 | xargs -r0 -- rmdir -v +} + +case "${1}" in + monitor) + shift + + typeset -a inotifyExtra + inotifyExtra=() + + if [[ "${1}" = <-> ]]; then + inotifyExtra=(-t "${1}") + shift + fi + + while + resize + inotifywait -qq -r ${dir} ${inotifyExtra} \ + -e modify \ + -e close_write \ + -e moved_to \ + -e move_self \ + -e create + true + do :; done + ;; + *) + resize + ;; +esac -- cgit v1.2.3