/
Eclipse.scala
489 lines (435 loc) · 17.8 KB
/
Eclipse.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
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
/*
* Copyright 2011 Typesafe Inc.
*
* This work is based on the original contribution of WeigleWilczek.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.typesafe.sbteclipse.core
import EclipsePlugin.{
EclipseClasspathEntry,
EclipseTransformerFactory,
EclipseClasspathEntryTransformerFactory,
EclipseRewriteRuleTransformerFactory,
EclipseCreateSrc,
EclipseExecutionEnvironment,
EclipseKeys
}
import java.io.{ FileWriter, Writer }
import java.util.Properties
import sbt.{
Attributed,
Artifact,
ClasspathDep,
Classpaths,
Command,
Configuration,
Configurations,
File,
IO,
Keys,
ModuleID,
Project,
ProjectRef,
Reference,
ResolvedProject,
SettingKey,
State,
TaskKey,
ThisBuild,
UpdateReport,
richFile
}
import sbt.complete.Parser
import scala.xml.{ Node, PrettyPrinter }
import scala.xml.transform.{ RewriteRule, RuleTransformer }
import scalaz.{ Failure, NonEmptyList, Success }
import scalaz.Scalaz._
import scalaz.effects._
private object Eclipse {
val SettingFormat = """-([^:]*):?(.*)""".r
val FileSepPattern = FileSep.replaceAll("""\\""", """\\\\""")
val JreContainer = "org.eclipse.jdt.launching.JRE_CONTAINER"
val StandardVmType = "org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType"
def eclipseCommand(commandName: String): Command =
Command(commandName)(_ => parser)((state, args) => action(args.toMap, state))
def parser: Parser[Seq[(String, Any)]] = {
import EclipseOpts._
(executionEnvironmentOpt | boolOpt(SkipParents) | boolOpt(WithSource)).*
}
def executionEnvironmentOpt: Parser[(String, EclipseExecutionEnvironment.Value)] = {
import EclipseExecutionEnvironment._
import EclipseOpts._
import sbt.complete.DefaultParsers._
val (head :: tail) = valueSeq map (_.toString)
val executionEnvironments = tail.foldLeft(head: Parser[String])(_ | _)
(Space ~> ExecutionEnvironment ~ ("=" ~> executionEnvironments)) map { case (k, v) => k -> withName(v) }
}
def action(args: Map[String, Any], state: State): State = {
state.log.info("About to create Eclipse project files for your project(s).")
import EclipseOpts._
handleProjects(
(args get ExecutionEnvironment).asInstanceOf[Option[EclipseExecutionEnvironment.Value]],
(args get SkipParents).asInstanceOf[Option[Boolean]] getOrElse skipParents(ThisBuild, state),
(args get WithSource).asInstanceOf[Option[Boolean]],
state
).fold(onFailure(state), onSuccess(state))
}
def handleProjects(
executionEnvironmentArg: Option[EclipseExecutionEnvironment.Value],
skipParents: Boolean,
withSourceArg: Option[Boolean],
state: State): Validation[IO[Seq[String]]] = {
val effects = for {
ref <- structure(state).allProjectRefs
project <- Project.getProject(ref, structure(state)) if project.aggregate.isEmpty || !skipParents
} yield {
val configs = configurations(ref, state)
val applic = classpathEntryTransformerFactory(ref, state).createTransformer(ref, state) |@|
(classpathTransformerFactories(ref, state) map (_.createTransformer(ref, state))).sequence[Validation, RewriteRule] |@|
(projectTransformerFactories(ref, state) map (_.createTransformer(ref, state))).sequence[Validation, RewriteRule] |@|
name(ref, state) |@|
buildDirectory(state) |@|
baseDirectory(ref, state) |@|
mapConfigurations(configs, srcDirectories(ref, createSrc(ref, state), eclipseOutput(ref, state), state)) |@|
scalacOptions(ref, state) |@|
mapConfigurations(configs, externalDependencies(ref, withSourceArg getOrElse withSource(ref, state), state)) |@|
mapConfigurations(configs, projectDependencies(ref, project, state))
applic(
handleProject(
jreContainer(executionEnvironmentArg orElse executionEnvironment(ref, state)),
preTasks(ref, state),
relativizeLibs(ref, state),
state
)
)
}
effects.sequence[Validation, IO[String]] map (_.sequence)
}
def onFailure(state: State)(errors: NonEmptyList[String]): State = {
state.log.error(
"Could not create Eclipse project files:%s%s".format(NewLine, errors.list mkString NewLine)
)
state.fail
}
def onSuccess(state: State)(effects: IO[Seq[String]]): State = {
val names = effects.unsafePerformIO
if (names.isEmpty)
state.log.warn("There was no project to create Eclipse project files for!")
else
state.log.info(
"Successfully created Eclipse project files for project(s):%s%s".format(
NewLine,
names mkString NewLine
)
)
state
}
def mapConfigurations[A](
configurations: Seq[Configuration],
f: Configuration => Validation[Seq[A]]): Validation[Seq[A]] =
(configurations map f).sequence map (_.flatten.distinct)
def handleProject(
jreContainer: String,
preTasks: Seq[(TaskKey[_], ProjectRef)],
relativizeLibs: Boolean,
state: State)(
classpathEntryTransformer: Seq[EclipseClasspathEntry] => Seq[EclipseClasspathEntry],
classpathTransformers: Seq[RewriteRule],
projectTransformers: Seq[RewriteRule],
name: String,
buildDirectory: File,
baseDirectory: File,
srcDirectories: Seq[(File, File)],
scalacOptions: Seq[(String, String)],
externalDependencies: Seq[Lib],
projectDependencies: Seq[String]): IO[String] = {
for {
_ <- executePreTasks(preTasks, state)
n <- io(name)
_ <- saveXml(baseDirectory / ".project", new RuleTransformer(projectTransformers: _*)(projectXml(name)))
cp <- classpath(
classpathEntryTransformer,
buildDirectory,
baseDirectory,
relativizeLibs,
srcDirectories,
externalDependencies,
projectDependencies,
jreContainer,
state
)
_ <- saveXml(baseDirectory / ".classpath", new RuleTransformer(classpathTransformers: _*)(cp))
_ <- saveProperties(baseDirectory / ".settings" / "org.scala-ide.sdt.core.prefs", scalacOptions)
} yield n
}
def executePreTasks(preTasks: Seq[(TaskKey[_], ProjectRef)], state: State): IO[Unit] =
io(for ((preTask, ref) <- preTasks) evaluateTask(preTask, ref, state))
def projectXml(name: String): Node =
<projectDescription>
<name>{ name }</name>
<buildSpec>
<buildCommand>
<name>org.scala-ide.sdt.core.scalabuilder</name>
</buildCommand>
</buildSpec>
<natures>
<nature>org.scala-ide.sdt.core.scalanature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
def classpath(
classpathEntryTransformer: Seq[EclipseClasspathEntry] => Seq[EclipseClasspathEntry],
buildDirectory: File,
baseDirectory: File,
relativizeLibs: Boolean,
srcDirectories: Seq[(File, File)],
externalDependencies: Seq[Lib],
projectDependencies: Seq[String],
jreContainer: String,
state: State): IO[Node] = {
val srcEntriesIoSeq =
for ((dir, output) <- srcDirectories) yield srcEntry(baseDirectory, dir, output, state)
for (srcEntries <- srcEntriesIoSeq.sequence) yield {
val entries = srcEntries ++
(externalDependencies map libEntry(buildDirectory, baseDirectory, relativizeLibs, state)) ++
(projectDependencies map EclipseClasspathEntry.Project) ++
(Seq(jreContainer) map EclipseClasspathEntry.Con) ++
(Seq("bin") map EclipseClasspathEntry.Output)
<classpath>{ classpathEntryTransformer(entries) map (_.toXml) }</classpath>
}
}
def srcEntry(
baseDirectory: File,
srcDirectory: File,
classDirectory: File,
state: State): IO[EclipseClasspathEntry.Src] =
io {
if (!srcDirectory.exists()) srcDirectory.mkdirs()
EclipseClasspathEntry.Src(
relativize(baseDirectory, srcDirectory),
relativize(baseDirectory, classDirectory)
)
}
def libEntry(
buildDirectory: File,
baseDirectory: File,
relativizeLibs: Boolean,
state: State)(
lib: Lib): EclipseClasspathEntry.Lib = {
def path(file: File) = {
val relativizedBase =
if (buildDirectory === baseDirectory) Some(".") else IO.relativize(buildDirectory, baseDirectory)
val relativizedFile = IO.relativize(buildDirectory, file)
val relativized = (relativizedBase |@| relativizedFile)((base, file) =>
"%s%s%s".format(
base split FileSepPattern map (part => if (part != ".") ".." else part) mkString FileSep,
FileSep,
file
)
)
if (relativizeLibs) relativized getOrElse file.getAbsolutePath else file.getAbsolutePath
}
EclipseClasspathEntry.Lib(path(lib.binary), lib.source map path)
}
def jreContainer(executionEnvironment: Option[EclipseExecutionEnvironment.Value]): String =
executionEnvironment match {
case Some(ee) => "%s/%s/%s".format(JreContainer, StandardVmType, ee)
case None => JreContainer
}
// Getting and transforming mandatory settings and task results
def name(ref: Reference, state: State): Validation[String] =
setting(Keys.name in ref, state)
def buildDirectory(state: State): Validation[File] =
setting(Keys.baseDirectory in ThisBuild, state)
def baseDirectory(ref: Reference, state: State): Validation[File] =
setting(Keys.baseDirectory in ref, state)
def target(ref: Reference, state: State): Validation[File] =
setting(Keys.target in ref, state)
def srcDirectories(
ref: Reference,
createSrc: EclipseCreateSrc.ValueSet,
eclipseOutput: Option[String],
state: State)(
configuration: Configuration): Validation[Seq[(File, File)]] = {
import EclipseCreateSrc._
val classDirectory = eclipseOutput match {
case Some(name) => baseDirectory(ref, state) map (new File(_, name))
case None => setting(Keys.classDirectory in (ref, configuration), state)
}
def dirs(values: ValueSet, key: SettingKey[Seq[File]]) =
if (values subsetOf createSrc)
(setting(key in (ref, configuration), state) <**> classDirectory)((sds, cd) => sds map (_ -> cd))
else
"".failNel
Seq(
dirs(ValueSet(Unmanaged, Source), Keys.unmanagedSourceDirectories),
dirs(ValueSet(Managed, Source), Keys.managedSourceDirectories),
dirs(ValueSet(Unmanaged, Resource), Keys.unmanagedResourceDirectories),
dirs(ValueSet(Managed, Resource), Keys.managedResourceDirectories)
) reduceLeft (_ >>*<< _)
}
def scalacOptions(ref: ProjectRef, state: State): Validation[Seq[(String, String)]] =
evaluateTask(Keys.scalacOptions, ref, state) map (options =>
if (options.isEmpty) Nil
else {
def pluginValues(value: String) =
value split "," map (_.trim) filterNot (_ contains "org.scala-lang.plugins/continuations")
options.zipAll(options.tail, "-", "-") collect {
case (SettingFormat("Xplugin", value), _) if !pluginValues(value).isEmpty =>
"Xplugin" -> (pluginValues(value) mkString ",")
case (SettingFormat(key, value), next) if next startsWith "-" =>
key -> (if (!value.isEmpty) value else "true")
case (SettingFormat(key, _), next) =>
key -> next
} match {
case Nil => Nil
case options => ("scala.compiler.useProjectSettings" -> "true") +: options
}
}
)
def externalDependencies(
ref: ProjectRef,
withSource: Boolean,
state: State)(
configuration: Configuration): Validation[Seq[Lib]] = {
def moduleToFile(key: TaskKey[UpdateReport], p: (Artifact, File) => Boolean = (_, _) => true) =
evaluateTask(key in configuration, ref, state) map { updateReport =>
val moduleToFile =
for {
configurationReport <- (updateReport configuration configuration.name).toSeq
moduleReport <- configurationReport.modules
(artifact, file) <- moduleReport.artifacts if p(artifact, file)
} yield moduleReport.module -> file
moduleToFile.toMap
}
def libs(files: Seq[Attributed[File]], binaries: Map[ModuleID, File], sources: Map[ModuleID, File]) = {
val binaryFilesToSourceFiles =
for {
(moduleId, binaryFile) <- binaries
sourceFile <- sources get moduleId
} yield binaryFile -> sourceFile
files.files map (file => Lib(file)(binaryFilesToSourceFiles get file))
}
val externalDependencyClasspath =
evaluateTask(Keys.externalDependencyClasspath in configuration, ref, state)
val binaryModuleToFile = moduleToFile(Keys.update)
val sourceModuleToFile =
if (withSource)
moduleToFile(Keys.updateClassifiers, (artifact, _) => artifact.classifier === Some("sources"))
else
Map[ModuleID, File]().success
val externalDependencies =
(externalDependencyClasspath |@| binaryModuleToFile |@| sourceModuleToFile)(libs)
state.log.debug(
"External dependencies for configuration '%s' and withSource '%s': %s".format(
configuration,
withSource,
externalDependencies
)
)
externalDependencies
}
def projectDependencies(
ref: ProjectRef,
project: ResolvedProject,
state: State)(
configuration: Configuration): Validation[Seq[String]] = {
val projectDependencies = project.dependencies collect {
case dependency if isInConfiguration(configuration, ref, dependency, state) =>
setting(Keys.name in dependency.project, state)
}
val projectDependenciesSeq = projectDependencies.sequence
state.log.debug("Project dependencies for configuration '%s': %s".format(configuration, projectDependenciesSeq))
projectDependenciesSeq
}
def isInConfiguration(
configuration: Configuration,
ref: ProjectRef,
dependency: ClasspathDep[ProjectRef],
state: State): Boolean = {
val map = Classpaths.mapped(
dependency.configuration,
Configurations.names(Classpaths.getConfigurations(ref, structure(state).data)),
Configurations.names(Classpaths.getConfigurations(dependency.project, structure(state).data)),
"compile", "*->compile"
)
!map(configuration.name).isEmpty
}
// Getting and transforming optional settings and task results
def executionEnvironment(ref: Reference, state: State): Option[EclipseExecutionEnvironment.Value] =
setting(EclipseKeys.executionEnvironment in ref, state).fold(_ => None, id)
def skipParents(ref: Reference, state: State): Boolean =
setting(EclipseKeys.skipParents in ref, state).fold(_ => true, id)
def withSource(ref: Reference, state: State): Boolean =
setting(EclipseKeys.withSource in ref, state).fold(_ => false, id)
def classpathEntryTransformerFactory(ref: Reference, state: State): EclipseTransformerFactory[Seq[EclipseClasspathEntry] => Seq[EclipseClasspathEntry]] =
setting(EclipseKeys.classpathEntryTransformerFactory in ref, state).fold(
_ => EclipseClasspathEntryTransformerFactory.Identity,
id
)
def classpathTransformerFactories(ref: Reference, state: State): Seq[EclipseTransformerFactory[RewriteRule]] =
setting(EclipseKeys.classpathTransformerFactories in ref, state).fold(
_ => Seq(EclipseRewriteRuleTransformerFactory.ClasspathDefault),
EclipseRewriteRuleTransformerFactory.ClasspathDefault +: _
)
def projectTransformerFactories(ref: Reference, state: State): Seq[EclipseTransformerFactory[RewriteRule]] =
setting(EclipseKeys.projectTransformerFactories in ref, state).fold(
_ => Seq(EclipseRewriteRuleTransformerFactory.Identity),
id
)
def configurations(ref: Reference, state: State): Seq[Configuration] =
setting(EclipseKeys.configurations in ref, state).fold(
_ => Seq(Configurations.Compile, Configurations.Test),
_.toSeq
)
def createSrc(ref: Reference, state: State): EclipseCreateSrc.ValueSet =
setting(EclipseKeys.createSrc in ref, state).fold(_ => EclipseCreateSrc.Default, id)
def eclipseOutput(ref: ProjectRef, state: State): Option[String] =
setting(EclipseKeys.eclipseOutput in ref, state).fold(_ => None, id)
def preTasks(ref: ProjectRef, state: State): Seq[(TaskKey[_], ProjectRef)] =
setting(EclipseKeys.preTasks in ref, state).fold(_ => Seq.empty, _.zipAll(Seq.empty, null, ref))
def relativizeLibs(ref: ProjectRef, state: State): Boolean =
setting(EclipseKeys.relativizeLibs in ref, state).fold(_ => true, id)
// IO
def saveXml(file: File, xml: Node): IO[Unit] =
fileWriter(file).bracket(closeWriter)(writer => io(writer.write(new PrettyPrinter(999, 2) format xml)))
def saveProperties(file: File, settings: Seq[(String, String)]): IO[Unit] =
if (!settings.isEmpty) {
val properties = new Properties
for ((key, value) <- settings) properties.setProperty(key, value)
fileWriterMkdirs(file).bracket(closeWriter)(writer =>
io(properties.store(writer, "Generated by sbteclipse"))
)
} else
io(())
def fileWriter(file: File): IO[FileWriter] =
io(new FileWriter(file))
def fileWriterMkdirs(file: File): IO[FileWriter] =
io {
file.getParentFile.mkdirs()
new FileWriter(file)
}
def closeWriter(writer: Writer): IO[Unit] =
io(writer.close())
// Utilities
def relativize(baseDirectory: File, file: File): String =
IO.relativize(baseDirectory, file).get
}
private case class Content(
name: String,
dir: File,
project: Node,
classpath: Node,
scalacOptions: Seq[(String, String)])
private case class Lib(binary: File)(val source: Option[File])