-
Notifications
You must be signed in to change notification settings - Fork 48
PoC of using gradle to obtain classpath for dependency expressed in config #137
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
Closed
Closed
Changes from all commits
Commits
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 |
---|---|---|
@@ -0,0 +1,76 @@ | ||
// swift-tools-version: 6.0 | ||
// The swift-tools-version declares the minimum version of Swift required to build this package. | ||
|
||
import CompilerPluginSupport | ||
import PackageDescription | ||
|
||
import class Foundation.FileManager | ||
import class Foundation.ProcessInfo | ||
|
||
// 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.") | ||
} | ||
let javaHome = findJavaHome() | ||
|
||
let javaIncludePath = "\(javaHome)/include" | ||
#if os(Linux) | ||
let javaPlatformIncludePath = "\(javaIncludePath)/linux" | ||
#elseif os(macOS) | ||
let javaPlatformIncludePath = "\(javaIncludePath)/darwin" | ||
#else | ||
// TODO: Handle windows as well | ||
#error("Currently only macOS and Linux platforms are supported, this may change in the future.") | ||
#endif | ||
|
||
let package = Package( | ||
name: "swift-java-benchmarks", | ||
|
||
platforms: [ | ||
.macOS(.v14) | ||
], | ||
|
||
dependencies: [ | ||
.package(name: "swift-java", path: "../"), | ||
|
||
// plugins | ||
.package(url: "https://github.com/ordo-one/package-benchmark", .upToNextMajor(from: "1.4.0")), | ||
], | ||
|
||
targets: [ | ||
.executableTarget( | ||
name: "JavaApiCallBenchmarks", | ||
dependencies: [ | ||
.product(name: "Benchmark", package: "package-benchmark"), | ||
.product(name: "JavaRuntime", package: "swift-java"), | ||
.product(name: "JavaKit", package: "swift-java"), | ||
.product(name: "JavaKitNetwork", package: "swift-java"), | ||
], | ||
path: "Benchmarks/JavaApiCallBenchmarks", | ||
swiftSettings: [ | ||
.unsafeFlags(["-I\(javaIncludePath)", "-I\(javaPlatformIncludePath)"]), | ||
.swiftLanguageMode(.v5), | ||
], | ||
plugins: [ | ||
.plugin(name: "BenchmarkPlugin", package: "package-benchmark"), | ||
] | ||
), | ||
] | ||
) |
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,44 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// 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 | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
plugins { | ||
id("build-logic.java-application-conventions") | ||
} | ||
|
||
group = "org.swift.javakit" | ||
version = "1.0-SNAPSHOT" | ||
|
||
repositories { | ||
mavenCentral() | ||
} | ||
|
||
java { | ||
toolchain { | ||
languageVersion.set(JavaLanguageVersion.of(22)) | ||
} | ||
} | ||
|
||
dependencies { | ||
implementation("dev.gradleplugins:gradle-api:8.10.1") | ||
|
||
testImplementation(platform("org.junit:junit-bom:5.10.0")) | ||
testImplementation("org.junit.jupiter:junit-jupiter") | ||
} | ||
|
||
tasks.test { | ||
useJUnitPlatform() | ||
testLogging { | ||
events("passed", "skipped", "failed") | ||
} | ||
} |
75 changes: 75 additions & 0 deletions
75
JavaKit/src/main/java/org/swift/javakit/dependencies/DependencyResolver.java
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,75 @@ | ||
package org.swift.javakit.dependencies; | ||
|
||
import org.gradle.tooling.GradleConnector; | ||
|
||
import java.io.*; | ||
import java.nio.file.Files; | ||
import java.util.Arrays; | ||
|
||
public class DependencyResolver { | ||
/** | ||
* May throw runtime exceptions including {@link org.gradle.api.internal.artifacts.ivyservice.TypedResolveException} | ||
* if unable to resolve a dependency. | ||
*/ | ||
public static String getClasspathWithDependency(String[] dependencies) throws IOException { | ||
File projectDir = Files.createTempDirectory("java-swift-dependencies").toFile(); | ||
projectDir.mkdirs(); | ||
|
||
File buildFile = new File(projectDir, "build.gradle"); | ||
try (PrintWriter writer = new PrintWriter(buildFile)) { | ||
writer.println("plugins { id 'java-library' }"); | ||
writer.println("repositories { mavenCentral() }"); | ||
|
||
writer.println("dependencies {"); | ||
for (String dependency : dependencies) { | ||
writer.println("implementation(\"" + dependency + "\")"); | ||
} | ||
writer.println("}"); | ||
|
||
writer.println(""" | ||
task printRuntimeClasspath { | ||
def runtimeClasspath = sourceSets.main.runtimeClasspath | ||
inputs.files(runtimeClasspath) | ||
doLast { | ||
println("CLASSPATH:${runtimeClasspath.asPath}") | ||
} | ||
} | ||
"""); | ||
} | ||
|
||
File settingsFile = new File(projectDir, "settings.gradle.kts"); | ||
try (PrintWriter writer = new PrintWriter(settingsFile)) { | ||
writer.println(""" | ||
rootProject.name = "swift-java-resolve-dependencies-temp-project" | ||
"""); | ||
} | ||
|
||
var connection = GradleConnector.newConnector() | ||
.forProjectDirectory(projectDir) | ||
.connect(); | ||
|
||
try (connection) { | ||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); | ||
PrintStream printStream = new PrintStream(outputStream); | ||
|
||
connection.newBuild().forTasks(":printRuntimeClasspath") | ||
.setStandardError(new NoopOutputStream()) | ||
.setStandardOutput(printStream) | ||
.run(); | ||
|
||
var all = outputStream.toString(); | ||
var classpath = Arrays.stream(all.split("\n")) | ||
.filter(s -> s.startsWith("CLASSPATH:")) | ||
.map(s -> s.substring("CLASSPATH:".length())) | ||
.findFirst().orElseThrow(() -> new RuntimeException("Could not find classpath output from ':printRuntimeClasspath' task.")); | ||
return classpath; | ||
} | ||
} | ||
|
||
private static class NoopOutputStream extends OutputStream { | ||
@Override | ||
public void write(int b) throws IOException { | ||
// ignore | ||
} | ||
} | ||
} |
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
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,8 @@ | ||
.DS_Store | ||
/.build | ||
/Packages | ||
xcuserdata/ | ||
DerivedData/ | ||
.swiftpm/configuration/registries.json | ||
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata | ||
.netrc |
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,63 @@ | ||
// swift-tools-version: 6.0 | ||
// The swift-tools-version declares the minimum version of Swift required to build this package. | ||
|
||
import PackageDescription | ||
|
||
import class Foundation.FileManager | ||
import class Foundation.ProcessInfo | ||
|
||
// 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.") | ||
} | ||
let javaHome = findJavaHome() | ||
|
||
let javaIncludePath = "\(javaHome)/include" | ||
#if os(Linux) | ||
let javaPlatformIncludePath = "\(javaIncludePath)/linux" | ||
#elseif os(macOS) | ||
let javaPlatformIncludePath = "\(javaIncludePath)/darwin" | ||
#else | ||
// TODO: Handle windows as well | ||
#error("Currently only macOS and Linux platforms are supported, this may change in the future.") | ||
#endif | ||
|
||
let package = Package( | ||
name: "JavaDependenciesExample", | ||
platforms: [ | ||
.macOS(.v10_15), | ||
], | ||
dependencies: [ | ||
.package(name: "swift-java", path: "../../"), | ||
], | ||
targets: [ | ||
.executableTarget( | ||
name: "JavaJacksonDatabind", | ||
dependencies: [ | ||
], | ||
swiftSettings: [ | ||
.unsafeFlags(["-I\(javaIncludePath)", "-I\(javaPlatformIncludePath)"]) | ||
], | ||
plugins: [ | ||
.plugin(name: "Java2SwiftPlugin", package: "swift-java"), | ||
] | ||
), | ||
] | ||
) |
6 changes: 6 additions & 0 deletions
6
Samples/JavaDependenciesApp/Sources/JavaJacksonDatabind/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,6 @@ | ||
{ | ||
"dependencies": [ | ||
"dev.gradleplugins:gradle-api:8.10.1" | ||
], | ||
"classes": {} | ||
} |
25 changes: 25 additions & 0 deletions
25
Samples/JavaDependenciesApp/Sources/JavaJacksonDatabind/main.swift
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,25 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// 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 JavaKit | ||
|
||
let jvm = try JavaVirtualMachine.shared(classPath: ["QuadraticSieve-1.0.jar"]) | ||
do { | ||
let sieveClass = try JavaClass<SieveOfEratosthenes>(environment: jvm.environment()) | ||
for prime in sieveClass.findPrimes(100)! { | ||
print("Found prime: \(prime.intValue())") | ||
} | ||
} catch { | ||
print("Failure: \(error)") | ||
} |
Oops, something went wrong.
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.
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.
Silly trick, but effective ¯_(ツ)_/¯
We could implement the same methods with more direct raw APIs eventually but this gets us going and tbh gets the job done well enough. It would also integrate well with targeting a real build.gradle so we can share dependencies with a real build definition, and not re-declare them for swift in a different place again if a project is using gradle anyway.