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
196
apple
czechboy0
@@ -20,6 +20,7 @@ extension TypesFileTranslator { /// - typedResponse: The typed response to declare. /// - Returns: A structure declaration. func translateResponseInTypes( + responseKind: String = "",
```suggestion responseKind: ResponseKind, ``` As below, let's pass in the typesafe variant and not provide a default.
swift-openapi-generator
github_2023
others
196
apple
czechboy0
@@ -22,10 +22,18 @@ extension TypesFileTranslator { /// - header: A response parameter. /// - Returns: A property blueprint. func parseResponseHeaderAsProperty( + responseKind: String = "", + typeName: TypeName, for header: TypedResponseHeader ) throws -> PropertyBlueprint { + let comment: Comment? = { + let subPath: String = typeName.isComponent + ? "headers/\(header.name)" + : "reponses/\(responseKind)/headers/\(header.name)"
```suggestion : "responses/\(responseKind)/headers/\(header.name)" ```
swift-openapi-generator
github_2023
others
196
apple
czechboy0
@@ -42,6 +42,7 @@ extension TypesFileTranslator { let responseStructDecl: Declaration? if typedResponse.isInlined { responseStructDecl = try translateResponseInTypes( + responseKind: responseKind.jsonPathComponent,
```suggestion responseKind: responseKind, ```
swift-openapi-generator
github_2023
others
196
apple
czechboy0
@@ -126,6 +126,10 @@ struct TypeName: Equatable { precondition(components.count >= 1, "Cannot get the parent of a root type") return .init(components: components.dropLast()) } + + var isComponent: Bool { + description.contains("#/components")
I think you could instead check if the first two JSON components are `#` and `components`, that'd at least use the internal `components` storage and be a little more reliable.
swift-openapi-generator
github_2023
others
196
apple
czechboy0
@@ -54,8 +54,18 @@ extension TypesFileTranslator { } let identifier = contentSwiftName(content.content.contentType)
```suggestion let contentType = content.content.contentType let identifier = contentSwiftName(contentType) ```
swift-openapi-generator
github_2023
others
196
apple
czechboy0
@@ -54,8 +54,18 @@ extension TypesFileTranslator { } let identifier = contentSwiftName(content.content.contentType) let associatedType = content.resolvedTypeUsage - let contentCase: Declaration = .enumCase( - .init( + + let subPath: String = { + let contentPath = requestBody.typeUsage.typeName.isComponent ? "content" : "requestBody/content" + return "\(contentPath)/\(content.content.contentType.lowercasedTypeAndSubtypeWithEscape)" + }() + + let contentCase: Declaration = .commentable( + requestBody + .typeUsage + .typeName
```suggestion let typeName = requestBody.typeUsage.typeName let subPath: String = { let contentPath = (typeName.isComponent ? "" : "requestBody/") + "content" return "\(contentPath)/\(contentType.lowercasedTypeAndSubtypeWithEscape)" }() let contentCase: Declaration = .commentable( typeName ```
swift-openapi-generator
github_2023
others
196
apple
czechboy0
@@ -20,6 +20,7 @@ extension TypesFileTranslator { /// - typedResponse: The typed response to declare. /// - Returns: A structure declaration. func translateResponseInTypes( + responseKind: ResponseKind?,
Actually, I wonder - don't we already have this information in `typeName`'s JSON components? Why do we need to pass `responseKind`, especially since it's optional so won't always be there?
swift-openapi-generator
github_2023
others
196
apple
czechboy0
@@ -76,22 +88,45 @@ extension TypesFileTranslator { ) bodyCases.append(contentsOf: inlineTypeDecls) } - let bodyCase: Declaration = .enumCase( - name: identifier, - kind: .nameWithAssociatedValues([ - .init(type: associatedType.fullyQualifiedSwiftName) - ]) + + let subPathForContentCase: String = { + if let responseKind = responseKind?.jsonPathComponent, !typeName.isComponent { + return + "responses/\(responseKind)/content/\(typedContent.content.contentType.lowercasedTypeAndSubtypeWithEscape)" + } else { + return "content/\(typedContent.content.contentType.lowercasedTypeAndSubtypeWithEscape)" + } + }() + let bodyCase: Declaration = .commentable( + typeName.docCommentWithUserDescription(nil, subPath: subPathForContentCase), + .enumCase( + name: identifier, + kind: .nameWithAssociatedValues([ + .init(type: associatedType.fullyQualifiedSwiftName) + ]) + ) ) bodyCases.append(bodyCase) } + let subPathForContent: String = { + if let responseKind = responseKind?.jsonPathComponent, !typeName.isComponent { + return "responses/\(responseKind)/content" + } else { + return "content" + }
There's quite a lot of duplication of prefixes of the comments, could we make it a bit more readable by building it up gradually using some local variables, and concatenating more components as needed? Otherwise it's difficult to read how the different branches of the if/else are different.
swift-openapi-generator
github_2023
others
196
apple
czechboy0
@@ -136,6 +171,7 @@ extension TypesFileTranslator { of: OpenAPI.Response.self ) return try translateResponseInTypes( + responseKind: nil,
Well, this is unfortunate. Now I wonder if we don't already have this info in `typeName`?
swift-openapi-generator
github_2023
others
196
apple
czechboy0
@@ -22,10 +22,22 @@ extension TypesFileTranslator { /// - header: A response parameter. /// - Returns: A property blueprint. func parseResponseHeaderAsProperty( + responseKind: ResponseKind?, + typeName: TypeName, for header: TypedResponseHeader ) throws -> PropertyBlueprint { + let comment: Comment? = { + let subPath: String = { + if let responseKind = responseKind?.jsonPathComponent, !typeName.isComponent { + return "responses/\(responseKind)/headers/\(header.name)" + } else { + return "headers/\(header.name)" + } + }() + return typeName.docCommentWithUserDescription(nil, subPath: subPath) + }()
If the comment is the only reason we have to start passing these other two params, let's move the creation of the comment to the caller of this method, this muddies up the purpose of the method.
swift-openapi-generator
github_2023
others
196
apple
czechboy0
@@ -126,6 +126,14 @@ struct TypeName: Equatable { precondition(components.count >= 1, "Cannot get the parent of a root type") return .init(components: components.dropLast()) } + + /// Returns a bool value indicating whether the list of JSON path components contains "#" first and "components" second. + var isComponent: Bool {
```suggestion var isInComponents: Bool { ```
swift-openapi-generator
github_2023
others
200
apple
FranzBusch
@@ -27,7 +27,7 @@ Below is a table of example changes you might make to an OpenAPI document, and w | Remove a required property | ❌ | ❌ | ❌ | | Rename a schema | ✅ | ❌ | ❌ | -> †: Safe change to make as long as no adopter captured the Swift function signature of the initializer of the generated struct, which gains a new parameter. Rare, but something to be aware of. +> †: Safe change to make as long as no adopter captured the Swift function signature of the initializer of the generated struct, which gains a new parameter. Rare, but something to be aware of. Note that when upgrading the generator to a newer version, we reserve the right to add new defaulted properties to generated structs, so such a change is considered non-breaking. For that reason, avoid capturing the function signature of generated structs.
> function signature of generated structs Do you mean the function signature of generated initialisers?
swift-openapi-generator
github_2023
others
183
apple
czechboy0
@@ -144,10 +144,29 @@ extension OperationDescription { ) } - /// Returns parameters from both the path item level - /// and the operation level. + /// Merged parameters from both the path item level and the operation level. + /// If duplicate parameters exist, only the parameters from the operation level are preserved. + /// + /// - Returns: An array of merged path item and operation level parameters without duplicates. + /// - Throws: When an invalid JSON reference is found. var allParameters: [UnresolvedParameter] { - pathParameters + operation.parameters + get throws { + var mergedParameters = [UnresolvedParameter]() + var uniqueIdentifiers = Set<String>()
```suggestion var mergedParameters: [UnresolvedParameter] = [] var uniqueIdentifiers: Set<String> = [] ``` Style nit: prefer a literal.
swift-openapi-generator
github_2023
others
183
apple
czechboy0
@@ -144,10 +144,29 @@ extension OperationDescription { ) } - /// Returns parameters from both the path item level - /// and the operation level. + /// Merged parameters from both the path item level and the operation level. + /// If duplicate parameters exist, only the parameters from the operation level are preserved. + /// + /// - Returns: An array of merged path item and operation level parameters without duplicates. + /// - Throws: When an invalid JSON reference is found. var allParameters: [UnresolvedParameter] { - pathParameters + operation.parameters + get throws { + var mergedParameters = [UnresolvedParameter]() + var uniqueIdentifiers = Set<String>() + + for parameter in pathParameters + operation.parameters { + let resolvedParameter = try parameter.resolve(in: components) + let identifier = resolvedParameter.name + resolvedParameter.location.rawValue
```suggestion let identifier = resolvedParameter.location.rawValue + ":" + resolvedParameter.name ``` Nit: it reads better if the larger scope (location) goes first, then the name that only needs to be unique within the location, and let's separate it with a character for easier readability when debugging.
swift-openapi-generator
github_2023
others
183
apple
czechboy0
@@ -144,10 +144,29 @@ extension OperationDescription { ) } - /// Returns parameters from both the path item level - /// and the operation level. + /// Merged parameters from both the path item level and the operation level. + /// If duplicate parameters exist, only the parameters from the operation level are preserved. + /// + /// - Returns: An array of merged path item and operation level parameters without duplicates. + /// - Throws: When an invalid JSON reference is found. var allParameters: [UnresolvedParameter] { - pathParameters + operation.parameters + get throws { + var mergedParameters = [UnresolvedParameter]() + var uniqueIdentifiers = Set<String>() + + for parameter in pathParameters + operation.parameters { + let resolvedParameter = try parameter.resolve(in: components) + let identifier = resolvedParameter.name + resolvedParameter.location.rawValue + + guard !uniqueIdentifiers.contains(identifier) + else { continue }
```suggestion guard !uniqueIdentifiers.contains(identifier) else { continue } ``` Style nit.
swift-openapi-generator
github_2023
others
183
apple
czechboy0
@@ -0,0 +1,112 @@ +//===----------------------------------------------------------------------===// +// +// 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 +@testable import _OpenAPIGeneratorCore + +final class Test_OperationDescription: Test_Core { + + func testAllParameters_duplicates_retainOnlyOperationParameters() throws {
I think constructing `OpenAPI.PathItem` is better than creating a document from YAML. See if you can get that to work to initialize an `OperationDescription`.
swift-openapi-generator
github_2023
others
183
apple
czechboy0
@@ -0,0 +1,96 @@ +//===----------------------------------------------------------------------===// +// +// 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 +@testable import _OpenAPIGeneratorCore + +final class Test_OperationDescription: Test_Core { + + func testAllParameters_duplicates_retainOnlyOperationParameters() throws { + let pathLevelParameter = UnresolvedParameter.b( + OpenAPI.Parameter( + name: "test", + context: .query(required: false), + schema: .integer + ) + ) + let operationLevelParameter = UnresolvedParameter.b( + OpenAPI.Parameter( + name: "test", + context: .query(required: false), + schema: .string + ) + ) + + let pathItem = OpenAPI.PathItem( + parameters: [pathLevelParameter], + get: .init( + parameters: [operationLevelParameter], + requestBody: .b(.init(content: [:])), + responses: [:] + ), + vendorExtensions: [:] + ) + let allParameters = try _test(pathItem) + + XCTAssertEqual(allParameters, [operationLevelParameter]) + } + + func testAllParameters_duplicates_keepsDuplicatesFromDifferentLocation() throws { + let pathLevelParameter = UnresolvedParameter.b( + OpenAPI.Parameter( + name: "test", + context: .query(required: false), + schema: .integer + ) + ) + let operationLevelParameter = UnresolvedParameter.b( + OpenAPI.Parameter( + name: "test", + context: .path, + schema: .string + ) + ) + + let pathItem = OpenAPI.PathItem( + parameters: [pathLevelParameter], + get: .init( + parameters: [operationLevelParameter], + requestBody: .b(.init(content: [:])), + responses: [:] + ), + vendorExtensions: [:] + ) + let allParameters = try _test(pathItem) + + XCTAssertEqual(allParameters, [pathLevelParameter, operationLevelParameter]) + } + + private func _test(_ pathItem: OpenAPI.PathItem) throws -> [UnresolvedParameter] { + guard let endpoint = pathItem.endpoints.first else { + XCTFail("Unable to retrieve the path item first endpoint.") + return [] + } + + let operationDescription = OperationDescription( + path: .init(["\test"]),
```suggestion path: .init(["/test"]), ```
swift-openapi-generator
github_2023
others
183
apple
czechboy0
@@ -0,0 +1,96 @@ +//===----------------------------------------------------------------------===// +// +// 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 +@testable import _OpenAPIGeneratorCore + +final class Test_OperationDescription: Test_Core { + + func testAllParameters_duplicates_retainOnlyOperationParameters() throws { + let pathLevelParameter = UnresolvedParameter.b( + OpenAPI.Parameter( + name: "test", + context: .query(required: false), + schema: .integer + ) + ) + let operationLevelParameter = UnresolvedParameter.b( + OpenAPI.Parameter( + name: "test", + context: .query(required: false), + schema: .string + ) + ) + + let pathItem = OpenAPI.PathItem( + parameters: [pathLevelParameter], + get: .init( + parameters: [operationLevelParameter], + requestBody: .b(.init(content: [:])), + responses: [:] + ), + vendorExtensions: [:] + ) + let allParameters = try _test(pathItem) + + XCTAssertEqual(allParameters, [operationLevelParameter]) + }
Can you please add one more test that verifies the correct ordering? Could be: - path item level: A, B - operation level: B, C - expected result: A, B, C
swift-openapi-generator
github_2023
others
179
apple
glbrntt
@@ -60,28 +60,42 @@ class Test_isSchemaSupported: XCTestCase { ) ), - // allOf with two schemas + // allOf with many schemas .all(of: [ .object(properties: [ "Foo": .string ]), .reference(.component(named: "MyObj")), + .string, + .array(items: .string), ]), - // oneOf with two schemas + // oneOf with a discriminator with two objectish schemas
The following code doesn't have a discriminator... is it meant to or is the comment wrong?
swift-openapi-generator
github_2023
others
179
apple
simonjbeaumont
@@ -1223,6 +1251,13 @@ extension SnippetBasedReferenceTests { line: UInt = #line ) throws { let translator = try makeTypesTranslator(componentsYAML: componentsYAML) + let schemas = translator.components.schemas + for (key, schema) in schemas { + XCTAssertTrue( + try translator.isSchemaSupported(schema) == .supported, + "Schema \(schema.prettyDescription) for key \(key) is not supported" + ) + }
Is this a preflight check of the test, rather than the test itself? What would be the behaviour if we removed this; wouldn't it just throw in `translator.translateSchemas`? IMO, that would be fine, because we can keep the logic simpler here and have tests that `XCTAssertThrowsError` for things we don't support today, if we'd like to keep track of them.
swift-openapi-generator
github_2023
others
179
apple
simonjbeaumont
@@ -142,12 +142,12 @@ Supported features are always provided on _both_ client and server. - [x] enum - [x] type - [x] allOf - - a wrapper struct is generated and children must be object schemas + - a wrapper struct is generated, children can be any schema - [x] oneOf - - if a discriminator is specified (recommended), children must be object schemas + - if a discriminator is specified, each child must be a reference to an object schema
> When using the discriminator, inline schemas will not be considered. Just want to check that we're not being over-strict here. We shouldn't consider inline schemas, sure; but hopefully we're not failing if we find any?
swift-openapi-generator
github_2023
others
179
apple
simonjbeaumont
@@ -256,8 +242,9 @@ extension FileTranslator { /// - Parameter schema: A schema to check. func isRefToObjectishSchemaAndSupported(_ schema: JSONSchema) throws -> IsSchemaSupportedResult { switch schema.value { - case .reference: - return try isObjectishSchemaAndSupported(schema) + case let .reference(ref, _): + let referencedSchema = try components.lookup(ref) + return try isObjectishSchemaAndSupported(referencedSchema)
This lookup isn't required IIUC, as AFAICT `isObjectishSchemaAndSupported` calls `isSchemaSupported` which also does the lookup, in the case of a `.reference`.
swift-openapi-generator
github_2023
others
178
apple
simonjbeaumont
@@ -0,0 +1,69 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +/// Runs validation steps on the incoming OpenAPI document. +/// - Parameters: +/// - doc: The OpenAPI document to validate. +/// - config: The generator config. +/// - Throws: An error if a fatal issue is found. +func validateDoc(_ doc: ParsedOpenAPIRepresentation, config: Config) throws -> [Diagnostic] { + guard config.featureFlags.contains(.strictOpenAPIValidation) else { + return [] + } + // Run OpenAPIKit's built-in validation. + // Pass `false` to `strict`, however, because we don't + // want to turn schema loading warnings into errors. + // We already propagate the warnings to the generator's + // diagnostics, so they get surfaced to the user. + // But the warnings are often too strict and should not + // block the generator from running. + // Validation errors continue to be fatal, such as + // structural issues, like non-unique operationIds, etc. + let warnings = try doc.validate(strict: false)
Maybe we can provide an even more consistent experience by catching the errors from this call and emitting fatal `.error` diagnostics?
swift-openapi-generator
github_2023
others
176
apple
simonjbeaumont
@@ -20,15 +20,23 @@ extension FileTranslator { /// - typeName: The name of the type to give to the declared enum. /// - openAPIDescription: A user-specified description from the OpenAPI /// document. + /// - isNullable: Whether the enum schema is nullable. /// - allowedValues: The enumerated allowed values. func translateStringEnum( typeName: TypeName, userDescription: String?, + isNullable: Bool, allowedValues: [AnyCodable] ) throws -> Declaration { let rawValues = try allowedValues.map(\.value) .map { anyValue in + // In nullable enum schemas, empty strings are parsed as Void. + // This is unlikely to be fixed, so handling that case here. + // https://github.com/apple/swift-openapi-generator/issues/118 + if isNullable && anyValue is Void { + return "" + }
Do we even need the `isNullable` parameter? i.e. would it be safe to just test if `anyValue is Void` unilaterally?
swift-openapi-generator
github_2023
others
171
apple
glbrntt
@@ -189,6 +192,14 @@ extension FileTranslator { .content .contentType .codingStrategy + switch parameter.location { + case .query, .cookie: + style = .form + explode = true + case .path, .header: + style = .simple + explode = false
These are just the defaults from https://swagger.io/specification/#parameter-object, right? Where we implement specs in our other projects we tend to drop in references to them so that if we return to the code later we can see why a decision was made (i.e. we are following the spec vs. just doing what we think is right).
swift-openapi-generator
github_2023
others
173
apple
glbrntt
@@ -17,103 +17,106 @@ import OpenAPIKit30 /// /// Represents the serialization method of the payload and affects /// the generated serialization code. -enum ContentType: Hashable { +struct ContentType: Hashable { + + /// The category of a content type. + enum Category: Hashable { + + /// A content type for JSON. + case json + + /// A content type for any plain text. + case text + + /// A content type for raw binary data. + case binary + + /// Creates a category from the provided raw string. + /// + /// First checks if the provided content type is a JSON, then text, + /// and uses binary if none of the two match. + /// - Parameter rawValue: A string with the content type to create. + init(rawValue: String) { + // https://json-schema.org/draft/2020-12/json-schema-core.html#section-4.2 + if rawValue == "application/json" || rawValue.hasSuffix("+json") { + self = .json + return + } + if rawValue.hasPrefix("text/") { + self = .text + return + } + self = .binary + } - /// A content type for JSON. - case json(String) + /// The coding strategy appropriate for this content type. + var codingStrategy: CodingStrategy { + switch self { + case .json: + return .json + case .text: + return .text + case .binary: + return .binary + } + } + } - /// A content type for any plain text. - case text(String) + /// The underlying raw content type string. + private var rawValue: String
Is this ever modified? Wondering if it can be `private let` so that the `category` can be `internal let`?
swift-openapi-generator
github_2023
others
173
apple
glbrntt
@@ -17,103 +17,106 @@ import OpenAPIKit30 /// /// Represents the serialization method of the payload and affects /// the generated serialization code. -enum ContentType: Hashable { +struct ContentType: Hashable { + + /// The category of a content type. + enum Category: Hashable { + + /// A content type for JSON. + case json + + /// A content type for any plain text. + case text + + /// A content type for raw binary data. + case binary + + /// Creates a category from the provided raw string. + /// + /// First checks if the provided content type is a JSON, then text, + /// and uses binary if none of the two match. + /// - Parameter rawValue: A string with the content type to create. + init(rawValue: String) { + // https://json-schema.org/draft/2020-12/json-schema-core.html#section-4.2 + if rawValue == "application/json" || rawValue.hasSuffix("+json") { + self = .json + return + } + if rawValue.hasPrefix("text/") { + self = .text + return + } + self = .binary
Why can we bucket everything else as `binary`? I don't think e.g. `xml` falls in to any of these categories.
swift-openapi-generator
github_2023
others
146
apple
simonjbeaumont
@@ -664,6 +664,38 @@ struct SwitchDescription: Equatable, Codable { var cases: [SwitchCaseDescription] } +/// A description of an if condition and the corresponding code block. +/// +/// For example: in `if foo { bar }`, the condition pair represents +/// `foo` + `bar`. +struct IfConditionPair: Equatable, Codable {
Does seem a bit of a strange one. Could it be folded _into_ the `IfStatementDescription`—e.g. could `IfStatementDescription.IfConditionPair` just be replaced with a tuple of `(Expression, [CodeBlock])`. If you do keep it here, it seems the term "branch" might be good—which you used as the property name in the below type: `IfStatementDescription.branches`.
swift-openapi-generator
github_2023
others
146
apple
simonjbeaumont
@@ -256,7 +256,7 @@ public struct Client: APIProtocol { try converter.setHeaderFieldAsText( in: &request.headerFields, name: "accept", - value: "application/json" + value: "application/json, text/plain, application/octet-stream"
I realise this might change later, but, to confirm, the plan here is to send _all_ content types the client _knows_ about—that is, all those in the OpenAPI doc—in the accept header? Looking at the OAS, it appears there's some specified precedence when there's overlap: > REQUIRED. The content of the request body. The key is a media type or [media type range](https://tools.ietf.org/html/rfc7231#appendix-D) and the value describes it. For requests that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/*
swift-openapi-generator
github_2023
others
146
apple
simonjbeaumont
@@ -113,6 +113,31 @@ paths: $ref: '#/components/schemas/Pet' '400': $ref: '#/components/responses/ErrorBadRequest' + /pets/stats: + get: + operationId: getStats + responses: + '200': + description: A successful response. + content: + application/json: + schema: + $ref: '#/components/schemas/PetStats' + text/plain: {} + application/octet-stream: {} + post: + operationId: postStats + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PetStats' + text/plain: {} + application/octet-stream: {}
Is the handling of content types with wildcards out of scope at this time?
swift-openapi-generator
github_2023
others
146
apple
simonjbeaumont
@@ -1202,6 +1248,23 @@ extension Expression { ) } + /// Returns an if statement, with optional else if's and an else + /// statement attached. + /// - Parameters: + /// - branches: The conditional branches. + /// - elseBody: The body of an else block. + static func ifStatement( + branches: [IfConditionPair], + elseBody: [CodeBlock]? = nil + ) -> Self {
Could the shape of this API be improved to encourage correctness? I.e. it's not possible to have just an `else` branch. > `/// Returns an if statement, with optional else if's and an else statement attached.` These docs make complete sense, which implies to me three parameters are needed: - The first if branch - Optional list of else-if branches - Optional else branch
swift-openapi-generator
github_2023
others
146
apple
simonjbeaumont
@@ -61,6 +61,78 @@ extension FileTranslator { return .init(content: content, typeUsage: associatedType) } + /// Extract the supported content types. + /// - Parameters: + /// - map: The content map from the OpenAPI document. + /// - excludeBinary: A Boolean value controlling whether binary content + /// type should be skipped, for example used when encoding headers. + /// - parent: The parent type of the chosen typed schema. + /// - Returns: The supported content type + schema + type names. + func supportedTypedContents( + _ map: OpenAPI.Content.Map, + excludeBinary: Bool = false, + inParent parent: TypeName + ) throws -> [TypedSchemaContent] { + let contents = supportedContents( + map, + excludeBinary: excludeBinary, + foundIn: parent.description + ) + return try contents.compactMap { content in + guard + try validateSchemaIsSupported( + content.schema, + foundIn: parent.description + ) + else { + return nil + }
IIUC there are two dimensions by which a value in a content map might be skipped: 1. The content map key isn't something we support. 2. The schema isn't supported. Are we emitting clear diagnostics for each? Specifically, I can see we do (1) in the functions below, but does `validateSchemaIsSupported` emit a diagnostic too?
swift-openapi-generator
github_2023
others
146
apple
simonjbeaumont
@@ -72,6 +144,7 @@ extension FileTranslator { /// - map: The content map from the OpenAPI document. /// - excludeBinary: A Boolean value controlling whether binary content /// type should be skipped, for example used when encoding headers. + /// - foundIn: The location where this content is parsed. /// - Returns: the detected content type + schema, nil if no supported /// schema found or if empty. func bestSingleContent(
Just popping this here, while I found it, on the OAS spec, but we can break this out into a separate discussion. The encoding can be specified by a user using an `encoding` field in their document[^1]. I don't think we support that today (correct me if I'm wrong)—are we tracking it? The reason I drop it here is because, IIUC, it specifies what the default rules are, when this isn't provided: > The Content-Type for encoding a specific property. Default value depends on the property type: for string with format being binary – application/octet-stream; for other primitive types – text/plain; for object - application/json; for array – the default is defined based on the inner type. The value can be a specific media type (e.g. application/json), a wildcard media type (e.g. image/*), or a comma-separated list of the two types. I'm not convinced we're following that precisely—again this would be a different issue, separate from this PR. [^1]: https://spec.openapis.org/oas/v3.0.3#encoding-object
swift-openapi-generator
github_2023
others
146
apple
simonjbeaumont
@@ -123,4 +196,62 @@ extension FileTranslator { return nil } } + + /// Returns a wrapped version of the provided content if supported, returns + /// nil otherwise. + /// + /// Priority of checking for known MIME types: + /// 1. JSON + /// 2. text + /// 3. binary + /// + /// - Parameters: + /// - contentKey: The content key from the OpenAPI document. + /// - contentValue: The content value from the OpenAPI document. + /// - excludeBinary: A Boolean value controlling whether binary content + /// type should be skipped, for example used when encoding headers. + /// - foundIn: The location where this content is parsed. + /// - Returns: The detected content type + schema, nil if unsupported. + func parseContentIfSupported( + contentKey: OpenAPI.ContentType, + contentValue: OpenAPI.Content, + excludeBinary: Bool = false, + foundIn: String + ) -> SchemaContent? { + if contentKey.isJSON, + let contentType = ContentType(contentKey.typeAndSubtype) + { + diagnostics.emitUnsupportedIfNotNil( + contentValue.encoding, + "Custom encoding for JSON content", + foundIn: "\(foundIn), content \(contentKey.rawValue)" + )
The `encoding` property in the `content` map should only be used in more specific cases[^1]. Should we be more precise about when we consider it? > The encoding object SHALL only apply to requestBody objects when the media type is multipart or application/x-www-form-urlencoded. [^1]: https://spec.openapis.org/oas/v3.0.3#mediaTypeObject
swift-openapi-generator
github_2023
others
146
apple
simonjbeaumont
@@ -95,12 +95,11 @@ extension FileTranslator { isInlined = true } - guard - let content = try bestSingleTypedContent( - request.content, - inParent: typeName - ) - else { + let contents = try supportedTypedContents( + request.content, + inParent: typeName + ) + if contents.isEmpty { return nil }
Took me a while to grok this, because I was expecting the feature flag switch to be here, but then realised that you fallback to the old behaviour in the _new_ function, based on the feature flag. What was the reasoning behind this? Could we move it here, which would also allow the new function, that does multiple content types, to be simplified to always do the new thing?
swift-openapi-generator
github_2023
others
146
apple
simonjbeaumont
@@ -616,7 +616,79 @@ final class SnippetBasedReferenceTests: XCTestCase { ) } - func testComponentsResponsesResponseWithOptionalHeader() throws { + func testComponentsResponsesResponseMultipleContentTypes() throws {
Thanks for adding these tests!
swift-openapi-generator
github_2023
others
146
apple
gjcairo
@@ -342,6 +342,120 @@ final class Test_Client: XCTestCase { } } + func testGetStats_200_json() async throws { + transport = .init { request, baseURL, operationID in + XCTAssertEqual(operationID, "getStats") + XCTAssertEqual(request.path, "/pets/stats") + XCTAssertEqual(request.method, .get) + XCTAssertNil(request.body) + return .init( + statusCode: 200, + headers: [ + .init(name: "content-type", value: "application/json") + ], + encodedBody: #""" + { + "count" : 1 + } + """# + ) + } + let response = try await client.getStats(.init()) + guard case let .ok(value) = response else { + XCTFail("Unexpected response: \(response)") + return + } + switch value.body { + case .json(let stats): + XCTAssertEqual(stats, .init(count: 1)) + default: + XCTFail("Unexpected content type") + } + } + + func testGetStats_200_default_json() async throws { + transport = .init { request, baseURL, operationID in + XCTAssertEqual(operationID, "getStats") + XCTAssertEqual(request.path, "/pets/stats") + XCTAssertEqual(request.method, .get) + XCTAssertNil(request.body) + return .init( + statusCode: 200, + headers: [], + encodedBody: #""" + { + "count" : 1 + } + """# + ) + } + let response = try await client.getStats(.init()) + guard case let .ok(value) = response else { + XCTFail("Unexpected response: \(response)") + return + } + switch value.body { + case .json(let stats): + XCTAssertEqual(stats, .init(count: 1)) + default: + XCTFail("Unexpected content type") + } + } + + func testGetStats_200_unexpectedContentType() async throws { + transport = .init { request, baseURL, operationID in + XCTAssertEqual(operationID, "getStats") + XCTAssertEqual(request.path, "/pets/stats") + XCTAssertEqual(request.method, .get) + XCTAssertNil(request.body) + return .init( + statusCode: 200, + headers: [ + .init(name: "content-type", value: "foo/bar") + ], + encodedBody: #""" + count_is_1 + """# + ) + } + do { + _ = try await client.getStats(.init()) + XCTFail("Should have thrown an error") + } catch {}
Do we want to assert anything about the error being thrown?
swift-openapi-generator
github_2023
others
146
apple
gjcairo
@@ -16,23 +16,18 @@ import OpenAPIKit30 extension TypesFileTranslator { /// Returns a list of declarations that define a Swift type for - /// the request body content and type name. + /// the request body content. /// - Parameters: - /// - typeName: The type name to declare the request body type under. - /// - requestBody: The request body to declare. - /// - Returns: A list of declarations; empty list if the request body is + /// - content: The typed schema content to declare. + /// - Returns: A list of declarations; empty list if the content is /// unsupported. func translateRequestBodyContentInTypes( - requestBody: TypedRequestBody + _ content: TypedSchemaContent ) throws -> [Declaration] { - let content = requestBody.content let decl = try translateSchema( typeName: content.resolvedTypeUsage.typeName, schema: content.content.schema, - overrides: .init( - isOptional: !requestBody.request.required, - userDescription: requestBody.request.description - ) + overrides: .none
What's the context behind removing this override?
swift-openapi-generator
github_2023
others
169
apple
simonjbeaumont
@@ -54,12 +54,15 @@ struct TextBasedRenderer: RendererProtocol { prefix = "// MARK:" commentString = string } - return commentString.transformingLines { line in - if line.isEmpty { - return prefix + return + commentString + .replacingOccurrences(of: "\r", with: "\n")
In the presence of `\r\n` this produces two newlines but I think it should just be one. Presumably the goal of this patch is to handle both newline conventions: `LF` or `CR+LF`. IIUC, the `\r` is a carriage return. Does `String` have any utilities for splitting on "newlines" which might just handle this for us internally?
swift-openapi-generator
github_2023
others
169
apple
simonjbeaumont
@@ -721,7 +723,7 @@ fileprivate extension String { /// Returns an array of strings, where each string represents one line /// in the current string. func asLines() -> [String] { - split(separator: "\n", omittingEmptySubsequences: false) + split(omittingEmptySubsequences: false, whereSeparator: \.isNewline)
Should we be omitting empty sequences? Realise this is scope creep because this was probably the behaviour before but I think that we should be preserving the number of newlines in comments. If you consider that a comment may be interpreted as markdown, you need two newlines to start a new block.
swift-openapi-generator
github_2023
others
164
apple
simonjbeaumont
@@ -13,6 +13,46 @@ //===----------------------------------------------------------------------===// import OpenAPIKit30 +/// A result of checking whether a schema is supported. +enum IsSchemaSupportedResult: Equatable { + + /// The schema is supported and can be generated. + case supported + + /// The reason a schema is unsupported. + enum UnsupportedReason: Equatable, CustomStringConvertible { + + /// Describes when no subschemas are found in an allOf, oneOf, or anyOf. + case noSubschemas + + /// Describes when the schema is not object-ish, in other words isn't + /// an object, a ref, or an allOf. + case notObjectish
But this is a valid schema that isn't "object-ish", right? ```yaml schema: type: string ``` Is this for when it's supposed to be "object-ish" but isn't?
swift-openapi-generator
github_2023
others
161
apple
denil-ct
@@ -29,6 +29,7 @@ If you have any questions, tag [Honza Dvorsky](https://github.com/czechboy0) or - Awaiting Review - In Review - Ready for Implementation +- Merged behind a Feature Flag
Mentioning the flag name in the state, would also be a good addition.
swift-openapi-generator
github_2023
others
162
apple
simonjbeaumont
@@ -125,31 +125,33 @@ func makeGeneratorPipeline( postTransitionHooks: [ { doc in - // Run OpenAPIKit's built-in validation. - try doc.validate() - - // Validate that the document is dereferenceable, which - // catches reference cycles, which we don't yet support. - _ = try doc.locallyDereferenced() - - // Also explicitly dereference the parts of components - // that the generator uses. `locallyDereferenced()` above - // only dereferences paths/operations, but not components. - let components = doc.components - try components.schemas.forEach { schema in - _ = try schema.value.dereferenced(in: components) - } - try components.parameters.forEach { schema in - _ = try schema.value.dereferenced(in: components) - } - try components.headers.forEach { schema in - _ = try schema.value.dereferenced(in: components) - } - try components.requestBodies.forEach { schema in - _ = try schema.value.dereferenced(in: components) - } - try components.responses.forEach { schema in - _ = try schema.value.dereferenced(in: components) + if config.featureFlags.contains(.strictOpenAPIValidation) { + // Run OpenAPIKit's built-in validation. + try doc.validate() + + // Validate that the document is dereferenceable, which + // catches reference cycles, which we don't yet support. + _ = try doc.locallyDereferenced() + + // Also explicitly dereference the parts of components + // that the generator uses. `locallyDereferenced()` above + // only dereferences paths/operations, but not components. + let components = doc.components + try components.schemas.forEach { schema in + _ = try schema.value.dereferenced(in: components) + } + try components.parameters.forEach { schema in + _ = try schema.value.dereferenced(in: components) + } + try components.headers.forEach { schema in + _ = try schema.value.dereferenced(in: components) + } + try components.requestBodies.forEach { schema in + _ = try schema.value.dereferenced(in: components) + } + try components.responses.forEach { schema in + _ = try schema.value.dereferenced(in: components) + }
Do we need to be more selective here about what's gated and what isn't? Didn't we add these originally to reject documents with reference cycles and/or external references that we cannot support, and would otherwise fail to generate anyway? If that's the case then shouldn't we keep the `locallyDereferened()` and all the `defererenced(in:)` checks, as this won't be a regression in what we can handle, it will just fail earlier, and with a clearer reason. I can entertain the idea that `doc.validate()` could be causing regressions, but only because we treat it as fatal. Maybe the better change here would be for us to call that and emit a warning diagnostic if it fails, rather than letting it throw?
swift-openapi-generator
github_2023
others
95
apple
michalsrutek
@@ -0,0 +1,50 @@ +# SOAR-0001 + +Encoding for Property Names + +## Overview + +- Proposal: SOAR-0001 +- Author(s): [Denil](https://github.com/denil-ct) +- Status: **Awaiting Review** +- Issue: https://github.com/apple/swift-openapi-generator/issues/21 +- Implementation: + - https://github.com/apple/swift-openapi-generator/pull/89 +- Affected components: + - generator + +### Introduction + +The goal of this proposal is to improve the way we handle unsupported characters in property names when generating code from specs. Currently, we use a block list approach, replacing offending characters with `_` which can cause name conflicts. By encoding the offending character we create unique and valid property names. This will avoid name collisions and ensure consistent code generation. + +### Motivation + +The current approach for handling unsupported characters in property names is not robust and can lead to unexpected and undesirable outcomes. For example, if there are two properties, `a_b` and `a b`, with the current implementation, this will result in the same generated property `a_b` for both, which would create a conflict. It can also result in loss of information or meaning from the original specification. Therefore, we need a better solution that can handle any unsupported character in a consistent and reliable way, without compromising the quality and functionality of the code. + +### Proposed solution + +The proposed solution to the problem is to use a mix of replacement words and hex encoding for any unsupported character in property names. We replace characters in the printable ASCII range (20-7E) with a wordified representation inspired by the HTML entity names [here](https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references). Hex encoding is a simple and standard way of representing any character as a sequence of hexadecimal digits. For example, the asterisk (*) character is encoded as 2A, the space ( ) character is encoded as 20, and the slash (/) character is encoded as 2F. Hex encoding also has the added benefit of not introducing any additional special characters. +In addition to this, we will be prefixing the hex codes with an `x` to indicate they are hex values. There are also delimiters added in the form of the underscore character to indicate a possible replacement. + +Some examples, + +yaml | swift +-- | -- +a b | a_space_b +a*b | a_ast_b +ab_ | ab_
Looking at the example mapping yaml | swift -- | -- a b | a_space_b ab_ | ab_ it follows that there would be a collision for yaml | swift -- | -- a b | a_space_b a_space_b | a_space_b which needs to be addressed somehow.
swift-openapi-generator
github_2023
others
147
apple
czechboy0
@@ -55,10 +55,10 @@ extension FileTranslator { switch type { case .allOf: // AllOf uses all required properties. - propertyType = rawPropertyType + propertyType = rawPropertyType.withOptional(false) case .anyOf: // AnyOf uses all optional properties. - propertyType = rawPropertyType.asOptional + propertyType = rawPropertyType.withOptional(true)
I like it, it feels right - `allOf` is all subschemas being required, `anyOf` is all subschemas being optional.
swift-openapi-generator
github_2023
others
150
apple
czechboy0
@@ -107,6 +107,13 @@ paths: application/json: schema: $ref: '#/components/schemas/CodeError' + X-Extra-Arguments2: + required: true + description: "A description here." + content: + application/json: + schema: + $ref: '#/components/schemas/CodeError'
I don't think we need this change to the integration test project, `listPets/My-Response-UUID` already is an example of a required response header.
swift-openapi-generator
github_2023
others
150
apple
czechboy0
@@ -519,7 +519,7 @@ final class SnippetBasedReferenceTests: XCTestCase { ) } - func testComponentsResponsesResponseWithHeader() throws { + func testComponentsResponsesResponseWithOptionalHeader() throws {
These changes are great, covering both in snippet tests gives us the confidence it works correctly without having to expand the file-based reference test.
swift-openapi-generator
github_2023
others
150
apple
czechboy0
@@ -192,6 +193,7 @@ final class Test_Client: XCTestCase { return } XCTAssertEqual(value.headers.X_Extra_Arguments, .init(code: 1)) + XCTAssertEqual(value.headers.X_Extra_Arguments2, .init(code: 9999))
Let's undo these changes, as per the comment in `petstore.yaml`.
swift-openapi-generator
github_2023
others
150
apple
czechboy0
@@ -166,7 +166,7 @@ final class Test_Server: XCTestCase { XCTAssertEqual( response.headerFields, [ - .init(name: "X-Extra-Arguments", value: #"{"code":1}"#), + .init(name: "X-Extra-Arguments2", value: #"{"code":1}"#),
Let's undo these changes, as per the comment in `petstore.yaml`.
swift-openapi-generator
github_2023
others
150
apple
czechboy0
@@ -985,12 +985,18 @@ public enum Operations { public struct Created: Sendable, Equatable, Hashable { public struct Headers: Sendable, Equatable, Hashable { public var X_Extra_Arguments: Components.Schemas.CodeError? + public var X_Extra_Arguments2: Components.Schemas.CodeError /// Creates a new `Headers`. /// /// - Parameters: /// - X_Extra_Arguments: - public init(X_Extra_Arguments: Components.Schemas.CodeError? = nil) { + /// - X_Extra_Arguments2: + public init( + X_Extra_Arguments: Components.Schemas.CodeError? = nil, + X_Extra_Arguments2: Components.Schemas.CodeError + ) { self.X_Extra_Arguments = X_Extra_Arguments + self.X_Extra_Arguments2 = X_Extra_Arguments2
Let's undo these changes, as per the comment in `petstore.yaml`.
swift-openapi-generator
github_2023
others
150
apple
czechboy0
@@ -220,6 +220,11 @@ fileprivate extension UniversalServer where APIHandler: APIProtocol { name: "X-Extra-Arguments", value: value.headers.X_Extra_Arguments ) + try converter.setHeaderFieldAsJSON( + in: &response.headerFields, + name: "X-Extra-Arguments2", + value: value.headers.X_Extra_Arguments2 + )
Let's undo these changes, as per the comment in `petstore.yaml`.
swift-openapi-generator
github_2023
others
150
apple
czechboy0
@@ -174,6 +174,11 @@ public struct Client: APIProtocol { in: response.headerFields, name: "X-Extra-Arguments", as: Components.Schemas.CodeError.self + ), + X_Extra_Arguments2: try converter.getRequiredHeaderFieldAsJSON( + in: response.headerFields, + name: "X-Extra-Arguments2", + as: Components.Schemas.CodeError.self
Let's undo these changes, as per the comment in `petstore.yaml`.
swift-openapi-generator
github_2023
others
150
apple
simonjbeaumont
@@ -80,6 +80,21 @@ struct StructBlueprint { var properties: [PropertyBlueprint] } +extension StructBlueprint { + + /// A Boolean value indicating whether the struct can be initialized using + /// an empty initializer. + /// + /// For example, when all the properties of the struct have a default value, + /// the struct can be initialized using `Foo()`. This is important for + /// other types referencing this type. + var hasEmptyInit: Bool { + // If at least one property requires an explicit value, this struct + // cannot have an empty initializer. + !properties.contains(where: { $0.defaultValue == nil })
Nit: Thin it would read nicer to invert this check: ```suggestion properties.allSatisfy { $0.defaultValue != nil } ```
swift-openapi-generator
github_2023
others
150
apple
simonjbeaumont
@@ -36,20 +36,21 @@ extension TypesFileTranslator { let headerProperties: [PropertyBlueprint] = try headers.map { header in try parseResponseHeaderAsProperty(for: header) } + let headersStructBlueprint: StructBlueprint = .init(
Nit: This syntax makes the reader ask "is there some kind of upcasting going on here?", could we replace with: ```suggestion let headersStructBlueprint = StructBlueprint( ```
swift-openapi-generator
github_2023
others
157
apple
gjcairo
@@ -11,127 +11,10 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -import OpenAPIRuntime -import Foundation - -enum TestError: Swift.Error, LocalizedError, CustomStringConvertible { - case noHandlerFound(method: HTTPMethod, path: [RouterPathComponent]) - case invalidURLString(String) - case unexpectedValue(Any) - case unexpectedMissingRequestBody - - var description: String { - switch self { - case .noHandlerFound(let method, let path): - return "No handler found for method \(method.name) and path \(path.stringPath)" - case .invalidURLString(let string): - return "Invalid URL string: \(string)" - case .unexpectedValue(let value): - return "Unexpected value: \(value)" - case .unexpectedMissingRequestBody: - return "Unexpected missing request body" - } - } - - var errorDescription: String? { - description - } -} - -extension Date { - static var test: Date { - Date(timeIntervalSince1970: 1_674_036_251) - } - - static var testString: String { - "2023-01-18T10:04:11Z" - } -} - -extension Array where Element == RouterPathComponent { - var stringPath: String { - map(\.description).joined(separator: "/") - } -} - -extension Response { - init( - statusCode: Int, - headers: [HeaderField] = [], - encodedBody: String - ) { - self.init( - statusCode: statusCode, - headerFields: headers, - body: Data(encodedBody.utf8) - ) - } - - static var listPetsSuccess: Self { - .init( - statusCode: 200, - headers: [ - .init(name: "content-type", value: "application/json") - ], - encodedBody: #""" - [ - { - "id": 1, - "name": "Fluffz" - } - ] - """# - ) - } -} +import XCTest extension Operations.listPets.Output { static var success: Self { .ok(.init(headers: .init(My_Response_UUID: "abcd"), body: .json([]))) } }
Potentially naive question but why wouldn't this belong in the common target too?
swift-openapi-generator
github_2023
others
98
apple
Kyle-Ye
@@ -0,0 +1,161 @@ +//===----------------------------------------------------------------------===// +// +// 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 PackagePlugin +import Foundation + +@main +struct SwiftOpenAPIGeneratorPlugin { + enum Error: Swift.Error, CustomStringConvertible, LocalizedError {
This logic is duplicated. Maybe we could move such code to a single file. And make soft link to it so that both plugins can depend on it.
swift-openapi-generator
github_2023
others
98
apple
denil-ct
@@ -0,0 +1,45 @@ +import PackagePlugin +import Foundation + +enum PluginError: Swift.Error, CustomStringConvertible, LocalizedError { + case incompatibleTarget(targetName: String) + case badArguments(arguments: [String]) + // The description is only suitable for Xcode, as it's only thrown in Xcode plugins. + case noTargetsMatchingTargetName(targetName: String) + // The description is not suitable for Xcode, as it's not thrown in Xcode plugins. + case tooManyTargetsMatchingTargetName(targetNames: [String]) + case noConfigFound(targetName: String) + case noDocumentFound(targetName: String) + case multiConfigFound(targetName: String, files: [Path]) + case multiDocumentFound(targetName: String, files: [Path])
```suggestion case multipleConfigsFound(targetName: String, files: [Path]) case multipleDocumentsFound(targetName: String, files: [Path]) ``` A bit clearer on the meaning.
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -27,6 +27,7 @@ let package = Package( products: [ .executable(name: "swift-openapi-generator", targets: ["swift-openapi-generator"]), .plugin(name: "OpenAPIGenerator", targets: ["OpenAPIGenerator"]), + .plugin(name: "OpenAPIGeneratorCommandPlugin", targets: ["OpenAPIGeneratorCommandPlugin"]),
```suggestion .plugin(name: "OpenAPIGeneratorCommand", targets: ["OpenAPIGeneratorCommand"]), ``` I think `OpenAPIGeneratorCommand` is a good name. `Plugin` is redundant, as the build system ensures that this product type is used in the correct context. It also reads better when it shows up in Xcode, as you're "invoking the OpenAPI generator command", and a command is a type of a plugin, so no need to use the phrase `...CommandPlugin`.
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -134,5 +135,19 @@ let package = Package( "swift-openapi-generator", ] ), + + .plugin( + name: "OpenAPIGeneratorCommandPlugin", + capability: Target.PluginCapability.command( + intent: .custom( + verb: "generate-openapi-code", + description: "Generates OpenAPI code"
```suggestion description: "Generates Swift code from an OpenAPI document." ```
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -134,5 +135,19 @@ let package = Package( "swift-openapi-generator", ] ), + + .plugin( + name: "OpenAPIGeneratorCommandPlugin", + capability: Target.PluginCapability.command( + intent: .custom( + verb: "generate-openapi-code", + description: "Generates OpenAPI code" + ), + permissions: [.writeToPackageDirectory(reason: "To generate OpenAPI code")]
```suggestion permissions: [.writeToPackageDirectory(reason: "To write the generated Swift files back into the source directory of the package.")] ```
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -0,0 +1,137 @@ +//===----------------------------------------------------------------------===// +// +// 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 PackagePlugin +import Foundation + +@main +struct SwiftOpenAPIGeneratorPlugin { + func runCommand( + targetWorkingDirectory: Path, + tool: (String) throws -> PluginContext.Tool, + sourceFiles: FileList, + targetName: String + ) throws { + let inputs = try PluginUtils.validateInputs( + workingDirectory: targetWorkingDirectory, + tool: tool, + sourceFiles: sourceFiles, + targetName: targetName, + invocationSource: .CommandPlugin + ) + + let toolUrl = URL(fileURLWithPath: inputs.tool.path.string) + let process = Process() + process.executableURL = toolUrl + process.arguments = inputs.arguments
Can you also clean the environment, to ensure that nothing leaks through. If that breaks the plugin, only add the exact env vars required. ```suggestion process.arguments = inputs.arguments process.environment = [:] ```
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -0,0 +1,137 @@ +//===----------------------------------------------------------------------===// +// +// 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 PackagePlugin +import Foundation + +@main +struct SwiftOpenAPIGeneratorPlugin { + func runCommand( + targetWorkingDirectory: Path, + tool: (String) throws -> PluginContext.Tool, + sourceFiles: FileList, + targetName: String + ) throws { + let inputs = try PluginUtils.validateInputs( + workingDirectory: targetWorkingDirectory, + tool: tool, + sourceFiles: sourceFiles, + targetName: targetName, + invocationSource: .CommandPlugin + ) + + let toolUrl = URL(fileURLWithPath: inputs.tool.path.string) + let process = Process() + process.executableURL = toolUrl + process.arguments = inputs.arguments + try process.run()
Should we have a `process.waitUntilExit()` here? Otherwise the command plugin might exit before the spawned process does.
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -0,0 +1,137 @@ +//===----------------------------------------------------------------------===// +// +// 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 PackagePlugin +import Foundation + +@main +struct SwiftOpenAPIGeneratorPlugin { + func runCommand( + targetWorkingDirectory: Path, + tool: (String) throws -> PluginContext.Tool, + sourceFiles: FileList, + targetName: String + ) throws { + let inputs = try PluginUtils.validateInputs( + workingDirectory: targetWorkingDirectory, + tool: tool, + sourceFiles: sourceFiles, + targetName: targetName, + invocationSource: .CommandPlugin + ) + + let toolUrl = URL(fileURLWithPath: inputs.tool.path.string) + let process = Process() + process.executableURL = toolUrl + process.arguments = inputs.arguments + try process.run() + } +} + +extension SwiftOpenAPIGeneratorPlugin: CommandPlugin { + func performCommand( + context: PluginContext, + arguments: [String] + ) async throws { + var hasHadASuccessfulRun = false + var errors = [(error: any Error, targetName: String)]() + for target in context.package.targets {
I think we can simplify the whole plugin by _always_ requiring exactly one target name. That way, we don't have to search for dependencies or worry about which targets are included in a scheme. It also means we can emit good errors in all scenarios, instead of guessing which target the adopter meant to generate code into.
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -0,0 +1,82 @@ +import PackagePlugin +import Foundation + +enum PluginError: Swift.Error, CustomStringConvertible, LocalizedError { + case incompatibleTarget(targetName: String) + case noTargetsFoundForCommandPlugin + case fileErrors([FileError], targetName: String) + + var description: String { + switch self { + case .incompatibleTarget(let targetName): + return "Incompatible target called '\(targetName)'. Only Swift source targets can be used with the Swift OpenAPI generator plugin."
```suggestion return "Incompatible target called '\(targetName)'. Only Swift source targets can be used with the Swift OpenAPI Generator plugin." ```
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -0,0 +1,82 @@ +import PackagePlugin +import Foundation + +enum PluginError: Swift.Error, CustomStringConvertible, LocalizedError { + case incompatibleTarget(targetName: String) + case noTargetsFoundForCommandPlugin + case fileErrors([FileError], targetName: String) + + var description: String { + switch self { + case .incompatibleTarget(let targetName): + return "Incompatible target called '\(targetName)'. Only Swift source targets can be used with the Swift OpenAPI generator plugin." + case .noTargetsFoundForCommandPlugin: + return "None of the targets include valid OpenAPI spec files. Please make sure at least one of your targets has any valid OpenAPI spec files before triggering this command plugin. See documentation for details."
I guess this case will go away if we simplify to always require the specific target to be passed in.
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -0,0 +1,82 @@ +import PackagePlugin +import Foundation + +enum PluginError: Swift.Error, CustomStringConvertible, LocalizedError { + case incompatibleTarget(targetName: String) + case noTargetsFoundForCommandPlugin + case fileErrors([FileError], targetName: String) + + var description: String { + switch self { + case .incompatibleTarget(let targetName): + return "Incompatible target called '\(targetName)'. Only Swift source targets can be used with the Swift OpenAPI generator plugin." + case .noTargetsFoundForCommandPlugin: + return "None of the targets include valid OpenAPI spec files. Please make sure at least one of your targets has any valid OpenAPI spec files before triggering this command plugin. See documentation for details." + case .fileErrors(let errors, let targetName): + return "Found file errors in target called '\(targetName)': \(errors.description)" + } + } + + var errorDescription: String? { + description + } +} + +extension [PluginError]: Swift.Error, CustomStringConvertible, LocalizedError { + public var errorDescription: String? { + description + } +} + +struct FileError: Swift.Error, CustomStringConvertible, LocalizedError { + + enum Kind: CaseIterable { + case config + case document + } + + enum Issue { + case notFound + case multiFound(files: [Path])
```suggestion case multipleFilesFound(files: [Path]) ``` While we're changing this, we can make it clearer.
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -42,16 +42,19 @@ struct _GenerateCommand: AsyncParsableCommand { ) var outputDirectory: URL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath) - @Flag( + @Option( help: "Whether this invocation is from the SwiftPM plugin. We always need to produce all files when invoked from the plugin. Non-requested modes produce empty files." ) - var isPluginInvocation: Bool = false + var invokedFrom: InvocationSource = .CLI
Allow me to bikeshed for a moment here: I think the name `pluginInvocationSource` would work well, as an option (so `PluginInvocationSource?`). Then, the `PluginInvocationSource` would only have the cases `.command` and `.build`. That way, by default, and when invoked manually, this option is nil. Otherwise, each plugin provides its own type.
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -0,0 +1,6 @@ +/// The source of the generator invocation. +enum InvocationSource: String, Codable {
```suggestion enum PluginInvocationSource: String, Codable { ```
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -0,0 +1,6 @@ +/// The source of the generator invocation. +enum InvocationSource: String, Codable { + case BuildToolPlugin + case CommandPlugin + case CLI
```suggestion case build case command ```
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -0,0 +1,118 @@ +import PackagePlugin + +enum PluginUtils { + private static var supportedConfigFiles: Set<String> { Set(["yaml", "yml"].map { "openapi-generator-config." + $0 }) } + private static var supportedDocFiles: Set<String> { Set(["yaml", "yml", "json"].map { "openapi." + $0 }) } + + /// Validated values to run a plugin with. + struct ValidatedInputs { + let doc: Path + let config: Path + let genSourcesDir: Path + let arguments: [String] + let tool: PluginContext.Tool + } + + /// Validates the inputs and returns the necessary values to run a plugin. + static func validateInputs( + workingDirectory: Path, + tool: (String) throws -> PluginContext.Tool, + sourceFiles: FileList, + targetName: String, + invocationSource: InvocationSource + ) throws -> ValidatedInputs { + let (config, doc) = try findFiles(inputFiles: sourceFiles, targetName: targetName) + let genSourcesDir = workingDirectory.appending("OpenAPISources")
I'd keep the name to the original name, that way when folks upgrade to the newer generator, they won't immediately get a build error as we'd generate duplicate files to the new directory name, and not clean up the old one. `GeneratedSources` is explicit enough, IMO.
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -151,5 +152,20 @@ let package = Package( "swift-openapi-generator" ] ), + + // Command Plugin + .plugin( + name: "OpenAPIGeneratorCommand", + capability: Target.PluginCapability.command(
```suggestion capability: .command( ```
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -151,5 +152,20 @@ let package = Package( "swift-openapi-generator" ] ), + + // Command Plugin + .plugin( + name: "OpenAPIGeneratorCommand", + capability: Target.PluginCapability.command( + intent: .custom( + verb: "generate-openapi-code",
```suggestion verb: "generate-code-from-openapi", ``` Maybe a slightly better name, I prefer if the input is on the left of the output when reading left-to-right, so "generate code from openapi".
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -151,5 +152,20 @@ let package = Package( "swift-openapi-generator" ] ), + + // Command Plugin + .plugin( + name: "OpenAPIGeneratorCommand", + capability: Target.PluginCapability.command( + intent: .custom( + verb: "generate-openapi-code", + description: "Generates Swift code from an OpenAPI document."
```suggestion description: "Generate Swift code from an OpenAPI document." ``` Unsure, but maybe this should be an imperative?
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -0,0 +1,125 @@ +import PackagePlugin +import Foundation + +enum PluginError: Swift.Error, CustomStringConvertible, LocalizedError { + case incompatibleTarget(targetName: String) + case noTargetOrDependenciesWithExpectedFiles(targetName: String, dependencyNames: [String]) + case badArguments([String]) + case noTargetsMatchingTargetName(targetName: String) + case tooManyTargetsMatchingTargetName(targetName: String, matchingTargetNames: [String]) + case fileErrors([FileError]) + + var description: String { + switch self { + case .incompatibleTarget(let targetName): + return "Incompatible target called '\(targetName)'. Only Swift source targets can be used with the Swift OpenAPI Generator plugin." + case .noTargetOrDependenciesWithExpectedFiles(let targetName, let dependencyNames): + let introduction = dependencyNames.isEmpty ? "Target called '\(targetName)' doesn't contain" : "Target called '\(targetName)' or its local dependencies \(dependencyNames) don't contain"
```suggestion let introduction = dependencyNames.isEmpty ? "Target called '\(targetName)' doesn't contain" : "Target called '\(targetName)' or its local dependencies \(dependencyNames.joined(separator: ", ") don't contain" ``` Should we format the names somehow?
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -0,0 +1,125 @@ +import PackagePlugin +import Foundation + +enum PluginError: Swift.Error, CustomStringConvertible, LocalizedError { + case incompatibleTarget(targetName: String)
```suggestion case incompatibleTarget(name: String) ```
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -0,0 +1,125 @@ +import PackagePlugin +import Foundation + +enum PluginError: Swift.Error, CustomStringConvertible, LocalizedError { + case incompatibleTarget(targetName: String) + case noTargetOrDependenciesWithExpectedFiles(targetName: String, dependencyNames: [String]) + case badArguments([String]) + case noTargetsMatchingTargetName(targetName: String)
```suggestion case noTargetsMatchingTargetName(String) ```
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -0,0 +1,125 @@ +import PackagePlugin +import Foundation + +enum PluginError: Swift.Error, CustomStringConvertible, LocalizedError { + case incompatibleTarget(targetName: String) + case noTargetOrDependenciesWithExpectedFiles(targetName: String, dependencyNames: [String]) + case badArguments([String]) + case noTargetsMatchingTargetName(targetName: String) + case tooManyTargetsMatchingTargetName(targetName: String, matchingTargetNames: [String]) + case fileErrors([FileError]) + + var description: String { + switch self { + case .incompatibleTarget(let targetName): + return "Incompatible target called '\(targetName)'. Only Swift source targets can be used with the Swift OpenAPI Generator plugin." + case .noTargetOrDependenciesWithExpectedFiles(let targetName, let dependencyNames): + let introduction = dependencyNames.isEmpty ? "Target called '\(targetName)' doesn't contain" : "Target called '\(targetName)' or its local dependencies \(dependencyNames) don't contain" + return "\(introduction) any config or document files with expected names. For OpenAPI code generation, a target needs to contain a config file named 'openapi-generator-config.yaml' or 'openapi-generator-config.yml', as well as an OpenAPI document named 'openapi.yaml', 'openapi.yml' or 'openapi.json' under target's source directory. See documentation for details."
```suggestion return "\(introduction) any config or OpenAPI document files with expected names. See documentation for details." ``` Let's add "OpenAPI" to the sentence and drop the summary of the docs, we don't want to have to keep it in sync here with the other places. Sending people to docs is good enough.
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -0,0 +1,125 @@ +import PackagePlugin +import Foundation + +enum PluginError: Swift.Error, CustomStringConvertible, LocalizedError { + case incompatibleTarget(targetName: String) + case noTargetOrDependenciesWithExpectedFiles(targetName: String, dependencyNames: [String]) + case badArguments([String]) + case noTargetsMatchingTargetName(targetName: String) + case tooManyTargetsMatchingTargetName(targetName: String, matchingTargetNames: [String]) + case fileErrors([FileError]) + + var description: String { + switch self { + case .incompatibleTarget(let targetName): + return "Incompatible target called '\(targetName)'. Only Swift source targets can be used with the Swift OpenAPI Generator plugin." + case .noTargetOrDependenciesWithExpectedFiles(let targetName, let dependencyNames): + let introduction = dependencyNames.isEmpty ? "Target called '\(targetName)' doesn't contain" : "Target called '\(targetName)' or its local dependencies \(dependencyNames) don't contain" + return "\(introduction) any config or document files with expected names. For OpenAPI code generation, a target needs to contain a config file named 'openapi-generator-config.yaml' or 'openapi-generator-config.yml', as well as an OpenAPI document named 'openapi.yaml', 'openapi.yml' or 'openapi.json' under target's source directory. See documentation for details." + case .badArguments(let arguments): + return "On Xcode, use Xcode's command plugin UI to choose one specific target before hitting 'Run'. On CLI make sure arguments are exactly of form '--target <target-name>'. The reason for this error is unexpected arguments: \(arguments)"
Adopters might be using this from other IDEs, so I'd drop the reference to Xcode specifically. ```suggestion return "Unexpected arguments: '\(arguments.joined(separator: " "))', expected: '--target MyTarget'." ```
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -0,0 +1,125 @@ +import PackagePlugin +import Foundation + +enum PluginError: Swift.Error, CustomStringConvertible, LocalizedError { + case incompatibleTarget(targetName: String) + case noTargetOrDependenciesWithExpectedFiles(targetName: String, dependencyNames: [String]) + case badArguments([String]) + case noTargetsMatchingTargetName(targetName: String) + case tooManyTargetsMatchingTargetName(targetName: String, matchingTargetNames: [String]) + case fileErrors([FileError]) + + var description: String { + switch self { + case .incompatibleTarget(let targetName): + return "Incompatible target called '\(targetName)'. Only Swift source targets can be used with the Swift OpenAPI Generator plugin." + case .noTargetOrDependenciesWithExpectedFiles(let targetName, let dependencyNames): + let introduction = dependencyNames.isEmpty ? "Target called '\(targetName)' doesn't contain" : "Target called '\(targetName)' or its local dependencies \(dependencyNames) don't contain" + return "\(introduction) any config or document files with expected names. For OpenAPI code generation, a target needs to contain a config file named 'openapi-generator-config.yaml' or 'openapi-generator-config.yml', as well as an OpenAPI document named 'openapi.yaml', 'openapi.yml' or 'openapi.json' under target's source directory. See documentation for details." + case .badArguments(let arguments): + return "On Xcode, use Xcode's command plugin UI to choose one specific target before hitting 'Run'. On CLI make sure arguments are exactly of form '--target <target-name>'. The reason for this error is unexpected arguments: \(arguments)" + case .noTargetsMatchingTargetName(let targetName): + return "Found no targets matching target name '\(targetName)'. Please make sure the target name argument leads to one and only one target."
```suggestion return "Found no targets with the name '\(targetName)'." ```
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -0,0 +1,125 @@ +import PackagePlugin +import Foundation + +enum PluginError: Swift.Error, CustomStringConvertible, LocalizedError { + case incompatibleTarget(targetName: String) + case noTargetOrDependenciesWithExpectedFiles(targetName: String, dependencyNames: [String]) + case badArguments([String]) + case noTargetsMatchingTargetName(targetName: String) + case tooManyTargetsMatchingTargetName(targetName: String, matchingTargetNames: [String]) + case fileErrors([FileError]) + + var description: String { + switch self { + case .incompatibleTarget(let targetName): + return "Incompatible target called '\(targetName)'. Only Swift source targets can be used with the Swift OpenAPI Generator plugin." + case .noTargetOrDependenciesWithExpectedFiles(let targetName, let dependencyNames): + let introduction = dependencyNames.isEmpty ? "Target called '\(targetName)' doesn't contain" : "Target called '\(targetName)' or its local dependencies \(dependencyNames) don't contain" + return "\(introduction) any config or document files with expected names. For OpenAPI code generation, a target needs to contain a config file named 'openapi-generator-config.yaml' or 'openapi-generator-config.yml', as well as an OpenAPI document named 'openapi.yaml', 'openapi.yml' or 'openapi.json' under target's source directory. See documentation for details." + case .badArguments(let arguments): + return "On Xcode, use Xcode's command plugin UI to choose one specific target before hitting 'Run'. On CLI make sure arguments are exactly of form '--target <target-name>'. The reason for this error is unexpected arguments: \(arguments)" + case .noTargetsMatchingTargetName(let targetName): + return "Found no targets matching target name '\(targetName)'. Please make sure the target name argument leads to one and only one target." + case .tooManyTargetsMatchingTargetName(let targetName, let matchingTargetNames): + return "Found too many targets matching target name '\(targetName)': \(matchingTargetNames). Please make sure the target name argument leads to a unique target."
```suggestion return "Found too many targets with the name '\(targetName)': \(matchingTargetNames.joined(separator: ", ")). Select a target name with a unique name." ```
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -0,0 +1,125 @@ +import PackagePlugin +import Foundation + +enum PluginError: Swift.Error, CustomStringConvertible, LocalizedError { + case incompatibleTarget(targetName: String) + case noTargetOrDependenciesWithExpectedFiles(targetName: String, dependencyNames: [String]) + case badArguments([String]) + case noTargetsMatchingTargetName(targetName: String) + case tooManyTargetsMatchingTargetName(targetName: String, matchingTargetNames: [String]) + case fileErrors([FileError]) + + var description: String { + switch self { + case .incompatibleTarget(let targetName): + return "Incompatible target called '\(targetName)'. Only Swift source targets can be used with the Swift OpenAPI Generator plugin." + case .noTargetOrDependenciesWithExpectedFiles(let targetName, let dependencyNames): + let introduction = dependencyNames.isEmpty ? "Target called '\(targetName)' doesn't contain" : "Target called '\(targetName)' or its local dependencies \(dependencyNames) don't contain" + return "\(introduction) any config or document files with expected names. For OpenAPI code generation, a target needs to contain a config file named 'openapi-generator-config.yaml' or 'openapi-generator-config.yml', as well as an OpenAPI document named 'openapi.yaml', 'openapi.yml' or 'openapi.json' under target's source directory. See documentation for details." + case .badArguments(let arguments): + return "On Xcode, use Xcode's command plugin UI to choose one specific target before hitting 'Run'. On CLI make sure arguments are exactly of form '--target <target-name>'. The reason for this error is unexpected arguments: \(arguments)" + case .noTargetsMatchingTargetName(let targetName): + return "Found no targets matching target name '\(targetName)'. Please make sure the target name argument leads to one and only one target." + case .tooManyTargetsMatchingTargetName(let targetName, let matchingTargetNames): + return "Found too many targets matching target name '\(targetName)': \(matchingTargetNames). Please make sure the target name argument leads to a unique target." + case .fileErrors(let errors): + return "Found file errors: \(errors)."
```suggestion return "Issues with required files: \(errors.map(\.localizedDescription).joined(separator: ", and"))." ```
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -0,0 +1,125 @@ +import PackagePlugin +import Foundation + +enum PluginError: Swift.Error, CustomStringConvertible, LocalizedError { + case incompatibleTarget(targetName: String) + case noTargetOrDependenciesWithExpectedFiles(targetName: String, dependencyNames: [String]) + case badArguments([String]) + case noTargetsMatchingTargetName(targetName: String) + case tooManyTargetsMatchingTargetName(targetName: String, matchingTargetNames: [String]) + case fileErrors([FileError]) + + var description: String { + switch self { + case .incompatibleTarget(let targetName): + return "Incompatible target called '\(targetName)'. Only Swift source targets can be used with the Swift OpenAPI Generator plugin." + case .noTargetOrDependenciesWithExpectedFiles(let targetName, let dependencyNames): + let introduction = dependencyNames.isEmpty ? "Target called '\(targetName)' doesn't contain" : "Target called '\(targetName)' or its local dependencies \(dependencyNames) don't contain" + return "\(introduction) any config or document files with expected names. For OpenAPI code generation, a target needs to contain a config file named 'openapi-generator-config.yaml' or 'openapi-generator-config.yml', as well as an OpenAPI document named 'openapi.yaml', 'openapi.yml' or 'openapi.json' under target's source directory. See documentation for details." + case .badArguments(let arguments): + return "On Xcode, use Xcode's command plugin UI to choose one specific target before hitting 'Run'. On CLI make sure arguments are exactly of form '--target <target-name>'. The reason for this error is unexpected arguments: \(arguments)" + case .noTargetsMatchingTargetName(let targetName): + return "Found no targets matching target name '\(targetName)'. Please make sure the target name argument leads to one and only one target." + case .tooManyTargetsMatchingTargetName(let targetName, let matchingTargetNames): + return "Found too many targets matching target name '\(targetName)': \(matchingTargetNames). Please make sure the target name argument leads to a unique target." + case .fileErrors(let errors): + return "Found file errors: \(errors)." + } + } + + var errorDescription: String? { + description + } + + /// The error is definitely due to misconfiguration of a target. + var isDefiniteMisconfigurationError: Bool { + switch self { + case .incompatibleTarget: + return false + case .noTargetOrDependenciesWithExpectedFiles: + return false + case .badArguments: + return false + case .noTargetsMatchingTargetName: + return false + case .tooManyTargetsMatchingTargetName:
Nit: You could put these first 5 on the same line, to more clearly communicate that they are handled the same way.
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -0,0 +1,125 @@ +import PackagePlugin +import Foundation + +enum PluginError: Swift.Error, CustomStringConvertible, LocalizedError { + case incompatibleTarget(targetName: String) + case noTargetOrDependenciesWithExpectedFiles(targetName: String, dependencyNames: [String]) + case badArguments([String]) + case noTargetsMatchingTargetName(targetName: String) + case tooManyTargetsMatchingTargetName(targetName: String, matchingTargetNames: [String]) + case fileErrors([FileError]) + + var description: String { + switch self { + case .incompatibleTarget(let targetName): + return "Incompatible target called '\(targetName)'. Only Swift source targets can be used with the Swift OpenAPI Generator plugin." + case .noTargetOrDependenciesWithExpectedFiles(let targetName, let dependencyNames): + let introduction = dependencyNames.isEmpty ? "Target called '\(targetName)' doesn't contain" : "Target called '\(targetName)' or its local dependencies \(dependencyNames) don't contain" + return "\(introduction) any config or document files with expected names. For OpenAPI code generation, a target needs to contain a config file named 'openapi-generator-config.yaml' or 'openapi-generator-config.yml', as well as an OpenAPI document named 'openapi.yaml', 'openapi.yml' or 'openapi.json' under target's source directory. See documentation for details." + case .badArguments(let arguments): + return "On Xcode, use Xcode's command plugin UI to choose one specific target before hitting 'Run'. On CLI make sure arguments are exactly of form '--target <target-name>'. The reason for this error is unexpected arguments: \(arguments)" + case .noTargetsMatchingTargetName(let targetName): + return "Found no targets matching target name '\(targetName)'. Please make sure the target name argument leads to one and only one target." + case .tooManyTargetsMatchingTargetName(let targetName, let matchingTargetNames): + return "Found too many targets matching target name '\(targetName)': \(matchingTargetNames). Please make sure the target name argument leads to a unique target." + case .fileErrors(let errors): + return "Found file errors: \(errors)." + } + } + + var errorDescription: String? { + description + } + + /// The error is definitely due to misconfiguration of a target. + var isDefiniteMisconfigurationError: Bool {
```suggestion var isMisconfigurationError: Bool { ``` You can drop the "Definite", as `isMisconfigurationError` already communicates what you need.
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -0,0 +1,125 @@ +import PackagePlugin +import Foundation + +enum PluginError: Swift.Error, CustomStringConvertible, LocalizedError { + case incompatibleTarget(targetName: String) + case noTargetOrDependenciesWithExpectedFiles(targetName: String, dependencyNames: [String]) + case badArguments([String]) + case noTargetsMatchingTargetName(targetName: String) + case tooManyTargetsMatchingTargetName(targetName: String, matchingTargetNames: [String]) + case fileErrors([FileError]) + + var description: String { + switch self { + case .incompatibleTarget(let targetName): + return "Incompatible target called '\(targetName)'. Only Swift source targets can be used with the Swift OpenAPI Generator plugin." + case .noTargetOrDependenciesWithExpectedFiles(let targetName, let dependencyNames): + let introduction = dependencyNames.isEmpty ? "Target called '\(targetName)' doesn't contain" : "Target called '\(targetName)' or its local dependencies \(dependencyNames) don't contain" + return "\(introduction) any config or document files with expected names. For OpenAPI code generation, a target needs to contain a config file named 'openapi-generator-config.yaml' or 'openapi-generator-config.yml', as well as an OpenAPI document named 'openapi.yaml', 'openapi.yml' or 'openapi.json' under target's source directory. See documentation for details." + case .badArguments(let arguments): + return "On Xcode, use Xcode's command plugin UI to choose one specific target before hitting 'Run'. On CLI make sure arguments are exactly of form '--target <target-name>'. The reason for this error is unexpected arguments: \(arguments)" + case .noTargetsMatchingTargetName(let targetName): + return "Found no targets matching target name '\(targetName)'. Please make sure the target name argument leads to one and only one target." + case .tooManyTargetsMatchingTargetName(let targetName, let matchingTargetNames): + return "Found too many targets matching target name '\(targetName)': \(matchingTargetNames). Please make sure the target name argument leads to a unique target." + case .fileErrors(let errors): + return "Found file errors: \(errors)." + } + } + + var errorDescription: String? { + description + } + + /// The error is definitely due to misconfiguration of a target. + var isDefiniteMisconfigurationError: Bool { + switch self { + case .incompatibleTarget: + return false + case .noTargetOrDependenciesWithExpectedFiles: + return false + case .badArguments: + return false + case .noTargetsMatchingTargetName: + return false + case .tooManyTargetsMatchingTargetName: + return false + case .fileErrors(let errors): + return errors.isDefiniteMisconfigurationError + } + } +} + +struct FileError: Swift.Error, CustomStringConvertible, LocalizedError { + + enum Kind: CaseIterable { + case config + case document + } + + enum Issue { + case noFilesFound + case multipleFilesFound(files: [Path]) + + /// The error is definitely due to misconfiguration of a target. + var isDefiniteMisconfigurationError: Bool {
```suggestion var isMisconfigurationError: Bool { ```
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -0,0 +1,125 @@ +import PackagePlugin +import Foundation + +enum PluginError: Swift.Error, CustomStringConvertible, LocalizedError { + case incompatibleTarget(targetName: String) + case noTargetOrDependenciesWithExpectedFiles(targetName: String, dependencyNames: [String]) + case badArguments([String]) + case noTargetsMatchingTargetName(targetName: String) + case tooManyTargetsMatchingTargetName(targetName: String, matchingTargetNames: [String]) + case fileErrors([FileError]) + + var description: String { + switch self { + case .incompatibleTarget(let targetName): + return "Incompatible target called '\(targetName)'. Only Swift source targets can be used with the Swift OpenAPI Generator plugin." + case .noTargetOrDependenciesWithExpectedFiles(let targetName, let dependencyNames): + let introduction = dependencyNames.isEmpty ? "Target called '\(targetName)' doesn't contain" : "Target called '\(targetName)' or its local dependencies \(dependencyNames) don't contain" + return "\(introduction) any config or document files with expected names. For OpenAPI code generation, a target needs to contain a config file named 'openapi-generator-config.yaml' or 'openapi-generator-config.yml', as well as an OpenAPI document named 'openapi.yaml', 'openapi.yml' or 'openapi.json' under target's source directory. See documentation for details." + case .badArguments(let arguments): + return "On Xcode, use Xcode's command plugin UI to choose one specific target before hitting 'Run'. On CLI make sure arguments are exactly of form '--target <target-name>'. The reason for this error is unexpected arguments: \(arguments)" + case .noTargetsMatchingTargetName(let targetName): + return "Found no targets matching target name '\(targetName)'. Please make sure the target name argument leads to one and only one target." + case .tooManyTargetsMatchingTargetName(let targetName, let matchingTargetNames): + return "Found too many targets matching target name '\(targetName)': \(matchingTargetNames). Please make sure the target name argument leads to a unique target." + case .fileErrors(let errors): + return "Found file errors: \(errors)." + } + } + + var errorDescription: String? { + description + } + + /// The error is definitely due to misconfiguration of a target. + var isDefiniteMisconfigurationError: Bool { + switch self { + case .incompatibleTarget: + return false + case .noTargetOrDependenciesWithExpectedFiles: + return false + case .badArguments: + return false + case .noTargetsMatchingTargetName: + return false + case .tooManyTargetsMatchingTargetName: + return false + case .fileErrors(let errors): + return errors.isDefiniteMisconfigurationError + } + } +} + +struct FileError: Swift.Error, CustomStringConvertible, LocalizedError { + + enum Kind: CaseIterable { + case config + case document + } + + enum Issue { + case noFilesFound + case multipleFilesFound(files: [Path]) + + /// The error is definitely due to misconfiguration of a target. + var isDefiniteMisconfigurationError: Bool { + switch self { + case .noFilesFound: + return false + case .multipleFilesFound: + return true + } + } + } + + let targetName: String + let fileKind: Kind + let issue: Issue + + var description: String { + "FileError { \(helpAnchor!) }"
Let's reshuffle this a bit to get rid of the force unwrap. 1. Move the contents of `helpAnchor` to be the implementation of `description`. 2. Have `helpAnchor` call `description`. 3. Drop the `FileError { ... }` part completely, unless it's specifically parsed some other tool?
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -0,0 +1,125 @@ +import PackagePlugin +import Foundation + +enum PluginError: Swift.Error, CustomStringConvertible, LocalizedError { + case incompatibleTarget(targetName: String) + case noTargetOrDependenciesWithExpectedFiles(targetName: String, dependencyNames: [String]) + case badArguments([String]) + case noTargetsMatchingTargetName(targetName: String) + case tooManyTargetsMatchingTargetName(targetName: String, matchingTargetNames: [String]) + case fileErrors([FileError]) + + var description: String { + switch self { + case .incompatibleTarget(let targetName): + return "Incompatible target called '\(targetName)'. Only Swift source targets can be used with the Swift OpenAPI Generator plugin." + case .noTargetOrDependenciesWithExpectedFiles(let targetName, let dependencyNames): + let introduction = dependencyNames.isEmpty ? "Target called '\(targetName)' doesn't contain" : "Target called '\(targetName)' or its local dependencies \(dependencyNames) don't contain" + return "\(introduction) any config or document files with expected names. For OpenAPI code generation, a target needs to contain a config file named 'openapi-generator-config.yaml' or 'openapi-generator-config.yml', as well as an OpenAPI document named 'openapi.yaml', 'openapi.yml' or 'openapi.json' under target's source directory. See documentation for details." + case .badArguments(let arguments): + return "On Xcode, use Xcode's command plugin UI to choose one specific target before hitting 'Run'. On CLI make sure arguments are exactly of form '--target <target-name>'. The reason for this error is unexpected arguments: \(arguments)" + case .noTargetsMatchingTargetName(let targetName): + return "Found no targets matching target name '\(targetName)'. Please make sure the target name argument leads to one and only one target." + case .tooManyTargetsMatchingTargetName(let targetName, let matchingTargetNames): + return "Found too many targets matching target name '\(targetName)': \(matchingTargetNames). Please make sure the target name argument leads to a unique target." + case .fileErrors(let errors): + return "Found file errors: \(errors)." + } + } + + var errorDescription: String? { + description + } + + /// The error is definitely due to misconfiguration of a target. + var isDefiniteMisconfigurationError: Bool { + switch self { + case .incompatibleTarget: + return false + case .noTargetOrDependenciesWithExpectedFiles: + return false + case .badArguments: + return false + case .noTargetsMatchingTargetName: + return false + case .tooManyTargetsMatchingTargetName: + return false + case .fileErrors(let errors): + return errors.isDefiniteMisconfigurationError + } + } +} + +struct FileError: Swift.Error, CustomStringConvertible, LocalizedError { + + enum Kind: CaseIterable { + case config + case document + } + + enum Issue { + case noFilesFound + case multipleFilesFound(files: [Path]) + + /// The error is definitely due to misconfiguration of a target. + var isDefiniteMisconfigurationError: Bool { + switch self { + case .noFilesFound: + return false + case .multipleFilesFound: + return true + } + } + } + + let targetName: String + let fileKind: Kind + let issue: Issue + + var description: String { + "FileError { \(helpAnchor!) }" + } + + var helpAnchor: String? { + switch fileKind { + case .config: + switch issue { + case .noFilesFound: + return "No config file 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 .multipleFilesFound(let files): + return "Multiple config files found in the target named '\(targetName)', but exactly one is expected. Found \(files.map(\.description).joined(separator: " "))." + } + case .document: + switch issue { + case .noFilesFound: + return "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 .multipleFilesFound(let files): + return "Multiple OpenAPI documents found in the target named '\(targetName)', but exactly one is expected. Found \(files.map(\.description).joined(separator: " "))." + } + } + } + + var errorDescription: String? { + description + } + + static func notFoundFileErrors(forTarget targetName: String) -> [FileError] {
Is anything calling this helper function?
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -0,0 +1,125 @@ +import PackagePlugin +import Foundation + +enum PluginError: Swift.Error, CustomStringConvertible, LocalizedError { + case incompatibleTarget(targetName: String) + case noTargetOrDependenciesWithExpectedFiles(targetName: String, dependencyNames: [String]) + case badArguments([String]) + case noTargetsMatchingTargetName(targetName: String) + case tooManyTargetsMatchingTargetName(targetName: String, matchingTargetNames: [String]) + case fileErrors([FileError]) + + var description: String { + switch self { + case .incompatibleTarget(let targetName): + return "Incompatible target called '\(targetName)'. Only Swift source targets can be used with the Swift OpenAPI Generator plugin." + case .noTargetOrDependenciesWithExpectedFiles(let targetName, let dependencyNames): + let introduction = dependencyNames.isEmpty ? "Target called '\(targetName)' doesn't contain" : "Target called '\(targetName)' or its local dependencies \(dependencyNames) don't contain" + return "\(introduction) any config or document files with expected names. For OpenAPI code generation, a target needs to contain a config file named 'openapi-generator-config.yaml' or 'openapi-generator-config.yml', as well as an OpenAPI document named 'openapi.yaml', 'openapi.yml' or 'openapi.json' under target's source directory. See documentation for details." + case .badArguments(let arguments): + return "On Xcode, use Xcode's command plugin UI to choose one specific target before hitting 'Run'. On CLI make sure arguments are exactly of form '--target <target-name>'. The reason for this error is unexpected arguments: \(arguments)" + case .noTargetsMatchingTargetName(let targetName): + return "Found no targets matching target name '\(targetName)'. Please make sure the target name argument leads to one and only one target." + case .tooManyTargetsMatchingTargetName(let targetName, let matchingTargetNames): + return "Found too many targets matching target name '\(targetName)': \(matchingTargetNames). Please make sure the target name argument leads to a unique target." + case .fileErrors(let errors): + return "Found file errors: \(errors)." + } + } + + var errorDescription: String? { + description + } + + /// The error is definitely due to misconfiguration of a target. + var isDefiniteMisconfigurationError: Bool { + switch self { + case .incompatibleTarget: + return false + case .noTargetOrDependenciesWithExpectedFiles: + return false + case .badArguments: + return false + case .noTargetsMatchingTargetName: + return false + case .tooManyTargetsMatchingTargetName: + return false + case .fileErrors(let errors): + return errors.isDefiniteMisconfigurationError + } + } +} + +struct FileError: Swift.Error, CustomStringConvertible, LocalizedError { + + enum Kind: CaseIterable { + case config + case document + } + + enum Issue { + case noFilesFound + case multipleFilesFound(files: [Path]) + + /// The error is definitely due to misconfiguration of a target. + var isDefiniteMisconfigurationError: Bool { + switch self { + case .noFilesFound: + return false + case .multipleFilesFound: + return true + } + } + } + + let targetName: String + let fileKind: Kind + let issue: Issue + + var description: String { + "FileError { \(helpAnchor!) }" + } + + var helpAnchor: String? { + switch fileKind { + case .config: + switch issue { + case .noFilesFound: + return "No config file 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 .multipleFilesFound(let files): + return "Multiple config files found in the target named '\(targetName)', but exactly one is expected. Found \(files.map(\.description).joined(separator: " "))." + } + case .document: + switch issue { + case .noFilesFound: + return "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 .multipleFilesFound(let files): + return "Multiple OpenAPI documents found in the target named '\(targetName)', but exactly one is expected. Found \(files.map(\.description).joined(separator: " "))." + } + } + } + + var errorDescription: String? { + description + } + + static func notFoundFileErrors(forTarget targetName: String) -> [FileError] { + FileError.Kind.allCases.map { kind in + FileError(targetName: targetName, fileKind: kind, issue: .noFilesFound) + } + } +} + +private extension [FileError] {
```suggestion private extension Array where Element == FileError { ``` Nit: This is the spelling we use in this project.
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -0,0 +1,125 @@ +import PackagePlugin +import Foundation + +enum PluginError: Swift.Error, CustomStringConvertible, LocalizedError { + case incompatibleTarget(targetName: String) + case noTargetOrDependenciesWithExpectedFiles(targetName: String, dependencyNames: [String]) + case badArguments([String]) + case noTargetsMatchingTargetName(targetName: String) + case tooManyTargetsMatchingTargetName(targetName: String, matchingTargetNames: [String]) + case fileErrors([FileError]) + + var description: String { + switch self { + case .incompatibleTarget(let targetName): + return "Incompatible target called '\(targetName)'. Only Swift source targets can be used with the Swift OpenAPI Generator plugin." + case .noTargetOrDependenciesWithExpectedFiles(let targetName, let dependencyNames): + let introduction = dependencyNames.isEmpty ? "Target called '\(targetName)' doesn't contain" : "Target called '\(targetName)' or its local dependencies \(dependencyNames) don't contain" + return "\(introduction) any config or document files with expected names. For OpenAPI code generation, a target needs to contain a config file named 'openapi-generator-config.yaml' or 'openapi-generator-config.yml', as well as an OpenAPI document named 'openapi.yaml', 'openapi.yml' or 'openapi.json' under target's source directory. See documentation for details." + case .badArguments(let arguments): + return "On Xcode, use Xcode's command plugin UI to choose one specific target before hitting 'Run'. On CLI make sure arguments are exactly of form '--target <target-name>'. The reason for this error is unexpected arguments: \(arguments)" + case .noTargetsMatchingTargetName(let targetName): + return "Found no targets matching target name '\(targetName)'. Please make sure the target name argument leads to one and only one target." + case .tooManyTargetsMatchingTargetName(let targetName, let matchingTargetNames): + return "Found too many targets matching target name '\(targetName)': \(matchingTargetNames). Please make sure the target name argument leads to a unique target." + case .fileErrors(let errors): + return "Found file errors: \(errors)." + } + } + + var errorDescription: String? { + description + } + + /// The error is definitely due to misconfiguration of a target. + var isDefiniteMisconfigurationError: Bool { + switch self { + case .incompatibleTarget: + return false + case .noTargetOrDependenciesWithExpectedFiles: + return false + case .badArguments: + return false + case .noTargetsMatchingTargetName: + return false + case .tooManyTargetsMatchingTargetName: + return false + case .fileErrors(let errors): + return errors.isDefiniteMisconfigurationError + } + } +} + +struct FileError: Swift.Error, CustomStringConvertible, LocalizedError { + + enum Kind: CaseIterable { + case config + case document + } + + enum Issue { + case noFilesFound + case multipleFilesFound(files: [Path]) + + /// The error is definitely due to misconfiguration of a target. + var isDefiniteMisconfigurationError: Bool { + switch self { + case .noFilesFound: + return false + case .multipleFilesFound: + return true + } + } + } + + let targetName: String + let fileKind: Kind + let issue: Issue + + var description: String { + "FileError { \(helpAnchor!) }" + } + + var helpAnchor: String? { + switch fileKind { + case .config: + switch issue { + case .noFilesFound: + return "No config file 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 .multipleFilesFound(let files): + return "Multiple config files found in the target named '\(targetName)', but exactly one is expected. Found \(files.map(\.description).joined(separator: " "))." + } + case .document: + switch issue { + case .noFilesFound: + return "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 .multipleFilesFound(let files): + return "Multiple OpenAPI documents found in the target named '\(targetName)', but exactly one is expected. Found \(files.map(\.description).joined(separator: " "))." + } + } + } + + var errorDescription: String? { + description + } + + static func notFoundFileErrors(forTarget targetName: String) -> [FileError] { + FileError.Kind.allCases.map { kind in + FileError(targetName: targetName, fileKind: kind, issue: .noFilesFound) + } + } +} + +private extension [FileError] { + /// The error is definitely due to misconfiguration of a target. + var isDefiniteMisconfigurationError: Bool {
```suggestion var isMisconfigurationError: Bool { ```
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -0,0 +1,5 @@ +/// The source of a plugin generator invocation. +enum PluginSource: String, Codable { + case build + case command
Please add doc comments for the cases.
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -94,18 +105,31 @@ extension _Tool { /// - 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( + inDirectory outputDirectory: URL, + fileName: String, + with contents: () throws -> Data + ) throws -> Bool { + let fm = FileManager.default
```suggestion let fileManager = FileManager() ``` Variable naming, and it's better to create a new FileManager, as otherwise someone might have set the delegate on the shared file manager, which can lead to unexpected results.
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -42,16 +42,19 @@ struct _GenerateCommand: AsyncParsableCommand { ) var outputDirectory: URL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath) - @Flag( + @Option( help: - "Whether this invocation is from the SwiftPM plugin. We always need to produce all files when invoked from the plugin. Non-requested modes produce empty files." + "Source of invocation if by a plugin. The generator needs to produce all files when invoked as a build plugin, so non-requested modes produce empty files." ) - var isPluginInvocation: Bool = false + var invokedFrom: PluginSource?
Just bumping the first half of this comment: https://github.com/apple/swift-openapi-generator/pull/98#discussion_r1265064137 Let's also rename the option (will require a change in the plugins as well, and in the docs) to `--plugin-source`, I'm not a fan of options ending with a preposition. ```suggestion var pluginSource: PluginSource? ```
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -0,0 +1,118 @@ +import PackagePlugin + +enum PluginUtils { + private static var supportedConfigFiles: Set<String> { Set(["yaml", "yml"].map { "openapi-generator-config." + $0 }) } + private static var supportedDocFiles: Set<String> { Set(["yaml", "yml", "json"].map { "openapi." + $0 }) } + + /// Validated values to run a plugin with. + struct ValidatedInputs { + let doc: Path + let config: Path + let genSourcesDir: Path + let arguments: [String] + let tool: PluginContext.Tool + } + + /// Validates the inputs and returns the necessary values to run a plugin. + static func validateInputs( + workingDirectory: Path, + tool: (String) throws -> PluginContext.Tool, + sourceFiles: FileList, + targetName: String, + pluginSource: PluginSource + ) throws -> ValidatedInputs { + let (config, doc) = try findFiles(inputFiles: sourceFiles, targetName: targetName) + let genSourcesDir = workingDirectory.appending("GeneratedSources") + + let arguments = [ + "generate", "\(doc)", + "--config", "\(config)", + "--output-directory", "\(genSourcesDir)", + "--invoked-from", "\(pluginSource.rawValue)",
```suggestion "--plugin-source", "\(pluginSource.rawValue)", ```
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -0,0 +1,103 @@ +//===----------------------------------------------------------------------===// +// +// 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 PackagePlugin +import Foundation + +@main +struct SwiftOpenAPIGeneratorPlugin { + func runCommand( + targetWorkingDirectory: Path, + tool: (String) throws -> PluginContext.Tool, + sourceFiles: FileList, + targetName: String + ) throws { + let inputs = try PluginUtils.validateInputs( + workingDirectory: targetWorkingDirectory, + tool: tool, + sourceFiles: sourceFiles, + targetName: targetName, + pluginSource: .command + ) + + let toolUrl = URL(fileURLWithPath: inputs.tool.path.string) + let process = Process() + process.executableURL = toolUrl + process.arguments = inputs.arguments + process.environment = [:] + try process.run() + process.waitUntilExit()
Also, we should inspect the `process.terminationStatus` and throw an error if it's not 0.
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -0,0 +1,103 @@ +//===----------------------------------------------------------------------===// +// +// 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 PackagePlugin +import Foundation + +@main +struct SwiftOpenAPIGeneratorPlugin { + func runCommand( + targetWorkingDirectory: Path, + tool: (String) throws -> PluginContext.Tool, + sourceFiles: FileList, + targetName: String + ) throws { + let inputs = try PluginUtils.validateInputs( + workingDirectory: targetWorkingDirectory, + tool: tool, + sourceFiles: sourceFiles, + targetName: targetName, + pluginSource: .command + ) + + let toolUrl = URL(fileURLWithPath: inputs.tool.path.string) + let process = Process() + process.executableURL = toolUrl + process.arguments = inputs.arguments + process.environment = [:] + try process.run() + process.waitUntilExit() + } +} + +extension SwiftOpenAPIGeneratorPlugin: CommandPlugin { + func performCommand( + context: PluginContext, + arguments: [String] + ) async throws { + guard arguments.count == 2, + arguments[0] == "--target"
Idea: also accept a single argument name, and treat it as the name of the target? So the `--target` part would be somewhat optional. That way, folks can invoke it from CLI as ``` swift package generate-code-from-openapi MyTarget ```
swift-openapi-generator
github_2023
others
98
apple
czechboy0
@@ -0,0 +1,103 @@ +//===----------------------------------------------------------------------===// +// +// 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 PackagePlugin +import Foundation + +@main +struct SwiftOpenAPIGeneratorPlugin { + func runCommand( + targetWorkingDirectory: Path, + tool: (String) throws -> PluginContext.Tool, + sourceFiles: FileList, + targetName: String + ) throws { + let inputs = try PluginUtils.validateInputs( + workingDirectory: targetWorkingDirectory, + tool: tool, + sourceFiles: sourceFiles, + targetName: targetName, + pluginSource: .command + ) + + let toolUrl = URL(fileURLWithPath: inputs.tool.path.string) + let process = Process() + process.executableURL = toolUrl + process.arguments = inputs.arguments + process.environment = [:] + try process.run() + process.waitUntilExit() + } +} + +extension SwiftOpenAPIGeneratorPlugin: CommandPlugin { + func performCommand( + context: PluginContext, + arguments: [String] + ) async throws { + guard arguments.count == 2, + arguments[0] == "--target" + else { + throw PluginError.badArguments(arguments) + } + let targetName = arguments[1] + + let matchingTargets = try context.package.targets(named: [targetName]) + + switch matchingTargets.count { + case 0: + throw PluginError.noTargetsMatchingTargetName(targetName: targetName) + case 1: + let mainTarget = matchingTargets[0] + guard mainTarget is SwiftSourceModuleTarget else { + throw PluginError.incompatibleTarget(targetName: mainTarget.name) + } + let allDependencies = mainTarget.recursiveTargetDependencies + let packageTargets = Set(context.package.targets.map(\.id)) + let localDependencies = allDependencies.filter { packageTargets.contains($0.id) } + + var hadASuccessfulRun = false + + for target in [mainTarget] + localDependencies { + guard let swiftTarget = target as? SwiftSourceModuleTarget else { + continue + } + do { + try runCommand( + targetWorkingDirectory: target.directory, + tool: context.tool, + sourceFiles: swiftTarget.sourceFiles, + targetName: target.name + ) + hadASuccessfulRun = true + } catch let error as PluginError { + if error.isDefiniteMisconfigurationError { + throw error + } + }
Please add a simple `print(...)` describing which target is being inspected, and whether we tried to run the command on it, and if it succeeded or not. Just for easier debugging.
swift-openapi-generator
github_2023
others
148
apple
simonjbeaumont
@@ -61,7 +32,7 @@ fileprivate extension String { /// /// In addition to replacing illegal characters with an underscores, also /// ensures that the identifier starts with a letter and not a number. - var sanitizedForSwiftCode: String { + var safeForSwiftCode: String {
If we're going to dependency inject in the function for doing this, can we remove these functions from being extensions on `String` which seems a bit too easy to accidentally reach for.
swift-openapi-generator
github_2023
others
148
apple
simonjbeaumont
@@ -0,0 +1,27 @@ +//===----------------------------------------------------------------------===// +// +// 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 Foundation + +extension FileTranslator { + + /// Returns a copy of the string modified to be a valid Swift identifier. + /// + /// - Parameter string: The string to convert to be safe for Swift. + func swiftSafeName(for string: String) -> String {
Why do we have this wrapper function at this level. Shouldn't we be injecting this in at the top and have `swiftSafeName` be a property on `FileTranslator` too?
swift-openapi-generator
github_2023
others
148
apple
simonjbeaumont
@@ -30,6 +30,10 @@ struct OperationDescription { /// The OpenAPI components, used to resolve JSON references. var components: OpenAPI.Components + /// A converted function from user-provided strings to strings + /// safe to be used as a Swift identifier. + var asSwiftSafeName: (String) -> String
Having these as properties in the various description objects feels wrong to me. Having the various types that do generations holding onto one of these functions feels right, but these description objects are supposed to be just a datatype. I take it this was added because you didn't want to change the computed properties (e.g. methodName) to be a function that took a "safer". Two alternatives to this: - Do change the computed property to be a function, or maybe - Have the computed property return the "unsafe" name and make it the responsibility of the outer layer to safe the name.
swift-openapi-generator
github_2023
others
141
apple
simonjbeaumont
@@ -0,0 +1,36 @@ +//===----------------------------------------------------------------------===// +// +// 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 + +extension FileTranslator { + + /// Returns a Swift-safe identifier used as the name of the content + /// enum case. + /// + /// - Parameter contentType: The content type for which to compute the name. + func contentSwiftName(_ contentType: ContentType) -> String { + if config.featureFlags.contains(.multipleContentTypes) { + return "unsupported" + } else { + switch contentType { + case .json: + return "json" + case .text: + return "text" + case .binary: + return "binary" + } + } + }
I'm not sure I understand why this has been moved here. Couple of reasons: - This PR is in aid of the _multiple_ content types but it is operating on a single `ContentType` as it was when it was a computed property on `ContentType`. - This flow is no longer colocated with all the other logic, e.g. `headerValueForString`, which remain on the `ContentType`—I understand you need access to the config, but couldn't this be a method on `ContentType` that took a config?
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") + ) + ) + ) + } + ) + + do { + _ = try await server.createPet( + .init( + path: "/api/pets", + method: .post, + headerFields: [ + .init(name: "x-extra-arguments", value: #"{"code":1}"#), + .init(name: "content-type", value: "text/plain; charset=utf-8"), + ], + encodedBody: #""" + { + "name" : "Fluffz" + } + """# + ), + .init() + ) + XCTFail("The method should have thrown an error.") + } catch { + XCTAssertNotNil(error) + }
```suggestion } catch {} ``` You can remove the non-nil check, as the `error` variable in the `catch` block is of type `Error`, not `Error?`.