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 | 426 | apple | czechboy0 | @@ -0,0 +1,59 @@
+openapi: '3.1.0'
+info:
+ title: GreetingService
+ version: 1.0.0
+servers:
+ - url: https://example.com/api
+ description: Example service deployment.
+paths:
+ /greet:
+ get:
+ operationId: getGreeting
+ parameters:
+ - name: name
+ required: false
+ in: query
+ description: The name used in the returned greeting.
+ schema:
+ type: string
+ responses:
+ '200':
+ description: A success response with a greeting.
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Greeting'
+ /count:
+ get:
+ operationId: getCount
+ responses:
+ '200':
+ description: The previous greetings issued.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ count:
+ type: integer
+ required:
+ - count
+ /reset:
+ get: | Should be POST/PUT? |
swift-openapi-generator | github_2023 | others | 426 | apple | czechboy0 | @@ -0,0 +1,59 @@
+openapi: '3.1.0'
+info:
+ title: GreetingService
+ version: 1.0.0
+servers:
+ - url: https://example.com/api
+ description: Example service deployment.
+paths:
+ /greet:
+ get:
+ operationId: getGreeting
+ parameters:
+ - name: name
+ required: false
+ in: query
+ description: The name used in the returned greeting.
+ schema:
+ type: string
+ responses:
+ '200':
+ description: A success response with a greeting.
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Greeting'
+ /count:
+ get:
+ operationId: getCount
+ responses:
+ '200':
+ description: The previous greetings issued.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ count:
+ type: integer
+ required:
+ - count
+ /reset:
+ get:
+ operationId: reset
+ responses:
+ '200':
+ description: Clear out table
+ content:
+ application/json:
+ schema:
+ type: object | Can return 204 No Content instead. |
swift-openapi-generator | github_2023 | others | 415 | apple | simonjbeaumont | @@ -0,0 +1,45 @@
+// swift-tools-version:5.9
+//===----------------------------------------------------------------------===//
+//
+// 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 PackageDescription
+
+let package = Package(
+ name: "HelloWorldServer",
+ platforms: [.macOS(.v13)], | I think this is overly restrictive these days and dates back to before we relaxed things, pre 0.1. |
swift-openapi-generator | github_2023 | others | 415 | apple | simonjbeaumont | @@ -0,0 +1,45 @@
+// swift-tools-version:5.9
+//===----------------------------------------------------------------------===//
+//
+// 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 PackageDescription
+
+let package = Package(
+ name: "HelloWorldServer",
+ platforms: [.macOS(.v13)],
+ dependencies: [
+ .package(url: "https://github.com/apple/swift-openapi-generator", exact: "1.0.0-alpha.1"),
+ .package(url: "https://github.com/apple/swift-openapi-runtime", exact: "1.0.0-alpha.1"),
+ .package(url: "https://github.com/swift-server/swift-openapi-vapor", exact: "1.0.0-alpha.1"),
+ .package(url: "https://github.com/vapor/vapor", from: "4.76.0"), | Weren't there some bug fixes related to streaming in Vapor? I realise we'd probably get them by resolution, but let's set this to something more recent, that we know has the fixes we need. |
swift-openapi-generator | github_2023 | others | 415 | apple | simonjbeaumont | @@ -0,0 +1,40 @@
+# Hello World Server
+
+An example project using [Swift OpenAPI Generator](https://github.com/apple/swift-openapi-generator).
+
+## Overview
+
+A "hello world" server that uses generated server stubs to handle requests as the Greeting Service.
+
+The tool uses the [Vapor](https://github.com/vapor/vapor) server framework to handle HTTP requests, wrapped in the [Swift OpenAPI Vapor Transport](https://github.com/swift-server/swift-openapi-vapor).
+
+The CLI starts the server on `http://localhost:8080` and can be invoked by running the `HelloWorldClient` example client or on the command line using:
+
+```
+$ curl http://localhost:8080/api/greet
+{
+ "message" : "Hello, Stranger!"
+}
+```
+
+## Usage
+
+Build and run the server CLI using:
+
+```
+$ swift run
+2023-12-01T14:14:35+0100 notice codes.vapor.application : [Vapor] Server starting on http://127.0.0.1:8080
+...
+```
+
+## Testing
+
+Run tests using:
+
+```
+swift test
+```
+
+The testing strategy is to call the `Handler` directly from tests, as it conforms the `APIProtocol` and implements the business logic.
+
+This allows you to provide any input to the handler methods and verify that the correct outputs are returned, such as error responses when the input data is invalid, and so on. | Could we emphasise here that there's no transport involved in these tests so you preserve the ability to swap to another one at any time and no networking types or connectivity is required to run the tests. |
swift-openapi-generator | github_2023 | others | 412 | apple | simonjbeaumont | @@ -0,0 +1,51 @@
+#!/usr/bin/env bash
+##===----------------------------------------------------------------------===##
+##
+## This source file is part of the SwiftOpenAPIGenerator open source project
+##
+## Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+## Licensed under Apache License v2.0
+##
+## See LICENSE.txt for license information
+## See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+##
+## SPDX-License-Identifier: Apache-2.0
+##
+##===----------------------------------------------------------------------===##
+set -euo pipefail
+
+log() { printf -- "** %s\n" "$*" >&2; }
+error() { printf -- "** ERROR: %s\n" "$*" >&2; }
+fatal() { error "$@"; exit 1; }
+
+log "Checking required executables..."
+SWIFT_BIN=${SWIFT_BIN:-$(command -v swift || xcrun -f swift)} || fatal "SWIFT_BIN unset and no swift on PATH"
+JQ_BIN=${JQ_BIN:-$(command -v jq)} || fatal "JQ_BIN unset and no jq on PATH" | ```suggestion
``` |
swift-openapi-generator | github_2023 | others | 412 | apple | simonjbeaumont | @@ -0,0 +1,51 @@
+#!/usr/bin/env bash
+##===----------------------------------------------------------------------===##
+##
+## This source file is part of the SwiftOpenAPIGenerator open source project
+##
+## Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+## Licensed under Apache License v2.0
+##
+## See LICENSE.txt for license information
+## See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+##
+## SPDX-License-Identifier: Apache-2.0
+##
+##===----------------------------------------------------------------------===##
+set -euo pipefail
+
+log() { printf -- "** %s\n" "$*" >&2; }
+error() { printf -- "** ERROR: %s\n" "$*" >&2; }
+fatal() { error "$@"; exit 1; }
+
+log "Checking required executables..."
+SWIFT_BIN=${SWIFT_BIN:-$(command -v swift || xcrun -f swift)} || fatal "SWIFT_BIN unset and no swift on PATH"
+JQ_BIN=${JQ_BIN:-$(command -v jq)} || fatal "JQ_BIN unset and no jq on PATH"
+
+CURRENT_SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
+REPO_ROOT="$(git -C "${CURRENT_SCRIPT_DIR}" rev-parse --show-toplevel)"
+TMP_DIR=$(/usr/bin/mktemp -d -p "${TMPDIR-/tmp}" "$(basename "$0").XXXXXXXXXX")
+
+PACKAGE_PATH=${PACKAGE_PATH:-${REPO_ROOT}}
+EXAMPLES_PACKAGE_PATH="${PACKAGE_PATH}/Examples"
+
+for EXAMPLE_PACKAGE_PATH in $(find "${EXAMPLES_PACKAGE_PATH}" -maxdepth 2 -name Package.swift -type f | xargs dirname); do
+
+ EXAMPLE_PACKAGE_NAME=$(basename "${EXAMPLE_PACKAGE_PATH}")
+ EXAMPLE_COPY_DIR="${TMP_DIR}/${EXAMPLE_PACKAGE_NAME}"
+ log "Copying example ${EXAMPLE_PACKAGE_NAME} to ${EXAMPLE_COPY_DIR}"
+ cp -R "${EXAMPLE_PACKAGE_PATH}" "${EXAMPLE_COPY_DIR}"
+
+ log "Overriding dependency in ${EXAMPLE_PACKAGE_NAME} to use ${PACKAGE_PATH}"
+ swift package --package-path "${EXAMPLE_COPY_DIR}" \ | ```suggestion
"${SWIFT_BIN}" package --package-path "${EXAMPLE_COPY_DIR}" \
``` |
swift-openapi-generator | github_2023 | others | 412 | apple | simonjbeaumont | @@ -0,0 +1,51 @@
+#!/usr/bin/env bash
+##===----------------------------------------------------------------------===##
+##
+## This source file is part of the SwiftOpenAPIGenerator open source project
+##
+## Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+## Licensed under Apache License v2.0
+##
+## See LICENSE.txt for license information
+## See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+##
+## SPDX-License-Identifier: Apache-2.0
+##
+##===----------------------------------------------------------------------===##
+set -euo pipefail
+
+log() { printf -- "** %s\n" "$*" >&2; }
+error() { printf -- "** ERROR: %s\n" "$*" >&2; }
+fatal() { error "$@"; exit 1; }
+
+log "Checking required executables..."
+SWIFT_BIN=${SWIFT_BIN:-$(command -v swift || xcrun -f swift)} || fatal "SWIFT_BIN unset and no swift on PATH"
+JQ_BIN=${JQ_BIN:-$(command -v jq)} || fatal "JQ_BIN unset and no jq on PATH"
+
+CURRENT_SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
+REPO_ROOT="$(git -C "${CURRENT_SCRIPT_DIR}" rev-parse --show-toplevel)"
+TMP_DIR=$(/usr/bin/mktemp -d -p "${TMPDIR-/tmp}" "$(basename "$0").XXXXXXXXXX")
+
+PACKAGE_PATH=${PACKAGE_PATH:-${REPO_ROOT}}
+EXAMPLES_PACKAGE_PATH="${PACKAGE_PATH}/Examples"
+
+for EXAMPLE_PACKAGE_PATH in $(find "${EXAMPLES_PACKAGE_PATH}" -maxdepth 2 -name Package.swift -type f | xargs dirname); do
+
+ EXAMPLE_PACKAGE_NAME=$(basename "${EXAMPLE_PACKAGE_PATH}")
+ EXAMPLE_COPY_DIR="${TMP_DIR}/${EXAMPLE_PACKAGE_NAME}"
+ log "Copying example ${EXAMPLE_PACKAGE_NAME} to ${EXAMPLE_COPY_DIR}"
+ cp -R "${EXAMPLE_PACKAGE_PATH}" "${EXAMPLE_COPY_DIR}"
+
+ log "Overriding dependency in ${EXAMPLE_PACKAGE_NAME} to use ${PACKAGE_PATH}"
+ swift package --package-path "${EXAMPLE_COPY_DIR}" \
+ edit swift-openapi-generator --path "${PACKAGE_PATH}"
+
+ log "Building example package: ${EXAMPLE_PACKAGE_NAME}"
+ swift build --package-path "${EXAMPLE_COPY_DIR}" | ```suggestion
"${SWIFT_BIN}" build --package-path "${EXAMPLE_COPY_DIR}"
``` |
swift-openapi-generator | github_2023 | others | 412 | apple | simonjbeaumont | @@ -0,0 +1,51 @@
+#!/usr/bin/env bash
+##===----------------------------------------------------------------------===##
+##
+## This source file is part of the SwiftOpenAPIGenerator open source project
+##
+## Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+## Licensed under Apache License v2.0
+##
+## See LICENSE.txt for license information
+## See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+##
+## SPDX-License-Identifier: Apache-2.0
+##
+##===----------------------------------------------------------------------===##
+set -euo pipefail
+
+log() { printf -- "** %s\n" "$*" >&2; }
+error() { printf -- "** ERROR: %s\n" "$*" >&2; }
+fatal() { error "$@"; exit 1; }
+
+log "Checking required executables..."
+SWIFT_BIN=${SWIFT_BIN:-$(command -v swift || xcrun -f swift)} || fatal "SWIFT_BIN unset and no swift on PATH"
+JQ_BIN=${JQ_BIN:-$(command -v jq)} || fatal "JQ_BIN unset and no jq on PATH"
+
+CURRENT_SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
+REPO_ROOT="$(git -C "${CURRENT_SCRIPT_DIR}" rev-parse --show-toplevel)"
+TMP_DIR=$(/usr/bin/mktemp -d -p "${TMPDIR-/tmp}" "$(basename "$0").XXXXXXXXXX")
+
+PACKAGE_PATH=${PACKAGE_PATH:-${REPO_ROOT}}
+EXAMPLES_PACKAGE_PATH="${PACKAGE_PATH}/Examples"
+
+for EXAMPLE_PACKAGE_PATH in $(find "${EXAMPLES_PACKAGE_PATH}" -maxdepth 2 -name Package.swift -type f | xargs dirname); do | ```suggestion
for EXAMPLE_PACKAGE_PATH in $(find "${EXAMPLES_PACKAGE_PATH}" -maxdepth 2 -name Package.swift -type f -print0 | xargs -0 dirname); do
```
(FYI, this kind of thing can be picked up by `shellcheck`). |
swift-openapi-generator | github_2023 | others | 412 | apple | simonjbeaumont | @@ -0,0 +1,51 @@
+#!/usr/bin/env bash
+##===----------------------------------------------------------------------===##
+##
+## This source file is part of the SwiftOpenAPIGenerator open source project
+##
+## Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+## Licensed under Apache License v2.0
+##
+## See LICENSE.txt for license information
+## See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+##
+## SPDX-License-Identifier: Apache-2.0
+##
+##===----------------------------------------------------------------------===##
+set -euo pipefail
+
+log() { printf -- "** %s\n" "$*" >&2; }
+error() { printf -- "** ERROR: %s\n" "$*" >&2; }
+fatal() { error "$@"; exit 1; }
+
+log "Checking required executables..."
+SWIFT_BIN=${SWIFT_BIN:-$(command -v swift || xcrun -f swift)} || fatal "SWIFT_BIN unset and no swift on PATH"
+JQ_BIN=${JQ_BIN:-$(command -v jq)} || fatal "JQ_BIN unset and no jq on PATH"
+
+CURRENT_SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
+REPO_ROOT="$(git -C "${CURRENT_SCRIPT_DIR}" rev-parse --show-toplevel)"
+TMP_DIR=$(/usr/bin/mktemp -d -p "${TMPDIR-/tmp}" "$(basename "$0").XXXXXXXXXX")
+
+PACKAGE_PATH=${PACKAGE_PATH:-${REPO_ROOT}}
+EXAMPLES_PACKAGE_PATH="${PACKAGE_PATH}/Examples"
+
+for EXAMPLE_PACKAGE_PATH in $(find "${EXAMPLES_PACKAGE_PATH}" -maxdepth 2 -name Package.swift -type f | xargs dirname); do
+
+ EXAMPLE_PACKAGE_NAME=$(basename "${EXAMPLE_PACKAGE_PATH}") | ```suggestion
EXAMPLE_PACKAGE_NAME="$(basename "${EXAMPLE_PACKAGE_PATH}")"
``` |
swift-openapi-generator | github_2023 | others | 412 | apple | simonjbeaumont | @@ -0,0 +1,51 @@
+#!/usr/bin/env bash
+##===----------------------------------------------------------------------===##
+##
+## This source file is part of the SwiftOpenAPIGenerator open source project
+##
+## Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+## Licensed under Apache License v2.0
+##
+## See LICENSE.txt for license information
+## See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+##
+## SPDX-License-Identifier: Apache-2.0
+##
+##===----------------------------------------------------------------------===##
+set -euo pipefail
+
+log() { printf -- "** %s\n" "$*" >&2; }
+error() { printf -- "** ERROR: %s\n" "$*" >&2; }
+fatal() { error "$@"; exit 1; }
+
+log "Checking required executables..."
+SWIFT_BIN=${SWIFT_BIN:-$(command -v swift || xcrun -f swift)} || fatal "SWIFT_BIN unset and no swift on PATH"
+JQ_BIN=${JQ_BIN:-$(command -v jq)} || fatal "JQ_BIN unset and no jq on PATH"
+
+CURRENT_SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
+REPO_ROOT="$(git -C "${CURRENT_SCRIPT_DIR}" rev-parse --show-toplevel)"
+TMP_DIR=$(/usr/bin/mktemp -d -p "${TMPDIR-/tmp}" "$(basename "$0").XXXXXXXXXX")
+
+PACKAGE_PATH=${PACKAGE_PATH:-${REPO_ROOT}}
+EXAMPLES_PACKAGE_PATH="${PACKAGE_PATH}/Examples"
+
+for EXAMPLE_PACKAGE_PATH in $(find "${EXAMPLES_PACKAGE_PATH}" -maxdepth 2 -name Package.swift -type f | xargs dirname); do
+
+ EXAMPLE_PACKAGE_NAME=$(basename "${EXAMPLE_PACKAGE_PATH}")
+ EXAMPLE_COPY_DIR="${TMP_DIR}/${EXAMPLE_PACKAGE_NAME}"
+ log "Copying example ${EXAMPLE_PACKAGE_NAME} to ${EXAMPLE_COPY_DIR}"
+ cp -R "${EXAMPLE_PACKAGE_PATH}" "${EXAMPLE_COPY_DIR}" | Fun. In all these years I never knew `-R` is the same as `-r`. |
swift-openapi-generator | github_2023 | others | 412 | apple | simonjbeaumont | @@ -0,0 +1,51 @@
+#!/usr/bin/env bash
+##===----------------------------------------------------------------------===##
+##
+## This source file is part of the SwiftOpenAPIGenerator open source project
+##
+## Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+## Licensed under Apache License v2.0
+##
+## See LICENSE.txt for license information
+## See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+##
+## SPDX-License-Identifier: Apache-2.0
+##
+##===----------------------------------------------------------------------===##
+set -euo pipefail
+
+log() { printf -- "** %s\n" "$*" >&2; }
+error() { printf -- "** ERROR: %s\n" "$*" >&2; }
+fatal() { error "$@"; exit 1; }
+
+log "Checking required executables..."
+SWIFT_BIN=${SWIFT_BIN:-$(command -v swift || xcrun -f swift)} || fatal "SWIFT_BIN unset and no swift on PATH"
+JQ_BIN=${JQ_BIN:-$(command -v jq)} || fatal "JQ_BIN unset and no jq on PATH"
+
+CURRENT_SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
+REPO_ROOT="$(git -C "${CURRENT_SCRIPT_DIR}" rev-parse --show-toplevel)"
+TMP_DIR=$(/usr/bin/mktemp -d -p "${TMPDIR-/tmp}" "$(basename "$0").XXXXXXXXXX")
+
+PACKAGE_PATH=${PACKAGE_PATH:-${REPO_ROOT}}
+EXAMPLES_PACKAGE_PATH="${PACKAGE_PATH}/Examples"
+
+for EXAMPLE_PACKAGE_PATH in $(find "${EXAMPLES_PACKAGE_PATH}" -maxdepth 2 -name Package.swift -type f | xargs dirname); do
+
+ EXAMPLE_PACKAGE_NAME=$(basename "${EXAMPLE_PACKAGE_PATH}")
+ EXAMPLE_COPY_DIR="${TMP_DIR}/${EXAMPLE_PACKAGE_NAME}"
+ log "Copying example ${EXAMPLE_PACKAGE_NAME} to ${EXAMPLE_COPY_DIR}"
+ cp -R "${EXAMPLE_PACKAGE_PATH}" "${EXAMPLE_COPY_DIR}"
+
+ log "Overriding dependency in ${EXAMPLE_PACKAGE_NAME} to use ${PACKAGE_PATH}"
+ swift package --package-path "${EXAMPLE_COPY_DIR}" \
+ edit swift-openapi-generator --path "${PACKAGE_PATH}"
+
+ log "Building example package: ${EXAMPLE_PACKAGE_NAME}"
+ swift build --package-path "${EXAMPLE_COPY_DIR}"
+ log "β
Successfully built the example package ${EXAMPLE_PACKAGE_NAME}."
+
+ if [ -d "${EXAMPLE_COPY_DIR}/Tests" ]; then
+ swift test --package-path "${EXAMPLE_COPY_DIR}" | ```suggestion
log "Running tests for example package: ${EXAMPLE_PACKAGE_NAME}"
"${SWIFT_BIN}" test --package-path "${EXAMPLE_COPY_DIR}"
``` |
swift-openapi-generator | github_2023 | others | 398 | apple | czechboy0 | @@ -37,7 +37,7 @@ let package = Package(
// The platforms below are not currently supported for running
// the generator itself. We include them here to allow the generator
// to emit a more descriptive compiler error.
- .iOS(.v13), .tvOS(.v13), .watchOS(.v6),
+ .iOS(.v13), .tvOS(.v13), .watchOS(.v6), .visionOS(.v1), | Technically, this isn't necessary, as any platform _not_ listed here is assumed to work using _all_ versions, which matches visionOS. But it's probably a good idea to have it here explicitly anyway, to signal that it's been considered. |
swift-openapi-generator | github_2023 | others | 366 | apple | simonjbeaumont | @@ -64,7 +64,7 @@ let package = Package(
// Tests-only: Runtime library linked by generated code, and also
// helps keep the runtime library new enough to work with the generated
// code.
- .package(url: "https://github.com/apple/swift-openapi-runtime", .upToNextMinor(from: "0.3.6")),
+ .package(url: "https://github.com/apple/swift-openapi-runtime", branch: "main"), | Would you prefer us to cut a 0.3.7 runtime and move to main separately? |
swift-openapi-generator | github_2023 | others | 366 | apple | simonjbeaumont | @@ -162,29 +168,40 @@ extension FileTranslator {
/// - 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.
+ /// - isRequired: Whether the contents are in a required container.
/// - foundIn: The location where this content is parsed.
/// - Returns: The detected content type + schema, nil if unsupported.
/// - Throws: If a malformed content type string is encountered.
func parseContentIfSupported(
contentKey: OpenAPI.ContentType,
contentValue: OpenAPI.Content,
excludeBinary: Bool = false,
+ isRequired: Bool,
foundIn: String
) throws -> SchemaContent? {
let contentType = try contentKey.asGeneratorContentType
- if contentType.isJSON {
- if contentType.lowercasedType == "multipart"
- || contentType.lowercasedTypeAndSubtype.contains("application/x-www-form-urlencoded")
- {
- diagnostics.emitUnsupportedIfNotNil(
- contentValue.encoding,
- "Custom encoding for multipart/formEncoded content",
- foundIn: "\(foundIn), content \(contentType.originallyCasedTypeAndSubtype)"
+ if contentType.lowercasedTypeAndSubtype.contains("application/x-www-form-urlencoded") {
+ diagnostics.emitUnsupportedIfNotNil(
+ contentValue.encoding,
+ "Custom encoding for formEncoded content",
+ foundIn: "\(foundIn), content \(contentType.originallyCasedTypeAndSubtype)"
+ )
+ }
+ if contentType.isJSON { return .init(contentType: contentType, schema: contentValue.schema) }
+ if contentType.isUrlEncodedForm { return .init(contentType: contentType, schema: contentValue.schema) }
+ if contentType.isMultipart {
+ guard isRequired else {
+ diagnostics.emit(
+ .warning(
+ message:
+ "Multipart request bodies must always be required, but found an optional one - skipping. Mark as `required: true` to get this body generated.",
+ context: ["foundIn": foundIn]
+ ) | Can you elaborate on why this is here? Is this something that is convention in OpenAPI docs but compliant with OAS? |
swift-openapi-generator | github_2023 | others | 366 | apple | simonjbeaumont | @@ -45,12 +46,18 @@ extension TypesFileTranslator {
let contentTypeName = typeName.appending(jsonComponent: "content")
let contents = requestBody.contents
for content in contents {
- if TypeMatcher.isInlinable(content.content.schema) {
+ if TypeMatcher.isInlinable(content.content.schema)
+ || (content.content.contentType.isMultipart
+ && TypeMatcher.multipartElementTypeReferenceIfReferenceable(
+ schema: content.content.schema,
+ encoding: content.content.encoding
+ ) == nil) | Could this be chopped up a bit to make it easier to follow the conditions? |
swift-openapi-generator | github_2023 | others | 366 | apple | simonjbeaumont | @@ -149,6 +149,21 @@ struct TypeMatcher {
/// - Returns: `true` if the schema is inlinable; `false` otherwise.
static func isInlinable(_ schema: UnresolvedSchema?) -> Bool { !isReferenceable(schema) }
+ /// Return a reference to a multipart element type if the provided schema is referenceable.
+ /// - Parameters:
+ /// - schema: The schema to try to reference.
+ /// - encoding: The associated encoding.
+ /// - Returns: A reference if the schema is referenceable, nil otherwise.
+ static func multipartElementTypeReferenceIfReferenceable(
+ schema: UnresolvedSchema?,
+ encoding: OrderedDictionary<String, OpenAPI.Content.Encoding>?
+ ) -> OpenAPI.Reference<JSONSchema>? {
+ // If the schema is a ref AND no encoding is provided, we can reference the type.
+ // Otherwise, we must inline. | This one sounds like it should have some good test coverage; does it? I looked but didn't see it. |
swift-openapi-generator | github_2023 | others | 369 | apple | dnadoba | @@ -0,0 +1,933 @@
+# SOAR-0009: Type-safe streaming multipart support
+
+Provide a type-safe streaming API to produce and consume multipart bodies.
+
+## Overview
+
+- Proposal: SOAR-0009
+- Author(s): [Honza Dvorsky](https://github.com/czechboy0)
+- Status: **In Review**
+- Issue: [apple/swift-openapi-generator#36](https://github.com/apple/swift-openapi-generator/issues/36)
+- Implementation:
+ - [apple/swift-openapi-runtime#69](https://github.com/apple/swift-openapi-runtime/pull/69)
+ - [apple/swift-openapi-generator#366](https://github.com/apple/swift-openapi-generator/pull/366)
+- Feature flag: `multipart`
+- Affected components:
+ - generator
+ - runtime
+- Links:
+ - [OpenAPI 3.0.3 specification][openapi303]
+ - [OpenAPI 3.1.0 specification][openapi310]
+ - [Swagger.io documentation on multipart support in OpenAPI 3.x][swaggerio-multipart]
+ - [RFC 7578: Returning Values from Forms: multipart/form-data][rfc7578]
+ - [RFC 2046: Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types][rfc2046]
+- Versions:
+ - v1.0 (2023-11-08): Initial version
+
+### Introduction
+
+Support multipart requests and responses by providing a streaming way to produce and consume type-safe parts.
+
+### Motivation
+
+Since its first version, Swift OpenAPI Generator has supported OpenAPI operations that represent the most common HTTP request/response pairs.
+
+For example, posting JSON data to a server, which can look like this:
+
+```
+> POST /cat-photo-metadata HTTP/1.1
+> content-type: application/json
+> x-sender-id: zoom123
+>
+> {"objectCatName":"Waffles","photographerId":24}
+---
+< HTTP/1.1 204 No Content
+```
+
+Or uploading a raw file, such as a photo, to a server:
+
+```
+> POST /cat-photo HTTP/1.1
+> content-type: image/jpeg
+>
+> ...
+---
+< HTTP/1.1 204 No Content
+```
+
+In both of these examples, the HTTP message (a request or a response) has a single content type that describes the format of the body payload.
+
+However, there are use cases where the client wants to send multiple different payloads, each of a different content type, in a single HTTP message. That's what the [multipart][rfc7578] content type is for, and this proposal describes how Swift OpenAPI Generator can add support for it, providing both type safety while retaining a fully streaming API.
+
+> Note: In this proposal, we mostly discuss an example of making a multipart request, but all the proposed features apply to responses as well.
+
+With multipart support, uploading both a JSON object and a raw file to the server in one request could look something like:
+
+```
+> POST /photos HTTP/1.1
+> content-type: multipart/form-data; boundary=___MY_BOUNDARY_1234__
+>
+> --___MY_BOUNDARY_1234__
+> content-disposition: form-data; name="metadata"
+> content-type: application/json
+> x-sender-id: zoom123
+>
+> {"objectCatName":"Waffles","photographerId":24}
+> --___MY_BOUNDARY_1234__
+> content-disposition: form-data; name="contents"
+> content-type: image/jpeg
+>
+> ...
+> --___MY_BOUNDARY_1234__--
+---
+< HTTP/1.1 204 No Content
+```
+
+While we'll discuss the structure of a multipart message in detail below, the TL;DR is:
+- This is still a regular HTTP message, just with a different content type and body.
+- The body uses a _boundary_ string to separate individual _parts_.
+- Each part has its own header fields and body.
+
+Extra requirements to keep in mind:
+- A multipart message must have at least one part (an empty multipart body is invalid).
+- But, a part can have no headers or an empty body.
+- So, the least you can send is a single part with no headers and no body bytes, but it'd still have the boundary strings around it, making it a valid multipart body consisting of one part.
+
+### Proposed solution
+
+As an example, let's consider a service that allows uploading cat photos together with additional JSON metadata in a single request, as seen in the previous section.
+
+#### Describing a multipart request in OpenAPI
+
+Let's define a `POST` request on the `/photos` path that accepts a `multipart/form-data` body containing 2 parts, one JSON part with the name "metadata", and another called "contents" that contains the raw JPEG bytes of the cat photo.
+
+> Note: Parts do not have a predefined order, they can arrive in any order the sender chooses. So let's think of a multipart body as a _stream_ of parts.
+
+In OpenAPI 3.1.0, the operation could look like this (irrelevant parts were omitted, see the full OpenAPI document in [Appendix A][appendix-a]):
+
+```yaml
+paths:
+ /photos:
+ post:
+ requestBody:
+ required: true
+ content:
+ multipart/form-data:
+ schema:
+ type: object
+ properties:
+ metadata:
+ $ref: '#/components/schemas/PhotoMetadata'
+ contents:
+ type: string
+ contentEncoding: binary
+ required:
+ - metadata
+ - contents
+ encoding:
+ metadata:
+ headers:
+ x-sender-id:
+ schema:
+ type: string
+ contents:
+ contentType: image/jpeg
+```
+
+In OpenAPI, the schema for the multipart message is defined using JSON Schema, even though the top level schema is never actually serialized as JSON - it only serves as a way to define the individual parts.
+
+The top level schema is always an object (or an object-ish type, such as allOf or anyOf of objects), and each property describes one part. Top level properties that describe an array schema are interpreted as a way to say that there might be more than one part of the provided name (matching the property name). The `required` property of the schema is used just like in regular JSON Schema β to communicate which properties (in this case, parts) are required and which are optional.
+
+Finally, a sibling field of the `schema` is called `encoding` and mirrors the `schema` structure. For each part, you can override the content type and add custom header fields for each part.
+
+#### Generating a multipart request in Swift
+
+As with other Swift OpenAPI Generator features, the goal of generating code for multipart is to maximize type safety for adopters without compromising their ability to stream HTTP bodies.
+
+With that in mind, multiple different strategies were considered for how to best represent a multipart body in Swift β for details, see the "Future directions" and "Alternatives considered" sections of this proposal.
+
+To that end, we propose to represent a multipart body as an _async sequence of type-safe parts_ (spelled as `OpenAPIRuntime.MultipartBody` in this proposal). This is motivated by the fact that multipart bodies can be gigabytes in size and contain hundreds of parts, so any Swift representation that forces buffering immediately prevents advanced use cases.
+
+> Note: That said, a proposal in the future might introduce an opt-in buffered variant of each type-safe body that builds on the foundation of the async sequence. If this is something you'd like to use, please open an issue on GitHub and start a thread on the Swift Forums, describing your use case.
+
+In addition to `MultipartBody`, we are proposing a few new public types (`MultipartPart` and `MultipartRawPart`) in the runtime library that are used in the Swift snippets below. The full proposed runtime library API diff can be found in [Appendix B][appendix-b], and the details of each type will be discussed in "Detailed design" section.
+
+Getting back to the cat photo service and our multipart request, the body definition would look something like (omitted irrelevant parts of code for brevity):
+
+```swift
+/// - Remark: Generated from `#/paths/photos/POST/requestBody/content`.
+/* nested in Operations.uploadPhoto.Input */ {
+ enum Body {
+ enum multipartFormPayload {
+ struct metadataPayload {
+ struct Headers {
+ var x_dash_sender_dash_id: String?
+ }
+ var headers: Headers
+ var body: Components.Schemas.PhotoMetadata
+ }
+ case metadata(MultipartPart<metadataPayload>)
+ struct contentsPayload {
+ var body: HTTPBody
+ }
+ case contents(MultipartPart<contentsPayload>)
+ case undocumented(MultipartRawPart)
+ }
+ /// - Remark: Generated from `#/paths/photos/POST/requestBody/content/multipart\/form-data`.
+ case multipartForm(MultipartBody<multipartFormPayload>)
+ }
+}
+```
+
+The generated type `multipartFormPayload` is an enum with associated value, where each case is one of the parts documented in the OpenAPI document. By default, undocumented parts are also collected, and this behavior is controlled by the `additionalProperties` schema field - more on that in the "Detailed design" section below.
+
+#### Producing a multipart body sequence
+
+As a client sending this multipart request (or a server sending a multipart response), you are expected to provide a value of type `OpenAPIRuntime.MultipartBody<Part>`, where `Part` is your concrete generated enum:
+
+```swift
+let multipartBody: OpenAPIRuntime.MultipartBody<Operations.uploadPhoto.Input.Body.multipartFormPayload> = ...
+let response = try await client.uploadPhoto(body: multipartBody)
+// ...
+```
+
+Similarly to `OpenAPIRuntime.HTTPBody`, the `OpenAPIRuntime.MultipartBody` async sequence has several convenience initializers, making it easy to construct both from buffered and streaming sources.
+
+For a buffered example, just provide an array of the part values, such as:
+
+```swift
+let multipartBody: OpenAPIRuntime.MultipartBody<Operations.uploadPhoto.Input.Body.multipartFormPayload> = [
+ .metadata(.init(
+ payload: .init(
+ headers: .init(x_dash_sender_dash_id: "zoom123"),
+ body: .init(objectCatName: "Waffles", photographerId: 24)
+ )
+ )),
+ .contents(.init(
+ payload: .init(
+ body: .init(try Data(contentsOf: URL(fileURLWithPath: "/tmp/waffles-summer-2023.jpg")))
+ ),
+ filename: "cat.jpg"
+ ))
+]
+let response = try await client.uploadPhoto(body: multipartBody)
+// ...
+```
+
+However, you can also stream the parts and their bodies:
+
+```swift
+let (stream, continuation) = AsyncStream.makeStream(of: Operations.uploadPhoto.Input.Body.multipartFormPayload.self)
+// Pass `continuation` to another task to start producing parts by calling `continuation.yield(...)` and at the end, `continuation.finish()`.
+let response = try await client.uploadPhoto(body: .init(stream))
+// ...
+```
+
+#### Consuming a multipart body sequence
+
+When consuming a multipart body sequence, for example as a client consuming a multipart response, or a server consuming a multipart request, you are provided with the multipart body async sequence and are responsible for iterating it to completion.
+
+Additionally, for received parts that have their own streaming bodies, you _must_ consume those bodies before requesting the next part, as the underlying async sequence never does any buffering for you, so you can't "skip" any parts or chunks of bytes within a part without explicitly consuming it.
+
+Consuming a multipart body, where you print the metadata fields, and write the photo to disk, could look something like this:
+
+```swift
+let multipartBody: OpenAPIRuntime.MultipartBody<Operations.uploadPhoto.Input.Body.multipartFormPayload> = ...
+for try await part in multipartBody {
+ switch part {
+ case .metadata(let metadataPart):
+ let metadata = metadataPart.payload
+ print("x-sender-id: \(metadata.headers.x_dash_sender_dash_id ?? "<nil>")")
+ print("Cat name: \(metadata.body.objectCatName)")
+ print("Photographer ID: \(metadata.body.photographerId?.description ?? "<nil>")")
+ case .contents(let contentsPart):
+ // Ensure the incoming filepath doesn't try to escape to a parent directory, and so on, before using it.
+ let fileName = contentsPart.filename ?? "\(UUID().uuidString).jpg"
+ guard let outputStream = OutputStream(toFileAtPath: "/tmp/received-cat-photos/\(fileName)", shouldAppend: false) else {
+ // failed to open a stream
+ }
+ outputStream.open()
+ defer {
+ outputStream.close()
+ }
+ // Consume the body before moving to the next part.
+ for try await chunk in contentsPart.body {
+ chunk.withUnsafeBufferPointer { _ = outputStream.write($0.baseAddress!, maxLength: $0.count) }
+ }
+ case .undocumented(let rawPart):
+ print("Received an undocumented part with header fields: \(rawPart.headerFields)")
+ // Consume the body before moving to the next part.
+ _ = try await ArraySlice<UInt8>(collecting: rawPart.body, upTo: 10 * 1024 * 1024)
+ }
+}
+```
+
+### Detailed design
+
+This section describes more details of the functionality supporting the kind of examples we saw above.
+
+#### Different enum case types
+
+The example in the section "Proposed solution" already showed different case types of the generated enum, namely type-safe ones (`case metadata(MultipartPart<metadataPayload>)`) and an undocumented one (`case undocumented(MultipartRawPart)`).
+
+> Note: As a reminder, the full API of the types `MultipartPart`, `MultipartRawPart`, and `MultipartDynamicallyNamedPart` can be found in [Appendix B][appendix-b].
+
+In this section, we enumerate the different enum case types and under what circumstances they are generated.
+
+- **Scenario A**: Zero or more documented cases and `additionalProperties` is not set - a common default.
+ - For each documented case, generates an associated type of `MultipartPart<metadataPayload>` (note that `metadataPayload` is specific to this case only, would be called something else in other documents and properties.)
+ - Also generates an `undocumented` case with an associated type `MultipartRawPart`.
+
+OpenAPI:
+
+```yaml
+multipart/form-data:
+ schema:
+ type: object
+ properties:
+ metadata:
+ $ref: '#/components/schemas/PhotoMetadata'
+```
+
+Generated Swift enum members:
+
+```swift
+struct metadataPayload {
+ var body: Components.Schemas.PhotoMetadata
+}
+case metadata(MultipartPart<metadataPayload>)
+case undocumented(MultipartRawType)
+```
+
+- **Scenario B**: Zero or more documented cases and `additionalProperties: true`.
+ - For each documented case, same as Scenario A.
+ - Also generates an `other` case with an associated type `MultipartRawPart`.
+ - Note that while similar to `undocumented`, the `other` case uses a different name to communicate the fact that the OpenAPI author deliberately enabled `additionalProperties` and thus any parts with unknown names are expected β so the name "undocumented" would not be appropriate.
+
+OpenAPI:
+
+```yaml
+multipart/form-data:
+ schema:
+ type: object
+ properties:
+ metadata:
+ $ref: '#/components/schemas/PhotoMetadata'
+ additionalProperties: true
+```
+
+Generated Swift enum members:
+
+```swift
+struct metadataPayload {
+ var body: Components.Schemas.PhotoMetadata
+}
+case metadata(MultipartPart<metadataPayload>)
+case other(MultipartRawType)
+```
+
+- **Scenario C**: Zero or more documented cases and `additionalProperties: <SCHEMA>`.
+ - For each documented case, same as Scenario A.
+ - Also generates an `other` case with an associated type `MultipartDynamicallyNamedPart`.
+ - Note that while similar to `MultipartPart`, `MultipartDynamicallyNamedPart` adds a read-write `name` property, because while the part name is statically known when `MultipartPart` is used, that's not the case when `MultipartDynamicallyNamedPart` is used, thus the extra property into which the part name is written is required.
+ - Also, since there is no way to define custom headers in this case, the generic parameter of `MultipartDynamicallyNamedPart` is the body value itself, instead of being nested in an `otherPayload` generated struct like for statically documented parts.
+
+OpenAPI:
+
+```yaml
+multipart/form-data:
+ schema:
+ type: object
+ properties:
+ metadata:
+ $ref: '#/components/schemas/PhotoMetadata'
+ additionalProperties:
+ $ref: '#/components/schemas/OtherInfo'
+```
+
+Generated Swift enum members:
+
+```swift
+struct metadataPayload {
+ var body: Components.Schemas.PhotoMetadata
+}
+case metadata(MultipartPart<metadataPayload>)
+case other(MultipartDynamicallyNamedPart<Components.Schemas.OtherInfo>)
+```
+
+- **Scenario D**: Zero or more documented cases and `additionalProperties: false`.
+ - For each documented case, same as Scenario A.
+ - No other cases are generated, and the runtime validation logic ensures that no undocumented part is allowed through.
+
+OpenAPI:
+
+```yaml
+multipart/form-data:
+ schema:
+ type: object
+ properties:
+ metadata:
+ $ref: '#/components/schemas/PhotoMetadata'
+ additionalProperties: false
+```
+
+Generated Swift enum members:
+
+```swift
+struct metadataPayload {
+ var body: Components.Schemas.PhotoMetadata
+}
+case metadata(MultipartPart<metadataPayload>)
+```
+
+#### Validation
+
+Since the OpenAPI document can describe some parts as single value properties, and others as array; and some as required, while others as optional, the generator will emit code that enforces these semantics in the internals of the `MultipartBody` sequence.
+
+The following will be enforced:
+- if a property is a required single value, the sequence fails validation with an error if a part of that name is not seen before the sequence is finished, or if it appears multiple times
+- if a property is an optional single value, the sequence fails validation with an error if a part of that name is seen multiple times
+- if a property is a required array value, the sequence fails validation with an error if a part of that name is not seen at least once
+- if a property is an optional array value, the sequence never fails validation, as any number, from 0 up, are a valid number of occurrences
+- if `additionalProperties` is not specified, the default behavior is to allow undocumented parts through
+- if `additionalProperties: true`, the sequence never fails validation when an undocumented part is encountered
+- if `additionalProperties: false`, the sequence fails validation if an undocumented part is encountered
+- if `additionalProperties: <SCHEMA>`, the sequence doesn't fail validation, but will fail later if the provided part can't be parsed as `<SCHEMA>`
+
+This validation is implemented as a private async sequence inserted into the chain with the names of parts that need the specific requirements enforced. This affords the adopter the same amount of type safety as the rest of the generated code, such as `Codable` generated types that parse from JSON.
+
+Optionality of parts is not reflected as an optional type (`Type?`) here, instead the _absence_ of a part in the async sequence represents it being nil.
+
+#### Boundary customization
+
+When sending a multipart message, the sender needs to choose a boundary string (for example, `___MY_BOUNDARY_1234__`) that is used to separate the individual parts. The boundary string must not appear in any of the parts themselves.
+
+With this proposal, we introduce a protocol called `MultipartBoundaryGenerator` with a single method `func makeBoundary() -> String`, which returns the boundary string. The method is called once per multipart message, so it's encouraged for implementations of `MultipartBoundaryGenerator` to return a somewhat random output every time the `makeBoundary` method is called.
+
+The runtime library comes with two implementations, `ConstantMultipartBoundaryGenerator` and `RandomizedMultipartBoundaryGenerator`.
+
+`ConstantMultipartBoundaryGenerator` returns the same boundary every time and is useful for testing and in cases where stable output for stable inputs is desired, for example for caching.
+`RandomizedMultipartBoundaryGenerator` uses a constant prefix and appends a random suffix made out of `0-9` digits, returning a different output every time. | I would suggest calling it RandomMultipartBoundaryGenerator
Similar to the existing [`RandomNumberGenerator`](https://developer.apple.com/documentation/swift/randomnumbergenerator) protocol and [`SystemRandomNumberGenerator`](https://developer.apple.com/documentation/swift/systemrandomnumbergenerator) struct.
```suggestion
`RandomMultipartBoundaryGenerator` uses a constant prefix and appends a random suffix made out of `0-9` digits, returning a different output every time.
``` |
swift-openapi-generator | github_2023 | others | 346 | apple | czechboy0 | @@ -44,8 +43,7 @@ struct GreetingServiceClient {
}
// Use shorthand APIs to get an expected response or otherwise throw a runtime error.
- print(try await client.getGreeting().ok.body.json.message)
- // ^ ^ ^
+ print(try await client.getGreeting().ok.body.json.message) // ^ ^ ^ | Try to put an extra newline to see if then swift-format leaves the comment alone. |
swift-openapi-generator | github_2023 | others | 345 | apple | glbrntt | @@ -35,6 +41,13 @@ for SCRIPT_PATH in "${SCRIPT_PATHS[@]}"; do
fi
done
+log "Running swift-format..."
+bash ${CURRENT_SCRIPT_DIR}/run-swift-format.sh $FIX_FORMAT > /dev/null | ```suggestion
bash "${CURRENT_SCRIPT_DIR}"/run-swift-format.sh $FIX_FORMAT > /dev/null
``` |
swift-openapi-generator | github_2023 | others | 343 | apple | glbrntt | @@ -13,6 +13,86 @@
//===----------------------------------------------------------------------===//
import Foundation
+/// An object for building up a generated file line-by-line.
+///
+/// After creation, make calls such as `writeLine` to build up the file,
+/// and call `rendered` at the end to get the full file contents.
+final class StringCodeWriter {
+
+ /// The stored lines of code.
+ private var lines: [String]
+
+ /// The current nesting level.
+ private var level: Int
+
+ /// Whether the next call to `writeLine` will continue writing to the last
+ /// stored line. Otherwise a new line is appended.
+ private var nextWriteAppendsToLastLine: Bool = false
+
+ /// Creates a new empty writer.
+ init() {
+ self.level = 0
+ self.lines = []
+ }
+
+ /// Concatenates the stored lines of code into a single string.
+ /// - Returns: The contents of the full file in a single string.
+ func rendered() -> String {
+ lines.joined(separator: "\n")
+ }
+
+ /// Writes a line of code.
+ ///
+ /// By default, a new line is appended to the file.
+ ///
+ /// To continue the last line, make a call to `nextLineAppendsToLastLine` | Maybe it will become more obvious when I see call-sites, but why not have this as a parameter to `writeLine` which defaults to `false`? |
swift-openapi-generator | github_2023 | others | 343 | apple | glbrntt | @@ -13,6 +13,86 @@
//===----------------------------------------------------------------------===//
import Foundation
+/// An object for building up a generated file line-by-line.
+///
+/// After creation, make calls such as `writeLine` to build up the file,
+/// and call `rendered` at the end to get the full file contents.
+final class StringCodeWriter {
+
+ /// The stored lines of code.
+ private var lines: [String]
+
+ /// The current nesting level.
+ private var level: Int
+
+ /// Whether the next call to `writeLine` will continue writing to the last
+ /// stored line. Otherwise a new line is appended.
+ private var nextWriteAppendsToLastLine: Bool = false
+
+ /// Creates a new empty writer.
+ init() {
+ self.level = 0
+ self.lines = []
+ }
+
+ /// Concatenates the stored lines of code into a single string.
+ /// - Returns: The contents of the full file in a single string.
+ func rendered() -> String {
+ lines.joined(separator: "\n")
+ }
+
+ /// Writes a line of code.
+ ///
+ /// By default, a new line is appended to the file.
+ ///
+ /// To continue the last line, make a call to `nextLineAppendsToLastLine`
+ /// before calling `writeLine`.
+ /// - Parameter line: The contents of the line to write.
+ func writeLine(_ line: String) {
+ let newLine: String
+ if nextWriteAppendsToLastLine && !lines.isEmpty {
+ let existingLine = lines.removeLast()
+ newLine = existingLine + line
+ } else {
+ let indentation = Array(repeating: " ", count: level).joined() | Makes basically no practical difference but feels odd to me to do this with an array vs `String(repeating: " ", count: level * 4)` |
swift-openapi-generator | github_2023 | others | 343 | apple | glbrntt | @@ -13,6 +13,86 @@
//===----------------------------------------------------------------------===//
import Foundation
+/// An object for building up a generated file line-by-line.
+///
+/// After creation, make calls such as `writeLine` to build up the file,
+/// and call `rendered` at the end to get the full file contents.
+final class StringCodeWriter {
+
+ /// The stored lines of code.
+ private var lines: [String]
+
+ /// The current nesting level.
+ private var level: Int
+
+ /// Whether the next call to `writeLine` will continue writing to the last
+ /// stored line. Otherwise a new line is appended.
+ private var nextWriteAppendsToLastLine: Bool = false
+
+ /// Creates a new empty writer.
+ init() {
+ self.level = 0
+ self.lines = []
+ }
+
+ /// Concatenates the stored lines of code into a single string.
+ /// - Returns: The contents of the full file in a single string.
+ func rendered() -> String {
+ lines.joined(separator: "\n")
+ }
+
+ /// Writes a line of code.
+ ///
+ /// By default, a new line is appended to the file.
+ ///
+ /// To continue the last line, make a call to `nextLineAppendsToLastLine`
+ /// before calling `writeLine`.
+ /// - Parameter line: The contents of the line to write.
+ func writeLine(_ line: String) {
+ let newLine: String
+ if nextWriteAppendsToLastLine && !lines.isEmpty {
+ let existingLine = lines.removeLast()
+ newLine = existingLine + line
+ } else {
+ let indentation = Array(repeating: " ", count: level).joined()
+ newLine = indentation + line
+ }
+ lines.append(newLine)
+ nextWriteAppendsToLastLine = false
+ }
+
+ /// Increases the indentation level by 1.
+ func push() {
+ level += 1
+ }
+
+ /// Decreases the indentation level by 1.
+ /// - Precondition: Current level must be greater than 0.
+ func pop() {
+ precondition(level > 0, "Cannot pop below 0")
+ level -= 1
+ }
+
+ /// Executes the provided closure with one level deeper indentation.
+ /// - Parameter work: The closure to execute.
+ /// - Returns: The result of the closure execution.
+ func withNestedLevel<R>(_ work: () -> R) -> R { | We do this in grpc as well, makes the code-gen _so_ much easier to write and follow. |
swift-openapi-generator | github_2023 | others | 343 | apple | glbrntt | @@ -127,38 +227,65 @@ struct TextBasedRenderer: RendererProtocol {
}
/// Renders the specified member access expression.
- func renderedMemberAccess(_ memberAccess: MemberAccessDescription) -> String {
- let left = memberAccess.left.flatMap { renderedExpression($0) } ?? ""
- return "\(left).\(memberAccess.right)"
+ func renderMemberAccess(_ memberAccess: MemberAccessDescription) {
+ if let left = memberAccess.left {
+ renderExpression(left)
+ writer.nextLineAppendsToLastLine()
+ }
+ writer.writeLine(".\(memberAccess.right)")
}
/// Renders the specified function call argument.
- func renderedFunctionCallArgument(_ arg: FunctionArgumentDescription) -> String {
- let left = arg.label.flatMap { "\($0): " } ?? ""
- return left + renderedExpression(arg.expression)
+ func renderFunctionCallArgument(_ arg: FunctionArgumentDescription) {
+ if let left = arg.label {
+ writer.writeLine("\(left): ")
+ writer.nextLineAppendsToLastLine()
+ }
+ renderExpression(arg.expression)
}
/// Renders the specified function call.
- func renderedFunctionCall(_ functionCall: FunctionCallDescription) -> String {
+ func renderFunctionCall(_ functionCall: FunctionCallDescription) {
+ renderExpression(functionCall.calledExpression)
+ writer.nextLineAppendsToLastLine()
+ writer.writeLine("(")
let arguments = functionCall.arguments
- let trailingClosureString: String
- if let trailingClosure = functionCall.trailingClosure {
- trailingClosureString = renderedClosureInvocation(trailingClosure)
+ if arguments.count > 1 {
+ writer.withNestedLevel {
+ for (index, argument) in arguments.enumerated() {
+ renderFunctionCallArgument(argument)
+ if index < arguments.count - 1 { | One helper I've used before is a sequence which return the underlying element and whether it's the final value or not which would simplify this a tiny amount (and allows you to avoid conflating index and offset). |
swift-openapi-generator | github_2023 | others | 343 | apple | glbrntt | @@ -34,7 +34,7 @@ if [ "${SWIFT_FORMAT_RC}" -ne 0 ]; then
To fix, run the following command:
- % git ls-files -z '*.swift' | xargs -0 swift-format --in-place --parallel
+ % git ls-files -z '*.swift' | grep -z -v -e 'Tests/OpenAPIGeneratorReferenceTests/Resources' -e 'Sources/swift-openapi-generator/Documentation.docc' | xargs -0 swift-format --in-place --parallel | It might be worth adding `// swift-format-ignore-file` (or whatever the directive is) to the generated code; makes life easier for adopters who check in the code (both grpc and protobuf do this). |
swift-openapi-generator | github_2023 | others | 338 | apple | czechboy0 | @@ -17,7 +17,9 @@ struct GreetingServiceAPIImpl: APIProtocol {
_ input: Operations.getEmoji.Input
) async throws -> Operations.getEmoji.Output {
let emojis = "πππππ€π€"
- return .ok(.init(body: .text(String(emojis.randomElement()!))))
+ let emoji = String(emojis.randomElement()!)
+ let data = emoji.data(using: .utf8)!
+ return .ok(.init(body: .plainText(.init(data)))) | You can provide the string directly to the HTTPBody initializer, no need to explicitly concert to data first. |
swift-openapi-generator | github_2023 | others | 340 | apple | dnadoba | @@ -17,6 +17,7 @@ import PetstoreConsumerTestCore
final class Test_Types: XCTestCase {
+ /// Setup method called before the invocation of each test method in the class. | hm... we might want to have a different swift-format docs policy for test targets but this can be in a separate PR if we decided to do it |
swift-openapi-generator | github_2023 | others | 337 | apple | glbrntt | @@ -16,7 +16,7 @@ import XCTest
import Yams
@testable import _OpenAPIGeneratorCore
-final class FilteredDocumentTests: XCTestCase {
+final class Test_FilteredDocument: XCTestCase { | Is it possible to add a test that filters a document twice and validates the output is identical? |
swift-openapi-generator | github_2023 | others | 335 | apple | glbrntt | @@ -125,42 +122,38 @@ struct RecursionDetector {
// We have seen this node.
- // If the name is not in the stack, this is not a cycle.
- if !stackSet.contains(name) {
+ // If the name is not in the stack twice, this is not a cycle.
+ if !previousStackSet.contains(name) {
return
}
- // It is in the stack, so we just closed a cycle.
+ // It is in the stack twice, so we just closed a cycle.
// Identify the names involved in the cycle.
// Right now, the stack must have the current node there twice.
// Ignore everything before the first occurrence.
-
let cycleNodes = stack.drop(while: { $0.name != name })
- let cycleNames = Set(cycleNodes.map(\.name))
-
- // Check if any of the names are already boxed.
- if cycleNames.contains(where: { boxed.contains($0) }) {
- // Found one, so we know this cycle will already be broken.
- // No need to add any other type, just return from this
- // visit.
- return
- }
// We now choose which node will be marked as recursive.
// Only consider boxable nodes, trying from the start of the cycle.
guard let firstBoxable = cycleNodes.first(where: \.isBoxable) else {
throw RecursionError.invalidRecursion(name.description)
}
+ let nameToAdd = firstBoxable.name
+
+ // Check if we're already going to box this type, if so, we're done. | Is it worth checking if any of the boxable `cycleNodes` are already in `boxed`? |
swift-openapi-generator | github_2023 | others | 330 | apple | dnadoba | @@ -0,0 +1,130 @@
+# Supporting recursive types
+
+Learn how the generator supports recursive types.
+
+## Overview
+
+In some applications, the most expressive way to represent arbitrarily nested data is using a type that holds another value of itself, either directly, or through another type. We refer to such types as _recursive types_.
+
+By default, structs and enums do not support recursion in Swift, so the generator needs to detect recursion in the OpenAPI document and emit a different internal representation for the Swift types involved in recursion.
+
+This article discusses the details of what boxing is, and how the generator chooses the types to box.
+
+### Examples of recursive types
+
+One example of a recursive type would be a file system item, representing a tree. The `FileItem` node contains more `FileItem` nodes in an array.
+
+```yaml
+FileItem:
+ type: object
+ properties:
+ name:
+ type: string
+ isDirectory:
+ type: boolean
+ contents:
+ type: array
+ items:
+ $ref: '#/components/schemas/FileItem'
+ required:
+ - name
+```
+
+Another example would be a `Person` type, that can have a `partner` property of type `Person`.
+
+```yaml
+Person:
+ type: object
+ properties:
+ name:
+ type: string
+ partner:
+ $ref: '#/components/schemas/Person'
+ required:
+ - name
+```
+
+### Recursive types in Swift
+
+In Swift, the generator emits structs or enums for JSON schemas that support recursion (enums for `oneOf`, structs for `object`, `allOf`, and `anyOf`). Both structs and enums require that their size is known at compile time, however for arbitrarily nested values, such as a file system hierarchy, it cannot be known at compile time how deep the nesting goes. If such types were generated naively, they would not compile.
+
+To allow recursion, a _reference_ Swift type must be involved in the reference cycle (as opposed to only _value_ types). We call this technique of using a reference type for storage inside a value type "boxing" and it allows for the outer type to keep its original API, including value semantics, but at the same time be used as a recursive type.
+
+### Boxing different Swift types
+
+- Enums can be boxed by adding the `indirect` keyword to the declaration, for example by changing:
+
+```swift
+public enum Directory {}
+```
+
+to:
+
+```swift
+public indirect enum Directory { ... }
+```
+
+When an enum type needs to be boxed, the generator simply includes the `indirect` keyword in the generated type.
+
+- Structs require more work, including:
+ - Moving the stored properties into a private `final class Storage` type.
+ - Adding an explicit setter and getter for each property that calls into the storage.
+ - Adjusting the initializer to forward the initial values to the storage.
+ - Using a copy-on-write wrapper for the storage to avoid creating copies unless multiple references exist to the value and it's being modified.
+
+For example, the original struct:
+```swift
+public struct Person {
+ public var partner: Person?
+ public init(partner: Person? = nil) {
+ self.partner = partner
+ }
+}
+```
+
+Would look like this when boxed:
+```swift
+public struct Person {
+ public var partner: Person? {
+ set { CopyOnWriteBox.write(to: &storage) { $0.partner = newValue }}
+ get { storage.read().partner } | You will very likely need a `_modify` accessor here to not always trigger copy on write if mutated. |
swift-openapi-generator | github_2023 | others | 330 | apple | dnadoba | @@ -0,0 +1,204 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+/// A set of specialized types for using the recursion detector for
+/// declarations.
+struct DeclarationRecursionDetector {
+
+ /// A node for a pair of a Swift type name and a corresponding declaration.
+ struct Node: TypeNode, Equatable {
+
+ /// The type of the name is a string.
+ typealias NameType = String
+
+ /// The name of the node.
+ var name: NameType
+
+ /// Whether the type can be boxed.
+ var isBoxable: Bool
+
+ /// The names of nodes pointed to by this node.
+ var edges: [NameType]
+
+ /// The declaration represented by this node.
+ var decl: Declaration
+
+ /// Creates a new node.
+ /// - Parameters:
+ /// - name: The name of the node.
+ /// - isBoxable: Whether the type can be boxed.
+ /// - edges: The names of nodes pointed to by this node.
+ /// - decl: The declaration represented by this node.
+ private init(name: NameType, isBoxable: Bool, edges: [NameType], decl: Declaration) {
+ self.name = name
+ self.isBoxable = isBoxable
+ self.edges = edges
+ self.decl = decl
+ }
+
+ /// Creates a new node from the provided declaration.
+ ///
+ /// Returns nil when the declaration is missing a name.
+ /// - Parameter decl: A declaration.
+ init?(_ decl: Declaration) {
+ guard let name = decl.name else {
+ return nil
+ }
+ let edges = decl.schemaComponentNamesOfUnbreakableReferences
+ self.init(
+ name: name,
+ isBoxable: decl.isBoxable,
+ edges: edges,
+ decl: decl
+ )
+ }
+ }
+
+ /// A container for declarations.
+ struct Container: TypeNodeContainer {
+
+ /// The type of the node.
+ typealias Node = DeclarationRecursionDetector.Node
+
+ /// An error thrown by the container.
+ enum ContainerError: Swift.Error {
+
+ /// The node for the provided name was not found.
+ case nodeNotFound(Node.NameType)
+ }
+
+ /// The lookup map from the name to the node.
+ var lookupMap: [String: Node]
+
+ func lookup(_ name: String) throws -> DeclarationRecursionDetector.Node {
+ guard let node = lookupMap[name] else {
+ throw ContainerError.nodeNotFound(name)
+ }
+ return node
+ }
+ }
+}
+
+extension Declaration {
+
+ /// A name of the declaration, if it has one.
+ var name: String? {
+ switch self {
+ case .struct(let desc):
+ return desc.name
+ case .enum(let desc):
+ return desc.name
+ case .typealias(let desc):
+ return desc.name
+ case .commentable(_, let decl), .deprecated(_, let decl):
+ return decl.name
+ case .variable, .extension, .protocol, .function, .enumCase:
+ return nil
+ }
+ }
+
+ /// A Boolean value representing whether this declaration can be boxed.
+ var isBoxable: Bool {
+ switch self {
+ case .struct, .enum:
+ return true
+ case .commentable(_, let decl), .deprecated(_, let decl):
+ return decl.isBoxable
+ case .typealias, .variable, .extension, .protocol, .function, .enumCase:
+ return false
+ }
+ }
+
+ /// An array of names that can be found in `#/components/schemas` in
+ /// the OpenAPI document that represent references that can cause
+ /// a reference cycle.
+ var schemaComponentNamesOfUnbreakableReferences: [String] {
+ switch self {
+ case .struct(let desc):
+ return desc
+ .members
+ .compactMap { (member) -> [String]? in
+ switch member.strippingTopComment {
+ case .variable, // A reference to a reusable type.
+ .struct, .enum: // An inline type.
+ return member.schemaComponentNamesOfUnbreakableReferences
+ default:
+ return nil
+ }
+ }
+ .flatMap { $0 }
+ case .enum(let desc):
+ return desc
+ .members
+ .compactMap { (member) -> [String]? in
+ guard case .enumCase = member.strippingTopComment else {
+ return nil
+ }
+ return member
+ .schemaComponentNamesOfUnbreakableReferences
+ }
+ .flatMap { $0 }
+ case .commentable(_, let decl), .deprecated(_, let decl):
+ return decl
+ .schemaComponentNamesOfUnbreakableReferences
+ case .typealias(let desc):
+ return desc
+ .existingType
+ .referencedSchemaComponentName
+ .map { [$0] } ?? []
+ case .variable(let desc):
+ return desc.type?.referencedSchemaComponentName.map { [$0] } ?? []
+ case .enumCase(let desc):
+ switch desc.kind {
+ case .nameWithAssociatedValues(let values):
+ return values.compactMap { $0.type.referencedSchemaComponentName }
+ default:
+ return []
+ }
+ case .extension, .protocol, .function:
+ return []
+ }
+ }
+}
+
+fileprivate extension Array where Element == String { | FWIW this can now also be written as `extension Array<String> { ... }` or even `extension [String] { ... }` but that's just a matter of style. |
swift-openapi-generator | github_2023 | others | 331 | apple | czechboy0 | @@ -44,9 +44,11 @@ class FileBasedReferenceTests: XCTestCase {
#endif
}
- func testPetstore() throws {
- try _test(referenceProject: .init(name: .petstore))
- }
+ #if canImport(SwiftSyntax509)
+ func testPetstore() throws {
+ try _test(referenceProject: .init(name: .petstore))
+ } | One more thing - to avoid silently not running the test, can you put the #if into the function and in the #else just fail with a descriptive message? Once this lands, nobody should be running tests of this package with the 5.8 version of the dependencies. |
swift-openapi-generator | github_2023 | others | 319 | apple | czechboy0 | @@ -0,0 +1,76 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+@preconcurrency import OpenAPIKit
+
+/// Rules used to filter an OpenAPI document.
+///
+/// - Todo: Add endpoint support | Still relevant TODO? |
swift-openapi-generator | github_2023 | others | 319 | apple | czechboy0 | @@ -0,0 +1,76 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+@preconcurrency import OpenAPIKit
+
+/// Rules used to filter an OpenAPI document.
+///
+/// - Todo: Add endpoint support
+public struct DocumentFilter: Codable, Sendable { | Might be enough as `Decodable`? |
swift-openapi-generator | github_2023 | others | 319 | apple | czechboy0 | @@ -0,0 +1,76 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+@preconcurrency import OpenAPIKit
+
+/// Rules used to filter an OpenAPI document.
+///
+/// - Todo: Add endpoint support
+public struct DocumentFilter: Codable, Sendable {
+
+ /// Operations with these operation IDs will be included in the filter.
+ public var operations: [String]?
+
+ /// Operations tagged with these tags will be included in the filter.
+ public var tags: [String]?
+
+ /// These paths will be included in the filter.
+ public var paths: [OpenAPI.Path]? | Is there extra validation in the decoder of OpenAPI.Path we want to take advantage of? Or should we just make this a String? |
swift-openapi-generator | github_2023 | others | 319 | apple | czechboy0 | @@ -0,0 +1,76 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+@preconcurrency import OpenAPIKit
+
+/// Rules used to filter an OpenAPI document.
+///
+/// - Todo: Add endpoint support
+public struct DocumentFilter: Codable, Sendable {
+
+ /// Operations with these operation IDs will be included in the filter.
+ public var operations: [String]?
+
+ /// Operations tagged with these tags will be included in the filter.
+ public var tags: [String]?
+
+ /// These paths will be included in the filter.
+ public var paths: [OpenAPI.Path]?
+
+ /// These (additional) schemas will be included in the filter.
+ ///
+ /// These schemas are included in addition to the transitive closure of schema dependencies of
+ /// the paths included in the filter.
+ public var schemas: [String]?
+
+ /// Create a new DocumentFilter.
+ ///
+ /// - Parameters:
+ /// - operations: Operations with these IDs will be included in the filter.
+ /// - tags: Operations tagged with these tags will be included in the filter.
+ /// - paths: These paths will be included in the filter.
+ /// - schemas: These (additional) schemas will be included in the filter.
+ public init(
+ operations: [String] = [], | Is there a distinction between an empty array and a nil array? Naively, I'd expect a nil array to mean "don't filter using this axis, aka keep everything", versus an empty array, which I'd understand as "filter out everything". |
swift-openapi-generator | github_2023 | others | 319 | apple | czechboy0 | @@ -0,0 +1,485 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+@preconcurrency import OpenAPIKit
+
+/// Filter the paths and components of an OpenAPI document.
+///
+/// The builder starts with an empty filter, which will return the underlying document, but empty
+/// paths and components maps.
+///
+/// Desired paths and/or named schemas are included by calling the `requireXXX` methods.
+///
+/// When adding a path to the filter, the transitive closure of all referenced components are also
+/// included in the filtered document.
+public struct FilteredDocumentBuilder {
+
+ /// The underlying OpenAPI document to filter.
+ private(set) var document: OpenAPI.Document
+
+ private(set) var requiredPaths: Set<OpenAPI.Path>
+ private(set) var requiredPathItemReferences: Set<OpenAPI.Reference<OpenAPI.PathItem>>
+ private(set) var requiredSchemaReferences: Set<OpenAPI.Reference<JSONSchema>>
+ private(set) var requiredParameterReferences: Set<OpenAPI.Reference<OpenAPI.Parameter>>
+ private(set) var requiredHeaderReferences: Set<OpenAPI.Reference<OpenAPI.Header>>
+ private(set) var requiredResponseReferences: Set<OpenAPI.Reference<OpenAPI.Response>>
+ private(set) var requiredCallbacksReferences: Set<OpenAPI.Reference<OpenAPI.Callbacks>>
+ private(set) var requiredExampleReferences: Set<OpenAPI.Reference<OpenAPI.Example>>
+ private(set) var requiredLinkReferences: Set<OpenAPI.Reference<OpenAPI.Link>>
+ private(set) var requiredRequestReferences: Set<OpenAPI.Reference<OpenAPI.Request>>
+ private(set) var requiredEndpoints: [OpenAPI.Path: Set<OpenAPI.HttpMethod>]
+
+ /// Create a new FilteredDocumentBuilder.
+ ///
+ /// - Parameter document: The underlying OpenAPI document to filter.
+ public init(document: OpenAPI.Document) {
+ self.document = document
+ self.requiredPaths = []
+ self.requiredPathItemReferences = []
+ self.requiredSchemaReferences = []
+ self.requiredParameterReferences = []
+ self.requiredHeaderReferences = []
+ self.requiredResponseReferences = []
+ self.requiredCallbacksReferences = []
+ self.requiredExampleReferences = []
+ self.requiredLinkReferences = []
+ self.requiredRequestReferences = []
+ self.requiredEndpoints = [:]
+ }
+
+ /// Filter the underlying document based on the rules provided.
+ ///
+ /// - Returns: The filtered OpenAPI document.
+ public func filter() throws -> OpenAPI.Document {
+ var components = OpenAPI.Components.noComponents
+ for reference in requiredSchemaReferences {
+ components.schemas[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredPathItemReferences {
+ components.pathItems[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredParameterReferences {
+ components.parameters[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredHeaderReferences {
+ components.headers[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredResponseReferences {
+ components.responses[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredCallbacksReferences {
+ components.callbacks[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredExampleReferences {
+ components.examples[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredLinkReferences {
+ components.links[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredRequestReferences {
+ components.requestBodies[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ var filteredDocument = document.filteringPaths(with: requiredPaths.contains(_:))
+ for (path, methods) in requiredEndpoints {
+ if filteredDocument.paths.contains(key: path) {
+ continue
+ }
+ guard let maybeReference = document.paths[path] else {
+ continue
+ }
+ switch maybeReference {
+ case .a(let reference):
+ components.pathItems[try reference.internalComponentKey] = try document.components.lookup(reference)
+ .filteringEndpoints { methods.contains($0.method) }
+ case .b(let pathItem):
+ filteredDocument.paths[path] = .b(pathItem.filteringEndpoints { methods.contains($0.method) })
+ }
+ }
+ filteredDocument.components = components
+ return filteredDocument
+ }
+
+ /// Include a path (and all its component dependencies).
+ ///
+ /// The path is added to the filter, along with the transitive closure of all components
+ /// referenced within the corresponding path item.
+ ///
+ /// - Parameter path: The path to be included in the filter.
+ public mutating func requirePath(_ path: OpenAPI.Path) throws { | Super small nit, I find the word "include" a bit clearer than "require" here. Especially if we might add "exclude" down the line. |
swift-openapi-generator | github_2023 | others | 319 | apple | czechboy0 | @@ -0,0 +1,485 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+@preconcurrency import OpenAPIKit
+
+/// Filter the paths and components of an OpenAPI document.
+///
+/// The builder starts with an empty filter, which will return the underlying document, but empty
+/// paths and components maps.
+///
+/// Desired paths and/or named schemas are included by calling the `requireXXX` methods.
+///
+/// When adding a path to the filter, the transitive closure of all referenced components are also
+/// included in the filtered document.
+public struct FilteredDocumentBuilder {
+
+ /// The underlying OpenAPI document to filter.
+ private(set) var document: OpenAPI.Document
+
+ private(set) var requiredPaths: Set<OpenAPI.Path>
+ private(set) var requiredPathItemReferences: Set<OpenAPI.Reference<OpenAPI.PathItem>>
+ private(set) var requiredSchemaReferences: Set<OpenAPI.Reference<JSONSchema>>
+ private(set) var requiredParameterReferences: Set<OpenAPI.Reference<OpenAPI.Parameter>>
+ private(set) var requiredHeaderReferences: Set<OpenAPI.Reference<OpenAPI.Header>>
+ private(set) var requiredResponseReferences: Set<OpenAPI.Reference<OpenAPI.Response>>
+ private(set) var requiredCallbacksReferences: Set<OpenAPI.Reference<OpenAPI.Callbacks>>
+ private(set) var requiredExampleReferences: Set<OpenAPI.Reference<OpenAPI.Example>>
+ private(set) var requiredLinkReferences: Set<OpenAPI.Reference<OpenAPI.Link>>
+ private(set) var requiredRequestReferences: Set<OpenAPI.Reference<OpenAPI.Request>>
+ private(set) var requiredEndpoints: [OpenAPI.Path: Set<OpenAPI.HttpMethod>]
+
+ /// Create a new FilteredDocumentBuilder.
+ ///
+ /// - Parameter document: The underlying OpenAPI document to filter.
+ public init(document: OpenAPI.Document) {
+ self.document = document
+ self.requiredPaths = []
+ self.requiredPathItemReferences = []
+ self.requiredSchemaReferences = []
+ self.requiredParameterReferences = []
+ self.requiredHeaderReferences = []
+ self.requiredResponseReferences = []
+ self.requiredCallbacksReferences = []
+ self.requiredExampleReferences = []
+ self.requiredLinkReferences = []
+ self.requiredRequestReferences = []
+ self.requiredEndpoints = [:]
+ }
+
+ /// Filter the underlying document based on the rules provided.
+ ///
+ /// - Returns: The filtered OpenAPI document.
+ public func filter() throws -> OpenAPI.Document {
+ var components = OpenAPI.Components.noComponents
+ for reference in requiredSchemaReferences {
+ components.schemas[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredPathItemReferences {
+ components.pathItems[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredParameterReferences {
+ components.parameters[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredHeaderReferences {
+ components.headers[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredResponseReferences {
+ components.responses[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredCallbacksReferences {
+ components.callbacks[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredExampleReferences {
+ components.examples[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredLinkReferences {
+ components.links[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredRequestReferences {
+ components.requestBodies[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ var filteredDocument = document.filteringPaths(with: requiredPaths.contains(_:))
+ for (path, methods) in requiredEndpoints {
+ if filteredDocument.paths.contains(key: path) {
+ continue
+ }
+ guard let maybeReference = document.paths[path] else {
+ continue
+ }
+ switch maybeReference {
+ case .a(let reference):
+ components.pathItems[try reference.internalComponentKey] = try document.components.lookup(reference)
+ .filteringEndpoints { methods.contains($0.method) }
+ case .b(let pathItem):
+ filteredDocument.paths[path] = .b(pathItem.filteringEndpoints { methods.contains($0.method) })
+ }
+ }
+ filteredDocument.components = components
+ return filteredDocument
+ }
+
+ /// Include a path (and all its component dependencies).
+ ///
+ /// The path is added to the filter, along with the transitive closure of all components
+ /// referenced within the corresponding path item.
+ ///
+ /// - Parameter path: The path to be included in the filter.
+ public mutating func requirePath(_ path: OpenAPI.Path) throws {
+ guard let pathItem = document.paths[path] else {
+ throw FilteredDocumentBuilderError.pathDoesNotExist(path)
+ }
+ guard requiredPaths.insert(path).inserted else { return }
+ try requirePathItem(pathItem)
+ }
+
+ /// Include operations that have a given tag (and all their component dependencies).
+ ///
+ /// Because tags are applied to operations (cf. paths), this may result in paths within filtered
+ /// document with a subset of the operations defined in the original document.
+ ///
+ /// - Parameter tag: The tag to use to include operations (and their paths).
+ public mutating func requireOperations(tagged tag: String) throws {
+ guard document.allTags.contains(tag) else {
+ throw FilteredDocumentBuilderError.tagDoesNotExist(tag)
+ }
+ try requireOperations { endpoint in endpoint.operation.tags?.contains(tag) ?? false }
+ }
+
+ /// Include operations that have a given tag (and all their component dependencies).
+ ///
+ /// Because tags are applied to operations (cf. paths), this may result in paths within filtered
+ /// document with a subset of the operations defined in the original document.
+ ///
+ /// - Parameter tag: The tag by which to include operations (and their paths).
+ public mutating func requireOperations(tagged tag: OpenAPI.Tag) throws {
+ try requireOperations(tagged: tag.name)
+ }
+
+ /// Include the operation with a given ID (and all its component dependencies).
+ ///
+ /// This may result in paths within filtered document with a subset of the operations defined
+ /// in the original document.
+ ///
+ /// - Parameter operationID: The operation to include (and its path).
+ public mutating func requireOperation(operationID: String) throws {
+ guard document.allOperationIds.contains(operationID) else {
+ throw FilteredDocumentBuilderError.operationDoesNotExist(operationID: operationID) | Very good call, will ensure adopters don't make a typo in their operation id and then spend time debugging why their operation isn't showing up.
I wonder if we should somehow "consume" all the other filters as well, and throw an error if you're trying to include something that doesn't exist in the document? Not crucial, but would make debugging a lot easier, especially since this is all stringly programming from the config file, without any autocompletion or validation. |
swift-openapi-generator | github_2023 | others | 319 | apple | czechboy0 | @@ -0,0 +1,485 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+@preconcurrency import OpenAPIKit
+
+/// Filter the paths and components of an OpenAPI document.
+///
+/// The builder starts with an empty filter, which will return the underlying document, but empty
+/// paths and components maps.
+///
+/// Desired paths and/or named schemas are included by calling the `requireXXX` methods.
+///
+/// When adding a path to the filter, the transitive closure of all referenced components are also
+/// included in the filtered document.
+public struct FilteredDocumentBuilder {
+
+ /// The underlying OpenAPI document to filter.
+ private(set) var document: OpenAPI.Document
+
+ private(set) var requiredPaths: Set<OpenAPI.Path>
+ private(set) var requiredPathItemReferences: Set<OpenAPI.Reference<OpenAPI.PathItem>>
+ private(set) var requiredSchemaReferences: Set<OpenAPI.Reference<JSONSchema>>
+ private(set) var requiredParameterReferences: Set<OpenAPI.Reference<OpenAPI.Parameter>>
+ private(set) var requiredHeaderReferences: Set<OpenAPI.Reference<OpenAPI.Header>>
+ private(set) var requiredResponseReferences: Set<OpenAPI.Reference<OpenAPI.Response>>
+ private(set) var requiredCallbacksReferences: Set<OpenAPI.Reference<OpenAPI.Callbacks>>
+ private(set) var requiredExampleReferences: Set<OpenAPI.Reference<OpenAPI.Example>>
+ private(set) var requiredLinkReferences: Set<OpenAPI.Reference<OpenAPI.Link>>
+ private(set) var requiredRequestReferences: Set<OpenAPI.Reference<OpenAPI.Request>>
+ private(set) var requiredEndpoints: [OpenAPI.Path: Set<OpenAPI.HttpMethod>]
+
+ /// Create a new FilteredDocumentBuilder.
+ ///
+ /// - Parameter document: The underlying OpenAPI document to filter.
+ public init(document: OpenAPI.Document) {
+ self.document = document
+ self.requiredPaths = []
+ self.requiredPathItemReferences = []
+ self.requiredSchemaReferences = []
+ self.requiredParameterReferences = []
+ self.requiredHeaderReferences = []
+ self.requiredResponseReferences = []
+ self.requiredCallbacksReferences = []
+ self.requiredExampleReferences = []
+ self.requiredLinkReferences = []
+ self.requiredRequestReferences = []
+ self.requiredEndpoints = [:]
+ }
+
+ /// Filter the underlying document based on the rules provided.
+ ///
+ /// - Returns: The filtered OpenAPI document.
+ public func filter() throws -> OpenAPI.Document {
+ var components = OpenAPI.Components.noComponents
+ for reference in requiredSchemaReferences {
+ components.schemas[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredPathItemReferences {
+ components.pathItems[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredParameterReferences {
+ components.parameters[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredHeaderReferences {
+ components.headers[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredResponseReferences {
+ components.responses[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredCallbacksReferences {
+ components.callbacks[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredExampleReferences {
+ components.examples[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredLinkReferences {
+ components.links[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredRequestReferences {
+ components.requestBodies[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ var filteredDocument = document.filteringPaths(with: requiredPaths.contains(_:))
+ for (path, methods) in requiredEndpoints {
+ if filteredDocument.paths.contains(key: path) {
+ continue
+ }
+ guard let maybeReference = document.paths[path] else {
+ continue
+ }
+ switch maybeReference {
+ case .a(let reference):
+ components.pathItems[try reference.internalComponentKey] = try document.components.lookup(reference)
+ .filteringEndpoints { methods.contains($0.method) }
+ case .b(let pathItem):
+ filteredDocument.paths[path] = .b(pathItem.filteringEndpoints { methods.contains($0.method) })
+ }
+ }
+ filteredDocument.components = components
+ return filteredDocument
+ }
+
+ /// Include a path (and all its component dependencies).
+ ///
+ /// The path is added to the filter, along with the transitive closure of all components
+ /// referenced within the corresponding path item.
+ ///
+ /// - Parameter path: The path to be included in the filter.
+ public mutating func requirePath(_ path: OpenAPI.Path) throws {
+ guard let pathItem = document.paths[path] else {
+ throw FilteredDocumentBuilderError.pathDoesNotExist(path)
+ }
+ guard requiredPaths.insert(path).inserted else { return }
+ try requirePathItem(pathItem)
+ }
+
+ /// Include operations that have a given tag (and all their component dependencies).
+ ///
+ /// Because tags are applied to operations (cf. paths), this may result in paths within filtered
+ /// document with a subset of the operations defined in the original document.
+ ///
+ /// - Parameter tag: The tag to use to include operations (and their paths).
+ public mutating func requireOperations(tagged tag: String) throws {
+ guard document.allTags.contains(tag) else {
+ throw FilteredDocumentBuilderError.tagDoesNotExist(tag)
+ }
+ try requireOperations { endpoint in endpoint.operation.tags?.contains(tag) ?? false }
+ }
+
+ /// Include operations that have a given tag (and all their component dependencies).
+ ///
+ /// Because tags are applied to operations (cf. paths), this may result in paths within filtered
+ /// document with a subset of the operations defined in the original document.
+ ///
+ /// - Parameter tag: The tag by which to include operations (and their paths).
+ public mutating func requireOperations(tagged tag: OpenAPI.Tag) throws {
+ try requireOperations(tagged: tag.name)
+ }
+
+ /// Include the operation with a given ID (and all its component dependencies).
+ ///
+ /// This may result in paths within filtered document with a subset of the operations defined
+ /// in the original document.
+ ///
+ /// - Parameter operationID: The operation to include (and its path).
+ public mutating func requireOperation(operationID: String) throws {
+ guard document.allOperationIds.contains(operationID) else {
+ throw FilteredDocumentBuilderError.operationDoesNotExist(operationID: operationID)
+ }
+ try requireOperations { endpoint in endpoint.operation.operationId == operationID }
+ }
+
+ /// Include schema (and all its schema dependencies).
+ ///
+ /// The schema is added to the filter, along with the transitive closure of all other schemas
+ /// it references.
+ ///
+ /// - Parameter name: The key in the `#/components/schemas` map in the OpenAPI document.
+ public mutating func requireSchema(_ name: String) throws {
+ try requireSchema(.a(OpenAPI.Reference<JSONSchema>.component(named: name)))
+ }
+}
+
+enum FilteredDocumentBuilderError: Error, LocalizedError {
+ case pathDoesNotExist(OpenAPI.Path)
+ case tagDoesNotExist(String)
+ case operationDoesNotExist(operationID: String)
+ case cannotResolveInternalReference(String)
+
+ var errorDescription: String? {
+ switch self {
+ case .pathDoesNotExist(let path):
+ return "Required path does not exist in OpenAPI document: \(path)"
+ case .tagDoesNotExist(let tag):
+ return "Required tag does not exist in OpenAPI document: \(tag)"
+ case .operationDoesNotExist(let operationID):
+ return "Required operation does not exist in OpenAPI document: \(operationID)"
+ case .cannotResolveInternalReference(let reference):
+ return "Cannot resolve reference; not local reference to component: \(reference)"
+ }
+ }
+}
+
+private extension FilteredDocumentBuilder {
+ mutating func requirePathItem(_ maybeReference: Either<OpenAPI.Reference<OpenAPI.PathItem>, OpenAPI.PathItem>)
+ throws
+ {
+ switch maybeReference {
+ case .a(let reference):
+ guard requiredPathItemReferences.insert(reference).inserted else { return }
+ try addComponentsReferencedBy(try document.components.lookup(reference))
+ case .b(let value):
+ try addComponentsReferencedBy(value)
+ }
+ }
+
+ mutating func requireSchema(_ maybeReference: Either<OpenAPI.Reference<JSONSchema>, JSONSchema>) throws {
+ switch maybeReference {
+ case .a(let reference):
+ guard requiredSchemaReferences.insert(reference).inserted else { return }
+ try addComponentsReferencedBy(try document.components.lookup(reference))
+ case .b(let value):
+ try addComponentsReferencedBy(value)
+ }
+ }
+
+ mutating func requireParameter(_ maybeReference: Either<OpenAPI.Reference<OpenAPI.Parameter>, OpenAPI.Parameter>)
+ throws
+ {
+ switch maybeReference {
+ case .a(let reference):
+ guard requiredParameterReferences.insert(reference).inserted else { return }
+ try addComponentsReferencedBy(try document.components.lookup(reference))
+ case .b(let value):
+ try addComponentsReferencedBy(value)
+ }
+ }
+
+ mutating func requireResponse(_ maybeReference: Either<OpenAPI.Reference<OpenAPI.Response>, OpenAPI.Response>)
+ throws
+ {
+ switch maybeReference {
+ case .a(let reference):
+ guard requiredResponseReferences.insert(reference).inserted else { return }
+ try addComponentsReferencedBy(try document.components.lookup(reference))
+ case .b(let value):
+ try addComponentsReferencedBy(value)
+ }
+ }
+
+ mutating func requireHeader(_ maybeReference: Either<OpenAPI.Reference<OpenAPI.Header>, OpenAPI.Header>) throws {
+ switch maybeReference {
+ case .a(let reference):
+ guard requiredHeaderReferences.insert(reference).inserted else { return }
+ try addComponentsReferencedBy(try document.components.lookup(reference))
+ case .b(let value):
+ try addComponentsReferencedBy(value)
+ }
+ }
+
+ mutating func requireLink(_ maybeReference: Either<OpenAPI.Reference<OpenAPI.Link>, OpenAPI.Link>) throws {
+ switch maybeReference {
+ case .a(let reference):
+ guard requiredLinkReferences.insert(reference).inserted else { return }
+ try addComponentsReferencedBy(try document.components.lookup(reference))
+ case .b(let value):
+ try addComponentsReferencedBy(value)
+ }
+ }
+
+ mutating func requireCallbacks(_ maybeReference: Either<OpenAPI.Reference<OpenAPI.Callbacks>, OpenAPI.Callbacks>)
+ throws
+ {
+ switch maybeReference {
+ case .a(let reference):
+ guard requiredCallbacksReferences.insert(reference).inserted else { return }
+ try addComponentsReferencedBy(try document.components.lookup(reference))
+ case .b(let value):
+ try addComponentsReferencedBy(value)
+ }
+ }
+
+ mutating func requireRequestBody(_ maybeReference: Either<OpenAPI.Reference<OpenAPI.Request>, OpenAPI.Request>)
+ throws
+ {
+ switch maybeReference {
+ case .a(let reference):
+ guard requiredRequestReferences.insert(reference).inserted else { return }
+ try addComponentsReferencedBy(try document.components.lookup(reference))
+ case .b(let value):
+ try addComponentsReferencedBy(value)
+ }
+ }
+
+ mutating func requireExample(_ maybeReference: Either<OpenAPI.Reference<OpenAPI.Example>, OpenAPI.Example>) throws {
+ switch maybeReference {
+ case .a(let reference):
+ guard requiredExampleReferences.insert(reference).inserted else { return }
+ try addComponentsReferencedBy(try document.components.lookup(reference))
+ case .b(let value):
+ try addComponentsReferencedBy(value)
+ }
+ }
+
+ mutating func requireOperations(where predicate: (OpenAPI.PathItem.Endpoint) -> Bool) throws {
+ for (path, maybePathItemReference) in document.paths {
+ let originalPathItem: OpenAPI.PathItem
+ switch maybePathItemReference {
+ case .a(let reference):
+ originalPathItem = try document.components.lookup(reference)
+ case .b(let pathItem):
+ originalPathItem = pathItem
+ }
+
+ for endpoint in originalPathItem.endpoints {
+ guard predicate(endpoint) else {
+ continue
+ }
+ if requiredEndpoints[path] == nil {
+ requiredEndpoints[path] = Set()
+ }
+ if requiredEndpoints[path]!.insert(endpoint.method).inserted {
+ try addComponentsReferencedBy(endpoint.operation)
+ }
+ }
+ }
+ }
+}
+
+private extension FilteredDocumentBuilder {
+
+ mutating func addComponentsReferencedBy(_ pathItem: OpenAPI.PathItem) throws {
+ for endpoint in pathItem.endpoints {
+ try addComponentsReferencedBy(endpoint.operation)
+ }
+ for parameter in pathItem.parameters {
+ try requireParameter(parameter)
+ }
+ }
+
+ mutating func addComponentsReferencedBy(_ operation: OpenAPI.Operation) throws {
+ for parameter in operation.parameters {
+ try requireParameter(parameter)
+ }
+ for response in operation.responses.values {
+ try requireResponse(response)
+ }
+ if let requestBody = operation.requestBody {
+ try requireRequestBody(requestBody)
+ }
+ for callbacks in operation.callbacks.values {
+ try requireCallbacks(callbacks)
+ }
+ }
+
+ mutating func addComponentsReferencedBy(_ request: OpenAPI.Request) throws {
+ for content in request.content.values {
+ try addComponentsReferencedBy(content)
+ }
+ }
+ mutating func addComponentsReferencedBy(_ callbacks: OpenAPI.Callbacks) throws {
+ for pathItem in callbacks.values {
+ try requirePathItem(pathItem)
+ }
+ }
+
+ mutating func addComponentsReferencedBy(_ schema: JSONSchema) throws {
+ switch schema.value {
+
+ case .reference(let reference, _):
+ guard requiredSchemaReferences.insert(OpenAPI.Reference(reference)).inserted else { return }
+ try addComponentsReferencedBy(document.components.lookup(reference))
+
+ case .object(_, let object):
+ for schema in object.properties.values {
+ try addComponentsReferencedBy(schema)
+ }
+ if case .b(let schema) = object.additionalProperties {
+ try addComponentsReferencedBy(schema)
+ }
+
+ case .array(_, let array):
+ if let schema = array.items {
+ try addComponentsReferencedBy(schema)
+ }
+
+ case .not(let schema, _):
+ try addComponentsReferencedBy(schema)
+
+ case .all(of: let schemas, _): fallthrough
+ case .one(of: let schemas, _): fallthrough
+ case .any(of: let schemas, _): | ```suggestion
case .all(of: let schemas, _), .one(of: let schemas, _), .any(of: let schemas, _):
```
Does the same thing and avoids the scary fallthrough π |
swift-openapi-generator | github_2023 | others | 319 | apple | czechboy0 | @@ -0,0 +1,485 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+@preconcurrency import OpenAPIKit
+
+/// Filter the paths and components of an OpenAPI document.
+///
+/// The builder starts with an empty filter, which will return the underlying document, but empty
+/// paths and components maps.
+///
+/// Desired paths and/or named schemas are included by calling the `requireXXX` methods.
+///
+/// When adding a path to the filter, the transitive closure of all referenced components are also
+/// included in the filtered document.
+public struct FilteredDocumentBuilder {
+
+ /// The underlying OpenAPI document to filter.
+ private(set) var document: OpenAPI.Document
+
+ private(set) var requiredPaths: Set<OpenAPI.Path>
+ private(set) var requiredPathItemReferences: Set<OpenAPI.Reference<OpenAPI.PathItem>>
+ private(set) var requiredSchemaReferences: Set<OpenAPI.Reference<JSONSchema>>
+ private(set) var requiredParameterReferences: Set<OpenAPI.Reference<OpenAPI.Parameter>>
+ private(set) var requiredHeaderReferences: Set<OpenAPI.Reference<OpenAPI.Header>>
+ private(set) var requiredResponseReferences: Set<OpenAPI.Reference<OpenAPI.Response>>
+ private(set) var requiredCallbacksReferences: Set<OpenAPI.Reference<OpenAPI.Callbacks>>
+ private(set) var requiredExampleReferences: Set<OpenAPI.Reference<OpenAPI.Example>>
+ private(set) var requiredLinkReferences: Set<OpenAPI.Reference<OpenAPI.Link>>
+ private(set) var requiredRequestReferences: Set<OpenAPI.Reference<OpenAPI.Request>>
+ private(set) var requiredEndpoints: [OpenAPI.Path: Set<OpenAPI.HttpMethod>]
+
+ /// Create a new FilteredDocumentBuilder.
+ ///
+ /// - Parameter document: The underlying OpenAPI document to filter.
+ public init(document: OpenAPI.Document) {
+ self.document = document
+ self.requiredPaths = []
+ self.requiredPathItemReferences = []
+ self.requiredSchemaReferences = []
+ self.requiredParameterReferences = []
+ self.requiredHeaderReferences = []
+ self.requiredResponseReferences = []
+ self.requiredCallbacksReferences = []
+ self.requiredExampleReferences = []
+ self.requiredLinkReferences = []
+ self.requiredRequestReferences = []
+ self.requiredEndpoints = [:]
+ }
+
+ /// Filter the underlying document based on the rules provided.
+ ///
+ /// - Returns: The filtered OpenAPI document.
+ public func filter() throws -> OpenAPI.Document {
+ var components = OpenAPI.Components.noComponents
+ for reference in requiredSchemaReferences {
+ components.schemas[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredPathItemReferences {
+ components.pathItems[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredParameterReferences {
+ components.parameters[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredHeaderReferences {
+ components.headers[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredResponseReferences {
+ components.responses[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredCallbacksReferences {
+ components.callbacks[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredExampleReferences {
+ components.examples[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredLinkReferences {
+ components.links[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ for reference in requiredRequestReferences {
+ components.requestBodies[try reference.internalComponentKey] = try document.components.lookup(reference)
+ }
+ var filteredDocument = document.filteringPaths(with: requiredPaths.contains(_:))
+ for (path, methods) in requiredEndpoints {
+ if filteredDocument.paths.contains(key: path) {
+ continue
+ }
+ guard let maybeReference = document.paths[path] else {
+ continue
+ }
+ switch maybeReference {
+ case .a(let reference):
+ components.pathItems[try reference.internalComponentKey] = try document.components.lookup(reference)
+ .filteringEndpoints { methods.contains($0.method) }
+ case .b(let pathItem):
+ filteredDocument.paths[path] = .b(pathItem.filteringEndpoints { methods.contains($0.method) })
+ }
+ }
+ filteredDocument.components = components
+ return filteredDocument
+ }
+
+ /// Include a path (and all its component dependencies).
+ ///
+ /// The path is added to the filter, along with the transitive closure of all components
+ /// referenced within the corresponding path item.
+ ///
+ /// - Parameter path: The path to be included in the filter.
+ public mutating func requirePath(_ path: OpenAPI.Path) throws {
+ guard let pathItem = document.paths[path] else {
+ throw FilteredDocumentBuilderError.pathDoesNotExist(path)
+ }
+ guard requiredPaths.insert(path).inserted else { return }
+ try requirePathItem(pathItem)
+ }
+
+ /// Include operations that have a given tag (and all their component dependencies).
+ ///
+ /// Because tags are applied to operations (cf. paths), this may result in paths within filtered
+ /// document with a subset of the operations defined in the original document.
+ ///
+ /// - Parameter tag: The tag to use to include operations (and their paths).
+ public mutating func requireOperations(tagged tag: String) throws {
+ guard document.allTags.contains(tag) else {
+ throw FilteredDocumentBuilderError.tagDoesNotExist(tag)
+ }
+ try requireOperations { endpoint in endpoint.operation.tags?.contains(tag) ?? false }
+ }
+
+ /// Include operations that have a given tag (and all their component dependencies).
+ ///
+ /// Because tags are applied to operations (cf. paths), this may result in paths within filtered
+ /// document with a subset of the operations defined in the original document.
+ ///
+ /// - Parameter tag: The tag by which to include operations (and their paths).
+ public mutating func requireOperations(tagged tag: OpenAPI.Tag) throws {
+ try requireOperations(tagged: tag.name)
+ }
+
+ /// Include the operation with a given ID (and all its component dependencies).
+ ///
+ /// This may result in paths within filtered document with a subset of the operations defined
+ /// in the original document.
+ ///
+ /// - Parameter operationID: The operation to include (and its path).
+ public mutating func requireOperation(operationID: String) throws {
+ guard document.allOperationIds.contains(operationID) else {
+ throw FilteredDocumentBuilderError.operationDoesNotExist(operationID: operationID)
+ }
+ try requireOperations { endpoint in endpoint.operation.operationId == operationID }
+ }
+
+ /// Include schema (and all its schema dependencies).
+ ///
+ /// The schema is added to the filter, along with the transitive closure of all other schemas
+ /// it references.
+ ///
+ /// - Parameter name: The key in the `#/components/schemas` map in the OpenAPI document.
+ public mutating func requireSchema(_ name: String) throws {
+ try requireSchema(.a(OpenAPI.Reference<JSONSchema>.component(named: name)))
+ }
+}
+
+enum FilteredDocumentBuilderError: Error, LocalizedError {
+ case pathDoesNotExist(OpenAPI.Path)
+ case tagDoesNotExist(String)
+ case operationDoesNotExist(operationID: String)
+ case cannotResolveInternalReference(String)
+
+ var errorDescription: String? {
+ switch self {
+ case .pathDoesNotExist(let path):
+ return "Required path does not exist in OpenAPI document: \(path)"
+ case .tagDoesNotExist(let tag):
+ return "Required tag does not exist in OpenAPI document: \(tag)"
+ case .operationDoesNotExist(let operationID):
+ return "Required operation does not exist in OpenAPI document: \(operationID)"
+ case .cannotResolveInternalReference(let reference):
+ return "Cannot resolve reference; not local reference to component: \(reference)"
+ }
+ }
+}
+
+private extension FilteredDocumentBuilder {
+ mutating func requirePathItem(_ maybeReference: Either<OpenAPI.Reference<OpenAPI.PathItem>, OpenAPI.PathItem>)
+ throws
+ {
+ switch maybeReference {
+ case .a(let reference):
+ guard requiredPathItemReferences.insert(reference).inserted else { return }
+ try addComponentsReferencedBy(try document.components.lookup(reference))
+ case .b(let value):
+ try addComponentsReferencedBy(value)
+ }
+ }
+
+ mutating func requireSchema(_ maybeReference: Either<OpenAPI.Reference<JSONSchema>, JSONSchema>) throws {
+ switch maybeReference {
+ case .a(let reference):
+ guard requiredSchemaReferences.insert(reference).inserted else { return }
+ try addComponentsReferencedBy(try document.components.lookup(reference))
+ case .b(let value):
+ try addComponentsReferencedBy(value)
+ }
+ }
+
+ mutating func requireParameter(_ maybeReference: Either<OpenAPI.Reference<OpenAPI.Parameter>, OpenAPI.Parameter>)
+ throws
+ {
+ switch maybeReference {
+ case .a(let reference):
+ guard requiredParameterReferences.insert(reference).inserted else { return }
+ try addComponentsReferencedBy(try document.components.lookup(reference))
+ case .b(let value):
+ try addComponentsReferencedBy(value)
+ }
+ }
+
+ mutating func requireResponse(_ maybeReference: Either<OpenAPI.Reference<OpenAPI.Response>, OpenAPI.Response>)
+ throws
+ {
+ switch maybeReference {
+ case .a(let reference):
+ guard requiredResponseReferences.insert(reference).inserted else { return }
+ try addComponentsReferencedBy(try document.components.lookup(reference))
+ case .b(let value):
+ try addComponentsReferencedBy(value)
+ }
+ }
+
+ mutating func requireHeader(_ maybeReference: Either<OpenAPI.Reference<OpenAPI.Header>, OpenAPI.Header>) throws {
+ switch maybeReference {
+ case .a(let reference):
+ guard requiredHeaderReferences.insert(reference).inserted else { return }
+ try addComponentsReferencedBy(try document.components.lookup(reference))
+ case .b(let value):
+ try addComponentsReferencedBy(value)
+ }
+ }
+
+ mutating func requireLink(_ maybeReference: Either<OpenAPI.Reference<OpenAPI.Link>, OpenAPI.Link>) throws {
+ switch maybeReference {
+ case .a(let reference):
+ guard requiredLinkReferences.insert(reference).inserted else { return }
+ try addComponentsReferencedBy(try document.components.lookup(reference))
+ case .b(let value):
+ try addComponentsReferencedBy(value)
+ }
+ }
+
+ mutating func requireCallbacks(_ maybeReference: Either<OpenAPI.Reference<OpenAPI.Callbacks>, OpenAPI.Callbacks>)
+ throws
+ {
+ switch maybeReference {
+ case .a(let reference):
+ guard requiredCallbacksReferences.insert(reference).inserted else { return }
+ try addComponentsReferencedBy(try document.components.lookup(reference))
+ case .b(let value):
+ try addComponentsReferencedBy(value)
+ }
+ }
+
+ mutating func requireRequestBody(_ maybeReference: Either<OpenAPI.Reference<OpenAPI.Request>, OpenAPI.Request>)
+ throws
+ {
+ switch maybeReference {
+ case .a(let reference):
+ guard requiredRequestReferences.insert(reference).inserted else { return }
+ try addComponentsReferencedBy(try document.components.lookup(reference))
+ case .b(let value):
+ try addComponentsReferencedBy(value)
+ }
+ }
+
+ mutating func requireExample(_ maybeReference: Either<OpenAPI.Reference<OpenAPI.Example>, OpenAPI.Example>) throws {
+ switch maybeReference {
+ case .a(let reference):
+ guard requiredExampleReferences.insert(reference).inserted else { return }
+ try addComponentsReferencedBy(try document.components.lookup(reference))
+ case .b(let value):
+ try addComponentsReferencedBy(value)
+ }
+ }
+
+ mutating func requireOperations(where predicate: (OpenAPI.PathItem.Endpoint) -> Bool) throws {
+ for (path, maybePathItemReference) in document.paths {
+ let originalPathItem: OpenAPI.PathItem
+ switch maybePathItemReference {
+ case .a(let reference):
+ originalPathItem = try document.components.lookup(reference)
+ case .b(let pathItem):
+ originalPathItem = pathItem
+ }
+
+ for endpoint in originalPathItem.endpoints {
+ guard predicate(endpoint) else {
+ continue
+ }
+ if requiredEndpoints[path] == nil {
+ requiredEndpoints[path] = Set()
+ }
+ if requiredEndpoints[path]!.insert(endpoint.method).inserted {
+ try addComponentsReferencedBy(endpoint.operation)
+ }
+ }
+ }
+ }
+}
+
+private extension FilteredDocumentBuilder {
+
+ mutating func addComponentsReferencedBy(_ pathItem: OpenAPI.PathItem) throws {
+ for endpoint in pathItem.endpoints {
+ try addComponentsReferencedBy(endpoint.operation)
+ }
+ for parameter in pathItem.parameters {
+ try requireParameter(parameter)
+ }
+ }
+
+ mutating func addComponentsReferencedBy(_ operation: OpenAPI.Operation) throws {
+ for parameter in operation.parameters {
+ try requireParameter(parameter)
+ }
+ for response in operation.responses.values {
+ try requireResponse(response)
+ }
+ if let requestBody = operation.requestBody {
+ try requireRequestBody(requestBody)
+ }
+ for callbacks in operation.callbacks.values {
+ try requireCallbacks(callbacks)
+ }
+ }
+
+ mutating func addComponentsReferencedBy(_ request: OpenAPI.Request) throws {
+ for content in request.content.values {
+ try addComponentsReferencedBy(content)
+ }
+ }
+ mutating func addComponentsReferencedBy(_ callbacks: OpenAPI.Callbacks) throws {
+ for pathItem in callbacks.values {
+ try requirePathItem(pathItem)
+ }
+ }
+
+ mutating func addComponentsReferencedBy(_ schema: JSONSchema) throws {
+ switch schema.value {
+
+ case .reference(let reference, _):
+ guard requiredSchemaReferences.insert(OpenAPI.Reference(reference)).inserted else { return }
+ try addComponentsReferencedBy(document.components.lookup(reference))
+
+ case .object(_, let object):
+ for schema in object.properties.values {
+ try addComponentsReferencedBy(schema)
+ }
+ if case .b(let schema) = object.additionalProperties {
+ try addComponentsReferencedBy(schema)
+ }
+
+ case .array(_, let array):
+ if let schema = array.items {
+ try addComponentsReferencedBy(schema)
+ }
+
+ case .not(let schema, _):
+ try addComponentsReferencedBy(schema)
+
+ case .all(of: let schemas, _): fallthrough
+ case .one(of: let schemas, _): fallthrough
+ case .any(of: let schemas, _):
+ for schema in schemas {
+ try addComponentsReferencedBy(schema)
+ }
+ case .null, .boolean, .number, .integer, .string, .fragment: return
+ }
+ }
+
+ mutating func addComponentsReferencedBy(_ parameter: OpenAPI.Parameter) throws {
+ try addComponentsReferencedBy(parameter.schemaOrContent)
+ }
+
+ mutating func addComponentsReferencedBy(_ header: OpenAPI.Header) throws {
+ try addComponentsReferencedBy(header.schemaOrContent)
+ }
+
+ mutating func addComponentsReferencedBy(
+ _ schemaOrContent: Either<OpenAPI.Parameter.SchemaContext, OpenAPI.Content.Map>
+ ) throws {
+ switch schemaOrContent {
+ case .a(let schemaContext):
+ switch schemaContext.schema {
+ case .a(let reference):
+ guard requiredSchemaReferences.insert(reference).inserted else { return }
+ try addComponentsReferencedBy(try document.components.lookup(reference))
+ case .b(let schema):
+ try addComponentsReferencedBy(schema)
+ }
+ case .b(let contentMap):
+ for value in contentMap.values {
+ switch value.schema {
+ case .a(let reference):
+ guard requiredSchemaReferences.insert(reference).inserted else { return }
+ try addComponentsReferencedBy(try document.components.lookup(reference))
+ case .b(let schema):
+ try addComponentsReferencedBy(schema)
+ case .none:
+ continue
+ }
+ }
+ }
+ }
+
+ mutating func addComponentsReferencedBy(_ response: OpenAPI.Response) throws {
+ if let headers = response.headers {
+ for header in headers.values {
+ try requireHeader(header)
+ }
+ }
+ for content in response.content.values {
+ try addComponentsReferencedBy(content)
+ }
+ for link in response.links.values {
+ try requireLink(link)
+ }
+ }
+
+ mutating func addComponentsReferencedBy(_ content: OpenAPI.Content) throws {
+ if let schema = content.schema {
+ try requireSchema(schema)
+ }
+ if let encoding = content.encoding {
+ for encoding in encoding.values {
+ if let headers = encoding.headers {
+ for header in headers.values {
+ try requireHeader(header)
+ }
+ }
+ }
+ }
+ if let examples = content.examples {
+ for example in examples.values {
+ try requireExample(example)
+ }
+ }
+ }
+
+ mutating func addComponentsReferencedBy(_ content: OpenAPI.Link) throws {}
+
+ mutating func addComponentsReferencedBy(_ content: OpenAPI.Example) throws {}
+}
+
+fileprivate extension OpenAPI.Reference {
+ var internalComponentKey: OpenAPI.ComponentKey {
+ get throws {
+ guard case .internal(.component(name: let name)) = jsonReference else {
+ throw FilteredDocumentBuilderError.cannotResolveInternalReference(absoluteString)
+ }
+ return OpenAPI.ComponentKey(rawValue: name)! | Can we throw an error if it fails to init? Looking at the impl, there might be situations where the user's document could cause this to crash, which becomes difficult to debug. |
swift-openapi-generator | github_2023 | others | 319 | apple | czechboy0 | @@ -0,0 +1,100 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 ArgumentParser
+import Foundation
+import _OpenAPIGeneratorCore
+import Yams
+import OpenAPIKit
+import OpenAPIKit30
+
+struct _FilterCommand: AsyncParsableCommand { | This will be useful for debugging. Could you also add a few words about it to the Configuring docc article, both about the new keys in the config file, and about using the new filter command? |
swift-openapi-generator | github_2023 | others | 319 | apple | czechboy0 | @@ -0,0 +1,100 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 ArgumentParser
+import Foundation
+import _OpenAPIGeneratorCore
+import Yams
+import OpenAPIKit
+import OpenAPIKit30
+
+struct _FilterCommand: AsyncParsableCommand {
+ static var configuration = CommandConfiguration(
+ commandName: "filter",
+ abstract: "Filter an OpenAPI document",
+ discussion: """
+ Filtering rules are provided in a YAML configuration file.
+
+ Example configuration file contents:
+
+ ```yaml
+ \(try! YAMLEncoder().encode(sampleConfig))
+ ```
+ """
+ )
+
+ @Option(help: "Path to a YAML configuration file.")
+ var config: URL
+
+ @Argument(help: "Path to the OpenAPI document, either in YAML or JSON.")
+ var docPath: URL
+
+ func parseOpenAPIDocument(_ documentData: Data) throws -> OpenAPIKit.OpenAPI.Document {
+ let decoder = YAMLDecoder()
+
+ struct OpenAPIVersionedDocument: Decodable {
+ var openapi: String
+ }
+
+ let versionedDocument = try decoder.decode(OpenAPIVersionedDocument.self, from: documentData)
+
+ let document: OpenAPIKit.OpenAPI.Document
+ switch versionedDocument.openapi {
+ case "3.0.0", "3.0.1", "3.0.2", "3.0.3":
+ let document30x = try decoder.decode(OpenAPIKit30.OpenAPI.Document.self, from: documentData)
+ document = document30x.convert(to: .v3_1_0)
+ case "3.1.0":
+ document = try decoder.decode(OpenAPIKit.OpenAPI.Document.self, from: documentData)
+ default:
+ fatalError("Unsupported OpenAPI version found: \(versionedDocument.openapi)")
+ }
+ return document
+ } | `parseOpenAPIDocument` looks very similar to code we have in YamsParser, could you factor it out into a shared API on `_OpenAPIGeneratorCore`? |
swift-openapi-generator | github_2023 | others | 319 | apple | czechboy0 | @@ -0,0 +1,185 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 OpenAPIKit
+import XCTest
+import Yams
+@testable import _OpenAPIGeneratorCore
+
+final class FilteredDocumentTests: XCTestCase {
+
+ func testDocumentFilter() throws {
+ let documentYAML = """
+ openapi: 3.1.0
+ info:
+ title: ExampleService
+ version: 1.0.0
+ tags:
+ - name: t
+ paths:
+ /things/a:
+ get:
+ operationId: getA
+ tags:
+ - t
+ responses:
+ 200:
+ $ref: '#/components/responses/A'
+ delete:
+ operationId: deleteA
+ responses:
+ 200:
+ $ref: '#/components/responses/Empty'
+ /things/b:
+ get:
+ operationId: getB
+ responses:
+ 200:
+ $ref: '#/components/responses/B'
+ components:
+ schemas:
+ A:
+ type: string
+ B:
+ $ref: '#/components/schemas/A'
+ responses:
+ A:
+ description: success
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/A'
+ B:
+ description: success
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/B'
+ Empty:
+ description: success
+ """
+ let document = try YAMLDecoder().decode(OpenAPI.Document.self, from: documentYAML)
+ assert(
+ filtering: document,
+ filter: DocumentFilter(),
+ hasPaths: [],
+ hasOperations: [],
+ hasSchemas: []
+ )
+ assert(
+ filtering: document,
+ filter: DocumentFilter(tags: ["t"]),
+ hasPaths: ["/things/a"],
+ hasOperations: ["getA"],
+ hasSchemas: ["A"]
+ )
+ assert(
+ filtering: document,
+ filter: DocumentFilter(paths: ["/things/a"]),
+ hasPaths: ["/things/a"],
+ hasOperations: ["getA", "deleteA"],
+ hasSchemas: ["A"]
+ )
+ assert(
+ filtering: document,
+ filter: DocumentFilter(paths: ["/things/b"]),
+ hasPaths: ["/things/b"],
+ hasOperations: ["getB"],
+ hasSchemas: ["A", "B"]
+ )
+ assert(
+ filtering: document,
+ filter: DocumentFilter(paths: ["/things/a", "/things/b"]),
+ hasPaths: ["/things/a", "/things/b"],
+ hasOperations: ["getA", "deleteA", "getB"],
+ hasSchemas: ["A", "B"]
+ )
+ assert(
+ filtering: document,
+ filter: DocumentFilter(schemas: ["A"]),
+ hasPaths: [],
+ hasOperations: [],
+ hasSchemas: ["A"]
+ )
+ assert(
+ filtering: document,
+ filter: DocumentFilter(schemas: ["B"]),
+ hasPaths: [],
+ hasOperations: [],
+ hasSchemas: ["A", "B"]
+ )
+ assert(
+ filtering: document,
+ filter: DocumentFilter(paths: ["/things/a"], schemas: ["B"]),
+ hasPaths: ["/things/a"],
+ hasOperations: ["getA", "deleteA"],
+ hasSchemas: ["A", "B"]
+ )
+ assert(
+ filtering: document,
+ filter: DocumentFilter(tags: ["t"], schemas: ["B"]),
+ hasPaths: ["/things/a"],
+ hasOperations: ["getA"],
+ hasSchemas: ["A", "B"]
+ )
+ assert(
+ filtering: document,
+ filter: DocumentFilter(operations: ["deleteA"]),
+ hasPaths: ["/things/a"],
+ hasOperations: ["deleteA"],
+ hasSchemas: []
+ )
+ }
+
+ func assert(
+ filtering document: OpenAPI.Document,
+ filter: DocumentFilter,
+ hasPaths paths: [OpenAPI.Path.RawValue],
+ hasOperations operationIDs: [String],
+ hasSchemas schemas: [String],
+ file: StaticString = #filePath,
+ line: UInt = #line
+ ) {
+ let filteredDocument: OpenAPI.Document
+ do {
+ filteredDocument = try filter.filter(document)
+ } catch {
+ XCTFail("Filter threw error: \(error)", file: file, line: line)
+ return
+ }
+ XCTAssertUnsortedEqual(filteredDocument.paths.keys.map(\.rawValue), paths, file: file, line: line)
+ XCTAssertUnsortedEqual(filteredDocument.allOperationIds, operationIDs, file: file, line: line)
+ XCTAssertUnsortedEqual(
+ filteredDocument.components.schemas.keys.map(\.rawValue),
+ schemas,
+ file: file,
+ line: line
+ )
+ }
+}
+
+private func XCTAssertUnsortedEqual<T>( | Can you move this to `TestUtilities.swift`? Could be useful elsewhere, and we already have some XCTAssert* utils there. |
swift-openapi-generator | github_2023 | others | 319 | apple | czechboy0 | @@ -66,3 +72,40 @@ generate:
additionalImports:
- APITypes
```
+
+### Document filtering
+
+The geneartor supports filtering the OpenAPI document prior to generation, which can be useful when | ```suggestion
The generator supports filtering the OpenAPI document prior to generation, which can be useful when
``` |
swift-openapi-generator | github_2023 | others | 319 | apple | czechboy0 | @@ -66,3 +72,40 @@ generate:
additionalImports:
- APITypes
```
+
+### Document filtering
+
+The geneartor supports filtering the OpenAPI document prior to generation, which can be useful when
+generating client code for a subset of a large API. | ```suggestion
generating client code for a subset of a large API, or splitting an implementation of a server across multiple modules.
``` |
swift-openapi-generator | github_2023 | others | 319 | apple | czechboy0 | @@ -66,3 +72,40 @@ generate:
additionalImports:
- APITypes
```
+
+### Document filtering
+
+The geneartor supports filtering the OpenAPI document prior to generation, which can be useful when
+generating client code for a subset of a large API.
+
+For example, to generate client code for only the operations with a given tag, use the following config: | ```suggestion
For example, to generate code for only the operations with a given tag, use the following config:
``` |
swift-openapi-generator | github_2023 | others | 319 | apple | czechboy0 | @@ -0,0 +1,82 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 ArgumentParser
+import Foundation
+import _OpenAPIGeneratorCore
+import Yams
+import OpenAPIKit
+import OpenAPIKit30
+
+struct _FilterCommand: AsyncParsableCommand {
+ static var configuration = CommandConfiguration(
+ commandName: "filter",
+ abstract: "Filter an OpenAPI document",
+ discussion: """
+ Filtering rules are provided in a YAML configuration file.
+
+ Example configuration file contents:
+
+ ```yaml
+ \(try! YAMLEncoder().encode(sampleConfig))
+ ```
+ """
+ )
+
+ @Option(help: "Path to a YAML configuration file.")
+ var config: URL
+
+ @Argument(help: "Path to the OpenAPI document, either in YAML or JSON.")
+ var docPath: URL
+
+ func run() async throws {
+ let configData = try Data(contentsOf: config)
+ let config = try YAMLDecoder().decode(_UserConfig.self, from: configData)
+ let documentInput = try InMemoryInputFile(absolutePath: docPath, contents: Data(contentsOf: docPath))
+ let document = try timing(
+ "Parsing document",
+ YamsParser.parseOpenAPIDocument(documentInput, diagnostics: StdErrPrintingDiagnosticCollector())
+ )
+ try document.validate() | I think you actually want to use the function `validateDoc` from `validateDoc.swift`, which also takes the diagnostic collector and uses the same logic as the generation command. By default the `validate()` call contains a slightly different set of validations, and is overly strict about schema warnings. |
swift-openapi-generator | github_2023 | others | 319 | apple | czechboy0 | @@ -0,0 +1,82 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 ArgumentParser
+import Foundation
+import _OpenAPIGeneratorCore
+import Yams
+import OpenAPIKit
+import OpenAPIKit30
+
+struct _FilterCommand: AsyncParsableCommand {
+ static var configuration = CommandConfiguration(
+ commandName: "filter",
+ abstract: "Filter an OpenAPI document",
+ discussion: """
+ Filtering rules are provided in a YAML configuration file.
+
+ Example configuration file contents:
+
+ ```yaml
+ \(try! YAMLEncoder().encode(sampleConfig))
+ ```
+ """
+ )
+
+ @Option(help: "Path to a YAML configuration file.")
+ var config: URL
+
+ @Argument(help: "Path to the OpenAPI document, either in YAML or JSON.")
+ var docPath: URL
+
+ func run() async throws {
+ let configData = try Data(contentsOf: config)
+ let config = try YAMLDecoder().decode(_UserConfig.self, from: configData)
+ let documentInput = try InMemoryInputFile(absolutePath: docPath, contents: Data(contentsOf: docPath))
+ let document = try timing(
+ "Parsing document",
+ YamsParser.parseOpenAPIDocument(documentInput, diagnostics: StdErrPrintingDiagnosticCollector())
+ )
+ try document.validate()
+ guard let documentFilter = config.filter else {
+ FileHandle.standardError.write("warning: No filter config provided\n")
+ FileHandle.standardOutput.write(try YAMLEncoder().encode(document)) | Should we generate JSON if the user gave us JSON here? |
swift-openapi-generator | github_2023 | others | 188 | apple | czechboy0 | @@ -16,7 +16,7 @@
"prioritizeKeepingFunctionOutputTogether" : false,
"respectsExistingLineBreaks" : true,
"rules" : {
- "AllPublicDeclarationsHaveDocumentation" : false,
+ "AllPublicDeclarationsHaveDocumentation" :true, | ```suggestion
"AllPublicDeclarationsHaveDocumentation" : true,
```
Nit: whitespace. |
swift-openapi-generator | github_2023 | others | 188 | apple | czechboy0 | @@ -23,16 +23,17 @@ REPO_ROOT="$(git -C "${CURRENT_SCRIPT_DIR}" rev-parse --show-toplevel)"
SWIFTFORMAT_BIN=${SWIFTFORMAT_BIN:-$(command -v swift-format)} || fatal "β SWIFTFORMAT_BIN unset and no swift-format on PATH"
-git -C "${REPO_ROOT}" ls-files -z '*.swift' \
- | xargs -0 "${SWIFTFORMAT_BIN}" lint --parallel --strict \
+"${SWIFTFORMAT_BIN}" lint \
+ --parallel --recursive --strict \
+ "${REPO_ROOT}/Sources" \ | What was the issue with before? I think this would disable linting the Test and other directories, which I don't think we want. cc @simonjbeaumont |
swift-openapi-generator | github_2023 | others | 188 | apple | czechboy0 | @@ -24,6 +24,7 @@ REPO_ROOT="$(git -C "${CURRENT_SCRIPT_DIR}" rev-parse --show-toplevel)"
SWIFTFORMAT_BIN=${SWIFTFORMAT_BIN:-$(command -v swift-format)} || fatal "β SWIFTFORMAT_BIN unset and no swift-format on PATH"
git -C "${REPO_ROOT}" ls-files -z '*.swift' \
+ | grep -z -v 'Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore' \ | ```suggestion
| grep -z -v 'Tests/OpenAPIGeneratorReferenceTests/Resources' \
```
And please also exclude and remove any changes to `Sources/swift-openapi-generator/Documentation.docc`, we don't want the tutorials to be affected. Otherwise will be ready to go. |
swift-openapi-generator | github_2023 | others | 317 | apple | czechboy0 | @@ -5,7 +5,8 @@ services:
image: &image swift-openapi-generator:22.04-5.9
build:
args:
- base_image: "swiftlang/swift:nightly-5.9-jammy"
+ ubuntu_version: "jammy" | Should we make this change in the 5.10 one as well? |
swift-openapi-generator | github_2023 | others | 308 | apple | czechboy0 | @@ -103,6 +103,61 @@ extension TypesFileTranslator {
)
)
bodyCases.append(bodyCase)
+
+ var throwingGetterSwitchCases = [
+ SwitchCaseDescription(
+ kind: .case(.identifier(".\(identifier)"), ["body"]),
+ body: [.expression(.return(.identifier("body")))]
+ )
+ ]
+ // We only generate the default branch if there is more than one case to prevent
+ // a warning when compiling the generated code. | That's a good idea. |
swift-openapi-generator | github_2023 | others | 308 | apple | czechboy0 | @@ -103,6 +103,61 @@ extension TypesFileTranslator {
)
)
bodyCases.append(bodyCase)
+
+ var throwingGetterSwitchCases = [
+ SwitchCaseDescription(
+ kind: .case(.identifier(".\(identifier)"), ["body"]),
+ body: [.expression(.return(.identifier("body")))]
+ )
+ ]
+ // We only generate the default branch if there is more than one case to prevent
+ // a warning when compiling the generated code.
+ if typedContents.count > 1 {
+ throwingGetterSwitchCases.append(
+ SwitchCaseDescription(
+ kind: .default,
+ body: [
+ .expression(
+ .try(
+ .identifier("throwUnexpectedResponseBody")
+ .call([
+ .init(
+ label: "expectedContent",
+ expression: .literal(.string(contentType.headerValueForSending)) | ```suggestion
expression: .literal(.string(contentType.headerValueForValidation))
```
While this is just for printing, `headerValueForValidation` is more appropriate as it doesn't include `charset`, which isn't used to match content types. |
swift-openapi-generator | github_2023 | others | 308 | apple | czechboy0 | @@ -103,6 +103,61 @@ extension TypesFileTranslator {
)
)
bodyCases.append(bodyCase)
+
+ var throwingGetterSwitchCases = [
+ SwitchCaseDescription(
+ kind: .case(.identifier(".\(identifier)"), ["body"]),
+ body: [.expression(.return(.identifier("body")))]
+ )
+ ]
+ // We only generate the default branch if there is more than one case to prevent
+ // a warning when compiling the generated code.
+ if typedContents.count > 1 {
+ throwingGetterSwitchCases.append(
+ SwitchCaseDescription(
+ kind: .default,
+ body: [
+ .expression(
+ .try(
+ .identifier("throwUnexpectedResponseBody")
+ .call([
+ .init(
+ label: "expectedContent",
+ expression: .literal(.string(contentType.headerValueForSending))
+ ),
+ .init(label: "body", expression: .identifier("self")),
+ ])
+ )
+ )
+ ]
+ )
+ )
+ }
+ let throwingGetter = VariableDescription(
+ accessModifier: config.access,
+ isStatic: false,
+ kind: .var,
+ left: identifier,
+ type: associatedType.fullyQualifiedSwiftName,
+ getter: [
+ .expression(
+ .switch(
+ switchedExpression: .identifier("self"),
+ cases: throwingGetterSwitchCases
+ )
+ )
+ ],
+ getterEffects: [.throws]
+ )
+ let throwingGetterComment = Comment.doc(
+ """
+ The associated value of the enum case if `self` is `.\(identifier)`.
+
+ - Throws: Runtime error if `self` is not `.\(identifier)`. | ```suggestion
- Throws: An error if `self` is not `.\(identifier)`.
```
Since "runtime error" isn't a public type, I wouldn't mention it here. |
swift-openapi-generator | github_2023 | others | 308 | apple | czechboy0 | @@ -73,7 +67,61 @@ extension TypesFileTranslator {
),
.enumCase(enumCaseDesc)
)
- return (responseStructDecl, enumCaseDecl)
+
+ let throwingGetterDesc = VariableDescription(
+ accessModifier: config.access,
+ kind: .var,
+ left: enumCaseName,
+ type: responseStructTypeName.fullyQualifiedSwiftName,
+ getter: [
+ .expression(
+ .switch(
+ switchedExpression: .identifier("self"),
+ cases: [
+ SwitchCaseDescription(
+ kind: .case(
+ .identifier(".\(responseKind.identifier)"),
+ responseKind.wantsStatusCode ? ["_", "response"] : ["response"] | I thought about this a bit, and I think you made the right choice. For ranges, the alternative choice would have been to return `(Int, BODY_TYPE)`, but I prefer just returning `BODY_TYPE`, and if the adopter wants the code, they need to switch manually. |
swift-openapi-generator | github_2023 | others | 308 | apple | czechboy0 | @@ -73,7 +67,61 @@ extension TypesFileTranslator {
),
.enumCase(enumCaseDesc)
)
- return (responseStructDecl, enumCaseDecl)
+
+ let throwingGetterDesc = VariableDescription(
+ accessModifier: config.access,
+ kind: .var,
+ left: enumCaseName,
+ type: responseStructTypeName.fullyQualifiedSwiftName,
+ getter: [
+ .expression(
+ .switch(
+ switchedExpression: .identifier("self"),
+ cases: [
+ SwitchCaseDescription(
+ kind: .case(
+ .identifier(".\(responseKind.identifier)"),
+ responseKind.wantsStatusCode ? ["_", "response"] : ["response"]
+ ),
+ body: [.expression(.return(.identifier("response")))]
+ ),
+ SwitchCaseDescription(
+ kind: .default,
+ body: [
+ .expression(
+ .try(
+ .identifier("throwUnexpectedResponseStatus")
+ .call([
+ .init(
+ label: "expectedStatus",
+ expression: .literal(.string(responseKind.prettyName))
+ ),
+ .init(label: "response", expression: .identifier("self")),
+ ])
+ )
+ )
+ ]
+ ),
+ ]
+ )
+ )
+ ],
+ getterEffects: [.throws]
+ )
+ let throwingGetterComment = Comment.doc(
+ """
+ The associated value of the enum case if `self` is `.\(enumCaseName)`.
+
+ - Throws: Runtime error if `self` is not `.\(enumCaseName)`. | ```suggestion
- Throws: An error if `self` is not `.\(enumCaseName)`.
```
Same as above. |
swift-openapi-generator | github_2023 | others | 245 | apple | simonjbeaumont | @@ -1087,9 +1087,9 @@ public enum Operations {
/// - Remark: Generated from `#/paths/pets/stats/GET/responses/200/content/application\/json`.
case json(Components.Schemas.PetStats)
/// - Remark: Generated from `#/paths/pets/stats/GET/responses/200/content/text\/plain`.
- case plainText(Swift.String)
+ case plainText(OpenAPIRuntime.HTTPBody)
/// - Remark: Generated from `#/paths/pets/stats/GET/responses/200/content/application\/octet-stream`.
- case binary(Foundation.Data)
+ case binary(OpenAPIRuntime.HTTPBody) | Just confirming, is `HTTPBody` the best we can do for `text/plain` in all cases? |
swift-openapi-generator | github_2023 | others | 245 | apple | simonjbeaumont | @@ -111,21 +103,8 @@ public extension Data {
}
}
-public extension Request {
- init(
- path: String,
- query: String? = nil,
- method: HTTPMethod,
- headerFields: [HeaderField] = [],
- encodedBody: String
- ) throws {
- let body = Data(encodedBody.utf8)
- self.init(
- path: path,
- query: query,
- method: method,
- headerFields: headerFields,
- body: body
- )
+public extension HTTPRequest {
+ func withEncodedBody(_ encodedBody: String) -> (HTTPRequest, HTTPBody) { | I'm not sure what value this provides, but if it's just part of tests we can leave it. |
swift-openapi-generator | github_2023 | others | 245 | apple | simonjbeaumont | @@ -12,9 +12,16 @@
//
//===----------------------------------------------------------------------===//
import XCTest
+import HTTPTypes
extension Operations.listPets.Output {
static var success: Self {
.ok(.init(headers: .init(My_hyphen_Response_hyphen_UUID: "abcd"), body: .json([])))
}
}
+
+extension HTTPRequest {
+ public init(soar_path path: String, method: Method, headerFields: HTTPFields = .init()) {
+ self.init(method: method, scheme: nil, authority: nil, path: path, headerFields: headerFields)
+ }
+} | Didn't this land in a runtime SPI? |
swift-openapi-generator | github_2023 | others | 245 | apple | simonjbeaumont | @@ -0,0 +1,344 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 XCTest
+import OpenAPIRuntime
+import PetstoreConsumerTestCore
+
+final class Test_Playground: XCTestCase { | Just checking you meant to include this file, as most of the methods in it `fatalError()`. |
swift-openapi-generator | github_2023 | others | 297 | apple | czechboy0 | @@ -99,6 +117,16 @@ extension _GenerateOptions {
}
do {
let data = try Data(contentsOf: config)
+ let configAsString = String(data: data, encoding: .utf8)
+
+ let yamlKeys = extractYamlKeys(yamlString: configAsString!) | ```suggestion
let configAsString = String(decoding: data, as: UTF8.self)
let yamlKeys = extractYamlKeys(yamlString: configAsString)
``` |
swift-openapi-generator | github_2023 | others | 297 | apple | czechboy0 | @@ -29,4 +29,12 @@ struct _UserConfig: Codable {
/// A set of features to explicitly enable.
var featureFlags: FeatureFlags?
+
+ static let codingKeysRawValues = Set(CodingKeys.allCases.map({ $0.rawValue })) | Please add a comment for the symbol. |
swift-openapi-generator | github_2023 | others | 297 | apple | czechboy0 | @@ -86,7 +86,25 @@ extension _GenerateOptions {
if !featureFlag.isEmpty {
return Set(featureFlag)
}
- return Set(config?.featureFlags ?? [])
+ return config?.featureFlags ?? []
+ }
+
+ /// Extracts keys from a YAML string.
+ ///
+ /// - Parameter yamlString: The YAML string from which to extract keys.
+ /// - Returns: An array of strings representing the keys extracted from the YAML string.
+ func extractYamlKeys(yamlString: String) -> [String] {
+ let lines = yamlString.components(separatedBy: "\n")
+
+ var extractedKeys = [String]()
+
+ for line in lines {
+ if let range = line.range(of: ":") {
+ let key = line[line.startIndex..<range.lowerBound].trimmingCharacters(in: .whitespaces)
+ extractedKeys.append(key)
+ }
+ }
+ return extractedKeys | I agree we need to extract the keys somehow, but I don't think we should try to write our own YAML parser here. Can you see if you can use the lower level Yams API to do the same? https://www.jpsim.com/Yams/Classes/Parser.html |
swift-openapi-generator | github_2023 | others | 297 | apple | czechboy0 | @@ -86,7 +86,42 @@ extension _GenerateOptions {
if !featureFlag.isEmpty {
return Set(featureFlag)
}
- return Set(config?.featureFlags ?? [])
+ return config?.featureFlags ?? []
+ }
+
+ /// Extracts the top-level keys from a YAML string.
+ ///
+ /// - Parameter yamlString: The YAML string from which to extract keys.
+ /// - Returns: An array of top-level keys as strings.
+ func extractTopLevelKeys(fromYAMLString yamlString: String) -> [String] {
+ var yamlKeys = [String]()
+
+ do {
+ let parser = try Parser(yaml: yamlString)
+ if let rootNode = try parser.singleRoot(),
+ case let .mapping(mapping) = rootNode
+ {
+ for (key, _) in mapping {
+ yamlKeys.append(key.string ?? "")
+ }
+ }
+ } catch {
+ print("Error parsing YAML: \(error)") | I think it's better to just let the error be thrown one level up, and there emit a ValidationError saying the config isn't valid and include the description of the error thrown by Yams. So you can remove the do/catch here. |
swift-openapi-generator | github_2023 | others | 254 | apple | gjcairo | @@ -305,24 +308,24 @@ A reminder that the exact spelling of integrating `HTTPBody` into the transport
///
/// ## Consuming a body as a buffer
/// If you need to collect the whole body before processing it, use one of
-/// the convenience `collect` methods on `HTTPBody`.
+/// the convenience initializers on the target types that take an `HTTPBody`.
///
-/// To get all the bytes, use:
+/// To get all the bytes, use the initializer on `ArraySlice<UInt8>` or `[UInt8]`:
///
/// ```swift
-/// let buffer = try await body.collect(upTo: 2 * 1024 * 1024)
+/// let buffer = try await ArraySlice(collecting: body, upTo: 2 * 1024 * 1024) | Tiny nit: you use this new initialiser here but I don't think it's included in the code snippet below. |
swift-openapi-generator | github_2023 | others | 254 | apple | gjcairo | @@ -470,71 +505,52 @@ extension HTTPBody {
/// - Parameters:
/// - string: A string to encode as bytes.
/// - length: The total length of the body.
- @inlinable public convenience init(string: some StringProtocol, length: Length)
+ @inlinable public convenience init(_ string: some StringProtocol & Sendable, length: Length)
/// Creates a new body with the provided string encoded as UTF-8 bytes.
/// - Parameters:
/// - string: A string to encode as bytes.
- @inlinable public convenience init(string: some StringProtocol)
-
- /// Creates a new body with the provided strings encoded as UTF-8 bytes.
- /// - Parameters:
- /// - stringChunks: A sequence of string chunks.
- /// - length: The total length of the body.
- /// - iterationBehavior: The iteration behavior of the sequence, which
- /// indicates whether it can be iterated multiple times.
- @inlinable public convenience init<S>(stringChunks: S, length: Length, iterationBehavior: IterationBehavior) where S : Sequence, S.Element : StringProtocol
-
- /// Creates a new body with the provided strings encoded as UTF-8 bytes.
- /// - Parameters:
- /// - stringChunks: A collection of string chunks.
- /// - length: The total length of the body.
- @inlinable public convenience init<C>(stringChunks: C, length: Length) where C : Collection, C.Element : StringProtocol
-
- /// Creates a new body with the provided strings encoded as UTF-8 bytes.
- /// - Parameters:
- /// - stringChunks: A collection of string chunks.
- @inlinable public convenience init<C>(stringChunks: C) where C : Collection, C.Element : StringProtocol
+ @inlinable public convenience init(_ string: some StringProtocol & Sendable)
/// Creates a new body with the provided async throwing stream of strings.
/// - Parameters:
/// - stream: An async throwing stream that provides the string chunks.
/// - length: The total length of the body.
- @inlinable public convenience init(stream: AsyncThrowingStream<some StringProtocol, any Error>, length: HTTPBody.Length)
+ @inlinable public convenience init(_ stream: AsyncThrowingStream<some StringProtocol & Sendable, any Error & Sendable>, length: HTTPBody.Length)
/// Creates a new body with the provided async stream of strings.
/// - Parameters:
/// - stream: An async stream that provides the string chunks.
/// - length: The total length of the body.
- @inlinable public convenience init(stream: AsyncStream<some StringProtocol>, length: HTTPBody.Length)
+ @inlinable public convenience init(_ stream: AsyncStream<some StringProtocol & Sendable>, length: HTTPBody.Length)
/// Creates a new body with the provided async sequence of string chunks.
/// - Parameters:
/// - sequence: An async sequence that provides the string chunks.
/// - length: The total lenght of the body.
/// - iterationBehavior: The iteration behavior of the sequence, which
/// indicates whether it can be iterated multiple times.
- @inlinable public convenience init<S>(sequence: S, length: HTTPBody.Length, iterationBehavior: IterationBehavior) where S : AsyncSequence, S.Element : StringProtocol
+ @inlinable public convenience init<Strings>(_ sequence: Strings, length: HTTPBody.Length, iterationBehavior: IterationBehavior) where Strings : Sendable, Strings : AsyncSequence, Strings.Element : Sendable, Strings.Element : StringProtocol
}
-extension StringProtocol {
+extension HTTPBody.ByteChunk where Element == UInt8 {
- /// Returns the string as a byte chunk compatible with the `HTTPBody` type.
- @inlinable internal var asBodyChunk: HTTPBody.ByteChunk { get }
+ /// Creates a byte chunk compatible with the `HTTPBody` type from the provided string.
+ /// - Parameter string: The string to encode.
+ @inlinable internal init(_ string: some StringProtocol & Sendable)
}
-extension HTTPBody {
+extension String {
- /// Accumulates the full body in-memory into a single buffer up to
- /// the provided maximum number of bytes, converts it to string from
- /// the UTF-8 bytes, and returns it.
+ /// Creates a string by accumulating the full body in-memory into a single buffer up to
+ /// the provided maximum number of bytes, converting it to string using the provided encoding.
/// - Parameters:
+ /// - body: The HTTP body to collect.
/// - maxBytes: The maximum number of bytes this method is allowed
/// to accumulate in memory before it throws an error.
- /// - Throws: `TooManyBytesError` if the the body contains more
+ /// - Throws: `TooManyBytesError` if the the sequence contains more | Nit: extra "the"
```suggestion
/// - Throws: `TooManyBytesError` if the sequence contains more
```
Also, isn't `body` more accurate here? |
swift-openapi-generator | github_2023 | others | 283 | apple | czechboy0 | @@ -82,7 +93,8 @@ struct TestClient: APIProtocol {
return try await block(input)
}
- typealias UploadAvatarForPetSignature = @Sendable (Operations.uploadAvatarForPet.Input) async throws -> Operations
+ typealias UploadAvatarForPetSignature = @Sendable (Operations.uploadAvatarForPet.Input) async throws ->
+ Operations
.uploadAvatarForPet.Output
var uploadAvatarForPetBlock: UploadAvatarForPetSignature? | Please also add corresponding tests to Test_Client and Test_Server that ensures at runtime everything is correctly propagated. |
swift-openapi-generator | github_2023 | others | 283 | apple | czechboy0 | @@ -113,6 +113,47 @@ paths:
$ref: '#/components/schemas/Pet'
'4XX':
$ref: '#/components/responses/ErrorBadRequest'
+ /pets/create: | Let's simplify this to only test what we want to test here - url encoded request bodies.
- remove X-Extra-Arguments from the request and response headers
- remove the 400 response
- make the success response be 204 and return no content at all |
swift-openapi-generator | github_2023 | others | 283 | apple | czechboy0 | @@ -48,7 +48,8 @@ public struct Client: APIProtocol {
try await client.send(
input: input,
forOperation: Operations.listPets.id,
- serializer: { input in let path = try converter.renderedPath(template: "/pets", parameters: [])
+ serializer: { input in
+ let path = try converter.renderedPath(template: "/pets", parameters: []) | Could this be due to the swift-format version mismatch again? We'll upgrade at some point, but you'll likely need to revert this to pass CI :) |
swift-openapi-generator | github_2023 | others | 280 | apple | czechboy0 | @@ -33,23 +33,29 @@ extension _Tool {
outputDirectory: URL,
isDryRun: Bool,
diagnostics: any DiagnosticCollector
- ) throws {
+ ) async throws {
let docData: Data
do {
docData = try Data(contentsOf: doc)
} catch {
throw ValidationError("Failed to load the OpenAPI document at path \(doc.path), error: \(error)")
}
- for config in configs {
- try runGenerator(
- doc: doc,
- docData: docData,
- config: config,
- outputDirectory: outputDirectory,
- outputFileName: config.mode.outputFileName,
- isDryRun: isDryRun,
- diagnostics: diagnostics
- )
+
+ try await withThrowingTaskGroup(of: Void.self) { group in
+ for config in configs {
+ group.addTask {
+ try runGenerator(
+ doc: doc,
+ docData: docData,
+ config: config,
+ outputDirectory: outputDirectory,
+ outputFileName: config.mode.outputFileName,
+ isDryRun: isDryRun,
+ diagnostics: diagnostics | Can you make the YAML diagnostics collector thread-safe please? I think that's the only one that could encounter problems with this change. |
swift-openapi-generator | github_2023 | others | 281 | apple | czechboy0 | @@ -23,6 +24,15 @@ swiftSettings.append(
// Require `any` for existential types.
.enableUpcomingFeature("ExistentialAny")
)
+
+// Strict concurrency is enabled in CI; use this environment variable to enable it locally.
+if ProcessInfo.processInfo.environment["SWIFT_OPENAPI_STRICT_CONCURRENCY"].flatMap(Bool.init) ?? false {
+ #warning("Compiling with Strict Concurrency")
+ swiftSettings.append(contentsOf: [
+ .enableExperimentalFeature("StrictConcurrency"), | Do we need this one if we already have this one? https://github.com/apple/swift-openapi-generator/pull/281/files#diff-cae86870418d35877d5f11c0ea0b536fdec37236d6ea5c0951eec4723f508ccfR15 |
swift-openapi-generator | github_2023 | others | 274 | apple | czechboy0 | @@ -61,7 +61,7 @@ extension FileTranslator {
guard let rawValue = anyValue as? Int else {
throw GenericError(message: "Disallowed value for an integer enum '\(typeName)': \(anyValue)")
}
- let caseName = "_\(rawValue)"
+ let caseName = rawValue < 0 ? "n\(abs(rawValue))" : "_\(rawValue)" | Thoughts on whether we should also make positive numbers spelled "p1" for consistency or keep the current "_1", @glbrntt @simonjbeaumont @gjcairo? |
swift-openapi-generator | github_2023 | others | 266 | apple | simonjbeaumont | @@ -27,7 +29,10 @@ func validateDoc(_ doc: ParsedOpenAPIRepresentation, config: Config) throws -> [
// 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)
+ let warnings = try doc.validate(
+ using: Validator().validating(.operationsContainResponses), | Looks like we're opting into more than the default now? Is that now _more_ strict than before?
Given we're emitting warnings for all of these, are there any more we can be enabling? |
swift-openapi-generator | github_2023 | others | 130 | apple | simonjbeaumont | @@ -122,7 +122,39 @@ func makeGeneratorPipeline(
diagnostics: diagnostics
)
},
- postTransitionHooks: []
+ 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. | Why not do it for all parts of `components`, rather than just the ones we use _today_?
Otherwise I'd be concerned that we'd forget to update this as we move forward.
If there's a reference cycle in the OpenAPI document provided to the generator then it's a wonky input regardless of whether we try to make use of _that_ part of the document. |
swift-openapi-generator | github_2023 | others | 130 | apple | simonjbeaumont | @@ -122,7 +122,39 @@ func makeGeneratorPipeline(
diagnostics: diagnostics
)
},
- postTransitionHooks: []
+ postTransitionHooks: [
+ { doc in
+
+ // Run OpenAPIKit's built-in validation.
+ try doc.validate() | Are we happy just surfacing the errors, as-is, from OpenAPIKit? |
swift-openapi-generator | github_2023 | others | 89 | apple | czechboy0 | @@ -0,0 +1,52 @@
+# 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 hex encoding for any unsupported character in property names. 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.
+
+Some examples,
+
+yaml | swift
+-- | --
+a b | a20b
+a*b | a2Ab
+ab_ | ab_
+ab* | ab2A
+/ab | _2Fab
+Hu&J_?kin | Hu26J_3Fkin
+message | message
+
+This would mean, that for the users of the generator, a future version of the generator might produce different names that what it currently produces right now and should be ready to make those changes before upgrading to this version.
+
+### Detailed design
+
+The implementation for this is quite simple as you can see in https://github.com/apple/swift-openapi-generator/pull/89, we just made changes to the substitution logic where it used to substitute with `_`. We now add an additional encoding to the special character before substituting it. Contributors should be aware of this change and should review the places where they use this extension and evaluate if its suitable for them with this change.
+
+### API stability
+
+This is an API breaking change, as it will produce different symbol names than before. Other components such as the runtime and transports should not have any impacts.
+
+### Future directions
+
+The encoding strategy is open for further discussion. As a starting point, we have chosen the most simplest encoding format of hex. One of the reasons for this the hex encoding adds quite arbitrary symbols to the property name, which is not ideal. We could go towards a middle of the road approach where we have wordified versions of the special characters which we can map to. For example `a+b` can be `aplusb` or `a_plus_b` to add some kind of delimiter to specify the replaced portion. | I'd like to see the map of special characters to names in this proposal, not just as a future direction. I like that you started without it, as it's simpler, but since this is a breaking change anyway, we might as well make the experience nicer for a hard-coded set of characters.
I'd start with: +, -, #, and also take a look at identifiers used in some large OpenAPI docs, such as GitHub's.
I'll also let @simonjbeaumont suggest other ones that come to mind. |
swift-openapi-generator | github_2023 | others | 89 | apple | siemensikkema | @@ -56,18 +56,19 @@ fileprivate extension String {
/// Returns a string sanitized to be usable as a Swift identifier.
///
- /// For example, the string `$nake` would be returned as `_nake`, because
- /// the dollar sign is not a valid character in a Swift identifier.
+ /// For example, the string `$nakeβ¦` would be returned as `_dollar_nake_x2026_`, because
+ /// both the dollar and ellipsis sign are not valid characters in a Swift identifier.
+ /// So, it replaces such characters with their html enity equivalents or unicode hex representation, | ```suggestion
/// So, it replaces such characters with their html entity equivalents or unicode hex representation,
``` |
swift-openapi-generator | github_2023 | others | 89 | apple | siemensikkema | @@ -56,18 +56,19 @@ fileprivate extension String {
/// Returns a string sanitized to be usable as a Swift identifier.
///
- /// For example, the string `$nake` would be returned as `_nake`, because
- /// the dollar sign is not a valid character in a Swift identifier.
+ /// For example, the string `$nakeβ¦` would be returned as `_dollar_nake_x2026_`, because
+ /// both the dollar and ellipsis sign are not valid characters in a Swift identifier.
+ /// So, it replaces such characters with their html enity equivalents or unicode hex representation,
+ /// in case its not present in the `specialCharsMap`. It marks this replacement with `_` as a delimiter. | ```suggestion
/// in case itβs not present in the `specialCharsMap`. It marks this replacement with `_` as a delimiter.
``` |
swift-openapi-generator | github_2023 | others | 236 | apple | gjcairo | @@ -143,21 +182,25 @@ struct ContentType: Hashable {
"\(lowercasedType)/\(lowercasedSubtype)"
}
- /// Returns the type and subtype as a "<type>\/<subtype>" string.
+ /// Returns the type and subtype as a "<type>\/<subtype>[;<param>...]" string. | Small nit: maybe worth updating to something like this?
```suggestion
/// Returns the type, subtype and parameters (if present) as a "<type>\/<subtype>[;<param>...]" string.
``` |
swift-openapi-generator | github_2023 | others | 236 | apple | glbrntt | @@ -39,6 +39,10 @@ final class Test_ContentSwiftName: Test_Core {
// Generic names.
("application/myformat+json", "application_myformat_plus_json"),
("foo/bar", "foo_bar"),
+
+ // Names with a parameter.
+ ("application/foo", "application_foo"),
+ ("application/foo; bar=baz; boo=foo", "application_foo_bar_baz_boo_foo"), | Is it worth testing that additional whitespace is handled too? e.g. `"application/foo; bar = baz"`? |
swift-openapi-generator | github_2023 | others | 237 | apple | czechboy0 | @@ -1,6 +1,6 @@
# Converting between data and Swift types
-Learn about the type responsible for convertering between binary data and Swift types. | `convertering` π |
swift-openapi-generator | github_2023 | others | 237 | apple | czechboy0 | @@ -6,7 +6,7 @@ Learn about the internals of Swift OpenAPI Generator.
Swift OpenAPI Generator contains multiple moving pieces, from the runtime library, to the generator CLI, plugin, to extension packages using the transport and middleware APIs.
-Use the resources below if you'd like to learn more about how the generator works under the hood, for example as part of contribututing a new feature to it. | `contribututing` π wow these are gems |
swift-openapi-generator | github_2023 | others | 225 | apple | glbrntt | @@ -124,55 +124,71 @@ extension FileTranslator {
discriminator: OpenAPI.Discriminator?,
schemas: [JSONSchema]
) throws -> Declaration {
- // > When using the discriminator, inline schemas will not be considered.
- // > β https://spec.openapis.org/oas/v3.0.3#discriminator-object
- let includedSchemas: [JSONSchema]
- if discriminator != nil {
- includedSchemas = schemas.filter(\.isReference)
- } else {
- includedSchemas = schemas
- }
-
- let cases: [(String, Comment?, TypeUsage, [Declaration])] =
- try includedSchemas
- .enumerated()
- .map { index, schema in
- let key = "case\(index+1)"
- let childType = try typeAssigner.typeUsage(
- forAllOrAnyOrOneOfChildSchemaNamed: key,
- withSchema: schema,
- inParent: typeName
- )
- let caseName: String
- // Only use the type name for the case for references,
- // as inline schemas have nothing that guarantees uniqueness.
- if schema.isReference {
- // Use the type name.
- caseName = childType.typeName.shortSwiftName
- } else {
- // Use a position-based key.
- caseName = key
+ let cases: [(String, [String]?, Comment?, TypeUsage, [Declaration])]
+ if let discriminator {
+ // > When using the discriminator, inline schemas will not be considered.
+ // > β https://spec.openapis.org/oas/v3.0.3#discriminator-object | Might be worth referencing the 3.1.x docs now |
swift-openapi-generator | github_2023 | others | 219 | apple | Kyle-Ye | @@ -1,4 +1,4 @@
-openapi: "3.0.3" | Since we are supporing both 3.0.x and and 3.1, maybe add a new petstore_3_1.yaml file and a new test case while keeping the original 3.0.3 test case is better IMO. |
swift-openapi-generator | github_2023 | others | 219 | apple | Kyle-Ye | @@ -104,7 +112,7 @@ extension Diagnostic {
static func openAPIVersionError(versionString: String, location: Location) -> Diagnostic {
return error(
message:
- "Unsupported document version: \(versionString). Please provide a document with OpenAPI versions in the 3.0.x set.",
+ "Unsupported document version: \(versionString). Please provide a document with OpenAPI versions in the 3.0.x or 3.1.x sets.", | When the user accidentally uses the non-existent version 3.0.4, the error message here may be confusing. |
swift-openapi-generator | github_2023 | others | 219 | apple | glbrntt | @@ -4,9 +4,9 @@ Learn which OpenAPI features are supported by Swift OpenAPI Generator.
## Overview
-Swift OpenAPI Generator is currently focused on supporting [OpenAPI 3.0.3][0].
+Swift OpenAPI Generator is currently focused on supporting [OpenAPI 3.0.3][0] and [OpenAPI 3.1.0][1]. | The yams parser suggests `3.0.{0,1,2}` are also supported. Should they be listed here as well?
More generally how good are OpenAPI document vendors at switching to newer versions? |
swift-openapi-generator | github_2023 | others | 219 | apple | glbrntt | @@ -155,7 +155,7 @@ Supported features are always provided on _both_ client and server.
- [x] description
- [x] format
- [ ] default
-- [ ] nullable
+- [ ] nullable (only in 3.0, removed in 3.1) | Does this mean the types generated from a 3.0.x document prior to this change will be different to that of the same document after this change as it's converted to 3.1.x first? |
swift-openapi-generator | github_2023 | others | 201 | apple | gjcairo | @@ -0,0 +1,265 @@
+# SOAR-0003: Type-safe Accept headers
+
+Generate a dedicated Accept header enum for each operation.
+
+## Overview
+
+- Proposal: SOAR-0003
+- Author(s): [Honza Dvorsky](https://github.com/czechboy0), [Si Beaumont](https://github.com/simonjbeaumont)
+- Status: **Awaiting Review**
+- Issue: [apple/swift-openapi-generator#160](https://github.com/apple/swift-openapi-generator/issues/160)
+- Implementation:
+ - [apple/swift-openapi-runtime#37](https://github.com/apple/swift-openapi-runtime/pull/37)
+ - [apple/swift-openapi-generator#185](https://github.com/apple/swift-openapi-generator/pull/185)
+- Feature flag: none, purely additive
+- Affected components:
+ - generator
+ - runtime
+
+### Introduction
+
+Generate a type-safe representation of the possible values in the Accept header for each operation.
+
+### Motivation
+
+#### Accept header
+
+The [Accept request header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept) allows the client to communicate to the server which content types the client can handle in the response body. This includes the ability to provide multiple values, and to give each a numeric value to that represents preference (called "quality").
+
+Many clients don't provide any preference, for example by not including the Accept header, providing `accept: */*`, or listing all the known response headers in a list. The last option is what our generated clients do by default already today.
+
+However, sometimes the client needs to narrow down the list of acceptable content types, or it prefers one over the other, while it can still technically handle both.
+
+For example, let's consider an operation that returns an image either in the `png` or `jpeg` format. A client with a low amount of CPU and memory might choose `jpeg`, even though it could also handle `png`. In such a scenario, it would send an Accept header that could look like: `accept: image/jpeg, image/png; q=0.1`. This tells the server that while the client can handle both formats, it really prefers `jpeg`. Note that the "q" parameter represents a priority value between `0.0` and `1.0` inclusive, and the default value is `1.0`.
+
+However, the client could also completely lack a `png` decoder, in which case it would only request the `jpeg` format with: `accept: image/jpeg`. Note that `image/png` is completely omitted from the Accept header in this case.
+
+To summarize, the client needs to _provide_ Accept header information, and the server _inspects_ that information and uses it as a hint. Note that the server is still in charge of making the final decision over which of the acceptable content types it chooses, or it can return a 4xx status code if it cannot satisfy the client's request.
+
+#### Existing behavior
+
+Today, the generated client includes in the Accept header all the content types that appear in any response for the invoked operation in the OpenAPI document, essentially allowing the server to pick any content type. For an operation that uses JSON and plain text, the header would be: `accept: application/json, text/plain`. However, there is no way for the client to narrow down the choices or customize the quality value, meaning the only workaround is to build a [`ClientMiddleware`](https://swiftpackageindex.com/apple/swift-openapi-runtime/0.1.8/documentation/openapiruntime/clientmiddleware) that modifies the raw HTTP request before it's executed by the transport.
+
+On the server side, adopters have had to resort to workarounds, such as extracting the Accept header in a custom [`ServerMiddleware`](https://swiftpackageindex.com/apple/swift-openapi-runtime/0.1.8/documentation/openapiruntime/servermiddleware) and saving the parsed value into a task local value.
+
+#### Why now?
+
+While the Accept header can be sent even with requests that only have one documented response content type, it is most useful when the response contains multiple possible content types.
+
+That's why we are proposing this feature now, since multiple content types recently got implemented in Swift OpenAPI Generator - hidden behind the feature flag `multipleContentTypes` in versions `0.1.7+`.
+
+### Proposed solution
+
+We propose to start generating a new enum in each operation's namespace that contains all the unique concrete content types that appear in any of the operation's responses. This enum would also have a case called `other` with an associated `String` value, which would be an escape hatch, similar to the `undocumented(String)` case generated today for enums and `oneOf`s. | Nit: now that https://github.com/apple/swift-openapi-generator/pull/205 has been merged, this has/will become kind of irrelevant - does it make sense to have this reference to `undocumented` here? |
swift-openapi-generator | github_2023 | others | 185 | apple | gjcairo | @@ -1066,8 +1066,48 @@ public enum Operations {
}
public var query: Operations.getStats.Input.Query
public struct Headers: Sendable, Equatable, Hashable {
+ public enum AcceptableContentType: AcceptableProtocol {
+ case json
+ case text
+ case binary
+ case other(String)
+ public static var defaultValues: [Operations.getStats.Input.Headers.AcceptableContentType] {
+ [.json, .text, .binary]
+ }
+ public init?(rawValue: String) {
+ let lowercasedRawValue = rawValue.lowercased()
+ switch lowercasedRawValue {
+ case "application/json": | Should we consider all types ending in `+json` as JSON too? |
swift-openapi-generator | github_2023 | others | 185 | apple | glbrntt | @@ -1066,8 +1066,48 @@ public enum Operations {
}
public var query: Operations.getStats.Input.Query
public struct Headers: Sendable, Equatable, Hashable {
+ public enum AcceptableContentType: AcceptableProtocol {
+ case json
+ case text
+ case binary
+ case other(String)
+ public static var defaultValues: [Operations.getStats.Input.Headers.AcceptableContentType] {
+ [.json, .text, .binary]
+ }
+ public init?(rawValue: String) {
+ let lowercasedRawValue = rawValue.lowercased()
+ switch lowercasedRawValue {
+ case "application/json":
+ self = .json
+ case "text/plain":
+ self = .text
+ case "application/octet-stream":
+ self = .binary
+ default:
+ self = .other(rawValue)
+ }
+ }
+ public var rawValue: String {
+ switch self {
+ case .json:
+ return "application/json"
+ case .text:
+ return "text/plain"
+ case .binary:
+ return "application/octet-stream"
+ case .other(let value):
+ return value
+ }
+ }
+ }
+ public typealias Accept = [AcceptHeaderContentType<AcceptableContentType>] | FWIW I think just using the type directly is clearer for the caller. |
swift-openapi-generator | github_2023 | others | 185 | apple | glbrntt | @@ -61,6 +67,48 @@ final class Test_Client: XCTestCase {
}
}
+ func testGetStats_200_text_customAccept() async throws {
+ transport = .init { request, baseURL, operationID in
+ XCTAssertEqual(operationID, "getStats")
+ XCTAssertEqual(request.path, "/pets/stats")
+ XCTAssertEqual(request.method, .get)
+ XCTAssertEqual(
+ request.headerFields,
+ [
+ .init(name: "accept", value: "application/json; q=0.800, text/plain")
+ ]
+ )
+ XCTAssertNil(request.body)
+ return .init(
+ statusCode: 200,
+ headers: [
+ .init(name: "content-type", value: "text/plain")
+ ],
+ encodedBody: #"""
+ count is 1
+ """#
+ )
+ }
+ let response = try await client.getStats(
+ .init(
+ headers: .init(accept: [
+ .init(quality: 0.8, contentType: .json), | This feels backwards, I'd expect to specify the content type and then it's q-factor. |
swift-openapi-generator | github_2023 | others | 185 | apple | gjcairo | @@ -0,0 +1,216 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 declaration of the specified raw representable enum.
+ /// - Parameters:
+ /// - typeName: The name of the type to give to the declared enum.
+ /// - conformances: The list of types the enum conforms to.
+ /// - userDescription: The contents of the documentation comment.
+ /// - cases: The list of cases to generate.
+ /// - unknownCaseName: The name of the extra unknown case that preserves | Should we document that, if absent, we won't generate unknown cases? |
swift-openapi-generator | github_2023 | others | 208 | apple | gjcairo | @@ -72,3 +72,56 @@ MyOpenOneOf:
- #/components/schemas/Baz
- type: object
```
+
+### Server-sent Events/EventSource
+
+While [Server-sent Events](https://en.wikipedia.org/wiki/Server-sent_events) are not explicitly part of the OpenAPI 3.0 or 3.1 specification, you can document an operation that returns SSE and also the event payloads themselves.
+
+> Important: Until [async bodies](https://github.com/apple/swift-openapi-generator/issues/9) are supported in Swift OpenAPI Generator are supported, SSE are of limited value, as bodies are fully buffered before being returned to the caller. | ```suggestion
> Important: Until [async bodies](https://github.com/apple/swift-openapi-generator/issues/9) are supported in Swift OpenAPI Generator, SSE are of limited value, as bodies are fully buffered before being returned to the caller.
``` |
swift-openapi-generator | github_2023 | others | 196 | apple | czechboy0 | @@ -43,7 +43,11 @@ extension TypesFileTranslator {
} else {
associatedDeclarations = []
}
+
+ let comment: Comment? = parent.docCommentWithUserDescription(nil,
+ subPath: "\(parameter.location.rawValue)/\(parameter.name)") | ```suggestion
let comment: Comment? = parent.docCommentWithUserDescription(
nil,
subPath: "\(parameter.location.rawValue)/\(parameter.name)"
)
```
Nit: whitespace |
swift-openapi-generator | github_2023 | others | 196 | apple | czechboy0 | @@ -41,6 +41,7 @@ extension TypesFileTranslator {
/// - Returns: A list of declarations; empty if the request body is
/// unsupported.
func requestBodyContentCases(
+ typeName: TypeName, | ```suggestion
```
You shouldn't need to pass this type in, it's already present on `requestBody.typeUsage.typeName`. |
swift-openapi-generator | github_2023 | others | 196 | apple | czechboy0 | @@ -54,13 +55,20 @@ extension TypesFileTranslator {
}
let identifier = contentSwiftName(content.content.contentType)
let associatedType = content.resolvedTypeUsage
- let contentCase: Declaration = .enumCase(
- .init(
+
+ let subPath: String = {
+ let contentPath = typeName.isComponent ? "content" : "requestBody/content"
+ return "\(contentPath)/\(content.content.contentType.lowercasedTypeAndSubtypeWithEscape)"
+ }()
+
+ let contentCase: Declaration = .commentable(
+ typeName.docCommentWithUserDescription(nil, subPath: subPath),
+ .enumCase(.init( | ```suggestion
.enumCase(
```
I think we have a utility function on `Declaration` that allows passing in the parameters directly, don't we? |
swift-openapi-generator | github_2023 | others | 196 | apple | czechboy0 | @@ -131,7 +139,8 @@ extension TypesFileTranslator {
requestBody: TypedRequestBody
) throws -> Declaration {
let type = requestBody.typeUsage.typeName
- let members = try requestBodyContentCases(for: requestBody)
+ let members = try requestBodyContentCases(typeName: type,
+ for: requestBody) | ```suggestion
let members = try requestBodyContentCases(for: requestBody)
```
As commented above, I don't think we need to pass it in, the type name should already be present on `requestBody`. |
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 = "", | ```suggestion
responseKind: ResponseKind,
```
If the response kind is needed, pass it in as the typesafe type `ResponseKind` and don't provide a default value, we want to make sure all callers are updated. |
swift-openapi-generator | github_2023 | others | 196 | apple | czechboy0 | @@ -34,10 +35,19 @@ extension TypesFileTranslator {
inParent: headersTypeName
)
let headerProperties: [PropertyBlueprint] = try headers.map { header in
- try parseResponseHeaderAsProperty(for: header)
+ try parseResponseHeaderAsProperty(
+ responseKind: responseKind,
+ typeName: typeName,
+ for: header)
}
+ let headerStructComment: Comment? = {
+ let subPath = typeName.isComponent
+ ? "headers"
+ : "reponses/\(responseKind)/headers" | ```suggestion
: "responses/\(responseKind)/headers"
```
Typo |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.