Commits

Anonymous committed e3a71d2

Fixes #5.

- Added with-temp macro.

  • Participants
  • Parent commits d3b354a

Comments (0)

Files changed (3)

 walk
     Walk over directory structure, calling function on every step
 
+with-temp
+    Creates a scope in which a temporary file or directory can be
+    used, and ensures that the file or directory is deleted on exiting
+    the scope.
+
 writeable?
     Check if path is writable
 
      (.mkdir dir)
      path)))
 
+(defmacro with-temp
+  "bindings => [name path]
+
+   Evaluates body in a try expression with the name bound to the path
+   supplied. A finally clause calls (fs/deltree on name).
+
+   Typical usage:
+
+   (with-temp [d (fs/tempdir)]
+     (println d))
+
+   Or
+
+   (with-temp [f (fs/tempfile)]
+     (println f))
+  "
+  [bindings & body]
+  (assert
+   (and
+    (vector? bindings)
+    (= 2 (count bindings))
+    (symbol? (bindings 0))))
+  `(let ~bindings
+     (try
+       ~@body
+       (finally (deltree ~(bindings 0))))))
+
 (defn cwd
   "Return the current working directory."
   []

File test/fs_test.clj

 (deftest tempdir-test
   (is (directory? (tempdir))))
 
+(deftest with-temp-test
+  (testing "Directory is created"
+    (with-temp [d (tempdir)]
+      (is (directory? d))))
+  (testing "File is created"
+    (with-temp [f (tempfile)]
+      (file? f)))
+  (testing "Directory is removed"
+    (let [dir (tempdir)]
+      (with-temp [d dir]
+        (is (directory? d))
+        (is (= dir d)))
+      (is (not (directory? dir)))))
+  (testing "File is removed"
+    (let [file (tempfile)]
+      (with-temp [f file]
+        (is (file? f))
+        (is (= f file)))
+      (is (not (file? file))))))
+
 ; FIXME: This test sucks
 (deftest cwd-test
   (is (> (count (cwd)) 3)))