Skip to content

Instantly share code, notes, and snippets.

@frankitox
Created January 9, 2021 00:33
Show Gist options
  • Save frankitox/19c41342716572b653b405b476d440af to your computer and use it in GitHub Desktop.
Save frankitox/19c41342716572b653b405b476d440af to your computer and use it in GitHub Desktop.
Helper to clean generated files
(require '[clojure.java.io :as io])
(defmacro with-file
"bindings => [name init ...]
Evaluates body in a try expression with names bound to the values
of the inits, and a finally clause that calls (io/delete-file name) on each
name in reverse order."
[bindings & body]
(#'clojure.core/assert-args
(vector? bindings) "a vector for its binding"
(even? (count bindings)) "an even number of forms in binding vector")
(cond
(= (count bindings) 0) `(do ~@body)
(symbol? (bindings 0)) `(let ~(subvec bindings 0 2)
(try
(with-file ~(subvec bindings 2) ~@body)
(finally
(when (.exists ~(bindings 0))
(io/delete-file ~(bindings 0))))))
:else (throw (IllegalArgumentException.
"with-file only allows Symbols in bindings"))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment