Skip to content

Instantly share code, notes, and snippets.

@zentrope
Created January 14, 2015 05:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zentrope/278fb61595d85351b584 to your computer and use it in GitHub Desktop.
Save zentrope/278fb61595d85351b584 to your computer and use it in GitHub Desktop.
file system utils
(ns lib.fs
;;
;; File system utilities
;;
(:require
[clojure.string :refer [lower-case join trim]]
[clojure.java.io :as io])
(:import
[java.util.zip ZipInputStream]))
(defn path->
"Given a vector of strings, return an OS specific path."
[& parts]
(->> (map trim parts)
(join java.io.File/separator)))
(defn exists?
"Does the given file exist?"
[file]
(.exists (io/as-file file)))
(defn delete-file!
"Delete the file if it exists."
[file]
(when (.exists file)
(io/delete-file file)))
(defn copy-file!
"Copy a file from one location to another."
[source target]
(io/copy (io/file source) (io/file target)))
(defn backup-file!
"Create a copy of a file with .bak, or .bak.1, .2, etc."
[source]
(let [file (io/file source)]
(loop [count 1
target (str (.getPath file) ".bak")]
(if (exists? target)
(recur (inc count) (str (.getPath file) ".bak." count))
(copy-file! source target)))))
(defn delete-directory-recursively!
"Delete the directory and everything it contains."
[base-dir]
(doseq [file (reverse (file-seq (io/file base-dir)))]
(delete-file! file)))
(defn download!
[url target]
(let [con (-> url java.net.URL. .openConnection)
buf (byte-array 2048)]
(with-open [in (io/input-stream (.getInputStream con))
out (io/output-stream (io/file target))]
(io/copy in out))
(.disconnect con)))
(defn unzip!
[file destination]
(let [buf (byte-array 10240)]
(with-open [in (ZipInputStream. (io/input-stream file))]
(loop [ze (.getNextEntry in)]
(when-not (nil? ze)
(let [target (io/file destination (.getName ze))]
(when (.isDirectory ze)
(.mkdirs target))
(when (not (.isDirectory ze))
(io/copy in target)))
(recur (.getNextEntry in)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment