Created
January 14, 2015 05:54
-
-
Save zentrope/278fb61595d85351b584 to your computer and use it in GitHub Desktop.
file system utils
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 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