Reputation: 58786
Is there a library which allows me to copy a directory and all subdirectories in Clojure? Something like:
(copy "source-dir" "destination-dir")
Upvotes: 1
Views: 1469
Reputation: 23002
You can use copy-dir
of the fs library
as already answered.
One issue with copy-dir
is that it'll put the source directory under the target directory if the target directory already exists behaving like:
# if target already exists
cp -r source/ target/
# target/source/...
To avoid this, you can use the copy-dir-into
function. It will behave something like this:
cp -r source/* target/
It's not in the document but it's a public function so it should be safe to use.
Upvotes: 1
Reputation: 22893
You could use the following code for copy-dir
:
copy-dir (copy-dir from to)
Copy a directory from
from
toto
. Ifto
already exists, copy the directory to a directory with the same name asfrom
within theto
directory.
(defn copy-dir
"Copy a directory from `from` to `to`. If `to` already exists, copy the directory
to a directory with the same name as `from` within the `to` directory."
[from to]
(when (exists? from)
(if (file? to)
(throw (IllegalArgumentException. (str to " is a file")))
(let [from (file from)
to (if (exists? to)
(file to (base-name from))
(file to))
trim-size (-> from str count inc)
dest #(file to (subs (str %) trim-size))]
(mkdirs to)
(dorun
(walk (fn [root dirs files]
(doseq [dir dirs]
(when-not (directory? dir)
(-> root (file dir) dest mkdirs)))
(doseq [f files]
(copy+ (file root f) (dest (file root f)))))
from))
to))))
Or directly use the fs library available on Github.
Upvotes: 5