From 16668dced6fa43e38dd5a1971c8aa096b6761168 Mon Sep 17 00:00:00 2001 From: Honza Dvorsky Date: Tue, 31 Oct 2023 13:42:33 +0100 Subject: [PATCH] Add some new swift-format 5.9 rules (#356) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add some new swift-format 5.9 rules ### Motivation I scanned the swift-format 5.9 release notes and found a few new rules that can make our code further consistent. ### Modifications Added those rules and reformatted. The only hand-made change is in `.swift-format`, the rest is the result of rerunning swift-format. ### Result More consistent code, fewer style discussions on PRs. ### Test Plan CI. Reviewed by: simonjbeaumont Builds: ✔︎ pull request validation (5.10) - Build finished. ✔︎ pull request validation (5.8) - Build finished. ✔︎ pull request validation (5.9) - Build finished. ✔︎ pull request validation (compatibility test) - Build finished. ✔︎ pull request validation (docc test) - Build finished. ✔︎ pull request validation (integration test) - Build finished. ✔︎ pull request validation (nightly) - Build finished. ✔︎ pull request validation (soundness) - Build finished. https://github.com/apple/swift-openapi-generator/pull/356 --- .swift-format | 3 +++ Plugins/OpenAPIGenerator/plugin.swift | 2 +- .../Layers/StructuredSwiftRepresentation.swift | 10 +++++----- .../_OpenAPIGeneratorCore/Parser/YamsParser.swift | 6 +++--- .../Translator/Operations/OperationDescription.swift | 2 +- .../Responses/translateResponseHeader.swift | 2 +- .../swift-openapi-generator/GenerateOptions.swift | 2 +- Tests/PetstoreConsumerTests/Test_Client.swift | 2 +- Tests/PetstoreConsumerTests/Test_Server.swift | 12 ++++++------ 9 files changed, 22 insertions(+), 19 deletions(-) diff --git a/.swift-format b/.swift-format index e5690f7b..3213ba65 100644 --- a/.swift-format +++ b/.swift-format @@ -18,6 +18,7 @@ "rules" : { "AllPublicDeclarationsHaveDocumentation" : true, "AlwaysUseLowerCamelCase" : false, + "AlwaysUseLiteralForEmptyCollectionInit" : true, "AmbiguousTrailingClosureOverload" : true, "BeginDocumentationCommentWithOneLineSummary" : false, "DoNotUseSemicolons" : true, @@ -38,10 +39,12 @@ "NoLeadingUnderscores" : false, "NoParensAroundConditions" : true, "NoVoidReturnOnFunctionSignature" : true, + "OmitExplicitReturns" : true, "OneCasePerLine" : true, "OneVariableDeclarationPerLine" : true, "OnlyOneTrailingClosureArgument" : true, "OrderedImports" : false, + "ReplaceForEachWithForLoop" : true, "ReturnVoidInsteadOfEmptyTuple" : true, "UseEarlyExits" : false, "UseLetInEveryBoundCaseVariable" : false, diff --git a/Plugins/OpenAPIGenerator/plugin.swift b/Plugins/OpenAPIGenerator/plugin.swift index 3108658a..0e4a08f2 100644 --- a/Plugins/OpenAPIGenerator/plugin.swift +++ b/Plugins/OpenAPIGenerator/plugin.swift @@ -62,7 +62,7 @@ import XcodeProjectPlugin extension SwiftOpenAPIGeneratorPlugin: XcodeBuildToolPlugin { func createBuildCommands(context: XcodePluginContext, target: XcodeTarget) throws -> [Command] { - return try createBuildCommands( + try createBuildCommands( pluginWorkDirectory: context.pluginWorkDirectory, tool: context.tool, sourceFiles: target.inputFiles, diff --git a/Sources/_OpenAPIGeneratorCore/Layers/StructuredSwiftRepresentation.swift b/Sources/_OpenAPIGeneratorCore/Layers/StructuredSwiftRepresentation.swift index 03128e84..0ca39e9f 100644 --- a/Sources/_OpenAPIGeneratorCore/Layers/StructuredSwiftRepresentation.swift +++ b/Sources/_OpenAPIGeneratorCore/Layers/StructuredSwiftRepresentation.swift @@ -1251,7 +1251,7 @@ extension Declaration { extension FunctionKind { /// Returns a non-failable initializer, for example `init()`. - static var initializer: Self { return .initializer(failable: false) } + static var initializer: Self { .initializer(failable: false) } /// Returns a non-static function kind. static func function(name: String) -> Self { .function(name: name, isStatic: false) } @@ -1262,12 +1262,12 @@ 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)) } + static func declaration(_ declaration: Declaration) -> Self { 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)) } + static func expression(_ expression: Expression) -> Self { CodeBlock(item: .expression(expression)) } } extension Expression { @@ -1290,7 +1290,7 @@ extension Expression { /// 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)) } + func dot(_ member: String) -> Expression { .memberAccess(.init(left: self, right: member)) } /// Returns a new expression that calls the current expression as a function /// with the specified arguments. @@ -1306,7 +1306,7 @@ 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)) } + static func dot(_ member: String) -> Self { Self.memberAccess(.init(right: member)) } /// Returns a new identifier expression for the provided pattern, such /// as a variable or function name. diff --git a/Sources/_OpenAPIGeneratorCore/Parser/YamsParser.swift b/Sources/_OpenAPIGeneratorCore/Parser/YamsParser.swift index 464f0ceb..dfd605f0 100644 --- a/Sources/_OpenAPIGeneratorCore/Parser/YamsParser.swift +++ b/Sources/_OpenAPIGeneratorCore/Parser/YamsParser.swift @@ -27,7 +27,7 @@ public struct YamsParser: ParserProtocol { /// - Returns: An array of top-level keys as strings. /// - Throws: An error if there are any issues with parsing the YAML string. public static func extractTopLevelKeys(fromYAMLString yamlString: String) throws -> [String] { - var yamlKeys = [String]() + var yamlKeys: [String] = [] let parser = try Parser(yaml: yamlString) if let rootNode = try parser.singleRoot(), case let .mapping(mapping) = rootNode { @@ -126,7 +126,7 @@ extension Diagnostic { /// - location: Describes the input file being worked on when the error occurred. /// - Returns: An error diagnostic. static func openAPIVersionError(versionString: String, location: Location) -> Diagnostic { - return error( + error( message: "Unsupported document version: \(versionString). Please provide a document with OpenAPI versions in the 3.0.x or 3.1.x sets.", location: location @@ -137,7 +137,7 @@ extension Diagnostic { /// - Parameter location: Describes the input file being worked on when the error occurred /// - Returns: An error diagnostic. static func openAPIMissingVersionError(location: Location) -> Diagnostic { - return error( + error( message: "No openapi key found, please provide a valid OpenAPI document with OpenAPI versions in the 3.0.x or 3.1.x sets.", location: location diff --git a/Sources/_OpenAPIGeneratorCore/Translator/Operations/OperationDescription.swift b/Sources/_OpenAPIGeneratorCore/Translator/Operations/OperationDescription.swift index 8b26ad6c..1284996d 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/Operations/OperationDescription.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/Operations/OperationDescription.swift @@ -102,7 +102,7 @@ extension OperationDescription { /// Returns the type name of the namespace unique to the operation. var operationNamespace: TypeName { - return .init( + .init( components: [.root, .init(swift: Constants.Operations.namespace, json: "paths")] + path.components.map { .init(swift: nil, json: $0) } + [ .init(swift: methodName, json: httpMethod.rawValue) diff --git a/Sources/_OpenAPIGeneratorCore/Translator/Responses/translateResponseHeader.swift b/Sources/_OpenAPIGeneratorCore/Translator/Responses/translateResponseHeader.swift index 55e49ff6..4412a7be 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/Responses/translateResponseHeader.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/Responses/translateResponseHeader.swift @@ -126,7 +126,7 @@ extension ServerFileTranslator { func translateResponseHeaderInServer(_ header: TypedResponseHeader, responseVariableName: String) throws -> Expression { - return .try( + .try( .identifierPattern("converter").dot("setHeaderFieldAs\(header.codingStrategy.runtimeName)") .call([ .init( diff --git a/Sources/swift-openapi-generator/GenerateOptions.swift b/Sources/swift-openapi-generator/GenerateOptions.swift index 7c83e50a..4e061714 100644 --- a/Sources/swift-openapi-generator/GenerateOptions.swift +++ b/Sources/swift-openapi-generator/GenerateOptions.swift @@ -98,7 +98,7 @@ extension _GenerateOptions { do { let data = try Data(contentsOf: config) let configAsString = String(decoding: data, as: UTF8.self) - var yamlKeys = [String]() + var yamlKeys: [String] = [] do { yamlKeys = try YamsParser.extractTopLevelKeys(fromYAMLString: configAsString) } catch { throw ValidationError("The config isn't valid. \(error)") diff --git a/Tests/PetstoreConsumerTests/Test_Client.swift b/Tests/PetstoreConsumerTests/Test_Client.swift index 2e3b30c6..7156cb25 100644 --- a/Tests/PetstoreConsumerTests/Test_Client.swift +++ b/Tests/PetstoreConsumerTests/Test_Client.swift @@ -676,7 +676,7 @@ final class Test_Client: XCTestCase { func testUploadAvatarForPet_500() async throws { transport = .init { request, requestBody, baseURL, operationID in - return try HTTPResponse(status: .internalServerError, headerFields: [.contentType: "text/plain"]) + try HTTPResponse(status: .internalServerError, headerFields: [.contentType: "text/plain"]) .withEncodedBody(Data.efghString) } let response = try await client.uploadAvatarForPet(.init(path: .init(petId: 1), body: .binary(.init(.abcd)))) diff --git a/Tests/PetstoreConsumerTests/Test_Server.swift b/Tests/PetstoreConsumerTests/Test_Server.swift index 6ec48111..0eb86525 100644 --- a/Tests/PetstoreConsumerTests/Test_Server.swift +++ b/Tests/PetstoreConsumerTests/Test_Server.swift @@ -79,7 +79,7 @@ final class Test_Server: XCTestCase { func testListPets_default() async throws { client = .init(listPetsBlock: { input in - return .default(statusCode: 400, .init(body: .json(.init(code: 1, me_dollar_sage: "Oh no!")))) + .default(statusCode: 400, .init(body: .json(.init(code: 1, me_dollar_sage: "Oh no!")))) }) let (response, responseBody) = try await server.listPets( .init(soar_path: "/api/pets", method: .get), @@ -377,7 +377,7 @@ final class Test_Server: XCTestCase { } func testGetStats_200_json() async throws { - client = .init(getStatsBlock: { input in return .ok(.init(body: .json(.init(count: 1)))) }) + client = .init(getStatsBlock: { input in .ok(.init(body: .json(.init(count: 1)))) }) let (response, responseBody) = try await server.getStats( .init( soar_path: "/api/pets/stats", @@ -400,7 +400,7 @@ final class Test_Server: XCTestCase { } func testGetStats_200_unexpectedAccept() async throws { - client = .init(getStatsBlock: { input in return .ok(.init(body: .json(.init(count: 1)))) }) + client = .init(getStatsBlock: { input in .ok(.init(body: .json(.init(count: 1)))) }) do { _ = try await server.getStats( .init(soar_path: "/api/pets/stats", method: .patch, headerFields: [.accept: "foo/bar"]), @@ -412,7 +412,7 @@ final class Test_Server: XCTestCase { } func testGetStats_200_text() async throws { - client = .init(getStatsBlock: { input in return .ok(.init(body: .plainText("count is 1"))) }) + client = .init(getStatsBlock: { input in .ok(.init(body: .plainText("count is 1"))) }) let (response, responseBody) = try await server.getStats( .init( soar_path: "/api/pets/stats", @@ -521,7 +521,7 @@ final class Test_Server: XCTestCase { } func testGetStats_200_binary() async throws { - client = .init(getStatsBlock: { input in return .ok(.init(body: .binary("count_is_1"))) }) + client = .init(getStatsBlock: { input in .ok(.init(body: .binary("count_is_1"))) }) let (response, responseBody) = try await server.getStats( .init( soar_path: "/api/pets/stats", @@ -634,7 +634,7 @@ final class Test_Server: XCTestCase { } func testProbe_204() async throws { - client = .init(probeBlock: { input in return .noContent(.init()) }) + client = .init(probeBlock: { input in .noContent(.init()) }) let (response, responseBody) = try await server.probe( .init(soar_path: "/api/probe/", method: .post), nil,