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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
|
package mill.eval
import java.net.URLClassLoader
import mill.util.Router.EntryPoint
import ammonite.ops._
import ammonite.runtime.SpecialClassLoader
import mill.define.{Ctx => _, _}
import mill.eval.Result.OuterStack
import mill.util
import mill.util._
import mill.util.Strict.Agg
import scala.collection.mutable
import scala.util.control.NonFatal
case class Labelled[T](task: NamedTask[T],
segments: Segments){
def format = task match{
case t: Target[T] => Some(t.readWrite.asInstanceOf[upickle.default.ReadWriter[T]])
case _ => None
}
def writer = task match{
case t: mill.define.Command[T] => Some(t.writer.asInstanceOf[upickle.default.Writer[T]])
case t: Target[T] => Some(t.readWrite.asInstanceOf[upickle.default.ReadWriter[T]])
case _ => None
}
}
case class Evaluator[T](outPath: Path,
externalOutPath: Path,
rootModule: mill.define.BaseModule,
discover: Discover[T],
log: Logger,
classLoaderSig: Seq[(Path, Long)] = Evaluator.classLoaderSig,
workerCache: mutable.Map[Segments, (Int, Any)] = mutable.Map.empty){
def evaluate(goals: Agg[Task[_]]): Evaluator.Results = {
mkdir(outPath)
val transitive = Graph.transitiveTargets(goals)
val topoSorted = Graph.topoSorted(transitive)
val sortedGroups = Graph.groupAroundImportantTargets(topoSorted){
case t: NamedTask[Any] =>
val segments = t.ctx.segments
val finalTaskOverrides = t match{
case t: Target[_] =>
rootModule.millInternal.segmentsToTargets.get(segments).fold(0)(_.ctx.overrides)
case c: mill.define.Command[_] =>
def findMatching(cls: Class[_]): Option[Seq[(Int, EntryPoint[_])]] = {
discover.value.get(cls) match{
case Some(v) => Some(v)
case None =>
cls.getSuperclass match{
case null => None
case superCls => findMatching(superCls)
}
}
}
findMatching(c.cls) match{
case Some(v) =>
v.find(_._2.name == c.ctx.segment.pathSegments.head).get._1
// For now we don't properly support overrides for external modules
// that do not appear in the Evaluator's main Discovered listing
case None => 0
}
case c: mill.define.Worker[_] => 0
}
val additional =
if (finalTaskOverrides == t.ctx.overrides) Nil
else Seq(Segment.Label("overriden"), Segment.Label(t.ctx.enclosing))
Right(Labelled(t, segments ++ additional))
case t if goals.contains(t) => Left(t)
}
val evaluated = new Agg.Mutable[Task[_]]
val results = mutable.LinkedHashMap.empty[Task[_], Result[(Any, Int)]]
for (((terminal, group), i) <- sortedGroups.items().zipWithIndex){
// Increment the counter message by 1 to go from 1/10 to 10/10 instead of 0/10 to 9/10
val counterMsg = (i+1) + "/" + sortedGroups.keyCount
val (newResults, newEvaluated) = evaluateGroupCached(terminal, group, results, counterMsg)
for(ev <- newEvaluated){
evaluated.append(ev)
}
for((k, v) <- newResults) {
results.put(k, v)
}
}
val failing = new util.MultiBiMap.Mutable[Either[Task[_], Labelled[_]], Result.Failing[_]]
for((k, vs) <- sortedGroups.items()){
failing.addAll(
k,
vs.items.flatMap(results.get).collect{case f: Result.Failing[_] => f.map(_._1)}
)
}
Evaluator.Results(
goals.indexed.map(results(_).map(_._1)),
evaluated,
transitive,
failing,
results.map{case (k, v) => (k, v.map(_._1))}
)
}
def evaluateGroupCached(terminal: Either[Task[_], Labelled[_]],
group: Agg[Task[_]],
results: collection.Map[Task[_], Result[(Any, Int)]],
counterMsg: String): (collection.Map[Task[_], Result[(Any, Int)]], Seq[Task[_]]) = {
val externalInputs = group.items.flatMap(_.inputs).filter(!group.contains(_)).toVector
val inputsHash =
externalInputs.map(results(_).map(_._2)).hashCode +
group.toIterator.map(_.sideHash).toVector.hashCode() +
classLoaderSig.hashCode()
terminal match{
case Left(task) =>
evaluateGroup(
group,
results,
inputsHash,
paths = None,
maybeTargetLabel = None,
counterMsg = counterMsg
)
case Right(labelledNamedTask) =>
val paths = Evaluator.resolveDestPaths(
if (!labelledNamedTask.task.ctx.external) outPath else externalOutPath,
labelledNamedTask.segments
)
mkdir(paths.out)
val cached = for{
json <- scala.util.Try(upickle.json.read(read(paths.meta))).toOption
(cachedHash, terminalResult) <- scala.util.Try(upickle.default.readJs[(Int, upickle.Js.Value)](json)).toOption
if cachedHash == inputsHash
reader <- labelledNamedTask.format
parsed <- reader.read.lift(terminalResult)
} yield parsed
val workerCached = labelledNamedTask.task.asWorker
.flatMap{w => workerCache.get(w.ctx.segments)}
.collect{case (`inputsHash`, v) => v}
workerCached.map((_, inputsHash)) orElse cached.map(p => (p, p.hashCode())) match{
case Some((v, hashCode)) =>
val newResults = mutable.LinkedHashMap.empty[Task[_], Result[(Any, Int)]]
newResults(labelledNamedTask.task) = Result.Success((v, hashCode))
(newResults, Nil)
case _ =>
val Seq(first, rest @_*) = labelledNamedTask.segments.value
val msgParts = Seq(first.asInstanceOf[Segment.Label].value) ++ rest.map{
case Segment.Label(s) => "." + s
case Segment.Cross(s) => "[" + s.mkString(",") + "]"
}
if (labelledNamedTask.task.flushDest) rm(paths.dest)
val (newResults, newEvaluated) = evaluateGroup(
group,
results,
inputsHash,
paths = Some(paths),
maybeTargetLabel = Some(msgParts.mkString),
counterMsg = counterMsg
)
newResults(labelledNamedTask.task) match{
case Result.Failure(_, Some((v, hashCode))) =>
labelledNamedTask.task.asWorker match{
case Some(w) =>
workerCache(w.ctx.segments) = (inputsHash, v)
case None =>
val terminalResult = labelledNamedTask
.writer
.asInstanceOf[Option[upickle.default.Writer[Any]]]
.map(_.write(v))
for(t <- terminalResult){
write.over(paths.meta, upickle.default.write(inputsHash -> t, indent = 4))
}
}
case Result.Success((v, hashCode)) =>
labelledNamedTask.task.asWorker match{
case Some(w) =>
workerCache(w.ctx.segments) = (inputsHash, v)
case None =>
val terminalResult = labelledNamedTask
.writer
.asInstanceOf[Option[upickle.default.Writer[Any]]]
.map(_.write(v))
for(t <- terminalResult){
write.over(paths.meta, upickle.default.write(inputsHash -> t, indent = 4))
}
}
case _ =>
// Wipe out any cached meta.json file that exists, so
// a following run won't look at the cached metadata file and
// assume it's associated with the possibly-borked state of the
// destPath after an evaluation failure.
rm(paths.meta)
}
(newResults, newEvaluated)
}
}
}
def evaluateGroup(group: Agg[Task[_]],
results: collection.Map[Task[_], Result[(Any, Int)]],
inputsHash: Int,
paths: Option[Evaluator.Paths],
maybeTargetLabel: Option[String],
counterMsg: String) = {
val newEvaluated = mutable.Buffer.empty[Task[_]]
val newResults = mutable.LinkedHashMap.empty[Task[_], Result[(Any, Int)]]
val nonEvaluatedTargets = group.indexed.filterNot(results.contains)
maybeTargetLabel.foreach { targetLabel =>
val inputResults = for {
target <- nonEvaluatedTargets
item <- target.inputs.filterNot(group.contains)
} yield results(item).map(_._1)
val logRun = inputResults.forall(_.isInstanceOf[Result.Success[_]])
if(logRun) { log.ticker(s"[$counterMsg] $targetLabel ") }
}
val multiLogger = resolveLogger(paths.map(_.log))
var usedDest = Option.empty[(Task[_], Array[StackTraceElement])]
for (task <- nonEvaluatedTargets) {
val currentStack = new Exception().getStackTrace
newEvaluated.append(task)
val targetInputValues = task.inputs
.map(x => newResults.getOrElse(x, results(x)))
.collect{ case Result.Success((v, hashCode)) => v }
val res =
if (targetInputValues.length != task.inputs.length) Result.Skipped
else {
val args = new Ctx(
targetInputValues.toArray[Any],
() => usedDest match{
case Some((earlierTask, earlierStack)) if earlierTask != task =>
val inner = new Exception("Earlier usage of `dest`")
inner.setStackTrace(earlierStack)
throw new Exception(
"`dest` can only be used in one place within each Target[T]",
inner
)
case _ =>
usedDest = Some((
task,
new Exception().getStackTrace.dropRight(currentStack.length)
))
paths match{
case Some(dest) =>
mkdir(dest.dest)
dest.dest
case None =>
throw new Exception("No `dest` folder available here")
}
},
multiLogger
)
val out = System.out
val err = System.err
try{
System.setErr(multiLogger.errorStream)
System.setOut(multiLogger.outputStream)
Console.withOut(multiLogger.outputStream){
Console.withErr(multiLogger.errorStream){
task.evaluate(args)
}
}
}catch{ case NonFatal(e) =>
Result.Exception(e, new OuterStack(currentStack))
}finally{
System.setErr(err)
System.setOut(out)
}
}
newResults(task) = for(v <- res) yield {
(v,
if (task.isInstanceOf[Worker[_]]) inputsHash
else v.hashCode
)
}
}
multiLogger.close()
(newResults, newEvaluated)
}
def resolveLogger(logPath: Option[Path]): Logger = logPath match{
case None => log
case Some(path) =>
rm(path)
MultiLogger(log.colored, log, FileLogger(log.colored, path))
}
}
object Evaluator{
// This needs to be a ThreadLocal because we need to pass it into the body of
// the TargetScopt#read call, which does not accept additional parameters.
// Until we migrate our CLI parsing off of Scopt (so we can pass the BaseModule
// in directly) we are forced to pass it in via a ThreadLocal
val currentEvaluator = new ThreadLocal[mill.eval.Evaluator[_]]
case class Paths(out: Path,
dest: Path,
meta: Path,
log: Path)
def makeSegmentStrings(segments: Segments) = segments.value.flatMap{
case Segment.Label(s) => Seq(s)
case Segment.Cross(values) => values.map(_.toString)
}
def resolveDestPaths(workspacePath: Path, segments: Segments): Paths = {
val segmentStrings = makeSegmentStrings(segments)
val targetPath = workspacePath / segmentStrings
Paths(targetPath, targetPath / 'dest, targetPath / "meta.json", targetPath / 'log)
}
// check if the build itself has changed
def classLoaderSig = Thread.currentThread().getContextClassLoader match {
case scl: SpecialClassLoader => scl.classpathSignature
case ucl: URLClassLoader => SpecialClassLoader.initialClasspathSignature(ucl)
case _ => Nil
}
case class Results(rawValues: Seq[Result[Any]],
evaluated: Agg[Task[_]],
transitive: Agg[Task[_]],
failing: MultiBiMap[Either[Task[_], Labelled[_]], Result.Failing[_]],
results: collection.Map[Task[_], Result[Any]]){
def values = rawValues.collect{case Result.Success(v) => v}
}
}
|