-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.clj
68 lines (57 loc) · 1.79 KB
/
file.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
(ns monkey.ci.storage.file
"File storage implementation. Useful for local or develop runs. It stores all
information in local .edn files."
(:require [clojure
[edn :as edn]
[string :as cs]]
[clojure.java.io :as io]
[clojure.tools.logging :as log]
[monkey.ci
[protocols :as p]
[storage :as s]
[utils :as u]])
(:import [java.io File PushbackReader]))
(defn- ensure-dir-exists
"Given a path, creates the parent directories if they do not exist already."
[^File f]
(let [p (.getParentFile f)]
(if-not (.exists p)
(.mkdirs p)
true)))
(def ext ".edn")
(defn- ->file [dir sid]
(apply io/file dir (concat (butlast sid) [(str (last sid) ext)])))
(defn- name-without-ext [f]
(let [n (.getName f)]
(if (.isFile f)
(cond-> n
(cs/ends-with? n ext) (subs 0 (- (count n) (count ext))))
n)))
(defrecord FileStorage [dir]
p/Storage
(read-obj [_ loc]
(let [f (->file dir loc)]
(log/trace "Checking for file at" f)
(when (.exists f)
(with-open [r (PushbackReader. (io/reader f))]
(edn/read r)))))
(write-obj [_ loc obj]
(let [f (->file dir loc)]
(when (ensure-dir-exists f)
(spit f (pr-str obj))
loc)))
(obj-exists? [_ loc]
(.exists (->file dir loc)))
(delete-obj [_ loc]
(.delete (->file dir loc)))
(list-obj [_ loc]
(->> (.listFiles (apply io/file dir loc))
(seq)
(map name-without-ext))))
(defn make-file-storage [dir]
(log/debug "File storage location:" dir)
(-> (->FileStorage dir)
(assoc :cached? true)))
(defmethod s/make-storage :file [{conf :storage}]
(log/info "Using file storage with configuration:" conf)
(make-file-storage (u/abs-path (:dir conf))))