Last active
June 4, 2023 16:12
-
-
Save olieidel/c551a911a4798312e4ef42a584677397 to your computer and use it in GitHub Desktop.
Delete Directories recursively with Clojure in only 4 lines of code.
This file contains 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
(ns yourproject.yourns | |
(:require [clojure.java.io :as io])) | |
(defn delete-directory-recursive | |
"Recursively delete a directory." | |
[^java.io.File file] | |
;; when `file` is a directory, list its entries and call this | |
;; function with each entry. can't `recur` here as it's not a tail | |
;; position, sadly. could cause a stack overflow for many entries? | |
;; thanks to @nikolavojicic for the idea to use `run!` instead of | |
;; `doseq` :) | |
(when (.isDirectory file) | |
(run! delete-directory-recursive (.listFiles file))) | |
;; delete the file or directory. if it it's a file, it's easily | |
;; deletable. if it's a directory, we already have deleted all its | |
;; contents with the code above (remember?) | |
(io/delete-file file)) |
Great point, I didn't even know about run!
. Thanks, edited!
That one line should work too:
(run! io/delete-file (reverse (file-seq file)))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Even shorter :)
(run! delete-directory-recursive (.listFiles file))
...instead of
doseq
...