44import CompilerPluginSupport
55import 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+
3174let javaHome = findJavaHome ( )
3275
3376let javaIncludePath = " \( javaHome) /include "
0 commit comments