Skip to content

Commit 0919860

Browse files
committed
[Package.swift] improve detecting JAVA_HOME on macos by using java_home
1 parent 7d8b901 commit 0919860

File tree

1 file changed

+45
-2
lines changed

1 file changed

+45
-2
lines changed

Package.swift

Lines changed: 45 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@
44
import CompilerPluginSupport
55
import PackageDescription
66

7-
import class Foundation.FileManager
8-
import class Foundation.ProcessInfo
7+
import Foundation
98

109
// Note: the JAVA_HOME environment variable must be set to point to where
1110
// Java is installed, e.g.,
@@ -25,9 +24,53 @@ func findJavaHome() -> String {
2524

2625
return home
2726
}
27+
28+
if let home = getJavaHomeFromLibexecJavaHome(),
29+
!home.isEmpty {
30+
return home
31+
}
2832

2933
fatalError("Please set the JAVA_HOME environment variable to point to where Java is installed.")
3034
}
35+
36+
/// On MacOS we can use the java_home tool as a fallback if we can't find JAVA_HOME environment variable.
37+
func getJavaHomeFromLibexecJavaHome() -> String? {
38+
let task = Process()
39+
task.executableURL = URL(fileURLWithPath: "/usr/libexec/java_home")
40+
41+
// Check if the executable exists before trying to run it
42+
guard FileManager.default.fileExists(atPath: task.executableURL!.path) else {
43+
print("/usr/libexec/java_home does not exist")
44+
return nil
45+
}
46+
47+
let pipe = Pipe()
48+
task.standardOutput = pipe
49+
task.standardError = pipe // Redirect standard error to the same pipe for simplicity
50+
51+
do {
52+
try task.run()
53+
task.waitUntilExit()
54+
55+
let data = pipe.fileHandleForReading.readDataToEndOfFile()
56+
let output = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines)
57+
58+
if task.terminationStatus == 0 {
59+
return output
60+
} else {
61+
print("java_home terminated with status: \(task.terminationStatus)")
62+
// Optionally, log the error output for debugging
63+
if let errorOutput = String(data: pipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) {
64+
print("Error output: \(errorOutput)")
65+
}
66+
return nil
67+
}
68+
} catch {
69+
print("Error running java_home: \(error)")
70+
return nil
71+
}
72+
}
73+
3174
let javaHome = findJavaHome()
3275

3376
let javaIncludePath = "\(javaHome)/include"

0 commit comments

Comments
 (0)