-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathScalafmtPlugin.scala
451 lines (412 loc) · 13.4 KB
/
ScalafmtPlugin.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
package org.scalafmt.sbt
import java.io.OutputStreamWriter
import java.nio.file.Path
import sbt.Keys._
import sbt.Def
import sbt._
import complete.DefaultParsers._
import sbt.util.CacheImplicits._
import sbt.util.CacheStoreFactory
import sbt.util.FileInfo
import sbt.util.FilesInfo
import sbt.util.Logger
import scala.util.Failure
import scala.util.Success
import scala.util.Try
import org.scalafmt.interfaces.{Scalafmt, ScalafmtSessionFactory}
import sbt.ConcurrentRestrictions.Tag
import sbt.librarymanagement.MavenRepository
object ScalafmtPlugin extends AutoPlugin {
override def trigger: PluginTrigger = allRequirements
object autoImport {
val scalafmt = taskKey[Unit]("Format Scala sources with scalafmt.")
private[sbt] val ScalafmtTagPack =
Seq(ConcurrentRestrictionTags.Scalafmt, Tags.CPU)
@deprecated("Use scalafmt instead.", "2.0.0")
val scalafmtIncremental = taskKey[Unit](
"Format Scala sources to be compiled incrementally with scalafmt (alias to scalafmt)."
)
val scalafmtCheck =
taskKey[Boolean](
"Fails if a Scala source is mis-formatted. Does not write to files."
)
val scalafmtOnCompile =
settingKey[Boolean](
"Format Scala source files on compile, off by default."
)
val scalafmtConfig = taskKey[File](
"Location of .scalafmt.conf file. " +
"If the file does not exist, exception is thrown."
)
val scalafmtSbt = taskKey[Unit](
"Format *.sbt and project/*.scala files for this sbt build."
)
val scalafmtSbtCheck =
taskKey[Boolean](
"Fails if a *.sbt or project/*.scala source is mis-formatted. " +
"Does not write to files."
)
val scalafmtOnly = inputKey[Unit]("Format a single given file.")
val scalafmtAll = taskKey[Unit](
"Execute the scalafmt task for all configurations in which it is enabled. " +
"(By default this means the Compile and Test configurations.)"
)
val scalafmtCheckAll = taskKey[Unit](
"Execute the scalafmtCheck task for all configurations in which it is enabled. " +
"(By default this means the Compile and Test configurations.)"
)
}
import autoImport._
case class ScalafmtAnalysis(failedScalafmtCheck: Set[File])
object ScalafmtAnalysis {
import sjsonnew.{:*:, LList, LNil}
implicit val analysisIso = LList.iso({ a: ScalafmtAnalysis =>
("failedScalafmtCheck", a.failedScalafmtCheck) :*: LNil
}, { in: Set[File] :*: LNil =>
ScalafmtAnalysis(in.head)
})
}
private val scalafmtDoFormatOnCompile =
taskKey[Unit]("Format Scala source files if scalafmtOnCompile is on.")
private val scalaConfig = {
scalafmtConfig.map { f =>
if (f.exists()) {
f.toPath
} else {
throw new MessageOnlyException(s"File not exists: ${f.toPath}")
}
}
}
private val sbtConfig = scalaConfig
private type Input = String
private type Output = String
val globalInstance = Scalafmt.create(this.getClass.getClassLoader)
private def withFormattedSources[T](
sources: Seq[File],
config: Path,
log: Logger,
writer: OutputStreamWriter,
resolvers: Seq[Resolver]
)(
onFormat: (File, Input, Output) => T
): Seq[Option[T]] = {
val reporter = new ScalafmtSbtReporter(log, writer)
val repositories = resolvers.collect {
case r: MavenRepository => r.root
}
val scalafmtSession =
globalInstance
.withReporter(reporter)
.withMavenRepositories(repositories: _*)
.withRespectProjectFilters(true) match {
case t: ScalafmtSessionFactory =>
val session = t.createSession(config.toAbsolutePath)
if (session == null) {
throw new MessageOnlyException(
"failed to create formatting session. Please report bug to https://github.com/scalameta/sbt-scalafmt"
)
}
session
case instance =>
new CompatibilityScalafmtSession(config.toAbsolutePath, instance)
}
log.debug(
s"Adding repositories ${repositories.mkString("[", ",", "]")}"
)
sources
.map { file =>
val input = IO.read(file)
val output =
scalafmtSession.format(
file.toPath.toAbsolutePath,
input
)
Some(onFormat(file, input, output))
}
}
private def formatSources(
cacheStoreFactory: CacheStoreFactory,
sources: Seq[File],
config: Path,
log: Logger,
writer: OutputStreamWriter,
resolvers: Seq[Resolver]
): Unit = {
trackSourcesAndConfig(cacheStoreFactory, sources, config) {
(outDiff, configChanged, prev) =>
log.debug(outDiff.toString)
val updatedOrAdded = outDiff.modified & outDiff.checked
val filesToFormat: Set[File] =
if (configChanged) sources.toSet
else {
// in addition to the detected changes, process files that failed scalafmtCheck
// we can ignore the succeeded files because, they don't require reformatting
updatedOrAdded | prev.failedScalafmtCheck
}
if (filesToFormat.nonEmpty) {
log.info(s"Formatting ${filesToFormat.size} Scala sources...")
formatSources(filesToFormat, config, log, writer, resolvers)
}
ScalafmtAnalysis(Set.empty)
}
}
private def formatSources(
sources: Set[File],
config: Path,
log: Logger,
writer: OutputStreamWriter,
resolvers: Seq[Resolver]
): Unit = {
val cnt =
withFormattedSources(sources.toSeq, config, log, writer, resolvers)(
(file, input, output) => {
if (input != output) {
IO.write(file, output)
1
} else {
0
}
}
).flatten.sum
if (cnt > 1) {
log.info(s"Reformatted $cnt Scala sources")
}
}
private def checkSources(
cacheStoreFactory: CacheStoreFactory,
sources: Seq[File],
config: Path,
log: Logger,
writer: OutputStreamWriter,
resolvers: Seq[Resolver]
): ScalafmtAnalysis = {
trackSourcesAndConfig(cacheStoreFactory, sources, config) {
(outDiff, configChanged, prev) =>
log.debug(outDiff.toString)
val updatedOrAdded = outDiff.modified & outDiff.checked
val filesToCheck: Set[File] =
if (configChanged) sources.toSet
else updatedOrAdded
val prevFailed: Set[File] =
if (configChanged) Set.empty
else prev.failedScalafmtCheck & outDiff.unmodified
prevFailed foreach { warnBadFormat(_, log) }
val result =
checkSources(filesToCheck.toSeq, config, log, writer, resolvers)
prev.copy(
failedScalafmtCheck = result.failedScalafmtCheck | prevFailed
)
}
}
private def trueOrBoom(analysis: ScalafmtAnalysis): Boolean = {
val failureCount = analysis.failedScalafmtCheck.size
if (failureCount > 0) {
throw new MessageOnlyException(
s"${failureCount} files must be formatted"
)
}
true
}
private def warnBadFormat(file: File, log: Logger): Unit = {
log.warn(s"${file.toString} isn't formatted properly!")
}
private def checkSources(
sources: Seq[File],
config: Path,
log: Logger,
writer: OutputStreamWriter,
resolvers: Seq[Resolver]
): ScalafmtAnalysis = {
if (sources.nonEmpty) {
log.info(s"Checking ${sources.size} Scala sources...")
}
val unformatted =
withFormattedSources(sources, config, log, writer, resolvers)(
(file, input, output) => {
val diff = input != output
if (diff) {
warnBadFormat(file, log)
Some(file)
} else None
}
).flatten.flatten.toSet
ScalafmtAnalysis(failedScalafmtCheck = unformatted)
}
// This tracks
// 1. previous value
// 2. changes to the config file
// 3. changes to source and their last modified dates after the operation
// The tracking is shared between scalafmt and scalafmtCheck
private def trackSourcesAndConfig(
cacheStoreFactory: CacheStoreFactory,
sources: Seq[File],
config: Path
)(
f: (ChangeReport[File], Boolean, ScalafmtAnalysis) => ScalafmtAnalysis
): ScalafmtAnalysis = {
// use prevTracker to share previous values between tasks
val prevTracker = Tracked.lastOutput[Unit, ScalafmtAnalysis](
cacheStoreFactory.make("last")
) { (_, prev0) =>
val prev = prev0.getOrElse(ScalafmtAnalysis(Set.empty))
val tracker = Tracked.inputChanged[HashFileInfo, ScalafmtAnalysis](
cacheStoreFactory.make("config")
) {
case (configChanged, configHash) =>
Tracked.diffOutputs(
cacheStoreFactory.make("output-diff"),
FileInfo.lastModified
)(sources.toSet) { (outDiff: ChangeReport[File]) =>
f(outDiff, configChanged, prev)
}
}
tracker(FileInfo.hash(config.toFile))
}
prevTracker(())
}
private lazy val sbtSources = Def.task {
val rootBase = (LocalRootProject / baseDirectory).value
val thisBase = (thisProject.value).base
val rootSbt =
BuildPaths.configurationSources(thisBase).filterNot(_.isHidden)
val metabuildSbt =
if (rootBase == thisBase)
(BuildPaths.projectStandard(thisBase) ** GlobFilter("*.sbt")).get
else Nil
rootSbt ++ metabuildSbt
}
private lazy val metabuildSources = Def.task {
val rootBase = (LocalRootProject / baseDirectory).value
val thisBase = (thisProject.value).base
if (rootBase == thisBase) {
val projectDirectory = BuildPaths.projectStandard(thisBase)
val targetDirectory =
BuildPaths.outputDirectory(projectDirectory).getAbsolutePath
projectDirectory
.descendantsExcept(
"*.scala",
(pathname: File) =>
pathname.getAbsolutePath.startsWith(targetDirectory)
)
.get
} else {
Nil
}
}
private def scalafmtTask =
Def.task {
formatSources(
streams.value.cacheStoreFactory,
(unmanagedSources in scalafmt).value,
scalaConfig.value,
streams.value.log,
outputStreamWriter(streams.value),
fullResolvers.value
)
} tag (ScalafmtTagPack: _*)
private def scalafmtSbtTask =
Def.task {
formatSources(
sbtSources.value.toSet,
sbtConfig.value,
streams.value.log,
outputStreamWriter(streams.value),
fullResolvers.value
)
formatSources(
metabuildSources.value.toSet,
scalaConfig.value,
streams.value.log,
outputStreamWriter(streams.value),
fullResolvers.value
)
} tag (ScalafmtTagPack: _*)
private def scalafmtCheckTask =
Def.task {
val analysis = checkSources(
(scalafmt / streams).value.cacheStoreFactory,
(unmanagedSources in scalafmt).value,
scalaConfig.value,
streams.value.log,
outputStreamWriter(streams.value),
fullResolvers.value
)
trueOrBoom(analysis)
} tag (ScalafmtTagPack: _*)
private def scalafmtSbtCheckTask =
Def.task {
trueOrBoom(
checkSources(
sbtSources.value,
sbtConfig.value,
streams.value.log,
outputStreamWriter(streams.value),
fullResolvers.value
)
)
trueOrBoom(
checkSources(
metabuildSources.value,
scalaConfig.value,
streams.value.log,
outputStreamWriter(streams.value),
fullResolvers.value
)
)
} tag (ScalafmtTagPack: _*)
lazy val scalafmtConfigSettings: Seq[Def.Setting[_]] = Seq(
scalafmt := scalafmtTask.value,
scalafmtIncremental := scalafmt.value,
scalafmtSbt := scalafmtSbtTask.value,
scalafmtCheck := scalafmtCheckTask.value,
scalafmtSbtCheck := scalafmtSbtCheckTask.value,
scalafmtDoFormatOnCompile := Def.settingDyn {
if (scalafmtOnCompile.value) {
(scalafmt in resolvedScoped.value.scope)
} else {
Def.task(())
}
}.value,
sources in Compile := (sources in Compile)
.dependsOn(scalafmtDoFormatOnCompile)
.value,
scalafmtOnly := {
val files = spaceDelimited("<files>").parsed
val absFiles = files.flatMap(fileS => {
Try { IO.resolve(baseDirectory.value, new File(fileS)) } match {
case Failure(e) =>
streams.value.log.error(s"Error with $fileS file: $e")
None
case Success(file) => Some(file)
}
})
// scalaConfig
formatSources(
absFiles.toSet,
scalaConfig.value,
streams.value.log,
outputStreamWriter(streams.value),
fullResolvers.value
)
}
)
private def outputStreamWriter(streams: TaskStreams): OutputStreamWriter =
new OutputStreamWriter(streams.binary())
private val anyConfigsInThisProject = ScopeFilter(
configurations = inAnyConfiguration
)
override def projectSettings: Seq[Def.Setting[_]] =
Seq(Compile, Test).flatMap(inConfig(_)(scalafmtConfigSettings)) ++ Seq(
scalafmtAll := scalafmt.?.all(anyConfigsInThisProject).value,
scalafmtCheckAll := scalafmtCheck.?.all(anyConfigsInThisProject).value
)
override def buildSettings: Seq[Def.Setting[_]] = Seq(
scalafmtConfig := {
(baseDirectory in ThisBuild).value / ".scalafmt.conf"
}
)
override def globalSettings: Seq[Def.Setting[_]] =
Seq(
scalafmtOnCompile := false
)
}