/
CrossSources.scala
306 lines (273 loc) · 11.8 KB
/
CrossSources.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
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
package scala.build
import scala.build.EitherCps.{either, value}
import scala.build.Ops.*
import scala.build.Positioned
import scala.build.errors.{BuildException, CompositeBuildException, MalformedDirectiveError}
import scala.build.input.ElementsUtils.*
import scala.build.input.*
import scala.build.internal.Constants
import scala.build.options.{
BuildOptions,
BuildRequirements,
MaybeScalaVersion,
Scope,
SuppressWarningOptions,
WithBuildRequirements
}
import scala.build.preprocessing.*
final case class CrossSources(
paths: Seq[WithBuildRequirements[(os.Path, os.RelPath)]],
inMemory: Seq[WithBuildRequirements[Sources.InMemory]],
defaultMainClass: Option[String],
resourceDirs: Seq[WithBuildRequirements[os.Path]],
buildOptions: Seq[WithBuildRequirements[BuildOptions]]
) {
def sharedOptions(baseOptions: BuildOptions): BuildOptions =
buildOptions
.filter(_.requirements.isEmpty)
.map(_.value)
.foldLeft(baseOptions)(_ orElse _)
private def needsScalaVersion =
paths.exists(_.needsScalaVersion) ||
inMemory.exists(_.needsScalaVersion) ||
resourceDirs.exists(_.needsScalaVersion) ||
buildOptions.exists(_.needsScalaVersion)
def scopedSources(baseOptions: BuildOptions): Either[BuildException, ScopedSources] = either {
val sharedOptions0 = sharedOptions(baseOptions)
// FIXME Not 100% sure the way we compute the intermediate and final BuildOptions
// is consistent (we successively filter out / retain options to compute a scala
// version and platform, which might not be the version and platform of the final
// BuildOptions).
val crossSources0 =
if (needsScalaVersion) {
val retainedScalaVersion = value(sharedOptions0.scalaParams)
.map(p => MaybeScalaVersion(p.scalaVersion))
.getOrElse(MaybeScalaVersion.none)
val buildOptionsWithScalaVersion = buildOptions
.flatMap(_.withScalaVersion(retainedScalaVersion).toSeq)
.filter(_.requirements.isEmpty)
.map(_.value)
.foldLeft(sharedOptions0)(_ orElse _)
val platform = buildOptionsWithScalaVersion.platform
copy(
paths = paths
.flatMap(_.withScalaVersion(retainedScalaVersion).toSeq)
.flatMap(_.withPlatform(platform.value).toSeq),
inMemory = inMemory
.flatMap(_.withScalaVersion(retainedScalaVersion).toSeq)
.flatMap(_.withPlatform(platform.value).toSeq),
resourceDirs = resourceDirs
.flatMap(_.withScalaVersion(retainedScalaVersion).toSeq)
.flatMap(_.withPlatform(platform.value).toSeq),
buildOptions = buildOptions
.filter(!_.requirements.isEmpty)
.flatMap(_.withScalaVersion(retainedScalaVersion).toSeq)
.flatMap(_.withPlatform(platform.value).toSeq)
)
}
else {
val platform = sharedOptions0.platform
copy(
paths = paths
.flatMap(_.withPlatform(platform.value).toSeq),
inMemory = inMemory
.flatMap(_.withPlatform(platform.value).toSeq),
resourceDirs = resourceDirs
.flatMap(_.withPlatform(platform.value).toSeq),
buildOptions = buildOptions
.filter(!_.requirements.isEmpty)
.flatMap(_.withPlatform(platform.value).toSeq)
)
}
val defaultScope: Scope = Scope.Main
ScopedSources(
crossSources0.paths.map(_.scopedValue(defaultScope)),
crossSources0.inMemory.map(_.scopedValue(defaultScope)),
defaultMainClass,
crossSources0.resourceDirs.map(_.scopedValue(defaultScope)),
crossSources0.buildOptions.map(_.scopedValue(defaultScope))
)
}
}
object CrossSources {
private def withinTestSubDirectory(p: ScopePath, inputs: Inputs): Boolean =
p.root.exists { path =>
val fullPath = path / p.subPath
inputs.elements.exists {
case Directory(path) =>
// Is this file subdirectory of given dir and if we have a subdiretory 'test' on the way
fullPath.startsWith(path) &&
fullPath.relativeTo(path).segments.contains("test")
case _ => false
}
}
/** @return
* a CrossSources and Inputs which contains element processed from using directives
*/
def forInputs(
inputs: Inputs,
preprocessors: Seq[Preprocessor],
logger: Logger,
suppressWarningOptions: SuppressWarningOptions,
maybeRecoverOnError: BuildException => Option[BuildException] = e => Some(e)
): Either[BuildException, (CrossSources, Inputs)] = either {
def preprocessSources(elems: Seq[SingleElement])
: Either[BuildException, Seq[PreprocessedSource]] =
elems
.map { elem =>
preprocessors
.iterator
.flatMap(p =>
p.preprocess(
elem,
logger,
maybeRecoverOnError,
inputs.allowRestrictedFeatures,
suppressWarningOptions
).iterator
)
.take(1)
.toList
.headOption
.getOrElse(Right(Nil)) // FIXME Warn about unprocessed stuff?
}
.sequence
.left.map(CompositeBuildException(_))
.map(_.flatten)
val preprocessedInputFromArgs = value(preprocessSources(inputs.flattened()))
val sourcesFromDirectives =
preprocessedInputFromArgs
.flatMap(_.options)
.flatMap(_.internal.extraSourceFiles)
.distinct
val inputsElemFromDirectives =
value(resolveInputsFromSources(sourcesFromDirectives, inputs.enableMarkdown))
val preprocessedSourcesFromDirectives = value(preprocessSources(inputsElemFromDirectives))
val allInputs = inputs.add(inputsElemFromDirectives)
val preprocessedSources =
(preprocessedInputFromArgs ++ preprocessedSourcesFromDirectives).distinct
val scopedRequirements = preprocessedSources.flatMap(_.scopedRequirements)
val scopedRequirementsByRoot = scopedRequirements.groupBy(_.path.root)
def baseReqs(path: ScopePath): BuildRequirements = {
val fromDirectives =
scopedRequirementsByRoot
.getOrElse(path.root, Nil)
.flatMap(_.valueFor(path).toSeq)
.foldLeft(BuildRequirements())(_ orElse _)
// Scala CLI treats all `.test.scala` files tests as well as
// files from within `test` subdirectory from provided input directories
// If file has `using target <scope>` directive this take precendeces.
if (
fromDirectives.scope.isEmpty &&
(path.subPath.last.endsWith(".test.scala") || withinTestSubDirectory(path, allInputs))
)
fromDirectives.copy(scope = Some(BuildRequirements.ScopeRequirement(Scope.Test)))
else fromDirectives
}
val buildOptions = for {
s <- preprocessedSources
opt <- s.options.toSeq
if opt != BuildOptions()
} yield {
val baseReqs0 = baseReqs(s.scopePath)
WithBuildRequirements(
s.requirements.fold(baseReqs0)(_ orElse baseReqs0),
opt
)
}
val defaultMainClassOpt = for {
mainClassPath <- allInputs.defaultMainClassElement
.map(s => ScopePath.fromPath(s.path).subPath)
processedMainClass <- preprocessedSources.find(_.scopePath.subPath == mainClassPath)
mainClass <- processedMainClass.mainClassOpt
} yield mainClass
val pathsWithDirectivePositions
: Seq[(WithBuildRequirements[(os.Path, os.RelPath)], Option[DirectivesPositions])] =
preprocessedSources.collect {
case d: PreprocessedSource.OnDisk =>
val baseReqs0 = baseReqs(d.scopePath)
WithBuildRequirements(
d.requirements.fold(baseReqs0)(_ orElse baseReqs0),
(d.path, d.path.relativeTo(allInputs.workspace))
) -> d.directivesPositions
}
val inMemoryWithDirectivePositions
: Seq[(WithBuildRequirements[Sources.InMemory], Option[DirectivesPositions])] =
preprocessedSources.collect {
case m: PreprocessedSource.InMemory =>
val baseReqs0 = baseReqs(m.scopePath)
WithBuildRequirements(
m.requirements.fold(baseReqs0)(_ orElse baseReqs0),
Sources.InMemory(m.originalPath, m.relPath, m.code, m.ignoreLen)
) -> m.directivesPositions
}
val resourceDirs = allInputs.elements.collect {
case r: ResourceDirectory =>
WithBuildRequirements(BuildRequirements(), r.path)
} ++ preprocessedSources.flatMap(_.options).flatMap(_.classPathOptions.resourcesDir).map(
WithBuildRequirements(BuildRequirements(), _)
)
val allPathsWithDirectivesByScope: Map[Scope, Seq[(os.Path, DirectivesPositions)]] =
(pathsWithDirectivePositions ++ inMemoryWithDirectivePositions)
.flatMap { (withBuildRequirements, directivesPositions) =>
val scope = withBuildRequirements.scopedValue(Scope.Main).scope
val path: os.Path = withBuildRequirements.value match
case im: Sources.InMemory =>
im.originalPath match
case Right((_, p: os.Path)) => p
case _ => inputs.workspace / im.generatedRelPath
case (p: os.Path, _) => p
directivesPositions.map((path, scope, _))
}
.groupBy((_, scope, _) => scope)
.view
.mapValues(_.map((path, _, directivesPositions) => path -> directivesPositions))
.toMap
lazy val anyScopeHasMultipleSourcesWithDirectives =
Scope.all.exists(allPathsWithDirectivesByScope.get(_).map(_.length).getOrElse(0) > 1)
val shouldSuppressWarning =
suppressWarningOptions.suppressDirectivesInMultipleFilesWarning.getOrElse(false)
if !shouldSuppressWarning && anyScopeHasMultipleSourcesWithDirectives then {
val projectFilePath = inputs.elements.projectSettingsFiles.headOption match
case Some(s) => s.path
case _ => inputs.workspace / Constants.projectFileName
allPathsWithDirectivesByScope
.values
.flatten
.filter((path, _) => ScopePath.fromPath(path) != ScopePath.fromPath(projectFilePath))
.foreach { (_, directivesPositions) =>
logger.diagnostic(
s"Using directives detected in multiple files. It is recommended to keep them centralized in the $projectFilePath file.",
positions = Seq(directivesPositions.all.maxBy(_.endPos._1))
)
}
}
val paths = pathsWithDirectivePositions.map(_._1)
val inMemory = inMemoryWithDirectivePositions.map(_._1)
(CrossSources(paths, inMemory, defaultMainClassOpt, resourceDirs, buildOptions), allInputs)
}
private def resolveInputsFromSources(sources: Seq[Positioned[os.Path]], enableMarkdown: Boolean) =
sources.map { source =>
val sourcePath = source.value
lazy val dir = sourcePath / os.up
lazy val subPath = sourcePath.subRelativeTo(dir)
if (os.isDir(sourcePath))
Right(Directory(sourcePath).singleFilesFromDirectory(enableMarkdown))
else if (sourcePath == os.sub / Constants.projectFileName)
Right(Seq(ProjectScalaFile(dir, subPath)))
else if (sourcePath.ext == "scala") Right(Seq(SourceScalaFile(dir, subPath)))
else if (sourcePath.ext == "sc") Right(Seq(Script(dir, subPath)))
else if (sourcePath.ext == "java") Right(Seq(JavaFile(dir, subPath)))
else if (sourcePath.ext == "jar") Right(Seq(JarFile(dir, subPath)))
else if (sourcePath.ext == "md") Right(Seq(MarkdownFile(dir, subPath)))
else {
val msg =
if (os.exists(sourcePath))
s"$sourcePath: unrecognized source type (expected .scala, .sc, .java extension or directory) in using directive."
else s"$sourcePath: not found path defined in using directive."
Left(new MalformedDirectiveError(msg, source.positions))
}
}.sequence
.left.map(CompositeBuildException(_))
.map(_.flatten)
}