|
1 |
| -(ns orchard.util.io) |
| 1 | +(ns orchard.util.io |
| 2 | + "Utility functions for dealing with file system objects, and in/out streams." |
| 3 | + (:require |
| 4 | + [clojure.java.io :as io]) |
| 5 | + (:import |
| 6 | + (java.io File) |
| 7 | + (java.net URL JarURLConnection))) |
2 | 8 |
|
3 | 9 | (defn wrap-silently
|
4 | 10 | "Middleware that executes `(f)` without printing to `System/out` or `System/err`.
|
|
22 | 28 | (System/setOut old-out))
|
23 | 29 | (when (= ps System/err) ;; `System/err` may have changed in the meantime (in face of concurrency)
|
24 | 30 | (System/setErr old-err)))))))
|
| 31 | + |
| 32 | +(defn url-protocol |
| 33 | + "Get the URL protocol as a string, e.g. http, file, jar." |
| 34 | + [^java.net.URL url] |
| 35 | + (.getProtocol url)) |
| 36 | + |
| 37 | +(defn url-to-file-within-archive? |
| 38 | + "Does this URL point to a file inside a jar (or zip) archive. |
| 39 | + i.e. does it use the jar: protocol." |
| 40 | + [^java.net.URL url] |
| 41 | + (= "jar" (url-protocol url))) |
| 42 | + |
| 43 | +(defn resource-jarfile |
| 44 | + "Given a jar:file:...!/... URL, return the location of the jar file on the |
| 45 | + filesystem. Returns nil on any other URL." |
| 46 | + ^File [^URL jar-resource] |
| 47 | + (assert (= "jar" (url-protocol jar-resource))) |
| 48 | + (let [^JarURLConnection conn (.openConnection jar-resource) |
| 49 | + inner-url (.getJarFileURL conn)] |
| 50 | + (when (= "file" (url-protocol inner-url)) |
| 51 | + (io/as-file inner-url)))) |
| 52 | + |
| 53 | +(defn resource-artifact |
| 54 | + "Return the File from which the given resource URL would be loaded. |
| 55 | +
|
| 56 | + For `file:` URLs returns the location of the resource itself, for |
| 57 | + `jar:..!/...` URLs returns the location of the archive containing the |
| 58 | + resource. Returns a fully qualified File, even when the URL is relative. |
| 59 | + Throws when the URL is not a `file:` or `jar:` URL." |
| 60 | + ^File [^java.net.URL resource] |
| 61 | + (let [protocol (url-protocol resource)] |
| 62 | + (case protocol |
| 63 | + "file" |
| 64 | + (io/as-file resource) |
| 65 | + "jar" |
| 66 | + (resource-jarfile resource) |
| 67 | + #_else |
| 68 | + (throw (ex-info (str "URLs with a " protocol |
| 69 | + " protocol can't be situated on the filesystem.") |
| 70 | + {:resource resource}))))) |
| 71 | + |
| 72 | +(defprotocol LastModifiedTime |
| 73 | + (last-modified-time [this] |
| 74 | + "Return the last modified time of a File or resource URL.")) |
| 75 | + |
| 76 | +(extend-protocol LastModifiedTime |
| 77 | + java.net.URL |
| 78 | + (last-modified-time [this] |
| 79 | + (last-modified-time (resource-artifact this))) |
| 80 | + java.io.File |
| 81 | + (last-modified-time [this] |
| 82 | + (.lastModified this))) |
0 commit comments