repo_name stringlengths 1 62 | dataset stringclasses 1 value | lang stringclasses 11 values | pr_id int64 1 20.1k | owner stringlengths 2 34 | reviewer stringlengths 2 39 | diff_hunk stringlengths 15 262k | code_review_comment stringlengths 1 99.6k |
|---|---|---|---|---|---|---|---|
swift-openapi-generator | github_2023 | others | 140 | apple | czechboy0 | @@ -231,6 +231,46 @@ final class Test_Server: XCTestCase {
)
}
+
+ func testCreatePet_withIncorrectContentType() async throws {
+ client = .init(
+ createPetBlock: { input in
+ return .created(
+ .init(
+ headers: .init(
+ X_Extra_Arguments: .init(code: 1)
+ ),
+ body: .json(
+ .init(id: 1, name: "Fluffz")
+ )
+ )
+ ) | ```suggestion
XCTFail("The handler should not have been called")
```
This should not be called, nor return, so no need to construct a response here, just assert that it's not called. |
swift-openapi-generator | github_2023 | others | 140 | apple | czechboy0 | @@ -231,6 +231,35 @@ final class Test_Server: XCTestCase {
)
}
+
+ func testCreatePet_withIncorrectContentType() async throws {
+ client = .init(
+ createPetBlock: { input in
+ XCTFail("The handler should not have been called") | The CI is complaining about this, we need to return Never here, for example like this.
```suggestion
XCTFail("The handler should not have been called")
fatalError("Unreachable")
```
|
swift-openapi-generator | github_2023 | others | 123 | apple | czechboy0 | @@ -16,6 +16,30 @@ import ArgumentParser
import _OpenAPIGeneratorCore
extension _Tool {
+
+ /// A structure that defines ANSI escape codes for different colors in the terminal output.
+ ///
+ /// You can use these codes to change the color of the text printed by the `print` function or other methods that write to the standard output. To reset the text color to the default, use the `reset` code.
+ ///
+ /// For example, to print "Hello" in red and "World" in green, you can use:
+ /// ```swift
+ /// print(
+ /// CommandLineColors.red +
+ /// "Hello" +
+ /// CommandLineColors.green +
+ /// "World" +
+ /// CommandLineColors.reset
+ /// )
+ /// ```
+ struct CommandLineColors { | Can you file adding support for command colors into a separate issue? I'd welcome command colors, but:
- we should add them to all the commands consistently
- detect when we're not in an interactive session and skip colors, so that they don't pollute text logs
- discuss how to use the colors to make information easy to read at a glance
So if you could remove the color changes from this PR, and open a new PR, that'd be better, thanks 🙏 |
swift-openapi-generator | github_2023 | others | 123 | apple | czechboy0 | @@ -67,44 +99,69 @@ extension _Tool {
/// - config: A set of configuration values for the generator.
/// - outputFilePath: The directory to which the generator writes
/// the generated Swift files.
+ /// - isDryRun: A Boolean value that indicates whether this invocation should
+ /// be a dry run.
/// - diagnostics: A collector for diagnostics emitted by the generator.
static func runGenerator(
doc: URL,
docData: Data,
config: Config,
outputFilePath: URL,
+ isDryRun: Bool,
diagnostics: any DiagnosticCollector
) throws {
- let didChange = try replaceFileContents(at: outputFilePath) {
- let output = try _OpenAPIGeneratorCore.runGenerator(
- input: .init(absolutePath: doc, contents: docData),
- config: config,
- diagnostics: diagnostics
- )
- return output.contents
+ let didChange = try replaceFileContents(
+ at: outputFilePath,
+ with: {
+ let output = try _OpenAPIGeneratorCore.runGenerator(
+ input: .init(absolutePath: doc, contents: docData),
+ config: config,
+ diagnostics: diagnostics
+ )
+ return output.contents
+ },
+ isDryRun: isDryRun
+ )
+ if !isDryRun {
+ print("File \(outputFilePath.lastPathComponent): \(didChange ? "changed" : "unchanged")")
}
- print("File \(outputFilePath.lastPathComponent): \(didChange ? "changed" : "unchanged")") | We can continue printing this line, it'd be useful to still see if the contents of this file changed or not, even in dry run. |
swift-openapi-generator | github_2023 | others | 123 | apple | czechboy0 | @@ -42,20 +44,25 @@ extension _Tool {
let filePathForMode: (GeneratorMode) -> URL = { mode in
outputDirectory.appendingPathComponent(mode.outputFileName)
}
+ if isDryRun {
+ print("--------------------------------")
+ print("Dry run mode: No files will be created or modified")
+ } | I don't think we need it, as it's already included in the launch summary that it's dry run. |
swift-openapi-generator | github_2023 | others | 123 | apple | czechboy0 | @@ -67,44 +74,66 @@ extension _Tool {
/// - config: A set of configuration values for the generator.
/// - outputFilePath: The directory to which the generator writes
/// the generated Swift files.
+ /// - isDryRun: A Boolean value that indicates whether this invocation should
+ /// be a dry run.
/// - diagnostics: A collector for diagnostics emitted by the generator.
static func runGenerator(
doc: URL,
docData: Data,
config: Config,
outputFilePath: URL,
+ isDryRun: Bool,
diagnostics: any DiagnosticCollector
) throws {
- let didChange = try replaceFileContents(at: outputFilePath) {
- let output = try _OpenAPIGeneratorCore.runGenerator(
- input: .init(absolutePath: doc, contents: docData),
- config: config,
- diagnostics: diagnostics
- )
- return output.contents
- }
- print("File \(outputFilePath.lastPathComponent): \(didChange ? "changed" : "unchanged")")
+ try replaceFileContents(
+ at: outputFilePath,
+ with: {
+ let output = try _OpenAPIGeneratorCore.runGenerator(
+ input: .init(absolutePath: doc, contents: docData),
+ config: config,
+ diagnostics: diagnostics
+ )
+ return output.contents
+ },
+ isDryRun: isDryRun
+ )
}
/// Evaluates a closure to generate file data and writes the data to disk
/// if the data is different than the current file contents.
/// - Parameters:
/// - path: A path to the file.
/// - contents: A closure evaluated to produce the file contents data.
+ /// - isDryRun: A Boolean value that indicates whether this invocation should
+ /// be a dry run. File system changes will not be written to disk in this mode.
/// - Throws: When writing to disk fails.
/// - Returns: `true` if the generated contents changed, otherwise `false`.
@discardableResult
- static func replaceFileContents(at path: URL, with contents: () throws -> Data) throws -> Bool {
+ static func replaceFileContents(
+ at path: URL,
+ with contents: () throws -> Data,
+ isDryRun: Bool
+ ) throws -> Bool {
let data = try contents()
let didChange: Bool
if FileManager.default.fileExists(atPath: path.path) {
let existingData = try? Data(contentsOf: path)
didChange = existingData != data
+ if didChange {
+ print("File \(path.lastPathComponent) will be overwritten.")
+ } else {
+ print("File \(path.lastPathComponent) will remain unchanged.")
+ }
} else {
+ print("File \(path.lastPathComponent) does not exist.\nCreating new file...")
didChange = true
}
if didChange {
- try data.write(to: path)
+ if isDryRun {
+ print("Writing data to \(path.lastPathComponent)...")
+ } else {
+ try data.write(to: path)
+ } | This method shouldn't print anything, just return whether the file contents have changed. Let's keep the printing in the caller, though. |
swift-openapi-generator | github_2023 | others | 123 | apple | czechboy0 | @@ -67,45 +70,72 @@ extension _Tool {
/// - config: A set of configuration values for the generator.
/// - outputFilePath: The directory to which the generator writes
/// the generated Swift files.
+ /// - isDryRun: A Boolean value that indicates whether this invocation should
+ /// be a dry run.
/// - diagnostics: A collector for diagnostics emitted by the generator.
static func runGenerator(
doc: URL,
docData: Data,
config: Config,
outputFilePath: URL,
+ isDryRun: Bool,
diagnostics: any DiagnosticCollector
) throws {
- let didChange = try replaceFileContents(at: outputFilePath) {
- let output = try _OpenAPIGeneratorCore.runGenerator(
- input: .init(absolutePath: doc, contents: docData),
- config: config,
- diagnostics: diagnostics
- )
- return output.contents
+ let result = try replaceFileContents(
+ at: outputFilePath,
+ with: {
+ let output = try _OpenAPIGeneratorCore.runGenerator(
+ input: .init(absolutePath: doc, contents: docData),
+ config: config,
+ diagnostics: diagnostics
+ )
+ return output.contents
+ },
+ isDryRun: isDryRun
+ )
+ if result.didCreate && isDryRun {
+ print("File \(outputFilePath.lastPathComponent) does not exist.\nCreating new file...")
+ } | I think we can get rid of this print, the summary below is enough to know what the generator did for this file. |
swift-openapi-generator | github_2023 | others | 123 | apple | simonjbeaumont | @@ -104,8 +118,12 @@ extension _Tool {
didChange = true
}
if didChange {
- try data.write(to: path)
+ print("File \(path.lastPathComponent) will be overwritten.")
+ if !isDryRun {
+ try data.write(to: path)
+ }
+ } else {
+ print("File \(path.lastPathComponent) will remain unchanged.")
}
- return didChange
} | At this stage, I'm going to approve the PR because it does what it set out to do.
However, IMO the code has become a bit too branchy. On inspection, I don't think that's really because of this PR.
We could also make use of some `guards` to early-return and make the code more linear.
Finally, this function also only replaces the contents if they are different but isn't clear from its name. This is an important nuance because IIUC this affects the timestamp on the file and, therefore, the rest of the build graph.
This function could therefore be rewritten as:
```swift
static func replaceFileContentsIfDifferent(
at path: URL,
with data: Data,
isDryRun: Bool
) throws {
if let existingData = try? Data(contentsOf: path), existingData == data {
print("File \(path.lastPathComponent) already up to date.")
return
}
guard !isDryRun else {
print("Not writing file \(path.lastPathComponent) (dry run).")
return
}
print("Writing file \(path.lastPathComponent).")
try data.write(to: path)
}
```
At this point it is questionable why we had this `@discardableResult` function that took a throwing closure anyway, because at the call site it's basically the only thing that's called by `runGenerator(...)`.
All that said, I'm hitting approve here because removing this complexity isn't on your plate @denil-ct :) |
swift-openapi-generator | github_2023 | others | 123 | apple | czechboy0 | @@ -48,10 +48,17 @@ struct _GenerateCommand: AsyncParsableCommand {
)
var isPluginInvocation: Bool = false
+ @Flag(
+ help:
+ "Simulate the command and print the operations, without actually affecting the file system."
+ )
+ var isDryRun: Bool = false | Oh sorry for the late request, could we just make it `--dry-run`? At the moment, the name would be `--is-dry-run`, which feels like a question rather than an instruction.
I believe there's a parameter on the Option property wrapper customize the CLI name, which means you won't need to change the property name itself. |
swift-openapi-generator | github_2023 | others | 103 | apple | czechboy0 | @@ -0,0 +1,351 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+import OpenAPIKit30
+import XCTest
+import Yams
+@testable import _OpenAPIGeneratorCore
+
+/// Tests that the generator produces Swift code that match a reference.
+final class SnippetBasedReferenceTests: XCTestCase {
+ func testComponentsHeadersInline() throws {
+ try self.assertHeadersTranslation(
+ """
+ openapi: "3.0.3"
+ info:
+ title: "Test"
+ version: "0.0.0"
+ paths: {} | Overall looks great, just one idea - to avoid having to duplicate the openapi version, info, and paths keys in every snippet, could we have them be added by default, unless specified explicitly? That way you can only specify the important part of the OpenAPI doc in each test, without duplicating the unimportant parts.
Might require using Yams to parse, fill in defaults, then serialize again, but could be worthwhile. |
swift-openapi-generator | github_2023 | others | 103 | apple | czechboy0 | @@ -0,0 +1,321 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+import OpenAPIKit30
+import XCTest
+import Yams
+@testable import _OpenAPIGeneratorCore
+
+/// Tests that the generator produces Swift code that match a reference.
+final class SnippetBasedReferenceTests: XCTestCase {
+ func testComponentsHeadersInline() throws {
+ try self.assertHeadersTranslation( | Yeah these three methods are a great way to test this, IMO. I'd be in favor of fleshing this out. 👍 |
swift-openapi-generator | github_2023 | others | 103 | apple | czechboy0 | @@ -0,0 +1,777 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+import OpenAPIKit30
+import XCTest
+import Yams
+@testable import _OpenAPIGeneratorCore
+
+/// Tests that the generator produces Swift code that match a reference.
+final class SnippetBasedReferenceTests: XCTestCase {
+ func testComponentsHeadersInline() throws {
+ try self.assertHeadersTranslation(
+ """
+ headers:
+ MyHeader:
+ schema:
+ type: string
+ """,
+ """
+ public enum Headers {
+ public typealias MyHeader = Swift.String
+ }
+ """
+ )
+ }
+
+ func testComponentsHeadersReference() throws {
+ try self.assertHeadersTranslation(
+ """
+ headers:
+ MyHeader:
+ schema:
+ $ref: "#/components/schemas/MySchema"
+ """,
+ """
+ public enum Headers {
+ public typealias MyHeader = Components.Schemas.MySchema
+ }
+ """
+ )
+ }
+
+ func testComponentsParametersInline() throws {
+ try self.assertParametersTranslation(
+ """
+ parameters:
+ MyParam:
+ in: query
+ name: my_param
+ schema:
+ type: string
+ """,
+ """
+ public enum Parameters {
+ public typealias MyParam = Swift.String
+ }
+ """
+ )
+ }
+
+ func testComponentsParametersReference() throws {
+ try self.assertParametersTranslation(
+ """
+ parameters:
+ MyParam:
+ in: query
+ name: my_param
+ schema:
+ $ref: "#/components/schemas/MySchema"
+ """,
+ """
+ public enum Parameters {
+ public typealias MyParam = Components.Schemas.MySchema
+ }
+ """
+ )
+ }
+
+ func testComponentsSchemasString() throws {
+ try self.assertSchemasTranslation(
+ """
+ schemas:
+ MyString:
+ type: string
+ """,
+ """
+ public enum Schemas {
+ public typealias MyString = Swift.String | I see here we have 4 spaces and 2 in the previous test, is that intentional? |
swift-openapi-generator | github_2023 | others | 103 | apple | czechboy0 | @@ -0,0 +1,777 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+import OpenAPIKit30
+import XCTest
+import Yams
+@testable import _OpenAPIGeneratorCore
+
+/// Tests that the generator produces Swift code that match a reference.
+final class SnippetBasedReferenceTests: XCTestCase { | I wonder if we should make SnippetBasedReferenceTests a superclass and put tests into a few smaller subclasses. That'd also keep the utilities at the end of this file out of the file with actual test cases.
But that's part of expected organic growth, so I'm fine with this not being changed in this PR, just wondering if that's a change you'd like to see. |
swift-openapi-generator | github_2023 | others | 92 | apple | czechboy0 | @@ -69,7 +69,7 @@ extension FileTranslator {
guard let comment = blueprint.comment else {
return structDecl | Seems we won't add the deprecation annotation in the else branch of this guard? |
swift-openapi-generator | github_2023 | others | 92 | apple | czechboy0 | @@ -103,6 +106,9 @@ struct PropertyBlueprint {
/// A documentation comment for the property.
var comment: Comment? = nil
+ /// Whether the type should be annotated as deprecated. | ```suggestion
/// Whether the property should be annotated as deprecated.
```
|
swift-openapi-generator | github_2023 | others | 92 | apple | czechboy0 | @@ -370,6 +372,17 @@ components:
- $ref: '#/components/schemas/MessagedExercise'
discriminator:
propertyName: kind
+ DeprecatedObject:
+ deprecated: true
+ type: object
+ properties: {}
+ additionalProperties: false | Did you explicitly turn off additional properties on purpose? You could just omit this field, and get the default behavior of an even smaller struct. |
swift-openapi-generator | github_2023 | others | 92 | apple | michalsrutek | @@ -11,7 +11,14 @@ services:
test:
image: *image
environment:
- - WARN_AS_ERROR_ARG=-Xswiftc -warnings-as-errors
+ # Because OpenAPI supports deprecation, the generated code could include
+ # deprecated symbols, which will produce warnings.
+ #
+ # We'll desable -warnings-as-errors for now and revisit this when we | typo in `desable` - should be `disable` |
swift-openapi-generator | github_2023 | others | 111 | apple | czechboy0 | @@ -56,7 +56,7 @@ let package = Package(
),
.package(
url: "https://github.com/jpsim/Yams.git",
- from: "4.0.0"
+ from: "5.0.0" | Can we change to a range that's 4..<6? I've seen that done in projects, allows adopters to be using either major version. Just requires that we're using API present in both. |
swift-openapi-generator | github_2023 | others | 81 | apple | czechboy0 | @@ -116,8 +117,7 @@ let package = Package(
.executableTarget(
name: "swift-openapi-generator",
dependencies: [
- "_OpenAPIGeneratorCore",
- .product(name: "ArgumentParser", package: "swift-argument-parser"),
+ "_OpenAPIGeneratorCore" | It'd be great to avoid making the library depend on swift-argument-parser, see comments below how we should be able to remove it again. |
swift-openapi-generator | github_2023 | others | 81 | apple | czechboy0 | @@ -37,6 +37,12 @@ public struct Diagnostic: Error, Codable {
/// A user-friendly description of the diagnostic.
public var message: String
+ /// The absolute path to a specific source file that triggered the diagnostic.
+ public var absoluteFilePath: URL?
+
+ /// The line number within the specific source file that triggered the diagnostic.
+ public var lineNumber: Int? | Since we'll either always have location, or not have location, let's represent it as
```swift
struct Diagnostic {
//...
struct Location {
var filePath: String
var lineNumber: Int
}
var location: Location?
}
``` |
swift-openapi-generator | github_2023 | others | 81 | apple | czechboy0 | @@ -101,8 +107,20 @@ extension Diagnostic.Severity: CustomStringConvertible {
extension Diagnostic: CustomStringConvertible {
public var description: String {
+ var prefix = ""
+ if let filePath = absoluteFilePath {
+ if #available(macOS 13.0, *) {
+ prefix = "\(filePath.path(percentEncoded: false)):"
+ } else {
+ prefix = "\(filePath.path):" | Just use this codepath that works on all platforms, no need to branch out to the new API on newer OS versions. |
swift-openapi-generator | github_2023 | others | 81 | apple | czechboy0 | @@ -58,9 +65,63 @@ struct YamsParser: ParserProtocol {
throw OpenAPIVersionError(versionString: "openapi: \(openAPIVersion)")
}
- return try decoder.decode(
- OpenAPI.Document.self,
- from: input.contents
- )
+ do {
+ return try decoder.decode(
+ OpenAPI.Document.self,
+ from: input.contents
+ )
+ } catch DecodingError.dataCorrupted(let errorContext) {
+ try possibly_throw_parsing_error(context: errorContext, input: input, diagnostics: diagnostics)
+ throw DecodingError.dataCorrupted(errorContext)
+ }
+ }
+
+ /// Detect specific YAML parsing errors to emit nicely formatted errors for IDEs
+ private func possibly_throw_parsing_error( | ```suggestion
private func checkParsingError(
```
A naming suggestion - let's use camelCase, and suggested slightly different phrase. |
swift-openapi-generator | github_2023 | others | 81 | apple | czechboy0 | @@ -58,9 +65,63 @@ struct YamsParser: ParserProtocol {
throw OpenAPIVersionError(versionString: "openapi: \(openAPIVersion)")
}
- return try decoder.decode(
- OpenAPI.Document.self,
- from: input.contents
- )
+ do {
+ return try decoder.decode(
+ OpenAPI.Document.self,
+ from: input.contents
+ )
+ } catch DecodingError.dataCorrupted(let errorContext) {
+ try possibly_throw_parsing_error(context: errorContext, input: input, diagnostics: diagnostics)
+ throw DecodingError.dataCorrupted(errorContext)
+ }
+ }
+
+ /// Detect specific YAML parsing errors to emit nicely formatted errors for IDEs
+ private func possibly_throw_parsing_error(
+ context: DecodingError.Context,
+ input: InMemoryInputFile,
+ diagnostics: DiagnosticCollector
+ ) throws {
+ if let yamlError = context.underlyingError as? YamlError {
+ if case .parser(let yamlContext, let yamlProblem, let yamlMark, _) = yamlError {
+ try throw_parsing_error(
+ context: yamlContext,
+ problem: yamlProblem,
+ lineNumber: yamlMark.line - 1,
+ input: input,
+ diagnostics
+ )
+ } else if case .scanner(let yamlContext, let yamlProblem, let yamlMark, _) = yamlError {
+ try throw_parsing_error(
+ context: yamlContext,
+ problem: yamlProblem,
+ lineNumber: yamlMark.line - 1,
+ input: input,
+ diagnostics
+ )
+ }
+ } else if let openAPIError = context.underlyingError as? OpenAPIError {
+ var problem = Diagnostic.error(message: openAPIError.localizedDescription) | Can you add `location: Location? = nil` to the convenience initializer so that we can create the Diagnostic in one step here, instead of modifying it after creation? |
swift-openapi-generator | github_2023 | others | 81 | apple | czechboy0 | @@ -58,9 +65,63 @@ struct YamsParser: ParserProtocol {
throw OpenAPIVersionError(versionString: "openapi: \(openAPIVersion)")
}
- return try decoder.decode(
- OpenAPI.Document.self,
- from: input.contents
- )
+ do {
+ return try decoder.decode(
+ OpenAPI.Document.self,
+ from: input.contents
+ )
+ } catch DecodingError.dataCorrupted(let errorContext) {
+ try possibly_throw_parsing_error(context: errorContext, input: input, diagnostics: diagnostics)
+ throw DecodingError.dataCorrupted(errorContext)
+ }
+ }
+
+ /// Detect specific YAML parsing errors to emit nicely formatted errors for IDEs
+ private func possibly_throw_parsing_error(
+ context: DecodingError.Context,
+ input: InMemoryInputFile,
+ diagnostics: DiagnosticCollector
+ ) throws {
+ if let yamlError = context.underlyingError as? YamlError {
+ if case .parser(let yamlContext, let yamlProblem, let yamlMark, _) = yamlError {
+ try throw_parsing_error(
+ context: yamlContext,
+ problem: yamlProblem,
+ lineNumber: yamlMark.line - 1,
+ input: input,
+ diagnostics
+ )
+ } else if case .scanner(let yamlContext, let yamlProblem, let yamlMark, _) = yamlError {
+ try throw_parsing_error(
+ context: yamlContext,
+ problem: yamlProblem,
+ lineNumber: yamlMark.line - 1,
+ input: input,
+ diagnostics
+ )
+ }
+ } else if let openAPIError = context.underlyingError as? OpenAPIError {
+ var problem = Diagnostic.error(message: openAPIError.localizedDescription)
+ problem.absoluteFilePath = input.absolutePath
+ diagnostics.emit(problem)
+ throw ExitCode.failure | The Diagnostic itself conforms to error, so you can emit it into the DiagnosticCollector, and then also throw it. This will allow us to drop the dependency on swift-argument-parser. |
swift-openapi-generator | github_2023 | others | 81 | apple | czechboy0 | @@ -58,9 +65,63 @@ struct YamsParser: ParserProtocol {
throw OpenAPIVersionError(versionString: "openapi: \(openAPIVersion)")
}
- return try decoder.decode(
- OpenAPI.Document.self,
- from: input.contents
- )
+ do {
+ return try decoder.decode(
+ OpenAPI.Document.self,
+ from: input.contents
+ )
+ } catch DecodingError.dataCorrupted(let errorContext) {
+ try possibly_throw_parsing_error(context: errorContext, input: input, diagnostics: diagnostics)
+ throw DecodingError.dataCorrupted(errorContext)
+ }
+ }
+
+ /// Detect specific YAML parsing errors to emit nicely formatted errors for IDEs
+ private func possibly_throw_parsing_error(
+ context: DecodingError.Context,
+ input: InMemoryInputFile,
+ diagnostics: DiagnosticCollector
+ ) throws {
+ if let yamlError = context.underlyingError as? YamlError {
+ if case .parser(let yamlContext, let yamlProblem, let yamlMark, _) = yamlError {
+ try throw_parsing_error(
+ context: yamlContext,
+ problem: yamlProblem,
+ lineNumber: yamlMark.line - 1,
+ input: input,
+ diagnostics
+ )
+ } else if case .scanner(let yamlContext, let yamlProblem, let yamlMark, _) = yamlError {
+ try throw_parsing_error(
+ context: yamlContext,
+ problem: yamlProblem,
+ lineNumber: yamlMark.line - 1,
+ input: input,
+ diagnostics
+ )
+ }
+ } else if let openAPIError = context.underlyingError as? OpenAPIError {
+ var problem = Diagnostic.error(message: openAPIError.localizedDescription)
+ problem.absoluteFilePath = input.absolutePath
+ diagnostics.emit(problem)
+ throw ExitCode.failure
+ }
+ }
+
+ private func throw_parsing_error( | ```suggestion
private func throwParsingError(
```
CamelCase, and please add a documentation comment for this method. |
swift-openapi-generator | github_2023 | others | 81 | apple | czechboy0 | @@ -25,24 +26,151 @@ final class Test_YamsParser: Test_Core {
XCTAssertThrowsError(try _test("2.0"))
}
- func _test(_ openAPIVersionString: String) throws -> ParsedOpenAPIRepresentation {
+ private func _test(_ openAPIVersionString: String) throws -> ParsedOpenAPIRepresentation {
+ try _test(
+ """
+ openapi: "\(openAPIVersionString)"
+ info:
+ title: "Test"
+ version: "1.0.0"
+ paths: {}
+ """,
+ diagnostics: PrintingDiagnosticCollector()
+ )
+ }
+
+ func testEmitsYamsParsingError() throws {
+ let collector = TestingDiagnosticsCollector()
+ // The `title: "Test"` line is indented the wrong amount to make the YAML invalid for the parser
+ let yaml = """
+ openapi: "3.0.0"
+ info:
+ title: "Test"
+ version: 1.0.0
+ paths: {}
+ """
+
+ XCTAssertThrowsError(try _test(yaml, diagnostics: collector)) { error in
+ if let exitError = error as? ExitCode { | Here, you'd check for the Diagnostic being thrown, after you remove the swift-argument-parser dependency. |
swift-openapi-generator | github_2023 | others | 81 | apple | czechboy0 | @@ -65,13 +66,19 @@ extension _GenerateOptions {
- Additional imports: \(resolvedAdditionalImports.isEmpty ? "<none>" : resolvedAdditionalImports.joined(separator: ", "))
"""
)
- try _Tool.runGenerator(
- doc: doc,
- configs: configs,
- isPluginInvocation: isPluginInvocation,
- outputDirectory: outputDirectory,
- diagnostics: diagnostics
- )
+ do {
+ try _Tool.runGenerator(
+ doc: doc,
+ configs: configs,
+ isPluginInvocation: isPluginInvocation,
+ outputDirectory: outputDirectory,
+ diagnostics: diagnostics
+ )
+ } catch let error as Diagnostic {
+ // Emit our nice Diagnostics message instead of relying on ArgumentParser output.
+ diagnostics.emit(error)
+ throw ExitCode.failure
+ } | Oh cool, does this avoid the duplication? |
swift-openapi-generator | github_2023 | others | 81 | apple | czechboy0 | @@ -30,37 +30,84 @@ struct YamsParser: ParserProtocol {
var openapi: String?
}
- struct OpenAPIVersionError: Error, CustomStringConvertible, LocalizedError {
- var versionString: String
- var description: String {
- "Unsupported document version: \(versionString). Please provide a document with OpenAPI versions in the 3.0.x set."
- }
+ let versionedDocument: OpenAPIVersionedDocument
+ do {
+ versionedDocument = try decoder.decode(
+ OpenAPIVersionedDocument.self,
+ from: openapiData
+ )
+ } catch DecodingError.dataCorrupted(let errorContext) {
+ try checkParsingError(context: errorContext, input: input, diagnostics: diagnostics)
+ throw DecodingError.dataCorrupted(errorContext)
}
- struct OpenAPIMissingVersionError: Error, CustomStringConvertible, LocalizedError {
- var description: String {
- "No openapi key found, please provide a valid OpenAPI document with OpenAPI versions in the 3.0.x set."
- }
- }
-
- let versionedDocument = try decoder.decode(
- OpenAPIVersionedDocument.self,
- from: openapiData
- )
-
guard let openAPIVersion = versionedDocument.openapi else {
- throw OpenAPIMissingVersionError()
+ throw Diagnostic.openAPIMissingVersionError(location: .init(filePath: input.absolutePath.path))
}
switch openAPIVersion {
case "3.0.0", "3.0.1", "3.0.2", "3.0.3":
break
default:
- throw OpenAPIVersionError(versionString: "openapi: \(openAPIVersion)")
+ throw Diagnostic.openAPIVersionError(
+ versionString: "openapi: \(openAPIVersion)",
+ location: .init(filePath: input.absolutePath.path)
+ )
+ }
+
+ do {
+ return try decoder.decode(
+ OpenAPI.Document.self,
+ from: input.contents
+ )
+ } catch DecodingError.dataCorrupted(let errorContext) {
+ try checkParsingError(context: errorContext, input: input, diagnostics: diagnostics)
+ throw DecodingError.dataCorrupted(errorContext)
+ }
+ }
+
+ /// Detect specific YAML parsing errors to throw nicely formatted diagnostics for IDEs
+ private func checkParsingError(
+ context: DecodingError.Context,
+ input: InMemoryInputFile,
+ diagnostics: DiagnosticCollector
+ ) throws {
+ if let yamlError = context.underlyingError as? YamlError {
+ if case .parser(let yamlContext, let yamlProblem, let yamlMark, _) = yamlError {
+ throw Diagnostic.error(
+ message: "\(yamlProblem) \(yamlContext?.description ?? "")",
+ location: .init(filePath: input.absolutePath.path, lineNumber: yamlMark.line - 1)
+ )
+ } else if case .scanner(let yamlContext, let yamlProblem, let yamlMark, _) = yamlError {
+ throw Diagnostic.error(
+ message: "\(yamlProblem) \(yamlContext?.description ?? "")",
+ location: .init(filePath: input.absolutePath.path, lineNumber: yamlMark.line - 1)
+ )
+ }
+ } else if let openAPIError = context.underlyingError as? OpenAPIError {
+ throw Diagnostic.error(
+ message: openAPIError.localizedDescription,
+ location: .init(filePath: input.absolutePath.path)
+ )
}
+ }
+}
+
+extension Diagnostic {
+ /// Use when the document is an unsupported version.
+ static func openAPIVersionError(versionString: String, location: Location) -> Diagnostic { | Please also document parameters |
swift-openapi-generator | github_2023 | others | 81 | apple | czechboy0 | @@ -30,37 +30,84 @@ struct YamsParser: ParserProtocol {
var openapi: String?
}
- struct OpenAPIVersionError: Error, CustomStringConvertible, LocalizedError {
- var versionString: String
- var description: String {
- "Unsupported document version: \(versionString). Please provide a document with OpenAPI versions in the 3.0.x set."
- }
+ let versionedDocument: OpenAPIVersionedDocument
+ do {
+ versionedDocument = try decoder.decode(
+ OpenAPIVersionedDocument.self,
+ from: openapiData
+ )
+ } catch DecodingError.dataCorrupted(let errorContext) {
+ try checkParsingError(context: errorContext, input: input, diagnostics: diagnostics)
+ throw DecodingError.dataCorrupted(errorContext)
}
- struct OpenAPIMissingVersionError: Error, CustomStringConvertible, LocalizedError {
- var description: String {
- "No openapi key found, please provide a valid OpenAPI document with OpenAPI versions in the 3.0.x set."
- }
- }
-
- let versionedDocument = try decoder.decode(
- OpenAPIVersionedDocument.self,
- from: openapiData
- )
-
guard let openAPIVersion = versionedDocument.openapi else {
- throw OpenAPIMissingVersionError()
+ throw Diagnostic.openAPIMissingVersionError(location: .init(filePath: input.absolutePath.path))
}
switch openAPIVersion {
case "3.0.0", "3.0.1", "3.0.2", "3.0.3":
break
default:
- throw OpenAPIVersionError(versionString: "openapi: \(openAPIVersion)")
+ throw Diagnostic.openAPIVersionError(
+ versionString: "openapi: \(openAPIVersion)",
+ location: .init(filePath: input.absolutePath.path)
+ )
+ }
+
+ do {
+ return try decoder.decode(
+ OpenAPI.Document.self,
+ from: input.contents
+ )
+ } catch DecodingError.dataCorrupted(let errorContext) {
+ try checkParsingError(context: errorContext, input: input, diagnostics: diagnostics)
+ throw DecodingError.dataCorrupted(errorContext)
+ }
+ }
+
+ /// Detect specific YAML parsing errors to throw nicely formatted diagnostics for IDEs
+ private func checkParsingError(
+ context: DecodingError.Context,
+ input: InMemoryInputFile,
+ diagnostics: DiagnosticCollector
+ ) throws {
+ if let yamlError = context.underlyingError as? YamlError {
+ if case .parser(let yamlContext, let yamlProblem, let yamlMark, _) = yamlError {
+ throw Diagnostic.error(
+ message: "\(yamlProblem) \(yamlContext?.description ?? "")",
+ location: .init(filePath: input.absolutePath.path, lineNumber: yamlMark.line - 1)
+ )
+ } else if case .scanner(let yamlContext, let yamlProblem, let yamlMark, _) = yamlError {
+ throw Diagnostic.error(
+ message: "\(yamlProblem) \(yamlContext?.description ?? "")",
+ location: .init(filePath: input.absolutePath.path, lineNumber: yamlMark.line - 1)
+ )
+ }
+ } else if let openAPIError = context.underlyingError as? OpenAPIError {
+ throw Diagnostic.error(
+ message: openAPIError.localizedDescription,
+ location: .init(filePath: input.absolutePath.path)
+ )
}
+ }
+}
+
+extension Diagnostic {
+ /// Use when the document is an unsupported version.
+ static func openAPIVersionError(versionString: String, location: Location) -> Diagnostic {
+ return error(
+ message:
+ "Unsupported document version: \(versionString). Please provide a document with OpenAPI versions in the 3.0.x set.",
+ location: location
+ )
+ }
- return try decoder.decode(
- OpenAPI.Document.self,
- from: input.contents
+ // Use when the YAML document is completely missing the `openapi` version key.
+ static func openAPIMissingVersionError(location: Location) -> Diagnostic { | Please also document parameters |
swift-openapi-generator | github_2023 | others | 81 | apple | czechboy0 | @@ -30,37 +30,84 @@ struct YamsParser: ParserProtocol {
var openapi: String?
}
- struct OpenAPIVersionError: Error, CustomStringConvertible, LocalizedError {
- var versionString: String
- var description: String {
- "Unsupported document version: \(versionString). Please provide a document with OpenAPI versions in the 3.0.x set."
- }
+ let versionedDocument: OpenAPIVersionedDocument
+ do {
+ versionedDocument = try decoder.decode(
+ OpenAPIVersionedDocument.self,
+ from: openapiData
+ )
+ } catch DecodingError.dataCorrupted(let errorContext) {
+ try checkParsingError(context: errorContext, input: input, diagnostics: diagnostics)
+ throw DecodingError.dataCorrupted(errorContext)
}
- struct OpenAPIMissingVersionError: Error, CustomStringConvertible, LocalizedError {
- var description: String {
- "No openapi key found, please provide a valid OpenAPI document with OpenAPI versions in the 3.0.x set."
- }
- }
-
- let versionedDocument = try decoder.decode(
- OpenAPIVersionedDocument.self,
- from: openapiData
- )
-
guard let openAPIVersion = versionedDocument.openapi else {
- throw OpenAPIMissingVersionError()
+ throw Diagnostic.openAPIMissingVersionError(location: .init(filePath: input.absolutePath.path))
}
switch openAPIVersion {
case "3.0.0", "3.0.1", "3.0.2", "3.0.3":
break
default:
- throw OpenAPIVersionError(versionString: "openapi: \(openAPIVersion)")
+ throw Diagnostic.openAPIVersionError(
+ versionString: "openapi: \(openAPIVersion)",
+ location: .init(filePath: input.absolutePath.path)
+ )
+ }
+
+ do {
+ return try decoder.decode(
+ OpenAPI.Document.self,
+ from: input.contents
+ )
+ } catch DecodingError.dataCorrupted(let errorContext) {
+ try checkParsingError(context: errorContext, input: input, diagnostics: diagnostics)
+ throw DecodingError.dataCorrupted(errorContext)
+ }
+ }
+
+ /// Detect specific YAML parsing errors to throw nicely formatted diagnostics for IDEs
+ private func checkParsingError( | Please also document parameters |
swift-openapi-generator | github_2023 | others | 81 | apple | czechboy0 | @@ -85,11 +94,16 @@ public struct Diagnostic: Error, Codable {
public static func unsupported( | Please add documentation for the location parameter |
swift-openapi-generator | github_2023 | others | 81 | apple | czechboy0 | @@ -67,9 +75,10 @@ public struct Diagnostic: Error, Codable {
/// - Returns: An error diagnostic. | Please add documentation for the location parameter |
swift-openapi-generator | github_2023 | others | 81 | apple | czechboy0 | @@ -54,9 +61,10 @@ public struct Diagnostic: Error, Codable {
/// - Returns: A warning diagnostic.
public static func warning( | Please add documentation for the location parameter |
swift-openapi-generator | github_2023 | others | 81 | apple | czechboy0 | @@ -37,12 +37,19 @@ public struct Diagnostic: Error, Codable {
/// A user-friendly description of the diagnostic.
public var message: String
+ /// The absolute path to a specific source file and optional line number within that file that triggered the diagnostic.
+ public struct Location: Codable {
+ public var filePath: String
+ public var lineNumber: Int?
+ }
+ public var location: Location? | Please add documentation for the properties inside Location, and the location property itself. |
swift-openapi-generator | github_2023 | others | 87 | apple | denil-ct | @@ -0,0 +1,5 @@
+
+// Details: https://github.com/apple/swift-openapi-generator/issues/86
+#if os(iOS) || os(tvOS) || os(watchOS)
+#error("Running the generator tool itself is not supported on iOS, tvOS, and watchOS. Check that your app is not linking the generator directly. For details, check out: https://github.com/apple/swift-openapi-generator/issues/86") | `The generator tool cannot run on iOS, tvOS, or watchOS. Make sure your app does not link against the generator directly. See https://github.com/apple/swift-openapi-generator/issues/86 for details.`
I feel like this removes redundant words from the first sentence and on the second, it adds a more polite and imperative tone. |
swift-openapi-generator | github_2023 | others | 87 | apple | simonjbeaumont | @@ -0,0 +1,18 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+
+// Details: https://github.com/apple/swift-openapi-generator/issues/86
+#if os(iOS) || os(tvOS) || os(watchOS) | I think this is what we want. Especially with upcoming `visionOS`.
```suggestion
#if !(os(macOS) || os(Linux))
``` |
swift-openapi-generator | github_2023 | others | 87 | apple | simonjbeaumont | @@ -0,0 +1,18 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+
+// Details: https://github.com/apple/swift-openapi-generator/issues/86 | I'd rather us carry informative comments _here_ than link out to Github.
```suggestion
// Emit a compiler error if this library is linked with a target in an adopter project.
``` |
swift-openapi-generator | github_2023 | others | 87 | apple | simonjbeaumont | @@ -0,0 +1,18 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+
+// Details: https://github.com/apple/swift-openapi-generator/issues/86
+#if os(iOS) || os(tvOS) || os(watchOS)
+#error("Running the generator tool itself is not supported on iOS, tvOS, and watchOS. Check that your app is not linking the generator directly. For details, check out: https://github.com/apple/swift-openapi-generator/issues/86") | ```suggestion
#error("_OpenAPIGeneratorCore is only to be used by swift-openapi-generator itself—your target should not link this library directly.")
``` |
swift-openapi-generator | github_2023 | others | 87 | apple | simonjbeaumont | @@ -17,7 +17,13 @@ import PackageDescription
let package = Package(
name: "swift-openapi-generator",
platforms: [
- .macOS(.v10_15)
+ .macOS(.v10_15),
+
+ // The platforms below are not currently supported for running the
+ // generator itself (only the generated code), they are here
+ // to allow the generator to emit a more descriptive error,
+ // see the file PlatformChecks.swift for details.
+ .iOS(.v13), .tvOS(.v13), .watchOS(.v6), | I'm really not a fan of us having to do this and would rather us consider removing `_OpenAPIGeneratorCore` from `products`.
If we do have to do it, we can make use of string version numbers for unreasonably high version numbers, e.g.
```suggestion
.macOS(.v10_15),
// The platforms below are not currently supported for running the generator itself.
// We include them here to allow the us to emit a more descriptive compiler error.
.iOS("99"), .tvOS("99"), .watchOS("99"),
``` |
swift-openapi-generator | github_2023 | others | 88 | apple | simonjbeaumont | @@ -217,5 +217,7 @@ fileprivate extension String {
"Array",
"Type",
"type",
+ "Protocol", | Do we need this one? This works fine:
```swift
let Protocol = 1
print(Protocol) // prints 1
``` |
swift-openapi-generator | github_2023 | others | 88 | apple | simonjbeaumont | @@ -217,5 +217,7 @@ fileprivate extension String {
"Array",
"Type",
"type",
+ "Protocol",
+ "await", | This one is fun... TIL this fails only at use, but not on the variable declaration:
```swift
let await = 1 // this is fine
print(await) // this is the problem
``` |
swift-openapi-generator | github_2023 | others | 85 | apple | czechboy0 | @@ -38,7 +38,7 @@ The generated code relies on functionality in the runtime library that is not pa
To use this functionality, use an SPI import:
-```swift
+``` | Why the removal? I still think it's good to have them, so that previewing the markdown files outside of docc still gives you a nice experience. |
swift-openapi-generator | github_2023 | others | 77 | apple | czechboy0 | @@ -47,14 +47,14 @@ struct SwiftOpenAPIGeneratorPlugin {
targetName: String
) throws -> [Command] {
let inputFiles = sourceFiles
- guard let config = inputFiles.first(where: { $0.path.lastComponent == "openapi-generator-config.yaml" })?.path
+ guard let config = inputFiles.first(where: { $0.path.lastComponent == "openapi-generator-config.yaml" || $0.path.lastComponent == "openapi-generator-config.yml" })?.path | Since we're going from 1 to many here, could you refactor the closure to be similar to how we check for multiple names below, for the OpenAPI doc name? To avoid repeating the `$0.path.lastComponent`. |
swift-openapi-generator | github_2023 | others | 77 | apple | czechboy0 | @@ -28,10 +28,10 @@ struct SwiftOpenAPIGeneratorPlugin {
"Incompatible target called '\(targetName)'. Only Swift source targets can be used with the Swift OpenAPI generator plugin."
case .noConfigFound(let targetName):
return
- "No config found in the target named '\(targetName)'. Add a file called 'openapi-generator-config.yaml' to the target's source directory. See documentation for details."
+ "No config found in the target named '\(targetName)'. Add a file called 'openapi-generator-config.yaml' or 'openapi-generator-config.yml' to the target's source directory. See documentation for details."
case .noDocumentFound(let targetName):
return
- "No OpenAPI document found in the target named '\(targetName)'. Add a file called 'openapi.yaml' or 'openapi.json' (can also be a symlink) to the target's source directory. See documentation for details."
+ "No OpenAPI document found in the target named '\(targetName)'. Add a file called 'openapi.yaml', 'openapi.yml' or 'openapi.json' (can also be a symlink) to the target's source directory. See documentation for details." | Ah, good call updating the docs. One more to update: https://swiftpackageindex.com/apple/swift-openapi-generator/0.1.2/documentation/swift-openapi-generator/configuring-the-generator |
swift-openapi-generator | github_2023 | others | 77 | apple | czechboy0 | @@ -28,17 +28,20 @@ struct SwiftOpenAPIGeneratorPlugin {
"Incompatible target called '\(targetName)'. Only Swift source targets can be used with the Swift OpenAPI generator plugin."
case .noConfigFound(let targetName):
return
- "No config found in the target named '\(targetName)'. Add a file called 'openapi-generator-config.yaml' to the target's source directory. See documentation for details."
+ "No config found in the target named '\(targetName)'. Add a file called 'openapi-generator-config.yaml' or 'openapi-generator-config.yml' to the target's source directory. See documentation for details."
case .noDocumentFound(let targetName):
return
- "No OpenAPI document found in the target named '\(targetName)'. Add a file called 'openapi.yaml' or 'openapi.json' (can also be a symlink) to the target's source directory. See documentation for details."
+ "No OpenAPI document found in the target named '\(targetName)'. Add a file called 'openapi.yaml', 'openapi.yml' or 'openapi.json' (can also be a symlink) to the target's source directory. See documentation for details."
}
}
var errorDescription: String? {
description
}
}
+
+ private var supportedConfigFiles: Set<String> { Set(["yaml", "yml"].map { "openapi-generator-config." + $0 }) }
+ private var supportedDocFiles: Set<String> { Set(["yaml", "yml", "json"].map { "openapi." + $0 }) } | 👏 |
swift-openapi-generator | github_2023 | others | 77 | apple | simonjbeaumont | @@ -47,21 +50,14 @@ struct SwiftOpenAPIGeneratorPlugin {
targetName: String
) throws -> [Command] {
let inputFiles = sourceFiles
- guard let config = inputFiles.first(where: { $0.path.lastComponent == "openapi-generator-config.yaml" })?.path
- else {
+ guard let config = inputFiles.first(where: {
+ supportedConfigFiles.contains($0.path.lastComponent)
+ })?.path else {
throw Error.noConfigFound(targetName: targetName)
}
- guard
- let doc = inputFiles.first(where: {
- switch $0.path.lastComponent {
- case "openapi.yaml", "openapi.json":
- return true
- default:
- return false
- }
- })?
- .path
- else {
+ guard let doc = inputFiles.first(where: {
+ supportedDocFiles.contains($0.path.lastComponent)
+ })?.path else { | Should we consider what happens when there are multiple files here with different extensions.
Should we throw an error?
Similar question about the config file. Be nice to have some clear semantics, even if it’s explicitly disallowed.
//cc @czechboy0 |
swift-openapi-generator | github_2023 | others | 77 | apple | czechboy0 | @@ -28,10 +30,16 @@ struct SwiftOpenAPIGeneratorPlugin {
"Incompatible target called '\(targetName)'. Only Swift source targets can be used with the Swift OpenAPI generator plugin."
case .noConfigFound(let targetName):
return
- "No config found in the target named '\(targetName)'. Add a file called 'openapi-generator-config.yaml' to the target's source directory. See documentation for details."
+ "No config found in the target named '\(targetName)'. Add a file called 'openapi-generator-config.yaml' or 'openapi-generator-config.yml' to the target's source directory. See documentation for details."
case .noDocumentFound(let targetName):
return
- "No OpenAPI document found in the target named '\(targetName)'. Add a file called 'openapi.yaml' or 'openapi.json' (can also be a symlink) to the target's source directory. See documentation for details."
+ "No OpenAPI document found in the target named '\(targetName)'. Add a file called 'openapi.yaml', 'openapi.yml' or 'openapi.json' (can also be a symlink) to the target's source directory. See documentation for details."
+ case .multiConfigFound(let targetName, let files):
+ return
+ "Multi configs found in the target named '\(targetName)'. Found \(files.map(\.description).joined(separator: " "))." | ```suggestion
"Multiple config files found in the target named '\(targetName)', but exactly one is required. Found \(files.map(\.description).joined(separator: " "))."
``` |
swift-openapi-generator | github_2023 | others | 77 | apple | czechboy0 | @@ -28,10 +30,16 @@ struct SwiftOpenAPIGeneratorPlugin {
"Incompatible target called '\(targetName)'. Only Swift source targets can be used with the Swift OpenAPI generator plugin."
case .noConfigFound(let targetName):
return
- "No config found in the target named '\(targetName)'. Add a file called 'openapi-generator-config.yaml' to the target's source directory. See documentation for details."
+ "No config found in the target named '\(targetName)'. Add a file called 'openapi-generator-config.yaml' or 'openapi-generator-config.yml' to the target's source directory. See documentation for details."
case .noDocumentFound(let targetName):
return
- "No OpenAPI document found in the target named '\(targetName)'. Add a file called 'openapi.yaml' or 'openapi.json' (can also be a symlink) to the target's source directory. See documentation for details."
+ "No OpenAPI document found in the target named '\(targetName)'. Add a file called 'openapi.yaml', 'openapi.yml' or 'openapi.json' (can also be a symlink) to the target's source directory. See documentation for details."
+ case .multiConfigFound(let targetName, let files):
+ return
+ "Multi configs found in the target named '\(targetName)'. Found \(files.map(\.description).joined(separator: " "))."
+ case .multiDocumentFound(let targetName, let files):
+ return
+ "Multi OpenAPI documents found in the target named '\(targetName)'. Found \(files.map(\.description).joined(separator: " "))." | ```suggestion
"Multiple OpenAPI documents found in the target named '\(targetName)', but exactly one is required. Found \(files.map(\.description).joined(separator: " "))."
``` |
swift-openapi-generator | github_2023 | others | 77 | apple | czechboy0 | @@ -40,28 +48,28 @@ struct SwiftOpenAPIGeneratorPlugin {
}
}
+ private var supportedConfigFiles: Set<String> { Set(["yaml", "yml"].map { "openapi-generator-config." + $0 }) }
+ private var supportedDocFiles: Set<String> { Set(["yaml", "yml", "json"].map { "openapi." + $0 }) }
+
func createBuildCommands(
pluginWorkDirectory: PackagePlugin.Path,
tool: (String) throws -> PackagePlugin.PluginContext.Tool,
sourceFiles: FileList,
targetName: String
) throws -> [Command] {
let inputFiles = sourceFiles
- guard let config = inputFiles.first(where: { $0.path.lastComponent == "openapi-generator-config.yaml" })?.path
- else {
+ let matchedConfigs = inputFiles.filter { supportedConfigFiles.contains($0.path.lastComponent) }.map(\.path)
+ guard matchedConfigs.count > 1 else {
+ throw Error.multiConfigFound(targetName: targetName, files: matchedConfigs)
+ }
+ guard let config = matchedConfigs.first else { | I think this (and similar for the docs below) needs a bit of work, to cover the following conditions:
- no match found, throw `noConfigFound`
- more than 1 match found, throw `multipleConfigsFound` |
swift-openapi-generator | github_2023 | others | 77 | apple | czechboy0 | @@ -37,7 +37,7 @@ if [ "${SWIFT_FORMAT_RC}" -ne 0 ]; then
To fix, run the following command:
- % swift-format format --parallel --recursive --in-place Examples IntegrationTests Plugins Sources Tests
+ % swift-format format --parallel --recursive --in-place Examples IntegrationTest Plugins Sources Tests | Oh, great catch, thanks for fixing as well. |
swift-openapi-generator | github_2023 | others | 69 | apple | czechboy0 | @@ -344,7 +344,7 @@ final class Test_Client: XCTestCase {
func testProbe_204() async throws {
transport = .init { request, baseURL, operationID in
XCTAssertEqual(operationID, "probe")
- XCTAssertEqual(request.path, "/probe")
+ XCTAssertEqual(request.path, "/probe/") | Great, thanks for updating the `PetstoreConsumerTests` target as well – this is the important bit that verifies that the trailing slash is actually passed to the transport, and not stripped between OpenAPIKit and the generated code. |
swift-openapi-generator | github_2023 | others | 74 | apple | czechboy0 | @@ -44,3 +44,8 @@ struct TypedSchemaContent {
typeUsage ?? TypeName.valueContainer.asUsage
}
}
+
+/// An unresolved OpenAPI schema.
+///
+/// Can be either a reference or an inline schema.
+typealias UnresolvedSchema = Either<JSONReference<JSONSchema>, JSONSchema> | I think the location is fine. |
swift-openapi-generator | github_2023 | others | 74 | apple | czechboy0 | @@ -113,3 +113,11 @@ extension FileTranslator {
)
}
}
+
+/// An unresolved OpenAPI request.
+///
+/// Can be either a reference or an inline request.
+typealias UnresolvedRequest = Either<JSONReference<OpenAPI.Request>, OpenAPI.Request>
+
+/// A resolved OpenAPI request.
+typealias ResolvedRequest = OpenAPI.Request | I think I agree - can you get rid of all the Resolved* typealiases? They seem like an unnecessary layer of indirection. |
swift-openapi-generator | github_2023 | others | 74 | apple | simonjbeaumont | @@ -228,9 +228,6 @@ extension FileTranslator {
/// Can be either a reference or an inline parameter.
typealias UnresolvedParameter = Either<JSONReference<OpenAPI.Parameter>, OpenAPI.Parameter>
-/// A resolved OpenAPI parameter.
-typealias ResolvedParameter = OpenAPI.Parameter | Thanks for clearing up the asymmetry here. 👍 |
swift-openapi-generator | github_2023 | others | 74 | apple | simonjbeaumont | @@ -164,3 +164,8 @@ extension FileTranslator {
)
}
}
+
+/// An unresolved OpenAPI response header.
+///
+/// Can be either a reference or an inline response header.
+typealias UnresolvedHeader = Either<JSONReference<OpenAPI.Header>, OpenAPI.Header> | Nit: The OpenAPI spec has the headers at a scope not specific to responses, e.g. when used in `#components/headers`.
```suggestion
/// An unresolved OpenAPI header.
///
/// Can be either a reference or an inline header.
typealias UnresolvedHeader = Either<JSONReference<OpenAPI.Header>, OpenAPI.Header>
``` |
swift-openapi-generator | github_2023 | others | 67 | apple | czechboy0 | @@ -133,31 +133,26 @@ extension ResponseKind {
extension Comment {
- /// Returns a documentation comment for an OpenAPI operation.
+ /// Returns a reference documentation string to attach to the generated function for an operation.
///
- /// For example: "Operation `getPet` performs `GET` on `/pets/{petId}`".
/// - Parameters:
- /// - operationID: The identifier of the OpenAPI operation.
- /// - method: The HTTP method of the OpenAPI operation.
- /// - path: The URL path of the OpenAPI operation.
- static func operation(
- operationID: String?,
- method: OpenAPI.HttpMethod,
- path: OpenAPI.Path
- ) -> Self {
- let operationName: String
- if let operationID {
- operationName = "`\(operationID)` "
- } else {
- operationName = ""
- }
+ /// - operationDescription: The OpenAPI operation description.
+ init(from operationDescription: OperationDescription) { | I'd prefer if we provided the necessary values explicitly, i.e. by adding `summary` and `description` as optional String parameters, instead of requiring a whole `OperationDescription`. That'll preserve its ability to be easily unit tested, whereas providing a whole `OperationDescription` would require bringing up a bunch of unnecessary state in tests.
But happy to go from a static method to an initializer, that part is fine. |
swift-openapi-generator | github_2023 | others | 56 | apple | czechboy0 | @@ -0,0 +1,48 @@
+#!/usr/bin/env bash
+##===----------------------------------------------------------------------===##
+##
+## This source file is part of the SwiftOpenAPIGenerator open source project
+##
+## Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+## Licensed under Apache License v2.0
+##
+## See LICENSE.txt for license information
+## See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+##
+## SPDX-License-Identifier: Apache-2.0
+##
+##===----------------------------------------------------------------------===##
+set -euo pipefail
+
+log() { printf -- "** %s\n" "$*" >&2; }
+error() { printf -- "** ERROR: %s\n" "$*" >&2; }
+fatal() { error "$@"; exit 1; }
+
+log "Checking required executables..."
+SWIFT_BIN=${SWIFT_BIN:-$(command -v swift || xcrun -f swift)} || fatal "SWIFT_BIN unset and no swift on PATH"
+JQ_BIN=${JQ_BIN:-$(command -v jq)} || fatal "JQ_BIN unset and no jq on PATH"
+
+CURRENT_SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
+REPO_ROOT="$(git -C "${CURRENT_SCRIPT_DIR}" rev-parse --show-toplevel)"
+TMP_DIR=$(mktemp -d "${PWD}/tmp.$(basename "$0").XXXXXXXXXX.noindex")
+
+PACKAGE_PATH=${PACKAGE_PATH:-${REPO_ROOT}}
+
+SWIFT_OPENAPI_GENERATOR_REPO_URL="${SWIFT_OPENAPI_GENERATOR_REPO_URL:-https://github.com/apple/swift-openapi-generator}"
+SWIFT_OPENAPI_GENERATOR_REPO_CLONE_DIR="${TMP_DIR}/$(basename "${SWIFT_OPENAPI_GENERATOR_REPO_URL}")"
+INTEGRATION_TEST_PACKAGE_PATH="${SWIFT_OPENAPI_GENERATOR_REPO_CLONE_DIR}/IntegrationTest"
+
+log "Cloning ${SWIFT_OPENAPI_GENERATOR_REPO_URL} to ${SWIFT_OPENAPI_GENERATOR_REPO_CLONE_DIR}"
+git clone --depth=1 "${SWIFT_OPENAPI_GENERATOR_REPO_URL}" "${SWIFT_OPENAPI_GENERATOR_REPO_CLONE_DIR}"
+
+log "Extracting name for Swift package: ${PACKAGE_PATH}"
+PACKAGE_NAME=$(swift package --package-path "${PACKAGE_PATH}" describe --type json | jq -r .name) | ```suggestion
PACKAGE_NAME=$(swift package --package-path "${PACKAGE_PATH}" describe --type json | $JQ_BIN -r .name)
``` |
swift-openapi-generator | github_2023 | others | 49 | apple | simonjbeaumont | @@ -0,0 +1,44 @@
+# Proposals
+
+Collaborate on API changes to Swift OpenAPI Generator by writing a proposal.
+
+## Overview
+
+For non-trivial changes that affect the public API, the Swift OpenAPI Generator project adopts a ligthweight version of the [Swift Evolution](https://github.com/apple/swift-evolution/blob/main/process.md) process.
+
+Writing a proposal first helps discuss multiple possible solutions early, apply useful feedback from other contributors, and avoid re-implementing the same feature multiple times. | Nit: re-implementing -> reimplementing
```suggestion
Writing a proposal first helps discuss multiple possible solutions early, apply useful feedback from other contributors, and avoid reimplementing the same feature multiple times.
``` |
swift-openapi-generator | github_2023 | others | 49 | apple | simonjbeaumont | @@ -0,0 +1,44 @@
+# Proposals
+
+Collaborate on API changes to Swift OpenAPI Generator by writing a proposal.
+
+## Overview
+
+For non-trivial changes that affect the public API, the Swift OpenAPI Generator project adopts a ligthweight version of the [Swift Evolution](https://github.com/apple/swift-evolution/blob/main/process.md) process.
+
+Writing a proposal first helps discuss multiple possible solutions early, apply useful feedback from other contributors, and avoid re-implementing the same feature multiple times.
+
+While it's encouraged to get feedback by opening a pull request with a proposal early in the process, it's also important to consider the complexity of the implementation when evaluating different solutions (as per <doc:Project-scope-and-goals>). For example, this might mean including a prototype implementation of the feature in the same PR as the proposal document.
+
+> Note: The goal of this process is to help solicit feedback from the whole community around the project, and we will continue to refine the proposal process itself. Use your best judgement, and don't hesitate to propose changes to the proposal structure itself! | Nit: extra space.
```suggestion
> Note: The goal of this process is to help solicit feedback from the whole community around the project, and we will continue to refine the proposal process itself. Use your best judgement, and don't hesitate to propose changes to the proposal structure itself!
``` |
swift-openapi-generator | github_2023 | others | 50 | apple | simonjbeaumont | @@ -0,0 +1,234 @@
+# Converting between data and Swift types
+
+Learn about the type responsible for convertering between raw data and Swift types.
+
+## Overview
+
+The [`Converter`](https://github.com/apple/swift-openapi-runtime/blob/main/Sources/OpenAPIRuntime/Conversion/Converter.swift) type is a structure defined in the runtime library and is used by both the client and server generated code to perform conversions between raw data and Swift types.
+
+> Note: `Converter` is one of the SPI types, not considered part of the public API of the runtime library. However, because generated code relies on it, SPI stability needs to be considered when making changes to it and to the generator.
+
+Most of the functionality of `Converter` is implemented as helper methods in extensions:
+- [`Converter+Client.swift`](https://github.com/apple/swift-openapi-runtime/blob/main/Sources/OpenAPIRuntime/Conversion/Converter%2BClient.swift)
+- [`Converter+Server.swift`](https://github.com/apple/swift-openapi-runtime/blob/main/Sources/OpenAPIRuntime/Conversion/Converter%2BServer.swift)
+- [`Converter+Common.swift`](https://github.com/apple/swift-openapi-runtime/blob/main/Sources/OpenAPIRuntime/Conversion/Converter%2BCommon.swift)
+
+Some helper methods can be reused between client and server code, such as headers, but most can't. It's important that we only generalize (move helper methods into common extensions) if the client and server variants would have been exact copies. However, if there are differences, prefer to keep them separate and optimize each variant (for client or server) separately.
+
+### Generated code and generics interaction
+
+As outlined in <doc:Project-scope-and-goals>, we aim to minimize the complexity of the generator and rely on the Swift compiler to help ensure that if generated code compiles, it's likely to work correctly.
+
+To that end, if the input OpenAPI document contains an input that Swift OpenAPI Generator doesn't support, our first preference is to catch it in the generator and emit a descriptive error. However, there are cases where that is prohibitively complex, and we let the Swift compiler ensure that, for example, an array of strings cannot be used as a path parameter. In this example case, the generator emits code with the path parameter being of Swift type `[String]`, but since there doesn't exist a converter method for it, it will fail to build. This is considered expected behavior. | > "...emit a descriptive error..."
Don't we usually emit a diagnostic and try to continue? |
swift-openapi-generator | github_2023 | others | 50 | apple | simonjbeaumont | @@ -0,0 +1,234 @@
+# Converting between data and Swift types
+
+Learn about the type responsible for convertering between raw data and Swift types.
+
+## Overview
+
+The [`Converter`](https://github.com/apple/swift-openapi-runtime/blob/main/Sources/OpenAPIRuntime/Conversion/Converter.swift) type is a structure defined in the runtime library and is used by both the client and server generated code to perform conversions between raw data and Swift types.
+
+> Note: `Converter` is one of the SPI types, not considered part of the public API of the runtime library. However, because generated code relies on it, SPI stability needs to be considered when making changes to it and to the generator.
+
+Most of the functionality of `Converter` is implemented as helper methods in extensions:
+- [`Converter+Client.swift`](https://github.com/apple/swift-openapi-runtime/blob/main/Sources/OpenAPIRuntime/Conversion/Converter%2BClient.swift)
+- [`Converter+Server.swift`](https://github.com/apple/swift-openapi-runtime/blob/main/Sources/OpenAPIRuntime/Conversion/Converter%2BServer.swift)
+- [`Converter+Common.swift`](https://github.com/apple/swift-openapi-runtime/blob/main/Sources/OpenAPIRuntime/Conversion/Converter%2BCommon.swift)
+
+Some helper methods can be reused between client and server code, such as headers, but most can't. It's important that we only generalize (move helper methods into common extensions) if the client and server variants would have been exact copies. However, if there are differences, prefer to keep them separate and optimize each variant (for client or server) separately.
+
+### Generated code and generics interaction
+
+As outlined in <doc:Project-scope-and-goals>, we aim to minimize the complexity of the generator and rely on the Swift compiler to help ensure that if generated code compiles, it's likely to work correctly.
+
+To that end, if the input OpenAPI document contains an input that Swift OpenAPI Generator doesn't support, our first preference is to catch it in the generator and emit a descriptive error. However, there are cases where that is prohibitively complex, and we let the Swift compiler ensure that, for example, an array of strings cannot be used as a path parameter. In this example case, the generator emits code with the path parameter being of Swift type `[String]`, but since there doesn't exist a converter method for it, it will fail to build. This is considered expected behavior.
+
+In the case of the converter, it contains helper methods for all the supported combinations of an HTTP location, a "content type family" and a Swift type.
+
+First, a _schema location_ refers to one of the several places where schemas can be used in OpenAPI documents. For example:
+- request path parameters
+- request headers
+- response bodies
+- and more
+
+Second, a _content type family_ can be one of:
+- `structured`
+ - example: `application/json`
+ - uses the type's `Codable` implementation
+- `text`
+ - example: `text/plain`
+ - uses the type's `LosslessStringConvertible` implementation, except for `Foundation.Date`, which uses a system date formatter
+- `raw`
+ - example: `application/octet-stream`
+ - doesn't transform the raw data, just passes it through
+
+The content type family is derived from the `content` map in the OpenAPI document, if provided. If none is provided, such as in case of parameters, `text` is used.
+
+And third, a Swift type is calculated from the JSON schema provided in the OpenAPI document.
+
+For example, a `string` schema is generated as `Swift.String`, an `object` schema is generated as a Swift structure, and an array schema is generated as a `Swift.Array` generic over the element type.
+
+Together, the schema location, the content type family, and the Swift type is enough to unambiguously decide which helper method on the converter should be used.
+
+For example, to use the converter to get a required response header of type `Foundation.Date` using the `text` content type family, look for a method (exact spelling is subject to change) that looks like:
+
+```swift
+func headerFieldGetTextRequired( // <<< 1.
+ in headerFields: [HeaderField],
+ name: String,
+ as type: Date.Type // <<< 2.
+) throws -> Date
+```
+
+In `1.`, notice that the method name contains which schema location, content type family, and optionality; whilie in `2.` it contains the Swift type. | ```suggestion
In `1.`, notice that the method name contains which schema location, content type family, and optionality; while in `2.` it contains the Swift type.
``` |
swift-openapi-generator | github_2023 | others | 50 | apple | simonjbeaumont | @@ -0,0 +1,234 @@
+# Converting between data and Swift types
+
+Learn about the type responsible for convertering between raw data and Swift types.
+
+## Overview
+
+The [`Converter`](https://github.com/apple/swift-openapi-runtime/blob/main/Sources/OpenAPIRuntime/Conversion/Converter.swift) type is a structure defined in the runtime library and is used by both the client and server generated code to perform conversions between raw data and Swift types.
+
+> Note: `Converter` is one of the SPI types, not considered part of the public API of the runtime library. However, because generated code relies on it, SPI stability needs to be considered when making changes to it and to the generator.
+
+Most of the functionality of `Converter` is implemented as helper methods in extensions:
+- [`Converter+Client.swift`](https://github.com/apple/swift-openapi-runtime/blob/main/Sources/OpenAPIRuntime/Conversion/Converter%2BClient.swift)
+- [`Converter+Server.swift`](https://github.com/apple/swift-openapi-runtime/blob/main/Sources/OpenAPIRuntime/Conversion/Converter%2BServer.swift)
+- [`Converter+Common.swift`](https://github.com/apple/swift-openapi-runtime/blob/main/Sources/OpenAPIRuntime/Conversion/Converter%2BCommon.swift)
+
+Some helper methods can be reused between client and server code, such as headers, but most can't. It's important that we only generalize (move helper methods into common extensions) if the client and server variants would have been exact copies. However, if there are differences, prefer to keep them separate and optimize each variant (for client or server) separately.
+
+### Generated code and generics interaction
+
+As outlined in <doc:Project-scope-and-goals>, we aim to minimize the complexity of the generator and rely on the Swift compiler to help ensure that if generated code compiles, it's likely to work correctly.
+
+To that end, if the input OpenAPI document contains an input that Swift OpenAPI Generator doesn't support, our first preference is to catch it in the generator and emit a descriptive error. However, there are cases where that is prohibitively complex, and we let the Swift compiler ensure that, for example, an array of strings cannot be used as a path parameter. In this example case, the generator emits code with the path parameter being of Swift type `[String]`, but since there doesn't exist a converter method for it, it will fail to build. This is considered expected behavior.
+
+In the case of the converter, it contains helper methods for all the supported combinations of an HTTP location, a "content type family" and a Swift type.
+
+First, a _schema location_ refers to one of the several places where schemas can be used in OpenAPI documents. For example:
+- request path parameters
+- request headers
+- response bodies
+- and more
+
+Second, a _content type family_ can be one of:
+- `structured`
+ - example: `application/json`
+ - uses the type's `Codable` implementation
+- `text`
+ - example: `text/plain`
+ - uses the type's `LosslessStringConvertible` implementation, except for `Foundation.Date`, which uses a system date formatter
+- `raw`
+ - example: `application/octet-stream`
+ - doesn't transform the raw data, just passes it through
+
+The content type family is derived from the `content` map in the OpenAPI document, if provided. If none is provided, such as in case of parameters, `text` is used.
+
+And third, a Swift type is calculated from the JSON schema provided in the OpenAPI document.
+
+For example, a `string` schema is generated as `Swift.String`, an `object` schema is generated as a Swift structure, and an array schema is generated as a `Swift.Array` generic over the element type.
+
+Together, the schema location, the content type family, and the Swift type is enough to unambiguously decide which helper method on the converter should be used.
+
+For example, to use the converter to get a required response header of type `Foundation.Date` using the `text` content type family, look for a method (exact spelling is subject to change) that looks like:
+
+```swift
+func headerFieldGetTextRequired( // <<< 1.
+ in headerFields: [HeaderField],
+ name: String,
+ as type: Date.Type // <<< 2.
+) throws -> Date | While we might want to have the combinatorial explosion of methods internally, could they all be dispatched from one to help reduce the complexity in the generator.
I haven't fully thought this through, but something like:
```swift
func getParameter<T>(
name: String,
location: ParameterLocation,
required: Bool,
as type: T.Type = T.self
) throws -> T
func getBody<T>(
name: String,
required: Bool,
contentType: ContentType,
) throws -> T
```
Where `ParameterLocation` and `ContentType` are enum-like types? |
swift-openapi-generator | github_2023 | others | 50 | apple | simonjbeaumont | @@ -0,0 +1,234 @@
+# Converting between data and Swift types
+
+Learn about the type responsible for convertering between raw data and Swift types.
+
+## Overview
+
+The [`Converter`](https://github.com/apple/swift-openapi-runtime/blob/main/Sources/OpenAPIRuntime/Conversion/Converter.swift) type is a structure defined in the runtime library and is used by both the client and server generated code to perform conversions between raw data and Swift types.
+
+> Note: `Converter` is one of the SPI types, not considered part of the public API of the runtime library. However, because generated code relies on it, SPI stability needs to be considered when making changes to it and to the generator.
+
+Most of the functionality of `Converter` is implemented as helper methods in extensions:
+- [`Converter+Client.swift`](https://github.com/apple/swift-openapi-runtime/blob/main/Sources/OpenAPIRuntime/Conversion/Converter%2BClient.swift)
+- [`Converter+Server.swift`](https://github.com/apple/swift-openapi-runtime/blob/main/Sources/OpenAPIRuntime/Conversion/Converter%2BServer.swift)
+- [`Converter+Common.swift`](https://github.com/apple/swift-openapi-runtime/blob/main/Sources/OpenAPIRuntime/Conversion/Converter%2BCommon.swift)
+
+Some helper methods can be reused between client and server code, such as headers, but most can't. It's important that we only generalize (move helper methods into common extensions) if the client and server variants would have been exact copies. However, if there are differences, prefer to keep them separate and optimize each variant (for client or server) separately.
+
+### Generated code and generics interaction
+
+As outlined in <doc:Project-scope-and-goals>, we aim to minimize the complexity of the generator and rely on the Swift compiler to help ensure that if generated code compiles, it's likely to work correctly.
+
+To that end, if the input OpenAPI document contains an input that Swift OpenAPI Generator doesn't support, our first preference is to catch it in the generator and emit a descriptive diagnostic. However, there are cases where that is prohibitively complex, and we let the Swift compiler ensure that, for example, an array of strings cannot be used as a path parameter. In this example case, the generator emits code with the path parameter being of Swift type `[String]`, but since there doesn't exist a converter method for it, it will fail to build. This is considered expected behavior.
+
+In the case of the converter, it contains helper methods for all the supported combinations of an HTTP location, a "content type family" and a Swift type.
+
+First, a _schema location_ refers to one of the several places where schemas can be used in OpenAPI documents. For example:
+- request path parameters
+- request headers
+- response bodies
+- and more
+
+Second, a _content type family_ can be one of:
+- `structured`
+ - example: `application/json`
+ - uses the type's `Codable` implementation
+- `text`
+ - example: `text/plain`
+ - uses the type's `LosslessStringConvertible` implementation, except for `Foundation.Date`, which uses a system date formatter
+- `raw`
+ - example: `application/octet-stream`
+ - doesn't transform the raw data, just passes it through
+
+The content type family is derived from the `content` map in the OpenAPI document, if provided. If none is provided, such as in case of parameters, `text` is used.
+
+And third, a Swift type is calculated from the JSON schema provided in the OpenAPI document.
+
+For example, a `string` schema is generated as `Swift.String`, an `object` schema is generated as a Swift structure, and an array schema is generated as a `Swift.Array` generic over the element type.
+
+Together, the schema location, the content type family, and the Swift type is enough to unambiguously decide which helper method on the converter should be used.
+
+For example, to use the converter to get a required response header of type `Foundation.Date` using the `text` content type family, look for a method (exact spelling is subject to change) that looks like:
+
+```swift
+func headerFieldGetTextRequired( // <<< 1.
+ in headerFields: [HeaderField],
+ name: String,
+ as type: Date.Type // <<< 2.
+) throws -> Date
+```
+
+In `1.`, notice that the method name contains which schema location, content type family, and optionality; while in `2.` it contains the Swift type.
+
+### Helper method variants
+
+In the nested list below, each leaf is one helper method.
+
+"string-convertible" refers to types that conform to `LosslessStringConvertible` (but not `Foundation.Date`, which is handled separately).
+
+
+#### Required by client code
+
+- request
+ - set request path [client-only]
+ - text
+ - string-convertible
+ - optional/required
+ - date
+ - optional/required
+ - set request query [client-only]
+ - text
+ - string-convertible
+ - optional/required
+ - array of string-convertibles
+ - optional/required
+ - date
+ - optional/required
+ - array of dates
+ - optional/required
+ - set request headers [common]
+ - text
+ - string-convertible
+ - optional/required
+ - array of string-convertibles
+ - optional/required
+ - date
+ - optional/required
+ - array of dates
+ - optional/required
+ - structured
+ - codable
+ - optional/required | Should I always read `codable` as JSON?
Are there other ways we can structure data that we want to support? If so, should we spell our API more explicitly to accommodate this, even if it's not going to be in the initial supported things?
|
swift-openapi-generator | github_2023 | others | 2 | apple | tomerd | @@ -61,7 +61,9 @@ let package = Package(
),
// Tests-only: Runtime library linked by generated code
- .package(url: "https://github.com/apple/swift-openapi-runtime", .upToNextMinor(from: "0.1.0")),
+ // FIXME: swift-openapi-runtime is private, so we can't access it anonymously yet
+ //.package(url: "https://github.com/apple/swift-openapi-runtime", .upToNextMinor(from: "0.1.0")),
+ .package(url: "git@github.com:apple/swift-openapi-runtime.git", .upToNextMinor(from: "0.1.0")), | seems fine for now, we can change later when made public? |
app-store-server-library-java | github_2023 | others | 97 | apple | izanger | @@ -1,5 +1,10 @@
# Changelog
+## Version 2.1.0
+- Incorporate changes for App Store Server API v1.11 and App Store Server Notifications v2.11 [https://github.com/apple/app-store-server-library-java/pull/94]
+- Add a proxy authenticator support [https://github.com/apple/app-store-server-library-java/pull/93] | Should this read `Add proxy authenticator support`?
|
app-store-server-library-java | github_2023 | java | 94 | apple | izanger | @@ -0,0 +1,45 @@
+// Copyright (c) 2024 Apple Inc. Licensed under MIT License.
+
+package com.apple.itunes.storekit.model;
+
+import com.fasterxml.jackson.annotation.JsonValue;
+
+/**
+ * The customer-provided reason for a refund request.
+ *
+ * @see <a href="https://developer.apple.com/documentation/appstoreservernotifications/consumptionrequestreason">consumptionRequestReason</a>
+ */
+public enum ConsumptionRequestReason {
+
+ UNINTENDED_PURCHASE("UNINTENDED_PURCHASE"),
+ FULFILLMENT_ISSUE("FULFILLMENT_ISSUE"),
+ UNSATISFIED_WITH_PURCHASE("UNSATISFIED_WITH_PURCHASE"),
+ LEGAL("LEGAL"),
+ OTHER("OTHER");
+
+ private final String value;
+
+ ConsumptionRequestReason(String value) {
+ this.value = value;
+ }
+
+ public static ConsumptionRequestReason fromValue(String value) {
+ for (ConsumptionRequestReason b : ConsumptionRequestReason.values()) { | Nit: Why the letter b? |
app-store-server-library-java | github_2023 | java | 94 | apple | izanger | @@ -0,0 +1,44 @@
+// Copyright (c) 2024 Apple Inc. Licensed under MIT License.
+
+package com.apple.itunes.storekit.model;
+
+import com.fasterxml.jackson.annotation.JsonValue;
+
+/**
+ * A value that indicates your preferred outcome for the refund request.
+ *
+ * @see <a href="https://developer.apple.com/documentation/appstoreserverapi/refundpreference">refundPreference</a>
+ */
+public enum RefundPreference {
+
+ UNDECLARED(0),
+ PREFER_GRANT(1),
+ PREFER_DECLINE(2),
+ NO_PREFERENCE(3);
+
+ private final Integer value;
+
+ RefundPreference(Integer value) {
+ this.value = value;
+ }
+
+ public static RefundPreference fromValue(Integer value) {
+ for (RefundPreference b : RefundPreference.values()) { | Same here |
app-store-server-library-java | github_2023 | others | 75 | apple | izanger | @@ -1,5 +1,9 @@
# Changelog
+## Version 1.1.0
+- Support App Store Server Notification v2.10 [#74] | Notification -> Notifications |
app-store-server-library-java | github_2023 | others | 75 | apple | izanger | @@ -1,5 +1,9 @@
# Changelog | Can we make this file an .md so GH renders it nicely? |
app-store-server-library-java | github_2023 | java | 60 | apple | izanger | @@ -9,40 +9,59 @@
*/
public class APIException extends Exception {
private final int httpStatusCode;
- private final Long apiError;
+ private final Long apiErrorCode;
+ private final String apiErrorMessage;
+
+ public APIException(int httpStatusCode, Exception cause) {
+ super("Failed to call API with httpStatusCode=" + httpStatusCode, cause);
+ this.httpStatusCode = httpStatusCode;
+ this.apiErrorCode = null;
+ this.apiErrorMessage = null;
+ }
public APIException(int httpStatusCode) {
+ super("Failed to call API with httpStatusCode=" + httpStatusCode);
this.httpStatusCode = httpStatusCode;
- this.apiError = null;
+ this.apiErrorCode = null;
+ this.apiErrorMessage = null;
}
- public APIException(int httpStatusCode, APIError apiError) {
+ public APIException(int httpStatusCode, APIError apiError, String apiErrorMessage) {
+ super("Failed to call API with error=\"" + apiErrorMessage + "\"");
this.httpStatusCode = httpStatusCode;
- this.apiError = apiError != null ? apiError.errorCode() : null;
+ this.apiErrorCode = apiError != null ? apiError.errorCode() : null;
+ this.apiErrorMessage = apiErrorMessage;
}
- public APIException(int httpStatusCode, Long rawApiError) {
+ public APIException(int httpStatusCode, Long rawApiError, String apiErrorMessage) {
+ super("Failed to call API with error=\"" + apiErrorMessage + "\"");
this.httpStatusCode = httpStatusCode;
- this.apiError = rawApiError;
+ this.apiErrorCode = rawApiError;
+ this.apiErrorMessage = apiErrorMessage;
}
public int getHttpStatusCode() {
return httpStatusCode;
}
public APIError getApiError() {
- return apiError != null ? APIError.fetchErrorResponseFromErrorCode(apiError) : null;
+ return apiErrorCode != null ? APIError.fetchErrorResponseFromErrorCode(apiErrorCode) : null;
}
public Long getRawApiError() { | Suggest renaming to `getRawApiErrorCode` or just `getApiErrorCode` |
app-store-server-library-java | github_2023 | java | 60 | apple | izanger | @@ -9,40 +9,59 @@
*/
public class APIException extends Exception {
private final int httpStatusCode;
- private final Long apiError;
+ private final Long apiErrorCode;
+ private final String apiErrorMessage;
+
+ public APIException(int httpStatusCode, Exception cause) {
+ super("Failed to call API with httpStatusCode=" + httpStatusCode, cause);
+ this.httpStatusCode = httpStatusCode;
+ this.apiErrorCode = null;
+ this.apiErrorMessage = null;
+ }
public APIException(int httpStatusCode) {
+ super("Failed to call API with httpStatusCode=" + httpStatusCode);
this.httpStatusCode = httpStatusCode;
- this.apiError = null;
+ this.apiErrorCode = null;
+ this.apiErrorMessage = null;
}
- public APIException(int httpStatusCode, APIError apiError) {
+ public APIException(int httpStatusCode, APIError apiError, String apiErrorMessage) {
+ super("Failed to call API with error=\"" + apiErrorMessage + "\"");
this.httpStatusCode = httpStatusCode;
- this.apiError = apiError != null ? apiError.errorCode() : null;
+ this.apiErrorCode = apiError != null ? apiError.errorCode() : null;
+ this.apiErrorMessage = apiErrorMessage;
}
- public APIException(int httpStatusCode, Long rawApiError) {
+ public APIException(int httpStatusCode, Long rawApiError, String apiErrorMessage) {
+ super("Failed to call API with error=\"" + apiErrorMessage + "\"");
this.httpStatusCode = httpStatusCode;
- this.apiError = rawApiError;
+ this.apiErrorCode = rawApiError;
+ this.apiErrorMessage = apiErrorMessage;
}
public int getHttpStatusCode() {
return httpStatusCode;
}
public APIError getApiError() {
- return apiError != null ? APIError.fetchErrorResponseFromErrorCode(apiError) : null;
+ return apiErrorCode != null ? APIError.fetchErrorResponseFromErrorCode(apiErrorCode) : null;
}
public Long getRawApiError() {
- return apiError;
+ return apiErrorCode;
+ }
+
+ public String getApiErrorMessage() {
+ return apiErrorMessage;
}
@Override
public String toString() {
return "APIException{" +
"httpStatusCode=" + httpStatusCode +
- ", apiError=" + apiError +
- "} " + super.toString();
+ ", apiError=" + apiErrorCode + | apiError -> apiErrorCode |
app-store-server-library-java | github_2023 | java | 60 | apple | izanger | @@ -10,60 +10,390 @@
* See the specific documentation for each endpoint to learn more about what codes are possible from each endpoint.
*/
public enum APIError {
+ /**
+ * An error that indicates an invalid request.
+ *
+ * @see <a href="https://developer.apple.com/documentation/appstoreserverapi/generalbadrequesterror">GeneralBadRequestError</a>
+ */
GENERAL_BAD_REQUEST(4000000L),
+
+ /**
+ * An error that indicates an invalid app identifier.
+ *
+ * @see <a href="https://developer.apple.com/documentation/appstoreserverapi/invalidappidentifiererror">InvalidAppIdentifierError</a>
+ */
INVALID_APP_IDENTIFIER(4000002L),
+
+ /**
+ * An error that indicates an invalid request revision.
+ *
+ * @see <a href="https://developer.apple.com/documentation/appstoreserverapi/invalidrequestrevisionerror">InvalidRequestRevisionError</a>
+ */
INVALID_REQUEST_REVISION(4000005L),
+
+ /**
+ * An error that indicates an invalid transaction identifier.
+ *
+ * @see <a href="https://developer.apple.com/documentation/appstoreserverapi/invalidtransactioniderror">InvalidTransactionIdError</a>
+ */
INVALID_TRANSACTION_ID(4000006L),
+
+ /**
+ * An error that indicates an invalid original transaction identifier.
+ *
+ * @see <a href="https://developer.apple.com/documentation/appstoreserverapi/invalidoriginaltransactioniderror">InvalidOriginalTransactionIdError</a>
+ */
INVALID_ORIGINAL_TRANSACTION_ID(4000008L),
+
+ /**
+ * An error that indicates an invalid extend-by-days value.
+ *
+ * @see <a href="https://developer.apple.com/documentation/appstoreserverapi/invalidextendbydayserror">InvalidExtendByDaysError</a>
+ */
INVALID_EXTEND_BY_DAYS(4000009L),
+
+ /**
+ * An error that indicates an invalid reason code.
+ *
+ * @see <a href="https://developer.apple.com/documentation/appstoreserverapi/invalidextendreasoncodeerror">InvalidExtendReasonCodeError</a>
+ */
INVALID_EXTEND_REASON_CODE(4000010L),
+
+ /**
+ * An error that indicates an invalid request identifier.
+ *
+ * @see <a href="https://developer.apple.com/documentation/appstoreserverapi/invalidrequestidentifiererror">InvalidRequestIdentifierError</a>
+ */
INVALID_IDENTIFIER(4000011L), | Suggest a rename to `INVALID_REQUEST_IDENTIFIER` |
app-store-server-library-java | github_2023 | others | 41 | apple | alexanderjordanbaker | @@ -0,0 +1,5 @@
+-----BEGIN PRIVATE KEY----- | How was this private key generated? |
app-store-server-library-java | github_2023 | others | 12 | apple | izanger | @@ -32,9 +32,10 @@ jobs:
run: >
sudo -E env "PATH=$PATH" bash -c "ulimit -l 65536 && ulimit -a &&
./gradlew properties --no-daemon --console=plain -q | grep -E '^version: [\.0-9]+\-SNAPSHOT$' &&
- ./gradlew --no-daemon --parallel clean check &&
+ (./gradlew --no-daemon --parallel clean check &&
./gradlew --no-daemon --parallel sign &&
./gradlew --no-daemon --parallel publish" | Is this trailing `"` still in the right place given the parentheses? |
pfl-research | github_2023 | python | 110 | apple | grananqvist | @@ -259,24 +259,24 @@ def evaluate(self,
postprocess_fns = []
allows_distributed_evaluation = True
# TODO: Use Dataset.iter interface.
- for start_index in range(0, len(dataset), batch_size):
+ for batch_idx, batch in enumerate(dataset.iter(batch_size)): | you don't use this batch variable, see how https://github.com/apple/pfl-research/pull/110/files#diff-f1f2212b462bbc2552740cdfff9215807fda11940ce307afa7cab9776fb3ee50R242 is done |
pfl-research | github_2023 | python | 110 | apple | grananqvist | @@ -259,24 +259,24 @@ def evaluate(self,
postprocess_fns = []
allows_distributed_evaluation = True
# TODO: Use Dataset.iter interface. | now you can remove this todo :) |
pfl-research | github_2023 | python | 105 | apple | grananqvist | @@ -0,0 +1,128 @@
+# Copyright © 2023-2024 Apple Inc.
+'''
+Joint mechanism for combining multiple mechanisms into one.
+'''
+
+from typing import Dict, List, Optional, Set, Tuple
+
+from pfl.metrics import Metrics, StringMetricName
+from pfl.stats import MappedVectorStatistics, TrainingStatistics
+
+from .privacy_mechanism import CentrallyApplicablePrivacyMechanism
+
+
+def check_if_partition(full_set: Set[str], partition: List[Set[str]]):
+ """
+ Checks if each element of full_list appears in exactly one of
+ the sets in partition
+ """
+ partition_union: Set = set()
+ partition_size = 0
+ for s in partition:
+ partition_union = partition_union.union(s)
+ partition_size += len(s)
+
+ return (partition_union == full_set) and (partition_size == len(full_set))
+
+
+class JointMechanism(CentrallyApplicablePrivacyMechanism):
+ """
+ Constructs a new CentrallyApplicablePrivacyMechanism from existing ones.
+ Each existing mechanism is applied to a disjoint subset of the client
+ statistics keys. As such JointMechanism can only be applied to client
+ statistics of type MappedVectorStatistics.
+
+ :param mechanisms_and_keys:
+ Dictionary in which each key is a name of a mechanism and each value
+ is a tuple consisting of the corresponding CentrallyApplicablePrivacyMechanism
+ and a list of keys specifying which portion of the user training statistics that
+ mechanism should be applied to. Note the names of each of the mechanisms must be
+ distinct for the purpose of naming the corresponding Metrics.
+
+ """
+
+ def __init__(
+ self,
+ mechanisms_and_keys: Dict[str,
+ Tuple[CentrallyApplicablePrivacyMechanism,
+ List[str]]]):
+ if len(set(mechanisms_and_keys.keys())) < len(
+ mechanisms_and_keys.keys()):
+ raise ValueError('Mechanism names must be unique.')
+ self.mechanisms_and_keys = mechanisms_and_keys
+
+ def constrain_sensitivity(
+ self,
+ statistics: TrainingStatistics,
+ name_formatting_fn=lambda n: StringMetricName(n),
+ seed: Optional[int] = None) -> Tuple[TrainingStatistics, Metrics]:
+
+ if not isinstance(statistics, MappedVectorStatistics):
+ raise TypeError(
+ 'Statistics must be of type MappedVectorStatistics.')
+
+ if not check_if_partition(
+ set(statistics.keys()),
+ [set(keys) for _, keys in self.mechanisms_and_keys.values()]):
+ raise ValueError(
+ 'Mechanism keys do not form a partition of the client statistics keys.'
+ )
+
+ clipped_statistics: MappedVectorStatistics = MappedVectorStatistics()
+ metrics = Metrics()
+ for mechanism_name, (
+ mechanism,
+ statistics_keys) in self.mechanisms_and_keys.items():
+
+ def mechanism_name_formatting_fn(n, prefix=mechanism_name):
+ return name_formatting_fn(f'{prefix}: {n}') | can you do `f'{prefix} | {n}'` , like how metrics are usually formatted |
pfl-research | github_2023 | python | 105 | apple | grananqvist | @@ -0,0 +1,128 @@
+# Copyright © 2023-2024 Apple Inc.
+'''
+Joint mechanism for combining multiple mechanisms into one.
+'''
+
+from typing import Dict, List, Optional, Set, Tuple
+
+from pfl.metrics import Metrics, StringMetricName
+from pfl.stats import MappedVectorStatistics, TrainingStatistics
+
+from .privacy_mechanism import CentrallyApplicablePrivacyMechanism
+
+
+def check_if_partition(full_set: Set[str], partition: List[Set[str]]):
+ """
+ Checks if each element of full_list appears in exactly one of
+ the sets in partition
+ """
+ partition_union: Set = set()
+ partition_size = 0
+ for s in partition:
+ partition_union = partition_union.union(s)
+ partition_size += len(s)
+
+ return (partition_union == full_set) and (partition_size == len(full_set))
+
+
+class JointMechanism(CentrallyApplicablePrivacyMechanism):
+ """
+ Constructs a new CentrallyApplicablePrivacyMechanism from existing ones.
+ Each existing mechanism is applied to a disjoint subset of the client
+ statistics keys. As such JointMechanism can only be applied to client
+ statistics of type MappedVectorStatistics.
+
+ :param mechanisms_and_keys:
+ Dictionary in which each key is a name of a mechanism and each value
+ is a tuple consisting of the corresponding CentrallyApplicablePrivacyMechanism
+ and a list of keys specifying which portion of the user training statistics that
+ mechanism should be applied to. Note the names of each of the mechanisms must be
+ distinct for the purpose of naming the corresponding Metrics.
+
+ """
+
+ def __init__(
+ self,
+ mechanisms_and_keys: Dict[str,
+ Tuple[CentrallyApplicablePrivacyMechanism,
+ List[str]]]):
+ if len(set(mechanisms_and_keys.keys())) < len(
+ mechanisms_and_keys.keys()):
+ raise ValueError('Mechanism names must be unique.')
+ self.mechanisms_and_keys = mechanisms_and_keys
+
+ def constrain_sensitivity(
+ self,
+ statistics: TrainingStatistics,
+ name_formatting_fn=lambda n: StringMetricName(n),
+ seed: Optional[int] = None) -> Tuple[TrainingStatistics, Metrics]:
+
+ if not isinstance(statistics, MappedVectorStatistics):
+ raise TypeError(
+ 'Statistics must be of type MappedVectorStatistics.')
+
+ if not check_if_partition(
+ set(statistics.keys()),
+ [set(keys) for _, keys in self.mechanisms_and_keys.values()]):
+ raise ValueError(
+ 'Mechanism keys do not form a partition of the client statistics keys.'
+ )
+
+ clipped_statistics: MappedVectorStatistics = MappedVectorStatistics() | `statistics.weight` is lost here. can you make sure it is preserved in the return object and this is discovered in the tests? |
pfl-research | github_2023 | python | 105 | apple | grananqvist | @@ -484,3 +485,228 @@ def test_norm_clipping_only(self, order, clipping_bound, expected_arrays,
is_local_privacy=True)
assert get_overall_value(
metrics[name]) == pytest.approx(expected_clip_fraction)
+
+ @pytest.mark.parametrize('ops_module', framework_fixtures) | Since the mechanisms themselves are tested in other unittests, you can simplify this a lot by just using MagicMock as mechanisms input to JointMechanism.
and the test will be much faster, as i recall these statistical tests are not super fast. |
pfl-research | github_2023 | python | 105 | apple | grananqvist | @@ -0,0 +1,128 @@
+# Copyright © 2023-2024 Apple Inc.
+'''
+Joint mechanism for combining multiple mechanisms into one.
+'''
+
+from typing import Dict, List, Optional, Set, Tuple
+
+from pfl.metrics import Metrics, StringMetricName
+from pfl.stats import MappedVectorStatistics, TrainingStatistics
+
+from .privacy_mechanism import CentrallyApplicablePrivacyMechanism
+
+
+def check_if_partition(full_set: Set[str], partition: List[Set[str]]):
+ """
+ Checks if each element of full_list appears in exactly one of
+ the sets in partition
+ """
+ partition_union: Set = set()
+ partition_size = 0
+ for s in partition:
+ partition_union = partition_union.union(s)
+ partition_size += len(s)
+
+ return (partition_union == full_set) and (partition_size == len(full_set))
+
+
+class JointMechanism(CentrallyApplicablePrivacyMechanism):
+ """
+ Constructs a new CentrallyApplicablePrivacyMechanism from existing ones.
+ Each existing mechanism is applied to a disjoint subset of the client
+ statistics keys. As such JointMechanism can only be applied to client
+ statistics of type MappedVectorStatistics.
+
+ :param mechanisms_and_keys: | is it possible to add a feature to also allow specify keys by sub path. e.g. if i have an LLM (which produce many keys) and then some other stats `algo/value1`, `algo/value2`, ... etc i want to put through a mechanism, it would be great if you can achieve this by:
```
mechanisms_and_keys = {
'algo_mechanism': (m0, ['algo/']),
'model_mechanism': (m1, [])
}
```
`algo_mechanism` takes all keys which start with `algo/` and `model_mechanism` take all the rest of the keys. |
pfl-research | github_2023 | python | 105 | apple | grananqvist | @@ -0,0 +1,128 @@
+# Copyright © 2023-2024 Apple Inc.
+'''
+Joint mechanism for combining multiple mechanisms into one.
+'''
+
+from typing import Dict, List, Optional, Set, Tuple
+
+from pfl.metrics import Metrics, StringMetricName
+from pfl.stats import MappedVectorStatistics, TrainingStatistics
+
+from .privacy_mechanism import CentrallyApplicablePrivacyMechanism
+
+
+def check_if_partition(full_set: Set[str], partition: List[Set[str]]): | make this private `_check_if_partition` |
pfl-research | github_2023 | python | 100 | apple | ac554 | @@ -167,7 +167,12 @@ def __init__(self):
hvd.local_rank(), hvd.local_size(), hvd.rank(), hvd.size())
self._post_init_check(hvd)
- if torch.cuda.is_available():
+ if torch.cuda.is_available( | Do you need an `else` clause if `"CUDA_VISIBLE_DEVICES" not in os.environ`? |
pfl-research | github_2023 | python | 100 | apple | ac554 | @@ -296,12 +301,42 @@ def __init__(self, seed=None):
def __enter__(self):
if self._seed is not None:
- self._saved_state = torch.random.get_rng_state()
+ self._saved_state = {"cpu": torch.random.get_rng_state()}
+ try:
+ self._saved_state["cuda"] = torch.cuda.get_rng_state_all()
+ except Exception as e:
+ logger.info(f"Failed to get cuda rng state: {e}")
+ try:
+ self._saved_state["mps"] = torch.mps.get_rng_state()
+ except Exception as e:
+ logger.info(f"Failed to get mps rng state: {e}")
torch.random.manual_seed(self._seed)
def __exit__(self, *args):
if self._seed is not None:
- torch.random.set_rng_state(self._saved_state)
+ torch.random.set_rng_state(self._saved_state["cpu"])
+ if "cuda" in self._saved_state:
+ torch.cuda.set_rng_state_all(self._saved_state["cuda"])
+ if "mps" in self._saved_state:
+ torch.mps.set_rng_state(self._saved_state["mps"])
+
+
+class Barrier: | Where is this class used? |
pfl-research | github_2023 | python | 100 | apple | ac554 | @@ -296,12 +301,42 @@ def __init__(self, seed=None):
def __enter__(self):
if self._seed is not None:
- self._saved_state = torch.random.get_rng_state()
+ self._saved_state = {"cpu": torch.random.get_rng_state()}
+ try: | Should we not check if cuda or mps are available rather than having two try-except blocks, with at least one of these blocks generating a "Failed to get ..." message?
E.g. using `if torch.cuda.is_available():` and `if torch.backends.mps.is_available():` |
pfl-research | github_2023 | python | 102 | apple | grananqvist | @@ -160,22 +160,6 @@ def pytorch_model(self) -> torch.nn.Module:
def variable_map(self) -> Dict[str, torch.Tensor]:
return self._variable_map
- @property
- def central_optimizer_variable_map( | This is removing a public interface, it should remain. If you still have this you shouldn't need to make changes in tests no? |
pfl-research | github_2023 | python | 82 | apple | congzheng-song | @@ -0,0 +1,151 @@
+# Copyright © 2024 Apple Inc.
+import math
+import mlx.core as mx
+import mlx.nn as nn
+from mlx.utils import tree_flatten
+from pfl.metrics import Weighted
+
+from model.numpy.layer import positional_encoding
+from model.numpy.metrics import Perplexity
+
+
+class PositionalEncoding(nn.Module):
+ def __init__(self, embedding_size: int, max_sequence_length: int):
+ super().__init__()
+ # Start with underscore so it is not included in the parameters
+ self._pe = mx.array(positional_encoding(max_sequence_length, embedding_size))
+
+ def __call__(self, x):
+ return x + mx.expand_dims(self._pe[:x.shape[1], :], 0)
+
+
+class LMTransformer(nn.Module):
+ def __init__(self, embedding_size: int, hidden_size: int, num_heads: int,
+ feedforward_size: int, num_transformer_layers: int,
+ dropout_rate: float, vocab_size: int,
+ max_sequence_length: int, pad_symbol: int, unk_symbol: int):
+ super().__init__()
+ self._pad_symbol = pad_symbol
+ self._unk_symbol = unk_symbol
+ self._embedding_size = embedding_size
+ self.embedding = nn.Embedding(vocab_size, embedding_size)
+ self.pe = PositionalEncoding(embedding_size, max_sequence_length)
+ self.layers = []
+ for _ in range(num_transformer_layers):
+ l = nn.TransformerEncoderLayer(
+ hidden_size, num_heads, feedforward_size, dropout_rate, norm_first=False
+ )
+ # Need to re-init multi-head attention with bias to match network of PyTorch and TF.
+ l.attention = nn.MultiHeadAttention(hidden_size, num_heads, bias=True)
+ self.layers.append(l)
+
+ self._proj_in = nn.Linear(embedding_size, hidden_size) if embedding_size != hidden_size else nn.Identity()
+ self._proj_out = nn.Linear(hidden_size, embedding_size) if embedding_size != hidden_size else nn.Identity()
+
+ self._init_weights()
+
+ def _init_weights(self):
+ embedding_w = mx.random.uniform(-0.05, 0.05, shape=self.embedding.trainable_parameters()['weight'].shape)
+ self.embedding.update({'weight':embedding_w})
+
+ def num_params(self):
+ nparams = sum(x.size for k, x in tree_flatten(self.trainable_parameters()))
+ return nparams
+
+ def __call__(self, inputs):
+ L = inputs.shape[1]
+ casual_mask = nn.MultiHeadAttention.create_additive_causal_mask(L)
+ x = self.embedding(inputs) * math.sqrt(self._embedding_size)
+ x = self.pe(x)
+ x = self._proj_in(x)
+ for l in self.layers:
+ x = l(x, casual_mask)
+ x = self._proj_out(x)
+ logits = x @ self.embedding.weight.T
+ return logits
+
+ def loss(self, inputs, targets, is_eval=False):
+ self.eval() if is_eval else self.train()
+ logits = self(inputs)
+ mask = (targets != self._pad_symbol).astype(mx.float32)
+ losses = nn.losses.cross_entropy(logits, targets, reduction='none')
+ loss = mx.sum(losses * mask)
+ num_tokens = mx.sum(mask)
+ # Above is equivalent to this but ignoring padding labels for loss. | I am not sure if we need this comment |
pfl-research | github_2023 | python | 80 | apple | congzheng-song | @@ -0,0 +1,158 @@
+# Copyright © 2023-2024 Apple Inc.
+import argparse
+import logging
+import os
+from functools import partial
+from uuid import uuid4
+
+import mlx
+import mlx.core as mx
+import mlx.nn as nn
+import numpy as np
+import torch # type: ignore | `import torch` not needed? |
pfl-research | github_2023 | python | 80 | apple | congzheng-song | @@ -0,0 +1,316 @@
+# Copyright © 2023-2024 Apple Inc.
+import logging
+import os
+import uuid
+from typing import Callable, Dict, Optional, Tuple
+
+import mlx
+import mlx.core as mx
+import mlx.nn as nn
+import mlx.optimizers
+
+from pfl.data.dataset import AbstractDatasetType
+from pfl.exception import CheckpointNotFoundError
+from pfl.hyperparam import NNEvalHyperParams, NNTrainHyperParams
+from pfl.internal.ops import mlx_ops
+from pfl.internal.ops.selector import get_framework_module, set_framework_module
+from pfl.metrics import Metrics, MetricsZero, StringMetricName, Weighted, Zero
+from pfl.model.base import StatefulModel
+from pfl.stats import MappedVectorStatistics
+
+logger = logging.getLogger(name=__name__)
+
+
+class MLXModel(StatefulModel):
+ """
+ :param model:
+ An ``mlx.nn.Module`` representing the MLX model to train.
+ The module must have two methods defined:
+ * loss - `(*user_data) --> loss_value`, where `user_data` is a user's
+ dataset unpacked into the call of `loss`, and `loss_value` is the
+ numeric value to minimize.
+ * metrics - A function `(*user_data) --> <name:metric_value>` where
+ `user_data` is the same as in `loss`, and the return value is a
+ dictionary where `name` is the name of the metric and `metric_value`
+ is an instance of :class:``~pfl.metric.MetricValue`` or a tuple of a
+ :class:``~pfl.metric.MetricValue`` and a function that postprocesses
+ the metric value for each user.
+ The `metrics` method has the signature:
+
+ .. code-block:: python | The example below is still for `torch`, needs to be updated for `mlx` |
pfl-research | github_2023 | python | 80 | apple | congzheng-song | @@ -0,0 +1,316 @@
+# Copyright © 2023-2024 Apple Inc.
+import logging
+import os
+import uuid
+from typing import Callable, Dict, Optional, Tuple
+
+import mlx
+import mlx.core as mx
+import mlx.nn as nn
+import mlx.optimizers
+
+from pfl.data.dataset import AbstractDatasetType
+from pfl.exception import CheckpointNotFoundError
+from pfl.hyperparam import NNEvalHyperParams, NNTrainHyperParams
+from pfl.internal.ops import mlx_ops
+from pfl.internal.ops.selector import get_framework_module, set_framework_module
+from pfl.metrics import Metrics, MetricsZero, StringMetricName, Weighted, Zero
+from pfl.model.base import StatefulModel
+from pfl.stats import MappedVectorStatistics
+
+logger = logging.getLogger(name=__name__)
+
+
+class MLXModel(StatefulModel):
+ """
+ :param model:
+ An ``mlx.nn.Module`` representing the MLX model to train.
+ The module must have two methods defined:
+ * loss - `(*user_data) --> loss_value`, where `user_data` is a user's
+ dataset unpacked into the call of `loss`, and `loss_value` is the
+ numeric value to minimize.
+ * metrics - A function `(*user_data) --> <name:metric_value>` where
+ `user_data` is the same as in `loss`, and the return value is a
+ dictionary where `name` is the name of the metric and `metric_value`
+ is an instance of :class:``~pfl.metric.MetricValue`` or a tuple of a
+ :class:``~pfl.metric.MetricValue`` and a function that postprocesses
+ the metric value for each user.
+ The `metrics` method has the signature:
+
+ .. code-block:: python
+
+ Callable[[*torch.Tensor],
+ Dict[str, Union[
+ MetricValue,
+ Tuple[MetricValue,
+ Callable[[MetricValue], MetricValue]
+ ]
+ ]]
+ ]
+
+ :example:
+
+ .. code-block:: python
+
+ # user data looks like this:
+ # UserDataset(raw_data=[x,y], eval_kwargs={'eval':True})
+ from pfl.metrics import user_average
+ l1loss = torch.nn.L1Loss(reduction='sum')
+
+ def loss(self, x, y, is_eval=False):
+ self.eval() if eval else self.train()
+ return nn.losses.cross_entropy(self(x),
+ y.squeeze(), reduction="mean")
+
+ def metrics(self, x, y, eval=False):
+ self.eval()
+ loss = mx.sum(
+ nn.losses.cross_entropy(self(x), y)).item()
+ num_samples = len(x)
+
+ return {
+ 'per sample loss': Weighted(loss, num_samples),
+ 'per user loss': (Weighted(loss, num_samples),
+ user_average),
+ }
+
+ :param local_optimizer:
+ An ``mlx.optimizers.Optimizer`` instance.
+ The learning rate of this optimizer will be replaced by other training
+ algorithms that uses this model.
+ :param central_optimizer:
+ An ``mlx.optimizers.Optimizer`` instance, which is used to apply the
+ central model updates to the variables.
+ """
+
+ set_framework_module(mlx_ops)
+
+ # Checkpoint constants
+ _MODEL_CKPT_NAME = "weights.npz"
+ _CENTRAL_OPTIMIZER_CKPT_NAME = "central_optimizer.npz"
+
+ def __init__(self, model, local_optimizer, central_optimizer):
+ super().__init__()
+
+ self._model = model
+ self._local_optimizer = local_optimizer
+ self._central_optimizer = central_optimizer
+
+ # Calculate this later dynamically in `evaluate`.
+ self._allows_distributed_evaluation: Optional[bool] = None
+
+ self._original_values: Dict = {}
+ self._model_diff = MappedVectorStatistics()
+
+ # To make the MLX grad function cache unique for each model instance.
+ self._postfix = str(uuid.uuid4())[:8]
+
+ @property
+ def uuid(self):
+ return self._postfix
+
+ @property
+ def allows_distributed_evaluation(self) -> Optional[bool]:
+ return self._allows_distributed_evaluation
+
+ @property
+ def mlx_model(self) -> nn.Module:
+ return self._model
+
+ @property
+ def variable_map(self) -> Dict[str, mx.array]:
+ # Need to calculate this every time because can't store
+ # references. Not updated in-place in MLX.
+ return dict(mlx.utils.tree_flatten(self._model.trainable_parameters()))
+
+ @property
+ def central_optimizer_variable_map(
+ self) -> Optional[Dict[Tuple[str, str], mx.array]]:
+ flat_state = dict(mlx.utils.tree_flatten(
+ self._central_optimizer.state))
+ del flat_state['step']
+ del flat_state['learning_rate']
+ return flat_state
+
+ def _reset_local_optimizer(self, learning_rate):
+ self._local_optimizer.init(self._model.trainable_parameters())
+ self._local_optimizer.state['learning_rate'] = mx.array(
+ learning_rate, dtype=mx.float32)
+
+ def save(self, dir_path: str) -> None:
+ """
+ Save model weights to file. Optimizer state is currently not saved.
+
+ :param dir_path:
+ Directory on disk to store state.
+ """
+ if not os.path.isdir(dir_path):
+ os.makedirs(dir_path)
+ self._model.save_weights(os.path.join(dir_path, self._MODEL_CKPT_NAME))
+ mx.savez(os.path.join(dir_path, self._CENTRAL_OPTIMIZER_CKPT_NAME),
+ **self.central_optimizer_variable_map)
+
+ def load(self, dir_path: str) -> None:
+ """
+ Load model weights from disk, which is the state previously
+ saved with ``save``.
+ Optimizer state is currently not loaded.
+
+ :param dir_path:
+ Path to root directory where weights can be loaded from.
+ Should be same path as used with ``save``.
+ """
+ save_path = os.path.join(dir_path, self._MODEL_CKPT_NAME)
+ if not os.path.exists(save_path):
+ raise CheckpointNotFoundError(save_path)
+ weights_path = os.path.join(dir_path, self._MODEL_CKPT_NAME)
+ self._model.load_weights(weights_path)
+ logger.info(f'Restored model weights from {weights_path}')
+
+ optimizer_path = os.path.join(dir_path,
+ self._CENTRAL_OPTIMIZER_CKPT_NAME)
+ if os.path.exists(optimizer_path):
+ optimizer_state = mx.load(optimizer_path)
+ self._central_optimizer.state.update(optimizer_state)
+ logger.info(
+ f'Restored central optimizer checkpoint from {optimizer_path}.'
+ )
+ else:
+ logger.info(
+ f'No central optimizer checkpoint found at {optimizer_path}.')
+
+ def get_parameters(
+ self,
+ placeholders: Optional[MappedVectorStatistics] = None
+ ) -> MappedVectorStatistics:
+ return MappedVectorStatistics({
+ k: mx.array(v)
+ for k, v in self.variable_map.items()
+ })
+
+ def set_parameters(self, w: MappedVectorStatistics) -> None:
+ self._model.update(mlx.utils.tree_unflatten(list(w.items())))
+
+ def get_model_difference(self,
+ other_parameters: MappedVectorStatistics,
+ clone: bool = False) -> MappedVectorStatistics:
+ model_diff: MappedVectorStatistics = MappedVectorStatistics()
+ for variable_name, variable in self.variable_map.items():
+ model_diff[
+ variable_name] = variable - other_parameters[variable_name]
+ #mx.eval(model_diff._data) | remove? |
pfl-research | github_2023 | python | 80 | apple | congzheng-song | @@ -0,0 +1,93 @@
+# Copyright © 2023-2024 Apple Inc.
+
+import types
+from typing import List, Tuple
+
+import mlx.core as mx
+import mlx.nn as nn
+import numpy as np
+from mlx.utils import tree_flatten
+
+from pfl.metrics import Weighted
+
+
+def maxpool2d(x, pool_size=2, stride=2):
+ batch, height, width, channels = x.shape
+ out_height = (height - pool_size) // stride + 1
+ out_width = (width - pool_size) // stride + 1
+ x = x.reshape(batch, out_height, stride, out_width, stride, channels)
+ # TODO: this is avg pooling, max doesn't work right now:
+ # https://github.com/ml-explore/mlx/issues/1234 | This is fixed in https://github.com/ml-explore/mlx/pull/1237, so we will need to monitor which mlx version has this change, and update here. |
pfl-research | github_2023 | others | 74 | apple | ac554 | @@ -15,6 +15,29 @@
*
+## v0.2.0
+
+### Breaking change!
+
+* `EMMGMMHyperParams` is renamed to `EMGMMHyperParams` (#55)
+
+### New features
+
+* Return local metadata from model training to algorithm (#71).
+
+### Tasks completed
+
+* Update FLAIR preprocessing script to download new dataset from HuggingFace, available at https://huggingface.co/datasets/apple/flair (#72). | Leave out "new", from "download new dataset", since the dataset is not new. |
pfl-research | github_2023 | python | 73 | apple | ac554 | @@ -132,6 +132,20 @@ def add_dataset_arguments(
default=100,
help='Maximum number of images per user')
+ parser.add_argument(
+ '--scheduling_base_weight_multiplier',
+ type=float,
+ default=1.0,
+ help=('Figure 3b in pfl-research paper '
+ 'https://arxiv.org/abs/2404.06430 show adding a' | How does one set the "base weight"? I don't see any arg allowing one to set it. I think this should be parameterised. |
pfl-research | github_2023 | python | 73 | apple | ac554 | @@ -11,12 +12,15 @@
from .common import get_label_mapping, get_multi_hot_targets, get_user_num_images
+logger = logging.getLogger(name=__name__)
+
def make_federated_dataset(
hdf5_path: str,
partition: str,
use_fine_grained_labels: bool,
max_num_user_images: int,
+ scheduling_base_weight_multiplier: int = 1,
numpy_to_tensor: Callable = lambda x: x) -> FederatedDataset:
"""
Create federated dataset from the flair dataset, to use in simulations. | This function now also controls the scheduling of users through a greedy algorithm. This is not alluded to in this docstring. |
pfl-research | github_2023 | python | 73 | apple | ac554 | @@ -37,8 +41,21 @@ def make_federated_dataset(
Federated dataset from the HDF5 data file.
"""
num_classes = len(get_label_mapping(hdf5_path, use_fine_grained_labels))
- user_num_images = get_user_num_images(hdf5_path, partition)
- user_ids = sorted(user_num_images.keys())
+ user_id_to_weight = {
+ k: min(v, max_num_user_images)
+ for k, v in get_user_num_images(hdf5_path, partition).items()
+ }
+ median_datapoints = np.median(list(user_id_to_weight.values()))
+ base_value = scheduling_base_weight_multiplier * median_datapoints | This feels like new functionality which should be abstracted out of this function `make_federated_dataset`. |
pfl-research | github_2023 | python | 73 | apple | ac554 | @@ -266,7 +266,7 @@ def test_3_workers(self, mock_get_ops, federated_dataset_mixture,
@pytest.fixture
def user_id_to_weight(request):
if hasattr(request, 'param') and request.param:
- return {i: i for i in range(100)}
+ return {i: i + 1 for i in range(100)} | I presume the "1" is for base weight? Perhaps a comment, or creating a variable name, `base_weight=1`, would help with legibility. |
pfl-research | github_2023 | python | 73 | apple | congzheng-song | @@ -11,12 +12,15 @@
from .common import get_label_mapping, get_multi_hot_targets, get_user_num_images
+logger = logging.getLogger(name=__name__)
+
def make_federated_dataset(
hdf5_path: str,
partition: str,
use_fine_grained_labels: bool,
max_num_user_images: int,
+ scheduling_base_weight_multiplier: int = 1, | It is a float right? from the argparse above |
pfl-research | github_2023 | python | 71 | apple | ac554 | @@ -72,20 +72,25 @@ def new_local_optimizer(*args, **kwargs):
return mock_local_optimizer
pytorch_model_setup.model.new_local_optimizer = new_local_optimizer
- bridges.sgd_bridge().do_sgd(
- pytorch_model_setup.model, user_dataset,
+ # This is same as bridges.sgd_bridge().do_sgd, but we want
+ # to check the returned metadata as well.
+ from pfl.internal.bridge.pytorch.sgd import _sgd_train_step
+ train_metadata = pytorch_model_setup.model.do_multiple_epochs_of(
+ user_dataset,
NNTrainHyperParams(
local_learning_rate=local_learning_rate,
local_num_epochs=local_num_epochs,
local_batch_size=1,
- grad_accumulation_steps=grad_accumulation_steps))
+ grad_accumulation_steps=grad_accumulation_steps),
+ _sgd_train_step)
# Check if optimizer step is called correct number of times
total_steps = 2 * local_num_epochs | I was confused about the "2" here. It's the `len(user_dataset) / local_batch size`, correct? I think writing it like this would make it much more legible in the tests. |
pfl-research | github_2023 | python | 70 | apple | mdmauthors | @@ -347,6 +338,15 @@ def __call__(self, parser, namespace, values, option_string=None):
'sampled to participate again. This parameter is used in '
'`BandedMatrixFactorizationMechanism`.')
+ argument_parser.add_argument(
+ '--noise_cohort_size',
+ type=int,
+ default=1000,
+ help=('The cohort size to use in calculating noise for DP. ' | Change "in" to "when":
"The cohort size to use when calculating noise for DP" |
pfl-research | github_2023 | python | 70 | apple | mdmauthors | @@ -347,6 +338,15 @@ def __call__(self, parser, namespace, values, option_string=None):
'sampled to participate again. This parameter is used in '
'`BandedMatrixFactorizationMechanism`.')
+ argument_parser.add_argument(
+ '--noise_cohort_size',
+ type=int,
+ default=1000,
+ help=('The cohort size to use in calculating noise for DP. '
+ 'If you run cohort_size=100 but noise_cohort_size=1000, '
+ 'then your results will only be valid if running with ' | Please add description of what happens to standard deviation of noise when `noise_cohort_size` > `cohort_size`. |
pfl-research | github_2023 | python | 34 | apple | monachitnis | @@ -0,0 +1,116 @@
+# Copyright © 2023-2024 Apple Inc.
+from typing import Optional
+
+from lm.argument_parsing import add_lm_arguments
+from peft import LoraConfig, PeftConfig, TaskType | so this `peft` package is compatible with horovod, and makes single GPU, multi-process training work? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.