Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Clojure mk-tmp-dir!
(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

This comment has been minimized.

Copy link

micahasmith commented Apr 15, 2018

(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 (.mkdir (File. (str 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 (io/file tmp-dir-name)]
          (if (.mkdir tmp-dir)
            tmp-dir
            (recur (inc num-attempts))))))))
@csakoda

This comment has been minimized.

Copy link

csakoda commented Jan 14, 2020

@micahasmith this has a bug that forces tmp-base to be a boolean.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.