/
ClassPath.scala
267 lines (224 loc) · 7.02 KB
/
ClassPath.scala
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
package com.twitter.app
import com.twitter.finagle.util.loadServiceIgnoredPaths
import java.io.{IOException, File}
import java.net.{URISyntaxException, URLClassLoader, URI}
import java.nio.charset.MalformedInputException
import java.util.jar.{JarEntry, JarFile}
import scala.collection.mutable
import scala.collection.mutable.Builder
import scala.collection.JavaConverters._
import scala.io.Source
private[app] object ClassPath {
val IgnoredPackages = Set(
"apple/",
"ch/epfl/",
"com/apple/",
"com/oracle/",
"com/sun/",
"java/",
"javax/",
"scala/",
"sun/",
"sunw/"
)
sealed abstract class Info(path: String)
case class FlagInfo(path: String) extends Info(path) {
val className: String = {
val prefixed =
if (path.endsWith(".class")) path.dropRight(6)
else path
prefixed.replace('/', '.')
}
}
case class LoadServiceInfo(path: String, iface: String, lines: Seq[String]) extends Info(path)
}
/**
* Inspect and load the classpath. Inspired by Guava's ClassPath
* utility.
*
* @note This is not a generic facility, rather it is designed
* specifically to support GlobalFlag and LoadService.
*/
private[app] sealed abstract class ClassPath[CpInfo <: ClassPath.Info] {
protected def ignoredPackages: Set[String]
def browse(loader: ClassLoader): Seq[CpInfo] = {
val buf = Vector.newBuilder[CpInfo]
val seenUris = mutable.HashSet[URI]()
for ((uri, loader) <- getEntries(loader)) {
browseUri0(uri, loader, buf, seenUris)
seenUris += uri
}
buf.result
}
// package protected for testing
private[app] def getEntries(loader: ClassLoader): Seq[(URI, ClassLoader)] = {
val parent = Option(loader.getParent)
val ownURIs: Vector[(URI, ClassLoader)] = for {
urlLoader <- Vector(loader).collect {case u: URLClassLoader => u}
urls <- Option(urlLoader.getURLs()).toVector
url <- urls if url != null
} yield (url.toURI -> loader)
val p = parent.toSeq.flatMap(getEntries)
ownURIs ++ p
}
// package protected for testing
private[app] def browseUri(uri: URI, loader: ClassLoader, buf: Builder[CpInfo, Seq[CpInfo]]): Unit =
browseUri0(uri, loader, buf, mutable.Set[URI]())
private[this] def browseUri0(
uri: URI,
loader: ClassLoader,
buf: Builder[CpInfo, Seq[CpInfo]],
history: mutable.Set[URI]
): Unit = {
if (!history.contains(uri)) {
history.add(uri)
if (uri.getScheme != "file")
return
val f = new File(uri)
if (!(f.exists() && f.canRead))
return
if (f.isDirectory)
browseDir(f, loader, "", buf)
else
browseJar(f, loader, buf, history)
}
}
private[this] def browseDir(
dir: File,
loader: ClassLoader,
prefix: String,
buf: Builder[CpInfo, Seq[CpInfo]]
): Unit = {
if (ignoredPackages.contains(prefix))
return
for (f <- dir.listFiles)
if (f.isDirectory && f.canRead) {
browseDir(f, loader, prefix + f.getName + "/", buf)
}
else
processFile(prefix, f, buf)
}
protected def processFile(prefix: String, file: File, buf: Builder[CpInfo, Seq[CpInfo]]): Unit
private def browseJar(
file: File,
loader: ClassLoader,
buf: Builder[CpInfo, Seq[CpInfo]],
seenUris: mutable.Set[URI]
): Unit = {
val jarFile = try new JarFile(file)
catch {
case _: IOException => return // not a Jar file
}
try {
for (uri <- jarClasspath(file, jarFile.getManifest)) {
browseUri0(uri, loader, buf, seenUris)
}
for {
e <- jarFile.entries.asScala if !e.isDirectory
n = e.getName if !ignoredPackages.exists(p => n.startsWith(p))
} {
processJarEntry(jarFile, e, buf)
}
} finally {
try jarFile.close()
catch {
case _: IOException =>
}
}
}
protected def processJarEntry(
jarFile: JarFile,
entry: JarEntry,
buf: Builder[CpInfo, Seq[CpInfo]]
): Unit
private def jarClasspath(jarFile: File, manifest: java.util.jar.Manifest): Seq[URI] =
for {
m <- Option(manifest).toSeq
attr <- Option(m.getMainAttributes.getValue("Class-Path")).toSeq
el <- attr.split(" ").toSeq
uri <- uriFromJarClasspath(jarFile, el)
} yield uri
private def uriFromJarClasspath(jarFile: File, path: String): Option[URI] =
try {
val uri = new URI(path)
if (uri.isAbsolute)
Some(uri)
else
Some(new File(jarFile.getParentFile, path.replace('/', File.separatorChar)).toURI)
} catch {
case _: URISyntaxException => None
}
}
private[app] class FlagClassPath extends ClassPath[ClassPath.FlagInfo] {
protected def ignoredPackages: Set[String] =
ClassPath.IgnoredPackages
private[this] def isClass(name: String): Boolean =
name.endsWith(".class") && (name.endsWith("$.class") || !name.contains("$"))
protected def processFile(
prefix: String,
file: File,
buf: Builder[ClassPath.FlagInfo, Seq[ClassPath.FlagInfo]]
): Unit = {
val name = file.getName
if (isClass(name)) {
buf += ClassPath.FlagInfo(prefix + name)
}
}
protected def processJarEntry(
jarFile: JarFile,
entry: JarEntry,
buf: Builder[ClassPath.FlagInfo, Seq[ClassPath.FlagInfo]]
): Unit = {
val name = entry.getName
if (isClass(name)) {
buf += ClassPath.FlagInfo(name)
}
}
}
private[app] class LoadServiceClassPath extends ClassPath[ClassPath.LoadServiceInfo] {
protected def ignoredPackages: Set[String] =
ClassPath.IgnoredPackages ++ loadServiceIgnoredPaths()
private[this] def ifaceOfName(name: String): Option[String] =
if (!name.contains("META-INF")) None
else
name.split("/").takeRight(3) match {
case Array("META-INF", "services", iface) => Some(iface)
case _ => None
}
private[app] def readLines(source: Source): Seq[String] = {
try {
source.getLines().toVector.flatMap { line =>
val commentIdx = line.indexOf('#')
val end = if (commentIdx != -1) commentIdx else line.length
val str = line.substring(0, end).trim
if (str.isEmpty) Nil else Seq(str)
}
} catch {
case ex: MalformedInputException => Nil /* skip malformed files (e.g. non UTF-8) */
} finally {
source.close()
}
}
protected def processFile(
prefix: String,
file: File,
buf: Builder[ClassPath.LoadServiceInfo, Seq[ClassPath.LoadServiceInfo]]
): Unit = {
for (iface <- ifaceOfName(prefix + file.getName)) {
val source = Source.fromFile(file, "UTF-8")
val lines = readLines(source)
buf += ClassPath.LoadServiceInfo(prefix + file.getName, iface, lines)
}
}
protected def processJarEntry(
jarFile: JarFile,
entry: JarEntry,
buf: Builder[ClassPath.LoadServiceInfo, Seq[ClassPath.LoadServiceInfo]]
): Unit = {
for (iface <- ifaceOfName(entry.getName)) {
val source = Source.fromInputStream(jarFile.getInputStream(entry), "UTF-8")
val lines = readLines(source)
buf += ClassPath.LoadServiceInfo(entry.getName, iface, lines)
}
}
}