-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.clj
219 lines (192 loc) · 8.43 KB
/
utils.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
(ns conjure-deps.compliment.v0v3v9.compliment.utils
"Functions and utilities for source implementations."
(:import java.io.File java.nio.file.Files
(java.util.jar JarFile JarEntry)
java.util.function.Consumer))
(def ^:dynamic *extra-metadata*
"Signals to downstream sources which additional information about completion
candidates they should attach . Should be a set of keywords."
nil)
(defn fuzzy-matches?
"Tests if symbol matches the prefix when symbol is split into parts on
separator."
[prefix, ^String symbol, separator]
(when (or (.startsWith symbol prefix) (= (first prefix) (first symbol)))
(loop [pre (rest prefix), sym (rest symbol), skipping false]
(cond (empty? pre) true
(empty? sym) false
skipping (if (= (first sym) separator)
(recur (if (= (first pre) separator)
(rest pre) pre)
(rest sym) false)
(recur pre (rest sym) true))
(= (first pre) (first sym)) (recur (rest pre) (rest sym) false)
:else (recur pre (rest sym) (not= (first sym) separator))))))
(defn fuzzy-matches-no-skip?
"Tests if symbol matches the prefix where separator? checks whether character
is a separator. Unlike `fuzzy-matches?` requires separator characters to be
present in prefix."
[prefix, ^String symbol, separator?]
(when (or (.startsWith symbol prefix) (= (first prefix) (first symbol)))
(loop [pre prefix, sym symbol, skipping false]
(cond (empty? pre) true
(empty? sym) false
skipping (if (separator? (first sym))
(recur pre sym false)
(recur pre (rest sym) true))
(= (first pre) (first sym)) (recur (rest pre) (rest sym) false)
:else (recur pre (rest sym) true)))))
(defn resolve-class
"Tries to resolve a classname from the given symbol, or returns nil
if classname can't be resolved."
[ns sym]
(when-let [val (try (ns-resolve ns sym)
(catch ClassNotFoundException ex nil))]
(when (class? val) val)))
(defn resolve-namespace
"Tries to resolve a namespace from the given symbol, either from a
fully qualified name or an alias in the given namespace."
[sym ns]
(or ((ns-aliases ns) sym) (find-ns sym)))
(defmacro ^{:doc "Defines a memoized function."
:forms '([name doc-string? [params*] body])}
defmemoized [name & fdecl]
(let [[doc & fdecl] (if (string? (first fdecl))
[(first fdecl) (rest fdecl)]
["" fdecl])]
`(def ~name ~doc (memoize (fn ~@fdecl)))))
(def primitive-cache (atom {}))
(defmacro cache-last-result
"If cache for `name` is absent, or `key` doesn't match the key in the cache,
calculate `v` and return it. Else return value from cache."
{:style/indent 2}
[name key value]
(let [ksym ()]
`(let [name# ~name
key# ~key
[cached-key# cached-value#] (@primitive-cache name#)]
(if (and (contains? @primitive-cache name#) (= cached-key# key#))
cached-value#
(let [value# ~value]
(swap! primitive-cache assoc name# [key# value#])
value#)))))
(defn flush-caches
"Removes all cached values, forcing functions that depend on
`cache-last-result` to recalculate."
[]
(reset! primitive-cache {}))
;; Classpath inspection
(def android-vm?
"Signifies if the application is running on Android."
(.contains ^String (System/getProperty "java.vendor") "Android"))
(def jdk9+?
"Signifies if the application is running on JDK 9 or higher."
(try (let [major (re-find #"^\d+" (System/getProperty "java.version"))
major (Integer/parseInt major)]
(>= major 9))
(catch Exception _ false)))
(defn- classpath
"Returns a sequence of File objects of the elements on the classpath."
[]
(if android-vm?
()
(mapcat #(.split (or (System/getProperty %) "") File/pathSeparator)
["sun.boot.class.path" "java.ext.dirs" "java.class.path"
;; This is where Boot keeps references to dependencies.
"fake.class.path"])))
(defn- symlink?
"Checks if the given file is a symlink."
[^File f]
(Files/isSymbolicLink (.toPath f)))
(defn- file-seq-nonr
"A tree seq on java.io.Files, doesn't resolve symlinked directories to avoid
infinite sequence resulting from recursive symlinked directories."
[dir]
(tree-seq
(fn [^File f] (and (.isDirectory f) (not (symlink? f))))
(fn [^File d] (seq (.listFiles d)))
dir))
(defn- list-files
"Given a path (either a jar file, directory with classes or directory with
paths) returns all files under that path."
[^String path, scan-jars?]
(cond (.endsWith path "/*")
(for [^File jar (.listFiles (File. path))
:when (.endsWith ^String (.getName jar) ".jar")
file (list-files (.getPath jar) scan-jars?)]
file)
(.endsWith path ".jar")
(if scan-jars?
(try (for [^JarEntry entry (enumeration-seq (.entries (JarFile. path)))
:when (not (.isDirectory entry))]
(.getName entry))
(catch Exception e))
())
(= path "") ()
:else
(for [^File file (file-seq-nonr (File. path))
:when (not (.isDirectory file))]
(.replace ^String (.getPath file) path ""))))
(defn- list-jdk9-base-classfiles
"Because on JDK9+ the classfiles are stored not in rt.jar on classpath, but in
modules, we have to do extra work to extract them."
[]
;; We have to do a lot of manual reflection here because otherwise JDK9+ barks
;; at us or illegally accessing internal classes. Bah.
(let [mf-class (Class/forName "java.lang.module.ModuleFinder")
of-system (.getMethod mf-class "ofSystem" (into-array Class []))
mfinder (.invoke of-system nil (object-array 0))
mrefs (.findAll mfinder)
mref-class (Class/forName "java.lang.module.ModuleReference")
open-method (.getMethod mref-class "open" (into-array Class []))
classes (transient [])
consumer (reify Consumer (accept [_ v] (conj! classes v)))]
(doseq [mref mrefs
:let [mrdr (.invoke open-method mref (object-array 0))
^java.util.stream.Stream stream (.list mrdr)]]
(.forEach stream consumer)
(.close mrdr))
(persistent! classes)))
(defn- all-files-on-classpath
"Given a list of files on the classpath, returns the list of all files,
including those located inside jar files."
[classpath]
(cache-last-result ::all-files-on-classpath classpath
(cond-> (vec (mapcat #(list-files % true) classpath))
jdk9+? (into (list-jdk9-base-classfiles)))))
(defn classes-on-classpath
"Returns a map of all classes that can be located on the classpath. Key
represent the root package of the class, and value is a list of all classes
for that package."
[]
(let [classpath (classpath)]
(cache-last-result ::classes-on-classpath classpath
(->> (for [^String file (all-files-on-classpath classpath)
:when (and (.endsWith file ".class") (not (.contains file "__"))
(not (.contains file "$")))]
(.. (if (.startsWith file File/separator)
(.substring file 1) file)
(replace ".class" "") (replace File/separator ".")))
(group-by #(subs % 0 (max (.indexOf ^String % ".") 0)))))))
(defn namespaces-on-classpath
"Returns the list of all Clojure namespaces obtained by classpath scanning."
[]
(let [classpath (classpath)]
(cache-last-result ::namespaces-on-classpath classpath
(set (for [^String file (all-files-on-classpath classpath)
:when (and (.endsWith file ".clj")
(not (.startsWith file "META-INF")))
:let [[_ ^String nsname] (re-matches #"[^\w]?(.+)\.clj" file)]
:when nsname]
(.. nsname (replace File/separator ".") (replace "_" "-")))))))
(defn project-resources
"Returns a list of all non-code files in the current project."
[]
(let [classpath (classpath)]
(cache-last-result ::project-resources classpath
(for [path classpath
^String file (list-files path false)
:when (not (or (empty? file) (.endsWith file ".clj")
(.endsWith file ".jar") (.endsWith file ".class")))]
(if (.startsWith file File/separator)
(.substring file 1) file)))))