Created
November 27, 2011 21:41
-
-
Save samaaron/1398198 to your computer and use it in GitHub Desktop.
Clojure mk-tmp-dir!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn mk-tmp-dir! | |
"Creates a unique temporary directory on the filesystem. Typically in /tmp on | |
*NIX systems. Returns a File object pointing to the new directory. Raises an | |
exception if the directory couldn't be created after 10000 tries." | |
[] | |
(let [base-dir (file (System/getProperty "java.io.tmpdir")) | |
base-name (str (System/currentTimeMillis) "-" (long (rand 1000000000)) "-") | |
tmp-base (mk-path base-dir base-name) | |
max-attempts 10000] | |
(loop [num-attempts 1] | |
(if (= num-attempts max-attempts) | |
(throw (Exception. (str "Failed to create temporary directory after " max-attempts " attempts."))) | |
(let [tmp-dir-name (str tmp-base num-attempts) | |
tmp-dir (file tmp-dir-name)] | |
(if (.mkdir tmp-dir) | |
tmp-dir | |
(recur (inc num-attempts)))))))) |
micahasmith
commented
Apr 15, 2018
@micahasmith this has a bug that forces tmp-base to be a boolean.
fixed version from @micahasmith :
(defn mk-tmp-dir!
"Creates a unique temporary directory on the filesystem. Typically in /tmp on
*NIX systems. Returns a File object pointing to the new directory. Raises an
exception if the directory couldn't be created after 10000 tries."
[]
(let [base-dir (io/file (System/getProperty "java.io.tmpdir"))
base-name (str (System/currentTimeMillis) "-" (long (rand 1000000000)) "-")
tmp-base (doto (File. (str base-dir "/" base-name)) (.mkdir))
max-attempts 10000]
(loop [num-attempts 1]
(if (= num-attempts max-attempts)
(throw (Exception. (str "Failed to create temporary directory after " max-attempts " attempts.")))
(let [tmp-dir-name (str tmp-base num-attempts)
tmp-dir (io/file tmp-dir-name)]
(if (.mkdir tmp-dir)
tmp-dir
(recur (inc num-attempts))))))))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment