-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathJavaCallbacksBuildCommand.swift
More file actions
213 lines (180 loc) · 6.87 KB
/
JavaCallbacksBuildCommand.swift
File metadata and controls
213 lines (180 loc) · 6.87 KB
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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2024 Apple Inc. and the Swift.org project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift.org project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import ArgumentParser
import Foundation
import Subprocess
#if canImport(System)
import System
#else
@preconcurrency import SystemPackage
#endif
extension SwiftJava {
/// Builds Swift-Java callbacks in a single command:
/// 1. Building SwiftKitCore with Gradle
/// 2. Compiling extracted Java sources with javac
/// 3. Running `swift-java configure` to produce a swift-java.config
/// 4. Running `swift-java wrap-java` to generate Swift wrappers
///
/// **WORKAROUND**: rdar://172649681 if we invoke commands one by one with java outputs SwiftPM will link Foundation
///
/// This command is used by ``JExtractSwiftPlugin`` to consolidate all of the above
/// into a single build command that declares only a Swift file as its output,
/// avoiding SPM treating intermediate Java artifacts (compiled classes, config files,
/// Gradle output directories) as module resources, which would trigger
/// resource_bundle_accessor.swift generation and pull Foundation.Bundle into the binary.
struct JavaCallbacksBuildCommand: AsyncParsableCommand {
static let configuration = CommandConfiguration(
commandName: "java-callbacks-build",
abstract:
"Build SwiftKitCore, compile Java callbacks, and generate Swift wrappers (for use by JExtractSwiftPlugin)",
shouldDisplay: false,
)
// MARK: Gradle options
@Option(help: "Path to the gradle (or gradlew) executable")
var gradleExecutable: String
@Option(help: "The Gradle project directory (passed as --project-dir)")
var gradleProjectDir: String
@Option(help: "The Gradle user home directory (GRADLE_USER_HOME)")
var gradleUserHome: String
// MARK: javac options
@Option(help: "Path to the javac executable")
var javac: String
@Option(help: "Path to the @-file listing Java sources to compile")
var javaSourcesList: String
@Option(help: "Directory where compiled Java classes should be output")
var javaOutputDirectory: String
@Option(help: "Path to SwiftKitCore compiled classes (classpath for javac and wrap-java)")
var swiftKitCoreClasspath: String
// MARK: Swift generation options
@Option(help: "The name of the Swift module")
var swiftModule: String
@Option(help: "Prefix to add to generated Swift type names")
var swiftTypePrefix: String?
@Option(
name: .customLong("output-directory"),
help: "Directory where generated Swift files should be written",
)
var outputDirectory: String
@Option(help: "Name of the single Swift output file")
var singleSwiftFileOutput: String
@Option(help: "Path to the swift-java tool executable (used to invoke subcommands)")
var swiftJavaTool: String
@Option(
help:
"Dependent module configurations (format: ModuleName=/path/to/swift-java.config)"
)
var dependsOn: [String] = []
mutating func run() async throws {
let outputDir = URL(fileURLWithPath: outputDirectory)
let outputFile = outputDir.appendingPathComponent(singleSwiftFileOutput)
// 1. Build SwiftKitCore using Gradle.
try await runSubprocess(
executable: gradleExecutable,
arguments: [
":SwiftKitCore:build",
"--project-dir", gradleProjectDir,
"--gradle-user-home", gradleUserHome,
"--configure-on-demand",
"--no-daemon",
],
environment: .inherit.updating(["GRADLE_USER_HOME": gradleUserHome]),
errorMessage: "gradle :SwiftKitCore:build",
)
// If the sources list does not exist, jextract produced no Java callbacks.
// Write an empty placeholder Swift file and return early.
guard FileManager.default.fileExists(atPath: javaSourcesList) else {
try FileManager.default.createDirectory(at: outputDir, withIntermediateDirectories: true)
try "// No Java callbacks generated\n".write(
to: outputFile,
atomically: true,
encoding: .utf8,
)
return
}
// 2. Compile Java sources with javac.
try FileManager.default.createDirectory(
atPath: javaOutputDirectory,
withIntermediateDirectories: true,
)
try await runSubprocess(
executable: javac,
arguments: [
"@\(javaSourcesList)",
"-d", javaOutputDirectory,
"-parameters",
"-classpath", swiftKitCoreClasspath,
],
errorMessage: "javac",
)
// 3. Generate swift-java.config from compiled classes.
// Written into javaOutputDirectory (inside pluginWorkDirectory) but NOT
// declared as a build command output, so SPM will not bundle it as a resource.
var configureArgs = [
"configure",
"--output-directory", javaOutputDirectory,
"--cp", javaOutputDirectory,
"--swift-module", swiftModule,
]
if let prefix = swiftTypePrefix {
configureArgs += ["--swift-type-prefix", prefix]
}
try await runSubprocess(
executable: swiftJavaTool,
arguments: configureArgs,
errorMessage: "swift-java configure",
)
// 4. Generate Swift wrappers using wrap-java.
let configPath = URL(fileURLWithPath: javaOutputDirectory)
.appendingPathComponent("swift-java.config").path
var wrapJavaArgs = [
"wrap-java",
"--swift-module", swiftModule,
"--output-directory", outputDirectory,
"--config", configPath,
"--cp", swiftKitCoreClasspath,
"--single-swift-file-output", singleSwiftFileOutput,
]
wrapJavaArgs += dependsOn.flatMap { ["--depends-on", $0] }
try await runSubprocess(
executable: swiftJavaTool,
arguments: wrapJavaArgs,
errorMessage: "swift-java wrap-java",
)
}
}
}
// MARK: - Helpers
private func runSubprocess(
executable: String,
arguments: [String],
environment: Subprocess.Environment = .inherit,
errorMessage: String,
) async throws {
let result = try await Subprocess.run(
.path(FilePath(executable)),
arguments: .init(arguments),
environment: environment,
output: .standardOutput,
error: .standardError,
)
guard result.terminationStatus.isSuccess else {
throw JavaCallbacksBuildError(
"\(errorMessage) failed with exit status \(result.terminationStatus)"
)
}
}
struct JavaCallbacksBuildError: Error, CustomStringConvertible {
let description: String
init(_ message: String) { self.description = message }
}