Skip to content

Commit f98dd76

Browse files
authored
Merge pull request #271 from mkurz/javafmt-java-home-overrides
Support overriding the formatter Java home
2 parents 5eb8ca3 + ccaaaff commit f98dd76

2 files changed

Lines changed: 22 additions & 2 deletions

File tree

README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,15 @@ This plugin uses the [Google Java Format](https://github.com/google/google-java-
5757

5858
The formatter runs in a forked JVM managed by the plugin.
5959

60+
By default it uses the same Java installation as the sbt process via `java.home`.
61+
62+
To make the plugin launch the formatter with a different Java installation, set either:
63+
64+
- the `sbt-javafmt.java.home` JVM system property
65+
- or the `SBT_JAVAFMT_JAVA_HOME` environment variable
66+
67+
If both are set, `sbt-javafmt.java.home` takes precedence.
68+
6069
Use `javafmtJavaMaxHeap` to control the maximum heap size passed to that JVM:
6170

6271
```scala

plugin/src/main/scala/com/github/sbt/javaformatter/JavaFormatter.scala

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ import scala.sys.process.{ Process, ProcessLogger }
3030
object JavaFormatter {
3131

3232
private val GoogleJavaFormatMain = "com.google.googlejavaformat.java.Main"
33+
private val JavaHomeEnvVar = "SBT_JAVAFMT_JAVA_HOME"
34+
private val JavaHomeProperty = "sbt-javafmt.java.home"
3335

3436
private val JavaExports = Seq("api", "code", "file", "parser", "tree", "util").map { exportedPackage =>
3537
s"--add-exports=jdk.compiler/com.sun.tools.javac.$exportedPackage=ALL-UNNAMED"
@@ -351,14 +353,23 @@ object JavaFormatter {
351353
classpathFrom(getClass.getClassLoader).distinct.mkString(File.pathSeparator)
352354

353355
private lazy val javaBin: String = {
354-
val javaHome = new File(sys.props("java.home"))
356+
val javaHomeSourceAndPath =
357+
sys.props
358+
.get(JavaHomeProperty)
359+
.filter(_.nonEmpty)
360+
.map(path => (JavaHomeProperty, path))
361+
.orElse(sys.env.get(JavaHomeEnvVar).filter(_.nonEmpty).map(path => (JavaHomeEnvVar, path)))
362+
.getOrElse(("java.home", sys.props("java.home")))
363+
val (javaHomeSource, javaHomePath) = javaHomeSourceAndPath
364+
val javaHome = new File(javaHomePath)
355365
val unixJava = new File(javaHome, "bin/java")
356366
val windowsJava = new File(javaHome, "bin/java.exe")
357367
val javaExec =
358368
if (unixJava.isFile) unixJava
359369
else if (windowsJava.isFile) windowsJava
360370
else {
361-
throw new MessageOnlyException(s"Could not locate a Java launcher under java.home=${javaHome.getAbsolutePath}")
371+
throw new MessageOnlyException(
372+
s"Could not locate a Java launcher under ${javaHomeSource}=${javaHome.getAbsolutePath}")
362373
}
363374
javaExec.getAbsolutePath
364375
}

0 commit comments

Comments
 (0)