Skip to content

Commit 1d4d25f

Browse files
committed
sample is now generating config from pulled dependency
1 parent 3254f8b commit 1d4d25f

File tree

17 files changed

+229
-143
lines changed

17 files changed

+229
-143
lines changed

Package.swift

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,7 @@ let package = Package(
316316
"JavaKitReflection",
317317
"JavaKitNetwork",
318318
"JavaTypes",
319+
"JavaKitShared",
319320
"JavaKitConfigurationShared",
320321
"JavaKitDependencyResolver",
321322
],
@@ -338,6 +339,7 @@ let package = Package(
338339
"JavaKitNetwork",
339340
"Java2SwiftLib",
340341
"JavaKitDependencyResolver",
342+
"JavaKitShared",
341343
],
342344

343345
swiftSettings: [

Samples/JavaDependencySampleApp/Package.swift

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,9 @@ let package = Package(
5151
],
5252

5353
products: [
54-
.library(
55-
name: "JavaKitExample",
56-
type: .dynamic,
57-
targets: ["JavaKitExample"]
54+
.executable(
55+
name: "JavaDependencySample",
56+
targets: ["JavaDependencySample"]
5857
),
5958
],
6059

@@ -63,11 +62,13 @@ let package = Package(
6362
],
6463

6564
targets: [
66-
.target(
65+
.executableTarget(
6766
name: "JavaDependencySample",
6867
dependencies: [
6968
.product(name: "JavaKit", package: "swift-java"),
69+
.product(name: "JavaRuntime", package: "swift-java"),
7070
.product(name: "JavaKitFunction", package: "swift-java"),
71+
"ReactiveStreams"
7172
],
7273
swiftSettings: [
7374
.unsafeFlags(["-I\(javaIncludePath)", "-I\(javaPlatformIncludePath)"])
@@ -76,5 +77,20 @@ let package = Package(
7677
.plugin(name: "SwiftJavaPlugin", package: "swift-java"),
7778
]
7879
),
80+
81+
.target(
82+
name: "ReactiveStreams",
83+
dependencies: [
84+
.product(name: "JavaKit", package: "swift-java"),
85+
.product(name: "JavaRuntime", package: "swift-java"),
86+
],
87+
swiftSettings: [
88+
.unsafeFlags(["-I\(javaIncludePath)", "-I\(javaPlatformIncludePath)"])
89+
],
90+
plugins: [
91+
.plugin(name: "SwiftJavaPlugin", package: "swift-java"),
92+
]
93+
),
94+
7995
]
8096
)
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"classes" : {
3+
},
4+
"classpath" : "\/Users\/ktoso\/.gradle\/caches\/modules-2\/files-2.1\/com.google.guava\/guava\/33.3.1-jre\/852f8b363da0111e819460021ca693cacca3e8db\/guava-33.3.1-jre.jar:\/Users\/ktoso\/.gradle\/caches\/modules-2\/files-2.1\/com.google.guava\/failureaccess\/1.0.2\/c4a06a64e650562f30b7bf9aaec1bfed43aca12b\/failureaccess-1.0.2.jar:\/Users\/ktoso\/.gradle\/caches\/modules-2\/files-2.1\/com.google.guava\/listenablefuture\/9999.0-empty-to-avoid-conflict-with-guava\/b421526c5f297295adef1c886e5246c39d4ac629\/listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar:\/Users\/ktoso\/.gradle\/caches\/modules-2\/files-2.1\/com.google.code.findbugs\/jsr305\/3.0.2\/25ea2e8b0c338a877313bd4672d3fe056ea78f0d\/jsr305-3.0.2.jar:\/Users\/ktoso\/.gradle\/caches\/modules-2\/files-2.1\/org.checkerframework\/checker-qual\/3.43.0\/9425eee39e56b116d2b998b7c2cebcbd11a3c98b\/checker-qual-3.43.0.jar:\/Users\/ktoso\/.gradle\/caches\/modules-2\/files-2.1\/com.google.errorprone\/error_prone_annotations\/2.28.0\/59fc00087ce372de42e394d2c789295dff2d19f0\/error_prone_annotations-2.28.0.jar:\/Users\/ktoso\/.gradle\/caches\/modules-2\/files-2.1\/com.google.j2objc\/j2objc-annotations\/3.0.0\/7399e65dd7e9ff3404f4535b2f017093bdb134c7\/j2objc-annotations-3.0.0.jar",
5+
"dependencies" : [
6+
"com.google.guava:guava:33.3.1-jre"
7+
]
8+
}

Samples/JavaDependencySampleApp/Sources/JavaDependencySample/main.swift

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,9 @@
1414

1515
import JavaKit
1616
import JavaKitFunction
17+
import ReactiveStreams
18+
19+
// Just showcasing that we imported the module
20+
let s: Subscriber<Int>? = nil
21+
22+
print("Done.")
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"dependencies": [
3-
"org.reactivestreams:reactive-streams:1.0.4"
3+
"com.google.guava:guava:33.3.1-jre"
44
],
55
"__FIXME": "we should not need to express this classpath!",
6-
"classPath": "JavaKit/build/classes/java/main:../../JavaKit/build/classes/java/main",
6+
"classpath": "JavaKit/build/classes/java/main:../../JavaKit/build/classes/java/main",
77
}

Samples/JavaDependencySampleApp/Sources/ReactiveStreams/.gitkeep

Whitespace-only changes.

Samples/JavaDependencySampleApp/Sources/ReactiveStreams/swift-java.config

Lines changed: 0 additions & 18 deletions
This file was deleted.
Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,24 @@
11
#!/bin/sh
22

3-
# TODO:
3+
JAVASWIFT="../../.build/debug/Java2Swift"
44

5-
# downloads all the dependencies
6-
../../.build/debug/Java2Swift --fetch Sources/JavaDependencySample/swift-java.config
5+
MODULE_NAME=Guava
6+
MODULE_CONFIG_DIR=$(pwd)/Sources/$MODULE_NAME/
7+
MODULE_CONFIG_PATH="$MODULE_CONFIG_DIR/swift-java.config"
78

8-
"$JAVA_HOME/bin/java" \
9-
-cp .build/plugins/outputs/javakitsampleapp/JavaKitExample/destination/JavaCompilerPlugin/Java \
10-
-Djava.library.path=.build/debug \
11-
"com.example.swift.JavaKitSampleMain"
9+
### 1) downloads all the dependencies
10+
"$JAVASWIFT" --fetch Sources/JavaDependencySample/swift-java.config \
11+
--module-name "$MODULE_NAME" \
12+
--output-directory "$MODULE_CONFIG_DIR"
13+
14+
### 2) extract the config for the fetched dependency
15+
DEP_JAR_CP=$(jq .classpath "$MODULE_CONFIG_PATH")
16+
DEP_JAR_CP=$(echo "$DEP_JAR_CP" | tr -d '"') # trim the "..."
17+
# FIXME: "jar" is the wrong word for it
18+
# shellcheck disable=SC2086
19+
"$JAVASWIFT" --jar $DEP_JAR_CP \
20+
--module-name "$MODULE_NAME" \
21+
--existing-config amend
22+
23+
### 3) make wrappers for the module
24+
"$JAVASWIFT" "$MODULE_CONFIG_PATH" --module-name "$MODULE_NAME"

Sources/Java2Swift/JavaToSwift+EmitConfiguration.swift

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,20 @@ import JavaKitDependencyResolver
2222
import JavaKitConfigurationShared
2323

2424
extension JavaToSwift {
25+
26+
// TODO: make this perhaps "emit type mappings"
2527
mutating func emitConfiguration(
2628
forJarFile jarFileName: String,
27-
classPath: String,
29+
classpath: String,
2830
environment: JNIEnvironment
2931
) throws {
30-
var configuration = Configuration()
31-
configuration.classPath = classPath
32+
// Get a fresh or existing configuration we'll amend
33+
var (amendExistingConfig, configuration) = try getBaseConfigurationForWrite()
34+
if amendExistingConfig {
35+
print("[java-swift] Amend existing swift-java.config file...")
36+
} else {
37+
configuration.classpath = classpath // TODO: is this correct?
38+
}
3239

3340
let jarFile = try JarFile(jarFileName, false, environment: environment)
3441
for entry in jarFile.entries()! {
@@ -44,15 +51,26 @@ extension JavaToSwift {
4451

4552
let javaCanonicalName = String(entry.getName().replacing("/", with: ".")
4653
.dropLast(".class".count))
54+
55+
if let javaPackageFilter {
56+
if !javaCanonicalName.hasPrefix(javaPackageFilter) {
57+
// Skip classes which don't match our expected prefix
58+
continue
59+
}
60+
}
61+
62+
if amendExistingConfig && configuration.classes?[javaCanonicalName] != nil {
63+
// If we're amending an existing config, we never overwrite an existing
64+
// class configuration. E.g. the user may have configured a custom name
65+
// for a type.
66+
continue
67+
}
4768
configuration.classes?[javaCanonicalName] =
4869
javaCanonicalName.defaultSwiftNameForJavaClass
4970
}
5071

5172
// Encode the configuration.
52-
let encoder = JSONEncoder()
53-
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
54-
var contents = String(data: try encoder.encode(configuration), encoding: .utf8)!
55-
contents.append("\n")
73+
let contents = try configuration.renderJSON()
5674

5775
// Write the file.
5876
try writeContents(

Sources/Java2Swift/JavaToSwift+FetchDependencies.swift

Lines changed: 54 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -12,52 +12,84 @@
1212
//
1313
//===----------------------------------------------------------------------===//
1414

15-
import ArgumentParser
15+
import Foundation
1616
import Java2SwiftLib
1717
import JavaKit
1818
import Foundation
1919
import JavaKitJar
2020
import Java2SwiftLib
2121
import JavaKitDependencyResolver
2222
import JavaKitConfigurationShared
23+
import JavaKitShared
2324

2425
extension JavaToSwift {
2526
func fetchDependencies(moduleName: String,
2627
dependencies: [JavaDependencyDescriptor],
27-
baseClasspath: [String]) throws -> JavaClasspath {
28+
baseClasspath: [String],
29+
environment: JNIEnvironment) throws -> ResolvedDependencyClasspath {
2830
let deps = dependencies.map { $0.descriptionGradleStyle }
29-
print("[debug][swift-java] Fetch dependencies: \(deps)")
30-
31-
let jvm = try JavaVirtualMachine.shared(classPath: baseClasspath)
32-
// let jvm = try ensureDependencyResolverDependenciesLoaded(baseClasspath: baseClasspath)
31+
print("[debug][swift-java] Resolve and fetch dependencies for: \(deps)")
32+
let resolverClass = try JavaClass<DependencyResolver>(environment: environment)
3333

34-
let resolverClass = try JavaClass<DependencyResolver>(environment: jvm.environment())
35-
let classpath = try resolverClass.resolveDependenciesToClasspath(
36-
projectBaseDirectory: URL(fileURLWithPath: ".").path,
37-
dependencies: deps)
34+
let fullClasspath = try resolverClass.resolveDependenciesToClasspath(
35+
projectBaseDirectory: URL(fileURLWithPath: ".").path,
36+
dependencies: deps)
37+
.split(separator: ":")
3838

39-
let entries = classpath.split(separator: ":")
40-
let entryCount = entries.count
39+
let classpathEntries = fullClasspath.filter {
40+
$0.hasSuffix(".jar")
41+
}
42+
let classpath = classpathEntries.joined(separator: ":")
4143

42-
print("[info][swift-java] Resolved classpath for \(deps.count) dependencies of '\(moduleName)': classpath entries: \(entryCount)... ", terminator: "")
44+
print("[info][swift-java] Resolved classpath for \(deps.count) dependencies of '\(moduleName)', classpath entries: \(classpathEntries.count), ", terminator: "")
4345
print("done.".green)
4446

45-
for entry in entries {
46-
print("[debug][swift-java] Classpath entry: \(entry)")
47-
}
47+
return ResolvedDependencyClasspath(for: dependencies, classpath: classpath)
48+
}
49+
}
4850

49-
return .init(classpath)
51+
extension JavaToSwift {
52+
mutating func writeFetchDependencies(resolvedClasspath: ResolvedDependencyClasspath) throws {
53+
var configuration = Configuration()
54+
configuration.dependencies = resolvedClasspath.rootDependencies
55+
configuration.classpath = resolvedClasspath.classpath
56+
57+
// Convert the artifact name to a module name
58+
// e.g. reactive-streams -> ReactiveStreams
59+
// TODO: Should we prefix them with `Java...`?
60+
let targetModule = artifactIDAsModuleID(resolvedClasspath.rootDependencies.first!.artifactID)
61+
62+
// Encode the configuration.
63+
let contents = try configuration.renderJSON()
64+
65+
// Write the file
66+
try writeContents(
67+
contents,
68+
to: "swift-java.config",
69+
description: "swift-java configuration file"
70+
)
71+
}
72+
73+
public func artifactIDAsModuleID(_ artifactID: String) -> String {
74+
let components = artifactID.split(whereSeparator: { $0 == "-" })
75+
let camelCased = components.map { $0.capitalized }.joined()
76+
return camelCased
5077
}
5178
}
5279

53-
struct JavaClasspath: CustomStringConvertible {
54-
let value: String
80+
struct ResolvedDependencyClasspath: CustomStringConvertible {
81+
/// The dependency identifiers this is the classpath for.
82+
let rootDependencies: [JavaDependencyDescriptor]
83+
84+
/// Plain string representation of a Java classpath
85+
let classpath: String
5586

56-
init(_ value: String) {
57-
self.value = value
87+
init(for rootDependencies: [JavaDependencyDescriptor], classpath: String) {
88+
self.rootDependencies = rootDependencies
89+
self.classpath = classpath
5890
}
5991

6092
var description: String {
61-
"JavaClasspath(value: \(value))"
93+
"JavaClasspath(for: \(rootDependencies), classpath: \(classpath))"
6294
}
6395
}

0 commit comments

Comments
 (0)