/
UserConfiguration.scala
664 lines (631 loc) Β· 24.4 KB
/
UserConfiguration.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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
package scala.meta.internal.metals
import java.util.Properties
import scala.collection.mutable.ListBuffer
import scala.util.Failure
import scala.util.Success
import scala.util.Try
import scala.meta.internal.jdk.CollectionConverters._
import scala.meta.internal.mtags.Symbol
import scala.meta.io.AbsolutePath
import scala.meta.pc.PresentationCompilerConfig
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.google.gson.JsonPrimitive
case class JavaFormatConfig(
eclipseFormatConfigPath: AbsolutePath,
eclipseFormatProfile: Option[String],
)
/**
* Configuration that the user can override via workspace/didChangeConfiguration.
*/
case class UserConfiguration(
javaHome: Option[String] = None,
sbtScript: Option[String] = None,
gradleScript: Option[String] = None,
mavenScript: Option[String] = None,
millScript: Option[String] = None,
scalafmtConfigPath: Option[AbsolutePath] = None,
scalafixConfigPath: Option[AbsolutePath] = None,
symbolPrefixes: Map[String, String] =
PresentationCompilerConfig.defaultSymbolPrefixes().asScala.toMap,
worksheetScreenWidth: Int = 120,
worksheetCancelTimeout: Int = 4,
bloopSbtAlreadyInstalled: Boolean = false,
bloopVersion: Option[String] = None,
bloopJvmProperties: Option[List[String]] = None,
ammoniteJvmProperties: Option[List[String]] = None,
superMethodLensesEnabled: Boolean = false,
showInferredType: Option[String] = None,
showImplicitArguments: Boolean = false,
showImplicitConversionsAndClasses: Boolean = false,
showEvidenceParams: Boolean = false,
enableStripMarginOnTypeFormatting: Boolean = true,
enableIndentOnPaste: Boolean = false,
enableSemanticHighlighting: Boolean = true,
excludedPackages: Option[List[String]] = None,
fallbackScalaVersion: Option[String] = None,
testUserInterface: TestUserInterfaceKind = TestUserInterfaceKind.CodeLenses,
javaFormatConfig: Option[JavaFormatConfig] = None,
scalafixRulesDependencies: List[String] = Nil,
customProjectRoot: Option[String] = None,
verboseCompilation: Boolean = false,
automaticImportBuild: AutoImportBuildKind = AutoImportBuildKind.Off,
scalaCliLauncher: Option[String] = None,
defaultBspToBuildTool: Boolean = false,
) {
def shouldAutoImportNewProject: Boolean =
automaticImportBuild != AutoImportBuildKind.Off
def currentBloopVersion: String =
bloopVersion.getOrElse(BuildInfo.bloopVersion)
def usedJavaBinary(): Option[AbsolutePath] = JavaBinary.path(javaHome)
def areSyntheticsEnabled(): Boolean = {
val showInferredType = !this.showInferredType.contains(
"false"
) && this.showInferredType.nonEmpty
showImplicitArguments || showInferredType || showImplicitConversionsAndClasses
}
def getCustomProjectRoot(workspace: AbsolutePath): Option[AbsolutePath] =
customProjectRoot
.map(relativePath => workspace.resolve(relativePath.trim()))
.filter { projectRoot =>
val exists = projectRoot.toFile.exists
if (!exists) {
scribe.error(s"custom project root $projectRoot does not exist")
}
exists
}
}
object UserConfiguration {
def default: UserConfiguration = UserConfiguration()
private val defaultExclusion =
ExcludedPackagesHandler.defaultExclusions
.map(_.dropRight(1))
.mkString("\n")
.replace("/", ".")
def options: List[UserConfigurationOption] =
List(
UserConfigurationOption(
"java-home",
"`JAVA_HOME` environment variable with fallback to `user.home` system property.",
""""/Library/Java/JavaVirtualMachines/jdk1.8.0_192.jdk/Contents/Home"""",
"Java Home directory",
"The Java Home directory used for indexing JDK sources and locating the `java` binary.",
),
UserConfigurationOption(
"sbt-script",
"""empty string `""`.""",
""""/usr/local/bin/sbt"""",
"sbt script",
"""Optional absolute path to an `sbt` executable to use for running `sbt bloopInstall`.
|By default, Metals uses `java -jar sbt-launch.jar` with an embedded launcher while respecting
|`.jvmopts` and `.sbtopts`. Update this setting if your `sbt` script requires more customizations
|like using environment variables.
|""".stripMargin,
),
UserConfigurationOption(
"gradle-script",
"""empty string `""`.""",
""""/usr/local/bin/gradle"""",
"Gradle script",
"""Optional absolute path to a `gradle` executable to use for running `gradle bloopInstall`.
|By default, Metals uses gradlew with 7.5.0 gradle version. Update this setting if your `gradle` script requires more customizations
|like using environment variables.
|""".stripMargin,
),
UserConfigurationOption(
"maven-script",
"""empty string `""`.""",
""""/usr/local/bin/mvn"""",
"Maven script",
"""Optional absolute path to a `maven` executable to use for generating bloop config.
|By default, Metals uses mvnw maven wrapper with 3.6.1 maven version. Update this setting if your `maven` script requires more customizations
|""".stripMargin,
),
UserConfigurationOption(
"mill-script",
"""empty string `""`.""",
""""/usr/local/bin/mill"""",
"Mill script",
"""Optional absolute path to a `mill` executable to use for running `mill mill.contrib.bloop.Bloop/install`.
|By default, Metals uses mill wrapper script with 0.5.0 mill version. Update this setting if your `mill` script requires more customizations
|like using environment variables.
|""".stripMargin,
),
UserConfigurationOption(
"scalafmt-config-path",
"""empty string `""`.""",
""""project/.scalafmt.conf"""",
"Scalafmt config path",
"""Optional custom path to the .scalafmt.conf file.
|It should be a path (relative or absolute - though an absolute path is recommended) and use
|forward slashes `/` for file separators (even on Windows).
|""".stripMargin,
),
UserConfigurationOption(
"scalafix-config-path",
"""empty string `""`.""",
""""project/.scalafix.conf"""",
"Scalafix config path",
"""Optional custom path to the .scalafix.conf file.
|It should be a path (relative or absolute - though an absolute path is recommended) and use
|forward slashes `/` for file separators (even on Windows).
|""".stripMargin,
),
UserConfigurationOption(
"ammonite-jvm-properties",
"""`[]`.""",
"""["-Xmx1G"]""",
"Ammonite JVM Properties",
"""|Optional list of JVM properties to pass along to the Ammonite server.
|Each property needs to be a separate item.\n\nExample: `-Xmx1G` or `-Xms100M`"
|""".stripMargin,
),
UserConfigurationOption(
"excluded-packages",
"""`[]`.""",
"""["akka.actor.typed.javadsl"]""",
"Excluded Packages",
s"""|Packages that will be excluded from completions, imports, and symbol searches.
|
|Note that this is in addition to some default packages that are already excluded.
|The default excluded packages are listed below:
|```js
|${defaultExclusion}
|```
|
|If there is a need to remove one of the defaults, you are able to do so by including the
|package in your list and prepending `--` to it.
|
|Example:
|
|```js
|["--sun"]
|```
|""".stripMargin,
),
UserConfigurationOption(
"bloop-sbt-already-installed", "false", "false",
"Don't generate Bloop plugin file for sbt",
"If true, Metals will not generate `metals.sbt` files under the assumption that sbt-bloop is already manually installed in the sbt build. Build import will fail with a 'not valid command bloopInstall' error in case Bloop is not manually installed in the build when using this option.",
),
UserConfigurationOption(
"bloop-version",
BuildInfo.bloopVersion,
""""1.4.0-RC1"""",
"Version of Bloop",
"""|This version will be used for the Bloop build tool plugin, for any supported build tool,
|while importing in Metals as well as for running the embedded server""".stripMargin,
),
UserConfigurationOption(
"bloop-jvm-properties",
"""["-Xmx1G"].""",
"""["-Xmx1G"]""",
"Bloop JVM Properties",
"""|Optional list of JVM properties to pass along to the Bloop server.
|Please follow this guide for the format https://scalacenter.github.io/bloop/docs/server-reference#global-settings-for-the-server"
|""".stripMargin,
),
UserConfigurationOption(
"super-method-lenses-enabled",
"false",
"false",
"Should display lenses with links to super methods",
"""|Super method lenses are visible above methods definition that override another methods. Clicking on a lens jumps to super method definition.
|Disabled lenses are not calculated for opened documents which might speed up document processing.
|
|""".stripMargin,
),
UserConfigurationOption(
"show-inferred-type",
"false",
"false",
"Should display type annotations for inferred types",
"""|When this option is enabled, each method that can have inferred types has them
|displayed either as additional decorations if they are supported by the editor or
|shown in the hover.
|""".stripMargin,
),
UserConfigurationOption(
"show-implicit-arguments",
"false",
"false",
"Should display implicit parameter at usage sites",
"""|When this option is enabled, each method that has implicit arguments has them
|displayed either as additional decorations if they are supported by the editor or
|shown in the hover.
|""".stripMargin,
),
UserConfigurationOption(
"show-implicit-conversions-and-classes",
"false",
"false",
"Should display implicit conversion at usage sites",
"""|When this option is enabled, each place where an implicit method or class is used has it
|displayed either as additional decorations if they are supported by the editor or
|shown in the hover.
|""".stripMargin,
),
UserConfigurationOption(
"show-evidence-params",
"false",
"false",
"Should display context bounds evidence parameters at usage sites",
"""|When this option is enabled, each place where a context bound is used has it
|displayed either as additional decorations if they are supported by the editor or
|shown in the hover.
|""".stripMargin,
),
UserConfigurationOption(
"enable-semantic-highlighting",
"true",
"false",
"Use semantic tokens highlight",
"""|When this option is enabled, Metals will provide semantic tokens for clients that support it.
|The feature should work within all supported files extensions aside from Java.
|""".stripMargin,
),
UserConfigurationOption(
"enable-indent-on-paste",
"false",
"false",
"Indent snippets when pasted.",
"""|When this option is enabled, when a snippet is pasted into a Scala file, Metals will
|try to adjust the indentation to that of the current cursor.
|""".stripMargin,
),
UserConfigurationOption(
"fallback-scala-version",
BuildInfo.scala3,
BuildInfo.scala3,
"Default fallback Scala version",
"""|The Scala compiler version that is used as the default or fallback in case a file
|doesn't belong to any build target or the specified Scala version isn't supported by Metals.
|This applies to standalone Scala files, worksheets, and Ammonite scripts.
""".stripMargin,
),
UserConfigurationOption(
"test-user-interface",
"Code Lenses",
"test explorer",
"Test UI used for tests and test suites",
"""|Default way of handling tests and test suites. The only valid values are
|"code lenses" and "test explorer". See https://scalameta.org/metals/docs/integrations/test-explorer
|for information on how to work with the test explorer.
|""".stripMargin,
),
UserConfigurationOption(
"java-format.eclipse-config-path",
"""empty string `""`.""",
""""formatters/eclipse-formatter.xml"""",
"Eclipse Java formatter config path",
"""Optional custom path to the eclipse-formatter.xml file.
|It should be a path (relative or absolute - though an absolute path is recommended) and use
|forward slashes `/` for file separators (even on Windows).
|""".stripMargin,
),
UserConfigurationOption(
"java-format.eclipse-profile",
"""empty string `""`.""",
""""GoogleStyle"""",
"Eclipse Java formatting profile",
"""|If the Eclipse formatter file contains more than one profile, this option can be used to control which is used.
|""".stripMargin,
),
UserConfigurationOption(
"scala-cli-launcher",
"""empty string `""`.""",
""""/usr/local/bin/scala-cli"""",
"Scala CLI launcher",
"""Optional absolute path to a `scala-cli` executable to use for running a Scala CLI BSP server.
|By default, Metals uses the scala-cli from the PATH, or it's not found, downloads and runs Scala
|CLI on the JVM (slower than native Scala CLI). Update this if you want to use a custom Scala CLI
|launcher, not available in PATH.
|""".stripMargin,
),
UserConfigurationOption(
"custom-project-root",
"""empty string `""`.""",
""""backend/scalaProject/"""",
"Custom project root",
"""Optional relative path to your project's root.
|If you want your project root to be the workspace/workspace root set it to "." .""".stripMargin,
),
UserConfigurationOption(
"verbose-compilation",
"false",
"true",
"Show all compilation debugging information",
"""|If a build server supports it (for example Bloop or Scala CLI), setting it to true
|will make the logs contain all the possible debugging information including
|about incremental compilation in Zinc.""".stripMargin,
),
UserConfigurationOption(
"auto-import-build",
"off",
"all",
"Import build when changes detected without prompting",
"""|Automatically import builds rather than prompting the user to choose. "initial" will
|only automatically import a build when a project is first opened, "all" will automate
|build imports after subsequent changes as well.""".stripMargin,
),
UserConfigurationOption(
"default-bsp-to-build-tool",
"false",
"true",
"Default to using build tool as your build server.",
"""|If your build tool can also serve as a build server,
|default to using it instead of Bloop.
|""".stripMargin,
),
)
def fromJson(
json: JsonObject,
clientConfiguration: ClientConfiguration,
properties: Properties = System.getProperties,
): Either[List[String], UserConfiguration] = {
val errors = ListBuffer.empty[String]
def getKey[A](
key: String,
currentObject: JsonObject,
f: JsonElement => Option[A],
): Option[A] = {
def option[T](fn: String => T): Option[T] =
Option(fn(key)).orElse(Option(fn(StringCase.kebabToCamel(key))))
for {
jsonValue <- option(k => properties.getProperty(s"metals.$k"))
.filterNot(_.isEmpty())
.map(prop => new JsonPrimitive(prop))
.orElse(option(currentObject.get))
value <- f(jsonValue)
} yield value
}
def getSubKey(key: String): Option[JsonObject] =
getKey(
key,
json,
{ value =>
Try(value.getAsJsonObject())
.fold(
_ => {
errors += s"json error: key '$key' should have value of type object but obtained $value"
None
},
Some(_),
)
},
)
def getStringKey(key: String): Option[String] =
getStringKeyOnObj(key, json)
def getStringKeyOnObj(
key: String,
currentObject: JsonObject,
): Option[String] =
getKey(
key,
currentObject,
{ value =>
Try(value.getAsString)
.fold(
_ => {
errors += s"json error: key '$key' should have value of type string but obtained $value"
None
},
Some(_),
)
.filter(_.nonEmpty)
},
)
def getBooleanKey(key: String): Option[Boolean] =
getKey(
key,
json,
{ value =>
Try(value.getAsBoolean())
.fold(
_ => {
errors += s"json error: key '$key' should have value of type boolean but obtained $value"
None
},
Some(_),
)
},
)
def getIntKey(key: String): Option[Int] =
getStringKey(key).flatMap { value =>
Try(value.toInt) match {
case Failure(_) =>
errors += s"Not a number: '$value'"
None
case Success(value) =>
Some(value)
}
}
def getStringListKey(key: String): Option[List[String]] =
getKey[List[String]](
key,
json,
{ elem =>
if (elem.isJsonArray()) {
val parsed = elem.getAsJsonArray().asScala.flatMap { value =>
Try(value.getAsJsonPrimitive().getAsString()) match {
case Failure(_) =>
errors += s"json error: values in '$key' should have value of type string but obtained $value"
None
case Success(value) =>
Some(value)
}
}
Some(parsed.toList)
} else {
errors += s"json error: key '$key' should have value of type array but obtained $elem"
None
}
},
)
def getStringMap(key: String): Option[Map[String, String]] =
getKey(
key,
json,
{ value =>
Try {
for {
entry <- value.getAsJsonObject.entrySet().asScala.iterator
if entry.getValue.isJsonPrimitive &&
entry.getValue.getAsJsonPrimitive.isString
} yield {
entry.getKey -> entry.getValue.getAsJsonPrimitive.getAsString
}
}.fold(
_ => {
errors += s"json error: key '$key' should have be object with string values but obtained $value"
None
},
entries => Some(entries.toMap),
).filter(_.nonEmpty)
},
)
val javaHome =
getStringKey("java-home")
val scalafmtConfigPath =
getStringKey("scalafmt-config-path")
.map(AbsolutePath(_))
val scalafixConfigPath =
getStringKey("scalafix-config-path")
.map(AbsolutePath(_))
val sbtScript =
getStringKey("sbt-script")
val gradleScript =
getStringKey("gradle-script")
val mavenScript =
getStringKey("maven-script")
val millScript =
getStringKey("mill-script")
val symbolPrefixes =
getStringMap("symbol-prefixes")
.getOrElse(default.symbolPrefixes)
errors ++= symbolPrefixes.keys.flatMap { sym =>
Symbol.validated(sym).left.toOption
}
val worksheetScreenWidth =
getIntKey("worksheet-screen-width")
.getOrElse(default.worksheetScreenWidth)
val worksheetCancelTimeout =
getIntKey("worksheet-cancel-timeout")
.getOrElse(default.worksheetCancelTimeout)
val ammoniteProperties = getStringListKey("ammonite-jvm-properties")
val bloopSbtAlreadyInstalled =
getBooleanKey("bloop-sbt-already-installed").getOrElse(false)
val bloopVersion =
getStringKey("bloop-version")
val bloopJvmProperties = getStringListKey("bloop-jvm-properties")
val superMethodLensesEnabled =
getBooleanKey("super-method-lenses-enabled").getOrElse(false)
val showInferredType =
getStringKey("show-inferred-type")
val showImplicitArguments =
getBooleanKey("show-implicit-arguments").getOrElse(false)
val showImplicitConversionsAndClasses =
getBooleanKey("show-implicit-conversions-and-classes").getOrElse(false)
val showEvidenceParams =
getBooleanKey("show-evidence-params").getOrElse(false)
val enableStripMarginOnTypeFormatting =
getBooleanKey("enable-strip-margin-on-type-formatting").getOrElse(true)
val enableIndentOnPaste =
getBooleanKey("enable-indent-on-paste").getOrElse(true)
val enableSemanticHighlighting =
getBooleanKey("enable-semantic-highlighting").getOrElse(true)
val excludedPackages =
getStringListKey("excluded-packages")
// `automatic` should be treated as None
// It was added only to have a meaningful option value in vscode
val defaultScalaVersion =
getStringKey("fallback-scala-version").filter(_ != "automatic")
val disableTestCodeLenses = {
val isTestExplorerEnabled = clientConfiguration.isTestExplorerProvider()
getStringKey("test-user-interface").map(_.toLowerCase()) match {
case Some("test explorer") if isTestExplorerEnabled =>
TestUserInterfaceKind.TestExplorer
case _ =>
TestUserInterfaceKind.CodeLenses
}
}
val javaFormatConfig =
getSubKey("java-format").flatMap(subKey =>
getStringKeyOnObj("eclipse-config-path", subKey).map(f =>
JavaFormatConfig(
AbsolutePath(f),
getStringKeyOnObj("eclipse-profile", subKey),
)
)
)
val scalafixRulesDependencies =
getStringListKey("scalafix-rules-dependencies").getOrElse(Nil)
val customProjectRoot = getStringKey("custom-project-root")
val verboseCompilation =
getBooleanKey("verbose-compilation").getOrElse(false)
val autoImportBuilds =
getStringKey("auto-import-builds").map(_.trim().toLowerCase()) match {
case Some("initial") => AutoImportBuildKind.Initial
case Some("all") => AutoImportBuildKind.All
case _ => AutoImportBuildKind.Off
}
val scalaCliLauncher = getStringKey("scala-cli-launcher")
val defaultBspToBuildTool =
getBooleanKey("default-bsp-to-build-tool").getOrElse(false)
if (errors.isEmpty) {
Right(
UserConfiguration(
javaHome,
sbtScript,
gradleScript,
mavenScript,
millScript,
scalafmtConfigPath,
scalafixConfigPath,
symbolPrefixes,
worksheetScreenWidth,
worksheetCancelTimeout,
bloopSbtAlreadyInstalled,
bloopVersion,
bloopJvmProperties,
ammoniteProperties,
superMethodLensesEnabled,
showInferredType,
showImplicitArguments,
showImplicitConversionsAndClasses,
showEvidenceParams,
enableStripMarginOnTypeFormatting,
enableIndentOnPaste,
enableSemanticHighlighting,
excludedPackages,
defaultScalaVersion,
disableTestCodeLenses,
javaFormatConfig,
scalafixRulesDependencies,
customProjectRoot,
verboseCompilation,
autoImportBuilds,
scalaCliLauncher,
defaultBspToBuildTool,
)
)
} else {
Left(errors.toList)
}
}
def parse(config: String): JsonObject = {
import JsonParser._
config.parseJson.getAsJsonObject
}
}
sealed trait TestUserInterfaceKind
object TestUserInterfaceKind {
object CodeLenses extends TestUserInterfaceKind
object TestExplorer extends TestUserInterfaceKind
}
sealed trait AutoImportBuildKind
object AutoImportBuildKind {
object Off extends AutoImportBuildKind
object Initial extends AutoImportBuildKind
object All extends AutoImportBuildKind
}