From 3f8542bc59032bf395cd471cbc181eaa9fe12030 Mon Sep 17 00:00:00 2001 From: PARAIPAN SORIN <51127880+PARAIPAN9@users.noreply.github.com> Date: Wed, 11 Oct 2023 11:25:11 +0300 Subject: [PATCH] Fixes #165 - Enable documentation comment validation in swift-format (#188) ### Motivation This is for better documentation Fixes #165 ### Modifications Enabled some rules in .swift-format ### Result The .swift-format will be changed and the rules will reflect into the project ### Test Plan Run tests and CI --- .swift-format | 4 +- .../GreetingService/GreetingService.swift | 12 +++++ .../PetstoreConsumerTestCore/Assertions.swift | 5 ++- Sources/PetstoreConsumerTestCore/Common.swift | 2 + .../TestClientTransport.swift | 29 ++++++++++++ .../TestServerTransport.swift | 44 ++++++++++++++++++- .../_OpenAPIGeneratorCore/Diagnostics.swift | 9 ++++ .../Extensions/Foundation.swift | 7 +++ .../Extensions/OpenAPIKit.swift | 2 + .../Extensions/String.swift | 1 + .../_OpenAPIGeneratorCore/GeneratorMode.swift | 1 + .../GeneratorPipeline.swift | 2 + .../GeneratorPipelineStage.swift | 1 + .../Layers/RenderedSwiftRepresentation.swift | 1 + .../StructuredSwiftRepresentation.swift | 28 ++++++++++++ .../Parser/ParserProtocol.swift | 1 + .../Parser/YamsParser.swift | 9 ++-- .../Parser/validateDoc.swift | 1 + .../Renderer/RendererProtocol.swift | 1 + .../Renderer/TextBasedRenderer.swift | 4 ++ .../translateClientMethod.swift | 7 +++ .../CommonTranslations/SwiftSafeNames.swift | 1 + .../translateAllAnyOneOf.swift | 8 +++- .../CommonTranslations/translateArray.swift | 2 + .../CommonTranslations/translateCodable.swift | 38 ++++++++++------ .../translateObjectStruct.swift | 14 ++++-- .../translateRawRepresentableEnum.swift | 2 + .../CommonTranslations/translateSchema.swift | 4 ++ .../translateStringEnum.swift | 2 + .../translateStructBlueprint.swift | 8 +++- .../translateTypealias.swift | 5 ++- .../Translator/CommonTypes/Annotations.swift | 1 + .../CommonTypes/CommentExtensions.swift | 25 ++++++++--- .../CommonTypes/DiscriminatorExtensions.swift | 4 ++ .../Translator/Content/ContentInspector.swift | 4 ++ .../Translator/Content/ContentSwiftName.swift | 1 + .../Translator/FileTranslator.swift | 1 + .../Operations/OperationDescription.swift | 2 + .../Parameters/TypedParameter.swift | 3 ++ .../Parameters/translateParameter.swift | 8 ++++ .../RequestBody/TypedRequestBody.swift | 6 ++- .../RequestBody/translateRequestBody.swift | 12 +++-- .../Responses/HTTPStatusCodes.swift | 1 + .../Translator/Responses/TypedResponse.swift | 4 +- .../Responses/TypedResponseHeader.swift | 5 +++ .../Responses/acceptHeaderContentTypes.swift | 1 + .../Responses/translateResponse.swift | 9 +++- .../Responses/translateResponseHeader.swift | 5 +++ .../Responses/translateResponseOutcome.swift | 8 ++++ .../ServerTranslator/ServerTranslator.swift | 3 ++ .../translateServerMethod.swift | 9 +++- .../Translator/TranslatorProtocol.swift | 1 + .../Translator/TypeAssignment/Builtins.swift | 4 ++ .../TypeAssignment/TypeAssigner.swift | 19 ++++++++ .../TypeAssignment/TypeMatcher.swift | 5 +++ .../Translator/TypeAssignment/TypeName.swift | 2 +- .../Translator/TypeAssignment/TypeUsage.swift | 2 + .../TypeAssignment/isSchemaSupported.swift | 20 +++++++-- .../translateComponentHeaders.swift | 1 + .../translateComponentParameters.swift | 1 + .../translateComponentRequestBodies.swift | 3 +- .../translateComponentResponses.swift | 1 + .../TypesTranslator/translateComponents.swift | 1 + .../TypesTranslator/translateOperations.swift | 5 +++ .../TypesTranslator/translateSchemas.swift | 2 + .../swift-openapi-generator/Extensions.swift | 5 +++ .../GenerateOptions+runGenerator.swift | 2 + .../GenerateOptions.swift | 5 +++ .../runGenerator.swift | 7 ++- .../CompatabilityTest.swift | 2 + Tests/PetstoreConsumerTests/Common.swift | 6 +++ scripts/run-swift-format.sh | 2 + 72 files changed, 408 insertions(+), 55 deletions(-) diff --git a/.swift-format b/.swift-format index efbc73c4..e966451a 100644 --- a/.swift-format +++ b/.swift-format @@ -16,7 +16,7 @@ "prioritizeKeepingFunctionOutputTogether" : false, "respectsExistingLineBreaks" : true, "rules" : { - "AllPublicDeclarationsHaveDocumentation" : false, + "AllPublicDeclarationsHaveDocumentation" : true, "AlwaysUseLowerCamelCase" : false, "AmbiguousTrailingClosureOverload" : true, "BeginDocumentationCommentWithOneLineSummary" : false, @@ -50,7 +50,7 @@ "UseSynthesizedInitializer" : true, "UseTripleSlashForDocumentationComments" : true, "UseWhereClausesInForLoops" : false, - "ValidateDocumentationComments" : false + "ValidateDocumentationComments" : true }, "spacesAroundRangeFormationOperators" : false, "tabWidth" : 8, diff --git a/Examples/GreetingService/Sources/GreetingService/GreetingService.swift b/Examples/GreetingService/Sources/GreetingService/GreetingService.swift index b3cebf7a..3c6c38fd 100644 --- a/Examples/GreetingService/Sources/GreetingService/GreetingService.swift +++ b/Examples/GreetingService/Sources/GreetingService/GreetingService.swift @@ -32,6 +32,18 @@ struct Handler: APIProtocol { @main struct Main { + /// The entry point of the program. + /// + /// This is where the execution of the program begins. Any code you want to run + /// when the program starts should be placed within this method. + /// + /// Example: + /// ``` + /// public static func main() { + /// print("Hello, World!") + /// } + /// ``` + /// - Throws: An error of type `Error` if there's an issue creating or running the Vapor application. public static func main() throws { // Create a Vapor application. let app = Vapor.Application() diff --git a/Sources/PetstoreConsumerTestCore/Assertions.swift b/Sources/PetstoreConsumerTestCore/Assertions.swift index 9edc3d3a..9b85bd21 100644 --- a/Sources/PetstoreConsumerTestCore/Assertions.swift +++ b/Sources/PetstoreConsumerTestCore/Assertions.swift @@ -15,6 +15,7 @@ import Foundation import XCTest import OpenAPIRuntime +/// Asserts that the stringified data matches the expected string value. public func XCTAssertEqualStringifiedData( _ expression1: @autoclosure () throws -> Data?, _ expression2: @autoclosure () throws -> String, @@ -33,7 +34,7 @@ public func XCTAssertEqualStringifiedData( XCTFail(error.localizedDescription, file: file, line: line) } } - +/// Asserts that the stringified data matches the expected string value. public func XCTAssertEqualStringifiedData( _ expression1: @autoclosure () throws -> S?, _ expression2: @autoclosure () throws -> String, @@ -52,7 +53,7 @@ public func XCTAssertEqualStringifiedData( XCTFail(error.localizedDescription, file: file, line: line) } } - +/// Asserts that the stringified data matches the expected string value. public func XCTAssertEqualStringifiedData( _ expression1: @autoclosure () throws -> HTTPBody?, _ expression2: @autoclosure () throws -> String, diff --git a/Sources/PetstoreConsumerTestCore/Common.swift b/Sources/PetstoreConsumerTestCore/Common.swift index b60f3450..52516cd1 100644 --- a/Sources/PetstoreConsumerTestCore/Common.swift +++ b/Sources/PetstoreConsumerTestCore/Common.swift @@ -21,6 +21,7 @@ public enum TestError: Swift.Error, LocalizedError, CustomStringConvertible, Sen case unexpectedValue(any Sendable) case unexpectedMissingRequestBody + /// A human-readable description of the error. public var description: String { switch self { case .noHandlerFound(let method, let path): @@ -34,6 +35,7 @@ public enum TestError: Swift.Error, LocalizedError, CustomStringConvertible, Sen } } + /// A localized description of the error suitable for presenting to the user. public var errorDescription: String? { description } diff --git a/Sources/PetstoreConsumerTestCore/TestClientTransport.swift b/Sources/PetstoreConsumerTestCore/TestClientTransport.swift index 8aa8273d..0edb12fe 100644 --- a/Sources/PetstoreConsumerTestCore/TestClientTransport.swift +++ b/Sources/PetstoreConsumerTestCore/TestClientTransport.swift @@ -15,18 +15,47 @@ import OpenAPIRuntime import Foundation import HTTPTypes +/// A test implementation of the `ClientTransport` protocol. +/// +/// The `TestClientTransport` struct provides a way to simulate network calls by +/// utilizing a custom `CallHandler` closure. This allows testing the behavior of +/// client-side API interactions in controlled scenarios. +/// +/// Example usage: +/// ```swift +/// let testTransport = TestClientTransport { request, baseURL, operationID in +/// // Simulate response logic here +/// return Response(...) +/// } +/// +/// let client = APIClient(transport: testTransport) +/// ``` public struct TestClientTransport: ClientTransport { + /// A typealias representing a call handler closure for processing client requests. public typealias CallHandler = @Sendable (HTTPRequest, HTTPBody?, URL, String) async throws -> ( HTTPResponse, HTTPBody? ) + /// The call handler responsible for processing client requests. public let callHandler: CallHandler + /// Initializes a `TestClientTransport` instance with a custom call handler. + /// + /// - Parameter callHandler: The closure responsible for processing client requests. public init(callHandler: @escaping CallHandler) { self.callHandler = callHandler } + /// Sends a client request using the test transport. + /// + /// - Parameters: + /// - request: The request to send. + /// - body: The optional HTTP body to include in the request. + /// - baseURL: The base URL for the request. + /// - operationID: The ID of the operation being performed. + /// - Returns: The response received from the call handler. + /// - Throws: An error if the call handler encounters an issue. public func send( _ request: HTTPRequest, body: HTTPBody?, diff --git a/Sources/PetstoreConsumerTestCore/TestServerTransport.swift b/Sources/PetstoreConsumerTestCore/TestServerTransport.swift index 9d1933bd..8e339171 100644 --- a/Sources/PetstoreConsumerTestCore/TestServerTransport.swift +++ b/Sources/PetstoreConsumerTestCore/TestServerTransport.swift @@ -14,35 +14,77 @@ import OpenAPIRuntime import HTTPTypes +/// A test implementation of the `ServerTransport` protocol for simulating server-side API handling. +/// +/// The `TestServerTransport` class allows you to define custom operations and handlers that +/// simulate server-side API handling. This is useful for testing and verifying the behavior of +/// your server-related code without the need for actual network interactions. +/// +/// Example usage: +/// ```swift +/// let testTransport = TestServerTransport() +/// try testTransport.register { request, metadata in +/// // Simulate server response logic here +/// return Response(...) +/// } +/// +/// let server = MyServer(transport: testTransport) +/// ``` public final class TestServerTransport: ServerTransport { - + /// Represents the input parameters for an API operation. public struct OperationInputs: Equatable { + /// The HTTP method of the operation. public var method: HTTPRequest.Method + /// The path components of the operation's route. public var path: String + /// Initializes a new instance of `OperationInputs`. + /// + /// - Parameters: + /// - method: The HTTP method of the operation. + /// - path: The path components of the operation's route. public init(method: HTTPRequest.Method, path: String) { self.method = method self.path = path } } + /// A typealias representing a handler closure for processing server requests. public typealias Handler = @Sendable (HTTPRequest, HTTPBody?, ServerRequestMetadata) async throws -> ( HTTPResponse, HTTPBody? ) + /// Represents an operation with its inputs and associated handler. public struct Operation { + /// The input parameters for the API operation. public var inputs: OperationInputs + /// The closure representing the server operation logic. public var closure: Handler + /// Initializes a new instance of `Operation`. + /// + /// - Parameters: + /// - inputs: The input parameters for the API operation. + /// - closure: The closure representing the server operation logic public init(inputs: OperationInputs, closure: @escaping Handler) { self.inputs = inputs self.closure = closure } } + /// Initializes a new instance of `TestServerTransport`. public init() {} + + /// The array of registered operations. public private(set) var registered: [Operation] = [] + /// Registers a new API operation handler with specific parameters. + /// + /// - Parameters: + /// - handler: The closure representing the server operation logic. + /// - method: The HTTP method of the operation. + /// - path: The path components of the operation. + /// - Throws: An error if there's an issue registering the operation. public func register( _ handler: @Sendable @escaping (HTTPRequest, HTTPBody?, ServerRequestMetadata) async throws -> ( HTTPResponse, HTTPBody? diff --git a/Sources/_OpenAPIGeneratorCore/Diagnostics.swift b/Sources/_OpenAPIGeneratorCore/Diagnostics.swift index b96e0c5b..a413d1f9 100644 --- a/Sources/_OpenAPIGeneratorCore/Diagnostics.swift +++ b/Sources/_OpenAPIGeneratorCore/Diagnostics.swift @@ -142,12 +142,14 @@ public struct Diagnostic: Error, Codable, Sendable { } extension Diagnostic.Severity: CustomStringConvertible { + /// A textual representation of the diagnostic severity. public var description: String { rawValue } } extension Diagnostic: CustomStringConvertible { + /// A textual representation of the diagnostic, including location, severity, message, and context. public var description: String { var prefix = "" if let location = location { @@ -163,6 +165,7 @@ extension Diagnostic: CustomStringConvertible { } extension Diagnostic: LocalizedError { + /// A localized description of the diagnostic. public var errorDescription: String? { description } @@ -321,6 +324,9 @@ struct PrintingDiagnosticCollector: DiagnosticCollector { /// Creates a new collector. public init() {} + /// Emits a diagnostic message by printing it to the standard output. + /// + /// - Parameter diagnostic: The diagnostic message to emit. public func emit(_ diagnostic: Diagnostic) { print(diagnostic.description) } @@ -331,6 +337,9 @@ public struct StdErrPrintingDiagnosticCollector: DiagnosticCollector, Sendable { /// Creates a new collector. public init() {} + /// Emits a diagnostic message to standard error. + /// + /// - Parameter diagnostic: The diagnostic message to emit. public func emit(_ diagnostic: Diagnostic) { stdErrHandle.write(diagnostic.description) } diff --git a/Sources/_OpenAPIGeneratorCore/Extensions/Foundation.swift b/Sources/_OpenAPIGeneratorCore/Extensions/Foundation.swift index 3bdf97b8..8dbe00df 100644 --- a/Sources/_OpenAPIGeneratorCore/Extensions/Foundation.swift +++ b/Sources/_OpenAPIGeneratorCore/Extensions/Foundation.swift @@ -30,6 +30,7 @@ extension Data { extension InMemoryInputFile { /// Creates a new in-memory file by reading the contents at the specified path. /// - Parameter url: The path to the file to read. + /// - Throws: An error if there's an issue reading the file or initializing the in-memory file. init(fromFileAt url: URL) throws { try self.init(absolutePath: url, contents: Data(contentsOf: url)) } @@ -50,6 +51,12 @@ extension InMemoryOutputFile { let stdErrHandle = FileHandle.standardError extension FileHandle: TextOutputStream { + /// Writes the given string to the file handle. + /// + /// This method writes the provided string to the file handle using its UTF-8 + /// representation. + /// + /// - Parameter string: The string to be written to the file handle. public func write(_ string: String) { write(Data(string.utf8)) } diff --git a/Sources/_OpenAPIGeneratorCore/Extensions/OpenAPIKit.swift b/Sources/_OpenAPIGeneratorCore/Extensions/OpenAPIKit.swift index 98e0a8e3..bdd44c94 100644 --- a/Sources/_OpenAPIGeneratorCore/Extensions/OpenAPIKit.swift +++ b/Sources/_OpenAPIGeneratorCore/Extensions/OpenAPIKit.swift @@ -18,6 +18,8 @@ extension Either { /// Returns the contained value, looking it up in the specified /// OpenAPI components if it contains a reference. /// - Parameter components: The Components section of the OpenAPI document. + /// - Returns: The resolved value from the `Either` instance. + /// - Throws: An error if there's an issue looking up the value in the components. func resolve( in components: OpenAPI.Components ) throws -> B where A == OpenAPI.Reference { diff --git a/Sources/_OpenAPIGeneratorCore/Extensions/String.swift b/Sources/_OpenAPIGeneratorCore/Extensions/String.swift index 14c4235b..6b4eaaa3 100644 --- a/Sources/_OpenAPIGeneratorCore/Extensions/String.swift +++ b/Sources/_OpenAPIGeneratorCore/Extensions/String.swift @@ -31,6 +31,7 @@ fileprivate extension String { /// Returns a copy of the string with the first letter modified by /// the specified closure. /// - Parameter transformation: A closure that modifies the first letter. + /// - Returns: A new string with the modified first letter, or the original string if no letter is found. func transformingFirstLetter(_ transformation: (Character) -> T) -> String where T: StringProtocol { guard let firstLetterIndex = self.firstIndex(where: \.isLetter) else { return self diff --git a/Sources/_OpenAPIGeneratorCore/GeneratorMode.swift b/Sources/_OpenAPIGeneratorCore/GeneratorMode.swift index ca758a7e..675449c2 100644 --- a/Sources/_OpenAPIGeneratorCore/GeneratorMode.swift +++ b/Sources/_OpenAPIGeneratorCore/GeneratorMode.swift @@ -67,6 +67,7 @@ extension GeneratorMode { } extension GeneratorMode: Comparable { + /// Compares modes based on their order. public static func < (lhs: GeneratorMode, rhs: GeneratorMode) -> Bool { lhs.order < rhs.order } diff --git a/Sources/_OpenAPIGeneratorCore/GeneratorPipeline.swift b/Sources/_OpenAPIGeneratorCore/GeneratorPipeline.swift index 1b508b70..62171cb9 100644 --- a/Sources/_OpenAPIGeneratorCore/GeneratorPipeline.swift +++ b/Sources/_OpenAPIGeneratorCore/GeneratorPipeline.swift @@ -67,6 +67,7 @@ struct GeneratorPipeline { /// recoverable diagnostics, such as unsupported features. /// - Parameter input: The input of the parsing stage. /// - Returns: The output of the rendering stage. + /// - Throws: An error if a non-recoverable issue occurs during pipeline execution. func run(_ input: RawInput) throws -> RenderedOutput { try renderSwiftFilesStage.run( translateOpenAPIToStructuredSwiftStage.run( @@ -97,6 +98,7 @@ public func runGenerator( /// Creates a new pipeline instance. /// - Parameters: /// - parser: An OpenAPI document parser. +/// - validator: A validator for parsed OpenAPI documents. /// - translator: A translator from OpenAPI to Swift. /// - renderer: A Swift code renderer. /// - formatter: A Swift code formatter. diff --git a/Sources/_OpenAPIGeneratorCore/GeneratorPipelineStage.swift b/Sources/_OpenAPIGeneratorCore/GeneratorPipelineStage.swift index 2c53c967..c07609e9 100644 --- a/Sources/_OpenAPIGeneratorCore/GeneratorPipelineStage.swift +++ b/Sources/_OpenAPIGeneratorCore/GeneratorPipelineStage.swift @@ -36,6 +36,7 @@ struct GeneratorPipelineStage { /// value or throwing an error. /// - Parameter input: An input value. /// - Returns: An output value. + /// - Throws: An error if an issue occurs during the stage execution. func run(_ input: Input) throws -> Output { let hookedInput = try self.preTransitionHooks.reduce(input) { try $1($0) } let output = try self.transition(hookedInput) diff --git a/Sources/_OpenAPIGeneratorCore/Layers/RenderedSwiftRepresentation.swift b/Sources/_OpenAPIGeneratorCore/Layers/RenderedSwiftRepresentation.swift index 5e8cda52..a78b9bea 100644 --- a/Sources/_OpenAPIGeneratorCore/Layers/RenderedSwiftRepresentation.swift +++ b/Sources/_OpenAPIGeneratorCore/Layers/RenderedSwiftRepresentation.swift @@ -63,6 +63,7 @@ public struct InMemoryOutputFile: Sendable { } extension InMemoryOutputFile: Comparable { + /// Compares two `InMemoryOutputFile` instances based on `baseName` and contents for ordering. public static func < (lhs: InMemoryOutputFile, rhs: InMemoryOutputFile) -> Bool { guard lhs.baseName == rhs.baseName else { return lhs.baseName < rhs.baseName diff --git a/Sources/_OpenAPIGeneratorCore/Layers/StructuredSwiftRepresentation.swift b/Sources/_OpenAPIGeneratorCore/Layers/StructuredSwiftRepresentation.swift index 106040d5..3cffc8f1 100644 --- a/Sources/_OpenAPIGeneratorCore/Layers/StructuredSwiftRepresentation.swift +++ b/Sources/_OpenAPIGeneratorCore/Layers/StructuredSwiftRepresentation.swift @@ -1215,12 +1215,14 @@ extension CodeBlock { /// Returns a new declaration code block wrapping the provided declaration. /// - Parameter declaration: The declaration to wrap. + /// - Returns: A new `CodeBlock` instance containing the provided declaration. static func declaration(_ declaration: Declaration) -> Self { return CodeBlock(item: .declaration(declaration)) } /// Returns a new expression code block wrapping the provided expression. /// - Parameter expression: The expression to wrap. + /// - Returns: A new `CodeBlock` instance containing the provided declaration. static func expression(_ expression: Expression) -> Self { return CodeBlock(item: .expression(expression)) } @@ -1232,6 +1234,7 @@ extension Expression { /// /// For example: `"hello"`. /// - Parameter value: The string value of the literal. + /// - Returns: A new `Expression` representing a string literal. static func literal(_ value: String) -> Self { .literal(.string(value)) } @@ -1240,6 +1243,7 @@ extension Expression { /// /// For example `42`. /// - Parameter value: The integer value of the literal. + /// - Returns: A new `Expression` representing an integer literal. static func literal(_ value: Int) -> Self { .literal(.int(value)) } @@ -1247,6 +1251,7 @@ extension Expression { /// Returns a new expression that accesses the member on the current /// expression. /// - Parameter member: The name of the member to access on the expression. + /// - Returns: A new expression representing member access. func dot(_ member: String) -> Expression { return .memberAccess(.init(left: self, right: member)) } @@ -1254,6 +1259,7 @@ extension Expression { /// Returns a new expression that calls the current expression as a function /// with the specified arguments. /// - Parameter arguments: The arguments used to call the expression. + /// - Returns: A new expression representing a function call. func call(_ arguments: [FunctionArgumentDescription]) -> Expression { .functionCall(.init(calledExpression: self, arguments: arguments)) } @@ -1263,12 +1269,14 @@ extension Expression { /// /// For example: `.foo`, where `member` is `foo`. /// - Parameter member: The name of the member to access. + /// - Returns: A new expression representing member access with a dot prefix. static func dot(_ member: String) -> Self { return Self.memberAccess(.init(right: member)) } /// Returns a new identifier expression for the provided name. /// - Parameter name: The name of the identifier. + /// - Returns: A new expression representing an identifier with the specified name. static func identifier(_ name: String) -> Self { .identifier(.init(name: name)) } @@ -1278,6 +1286,7 @@ extension Expression { /// - switchedExpression: The expression evaluated by the switch /// statement. /// - cases: The cases defined in the switch statement. + /// - Returns: A new expression representing a switch statement with the specified switched expression and cases static func `switch`( switchedExpression: Expression, cases: [SwitchCaseDescription] @@ -1296,6 +1305,7 @@ extension Expression { /// - ifBranch: The primary `if` branch. /// - elseIfBranches: Additional `else if` branches. /// - elseBody: The body of an else block. + /// - Returns: A new expression representing an `if` statement with the specified branches and blocks. static func ifStatement( ifBranch: IfBranch, elseIfBranches: [IfBranch] = [], @@ -1316,6 +1326,7 @@ extension Expression { /// - Parameters: /// - calledExpression: The expression to be called as a function. /// - arguments: The arguments to be passed to the function call. + /// - Returns: A new expression representing a function call with the specified called expression and arguments. static func functionCall( calledExpression: Expression, arguments: [FunctionArgumentDescription] = [] @@ -1334,6 +1345,7 @@ extension Expression { /// - Parameters: /// - calledExpression: The expression called as a function. /// - arguments: The arguments passed to the function call. + /// - Returns: A new expression representing a function call with the specified called expression and arguments. static func functionCall( calledExpression: Expression, arguments: [Expression] @@ -1350,6 +1362,7 @@ extension Expression { /// - Parameters: /// - kind: The keyword to place before the expression. /// - expression: The expression prefixed by the keyword. + /// - Returns: A new expression with the specified keyword placed before the expression. static func unaryKeyword( kind: KeywordKind, expression: Expression? = nil @@ -1360,6 +1373,7 @@ extension Expression { /// Returns a new expression that puts the return keyword before /// an expression. /// - Parameter expression: The expression to prepend. + /// - Returns: A new expression with the `return` keyword placed before the expression. static func `return`(_ expression: Expression? = nil) -> Self { .unaryKeyword(kind: .return, expression: expression) } @@ -1367,6 +1381,7 @@ extension Expression { /// Returns a new expression that puts the try keyword before /// an expression. /// - Parameter expression: The expression to prepend. + /// - Returns: A new expression with the `try` keyword placed before the expression. static func `try`(_ expression: Expression) -> Self { .unaryKeyword(kind: .try, expression: expression) } @@ -1374,6 +1389,7 @@ extension Expression { /// Returns a new expression that puts the try? keyword before /// an expression. /// - Parameter expression: The expression to prepend. + /// - Returns: A new expression with the `try?` keyword placed before the expression. static func optionalTry(_ expression: Expression) -> Self { .unaryKeyword( kind: .try(hasPostfixQuestionMark: true), @@ -1384,6 +1400,7 @@ extension Expression { /// Returns a new expression that puts the await keyword before /// an expression. /// - Parameter expression: The expression to prepend. + /// - Returns: A new expression with the `await` keyword placed before the expression. static func `await`(_ expression: Expression) -> Self { .unaryKeyword(kind: .await, expression: expression) } @@ -1394,6 +1411,7 @@ extension Expression { /// - Parameters: /// - kind: The binding kind: `let` or `var`. /// - value: The bound values in a function call expression syntax. + /// - Returns: A new expression representing the value binding. static func valueBinding( kind: BindingKind, value: FunctionCallDescription @@ -1407,6 +1425,7 @@ extension Expression { /// - Parameters: /// - argumentNames: The names of the arguments taken by the closure. /// - body: The code blocks of the closure body. + /// - Returns: A new expression representing the closure invocation static func `closureInvocation`( argumentNames: [String] = [], body: [CodeBlock]? = nil @@ -1421,6 +1440,7 @@ extension Expression { /// - left: The left-hand side expression of the operation. /// - operation: The binary operator tying the two expressions together. /// - right: The right-hand side expression of the operation. + /// - Returns: A new expression representing the binary operation. static func `binaryOperation`( left: Expression, operation: BinaryOperator, @@ -1434,6 +1454,7 @@ extension Expression { /// /// For example, `&foo` passes a reference to the `foo` variable. /// - Parameter referencedExpr: The referenced expression. + /// - Returns: A new expression representing the inout expression. static func inOut(_ referencedExpr: Expression) -> Self { .inOut(.init(referencedExpr: referencedExpr)) } @@ -1453,6 +1474,7 @@ extension Expression { /// expression. /// /// For example, for the current expression `foo`, returns `foo?`. + /// - Returns: A new expression representing the optional chaining operation. func optionallyChained() -> Self { .optionalChaining(.init(referencedExpr: self)) } @@ -1473,6 +1495,7 @@ extension MemberAccessDescription { /// /// For example, `.foo`, where `member` is `foo`. /// - Parameter member: The name of the member to access. + /// - Returns: A new member access expression. static func dot(_ member: String) -> Self { .init(right: member) } @@ -1512,6 +1535,7 @@ extension VariableDescription { /// /// For example `var foo = 42`. /// - Parameter name: The name of the variable. + /// - Returns: A new mutable variable declaration. static func `var`(_ name: String) -> Self { Self.init(kind: .var, left: name) } @@ -1520,6 +1544,7 @@ extension VariableDescription { /// /// For example `let foo = 42`. /// - Parameter name: The name of the variable. + /// - Returns: A new immutable variable declaration. static func `let`(_ name: String) -> Self { Self.init(kind: .let, left: name) } @@ -1530,6 +1555,7 @@ extension Expression { /// Creates a new assignment description where the called expression is /// assigned the value of the specified expression. /// - Parameter rhs: The right-hand side of the assignment expression. + /// - Returns: An assignment description representing the assignment. func equals(_ rhs: Expression) -> AssignmentDescription { .init(left: self, right: rhs) } @@ -1545,6 +1571,7 @@ extension FunctionSignatureDescription { /// Returns a new function signature description that has the access /// modifier updated to the specified one. /// - Parameter accessModifier: The access modifier to use. + /// - Returns: A function signature description with the specified access modifier. func withAccessModifier(_ accessModifier: AccessModifier?) -> Self { var value = self value.accessModifier = accessModifier @@ -1556,6 +1583,7 @@ extension SwitchCaseKind { /// Returns a new switch case kind with no argument names, only the /// specified expression as the name. /// - Parameter expression: The expression for the switch case label. + /// - Returns: A switch case kind with the specified expression as the label. static func `case`(_ expression: Expression) -> Self { .case(expression, []) } diff --git a/Sources/_OpenAPIGeneratorCore/Parser/ParserProtocol.swift b/Sources/_OpenAPIGeneratorCore/Parser/ParserProtocol.swift index 30df1df8..26a82b80 100644 --- a/Sources/_OpenAPIGeneratorCore/Parser/ParserProtocol.swift +++ b/Sources/_OpenAPIGeneratorCore/Parser/ParserProtocol.swift @@ -24,6 +24,7 @@ protocol ParserProtocol { /// - config: The configuration of the generator. /// - diagnostics: The collector to which to emit diagnostics. /// - Returns: A parsed and validated OpenAPI document. + /// - Throws: An error if an issue occurs during parsing or validation. func parseOpenAPI( _ input: InMemoryInputFile, config: Config, diff --git a/Sources/_OpenAPIGeneratorCore/Parser/YamsParser.swift b/Sources/_OpenAPIGeneratorCore/Parser/YamsParser.swift index af54d945..b7493e77 100644 --- a/Sources/_OpenAPIGeneratorCore/Parser/YamsParser.swift +++ b/Sources/_OpenAPIGeneratorCore/Parser/YamsParser.swift @@ -93,11 +93,12 @@ public struct YamsParser: ParserProtocol { } } - /// Detect specific YAML parsing errors to throw nicely formatted diagnostics for IDEs + /// Detects specific YAML parsing errors to throw nicely formatted diagnostics for IDEs. + /// /// - Parameters: - /// - context: The error context that triggered the `DecodingError`. - /// - input: The input file that was being worked on when the error was triggered. - /// - Throws: Will throw a `Diagnostic` if the decoding error is a common parsing error. + /// - context: The decoding error context that triggered the parsing error. + /// - input: The input file being worked on when the parsing error was triggered. + /// - Throws: Throws a `Diagnostic` if the decoding error is a common parsing error. private func checkParsingError( context: DecodingError.Context, input: InMemoryInputFile diff --git a/Sources/_OpenAPIGeneratorCore/Parser/validateDoc.swift b/Sources/_OpenAPIGeneratorCore/Parser/validateDoc.swift index 49f541fc..a14ddccd 100644 --- a/Sources/_OpenAPIGeneratorCore/Parser/validateDoc.swift +++ b/Sources/_OpenAPIGeneratorCore/Parser/validateDoc.swift @@ -18,6 +18,7 @@ import OpenAPIKit /// - Parameters: /// - doc: The OpenAPI document to validate. /// - config: The generator config. +/// - Returns: An array of diagnostic messages representing validation warnings. /// - Throws: An error if a fatal issue is found. func validateDoc(_ doc: ParsedOpenAPIRepresentation, config: Config) throws -> [Diagnostic] { // Run OpenAPIKit's built-in validation. diff --git a/Sources/_OpenAPIGeneratorCore/Renderer/RendererProtocol.swift b/Sources/_OpenAPIGeneratorCore/Renderer/RendererProtocol.swift index c76842f9..8ebcc645 100644 --- a/Sources/_OpenAPIGeneratorCore/Renderer/RendererProtocol.swift +++ b/Sources/_OpenAPIGeneratorCore/Renderer/RendererProtocol.swift @@ -24,6 +24,7 @@ protocol RendererProtocol { /// - config: The configuration of the generator. /// - diagnostics: The collector to which to emit diagnostics. /// - Returns: A raw file with Swift contents. + /// - Throws: An error if an issue occurs during rendering. func render( structured code: StructuredSwiftRepresentation, config: Config, diff --git a/Sources/_OpenAPIGeneratorCore/Renderer/TextBasedRenderer.swift b/Sources/_OpenAPIGeneratorCore/Renderer/TextBasedRenderer.swift index e226783e..a1945754 100644 --- a/Sources/_OpenAPIGeneratorCore/Renderer/TextBasedRenderer.swift +++ b/Sources/_OpenAPIGeneratorCore/Renderer/TextBasedRenderer.swift @@ -757,6 +757,7 @@ fileprivate extension Array where Element == String { /// empty lines. /// - Parameter omittingEmptyLines: If `true`, omits empty lines in the /// output. Otherwise, all lines are included in the output. + /// - Returns: A string with the elements of the array joined by newline characters. func joinedLines(omittingEmptyLines: Bool = true) -> String { filter { !omittingEmptyLines || !$0.isEmpty } .joined(separator: "\n") @@ -764,6 +765,7 @@ fileprivate extension Array where Element == String { /// Returns a string where the elements of the array are joined /// by a space character. + /// - Returns: A string with the elements of the array joined by space characters. func joinedWords() -> String { joined(separator: " ") } @@ -773,6 +775,7 @@ fileprivate extension String { /// Returns an array of strings, where each string represents one line /// in the current string. + /// - Returns: An array of strings, each representing one line in the original string. func asLines() -> [String] { split(omittingEmptySubsequences: false, whereSeparator: \.isNewline) .map(String.init) @@ -781,6 +784,7 @@ fileprivate extension String { /// Returns a new string where the provided closure transforms each line. /// The closure takes a string representing one line as a parameter. /// - Parameter work: The closure that transforms each line. + /// - Returns: A new string where each line has been transformed using the given closure. func transformingLines(_ work: (String) -> String) -> String { asLines().map(work).joinedLines() } diff --git a/Sources/_OpenAPIGeneratorCore/Translator/ClientTranslator/translateClientMethod.swift b/Sources/_OpenAPIGeneratorCore/Translator/ClientTranslator/translateClientMethod.swift index b9465c90..b0cb7486 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/ClientTranslator/translateClientMethod.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/ClientTranslator/translateClientMethod.swift @@ -18,6 +18,8 @@ extension ClientFileTranslator { /// Returns an expression that converts an Input type into a request for /// a specified OpenAPI operation. /// - Parameter description: The OpenAPI operation. + /// - Returns: An expression representing the converted request. + /// - Throws: An error if there is an issue during translation. func translateClientSerializer( _ description: OperationDescription ) throws -> Expression { @@ -134,7 +136,10 @@ extension ClientFileTranslator { /// Returns an expression that converts a Response into an Output for /// a specified OpenAPI operation. + /// /// - Parameter description: The OpenAPI operation. + /// - Throws: An error if there is an issue during translation. + /// - Returns: An expression representing the translation of a Response to an Output. func translateClientDeserializer( _ description: OperationDescription ) throws -> Expression { @@ -179,6 +184,8 @@ extension ClientFileTranslator { /// Returns a declaration of a client method that invokes a specified /// OpenAPI operation. /// - Parameter description: The OpenAPI operation. + /// - Throws: An error if there is an issue during translation. + /// - Returns: A declaration representing the translated client method. func translateClientMethod( _ description: OperationDescription ) throws -> Declaration { diff --git a/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/SwiftSafeNames.swift b/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/SwiftSafeNames.swift index 13f67532..c936805a 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/SwiftSafeNames.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/SwiftSafeNames.swift @@ -18,6 +18,7 @@ extension FileTranslator { /// Returns a copy of the string modified to be a valid Swift identifier. /// /// - Parameter string: The string to convert to be safe for Swift. + /// - Returns: A Swift-safe version of the input string. func swiftSafeName(for string: String) -> String { string.safeForSwiftCode } diff --git a/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateAllAnyOneOf.swift b/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateAllAnyOneOf.swift index e200f515..1bf50c2d 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateAllAnyOneOf.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateAllAnyOneOf.swift @@ -32,9 +32,11 @@ extension FileTranslator { /// defined as unnamed schemas in the OpenAPI document. /// - Parameters: /// - typeName: The name of the type to give to the declared structure. - /// - openAPIDescription: A user-specified description from the OpenAPI - /// document. + /// - openAPIDescription: A user-specified description from the OpenAPI document. + /// - type: The type of schema (allOf or anyOf). /// - schemas: The child schemas of the allOf/anyOf. + /// - Throws: An error if there is an issue during translation. + /// - Returns: A declaration representing the translated allOf/anyOf structure. func translateAllOrAnyOf( typeName: TypeName, openAPIDescription: String?, @@ -126,6 +128,8 @@ extension FileTranslator { /// document. /// - discriminator: A discriminator specified in the OpenAPI document. /// - schemas: The child schemas of the oneOf. + /// - Throws: An error if there is an issue during translation. + /// - Returns: A declaration representing the translated oneOf structure. func translateOneOf( typeName: TypeName, openAPIDescription: String?, diff --git a/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateArray.swift b/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateArray.swift index 13597e8c..ae9e8af0 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateArray.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateArray.swift @@ -26,6 +26,8 @@ extension FileTranslator { /// document. /// - arrayContext: The context for the array, including information such /// as the element schema. + /// - Throws: An error if there is an issue during translation. + /// - Returns: A list of declarations representing the translated array. func translateArray( typeName: TypeName, openAPIDescription: String?, diff --git a/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateCodable.swift b/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateCodable.swift index 283bf38a..a1179e5f 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateCodable.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateCodable.swift @@ -129,6 +129,7 @@ extension FileTranslator { /// - properties: The properties to decode. /// - trailingCodeBlocks: Additional code blocks to add at the end of /// the body of the decoder initializer. + /// - Returns: A declaration representing the custom decoder implementation. func translateStructBlueprintCustomDecoder( properties: [PropertyBlueprint], trailingCodeBlocks: [CodeBlock] = [] @@ -177,6 +178,7 @@ extension FileTranslator { /// - properties: The properties to encode. /// - trailingCodeBlocks: Additional code blocks to add at the end of /// the body of the encoder initializer. + /// - Returns: A `Declaration` representing the custom decoder implementation. func translateStructBlueprintCustomEncoder( properties: [PropertyBlueprint], trailingCodeBlocks: [CodeBlock] = [] @@ -225,8 +227,8 @@ extension FileTranslator { // MARK: - AllOf encoder and decoder /// Returns a declaration of an allOf decoder implementation. - /// - Parameters: - /// - properties: The properties to decode. + /// - Parameter properties: The properties to decode. + /// - Returns: A `Declaration` representing the `allOf` decoder implementation. func translateStructBlueprintAllOfDecoder( properties: [(property: PropertyBlueprint, isKeyValuePair: Bool)] ) -> Declaration { @@ -242,8 +244,8 @@ extension FileTranslator { } /// Returns a declaration of an allOf encoder implementation. - /// - Parameters: - /// - properties: The properties to encode. + /// - Parameter properties: The properties to encode. + /// - Returns: A `Declaration` representing the `allOf` encoder implementation. func translateStructBlueprintAllOfEncoder( properties: [(property: PropertyBlueprint, isKeyValuePair: Bool)] ) -> Declaration { @@ -269,8 +271,8 @@ extension FileTranslator { // MARK: - AnyOf encoder and decoder /// Returns a declaration of an anyOf decoder implementation. - /// - Parameters: - /// - properties: The properties to decode. + /// - Parameter properties: The properties to be decoded using the `AnyOf` schema. + /// - Returns: A `Declaration` representing the `anyOf` decoder implementation. func translateStructBlueprintAnyOfDecoder( properties: [(property: PropertyBlueprint, isKeyValuePair: Bool)] ) -> Declaration { @@ -312,8 +314,8 @@ extension FileTranslator { } /// Returns a declaration of an anyOf encoder implementation. - /// - Parameters: - /// - properties: The properties to encode. + /// - Parameter properties: The properties to be encoded using the `AnyOf` schema. + /// - Returns: A `Declaration` representing the `AnyOf` encoder implementation. func translateStructBlueprintAnyOfEncoder( properties: [(property: PropertyBlueprint, isKeyValuePair: Bool)] ) -> Declaration { @@ -358,8 +360,8 @@ extension FileTranslator { // MARK: - OneOf encoder and decoder /// Returns a declaration of a oneOf without discriminator decoder implementation. - /// - Parameters: - /// - properties: The properties to decode. + /// - Parameter cases: The names of the cases to be decoded. + /// - Returns: A `Declaration` representing the `OneOf` decoder implementation. func translateOneOfWithoutDiscriminatorDecoder( cases: [(name: String, isKeyValuePair: Bool)] ) -> Declaration { @@ -417,8 +419,12 @@ extension FileTranslator { ]) ) } - /// Returns a declaration of a oneOf with a discriminator decoder implementation. + /// - Parameters: + /// - discriminatorName: The name of the discriminator property used for case selection. + /// - cases: The cases to decode, first element is the raw string to check for, the second + /// element is the case name (without the leading dot). + /// - Returns: A `Declaration` representing the `oneOf` decoder implementation. func translateOneOfWithDiscriminatorDecoder( discriminatorName: String, cases: [(caseName: String, rawNames: [String])] @@ -491,8 +497,8 @@ extension FileTranslator { } /// Returns a declaration of a oneOf encoder implementation. - /// - Parameters: - /// - properties: The properties to encode. + /// - Parameter cases: The case names to be encoded, including the special case for undocumented cases. + /// - Returns: A `Declaration` representing the `OneOf` encoder implementation. func translateOneOfEncoder( cases: [(name: String, isKeyValuePair: Bool)] ) -> Declaration { @@ -530,6 +536,7 @@ fileprivate extension Expression { /// expression. /// /// Assumes the existence of an "encoder" variable in the current scope. + /// - Returns: An expression representing the encoding of the current value using the "encoder" variable. func encodeExpr() -> Expression { .try( self @@ -549,6 +556,7 @@ fileprivate extension Expression { /// Assumes the existence of an "encoder" variable in the current scope. /// - Parameter gracefully: A Boolean value indicating whether the graceful /// variant of the expression is used. + /// - Returns: An Expression representing the result of encoding the current expression. func encodeToSingleValueContainerExpr(gracefully: Bool) -> Expression { .try( .identifier("encoder") @@ -567,6 +575,7 @@ fileprivate extension Expression { /// Assumes the existence of an "decoder" variable in the current scope, /// and assumes that the result is assigned to a variable with a defined /// type, as the type checking relies on type inference. + /// - Returns: An expression representing the initialization of an instance using the decoder. static func initFromDecoderExpr() -> Expression { .dot("init") .call([ @@ -583,6 +592,8 @@ fileprivate extension Expression { /// Assumes the existence of a "decoder" variable in the current scope, /// and assumes that the result is assigned to a variable with a defined /// type, as the type checking relies on type inference. + /// - Returns: An Expression representing the result of calling the decoder initializer + /// for non-key-value pair values. static func decodeFromSingleValueContainerExpr() -> Expression { .identifier("decoder").dot("decodeFromSingleValueContainer").call([]) } @@ -591,6 +602,7 @@ fileprivate extension Expression { fileprivate extension Declaration { /// Returns a declaration of a container variable for CodingKeys. + /// - Returns: A variable declaration representing a container for CodingKeys. static func decoderContainerOfKeysVar() -> Declaration { .variable( kind: .let, diff --git a/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateObjectStruct.swift b/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateObjectStruct.swift index 3b1af8aa..9b0771ab 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateObjectStruct.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateObjectStruct.swift @@ -20,9 +20,12 @@ extension FileTranslator { /// - Parameters: /// - typeName: The name of the type to give to the declared structure. /// - openAPIDescription: A user-specified description from the OpenAPI - /// document. + /// document. /// - objectContext: The context for the object, including information - /// such as the names and schemas of the object's properties. + /// such as the names and schemas of the object's properties. + /// - isDeprecated: A flag indicating whether the object is deprecated. + /// - Throws: An error if there is an issue during translation. + /// - Returns: A declaration representing the translated object schema. func translateObjectStruct( typeName: TypeName, openAPIDescription: String?, @@ -125,9 +128,12 @@ extension FileTranslator { /// Parses the appropriate information about additionalProperties for /// an object struct. - /// - Parameter objectContext: The context describing the object. + /// - Parameters: + /// - objectContext: The context describing the object. + /// - parent: The parent type name where this function is called from. /// - Returns: The kind of Codable implementation required for the struct, - /// and an extra property to be added to the struct, if needed. + /// and an extra property to be added to the struct, if needed. + /// - Throws: An error if there is an issue during parsing. func parseAdditionalProperties( in objectContext: JSONSchema.ObjectContext, parent: TypeName diff --git a/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateRawRepresentableEnum.swift b/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateRawRepresentableEnum.swift index 8607d814..a395a59c 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateRawRepresentableEnum.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateRawRepresentableEnum.swift @@ -27,6 +27,8 @@ extension FileTranslator { /// - unknownCaseDescription: The contents of the documentation comment /// for the unknown case. /// - customSwitchedExpression: A closure + /// - Throws: An error if there's an issue generating the declaration. + /// - Returns: The generated declaration. func translateRawRepresentableEnum( typeName: TypeName, conformances: [String], diff --git a/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateSchema.swift b/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateSchema.swift index bff22c7d..687c95a8 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateSchema.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateSchema.swift @@ -28,6 +28,8 @@ extension FileTranslator { /// - schema: The JSON schema representing the type. /// - overrides: A structure with the properties that should be overridden /// instead of extracted from the schema. + /// - Throws: An error if there is an issue during translation. + /// - Returns: A list of declarations representing the translated schema. func translateSchema( typeName: TypeName, schema: UnresolvedSchema?, @@ -66,6 +68,8 @@ extension FileTranslator { /// - schema: The JSON schema representing the type. /// - overrides: A structure with the properties that should be overridden /// instead of extracted from the schema. + /// - Throws: An error if there is an issue during translation. + /// - Returns: A list of declarations representing the translated schema. func translateSchema( typeName: TypeName, schema: JSONSchema, diff --git a/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateStringEnum.swift b/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateStringEnum.swift index e2fb60a8..144d5b72 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateStringEnum.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateStringEnum.swift @@ -33,6 +33,8 @@ extension FileTranslator { /// document. /// - isNullable: Whether the enum schema is nullable. /// - allowedValues: The enumerated allowed values. + /// - Throws: A `GenericError` if a disallowed value is encountered. + /// - Returns: A declaration of the specified raw value-based enum schema. func translateRawEnum( backingType: RawEnumBackingType, typeName: TypeName, diff --git a/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateStructBlueprint.swift b/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateStructBlueprint.swift index 69db33b5..e3285930 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateStructBlueprint.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateStructBlueprint.swift @@ -18,6 +18,7 @@ extension FileTranslator { /// Returns a declaration of the specified blueprint. /// - Parameter blueprint: Structure blueprint containing the information /// required to generate the Swift structure. + /// - Returns: A `Declaration` representing the generated Swift structure. func translateStructBlueprint( _ blueprint: StructBlueprint ) -> Declaration { @@ -72,6 +73,7 @@ extension FileTranslator { /// - Parameters: /// - typeName: The type name of the structure. /// - properties: The properties to include in the initializer. + /// - Returns: A `Declaration` representing the translated struct. func translateStructBlueprintInitializer( typeName: TypeName, properties: [PropertyBlueprint] @@ -126,6 +128,7 @@ extension FileTranslator { /// JSON schema, in which case a type declaration of that type is included /// in the returned array. /// - Parameter property: Information about the property. + /// - Returns: A list of Swift declarations representing the translated property. func translatePropertyBlueprint( _ property: PropertyBlueprint ) -> [Declaration] { @@ -146,7 +149,8 @@ extension FileTranslator { } /// Returns a declaration of a coding keys enum. - /// - Parameter blueprint: Information about the structure. + /// - Parameter properties: The properties of the structure. + /// - Returns: A coding keys enum declaration. func translateStructBlueprintCodingKeys( properties: [PropertyBlueprint] ) -> Declaration { @@ -173,6 +177,8 @@ fileprivate extension Array where Element == PropertyBlueprint { /// Returns the comment string for an initializer of a structure with /// the properties contained in the current array. + /// - Parameter typeName: The name of the structure type. + /// - Returns: A comment string describing the initializer. func initializerComment(typeName: String) -> String { var components: [String] = [ "Creates a new `\(typeName)`." diff --git a/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateTypealias.swift b/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateTypealias.swift index ab734ca0..67588433 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateTypealias.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/CommonTranslations/translateTypealias.swift @@ -18,9 +18,10 @@ extension FileTranslator { /// Returns a declaration of a typealias. /// - Parameters: /// - typeName: The name of the type to give to the declared typealias. - /// - openAPIDescription: A user-specified description from the OpenAPI - /// document. + /// - userDescription: A user-specified description from the OpenAPI document. /// - existingTypeUsage: The existing type the alias points to. + /// - Throws: An error if there is an issue during translation. + /// - Returns: A declaration representing the translated typealias. func translateTypealias( named typeName: TypeName, userDescription: String?, diff --git a/Sources/_OpenAPIGeneratorCore/Translator/CommonTypes/Annotations.swift b/Sources/_OpenAPIGeneratorCore/Translator/CommonTypes/Annotations.swift index 2d8cd194..8cba3a85 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/CommonTypes/Annotations.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/CommonTypes/Annotations.swift @@ -40,6 +40,7 @@ extension Expression { /// Returns an expression that suppresses unused variable warnings. /// - Parameter name: The name of the variable for which to suppress /// the warning. + /// - Returns: An expression that represents the call to suppress the unused variable warning. static func suppressUnusedWarning(for name: String) -> Self { .identifier("suppressUnusedWarning") .call([ diff --git a/Sources/_OpenAPIGeneratorCore/Translator/CommonTypes/CommentExtensions.swift b/Sources/_OpenAPIGeneratorCore/Translator/CommonTypes/CommentExtensions.swift index 509d69d9..fd2658e4 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/CommonTypes/CommentExtensions.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/CommonTypes/CommentExtensions.swift @@ -47,6 +47,7 @@ extension Comment { /// - Parameters: /// - prefix: The string that comes first. /// - suffix: The string that comes second. + /// - Returns: A documentation comment if either prefix or suffix is provided; otherwise, nil. static func doc(prefix: String?, suffix: String?) -> Self? { text(prefix: prefix, suffix: suffix).map { .doc($0) } } @@ -60,6 +61,7 @@ extension Comment { /// - Parameters: /// - prefix: The string that comes first. /// - suffix: The string that comes second. + /// - Returns: A string with the joined prefix and suffix separated by a newline, or nil if both are nil. private static func text(prefix: String?, suffix: String?) -> String? { if let prefix, let suffix { return "\(prefix)\n\n\(suffix)" @@ -90,6 +92,7 @@ extension TypeName { /// string to the specified user description. /// - Parameter userDescription: The description specified by the user /// in the OpenAPI document. + /// - Returns: A documentation comment combining the user description and the "generated from" string. func docCommentWithUserDescription(_ userDescription: String?) -> Comment? { .doc( prefix: userDescription, @@ -101,9 +104,12 @@ extension TypeName { /// string to the specified user description. /// /// The "generated from" string also includes a subpath. - /// - Parameter userDescription: The description specified by the user. - /// - Parameter subPath: A subpath appended to the JSON path of this + /// - Parameters: + /// - userDescription: The description specified by the user. + /// - subPath: A subpath appended to the JSON path of this /// type name. + /// - Returns: A documentation comment with the "generated from" string + /// appended to the user description or nil if not available. func docCommentWithUserDescription(_ userDescription: String?, subPath: String) -> Comment? { guard let jsonPath = appending(jsonComponent: subPath).fullyQualifiedJSONPath else { return Comment.doc(prefix: userDescription, suffix: nil) @@ -136,6 +142,7 @@ extension ResponseKind { /// - userDescription: The comment provided by the user in the OpenAPI /// document. /// - jsonPath: The JSON path of the commented type. + /// - Returns: A documentation comment with information about the source JSON path and HTTP response code. func docComment(userDescription: String?, jsonPath: String) -> Comment? { .doc( prefix: userDescription, @@ -150,8 +157,8 @@ extension ResponseKind { extension TypedParameter { /// Returns a documentation comment for the parameter. - /// - Parameters: - /// - parent: The parent type of the parameter. + /// - Parameter parent: The parent type of the parameter. + /// - Returns: A documentation comment for the parameter or nil if not available. func docComment(parent: TypeName) -> Comment? { parent.docCommentWithUserDescription( parameter.description, @@ -162,8 +169,8 @@ extension TypedParameter { extension ContentType { /// Returns a documentation comment for the content type. - /// - Parameters: - /// - typeName: The type name of the content. + /// - Parameter typeName: The type name of the content. + /// - Returns: A documentation comment for the content type or nil if not available. func docComment(typeName: TypeName) -> Comment? { typeName.docCommentWithUserDescription( nil, @@ -175,6 +182,7 @@ extension ContentType { extension Comment { /// Returns a reference documentation string to attach to the generated function for an operation. + /// - Parameter operationDescription: The details of the operation from the OpenAPI document. init(from operationDescription: OperationDescription) { self.init( summary: operationDescription.operation.summary, @@ -190,8 +198,8 @@ extension Comment { /// - Parameters: /// - summary: A short summary of what the operation does. /// - description: A verbose explanation of the operation behavior. - /// - path: The path associated with this operation. /// - httpMethod: The HTTP method associated with this operation. + /// - path: The path associated with this operation. /// - openAPIDocumentPath: JSONPath to the operation element in the OpenAPI document. init( summary: String?, @@ -230,6 +238,7 @@ extension Comment { /// OpenAPI document. /// - parent: The Swift type name of the structure of which this is /// a property of. + /// - Returns: A documentation comment for the property. static func property( originalName: String, userDescription: String?, @@ -251,6 +260,7 @@ extension Comment { /// OpenAPI document. /// - parent: The Swift type name of the structure of which this is /// a child of. + /// - Returns: A documentation comment for the property. static func child( originalName: String, userDescription: String?, @@ -271,6 +281,7 @@ extension ComponentDictionaryLocatable { /// Returns a documentation comment for the Components section. /// /// Examples of sections: "Schemas", "Parameters", and so on. + /// - Returns: A documentation comment for the property. static func sectionComment() -> Comment { .doc( """ diff --git a/Sources/_OpenAPIGeneratorCore/Translator/CommonTypes/DiscriminatorExtensions.swift b/Sources/_OpenAPIGeneratorCore/Translator/CommonTypes/DiscriminatorExtensions.swift index 93fc3618..3b990c37 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/CommonTypes/DiscriminatorExtensions.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/CommonTypes/DiscriminatorExtensions.swift @@ -80,6 +80,8 @@ extension FileTranslator { /// /// Derived from the mapping key, or the type name, as the last path /// component. + /// - Parameter type: The `OneOfMappedType` for which to determine the case name. + /// - Returns: A string representing the safe Swift name for the specified `OneOfMappedType`. func safeSwiftNameForOneOfMappedType(_ type: OneOfMappedType) -> String { swiftSafeName(for: type.rawNames[0]) } @@ -108,6 +110,7 @@ extension OpenAPI.Discriminator { /// - Parameters: /// - schemas: The subschemas of the oneOf with this discriminator. /// - typeAssigner: The current type assigner. + /// - Throws: An error if there's an issue while discovering the types. /// - Returns: The list of discovered types. func allTypes( schemas: [JSONReference], @@ -131,6 +134,7 @@ extension OpenAPI.Discriminator { /// Returns the mapped types provided by the discriminator's mapping. /// - Parameter typeAssigner: The current type assigner, used to assign /// a Swift type to the found JSON reference. + /// - Throws: An error if there's an issue while extracting mapped types from the mapping. /// - Returns: An array of found mapped types, but might also be empty. private func pairsFromMapping(typeAssigner: TypeAssigner) throws -> [OneOfMappedType] { guard let mapping else { diff --git a/Sources/_OpenAPIGeneratorCore/Translator/Content/ContentInspector.swift b/Sources/_OpenAPIGeneratorCore/Translator/Content/ContentInspector.swift index c7388733..105890b8 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/Content/ContentInspector.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/Content/ContentInspector.swift @@ -30,6 +30,8 @@ extension FileTranslator { /// - parent: The parent type of the chosen typed schema. /// - Returns: the detected content type + schema + type name, nil if no /// supported schema found or if empty. + /// - Throws: An error if there's a problem while selecting the best content, validating + /// the schema, or assigning the associated type. func bestSingleTypedContent( _ map: OpenAPI.Content.Map, excludeBinary: Bool = false, @@ -69,6 +71,8 @@ extension FileTranslator { /// type should be skipped, for example used when encoding headers. /// - parent: The parent type of the chosen typed schema. /// - Returns: The supported content type + schema + type names. + /// - Throws: An error if there's a problem while extracting or validating the supported + /// content types or assigning the associated types. func supportedTypedContents( _ map: OpenAPI.Content.Map, excludeBinary: Bool = false, diff --git a/Sources/_OpenAPIGeneratorCore/Translator/Content/ContentSwiftName.swift b/Sources/_OpenAPIGeneratorCore/Translator/Content/ContentSwiftName.swift index b35ce886..318a175d 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/Content/ContentSwiftName.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/Content/ContentSwiftName.swift @@ -19,6 +19,7 @@ extension FileTranslator { /// enum case. /// /// - Parameter contentType: The content type for which to compute the name. + /// - Returns: A Swift-safe identifier representing the name of the content enum case. func contentSwiftName(_ contentType: ContentType) -> String { let rawContentType = contentType.lowercasedTypeSubtypeAndParameters switch rawContentType { diff --git a/Sources/_OpenAPIGeneratorCore/Translator/FileTranslator.swift b/Sources/_OpenAPIGeneratorCore/Translator/FileTranslator.swift index 90122176..25a6de72 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/FileTranslator.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/FileTranslator.swift @@ -40,6 +40,7 @@ protocol FileTranslator { /// requested by the generator mode. /// - Parameter parsedOpenAPI: The OpenAPI document. /// - Returns: Structured representation of the generated Swift file. + /// - Throws: An error if translation encounters issues or errors during the process. func translateFile( parsedOpenAPI: ParsedOpenAPIRepresentation ) throws -> StructuredSwiftRepresentation diff --git a/Sources/_OpenAPIGeneratorCore/Translator/Operations/OperationDescription.swift b/Sources/_OpenAPIGeneratorCore/Translator/Operations/OperationDescription.swift index a92d1dc3..2f5832f6 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/Operations/OperationDescription.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/Operations/OperationDescription.swift @@ -59,6 +59,8 @@ extension OperationDescription { /// - components: The components from the OpenAPI document. /// - asSwiftSafeName: A converted function from user-provided strings /// to strings safe to be used as a Swift identifier. + /// - Returns: An array of `OperationDescription` instances, each representing + /// an operation discovered in the provided paths. /// - Throws: if `map` contains any references; see discussion for details. /// /// This function will throw an error if `map` contains any references, because: diff --git a/Sources/_OpenAPIGeneratorCore/Translator/Parameters/TypedParameter.swift b/Sources/_OpenAPIGeneratorCore/Translator/Parameters/TypedParameter.swift index 6bacb743..0b9b07bc 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/Parameters/TypedParameter.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/Parameters/TypedParameter.swift @@ -101,6 +101,8 @@ extension FileTranslator { /// Omits unsupported parameters, which emit a diagnostic to the collector /// with more information. /// - Parameter operation: The operation to extract parameters from. + /// - Returns: A list of `TypedParameter` instances representing the supported parameters of the operation. + /// - Throws: An error if there is an issue parsing and typing the parameters. func typedParameters( from operation: OperationDescription ) throws -> [TypedParameter] { @@ -121,6 +123,7 @@ extension FileTranslator { /// - unresolvedParameter: An unresolved parameter. /// - parent: The parent type of the parameter. /// - Returns: A typed parameter. Nil if the parameter is unsupported. + /// - Throws: An error if there is an issue parsing and typing the parameter. func parseAsTypedParameter( from unresolvedParameter: UnresolvedParameter, inParent parent: TypeName diff --git a/Sources/_OpenAPIGeneratorCore/Translator/Parameters/translateParameter.swift b/Sources/_OpenAPIGeneratorCore/Translator/Parameters/translateParameter.swift index 30185408..59392508 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/Parameters/translateParameter.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/Parameters/translateParameter.swift @@ -21,6 +21,7 @@ extension TypesFileTranslator { /// - unresolvedParameter: An unresolved parameter. /// - parent: The parent type name. /// - Returns: A property blueprint; nil when the parameter is unsupported. + /// - Throws: An error if there is an issue parsing the parameter as a typed parameter or translating the schema. func parseParameterAsProperty( for unresolvedParameter: UnresolvedParameter, inParent parent: TypeName @@ -59,6 +60,7 @@ extension TypesFileTranslator { /// - componentKey: The component key for the parameter. /// - parameter: The typed parameter. /// - Returns: A list of declarations; empty list if the parameter is unsupported. + /// - Throws: An error if there is an issue translating the parameter into types. func translateParameterInTypes( componentKey: OpenAPI.ComponentKey, parameter: TypedParameter @@ -75,6 +77,7 @@ extension TypesFileTranslator { /// - typeName: The type name to declare the parameter type under. /// - parameter: The parameter to declare. /// - Returns: A list of declarations; empty list if the parameter is unsupported. + /// - Throws: An error if there is an issue translating the parameter into types. func translateParameterInTypes( typeName: TypeName, parameter: TypedParameter @@ -97,6 +100,8 @@ extension ClientFileTranslator { /// the specified operation, and an expression of an array literal /// with all those parameters. /// - Parameter description: The OpenAPI operation. + /// - Returns: A tuple containing a templated string with path parameters and an expression representing an array of those parameters. + /// - Throws: An error if there is an issue translating path parameters for the client. func translatePathParameterInClient( description: OperationDescription ) throws -> (String, Expression) { @@ -110,6 +115,7 @@ extension ClientFileTranslator { /// - requestVariableName: The name of the request variable. /// - inputVariableName: The name of the Input variable. /// - Returns: The expression; nil if the parameter is unsupported. + /// - Throws: An error if there is an issue translating path parameters for the client. func translateNonPathParameterInClient( _ parameter: TypedParameter, requestVariableName: String, @@ -171,6 +177,8 @@ extension ServerFileTranslator { /// Returns an expression that populates a function argument call with the /// result of extracting the parameter value from a request into an Input. /// - Parameter typedParameter: The parameter to extract from a request. + /// - Returns: The expression representing the extraction of the parameter value; nil if the parameter is unsupported. + /// - Throws: An error if there is an issue translating the parameter extraction for the client. func translateParameterInServer( _ typedParameter: TypedParameter ) throws -> FunctionArgumentDescription? { diff --git a/Sources/_OpenAPIGeneratorCore/Translator/RequestBody/TypedRequestBody.swift b/Sources/_OpenAPIGeneratorCore/Translator/RequestBody/TypedRequestBody.swift index 2f311765..36f5ed27 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/RequestBody/TypedRequestBody.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/RequestBody/TypedRequestBody.swift @@ -32,10 +32,10 @@ struct TypedRequestBody { extension FileTranslator { /// Returns typed request body for the specified operation's request body. - /// - Parameters: - /// - operation: The parent operation of the request body. + /// - Parameter operation: The parent operation of the request body. /// - Returns: Typed request content; nil if the request body is nil or /// unsupported. + /// - Throws: An error if there is an issue translating the parameter extraction for the client. func typedRequestBody( in operation: OperationDescription ) throws -> TypedRequestBody? { @@ -54,6 +54,7 @@ extension FileTranslator { /// - parent: The parent type of the request body. /// - Returns: Typed request content; nil if the request body is /// unsupported. + /// - Throws: An error if there is an issue translating the typed request body. func typedRequestBody( from unresolvedRequest: UnresolvedRequest, inParent parent: TypeName @@ -80,6 +81,7 @@ extension FileTranslator { /// - unresolvedRequest: An unresolved request body. /// - Returns: Typed request content; nil if the request body is /// unsupported. + /// - Throws: An error if there is an issue translating the typed request body. func typedRequestBody( typeName: TypeName, from unresolvedRequest: UnresolvedRequest diff --git a/Sources/_OpenAPIGeneratorCore/Translator/RequestBody/translateRequestBody.swift b/Sources/_OpenAPIGeneratorCore/Translator/RequestBody/translateRequestBody.swift index 7e2a8a93..edc1a9e8 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/RequestBody/translateRequestBody.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/RequestBody/translateRequestBody.swift @@ -17,10 +17,10 @@ extension TypesFileTranslator { /// Returns a list of declarations that define a Swift type for /// the request body content. - /// - Parameters: - /// - content: The typed schema content to declare. + /// - Parameter content: The typed schema content to declare. /// - Returns: A list of declarations; empty list if the content is /// unsupported. + /// - Throws: An error if there is an issue translating and declaring the schema content. func translateRequestBodyContentInTypes( _ content: TypedSchemaContent ) throws -> [Declaration] { @@ -40,6 +40,7 @@ extension TypesFileTranslator { /// - Parameter requestBody: The request body to declare. /// - Returns: A list of declarations; empty if the request body is /// unsupported. + /// - Throws: An error if there is an issue translating and declaring the request body content cases. func requestBodyContentCases( for requestBody: TypedRequestBody ) throws -> [Declaration] { @@ -76,6 +77,7 @@ extension TypesFileTranslator { /// - Parameters: /// - unresolvedRequestBody: An unresolved request body. /// - parent: The type name of the parent structure. + /// - Throws: An error if there's an issue while parsing the request body or generating the property blueprint. /// - Returns: The property blueprint; nil if no body is specified. func parseRequestBodyAsProperty( for unresolvedRequestBody: UnresolvedRequest?, @@ -117,10 +119,10 @@ extension TypesFileTranslator { } /// Returns a declaration that defines a Swift type for the request body. - /// - Parameters: - /// - requestBody: The request body to declare. + /// - Parameter requestBody: The request body to declare. /// - Returns: A list of declarations; empty list if the request body is /// unsupported. + /// - Throws: An error if there is an issue translating the request body. func translateRequestBodyInTypes( requestBody: TypedRequestBody ) throws -> Declaration { @@ -166,6 +168,7 @@ extension ClientFileTranslator { /// - bodyVariableName: The name of the body variable. /// - inputVariableName: The name of the Input variable. /// - Returns: An assignment expression. + /// - Throws: An error if there is an issue translating the request body. func translateRequestBodyInClient( _ requestBody: TypedRequestBody, requestVariableName: String, @@ -240,6 +243,7 @@ extension ServerFileTranslator { /// - bodyVariableName: The name of the body variable. /// - inputTypeName: The type of the Input. /// - Returns: A variable declaration. + /// - Throws: An error if there is an issue extracting or validating the request body. func translateRequestBodyInServer( _ requestBody: TypedRequestBody, requestVariableName: String, diff --git a/Sources/_OpenAPIGeneratorCore/Translator/Responses/HTTPStatusCodes.swift b/Sources/_OpenAPIGeneratorCore/Translator/Responses/HTTPStatusCodes.swift index 0cfb2dcc..d8f99fb3 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/Responses/HTTPStatusCodes.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/Responses/HTTPStatusCodes.swift @@ -17,6 +17,7 @@ struct HTTPStatusCodes { /// Returns a code-safe name for the specified HTTP status code. /// - Parameter code: The HTTP status code. + /// - Returns: A code-safe name for the specified HTTP status code. static func safeName(for code: Int) -> String { switch code { case 100: diff --git a/Sources/_OpenAPIGeneratorCore/Translator/Responses/TypedResponse.swift b/Sources/_OpenAPIGeneratorCore/Translator/Responses/TypedResponse.swift index 78e430fb..37152f3e 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/Responses/TypedResponse.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/Responses/TypedResponse.swift @@ -30,9 +30,11 @@ extension FileTranslator { /// Returns a typed response for the specified unresolved response. /// - Parameters: - /// - unresolvedResponse: An unresolved response. + /// - outcome: An unresolved response outcome. /// - operation: The operation in which the response resides. /// - Returns: A typed response. + /// - Throws: An error if there's an issue resolving the type name, fetching the response, + /// or determining the inlined status. func typedResponse( from outcome: OpenAPI.Operation.ResponseOutcome, operation: OperationDescription diff --git a/Sources/_OpenAPIGeneratorCore/Translator/Responses/TypedResponseHeader.swift b/Sources/_OpenAPIGeneratorCore/Translator/Responses/TypedResponseHeader.swift index d4c50bdf..6567d285 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/Responses/TypedResponseHeader.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/Responses/TypedResponseHeader.swift @@ -68,6 +68,8 @@ extension FileTranslator { /// - Returns: A list of response headers; can be empty if no response /// headers are specified in the OpenAPI document, or if all headers are /// unsupported. + /// - Throws: An error if there's an issue processing or generating typed response + /// headers, such as unsupported header types or invalid definitions. func typedResponseHeaders( from response: OpenAPI.Response, inParent parent: TypeName @@ -90,6 +92,9 @@ extension FileTranslator { /// - name: The name of the header. /// - parent: The Swift type name of the parent type of the headers. /// - Returns: Typed response header if supported, nil otherwise. + /// - Throws: An error if there's an issue processing or generating the typed response + /// header, such as unsupported header types, invalid definitions, or schema + /// validation failures. func typedResponseHeader( from unresolvedResponseHeader: UnresolvedResponseHeader, named name: String, diff --git a/Sources/_OpenAPIGeneratorCore/Translator/Responses/acceptHeaderContentTypes.swift b/Sources/_OpenAPIGeneratorCore/Translator/Responses/acceptHeaderContentTypes.swift index 0afac8a6..5a45adb4 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/Responses/acceptHeaderContentTypes.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/Responses/acceptHeaderContentTypes.swift @@ -22,6 +22,7 @@ extension FileTranslator { /// - Parameter description: The OpenAPI operation. /// - Returns: A list of content types. Might be empty, in which case no /// Accept header should be sent in the request. + /// - Throws: Any errors that occur during the process of analyzing the responses. func acceptHeaderContentTypes( for description: OperationDescription ) throws -> [ContentType] { diff --git a/Sources/_OpenAPIGeneratorCore/Translator/Responses/translateResponse.swift b/Sources/_OpenAPIGeneratorCore/Translator/Responses/translateResponse.swift index 06ce122d..78040cdc 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/Responses/translateResponse.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/Responses/translateResponse.swift @@ -17,8 +17,11 @@ extension TypesFileTranslator { /// Returns a declaration that defines a Swift type for the response. /// - Parameters: - /// - typedResponse: The typed response to declare. - /// - Returns: A structure declaration. + /// - typeName: The type name for the response structure. + /// - response: The typed response information containing the response headers and body content. + /// - Returns: A structure declaration representing the response type. + /// - Throws: An error if there's an issue while generating the response type declaration, + /// extracting response headers, or processing the body content. func translateResponseInTypes( typeName: TypeName, response: TypedResponse @@ -210,6 +213,8 @@ extension TypesFileTranslator { /// in the OpenAPI document. /// - response: The response to declare. /// - Returns: A structure declaration. + /// - Throws: An error if there's an issue while generating the response header type declaration, + /// or if there's a problem with extracting response headers or processing the body content. func translateResponseHeaderInTypes( componentKey: OpenAPI.ComponentKey, response: TypedResponse diff --git a/Sources/_OpenAPIGeneratorCore/Translator/Responses/translateResponseHeader.swift b/Sources/_OpenAPIGeneratorCore/Translator/Responses/translateResponseHeader.swift index 329f6f89..200a135a 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/Responses/translateResponseHeader.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/Responses/translateResponseHeader.swift @@ -22,6 +22,7 @@ extension TypesFileTranslator { /// - header: A response parameter. /// - parent: The type name of the parent struct. /// - Returns: A property blueprint. + /// - Throws: An error if there's an issue while parsing the response header. func parseResponseHeaderAsProperty( for header: TypedResponseHeader, parent: TypeName @@ -50,6 +51,7 @@ extension TypesFileTranslator { /// returned, the last one is the header type declaration, while any /// previous ones represent unnamed types in the OpenAPI document that /// need to be defined inline. + /// - Throws: An error if there's an issue while translating the response header or its inline types. func translateResponseHeaderInTypes( componentKey: OpenAPI.ComponentKey, header: TypedResponseHeader @@ -70,6 +72,7 @@ extension TypesFileTranslator { /// returned, the last one is the header type declaration, while any /// previous ones represent unnamed types in the OpenAPI document that /// need to be defined inline. + /// - Throws: An error if there's an issue while translating the response header or its inline types. func translateResponseHeaderInTypes( typeName: TypeName, header: TypedResponseHeader @@ -94,6 +97,7 @@ extension ClientFileTranslator { /// - header: The response header to extract. /// - responseVariableName: The name of the response variable. /// - Returns: A function argument expression. + /// - Throws: An error if there's an issue while generating the extraction expression. func translateResponseHeaderInClient( _ header: TypedResponseHeader, responseVariableName: String @@ -134,6 +138,7 @@ extension ServerFileTranslator { /// - header: The header to extract. /// - responseVariableName: The name of the response variable. /// - Returns: A function argument expression. + /// - Throws: An error if there's an issue while generating the expression for setting the header field. func translateResponseHeaderInServer( _ header: TypedResponseHeader, responseVariableName: String diff --git a/Sources/_OpenAPIGeneratorCore/Translator/Responses/translateResponseOutcome.swift b/Sources/_OpenAPIGeneratorCore/Translator/Responses/translateResponseOutcome.swift index a4b6a230..12c24572 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/Responses/translateResponseOutcome.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/Responses/translateResponseOutcome.swift @@ -26,6 +26,8 @@ extension TypesFileTranslator { /// - Returns: A declaration of the enum case and a declaration of the /// structure unique to the response that contains the response headers /// and a body payload. + /// - Throws: An error if there's an issue generating the declarations, such + /// as unsupported response types or invalid definitions. func translateResponseOutcomeInTypes( _ outcome: OpenAPI.Operation.ResponseOutcome, operation: OperationDescription, @@ -133,6 +135,9 @@ extension ClientFileTranslator { /// - outcome: The OpenAPI response. /// - operation: The OpenAPI operation. /// - Returns: A switch case expression. + /// - Throws: An error if there's an issue generating the switch case + /// expression, such as encountering unsupported response types or + /// invalid definitions. func translateResponseOutcomeInClient( outcome: OpenAPI.Operation.ResponseOutcome, operation: OperationDescription @@ -401,6 +406,9 @@ extension ServerFileTranslator { /// - outcome: The OpenAPI response. /// - operation: The OpenAPI operation. /// - Returns: A switch case expression. + /// - Throws: An error if there's an issue generating the switch case + /// expression, such as encountering unsupported response types + /// or invalid definitions. func translateResponseOutcomeInServer( outcome: OpenAPI.Operation.ResponseOutcome, operation: OperationDescription diff --git a/Sources/_OpenAPIGeneratorCore/Translator/ServerTranslator/ServerTranslator.swift b/Sources/_OpenAPIGeneratorCore/Translator/ServerTranslator/ServerTranslator.swift index 9cd39e05..11cad910 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/ServerTranslator/ServerTranslator.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/ServerTranslator/ServerTranslator.swift @@ -87,6 +87,9 @@ struct ServerFileTranslator: FileTranslator { /// Returns a declaration of the registerHandlers method and /// the declarations of the individual operation methods. /// - Parameter operations: The operations found in the OpenAPI document. + /// - Returns: A tuple containing the declaration of the `registerHandlers` method and + /// an array of operation method declarations. + /// - Throws: An error if there is an issue while generating the registration code. func translateRegisterHandlers( _ operations: [OperationDescription] ) throws -> (Declaration, [Declaration]) { diff --git a/Sources/_OpenAPIGeneratorCore/Translator/ServerTranslator/translateServerMethod.swift b/Sources/_OpenAPIGeneratorCore/Translator/ServerTranslator/translateServerMethod.swift index b1672529..c1f57bf4 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/ServerTranslator/translateServerMethod.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/ServerTranslator/translateServerMethod.swift @@ -17,7 +17,9 @@ extension ServerFileTranslator { /// Returns an expression that converts a request into an Input type for /// a specified OpenAPI operation. - /// - Parameter description: The OpenAPI operation. + /// - Parameter operation: The OpenAPI operation. + /// - Returns: An expression representing the process of converting a request into an Input type. + /// - Throws: An error if there's an issue while generating the expression for request conversion. func translateServerDeserializer( _ operation: OperationDescription ) throws -> Expression { @@ -147,6 +149,9 @@ extension ServerFileTranslator { /// Returns an expression that converts an Output type into a response /// for a specified OpenAPI operation. /// - Parameter description: The OpenAPI operation. + /// - Returns: An expression for converting the Output type into a structured response. + /// - Throws: An error if there's an issue generating the response conversion expression, + /// such as encountering unsupported response types or invalid definitions. func translateServerSerializer(_ description: OperationDescription) throws -> Expression { var cases: [SwitchCaseDescription] = try description @@ -201,6 +206,8 @@ extension ServerFileTranslator { /// - serverUrlVariableName: The name of the server URL variable. /// - Returns: A declaration of a function, and an expression that registers /// the function with the router. + /// - Throws: An error if there's an issue while generating the method declaration or + /// the router registration expression. func translateServerMethod( _ description: OperationDescription, serverUrlVariableName: String diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TranslatorProtocol.swift b/Sources/_OpenAPIGeneratorCore/Translator/TranslatorProtocol.swift index 09377c8b..2c69e507 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/TranslatorProtocol.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/TranslatorProtocol.swift @@ -25,6 +25,7 @@ protocol TranslatorProtocol { /// - diagnostics: The collector to which the translator emits /// diagnostics. /// - Returns: A structured Swift representation of the generated code. + /// - Throws: An error if there are issues parsing or translating the request body. func translate( parsedOpenAPI: ParsedOpenAPIRepresentation, config: Config, diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TypeAssignment/Builtins.swift b/Sources/_OpenAPIGeneratorCore/Translator/TypeAssignment/Builtins.swift index b114c80d..48056157 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/TypeAssignment/Builtins.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/TypeAssignment/Builtins.swift @@ -27,6 +27,7 @@ extension TypeName { /// Returns a type name for a type with the specified name in the /// Swift module. /// - Parameter name: The name of the type. + /// - Returns: A TypeName representing the specified type within the Swift module. static func swift(_ name: String) -> TypeName { TypeName(swiftKeyPath: ["Swift", name]) } @@ -34,6 +35,7 @@ extension TypeName { /// Returns a type name for a type with the specified name in the /// Foundation module. /// - Parameter name: The name of the type. + /// - Returns: A TypeName representing the specified type within the Foundation module. static func foundation(_ name: String) -> TypeName { TypeName(swiftKeyPath: ["Foundation", name]) } @@ -41,6 +43,7 @@ extension TypeName { /// Returns a type name for a type with the specified name in the /// OpenAPIRuntime module. /// - Parameter name: The name of the type. + /// - Returns: A TypeName representing the specified type within the OpenAPIRuntime module. static func runtime(_ name: String) -> TypeName { TypeName(swiftKeyPath: ["OpenAPIRuntime", name]) } @@ -48,6 +51,7 @@ extension TypeName { /// Returns a type name for a type with the specified name in the /// HTTPTypes module. /// - Parameter name: The name of the type. + /// - Returns: A TypeName representing the type with the given name in the HTTPTypes module. static func httpTypes(_ name: String) -> TypeName { TypeName(swiftKeyPath: ["HTTPTypes", name]) } diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TypeAssignment/TypeAssigner.swift b/Sources/_OpenAPIGeneratorCore/Translator/TypeAssignment/TypeAssigner.swift index 825d4d86..5acb9f3a 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/TypeAssignment/TypeAssigner.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/TypeAssignment/TypeAssigner.swift @@ -60,6 +60,7 @@ struct TypeAssigner { /// - originalName: The original type name (component key) from /// the OpenAPI document. /// - location: The location of the type in the OpenAPI document. + /// - Returns: A Swift type name for the specified component type. func typeName( forComponentOriginallyNamed originalName: String, in location: TypeLocation @@ -73,6 +74,7 @@ struct TypeAssigner { /// Returns the type name for an OpenAPI-named component namespace. /// - Parameter location: The location of the type in the OpenAPI document. + /// - Returns: A Swift type name representing the specified component namespace. func typeName(forLocation location: TypeLocation) -> TypeName { switch location { case .schemas: @@ -89,6 +91,7 @@ struct TypeAssigner { /// - components: The components in which to look up references. /// - parent: The parent type in which to name the type. /// - Returns: A type usage; or nil if the schema is nil or unsupported. + /// - Throws: An error if there's an issue while computing the type usage, such as when resolving a type name or checking compatibility. func typeUsage( usingNamingHint hint: String, withSchema schema: UnresolvedSchema?, @@ -122,6 +125,7 @@ struct TypeAssigner { /// - components: The components in which to look up references. /// - parent: The parent type in which to name the type. /// - Returns: A type usage. + /// - Throws: An error if there's an issue while processing the schema or generating the type usage. func typeUsage( forObjectPropertyNamed originalName: String, withSchema schema: JSONSchema, @@ -144,6 +148,7 @@ struct TypeAssigner { /// - components: The components in which to look up references. /// - parent: The parent type in which to name the type. /// - Returns: A type usage. + /// - Throws: An error if there's an issue while processing the schema or generating the type usage. func typeUsage( forAllOrAnyOrOneOfChildSchemaNamed originalName: String, withSchema schema: JSONSchema, @@ -166,6 +171,7 @@ struct TypeAssigner { /// - components: The components in which to look up references. /// - parent: The parent type in which to name the type. /// - Returns: A type usage. + /// - Throws: An error if there's an issue while processing the schema or generating the type usage. func typeUsage( forArrayElementWithSchema schema: JSONSchema, components: OpenAPI.Components, @@ -187,6 +193,7 @@ struct TypeAssigner { /// - components: The components in which to look up references. /// - parent: The parent type in which to name the type. /// - Returns: A type usage. + /// - Throws: An error if there's an issue while processing the schema or generating the type usage. func typeUsage( forParameterNamed originalName: String, withSchema schema: JSONSchema, @@ -260,9 +267,11 @@ struct TypeAssigner { /// reference component. /// - suffix: The string to append to the name for inline types. /// - schema: The schema describing the content of the type. + /// - components: The components from the OpenAPI document. /// - parent: The name of the parent type in which to name the type. /// - subtype: The naming method used by the type assigner. /// - Returns: A type usage. + /// - Throws: An error if there's an issue while processing the schema or generating the type usage. private func _typeUsage( forPotentiallyInlinedValueNamed originalName: String, jsonReferenceComponentOverride: String? = nil, @@ -323,6 +332,7 @@ struct TypeAssigner { /// /// - NOTE: Only internal references are currently supported; throws an error for external references. /// - Parameter component: The component for which to compute a name. + /// - Returns: A type name for a reusable component. func typeName( for component: OpenAPI.ComponentDictionary.Element ) -> TypeName { @@ -353,6 +363,7 @@ struct TypeAssigner { /// - Parameters: /// - key: The key for the component in the OpenAPI document. /// - componentType: The type of the component. + /// - Returns: A type name for a reusable component key. func typeName( for key: OpenAPI.ComponentKey, of componentType: Component.Type @@ -381,6 +392,8 @@ struct TypeAssigner { /// - reference: The reference to compute a type name for. /// - componentType: The type of the component to which the reference /// points. + /// - Returns: A type name for a JSON reference. + /// - Throws: An error if the provided reference is an external reference or if there's an issue while computing the type name. func typeName( for reference: JSONReference, in componentType: Component.Type = Component.self @@ -400,6 +413,8 @@ struct TypeAssigner { /// - reference: The reference to compute a type name for. /// - componentType: The type of the component to which the reference /// points. + /// - Throws: An error if there's an issue while computing the type name, or if the reference is external. + /// - Returns: A TypeName representing the computed type name for the reference. func typeName( for reference: OpenAPI.Reference, in componentType: Component.Type = Component.self @@ -417,6 +432,8 @@ struct TypeAssigner { /// - reference: The internal reference to compute a type name for. /// - componentType: The type of the component to which the reference /// points. + /// - Returns: A type name for an internal reference to a component. + /// - Throws: An error if the provided reference is not a component reference or if there's an issue while computing the type name. func typeName( for reference: JSONReference.InternalReference, in componentType: Component.Type = Component.self @@ -448,6 +465,7 @@ struct TypeAssigner { /// - `#/components/links` -> `OpenAPI.Link` /// /// - Parameter componentType: The type of the component. + /// - Returns: A type name for the namespace for the specified component type. func typeName( for componentType: Component.Type = Component.self ) -> TypeName { @@ -463,6 +481,7 @@ struct TypeAssigner { } /// Returns the root namespace for all OpenAPI components. + /// - Returns: The root namespace for all OpenAPI components. func typeNameForComponents() -> TypeName { TypeName(components: [ .root, diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TypeAssignment/TypeMatcher.swift b/Sources/_OpenAPIGeneratorCore/Translator/TypeAssignment/TypeMatcher.swift index 5259b6b4..71741fc3 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/TypeAssignment/TypeMatcher.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/TypeAssignment/TypeMatcher.swift @@ -71,6 +71,7 @@ struct TypeMatcher { /// - components: The components in which to look up references. /// - Returns: A type usage for the schema if the schema is supported. /// Otherwise, returns nil. + /// - Throws: An error if there is an issue during the matching process. func tryMatchReferenceableType( for schema: JSONSchema, components: OpenAPI.Components @@ -193,6 +194,7 @@ struct TypeMatcher { /// - Parameters: /// - schema: The schema to check. /// - components: The reusable components from the OpenAPI document. + /// - Throws: An error if there's an issue while checking the schema. /// - Returns: `true` if the schema is a key-value pair; `false` otherwise. static func isKeyValuePair( _ schema: JSONSchema, @@ -228,6 +230,7 @@ struct TypeMatcher { /// - Parameters: /// - schema: The schema to check. /// - components: The reusable components from the OpenAPI document. + /// - Throws: An error if there's an issue while checking the schema. /// - Returns: `true` if the schema is a key-value pair; `false` otherwise. static func isKeyValuePair( _ schema: UnresolvedSchema?, @@ -251,6 +254,7 @@ struct TypeMatcher { /// - Parameters: /// - schema: The schema to check. /// - components: The OpenAPI components for looking up references. + /// - Throws: An error if there's an issue while checking the schema. /// - Returns: `true` if the schema is optional, `false` otherwise. func isOptional( _ schema: JSONSchema, @@ -270,6 +274,7 @@ struct TypeMatcher { /// - Parameters: /// - schema: The schema to check. /// - components: The OpenAPI components for looking up references. + /// - Throws: An error if there's an issue while checking the schema. /// - Returns: `true` if the schema is optional, `false` otherwise. func isOptional( _ schema: UnresolvedSchema?, diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TypeAssignment/TypeName.swift b/Sources/_OpenAPIGeneratorCore/Translator/TypeAssignment/TypeName.swift index 2039becf..ff27492b 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/TypeAssignment/TypeName.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/TypeAssignment/TypeName.swift @@ -112,10 +112,10 @@ struct TypeName: Hashable { /// current type name. /// /// In other words, returns a type name for a child type. + /// - Precondition: At least one of the components must be non-nil. /// - Parameters: /// - swiftComponent: The name of the Swift type component. /// - jsonComponent: The name of the JSON path component. - /// - Precondition: At least one of the components must be non-nil. /// - Returns: A new type name. func appending(swiftComponent: String? = nil, jsonComponent: String? = nil) -> Self { precondition(swiftComponent != nil || jsonComponent != nil, "At least the Swift or JSON name must be non-nil.") diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TypeAssignment/TypeUsage.swift b/Sources/_OpenAPIGeneratorCore/Translator/TypeAssignment/TypeUsage.swift index e4553289..37dabaa6 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/TypeAssignment/TypeUsage.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/TypeAssignment/TypeUsage.swift @@ -127,6 +127,7 @@ extension TypeUsage { /// Returns a string representation of the type usage applied to the /// specified Swift path component. /// - Parameter component: A Swift path component. + /// - Returns: A string representation of the specified Swift path component with the applied type usage. private func applied(to component: String) -> String { switch usage { case .identity: @@ -177,6 +178,7 @@ extension TypeUsage { /// - Parameter isOptional: If `true`, wraps the current type usage in /// an optional. If `false`, removes a potential optional wrapper from the /// top level. + /// - Returns: A type usage with the adjusted optionality based on the `isOptional` parameter. func withOptional(_ isOptional: Bool) -> Self { if (isOptional && self.isOptional) || (!isOptional && !self.isOptional) { return self diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TypeAssignment/isSchemaSupported.swift b/Sources/_OpenAPIGeneratorCore/Translator/TypeAssignment/isSchemaSupported.swift index db3106da..7279cbf3 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/TypeAssignment/isSchemaSupported.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/TypeAssignment/isSchemaSupported.swift @@ -62,6 +62,7 @@ extension FileTranslator { /// - schema: The schema to validate. /// - foundIn: A description of the schema's context. /// - Returns: `true` if the schema is supported; `false` otherwise. + /// - Throws: An error if there's an issue during the validation process. func validateSchemaIsSupported( _ schema: JSONSchema, foundIn: String @@ -86,6 +87,7 @@ extension FileTranslator { /// - schema: The schema to validate. /// - foundIn: A description of the schema's context. /// - Returns: `true` if the schema is supported; `false` otherwise. + /// - Throws: An error if there's an issue during the validation process. func validateSchemaIsSupported( _ schema: UnresolvedSchema?, foundIn: String @@ -106,8 +108,9 @@ extension FileTranslator { /// Returns whether the schema is supported. /// /// If a schema is not supported, no references to it should be emitted. - /// - Parameters: - /// - schema: The schema to validate. + /// - Parameter schema: The schema to validate. + /// - Returns: An `IsSchemaSupportedResult` indicating whether the schema is supported or unsupported. + /// - Throws: An error if there's an issue during the validation process. func isSchemaSupported( _ schema: JSONSchema ) throws -> IsSchemaSupportedResult { @@ -174,8 +177,9 @@ extension FileTranslator { /// Returns a result indicating whether the schema is supported. /// /// If a schema is not supported, no references to it should be emitted. - /// - Parameters: - /// - schema: The schema to validate. + /// - Parameter schema: The schema to validate. + /// - Returns: An `IsSchemaSupportedResult` indicating whether the schema is supported or unsupported. + /// - Throws: An error if there's an issue during the validation process. func isSchemaSupported( _ schema: UnresolvedSchema? ) throws -> IsSchemaSupportedResult { @@ -195,6 +199,8 @@ extension FileTranslator { /// Returns a result indicating whether the provided schemas /// are supported. /// - Parameter schemas: Schemas to check. + /// - Returns: An `IsSchemaSupportedResult` indicating whether all schemas are supported or if there's an unsupported schema. + /// - Throws: An error if there's an issue during the validation process. func areSchemasSupported(_ schemas: [JSONSchema]) throws -> IsSchemaSupportedResult { for schema in schemas { let result = try isSchemaSupported(schema) @@ -208,6 +214,8 @@ extension FileTranslator { /// Returns a result indicating whether the provided schema /// is an reference, object, or allOf (object-ish) schema and is supported. /// - Parameter schema: A schemas to check. + /// - Returns: An `IsSchemaSupportedResult` indicating whether the schema is supported or not. + /// - Throws: An error if there's an issue during the validation process. func isObjectishSchemaAndSupported(_ schema: JSONSchema) throws -> IsSchemaSupportedResult { switch schema.value { case .object: @@ -227,6 +235,7 @@ extension FileTranslator { /// Returns a result indicating whether the provided schemas /// are object-ish schemas and supported. /// - Parameter schemas: Schemas to check. + /// - Throws: An error if there's an issue while checking the schemas. /// - Returns: `.supported` if all schemas match; `.unsupported` otherwise. func areObjectishSchemasAndSupported(_ schemas: [JSONSchema]) throws -> IsSchemaSupportedResult { for schema in schemas { @@ -242,6 +251,7 @@ extension FileTranslator { /// are reference schemas that point to object-ish schemas and supported. /// - Parameter schemas: Schemas to check. /// - Returns: `.supported` if all schemas match; `.unsupported` otherwise. + /// - Throws: An error if there's an issue during the validation process. func areRefsToObjectishSchemaAndSupported(_ schemas: [JSONSchema]) throws -> IsSchemaSupportedResult { for schema in schemas { let result = try isRefToObjectishSchemaAndSupported(schema) @@ -255,6 +265,8 @@ extension FileTranslator { /// Returns a result indicating whether the provided schema /// is a reference schema that points to an object-ish schema and is supported. /// - Parameter schema: A schema to check. + /// - Returns: An `IsSchemaSupportedResult` indicating whether the schema is supported or not. + /// - Throws: An error if there's an issue during the validation process. func isRefToObjectishSchemaAndSupported(_ schema: JSONSchema) throws -> IsSchemaSupportedResult { switch schema.value { case let .reference(ref, _): diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateComponentHeaders.swift b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateComponentHeaders.swift index 9f50c91f..cbcec1aa 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateComponentHeaders.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateComponentHeaders.swift @@ -19,6 +19,7 @@ extension TypesFileTranslator { /// in the OpenAPI document. /// - Parameter headers: The reusable response headers. /// - Returns: An enum declaration representing the headers namespace. + /// - Throws: An error if there's an issue during translation or header processing. func translateComponentHeaders( _ headers: OpenAPI.ComponentDictionary ) throws -> Declaration { diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateComponentParameters.swift b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateComponentParameters.swift index d8845a4f..f4e3d532 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateComponentParameters.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateComponentParameters.swift @@ -19,6 +19,7 @@ extension TypesFileTranslator { /// in the OpenAPI document. /// - Parameter parameters: The reusable request parameters. /// - Returns: An enum declaration representing the parameters namespace. + /// - Throws: An error if there's an issue during translation or parameter processing. func translateComponentParameters( _ parameters: OpenAPI.ComponentDictionary ) throws -> Declaration { diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateComponentRequestBodies.swift b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateComponentRequestBodies.swift index ac581608..3bf37759 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateComponentRequestBodies.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateComponentRequestBodies.swift @@ -17,8 +17,9 @@ extension TypesFileTranslator { /// Returns a declaration of the reusable request bodies defined /// in the OpenAPI document. - /// - Parameter requestBodies: The reusable request bodies. + /// - Parameter items: The reusable request bodies. /// - Returns: An enum declaration representing the requestBodies namespace. + /// - Throws: An error if there's an issue during translation or request body processing. func translateComponentRequestBodies( _ items: OpenAPI.ComponentDictionary ) throws -> Declaration { diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateComponentResponses.swift b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateComponentResponses.swift index c3d8e8b8..255002c7 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateComponentResponses.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateComponentResponses.swift @@ -19,6 +19,7 @@ extension TypesFileTranslator { /// in the OpenAPI document. /// - Parameter responses: The reusable responses. /// - Returns: An enum declaration representing the responses namespace. + /// - Throws: An error if there's an issue during translation or request body processing func translateComponentResponses( _ responses: OpenAPI.ComponentDictionary ) throws -> Declaration { diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateComponents.swift b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateComponents.swift index ed5dc1e9..1a63da3a 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateComponents.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateComponents.swift @@ -21,6 +21,7 @@ extension TypesFileTranslator { /// - Parameter components: The components defined in the OpenAPI document. /// - Returns: A code block with the enum representing the components /// namespace. + /// - Throws: An error if there's an issue during translation of components. func translateComponents( _ components: OpenAPI.Components ) throws -> CodeBlock { diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateOperations.swift b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateOperations.swift index 9817ea4d..e3786082 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateOperations.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateOperations.swift @@ -18,6 +18,7 @@ extension TypesFileTranslator { /// Returns a declaration of the Input type for the specified operation. /// - Parameter description: The OpenAPI operation. /// - Returns: A structure declaration that represents the Input type. + /// - Throws: An error if there's an issue during translation of the input type. func translateOperationInput( _ description: OperationDescription ) throws -> Declaration { @@ -138,6 +139,7 @@ extension TypesFileTranslator { /// Returns a declaration of the Output type for the specified operation. /// - Parameter description: The OpenAPI operation. /// - Returns: An enum declaration that represents the Output type. + /// - Throws: An error if there's an issue during translation of the output type. func translateOperationOutput( _ description: OperationDescription ) throws -> Declaration { @@ -200,6 +202,7 @@ extension TypesFileTranslator { /// - Returns: A structure declaration that represents /// the AcceptableContentType type, or nil if no acceptable content types /// were specified. + /// - Throws: An error if there's an issue generating the declaration. func translateOperationAcceptableContentType( _ description: OperationDescription ) throws -> Declaration? { @@ -234,6 +237,7 @@ extension TypesFileTranslator { /// - Parameter operation: The OpenAPI operation. /// - Returns: An enum declaration that represents the operation's /// namespace. + /// - Throws: An error if there's an issue during translation of the operation's namespace. func translateOperation( _ operation: OperationDescription ) throws -> Declaration { @@ -276,6 +280,7 @@ extension TypesFileTranslator { /// - Parameter operations: The operations defined in the OpenAPI document. /// - Returns: A code block that contains an enum declaration with a /// separate namespace type for each operation. + /// - Throws: An error if there is an issue during operation translation. func translateOperations( _ operations: [OperationDescription] ) throws -> CodeBlock { diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateSchemas.swift b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateSchemas.swift index 24dec36b..1279e037 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateSchemas.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateSchemas.swift @@ -28,6 +28,7 @@ extension TypesFileTranslator { /// list if the specified schema is unsupported. Returns multiple elements /// if the specified schema contains unnamed types that need to be declared /// inline. + /// - Throws: An error if there is an issue during the matching process. func translateSchema( componentKey: OpenAPI.ComponentKey, schema: JSONSchema @@ -53,6 +54,7 @@ extension TypesFileTranslator { /// - Parameter schemas: The schemas from the OpenAPI document. /// - Returns: A declaration of the schemas namespace in the parent /// components namespace. + /// - Throws: An error if there is an issue during schema translation. func translateSchemas( _ schemas: OpenAPI.ComponentDictionary ) throws -> Declaration { diff --git a/Sources/swift-openapi-generator/Extensions.swift b/Sources/swift-openapi-generator/Extensions.swift index ae878ae7..a88eed69 100644 --- a/Sources/swift-openapi-generator/Extensions.swift +++ b/Sources/swift-openapi-generator/Extensions.swift @@ -17,6 +17,11 @@ import _OpenAPIGeneratorCore import Yams extension URL: ExpressibleByArgument { + + /// Creates a `URL` instance from a string argument. + /// + /// Initializes a `URL` instance using the path provided as an argument string. + /// - Parameter argument: The string argument representing the path for the URL. public init?(argument: String) { self.init(fileURLWithPath: argument) } diff --git a/Sources/swift-openapi-generator/GenerateOptions+runGenerator.swift b/Sources/swift-openapi-generator/GenerateOptions+runGenerator.swift index 3300726e..8a576f7b 100644 --- a/Sources/swift-openapi-generator/GenerateOptions+runGenerator.swift +++ b/Sources/swift-openapi-generator/GenerateOptions+runGenerator.swift @@ -25,6 +25,8 @@ extension _GenerateOptions { /// - isDryRun: A Boolean value that indicates whether this invocation should /// be run in a testing mode to preview all the operations being carried out without /// making any actual changes. + /// - Throws: An error if any part of the generator execution encounters an issue, including loading configuration, + /// resolving options, generating code, and handling diagnostics. func runGenerator( outputDirectory: URL, pluginSource: PluginSource?, diff --git a/Sources/swift-openapi-generator/GenerateOptions.swift b/Sources/swift-openapi-generator/GenerateOptions.swift index bda103c7..ae3f1984 100644 --- a/Sources/swift-openapi-generator/GenerateOptions.swift +++ b/Sources/swift-openapi-generator/GenerateOptions.swift @@ -58,6 +58,8 @@ extension _GenerateOptions { /// Returns a list of the generator modes requested by the user. /// - Parameter config: The configuration specified by the user. + /// - Returns: A list of generator modes requested by the user. + /// - Throws: A `ValidationError` if no modes are provided and no configuration is available. func resolvedModes(_ config: _UserConfig?) throws -> [GeneratorMode] { if !mode.isEmpty { return mode @@ -70,6 +72,7 @@ extension _GenerateOptions { /// Returns a list of additional imports requested by the user. /// - Parameter config: The configuration specified by the user. + /// - Returns: A list of additional import statements requested by the user. func resolvedAdditionalImports(_ config: _UserConfig?) -> [String] { if !additionalImport.isEmpty { return additionalImport @@ -82,6 +85,7 @@ extension _GenerateOptions { /// Returns a list of the feature flags requested by the user. /// - Parameter config: The configuration specified by the user. + /// - Returns: A set of feature flags requested by the user. func resolvedFeatureFlags(_ config: _UserConfig?) -> FeatureFlags { if !featureFlag.isEmpty { return Set(featureFlag) @@ -106,6 +110,7 @@ extension _GenerateOptions { /// /// - Returns: Loaded configuration, if found and parsed successfully. /// Nil if the user provided no configuration file path. + /// - Throws: A `ValidationError` if loading or parsing the configuration file encounters an error. func loadedConfig() throws -> _UserConfig? { guard let config else { return nil diff --git a/Sources/swift-openapi-generator/runGenerator.swift b/Sources/swift-openapi-generator/runGenerator.swift index a5607a9e..36152f24 100644 --- a/Sources/swift-openapi-generator/runGenerator.swift +++ b/Sources/swift-openapi-generator/runGenerator.swift @@ -33,6 +33,8 @@ extension _Tool { /// - isDryRun: A Boolean value that indicates whether this invocation should /// be a dry run. /// - diagnostics: A collector for diagnostics emitted by the generator. + /// - Throws: An error if there are issues loading the OpenAPI document, + /// running the generator for each configuration, or handling diagnostics. static func runGenerator( doc: URL, configs: [Config], @@ -94,6 +96,8 @@ extension _Tool { /// - isDryRun: A Boolean value that indicates whether this invocation should /// be a dry run. /// - diagnostics: A collector for diagnostics emitted by the generator. + /// - Throws: An error if there are issues loading the OpenAPI document, + /// running the generator for each configuration, or handling diagnostics. static func runGenerator( doc: URL, docData: Data, @@ -122,7 +126,8 @@ extension _Tool { /// if the data is different than the current file contents. Will write to disk /// only if `isDryRun` is set as `false`. /// - Parameters: - /// - path: A path to the file. + /// - outputDirectory: The directory where the file is located. + /// - fileName: The name of the file. /// - contents: A closure evaluated to produce the file contents data. /// - isDryRun: A Boolean value that indicates whether this invocation should /// be a dry run. File system changes will not be written to disk in this mode. diff --git a/Tests/OpenAPIGeneratorReferenceTests/CompatabilityTest.swift b/Tests/OpenAPIGeneratorReferenceTests/CompatabilityTest.swift index 65e6b66d..81e0c5e2 100644 --- a/Tests/OpenAPIGeneratorReferenceTests/CompatabilityTest.swift +++ b/Tests/OpenAPIGeneratorReferenceTests/CompatabilityTest.swift @@ -205,6 +205,8 @@ fileprivate extension CompatibilityTest { /// - documentURL: The URL to the OpenAPI document. /// - license: The license of the OpenAPI document itself. Note, this is not necessarily the license of the code for the service API itself. /// - expectedDiagnostics: A set of diagnostics that should _not_ result in a test failure. + /// - skipBuild: A boolean value that indicates whether to skip the Swift package creation and build step. + /// - Throws: An error of if any step in the compatibility test harness fails. func _test( _ documentURL: String, license: License, diff --git a/Tests/PetstoreConsumerTests/Common.swift b/Tests/PetstoreConsumerTests/Common.swift index cd544454..d2d2c00e 100644 --- a/Tests/PetstoreConsumerTests/Common.swift +++ b/Tests/PetstoreConsumerTests/Common.swift @@ -21,6 +21,12 @@ extension Operations.listPets.Output { } extension HTTPRequest { + /// Initializes an HTTP request with the specified path, HTTP method, and header fields. + /// + /// - Parameters: + /// - path: The path of the HTTP request. + /// - method: The HTTP method (e.g., GET, POST, PUT, DELETE, etc.). + /// - headerFields: HTTP header fields to include in the request. public init(soar_path path: String, method: Method, headerFields: HTTPFields = .init()) { self.init(method: method, scheme: nil, authority: nil, path: path, headerFields: headerFields) } diff --git a/scripts/run-swift-format.sh b/scripts/run-swift-format.sh index 36d3a26d..878942e1 100644 --- a/scripts/run-swift-format.sh +++ b/scripts/run-swift-format.sh @@ -24,6 +24,8 @@ 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 -e 'Tests/OpenAPIGeneratorReferenceTests/Resources' \ + -e 'Sources/swift-openapi-generator/Documentation.docc' \ | xargs -0 "${SWIFTFORMAT_BIN}" lint --parallel --strict \ && SWIFT_FORMAT_RC=$? || SWIFT_FORMAT_RC=$?