4
4
import CompilerPluginSupport
5
5
import PackageDescription
6
6
7
- import class Foundation. FileManager
8
- import class Foundation. ProcessInfo
7
+ import Foundation
9
8
10
9
// Note: the JAVA_HOME environment variable must be set to point to where
11
10
// Java is installed, e.g.,
@@ -25,9 +24,53 @@ func findJavaHome() -> String {
25
24
26
25
return home
27
26
}
27
+
28
+ if let home = getJavaHomeFromLibexecJavaHome ( ) ,
29
+ !home. isEmpty {
30
+ return home
31
+ }
28
32
29
33
fatalError ( " Please set the JAVA_HOME environment variable to point to where Java is installed. " )
30
34
}
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
+
31
74
let javaHome = findJavaHome ( )
32
75
33
76
let javaIncludePath = " \( javaHome) /include "
0 commit comments