-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathConfiguration.swift
More file actions
430 lines (354 loc) · 14.2 KB
/
Configuration.swift
File metadata and controls
430 lines (354 loc) · 14.2 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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2024-2025 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
////////////////////////////////////////////////////////////////////////////////
// This file is only supposed to be edited in `Shared/` and must be symlinked //
// from everywhere else! We cannot share dependencies with or between plugins //
////////////////////////////////////////////////////////////////////////////////
public typealias JavaVersion = Int
/// Configuration for the SwiftJava tools and plugins, provided on a per-target basis.
public struct Configuration: Codable {
public var logLevel: LogLevel?
// ==== swift 2 java / jextract swift ---------------------------------------
public var javaPackage: String?
public var swiftModule: String?
public var inputSwiftDirectory: String?
public var outputSwiftDirectory: String?
public var outputJavaDirectory: String?
public var mode: JExtractGenerationMode?
public var effectiveMode: JExtractGenerationMode {
mode ?? .default
}
public var writeEmptyFiles: Bool? // FIXME: default it to false, but that plays not nice with Codable
public var minimumInputAccessLevelMode: JExtractMinimumAccessLevelMode?
public var effectiveMinimumInputAccessLevelMode: JExtractMinimumAccessLevelMode {
minimumInputAccessLevelMode ?? .default
}
public var memoryManagementMode: JExtractMemoryManagementMode?
public var effectiveMemoryManagementMode: JExtractMemoryManagementMode {
memoryManagementMode ?? .default
}
public var asyncFuncMode: JExtractAsyncFuncMode?
public var effectiveAsyncFuncMode: JExtractAsyncFuncMode {
asyncFuncMode ?? .default
}
public var enableJavaCallbacks: Bool?
public var effectiveEnableJavaCallbacks: Bool {
enableJavaCallbacks ?? false
}
public var generatedJavaSourcesListFileOutput: String?
// ==== wrap-java ---------------------------------------------------------
/// The Java class path that should be passed along to the swift-java tool.
public var classpath: String? = nil
public var classpathEntries: [String] {
return classpath?.split(separator: ":").map(String.init) ?? []
}
/// 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).
public var classes: [String: String]? = [:]
// Compile for the specified Java SE release.
public var sourceCompatibility: JavaVersion?
// Generate class files suitable for the specified Java SE release.
public var targetCompatibility: JavaVersion?
/// Filter input Java types by their package prefix if set.
public var filterInclude: [String]?
/// Exclude input Java types by their package prefix or exact match.
public var filterExclude: [String]?
public var singleSwiftFileOutput: String?
// ==== dependencies ---------------------------------------------------------
// Java dependencies we need to fetch for this target.
public var dependencies: [JavaDependencyDescriptor]?
/// Maven repositories for this target when fetching dependencies.
///
/// `mavenCentral()` will always be used.
///
/// Reference: [Repository Types](https://docs.gradle.org/current/userguide/supported_repository_types.html)
public var repositories: [JavaRepositoryDescriptor]?
public init() {
}
}
/// Represents a maven-style Java dependency.
public struct JavaDependencyDescriptor: Hashable, Codable {
public var groupID: String
public var artifactID: String
public var version: String
public init(groupID: String, artifactID: String, version: String) {
self.groupID = groupID
self.artifactID = artifactID
self.version = version
}
public init(from decoder: any Decoder) throws {
let container = try decoder.singleValueContainer()
let string = try container.decode(String.self)
let parts = string.split(separator: ":")
if parts.count == 1 && string.hasPrefix(":") {
self.groupID = ""
self.artifactID = ":" + String(parts.first!)
self.version = ""
return
}
guard parts.count == 3 else {
throw JavaDependencyDescriptorError(message: "Illegal dependency, did not match: `groupID:artifactID:version`, parts: '\(parts)'")
}
self.groupID = String(parts[0])
self.artifactID = String(parts[1])
self.version = String(parts[2])
}
public var descriptionGradleStyle: String {
[groupID, artifactID, version].joined(separator: ":")
}
public func encode(to encoder: any Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode("\(self.groupID):\(self.artifactID):\(self.version)")
}
struct JavaDependencyDescriptorError: Error {
let message: String
}
}
/// Descriptor for [repositories](https://docs.gradle.org/current/userguide/supported_repository_types.html#sec:maven-repo)
public enum JavaRepositoryDescriptor: Hashable, Codable, Equatable {
/// Haven't found a proper way to test credentials, packages that need to download from private repo can be downloaded by maven and then use local repo instead
///
/// References:
/// - [Maven repositories](https://docs.gradle.org/current/userguide/supported_repository_types.html#sec:maven-repo)
/// - [Artifacts](https://docs.gradle.org/current/dsl/org.gradle.api.artifacts.repositories.MavenArtifactRepository.html#:~:text=urls)-,Adds%20some%20additional%20URLs%20to%20use%20to%20find%20artifact%20files.%20Note%20that%20these%20URLs%20are%20not%20used%20to%20find%20POM%20files.,-The)
case maven(url: String, artifactUrls: [String]? = nil)
case mavenLocal(includeGroups: [String]? = nil)
case other(_ type: String)
enum CodingKeys: String, CodingKey { case type, url, artifactUrls, credentials, includeGroups }
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
let type = try c.decode(String.self, forKey: .type)
switch type {
case "maven":
self = try .maven(
url: c.decode(String.self, forKey: .url),
artifactUrls: try? c.decode([String].self, forKey: .artifactUrls),
)
case "mavenLocal":
self = .mavenLocal(includeGroups: try? c.decode([String].self, forKey: .includeGroups))
default:
self = .other(type)
}
}
public func encode(to encoder: Encoder) throws {
var c = encoder.container(keyedBy: CodingKeys.self)
switch self {
case let .maven(url, artifactUrls/*, creds*/):
try c.encode("maven", forKey: .type)
try c.encode(url, forKey: .url)
if let artifactUrls = artifactUrls {
try c.encode(artifactUrls, forKey: .artifactUrls)
}
case let .mavenLocal(includeGroups):
try c.encode("mavenLocal", forKey: .type)
if let gs = includeGroups {
try c.encode(gs, forKey: .includeGroups)
}
case let .other(type):
try c.encode("\(type)", forKey: .type)
}
}
public func renderGradleRepository() -> String? {
switch self {
case let .maven(url, artifactUrls):
return """
maven {
url = uri("\(url)")
\((artifactUrls ?? []).map({ "artifactUrls(\"\($0)\")" }).joined(separator: "\n"))
}
"""
case let .mavenLocal(groups):
if let gs = groups {
return """
mavenLocal {
content {
\(gs.map({ "includeGroup(\"\($0)\")" }).joined(separator: "\n"))
}
}
"""
} else {
return "mavenLocal()"
}
case let .other(type):
return "\(type)()"
}
}
}
public func readConfiguration(sourceDir: String, file: String = #fileID, line: UInt = #line) throws -> Configuration? {
// Workaround since filePath is macOS 13
let sourcePath =
if sourceDir.hasPrefix("file://") { sourceDir } else { "file://" + sourceDir }
let configPath = URL(string: sourcePath)!.appendingPathComponent("swift-java.config", isDirectory: false)
return try readConfiguration(configPath: configPath, file: file, line: line)
}
/// Read a swift-java.config file at the specified path.
///
/// Configuration is expected to be "JSON-with-comments".
/// Specifically "//" comments are allowed and will be trimmed before passing the rest of the config into a standard JSON parser.
public func readConfiguration(configPath: URL, file: String = #fileID, line: UInt = #line) throws -> Configuration? {
let configData: Data
do {
configData = try Data(contentsOf: configPath)
} catch {
print("Failed to read SwiftJava configuration at '\(configPath.absoluteURL)', error: \(error)")
return nil
}
guard let configString = String(data: configData, encoding: .utf8) else {
return nil
}
return try readConfiguration(string: configString, configPath: configPath)
}
public func readConfiguration(string: String, configPath: URL?, file: String = #fileID, line: UInt = #line) throws -> Configuration? {
guard let configData = string.data(using: .utf8) else {
return nil
}
do {
let decoder = JSONDecoder()
decoder.allowsJSON5 = true
return try decoder.decode(Configuration.self, from: configData)
} catch {
throw ConfigurationError(
message: "Failed to parse SwiftJava configuration at '\(configPath.map({ $0.absoluteURL.description }) ?? "<no-path>")'! \(#fileID):\(#line)",
error: error,
text: string,
file: file, line: line)
}
}
/// Load all dependent configs configured with `--depends-on` and return a list of
/// `(SwiftModuleName, Configuration)` tuples.
public func loadDependentConfigs(dependsOn: [String]) throws -> [(String?, Configuration)] {
try dependsOn.map { dependentConfig in
let equalLoc = dependentConfig.firstIndex(of: "=")
var swiftModuleName: String? = nil
if let equalLoc {
swiftModuleName = String(dependentConfig[..<equalLoc])
}
let afterEqual = equalLoc.map { dependentConfig.index(after: $0) } ?? dependentConfig.startIndex
let configFileName = String(dependentConfig[afterEqual...])
let config = try readConfiguration(configPath: URL(fileURLWithPath: configFileName)) ?? Configuration()
return (swiftModuleName, config)
}
}
public func findSwiftJavaClasspaths(swiftModule: String) -> [String] {
let basePath: String = FileManager.default.currentDirectoryPath
let pluginOutputsDir = URL(fileURLWithPath: basePath)
.appendingPathComponent(".build", isDirectory: true)
.appendingPathComponent("plugins", isDirectory: true)
.appendingPathComponent("outputs", isDirectory: true)
.appendingPathComponent(swiftModule, isDirectory: true)
return findSwiftJavaClasspaths(in: pluginOutputsDir.path)
}
public func findSwiftJavaClasspaths(in basePath: String = FileManager.default.currentDirectoryPath) -> [String] {
let fileManager = FileManager.default
let baseURL = URL(fileURLWithPath: basePath)
var classpathEntries: [String] = []
print("[debug][swift-java] Searching for *.swift-java.classpath files in: \(baseURL.absoluteString)")
guard let enumerator = fileManager.enumerator(at: baseURL, includingPropertiesForKeys: []) else {
print("[warning][swift-java] Failed to get enumerator for \(baseURL)")
return []
}
for case let fileURL as URL in enumerator {
if fileURL.lastPathComponent.hasSuffix(".swift-java.classpath") {
print("[debug][swift-java] Constructing classpath with entries from: \(fileURL.path)")
if let contents = try? String(contentsOf: fileURL) {
let entries = contents.split(separator: ":").map(String.init)
for entry in entries {
print("[debug][swift-java] Classpath += \(entry)")
}
classpathEntries += entries
}
}
}
return classpathEntries
}
extension Configuration {
public var compilerVersionArgs: [String] {
var compilerVersionArgs = [String]()
if let sourceCompatibility {
compilerVersionArgs += ["--source", String(sourceCompatibility)]
}
if let targetCompatibility {
compilerVersionArgs += ["--target", String(targetCompatibility)]
}
return compilerVersionArgs
}
}
extension Configuration {
/// Render the configuration as JSON text.
public func renderJSON() throws -> String {
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
var contents = String(data: try encoder.encode(self), encoding: .utf8)!
contents.append("\n")
return contents
}
}
public struct ConfigurationError: Error {
let message: String
let error: any Error
let text: String?
let file: String
let line: UInt
init(message: String, error: any Error, text: String?, file: String = #fileID, line: UInt = #line) {
self.message = message
self.error = error
self.text = text
self.file = file
self.line = line
}
}
public enum LogLevel: String, ExpressibleByStringLiteral, Codable, Hashable {
case trace = "trace"
case debug = "debug"
case info = "info"
case notice = "notice"
case warning = "warning"
case error = "error"
case critical = "critical"
public init(stringLiteral value: String) {
self = LogLevel(rawValue: value) ?? .info
}
}
extension LogLevel {
public init(from decoder: any Decoder) throws {
let container = try decoder.singleValueContainer()
let string = try container.decode(String.self)
switch string {
case "trace": self = .trace
case "debug": self = .debug
case "info": self = .info
case "notice": self = .notice
case "warning": self = .warning
case "error": self = .error
case "critical": self = .critical
default: fatalError("Unknown value for \(LogLevel.self): \(string)")
}
}
public func encode(to encoder: any Encoder) throws {
var container = encoder.singleValueContainer()
let text =
switch self {
case .trace: "trace"
case .debug: "debug"
case .info: "info"
case .notice: "notice"
case .warning: "warning"
case .error: "error"
case .critical: "critical"
}
try container.encode(text)
}
}