-
-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
RoutesCompiler.scala
244 lines (207 loc) · 9.22 KB
/
RoutesCompiler.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
/*
* Copyright (C) from 2022 The Play Framework Contributors <https://github.com/playframework>, 2011-2021 Lightbend Inc. <https://www.lightbend.com>
*/
package play.sbt.routes
import java.util.Optional
import scala.collection.mutable
import sbt._
import sbt.Keys._
import com.typesafe.sbt.web.incremental._
import play.api.PlayException
import play.core.PlayVersion
import play.routes.compiler.RoutesCompilationError
import play.routes.compiler.RoutesCompiler.GeneratedSource
import play.routes.compiler.RoutesCompiler.RoutesCompilerTask
import play.routes.compiler.RoutesGenerator
import xsbti.Position
object RoutesKeys {
val routesCompilerTasks = TaskKey[Seq[RoutesCompilerTask]]("playRoutesTasks", "The routes files to compile")
val routes = TaskKey[Seq[File]]("playRoutes", "Compile the routes files")
val routesImport = SettingKey[Seq[String]]("playRoutesImports", "Imports for the router")
val routesGenerator = SettingKey[RoutesGenerator]("playRoutesGenerator", "The routes generator")
val generateReverseRouter = SettingKey[Boolean](
"playGenerateReverseRouter",
"Whether the reverse router should be generated. Setting to false may reduce compile times if it's not needed."
)
val namespaceReverseRouter = SettingKey[Boolean](
"playNamespaceReverseRouter",
"Whether the reverse router should be namespaced. Useful if you have many routers that use the same actions."
)
/**
* This class is used to avoid infinite recursions when configuring aggregateReverseRoutes,
* since it makes the ProjectReference a thunk.
*/
class LazyProjectReference(ref: => ProjectReference) {
def project: ProjectReference = ref
}
object LazyProjectReference {
import scala.language.implicitConversions
implicit def fromProjectReference(ref: => ProjectReference): LazyProjectReference = new LazyProjectReference(ref)
implicit def fromProject(project: => Project): LazyProjectReference = new LazyProjectReference(project)
}
val aggregateReverseRoutes = SettingKey[Seq[LazyProjectReference]](
"playAggregateReverseRoutes",
"A list of projects that reverse routes should be aggregated from."
)
val InjectedRoutesGenerator = play.routes.compiler.InjectedRoutesGenerator
}
object RoutesCompiler extends AutoPlugin {
import RoutesKeys._
override def trigger = noTrigger
val autoImport = RoutesKeys
override def projectSettings =
defaultSettings ++
inConfig(Compile)(routesSettings) ++
inConfig(Test)(routesSettings)
def routesSettings = Seq(
routes / sources := Nil,
routesCompilerTasks := Def.taskDyn {
val generateReverseRouterValue = generateReverseRouter.value
val namespaceReverseRouterValue = namespaceReverseRouter.value
val sourcesInRoutes = (routes / sources).value
val routesImportValue = routesImport.value
// Aggregate all the routes file tasks that we want to compile the reverse routers for.
aggregateReverseRoutes.value
.map { agg => agg.project / configuration.value / routesCompilerTasks }
.join
.map { (aggTasks: Seq[Seq[RoutesCompilerTask]]) =>
// Aggregated tasks need to have forwards router compilation disabled and reverse router compilation enabled.
val reverseRouterTasks = aggTasks.flatten.map { task =>
task.copy(forwardsRouter = false, reverseRouter = true)
}
// Find the routes compile tasks for this project
val thisProjectTasks = sourcesInRoutes.map { file =>
RoutesCompilerTask(
file,
routesImportValue,
forwardsRouter = true,
reverseRouter = generateReverseRouterValue,
namespaceReverseRouter = namespaceReverseRouterValue
)
}
thisProjectTasks ++ reverseRouterTasks
}
}.value,
Defaults.ConfigGlobal / watchSources ++= (routes / sources).value,
routes / target := crossTarget.value / "routes" / Defaults.nameForSrc(configuration.value.name),
routes := compileRoutesFiles.value,
sourceGenerators += Def.task(routes.value).taskValue,
managedSourceDirectories += (routes / target).value
)
def defaultSettings = Seq(
routesImport := Nil,
aggregateReverseRoutes := Nil,
// Generate reverse router defaults to true if this project is not aggregated by any of the projects it depends on
// aggregateReverseRoutes projects. Otherwise, it will be false, since another project will be generating the
// reverse router for it.
generateReverseRouter := Def.settingDyn {
val projectRef = thisProjectRef.value
val dependencies = buildDependencies.value.classpathTransitiveRefs(projectRef)
// Go through each dependency of this project
dependencies
.map { dep =>
// Get the aggregated reverse routes projects for the dependency, if defined
Def.optional(dep / aggregateReverseRoutes)(_.map(_.map(_.project)).getOrElse(Nil))
}
.join
.apply { (aggregated: Seq[Seq[ProjectReference]]) =>
val localProject = LocalProject(projectRef.project)
// Return false if this project is aggregated by one of our dependencies
!aggregated.flatten.contains(localProject)
}
}.value,
namespaceReverseRouter := false,
routesGenerator := InjectedRoutesGenerator,
sourcePositionMappers += routesPositionMapper
)
private val routesPositionMapper: Position => Option[Position] = position => {
position.sourceFile.asScala.collect {
case GeneratedSource(generatedSource) => new MappedPos(position, generatedSource)
}
}
private final class MappedPos(generatedPosition: Position, generatedSource: GeneratedSource) extends Position {
private val source = generatedSource.source.get
lazy val line = generatedPosition.line.asScala.flatMap(l => generatedSource.mapLine(l).map(Int.box(_))).asJava
lazy val lineContent = line.asScala.flatMap(l => IO.read(source).split('\n').lift(l - 1)).getOrElse("")
val offset = Optional.empty[Integer]
val pointer = Optional.empty[Integer]
val pointerSpace = Optional.empty[String]
val sourcePath = Optional.ofNullable(source.getCanonicalPath)
val sourceFile = Optional.ofNullable(source)
override lazy val toString = {
val sb = new mutable.StringBuilder()
if (sourcePath.isPresent) sb.append(sourcePath.get)
if (line.isPresent) sb.append(":").append(line.get)
if (lineContent.nonEmpty) sb.append("\n").append(lineContent)
sb.toString()
}
}
private val compileRoutesFiles = Def.task[Seq[File]] {
val log = state.value.log
compileRoutes(
routesCompilerTasks.value,
routesGenerator.value,
(routes / target).value,
streams.value.cacheDirectory,
log
)
}
def compileRoutes(
tasks: Seq[RoutesCompilerTask],
generator: RoutesGenerator,
generatedDir: File,
cacheDirectory: File,
log: Logger
): Seq[File] = {
val ops = tasks.map(task => RoutesCompilerOp(task, generator.id, PlayVersion.current))
val (products, errors) = syncIncremental(cacheDirectory, ops) { (opsToRun: Seq[RoutesCompilerOp]) =>
val errs = Seq.newBuilder[RoutesCompilationError]
val opResults: Map[RoutesCompilerOp, OpResult] = opsToRun.map { op =>
play.routes.compiler.RoutesCompiler.compile(op.task, generator, generatedDir) match {
case Right(inputs) =>
op -> OpSuccess(Set(op.task.file), inputs.toSet)
case Left(details) =>
errs ++= details
op -> OpFailure
}
}(scala.collection.breakOut)
opResults -> errs.result()
}
if (errors.nonEmpty) {
val exceptions = errors.map {
case RoutesCompilationError(source, message, line, column) =>
reportCompilationError(log, RoutesCompilationException(source, message, line, column.map(_ - 1)))
}
throw exceptions.head
}
products.to[Seq]
}
private def reportCompilationError(log: Logger, error: PlayException.ExceptionSource) = {
// log the source file and line number with the error message
log.error(
Option(error.sourceName).getOrElse("") + Option(error.line).map(":" + _).getOrElse("") + ": " + error.getMessage
)
Option(error.interestingLines(0)).map(_.focus).flatMap(_.headOption).map { line =>
// log the line
log.error(line)
Option(error.position).map { pos =>
// print a carat under the offending character
val spaces = (line: Seq[Char]).take(pos).map {
case '\t' => '\t'
case x => ' '
}
log.error(spaces.mkString + "^")
}
}
error
}
}
private case class RoutesCompilerOp(task: RoutesCompilerTask, generatorId: String, playVersion: String)
case class RoutesCompilationException(source: File, message: String, atLine: Option[Int], column: Option[Int])
extends PlayException.ExceptionSource("Compilation error", message)
with FeedbackProvidedException {
def line = atLine.map(_.asInstanceOf[java.lang.Integer]).orNull
def position = column.map(_.asInstanceOf[java.lang.Integer]).orNull
def input = IO.read(source)
def sourceName = source.getAbsolutePath
}