-
Notifications
You must be signed in to change notification settings - Fork 49
Add a SwiftPM build plugin to generate Swift wrappers for Java classes #77
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,6 +5,7 @@ | |
.swift-format | ||
.github/* | ||
*.md | ||
**/*.config | ||
CONTRIBUTORS.txt | ||
LICENSE.txt | ||
NOTICE.txt | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// 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 | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
/// Configuration for the Java2Swift translation tool, provided on a per-target | ||
/// basis. | ||
struct Configuration: Codable { | ||
/// The Java class path that should be passed along to the Java2Swift tool. | ||
var classPath: String? = nil | ||
|
||
/// The Java classes that should be translated to Swift. The keys are | ||
/// canonical Java class names (e.g., java.util.Vector) and the values are | ||
/// the corresponding Swift names (e.g., JavaVector). If the value is `nil`, | ||
/// then the Java class name will be used for the Swift name, too. | ||
var classes: [String: String?] = [:] | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,154 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// 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 | ||
|
||
@main | ||
struct Java2SwiftBuildToolPlugin: BuildToolPlugin { | ||
func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] { | ||
guard let sourceModule = target.sourceModule else { return [] } | ||
|
||
// Note: Target doesn't have a directoryURL counterpart to directory, | ||
// so we cannot eliminate this deprecation warning. | ||
let sourceDir = target.directory.string | ||
|
||
// Read a configuration file JavaKit.config from the target that provides | ||
// information needed to call Java2Swift. | ||
let configFile = URL(filePath: sourceDir) | ||
.appending(path: "Java2Swift.config") | ||
let configData = try Data(contentsOf: configFile) | ||
let config = try JSONDecoder().decode(Configuration.self, from: configData) | ||
|
||
/// Find the manifest files from other Java2Swift executions in any targets | ||
/// this target depends on. | ||
var manifestFiles: [URL] = [] | ||
func searchForManifestFiles(in target: any Target) { | ||
let dependencyURL = URL(filePath: target.directory.string) | ||
|
||
// Look for a checked-in manifest file. | ||
let generatedManifestURL = dependencyURL | ||
.appending(path: "generated") | ||
.appending(path: "\(target.name).swift2java") | ||
let generatedManifestString = generatedManifestURL | ||
.path(percentEncoded: false) | ||
|
||
if FileManager.default.fileExists(atPath: generatedManifestString) { | ||
manifestFiles.append(generatedManifestURL) | ||
} | ||
|
||
// TODO: Look for a manifest file that was built by the plugin itself. | ||
} | ||
|
||
// Process direct dependencies of this target. | ||
for dependency in target.dependencies { | ||
switch dependency { | ||
case .target(let target): | ||
searchForManifestFiles(in: target) | ||
|
||
case .product(let product): | ||
for target in product.targets { | ||
searchForManifestFiles(in: target) | ||
} | ||
|
||
@unknown default: | ||
break | ||
} | ||
} | ||
|
||
// Process indirect target dependencies. | ||
for dependency in target.recursiveTargetDependencies { | ||
searchForManifestFiles(in: dependency) | ||
} | ||
|
||
/// Determine the list of Java classes that will be translated into Swift, | ||
/// along with the names of the corresponding Swift types. This will be | ||
/// passed along to the Java2Swift tool. | ||
let classes = config.classes.map { (javaClassName, swiftName) in | ||
(javaClassName, swiftName ?? javaClassName.defaultSwiftNameForJavaClass) | ||
}.sorted { (lhs, rhs) in | ||
lhs.0 < rhs.0 | ||
} | ||
|
||
let outputDirectory = context.pluginWorkDirectoryURL | ||
.appending(path: "generated") | ||
|
||
var arguments: [String] = [ | ||
"--module-name", sourceModule.name, | ||
"--output-directory", outputDirectory.path(percentEncoded: false), | ||
] | ||
if let classPath = config.classPath { | ||
arguments += ["-cp", classPath] | ||
} | ||
arguments += manifestFiles.flatMap { manifestFile in | ||
[ "--manifests", manifestFile.path(percentEncoded: false) ] | ||
} | ||
arguments += classes.map { (javaClassName, swiftName) in | ||
"\(javaClassName)=\(swiftName)" | ||
} | ||
|
||
/// Determine the set of Swift files that will be emitted by the Java2Swift | ||
/// tool. | ||
let outputSwiftFiles = classes.map { (javaClassName, swiftName) in | ||
outputDirectory.appending(path: "\(swiftName).swift") | ||
} + [ | ||
outputDirectory.appending(path: "\(sourceModule.name).swift2java") | ||
] | ||
|
||
return [ | ||
.buildCommand( | ||
displayName: "Wrapping \(classes.count) Java classes target \(sourceModule.name) in Swift", | ||
executable: try context.tool(named: "Java2Swift").url, | ||
arguments: arguments, | ||
inputFiles: [ configFile ], | ||
outputFiles: outputSwiftFiles | ||
) | ||
] | ||
} | ||
} | ||
|
||
// Note: the JAVA_HOME environment variable must be set to point to where | ||
// Java is installed, e.g., | ||
// Library/Java/JavaVirtualMachines/openjdk-21.jdk/Contents/Home. | ||
func findJavaHome() -> String { | ||
if let home = ProcessInfo.processInfo.environment["JAVA_HOME"] { | ||
return home | ||
} | ||
|
||
// This is a workaround for envs (some IDEs) which have trouble with | ||
// picking up env variables during the build process | ||
let path = "\(FileManager.default.homeDirectoryForCurrentUser.path()).java_home" | ||
if let home = try? String(contentsOfFile: path, encoding: .utf8) { | ||
if let lastChar = home.last, lastChar.isNewline { | ||
return String(home.dropLast()) | ||
} | ||
|
||
return home | ||
} | ||
|
||
fatalError("Please set the JAVA_HOME environment variable to point to where Java is installed.") | ||
} | ||
|
||
extension String { | ||
/// For a String that's of the form java.util.Vector, return the "Vector" | ||
/// part. | ||
fileprivate var defaultSwiftNameForJavaClass: String { | ||
if let dotLoc = lastIndex(of: ".") { | ||
let afterDot = index(after: dotLoc) | ||
return String(self[afterDot...]) | ||
} | ||
|
||
return self | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
5 changes: 5 additions & 0 deletions
5
Samples/JavaKitSampleApp/Sources/JavaKitExample/Java2Swift.config
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
{ | ||
"classes" : { | ||
"java.util.ArrayList" : "ArrayList" | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is to fix the license checking CI job, since it checked and failed on the new file not having a license header
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ah, thank you!