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
|
package mill
package scalalib
import java.io.File
import java.net.URLClassLoader
import java.util.Optional
import ammonite.ops._
import coursier.{Cache, Fetch, MavenRepository, Repository, Resolution, Module => CoursierModule}
import mill.define.Worker
import mill.eval.{PathRef, Result}
import mill.util.{Ctx}
import mill.util.Loose.OSet
import sbt.internal.inc._
import sbt.internal.util.{ConsoleOut, MainAppender}
import sbt.util.LogExchange
import xsbti.compile.{CompilerCache => _, FileAnalysisStore => _, ScalaInstance => _, _}
object CompilationResult {
implicit val jsonFormatter: upickle.default.ReadWriter[CompilationResult] = upickle.default.macroRW
}
// analysisFile is represented by Path, so we won't break caches after file changes
case class CompilationResult(analysisFile: Path, classes: PathRef)
object ZincWorker extends Worker[ZincWorker]{
def make() = new ZincWorker
}
class ZincWorker{
@volatile var scalaClassloaderCache = Option.empty[(Long, ClassLoader)]
@volatile var scalaInstanceCache = Option.empty[(Long, ScalaInstance)]
}
object Lib{
case class MockedLookup(am: File => Optional[CompileAnalysis]) extends PerClasspathEntryLookup {
override def analysis(classpathEntry: File): Optional[CompileAnalysis] =
am(classpathEntry)
override def definesClass(classpathEntry: File): DefinesClass =
Locate.definesClass(classpathEntry)
}
def grepJar(classPath: OSet[Path], s: String) = {
classPath
.find(_.toString.endsWith(s))
.getOrElse(throw new Exception("Cannot find " + s))
.toIO
}
def compileScala(zincWorker: ZincWorker,
scalaVersion: String,
sources: OSet[Path],
compileClasspath: OSet[Path],
compilerClasspath: OSet[Path],
pluginClasspath: OSet[Path],
compilerBridge: Path,
scalacOptions: Seq[String],
scalacPluginClasspath: OSet[Path],
javacOptions: Seq[String],
upstreamCompileOutput: Seq[CompilationResult])
(implicit ctx: Ctx): CompilationResult = {
val compileClasspathFiles = compileClasspath.map(_.toIO).toArray
val compilerJars = compilerClasspath.toArray.map(_.toIO)
val pluginJars = pluginClasspath.toArray.map(_.toIO)
val compilerClassloaderSig = compilerClasspath.map(p => p.toString().hashCode + p.mtime.toMillis).sum
val scalaInstanceSig =
compilerClassloaderSig + pluginClasspath.map(p => p.toString().hashCode + p.mtime.toMillis).sum
val compilerClassLoader = zincWorker.scalaClassloaderCache match{
case Some((k, v)) if k == compilerClassloaderSig => v
case _ =>
val classloader = new URLClassLoader(compilerJars.map(_.toURI.toURL), null)
zincWorker.scalaClassloaderCache = Some((compilerClassloaderSig, classloader))
classloader
}
val scalaInstance = zincWorker.scalaInstanceCache match{
case Some((k, v)) if k == scalaInstanceSig => v
case _ =>
val scalaInstance = new ScalaInstance(
version = scalaVersion,
loader = new URLClassLoader(pluginJars.map(_.toURI.toURL), compilerClassLoader),
libraryJar = grepJar(compilerClasspath, s"scala-library-$scalaVersion.jar"),
compilerJar = grepJar(compilerClasspath, s"scala-compiler-$scalaVersion.jar"),
allJars = compilerJars ++ pluginJars,
explicitActual = None
)
zincWorker.scalaInstanceCache = Some((scalaInstanceSig, scalaInstance))
scalaInstance
}
mkdir(ctx.dest)
val ic = new sbt.internal.inc.IncrementalCompilerImpl()
val logger = {
val consoleAppender = MainAppender.defaultScreen(ConsoleOut.printStreamOut(
ctx.log.outputStream
))
val l = LogExchange.logger("Hello")
LogExchange.unbindLoggerAppenders("Hello")
LogExchange.bindLoggerAppenders("Hello", (consoleAppender -> sbt.util.Level.Info) :: Nil)
l
}
def analysisMap(f: File): Optional[CompileAnalysis] = {
if (f.isFile) {
Optional.empty[CompileAnalysis]
} else {
upstreamCompileOutput.collectFirst {
case CompilationResult(zincPath, classFiles) if classFiles.path.toNIO == f.toPath =>
FileAnalysisStore.binary(zincPath.toIO).get().map[CompileAnalysis](_.getAnalysis)
}.getOrElse(Optional.empty[CompileAnalysis])
}
}
val lookup = MockedLookup(analysisMap)
val zincFile = ctx.dest / 'zinc
val classesDir = ctx.dest / 'classes
val zincIOFile = zincFile.toIO
val classesIODir = classesDir.toIO
val store = FileAnalysisStore.binary(zincIOFile)
val newResult = ic.compile(
ic.inputs(
classpath = classesIODir +: compileClasspathFiles,
sources = sources.filter(_.toIO.exists()).flatMap(ls.rec).filter(x => x.isFile && x.ext == "scala").map(_.toIO).toArray,
classesDirectory = classesIODir,
scalacOptions = (scalacPluginClasspath.map(jar => s"-Xplugin:${jar}") ++ scalacOptions).toArray,
javacOptions = javacOptions.toArray,
maxErrors = 10,
sourcePositionMappers = Array(),
order = CompileOrder.Mixed,
compilers = ic.compilers(
scalaInstance,
ClasspathOptionsUtil.boot,
None,
ZincUtil.scalaCompiler(scalaInstance, compilerBridge.toIO)
),
setup = ic.setup(
lookup,
skip = false,
zincIOFile,
new FreshCompilerCache,
IncOptions.of(),
new ManagedLoggedReporter(10, logger),
None,
Array()
),
pr = {
val prev = store.get()
PreviousResult.of(prev.map(_.getAnalysis), prev.map(_.getMiniSetup))
}
),
logger = logger
)
store.set(
AnalysisContents.create(
newResult.analysis(),
newResult.setup()
)
)
CompilationResult(zincFile, PathRef(classesDir))
}
def resolveDependencies(repositories: Seq[Repository],
scalaVersion: String,
scalaBinaryVersion: String,
deps: TraversableOnce[Dep],
sources: Boolean = false): Result[OSet[PathRef]] = {
val flattened = deps.map{
case Dep.Java(dep) => dep
case Dep.Scala(dep) =>
dep.copy(module = dep.module.copy(name = dep.module.name + "_" + scalaBinaryVersion))
case Dep.Point(dep) =>
dep.copy(module = dep.module.copy(name = dep.module.name + "_" + scalaVersion))
}.toSet
val start = Resolution(flattened)
val fetch = Fetch.from(repositories, Cache.fetch())
val resolution = start.process.run(fetch).unsafePerformSync
val errs = resolution.metadataErrors
if(errs.nonEmpty) {
val header =
s"""|
|Resolution failed for ${errs.length} modules:
|--------------------------------------------
|""".stripMargin
val errLines = errs.map {
case ((module, vsn), errMsgs) => s" ${module.trim}:$vsn \n\t" + errMsgs.mkString("\n\t")
}.mkString("\n")
val msg = header + errLines + "\n"
Result.Failure(msg)
} else {
val sourceOrJar =
if (sources) resolution.classifiersArtifacts(Seq("sources"))
else resolution.artifacts
val localArtifacts: Seq[File] = scalaz.concurrent.Task
.gatherUnordered(sourceOrJar.map(Cache.file(_).run))
.unsafePerformSync
.flatMap(_.toOption)
OSet.from(
localArtifacts.map(p => PathRef(Path(p), quick = true)).filter(_.path.ext == "jar")
)
}
}
def scalaCompilerIvyDeps(scalaVersion: String) = OSet[Dep](
Dep.Java("org.scala-lang", "scala-compiler", scalaVersion),
Dep.Java("org.scala-lang", "scala-reflect", scalaVersion)
)
def scalaRuntimeIvyDeps(scalaVersion: String) = OSet[Dep](
Dep.Java("org.scala-lang", "scala-library", scalaVersion)
)
def compilerBridgeIvyDep(scalaVersion: String) =
Dep.Point(coursier.Dependency(coursier.Module("com.lihaoyi", "mill-bridge"), "0.1", transitive = false))
val DefaultShellScript: Seq[String] = Seq(
"#!/usr/bin/env sh",
"exec java -jar \"$0\" \"$@\""
)
}
|