-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathSwiftJavaPlugin.swift
More file actions
308 lines (260 loc) · 10.9 KB
/
SwiftJavaPlugin.swift
File metadata and controls
308 lines (260 loc) · 10.9 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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
//===----------------------------------------------------------------------===//
//
// 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 Foundation
import PackagePlugin
fileprivate let SwiftJavaConfigFileName = "swift-java.config"
@main
struct SwiftJavaBuildToolPlugin: SwiftJavaPluginProtocol, BuildToolPlugin {
var pluginName: String = "swift-java"
var verbose: Bool = getEnvironmentBool("SWIFT_JAVA_VERBOSE")
func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {
log("Create build commands for target '\(target.name)'")
guard let sourceModule = target.sourceModule else { return [] }
let executable = try context.tool(named: "SwiftJavaTool").url
var commands: [Command] = []
// Note: Target doesn't have a directoryURL counterpart to directory,
// so we cannot eliminate this deprecation warning.
let sourceDir = target.directory.string
// The name of the configuration file SwiftJava.config from the target for
// which we are generating Swift wrappers for Java classes.
let configFile = URL(filePath: sourceDir)
.appending(path: SwiftJavaConfigFileName)
let config = try readConfiguration(sourceDir: sourceDir) ?? Configuration()
log("Config on path: \(configFile.path(percentEncoded: false))")
log("Config was: \(config)")
var javaDependencies = config.dependencies ?? []
/// Find the manifest files from other swift-java executions in any targets
/// this target depends on.
var dependentConfigFiles: [(String, URL)] = []
func searchForConfigFiles(in target: any Target) {
// log("Search for config files in target: \(target.name)")
let dependencyURL = URL(filePath: target.directory.string)
// Look for a config file within this target.
let dependencyConfigURL = dependencyURL
.appending(path: SwiftJavaConfigFileName)
let dependencyConfigString = dependencyConfigURL
.path(percentEncoded: false)
if FileManager.default.fileExists(atPath: dependencyConfigString) {
dependentConfigFiles.append((target.name, dependencyConfigURL))
}
}
// Process direct dependencies of this target.
for dependency in target.dependencies {
switch dependency {
case .target(let target):
// log("Dependency target: \(target.name)")
searchForConfigFiles(in: target)
case .product(let product):
// log("Dependency product: \(product.name)")
for target in product.targets {
// log("Dependency product: \(product.name), target: \(target.name)")
searchForConfigFiles(in: target)
}
@unknown default:
break
}
}
// Process indirect target dependencies.
for dependency in target.recursiveTargetDependencies {
// log("Recursive dependency target: \(dependency.name)")
searchForConfigFiles(in: dependency)
}
var arguments: [String] = []
arguments += argumentsSwiftModule(sourceModule: sourceModule)
arguments += argumentsOutputDirectory(context: context)
arguments += argumentsDependedOnConfigs(dependentConfigFiles)
let classes = config.classes ?? [:]
print("[swift-java-plugin] Classes to wrap (\(classes.count)): \(classes.map(\.key))")
/// Determine the set of Swift files that will be emitted by the swift-java tool.
// TODO: this is not precise and won't work with more advanced Java files, e.g. lambdas etc.
let outputDirectoryGenerated = self.outputDirectory(context: context, generated: true)
let outputSwiftFiles = classes.compactMap { (javaClassName, swiftName) -> URL? in
guard shouldImportJavaClass(javaClassName, config: config) else {
return nil
}
let swiftNestedName = swiftName.replacingOccurrences(of: ".", with: "+")
return outputDirectoryGenerated.appending(path: "\(swiftNestedName).swift")
}
arguments += [
"--cache-directory",
context.pluginWorkDirectoryURL.path(percentEncoded: false)
]
// Find the Java .class files generated from prior plugins.
let compiledClassFiles = sourceModule.pluginGeneratedResources.filter { url in
url.pathExtension == "class"
}
if let firstClassFile = compiledClassFiles.first {
// Keep stripping off parts of the path until we hit the "Java" part.
// That's where the class path starts.
var classpath = firstClassFile
while classpath.lastPathComponent != "Java" {
classpath.deleteLastPathComponent()
}
arguments += ["--classpath", classpath.path()]
// For each of the class files, note that it can have Swift-native
// implementations. We figure this out based on the path.
for classFile in compiledClassFiles {
var classFile = classFile.deletingPathExtension()
var classNameComponents: [String] = []
while classFile.lastPathComponent != "Java" {
classNameComponents.append(classFile.lastPathComponent)
classFile.deleteLastPathComponent()
}
let className = classNameComponents
.reversed()
.joined(separator: ".")
arguments += ["--swift-native-implementation", className]
}
}
var fetchDependenciesOutputFiles: [URL] = []
if let dependencies = config.dependencies, !dependencies.isEmpty {
let displayName = "Fetch (Java) dependencies for Swift target \(sourceModule.name)"
log("Prepared: \(displayName)")
fetchDependenciesOutputFiles += [
outputFilePath(context: context, generated: false, filename: "\(sourceModule.name).swift-java.classpath")
]
commands += [
.buildCommand(
displayName: displayName,
executable: executable,
arguments: ["resolve"]
+ argumentsOutputDirectory(context: context, generated: false)
+ argumentsSwiftModule(sourceModule: sourceModule),
environment: [:],
inputFiles: [configFile],
outputFiles: fetchDependenciesOutputFiles
)
]
} else {
log("No dependencies to fetch for target \(sourceModule.name)")
}
// Add all the core Java stdlib modules as --depends-on
let javaStdlibModules = getExtractedJavaStdlibModules()
log("Include Java standard library SwiftJava modules: \(javaStdlibModules)")
let dependsOnArguments = javaStdlibModules.flatMap { ["--depends-on", $0] }
// TODO: make the dependsOnArguments unique, and preserve the ordering. We cannot use external dependencies. Make an extension on Array to achieve this
arguments += dependsOnArguments
if !outputSwiftFiles.isEmpty {
arguments += [ configFile.path(percentEncoded: false) ]
let displayName = "Wrapping \(classes.count) Java classes in Swift target '\(sourceModule.name)'"
log("Prepared: \(displayName)")
commands += [
.buildCommand(
displayName: displayName,
executable: executable,
arguments: ["wrap-java"]
+ arguments,
inputFiles: compiledClassFiles + fetchDependenciesOutputFiles + [ configFile ],
outputFiles: outputSwiftFiles
)
]
}
if commands.isEmpty {
log("No swift-java commands for module '\(sourceModule.name)'")
}
return commands
}
}
extension SwiftJavaBuildToolPlugin {
private func shouldImportJavaClass(_ javaClassName: String, config: Configuration) -> Bool {
// If we have an inclusive filter, import only types from it
if let includes = config.filterInclude, !includes.isEmpty {
let anyIncludeFilterMatched = includes.contains { include in
if javaClassName.starts(with: include) {
// TODO: lower to trace level
log("Skip Java type: \(javaClassName) (does not match any include filter)")
return true
}
return false
}
guard anyIncludeFilterMatched else {
log("Skip Java type: \(javaClassName) (does not match any include filter)")
return false
}
}
// If we have an exclude filter, check for it as well
for exclude in config.filterExclude ?? [] {
if javaClassName.starts(with: exclude) {
log("Skip Java type: \(javaClassName) (does match exclude filter: \(exclude))")
return false
}
}
// The class matches import filters, if any, and was not excluded.
return true
}
}
extension SwiftJavaBuildToolPlugin {
func argumentsSwiftModule(sourceModule: Target) -> [String] {
return [
"--swift-module", sourceModule.name
]
}
// FIXME: remove this and the deprecated property inside SwiftJava, this is a workaround
// since we cannot have the same option in common options and in the top level
// command from which we get into sub commands. The top command will NOT have this option.
func argumentsSwiftModuleDeprecated(sourceModule: Target) -> [String] {
return [
"--swift-module-deprecated", sourceModule.name
]
}
func argumentsOutputDirectory(context: PluginContext, generated: Bool = true) -> [String] {
return [
"--output-directory",
outputDirectory(context: context, generated: generated).path(percentEncoded: false)
]
}
func argumentsDependedOnConfigs(_ dependentConfigFiles: [(String, URL)]) -> [String] {
dependentConfigFiles.flatMap { moduleAndConfigFile in
let (moduleName, configFile) = moduleAndConfigFile
return [
"--depends-on",
"\(moduleName)=\(configFile.path(percentEncoded: false))"
]
}
}
func outputDirectory(context: PluginContext, generated: Bool = true) -> URL {
let dir = context.pluginWorkDirectoryURL
if generated {
return dir.appending(path: "generated")
} else {
return dir
}
}
func outputFilePath(context: PluginContext, generated: Bool, filename: String) -> URL {
outputDirectory(context: context, generated: generated).appending(path: filename)
}
}
func getExtractedJavaStdlibModules() -> [String] {
let fileManager = FileManager.default
let sourcesPath = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent()
.deletingLastPathComponent()
.appendingPathComponent("Sources")
.appendingPathComponent("JavaStdlib")
guard let stdlibDirContents = try? fileManager.contentsOfDirectory(
at: sourcesPath,
includingPropertiesForKeys: [.isDirectoryKey],
options: [.skipsHiddenFiles]
) else {
return []
}
return stdlibDirContents.compactMap { url in
guard let resourceValues = try? url.resourceValues(forKeys: [.isDirectoryKey]),
let isDirectory = resourceValues.isDirectory,
isDirectory else {
return nil
}
return url.lastPathComponent
}.sorted()
}