Skip to content

Instantly share code, notes, and snippets.

@zahardzhan
Created July 23, 2010 03:27
Show Gist options
  • Save zahardzhan/486958 to your computer and use it in GitHub Desktop.
Save zahardzhan/486958 to your computer and use it in GitHub Desktop.
(defn as-file
[arg & {:as args :keys [exists create readable writeable directory]}]
(let [argtype (type arg)]
(cond (= argtype File)
(let [maybe-exists
(fn [f] (cond (= exists true) (when (.exists f) f)
(= exists false) (when-not (.exists f) f)
(not exists) f))
maybe-directory
(fn [f] (cond (= directory true) (when (.isDirectory f) f)
(= directory false) (when-not (.isDirectory f) f)
(not directory) f))
maybe-readable
(fn [f] (cond (= readable true) (when (.canRead f) f)
(= readable false) (when-not (.canRead f) f)
(not readable) f))
maybe-writeable
(fn [f] (cond (= writeable true) (when (.canWrite f) f)
(= writeable false) (when-not (.canWrite f) f)
(not writeable) f))
maybe-create
(fn [f] (cond (and (= create true) (not (.exists f)))
(let [dir (File. (.getParent f))]
(if-not (.exists dir)
(throw (new Exception
"Cannot create file in nonexistant directory."))
(if-not (.canWrite dir)
(throw (new Exception
"Cannot create file in nonwriteable directory."))
(with-return f (.createNewFile f)))))
:else f))]
(-> arg maybe-create maybe-exists maybe-directory maybe-readable maybe-writeable))
(= argtype String) (if args
(apply as-file (new File arg) (flatten (seq args)))
(as-file (new File arg))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment