repo_name stringlengths 1 62 | dataset stringclasses 1 value | lang stringclasses 11 values | pr_id int64 1 20.1k | owner stringlengths 2 34 | reviewer stringlengths 2 39 | diff_hunk stringlengths 15 262k | code_review_comment stringlengths 1 99.6k |
|---|---|---|---|---|---|---|---|
swift-openapi-generator | github_2023 | others | 679 | apple | simonjbeaumont | @@ -0,0 +1,160 @@
+# SOAR-0013: Optimistic naming strategy
+
+Introduce an alternative naming strategy for more idiomatic Swift identifiers, including a way to provide custom name overrides.
+
+## Overview
+
+- Proposal: SOAR-0013
+- Author(s): [Honza Dvorsky](https://github.com/czechboy0), [Si Beaumont](https://github.com/simonjbeaumont)
+- Status: **Awaiting Review**
+- Issues:
+ - [apple/swift-openapi-generator#112][issuePlugin]
+ - [apple/swift-openapi-generator#107][issue1]
+ - [apple/swift-openapi-generator#503][issue2]
+ - [apple/swift-openapi-generator#244][issue3]
+ - [apple/swift-openapi-generator#405][issue4]
+- Implementation:
+ - [apple/swift-openapi-generator#679][pr]
+- New configuration options:
+ - `namingStrategy`
+ - `nameOverrides`
+- Affected components:
+ - generator
+
+### Introduction
+
+Introduce a new naming strategy as an opt-in feature, instructing the generator to produce more conventional Swift names, and offer a way to completely customize how any OpenAPI identifier gets projected to a Swift identifier.
+
+### Motivation
+
+The purpose of Swift OpenAPI Generator is to generate Swift code from OpenAPI documents. As part of that process, names specified in the OpenAPI document have to be converted to names in Swift code - and there are many ways to do that. We call these "naming strategies" in this proposal.
+
+When Swift OpenAPI Generator 0.1.0 went open-source in May 2023, it had a simple naming strategy that produced relatively conventional Swift identifiers from OpenAPI names, however when tested on a large test corpus of around 3000 OpenAPI documents, it produced an unacceptably high number of non-compiling packages due to naming conflicts.
+
+The root cause of conflicts are the different allowed character sets for OpenAPI names and Swift identifiers. OpenAPI has a more flexible allowed character set than Swift identifiers.
+
+In response to the findings on the test corpus, the proposal [SOAR-0001: Improved mapping of identifiers][soar0001], which shipped in 0.2.0, changed the naming strategy to avoid conflicts and resulted in no conflicts produced in the test corpus, allowing hundreds of additional OpenAPI documents to be correctly handled by Swift OpenAPI Generator.
+
+The way the conflicts are avoided in the naming strategy from SOAR-0001 is by turning any special characters (any characters that aren't letters, numbers, or an underscore) into words, resulting in identifiers like:
+
+```
+User -> User
+User_1 -> User_1
+user-name -> user_hyphen_name
+my.org.User -> my_period_org_period_User
+```
+
+The existing naming strategy also avoids changing the character casing, as we discovered OpenAPI documents with properties within an object schema that only differred by case. | Suggestion: move this up to the constraints we found (the sentence that begins with "The root cause...") |
swift-openapi-generator | github_2023 | others | 679 | apple | simonjbeaumont | @@ -0,0 +1,160 @@
+# SOAR-0013: Optimistic naming strategy
+
+Introduce an alternative naming strategy for more idiomatic Swift identifiers, including a way to provide custom name overrides.
+
+## Overview
+
+- Proposal: SOAR-0013
+- Author(s): [Honza Dvorsky](https://github.com/czechboy0), [Si Beaumont](https://github.com/simonjbeaumont)
+- Status: **Awaiting Review**
+- Issues:
+ - [apple/swift-openapi-generator#112][issuePlugin]
+ - [apple/swift-openapi-generator#107][issue1]
+ - [apple/swift-openapi-generator#503][issue2]
+ - [apple/swift-openapi-generator#244][issue3]
+ - [apple/swift-openapi-generator#405][issue4]
+- Implementation:
+ - [apple/swift-openapi-generator#679][pr]
+- New configuration options:
+ - `namingStrategy`
+ - `nameOverrides`
+- Affected components:
+ - generator
+
+### Introduction
+
+Introduce a new naming strategy as an opt-in feature, instructing the generator to produce more conventional Swift names, and offer a way to completely customize how any OpenAPI identifier gets projected to a Swift identifier.
+
+### Motivation
+
+The purpose of Swift OpenAPI Generator is to generate Swift code from OpenAPI documents. As part of that process, names specified in the OpenAPI document have to be converted to names in Swift code - and there are many ways to do that. We call these "naming strategies" in this proposal.
+
+When Swift OpenAPI Generator 0.1.0 went open-source in May 2023, it had a simple naming strategy that produced relatively conventional Swift identifiers from OpenAPI names, however when tested on a large test corpus of around 3000 OpenAPI documents, it produced an unacceptably high number of non-compiling packages due to naming conflicts.
+
+The root cause of conflicts are the different allowed character sets for OpenAPI names and Swift identifiers. OpenAPI has a more flexible allowed character set than Swift identifiers.
+
+In response to the findings on the test corpus, the proposal [SOAR-0001: Improved mapping of identifiers][soar0001], which shipped in 0.2.0, changed the naming strategy to avoid conflicts and resulted in no conflicts produced in the test corpus, allowing hundreds of additional OpenAPI documents to be correctly handled by Swift OpenAPI Generator.
+
+The way the conflicts are avoided in the naming strategy from SOAR-0001 is by turning any special characters (any characters that aren't letters, numbers, or an underscore) into words, resulting in identifiers like:
+
+```
+User -> User
+User_1 -> User_1
+user-name -> user_hyphen_name
+my.org.User -> my_period_org_period_User
+```
+
+The existing naming strategy also avoids changing the character casing, as we discovered OpenAPI documents with properties within an object schema that only differred by case.
+
+The decision to rely on a naming strategy that can handle all the tested OpenAPI documents was the right one, and it has allowed more developers to get value from Swift OpenAPI Generator since then.
+
+However, we've also [heard][issue1] [from][issue2] [adopters][issue3] [who][issue4] don't use special characters in their OpenAPI documents, and how some of the generated Swift names are still difficult to read and are simply unpleasant to look at.
+
+We originally believed that a fully generalized solution, such as a ["naming extension"][issuePlugin], would be the right way to go, however after further consideration, we believe we can offer a solution that solves the majority of the problem without needing to invent an extension architecture for Swift OpenAPI Generator. | Suggest we can remove this. It's already called out in alternatives section. |
swift-openapi-generator | github_2023 | others | 679 | apple | simonjbeaumont | @@ -0,0 +1,160 @@
+# SOAR-0013: Optimistic naming strategy
+
+Introduce an alternative naming strategy for more idiomatic Swift identifiers, including a way to provide custom name overrides.
+
+## Overview
+
+- Proposal: SOAR-0013
+- Author(s): [Honza Dvorsky](https://github.com/czechboy0), [Si Beaumont](https://github.com/simonjbeaumont)
+- Status: **Awaiting Review**
+- Issues:
+ - [apple/swift-openapi-generator#112][issuePlugin]
+ - [apple/swift-openapi-generator#107][issue1]
+ - [apple/swift-openapi-generator#503][issue2]
+ - [apple/swift-openapi-generator#244][issue3]
+ - [apple/swift-openapi-generator#405][issue4]
+- Implementation:
+ - [apple/swift-openapi-generator#679][pr]
+- New configuration options:
+ - `namingStrategy`
+ - `nameOverrides`
+- Affected components:
+ - generator
+
+### Introduction
+
+Introduce a new naming strategy as an opt-in feature, instructing the generator to produce more conventional Swift names, and offer a way to completely customize how any OpenAPI identifier gets projected to a Swift identifier.
+
+### Motivation
+
+The purpose of Swift OpenAPI Generator is to generate Swift code from OpenAPI documents. As part of that process, names specified in the OpenAPI document have to be converted to names in Swift code - and there are many ways to do that. We call these "naming strategies" in this proposal.
+
+When Swift OpenAPI Generator 0.1.0 went open-source in May 2023, it had a simple naming strategy that produced relatively conventional Swift identifiers from OpenAPI names, however when tested on a large test corpus of around 3000 OpenAPI documents, it produced an unacceptably high number of non-compiling packages due to naming conflicts.
+
+The root cause of conflicts are the different allowed character sets for OpenAPI names and Swift identifiers. OpenAPI has a more flexible allowed character set than Swift identifiers.
+
+In response to the findings on the test corpus, the proposal [SOAR-0001: Improved mapping of identifiers][soar0001], which shipped in 0.2.0, changed the naming strategy to avoid conflicts and resulted in no conflicts produced in the test corpus, allowing hundreds of additional OpenAPI documents to be correctly handled by Swift OpenAPI Generator.
+
+The way the conflicts are avoided in the naming strategy from SOAR-0001 is by turning any special characters (any characters that aren't letters, numbers, or an underscore) into words, resulting in identifiers like:
+
+```
+User -> User
+User_1 -> User_1
+user-name -> user_hyphen_name
+my.org.User -> my_period_org_period_User
+```
+
+The existing naming strategy also avoids changing the character casing, as we discovered OpenAPI documents with properties within an object schema that only differred by case.
+
+The decision to rely on a naming strategy that can handle all the tested OpenAPI documents was the right one, and it has allowed more developers to get value from Swift OpenAPI Generator since then.
+
+However, we've also [heard][issue1] [from][issue2] [adopters][issue3] [who][issue4] don't use special characters in their OpenAPI documents, and how some of the generated Swift names are still difficult to read and are simply unpleasant to look at.
+
+We originally believed that a fully generalized solution, such as a ["naming extension"][issuePlugin], would be the right way to go, however after further consideration, we believe we can offer a solution that solves the majority of the problem without needing to invent an extension architecture for Swift OpenAPI Generator.
+
+### Proposed solution
+
+We propose to introduce a second, opt-in naming strategy, which produces idiomatic Swift identifiers from arbitrary OpenAPI names, and a way to fully customize the conversion from an OpenAPI name to a Swift identifier using a string -> string map.
+
+For clarity, we'll refer to the existing naming strategy as the "defensive" naming strategy, and to the new proposed strategy as the "optimistic" naming strategy. The names reflect the strengths of each strategy - the defensive strategy can handle any OpenAPI document and produce compiling Swift code, the optimistic naming strategy produces prettier names, but does not work for all documents, and falls back to the defensive strategy when needed on a per-name basis. | Naming bikeshed: I don't mind the terms `defensive` and `optimistic`, but should we make these terms symmetric?
E.g. `pessimistic` and `optimistic`? (Clearly `offensive` as a converse of `defensive` is bad).
Another idea: `defensive` and `idiomatic`. |
swift-openapi-generator | github_2023 | others | 679 | apple | simonjbeaumont | @@ -0,0 +1,160 @@
+# SOAR-0013: Optimistic naming strategy
+
+Introduce an alternative naming strategy for more idiomatic Swift identifiers, including a way to provide custom name overrides.
+
+## Overview
+
+- Proposal: SOAR-0013
+- Author(s): [Honza Dvorsky](https://github.com/czechboy0), [Si Beaumont](https://github.com/simonjbeaumont)
+- Status: **Awaiting Review**
+- Issues:
+ - [apple/swift-openapi-generator#112][issuePlugin]
+ - [apple/swift-openapi-generator#107][issue1]
+ - [apple/swift-openapi-generator#503][issue2]
+ - [apple/swift-openapi-generator#244][issue3]
+ - [apple/swift-openapi-generator#405][issue4]
+- Implementation:
+ - [apple/swift-openapi-generator#679][pr]
+- New configuration options:
+ - `namingStrategy`
+ - `nameOverrides`
+- Affected components:
+ - generator
+
+### Introduction
+
+Introduce a new naming strategy as an opt-in feature, instructing the generator to produce more conventional Swift names, and offer a way to completely customize how any OpenAPI identifier gets projected to a Swift identifier.
+
+### Motivation
+
+The purpose of Swift OpenAPI Generator is to generate Swift code from OpenAPI documents. As part of that process, names specified in the OpenAPI document have to be converted to names in Swift code - and there are many ways to do that. We call these "naming strategies" in this proposal.
+
+When Swift OpenAPI Generator 0.1.0 went open-source in May 2023, it had a simple naming strategy that produced relatively conventional Swift identifiers from OpenAPI names, however when tested on a large test corpus of around 3000 OpenAPI documents, it produced an unacceptably high number of non-compiling packages due to naming conflicts.
+
+The root cause of conflicts are the different allowed character sets for OpenAPI names and Swift identifiers. OpenAPI has a more flexible allowed character set than Swift identifiers.
+
+In response to the findings on the test corpus, the proposal [SOAR-0001: Improved mapping of identifiers][soar0001], which shipped in 0.2.0, changed the naming strategy to avoid conflicts and resulted in no conflicts produced in the test corpus, allowing hundreds of additional OpenAPI documents to be correctly handled by Swift OpenAPI Generator.
+
+The way the conflicts are avoided in the naming strategy from SOAR-0001 is by turning any special characters (any characters that aren't letters, numbers, or an underscore) into words, resulting in identifiers like:
+
+```
+User -> User
+User_1 -> User_1
+user-name -> user_hyphen_name
+my.org.User -> my_period_org_period_User
+```
+
+The existing naming strategy also avoids changing the character casing, as we discovered OpenAPI documents with properties within an object schema that only differred by case.
+
+The decision to rely on a naming strategy that can handle all the tested OpenAPI documents was the right one, and it has allowed more developers to get value from Swift OpenAPI Generator since then.
+
+However, we've also [heard][issue1] [from][issue2] [adopters][issue3] [who][issue4] don't use special characters in their OpenAPI documents, and how some of the generated Swift names are still difficult to read and are simply unpleasant to look at.
+
+We originally believed that a fully generalized solution, such as a ["naming extension"][issuePlugin], would be the right way to go, however after further consideration, we believe we can offer a solution that solves the majority of the problem without needing to invent an extension architecture for Swift OpenAPI Generator.
+
+### Proposed solution
+
+We propose to introduce a second, opt-in naming strategy, which produces idiomatic Swift identifiers from arbitrary OpenAPI names, and a way to fully customize the conversion from an OpenAPI name to a Swift identifier using a string -> string map.
+
+For clarity, we'll refer to the existing naming strategy as the "defensive" naming strategy, and to the new proposed strategy as the "optimistic" naming strategy. The names reflect the strengths of each strategy - the defensive strategy can handle any OpenAPI document and produce compiling Swift code, the optimistic naming strategy produces prettier names, but does not work for all documents, and falls back to the defensive strategy when needed on a per-name basis.
+
+Part of the new strategy is adjusting the capitalization, and producing `UpperCamelCase` names for types, and `lowerCamelCase` names for members, as is common in hand-written Swift code.
+
+> Warning: Due to the optimistic naming strategy changing capitalization, it is possible to get non-compiling Swift code from more OpenAPI documents than with the defensive naming strategy. We recommend you try to use the optimistic naming strategy on your OpenAPI document, and if it produces conflicts, switch back to the defensive naming strategy, which avoids conflicts. However, the number of documents that result in conflicts with the optimistic naming strategy is estimated to be very small (<1%). | If we move this down below the paragraph that introduces the naming overrides it allows us to provide more guidance. If you want to use it and it doesn't produce compiling code for a given OpenAPI document then you have two choices: (1) if the number of offending identifiers is small, you can use the naming overrides; or (2) revert back to `defensive`.
Additionally, I think we should make a call here (or in the alternatives considered) that there's no middle ground here. We're not, at this time, considering opening up any finer grain configurability: users can choose between the pessimistic safe, or one opinionated strategy that attempts to be idiomatic.
Finally, I think we should really emphasise that this has shrunk the window to **_only_** the mixed casing. Because we are layering the prettification with the sanitisation.
|
swift-openapi-generator | github_2023 | others | 679 | apple | simonjbeaumont | @@ -0,0 +1,160 @@
+# SOAR-0013: Optimistic naming strategy
+
+Introduce an alternative naming strategy for more idiomatic Swift identifiers, including a way to provide custom name overrides.
+
+## Overview
+
+- Proposal: SOAR-0013
+- Author(s): [Honza Dvorsky](https://github.com/czechboy0), [Si Beaumont](https://github.com/simonjbeaumont)
+- Status: **Awaiting Review**
+- Issues:
+ - [apple/swift-openapi-generator#112][issuePlugin]
+ - [apple/swift-openapi-generator#107][issue1]
+ - [apple/swift-openapi-generator#503][issue2]
+ - [apple/swift-openapi-generator#244][issue3]
+ - [apple/swift-openapi-generator#405][issue4]
+- Implementation:
+ - [apple/swift-openapi-generator#679][pr]
+- New configuration options:
+ - `namingStrategy`
+ - `nameOverrides`
+- Affected components:
+ - generator
+
+### Introduction
+
+Introduce a new naming strategy as an opt-in feature, instructing the generator to produce more conventional Swift names, and offer a way to completely customize how any OpenAPI identifier gets projected to a Swift identifier.
+
+### Motivation
+
+The purpose of Swift OpenAPI Generator is to generate Swift code from OpenAPI documents. As part of that process, names specified in the OpenAPI document have to be converted to names in Swift code - and there are many ways to do that. We call these "naming strategies" in this proposal.
+
+When Swift OpenAPI Generator 0.1.0 went open-source in May 2023, it had a simple naming strategy that produced relatively conventional Swift identifiers from OpenAPI names, however when tested on a large test corpus of around 3000 OpenAPI documents, it produced an unacceptably high number of non-compiling packages due to naming conflicts.
+
+The root cause of conflicts are the different allowed character sets for OpenAPI names and Swift identifiers. OpenAPI has a more flexible allowed character set than Swift identifiers.
+
+In response to the findings on the test corpus, the proposal [SOAR-0001: Improved mapping of identifiers][soar0001], which shipped in 0.2.0, changed the naming strategy to avoid conflicts and resulted in no conflicts produced in the test corpus, allowing hundreds of additional OpenAPI documents to be correctly handled by Swift OpenAPI Generator.
+
+The way the conflicts are avoided in the naming strategy from SOAR-0001 is by turning any special characters (any characters that aren't letters, numbers, or an underscore) into words, resulting in identifiers like:
+
+```
+User -> User
+User_1 -> User_1
+user-name -> user_hyphen_name
+my.org.User -> my_period_org_period_User
+```
+
+The existing naming strategy also avoids changing the character casing, as we discovered OpenAPI documents with properties within an object schema that only differred by case.
+
+The decision to rely on a naming strategy that can handle all the tested OpenAPI documents was the right one, and it has allowed more developers to get value from Swift OpenAPI Generator since then.
+
+However, we've also [heard][issue1] [from][issue2] [adopters][issue3] [who][issue4] don't use special characters in their OpenAPI documents, and how some of the generated Swift names are still difficult to read and are simply unpleasant to look at.
+
+We originally believed that a fully generalized solution, such as a ["naming extension"][issuePlugin], would be the right way to go, however after further consideration, we believe we can offer a solution that solves the majority of the problem without needing to invent an extension architecture for Swift OpenAPI Generator.
+
+### Proposed solution
+
+We propose to introduce a second, opt-in naming strategy, which produces idiomatic Swift identifiers from arbitrary OpenAPI names, and a way to fully customize the conversion from an OpenAPI name to a Swift identifier using a string -> string map.
+
+For clarity, we'll refer to the existing naming strategy as the "defensive" naming strategy, and to the new proposed strategy as the "optimistic" naming strategy. The names reflect the strengths of each strategy - the defensive strategy can handle any OpenAPI document and produce compiling Swift code, the optimistic naming strategy produces prettier names, but does not work for all documents, and falls back to the defensive strategy when needed on a per-name basis.
+
+Part of the new strategy is adjusting the capitalization, and producing `UpperCamelCase` names for types, and `lowerCamelCase` names for members, as is common in hand-written Swift code.
+
+> Warning: Due to the optimistic naming strategy changing capitalization, it is possible to get non-compiling Swift code from more OpenAPI documents than with the defensive naming strategy. We recommend you try to use the optimistic naming strategy on your OpenAPI document, and if it produces conflicts, switch back to the defensive naming strategy, which avoids conflicts. However, the number of documents that result in conflicts with the optimistic naming strategy is estimated to be very small (<1%).
+
+The second feature introduced as part of this proposal is a way to provide a string -> string map to fully override only specific OpenAPI names and provide their exact Swift identifiers. This is the ultimate escape hatch when both naming strategies fail to provide the desired result for the adopter.
+
+#### Examples
+
+To get a sense for the proposed change, check out the table below that compares the existing defensive strategy against the proposed optimistic strategy on a set of examples:
+
+| OpenAPI name | Defensive | Optimistic (capitalized) | Optimistic (non-capitalized) |
+| ------------ | --------- | ------------------------ | ---------------------------- |
+| `foo` | `foo` | `Foo` | `foo` |
+| `Hello world` | `Hello_space_world` | `HelloWorld` | `helloWorld` |
+| `My_URL_value` | `My_URL_value` | `MyURLValue` | `myURLValue` |
+| `Retry-After` | `Retry_hyphen_After` | `RetryAfter` | `retryAfter` |
+| `NOT_AVAILABLE` | `NOT_AVAILABLE` | `NotAvailable` | `notAvailable` |
+| `version 2.0` | `version_space_2_period_0` | `Version2_0` | `version2_0` |
+| `naïve café` | `naïve_space_café` | `NaïveCafé` | `naïveCafé` |
+| `__user` | `__user` | `__User` | `__user` |
+| `order#123` | `order_num_123` | `order_num_123` | `order_num_123` |
+
+Notice that in the last example, since the OpenAPI name contains the pound (`#`) character, the optimistic naming strategy falls back to the defensive naming strategy. In all the other cases, however, the resulting names are more idiomatic Swift identifiers.
+
+> Tip: For more examples, check out the updated [test suite](https://github.com/czechboy0/swift-openapi-generator/blob/hd-naming-strategy-optimistic/Tests/OpenAPIGeneratorCoreTests/Extensions/Test_SwiftSafeNames.swift).
+
+### Detailed design
+
+This section goes into detail of the [draft implementation][pr] that you can already check out and try to run on your OpenAPI document.
+
+> Note: To enable it, you'll need to add `namingStrategy: optimistic` to your `openapi-generator-config.yaml` file.
+
+#### Naming logic
+
+The optimistic naming strategy (check out the current code [here][impl], look for the method `safeForSwiftCode_optimistic`) is built around the decision to _only_ optimize for names that include the following:
+
+- letters
+- numbers
+- periods (`.`, ASCII: `0x2e`)
+- dashes (`-`, ASCII: `0x2d`)
+- underscores (`_`, ASCII: `0x5f`)
+- spaces (` `, ASCII: `0x20`)
+
+> Note: We let [`Swift.String.isLetter`](https://developer.apple.com/documentation/swift/character/isletter) decide whether a character is a letter, which has the advantage of including letters in the non-ASCII range. Swift identifiers also support a [wide range](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/lexicalstructure/#Identifiers) of alphanumeric characters.
+
+If the OpenAPI name includes any _other_ characters, the optimistic naming strategy _falls back_ to the defensive naming strategy for that input string only.
+
+There's a second special case for handling all uppercased names, such as `NOT_AVAILABLE` - if this situation is detected, the optimistic naming strategy turns it into `NotAvailable` for types and `notAvailable` for members.
+
+The best way to understand the detailed logic is to check out the [code][impl], feel free to leave comments on the pull request.
+
+#### Naming strategy configuration
+
+Since Swift OpenAPI Generator is on a stable 1.x version, we cannot change the naming strategy for everyone, as it would be considered an API break. So this new naming strategy is fully opt-in using a new configuration key called `namingStrategy`, with the following allowed values:
+
+- `defensive`: the existing naming strategy introduced in 0.2.0
+- `optimistic`: the new naming strategy proposed here
+- not specified: defaults to `defensive` for backwards compatibility | Aside: do we think this ever should become the default, e.g. if we were to cut a new major? IMO, no, but I'm curious what you think? |
swift-openapi-generator | github_2023 | others | 679 | apple | simonjbeaumont | @@ -0,0 +1,160 @@
+# SOAR-0013: Optimistic naming strategy
+
+Introduce an alternative naming strategy for more idiomatic Swift identifiers, including a way to provide custom name overrides.
+
+## Overview
+
+- Proposal: SOAR-0013
+- Author(s): [Honza Dvorsky](https://github.com/czechboy0), [Si Beaumont](https://github.com/simonjbeaumont)
+- Status: **Awaiting Review**
+- Issues:
+ - [apple/swift-openapi-generator#112][issuePlugin]
+ - [apple/swift-openapi-generator#107][issue1]
+ - [apple/swift-openapi-generator#503][issue2]
+ - [apple/swift-openapi-generator#244][issue3]
+ - [apple/swift-openapi-generator#405][issue4]
+- Implementation:
+ - [apple/swift-openapi-generator#679][pr]
+- New configuration options:
+ - `namingStrategy`
+ - `nameOverrides`
+- Affected components:
+ - generator
+
+### Introduction
+
+Introduce a new naming strategy as an opt-in feature, instructing the generator to produce more conventional Swift names, and offer a way to completely customize how any OpenAPI identifier gets projected to a Swift identifier.
+
+### Motivation
+
+The purpose of Swift OpenAPI Generator is to generate Swift code from OpenAPI documents. As part of that process, names specified in the OpenAPI document have to be converted to names in Swift code - and there are many ways to do that. We call these "naming strategies" in this proposal.
+
+When Swift OpenAPI Generator 0.1.0 went open-source in May 2023, it had a simple naming strategy that produced relatively conventional Swift identifiers from OpenAPI names, however when tested on a large test corpus of around 3000 OpenAPI documents, it produced an unacceptably high number of non-compiling packages due to naming conflicts.
+
+The root cause of conflicts are the different allowed character sets for OpenAPI names and Swift identifiers. OpenAPI has a more flexible allowed character set than Swift identifiers.
+
+In response to the findings on the test corpus, the proposal [SOAR-0001: Improved mapping of identifiers][soar0001], which shipped in 0.2.0, changed the naming strategy to avoid conflicts and resulted in no conflicts produced in the test corpus, allowing hundreds of additional OpenAPI documents to be correctly handled by Swift OpenAPI Generator.
+
+The way the conflicts are avoided in the naming strategy from SOAR-0001 is by turning any special characters (any characters that aren't letters, numbers, or an underscore) into words, resulting in identifiers like:
+
+```
+User -> User
+User_1 -> User_1
+user-name -> user_hyphen_name
+my.org.User -> my_period_org_period_User
+```
+
+The existing naming strategy also avoids changing the character casing, as we discovered OpenAPI documents with properties within an object schema that only differred by case.
+
+The decision to rely on a naming strategy that can handle all the tested OpenAPI documents was the right one, and it has allowed more developers to get value from Swift OpenAPI Generator since then.
+
+However, we've also [heard][issue1] [from][issue2] [adopters][issue3] [who][issue4] don't use special characters in their OpenAPI documents, and how some of the generated Swift names are still difficult to read and are simply unpleasant to look at. | Suggest we just state the facts here. E.g. let's say that this resolved all the compilation issues with our corpus of NNN OpenAPI documents, but we don't need to make a statement about whether we believe or not it was the right call. I believe it was; others might not and we don't want distract from the proposal itself. |
swift-openapi-generator | github_2023 | others | 679 | apple | simonjbeaumont | @@ -0,0 +1,160 @@
+# SOAR-0013: Optimistic naming strategy
+
+Introduce an alternative naming strategy for more idiomatic Swift identifiers, including a way to provide custom name overrides.
+
+## Overview
+
+- Proposal: SOAR-0013
+- Author(s): [Honza Dvorsky](https://github.com/czechboy0), [Si Beaumont](https://github.com/simonjbeaumont)
+- Status: **Awaiting Review**
+- Issues:
+ - [apple/swift-openapi-generator#112][issuePlugin]
+ - [apple/swift-openapi-generator#107][issue1]
+ - [apple/swift-openapi-generator#503][issue2]
+ - [apple/swift-openapi-generator#244][issue3]
+ - [apple/swift-openapi-generator#405][issue4]
+- Implementation:
+ - [apple/swift-openapi-generator#679][pr]
+- New configuration options:
+ - `namingStrategy`
+ - `nameOverrides`
+- Affected components:
+ - generator
+
+### Introduction
+
+Introduce a new naming strategy as an opt-in feature, instructing the generator to produce more conventional Swift names, and offer a way to completely customize how any OpenAPI identifier gets projected to a Swift identifier.
+
+### Motivation
+
+The purpose of Swift OpenAPI Generator is to generate Swift code from OpenAPI documents. As part of that process, names specified in the OpenAPI document have to be converted to names in Swift code - and there are many ways to do that. We call these "naming strategies" in this proposal.
+
+When Swift OpenAPI Generator 0.1.0 went open-source in May 2023, it had a simple naming strategy that produced relatively conventional Swift identifiers from OpenAPI names, however when tested on a large test corpus of around 3000 OpenAPI documents, it produced an unacceptably high number of non-compiling packages due to naming conflicts.
+
+The root cause of conflicts are the different allowed character sets for OpenAPI names and Swift identifiers. OpenAPI has a more flexible allowed character set than Swift identifiers.
+
+In response to the findings on the test corpus, the proposal [SOAR-0001: Improved mapping of identifiers][soar0001], which shipped in 0.2.0, changed the naming strategy to avoid conflicts and resulted in no conflicts produced in the test corpus, allowing hundreds of additional OpenAPI documents to be correctly handled by Swift OpenAPI Generator. | Suggest we move this down to after explaining what it does and we can talk about the outcome there (see the other comment too below about how we position the outcome). |
swift-openapi-generator | github_2023 | others | 679 | apple | simonjbeaumont | @@ -12,6 +12,24 @@
//
//===----------------------------------------------------------------------===//
+/// A strategy for turning OpenAPI identifiers into Swift identifiers.
+public enum NamingStrategy: String, Sendable, Codable, Equatable {
+
+ /// A defensive strategy that can handle any OpenAPI identifier and produce a non-conflicting Swift identifier.
+ ///
+ /// This strategy is the default in Swift OpenAPI Generator 1.x.
+ /// | ```suggestion
```
I don't think this is the right place to document this. We have it in the correct place already, which is the docs on the `Config` object. |
swift-openapi-generator | github_2023 | others | 679 | apple | simonjbeaumont | @@ -12,6 +12,24 @@
//
//===----------------------------------------------------------------------===//
+/// A strategy for turning OpenAPI identifiers into Swift identifiers.
+public enum NamingStrategy: String, Sendable, Codable, Equatable {
+
+ /// A defensive strategy that can handle any OpenAPI identifier and produce a non-conflicting Swift identifier.
+ ///
+ /// This strategy is the default in Swift OpenAPI Generator 1.x.
+ ///
+ /// Introduced in [SOAR-0001](https://swiftpackageindex.com/apple/swift-openapi-generator/documentation/swift-openapi-generator/soar-0001).
+ case defensive
+
+ /// An idiomatic strategy that produces Swift identifiers that more likely conform to Swift conventions.
+ ///
+ /// Opt-in since Swift OpenAPI Generator 1.6.0.
+ /// | ```suggestion
``` |
swift-openapi-generator | github_2023 | others | 679 | apple | simonjbeaumont | @@ -35,6 +53,14 @@ public struct Config: Sendable {
/// Filter to apply to the OpenAPI document before generation.
public var filter: DocumentFilter?
+ /// The naming strategy to use for deriving Swift identifiers from OpenAPI identifiers.
+ ///
+ /// Defaults to `defensive`.
+ public var namingStrategy: NamingStrategy? | This layer should have a non-optional value, with a default. The optionality will be in `GenerateOptions`, used in the CLI. |
swift-openapi-generator | github_2023 | others | 679 | apple | simonjbeaumont | @@ -13,6 +13,32 @@
//===----------------------------------------------------------------------===//
import Foundation
+/// Extra context for the `safeForSwiftCode_` family of functions to produce more appropriate Swift identifiers.
+struct SwiftNameOptions {
+
+ /// An option for controlling capitalization.
+ ///
+ /// Generally, type names are capitalized, for example: `Foo`.
+ /// And member names are not capitalized, for example: `foo`.
+ enum Capitalization {
+
+ /// Capitalize the name, used for type names, for example: `Foo`.
+ case capitalized
+
+ /// Don't capitalize the name, used for member names, for example: `foo`.
+ case noncapitalized
+ } | An enum with a "this" and "not this" case sounds like it should be replaced with boolean. |
swift-openapi-generator | github_2023 | others | 679 | apple | simonjbeaumont | @@ -67,6 +93,178 @@ extension String {
return "_\(validString)"
}
+ /// Returns a string sanitized to be usable as a Swift identifier, and tries to produce UpperCamelCase
+ /// or lowerCamelCase string, the casing is controlled using the provided options.
+ ///
+ /// If the string contains any illegal characters, falls back to the behavior
+ /// matching `safeForSwiftCode_defensive`.
+ ///
+ /// Check out [SOAR-0013](https://swiftpackageindex.com/apple/swift-openapi-generator/documentation/swift-openapi-generator/soar-0013) for details.
+ func safeForSwiftCode_idiomatic(options: SwiftNameOptions) -> String {
+ let capitalize = options.capitalization == .capitalized
+ if isEmpty { return capitalize ? "_Empty_" : "_empty_" }
+ // Detect cases like HELLO_WORLD, sometimes used for constants.
+ let isAllUppercase = allSatisfy {
+ // Must check that no characters are lowercased, as non-letter characters
+ // don't return `true` to `isUppercase`.
+ !$0.isLowercase
+ }
+
+ // 1. Leave leading underscores as-are
+ // 2. In the middle: word separators: ["_", "-", "/", <space>] -> remove and capitalize next word
+ // 3. In the middle: period: ["."] -> replace with "_"
+ // 4. In the middle: drop ["{", "}"] -> replace with ""
+
+ var buffer: [Character] = []
+ buffer.reserveCapacity(count)
+ enum State: Equatable {
+ case modifying
+ case preFirstWord
+ struct AccumulatingFirstWordContext: Equatable { var isAccumulatingInitialUppercase: Bool }
+ case accumulatingFirstWord(AccumulatingFirstWordContext)
+ case accumulatingWord
+ case waitingForWordStarter
+ case fallback
+ }
+ var state: State = .preFirstWord
+ for index in self[...].indices {
+ let char = self[index]
+ let _state = state
+ state = .modifying
+ switch _state {
+ case .preFirstWord:
+ if char == "_" {
+ // Leading underscores are kept.
+ buffer.append(char)
+ state = .preFirstWord
+ } else if char.isNumber {
+ // Prefix with an underscore if the first character is a number.
+ buffer.append("_")
+ buffer.append(char)
+ state = .accumulatingFirstWord(.init(isAccumulatingInitialUppercase: false))
+ } else if char.isLetter {
+ // First character in the identifier.
+ buffer.append(contentsOf: capitalize ? char.uppercased() : char.lowercased())
+ state = .accumulatingFirstWord(
+ .init(isAccumulatingInitialUppercase: !capitalize && char.isUppercase)
+ )
+ } else {
+ // Illegal character, fall back to the defensive strategy.
+ state = .fallback
+ }
+ case .accumulatingFirstWord(var context):
+ if char.isLetter || char.isNumber {
+ if isAllUppercase {
+ buffer.append(contentsOf: char.lowercased())
+ } else if context.isAccumulatingInitialUppercase {
+ // Example: "HTTPProxy"/"HTTP_Proxy"/"HTTP_proxy"" should all
+ // become "httpProxy" when capitalize == false.
+ // This means treating the first word differently.
+ // Here we are on the second or later character of the first word (the first
+ // character is handled in `.preFirstWord`.
+ // If the first character was uppercase, and we're in lowercasing mode,
+ // we need to lowercase every consequtive uppercase character while there's
+ // another uppercase character after it.
+ if char.isLowercase {
+ // No accumulating anymore, just append it and turn off accumulation.
+ buffer.append(char)
+ context.isAccumulatingInitialUppercase = false
+ } else {
+ let suffix = suffix(from: self.index(after: index))
+ if suffix.count >= 2 {
+ let next = suffix.first!
+ let secondNext = suffix.dropFirst().first!
+ if next.isUppercase && secondNext.isLowercase {
+ // Finished lowercasing.
+ context.isAccumulatingInitialUppercase = false
+ buffer.append(contentsOf: char.lowercased())
+ } else if Self.wordSeparators.contains(next) {
+ // Finished lowercasing.
+ context.isAccumulatingInitialUppercase = false
+ buffer.append(contentsOf: char.lowercased())
+ } else if next.isUppercase {
+ // Keep lowercasing.
+ buffer.append(contentsOf: char.lowercased())
+ } else {
+ // Append as-is, stop accumulating.
+ context.isAccumulatingInitialUppercase = false
+ buffer.append(char)
+ }
+ } else {
+ // This is the last or second to last character,
+ // since we were accumulating capitals, lowercase it.
+ buffer.append(contentsOf: char.lowercased())
+ context.isAccumulatingInitialUppercase = false
+ } | Note to self, check tests for this.
We're three conditionals (four including the switch), wondering if we can flatten this out with a more expressive switch statement with multiple terms or some `case ... where` statements. |
swift-openapi-generator | github_2023 | others | 679 | apple | simonjbeaumont | @@ -67,6 +93,178 @@ extension String {
return "_\(validString)"
}
+ /// Returns a string sanitized to be usable as a Swift identifier, and tries to produce UpperCamelCase
+ /// or lowerCamelCase string, the casing is controlled using the provided options.
+ ///
+ /// If the string contains any illegal characters, falls back to the behavior
+ /// matching `safeForSwiftCode_defensive`.
+ ///
+ /// Check out [SOAR-0013](https://swiftpackageindex.com/apple/swift-openapi-generator/documentation/swift-openapi-generator/soar-0013) for details.
+ func safeForSwiftCode_idiomatic(options: SwiftNameOptions) -> String {
+ let capitalize = options.capitalization == .capitalized
+ if isEmpty { return capitalize ? "_Empty_" : "_empty_" }
+ // Detect cases like HELLO_WORLD, sometimes used for constants.
+ let isAllUppercase = allSatisfy {
+ // Must check that no characters are lowercased, as non-letter characters
+ // don't return `true` to `isUppercase`.
+ !$0.isLowercase
+ }
+
+ // 1. Leave leading underscores as-are
+ // 2. In the middle: word separators: ["_", "-", "/", <space>] -> remove and capitalize next word
+ // 3. In the middle: period: ["."] -> replace with "_"
+ // 4. In the middle: drop ["{", "}"] -> replace with ""
+
+ var buffer: [Character] = []
+ buffer.reserveCapacity(count)
+ enum State: Equatable {
+ case modifying
+ case preFirstWord
+ struct AccumulatingFirstWordContext: Equatable { var isAccumulatingInitialUppercase: Bool }
+ case accumulatingFirstWord(AccumulatingFirstWordContext)
+ case accumulatingWord
+ case waitingForWordStarter
+ case fallback
+ }
+ var state: State = .preFirstWord
+ for index in self[...].indices {
+ let char = self[index]
+ let _state = state
+ state = .modifying
+ switch _state {
+ case .preFirstWord:
+ if char == "_" {
+ // Leading underscores are kept.
+ buffer.append(char)
+ state = .preFirstWord
+ } else if char.isNumber {
+ // Prefix with an underscore if the first character is a number.
+ buffer.append("_")
+ buffer.append(char)
+ state = .accumulatingFirstWord(.init(isAccumulatingInitialUppercase: false))
+ } else if char.isLetter {
+ // First character in the identifier.
+ buffer.append(contentsOf: capitalize ? char.uppercased() : char.lowercased())
+ state = .accumulatingFirstWord(
+ .init(isAccumulatingInitialUppercase: !capitalize && char.isUppercase)
+ )
+ } else {
+ // Illegal character, fall back to the defensive strategy.
+ state = .fallback
+ }
+ case .accumulatingFirstWord(var context):
+ if char.isLetter || char.isNumber {
+ if isAllUppercase {
+ buffer.append(contentsOf: char.lowercased())
+ } else if context.isAccumulatingInitialUppercase {
+ // Example: "HTTPProxy"/"HTTP_Proxy"/"HTTP_proxy"" should all
+ // become "httpProxy" when capitalize == false.
+ // This means treating the first word differently.
+ // Here we are on the second or later character of the first word (the first
+ // character is handled in `.preFirstWord`.
+ // If the first character was uppercase, and we're in lowercasing mode,
+ // we need to lowercase every consequtive uppercase character while there's
+ // another uppercase character after it.
+ if char.isLowercase {
+ // No accumulating anymore, just append it and turn off accumulation.
+ buffer.append(char)
+ context.isAccumulatingInitialUppercase = false
+ } else {
+ let suffix = suffix(from: self.index(after: index))
+ if suffix.count >= 2 {
+ let next = suffix.first!
+ let secondNext = suffix.dropFirst().first!
+ if next.isUppercase && secondNext.isLowercase {
+ // Finished lowercasing.
+ context.isAccumulatingInitialUppercase = false
+ buffer.append(contentsOf: char.lowercased())
+ } else if Self.wordSeparators.contains(next) {
+ // Finished lowercasing.
+ context.isAccumulatingInitialUppercase = false
+ buffer.append(contentsOf: char.lowercased())
+ } else if next.isUppercase {
+ // Keep lowercasing.
+ buffer.append(contentsOf: char.lowercased())
+ } else {
+ // Append as-is, stop accumulating.
+ context.isAccumulatingInitialUppercase = false
+ buffer.append(char)
+ }
+ } else {
+ // This is the last or second to last character,
+ // since we were accumulating capitals, lowercase it.
+ buffer.append(contentsOf: char.lowercased())
+ context.isAccumulatingInitialUppercase = false
+ }
+ }
+ } else {
+ buffer.append(char)
+ }
+ state = .accumulatingFirstWord(context)
+ } else if ["_", "-", " ", "/"].contains(char) {
+ // In the middle of an identifier, these are considered
+ // word separators, so we remove the character and end the current word.
+ state = .waitingForWordStarter
+ } else if ["."].contains(char) {
+ // In the middle of an identifier, these get replaced with
+ // an underscore, but continue the current word.
+ buffer.append("_")
+ state = .accumulatingFirstWord(.init(isAccumulatingInitialUppercase: false))
+ } else if ["{", "}"].contains(char) {
+ // In the middle of an identifier, curly braces are dropped.
+ state = .accumulatingFirstWord(.init(isAccumulatingInitialUppercase: false))
+ } else {
+ // Illegal character, fall back to the defensive strategy.
+ state = .fallback
+ }
+ case .accumulatingWord:
+ if char.isLetter || char.isNumber {
+ if isAllUppercase { buffer.append(contentsOf: char.lowercased()) } else { buffer.append(char) }
+ state = .accumulatingWord
+ } else if Self.wordSeparators.contains(char) {
+ // In the middle of an identifier, these are considered
+ // word separators, so we remove the character and end the current word.
+ state = .waitingForWordStarter
+ } else if ["."].contains(char) {
+ // In the middle of an identifier, these get replaced with
+ // an underscore, but continue the current word.
+ buffer.append("_")
+ state = .accumulatingWord
+ } else if ["{", "}"].contains(char) {
+ // In the middle of an identifier, curly braces are dropped.
+ state = .accumulatingWord
+ } else {
+ // Illegal character, fall back to the defensive strategy.
+ state = .fallback
+ }
+ case .waitingForWordStarter:
+ if ["_", "-", ".", "/", "{", "}"].contains(char) {
+ // Between words, just drop allowed special characters, since
+ // we're already between words anyway.
+ state = .waitingForWordStarter | Note to self: any uses of `.` in this position that would be a problem? |
swift-openapi-generator | github_2023 | others | 679 | apple | simonjbeaumont | @@ -67,6 +93,178 @@ extension String {
return "_\(validString)"
}
+ /// Returns a string sanitized to be usable as a Swift identifier, and tries to produce UpperCamelCase
+ /// or lowerCamelCase string, the casing is controlled using the provided options.
+ ///
+ /// If the string contains any illegal characters, falls back to the behavior
+ /// matching `safeForSwiftCode_defensive`.
+ ///
+ /// Check out [SOAR-0013](https://swiftpackageindex.com/apple/swift-openapi-generator/documentation/swift-openapi-generator/soar-0013) for details.
+ func safeForSwiftCode_idiomatic(options: SwiftNameOptions) -> String {
+ let capitalize = options.capitalization == .capitalized
+ if isEmpty { return capitalize ? "_Empty_" : "_empty_" }
+ // Detect cases like HELLO_WORLD, sometimes used for constants.
+ let isAllUppercase = allSatisfy {
+ // Must check that no characters are lowercased, as non-letter characters
+ // don't return `true` to `isUppercase`.
+ !$0.isLowercase
+ }
+
+ // 1. Leave leading underscores as-are
+ // 2. In the middle: word separators: ["_", "-", "/", <space>] -> remove and capitalize next word
+ // 3. In the middle: period: ["."] -> replace with "_"
+ // 4. In the middle: drop ["{", "}"] -> replace with ""
+
+ var buffer: [Character] = []
+ buffer.reserveCapacity(count)
+ enum State: Equatable {
+ case modifying
+ case preFirstWord
+ struct AccumulatingFirstWordContext: Equatable { var isAccumulatingInitialUppercase: Bool }
+ case accumulatingFirstWord(AccumulatingFirstWordContext)
+ case accumulatingWord
+ case waitingForWordStarter
+ case fallback
+ }
+ var state: State = .preFirstWord
+ for index in self[...].indices {
+ let char = self[index]
+ let _state = state
+ state = .modifying
+ switch _state {
+ case .preFirstWord:
+ if char == "_" {
+ // Leading underscores are kept.
+ buffer.append(char)
+ state = .preFirstWord
+ } else if char.isNumber {
+ // Prefix with an underscore if the first character is a number.
+ buffer.append("_")
+ buffer.append(char)
+ state = .accumulatingFirstWord(.init(isAccumulatingInitialUppercase: false))
+ } else if char.isLetter {
+ // First character in the identifier.
+ buffer.append(contentsOf: capitalize ? char.uppercased() : char.lowercased())
+ state = .accumulatingFirstWord(
+ .init(isAccumulatingInitialUppercase: !capitalize && char.isUppercase)
+ )
+ } else {
+ // Illegal character, fall back to the defensive strategy.
+ state = .fallback
+ }
+ case .accumulatingFirstWord(var context):
+ if char.isLetter || char.isNumber {
+ if isAllUppercase {
+ buffer.append(contentsOf: char.lowercased())
+ } else if context.isAccumulatingInitialUppercase {
+ // Example: "HTTPProxy"/"HTTP_Proxy"/"HTTP_proxy"" should all
+ // become "httpProxy" when capitalize == false.
+ // This means treating the first word differently.
+ // Here we are on the second or later character of the first word (the first
+ // character is handled in `.preFirstWord`.
+ // If the first character was uppercase, and we're in lowercasing mode,
+ // we need to lowercase every consequtive uppercase character while there's
+ // another uppercase character after it.
+ if char.isLowercase {
+ // No accumulating anymore, just append it and turn off accumulation.
+ buffer.append(char)
+ context.isAccumulatingInitialUppercase = false
+ } else {
+ let suffix = suffix(from: self.index(after: index))
+ if suffix.count >= 2 {
+ let next = suffix.first!
+ let secondNext = suffix.dropFirst().first!
+ if next.isUppercase && secondNext.isLowercase {
+ // Finished lowercasing.
+ context.isAccumulatingInitialUppercase = false
+ buffer.append(contentsOf: char.lowercased())
+ } else if Self.wordSeparators.contains(next) {
+ // Finished lowercasing.
+ context.isAccumulatingInitialUppercase = false
+ buffer.append(contentsOf: char.lowercased())
+ } else if next.isUppercase {
+ // Keep lowercasing.
+ buffer.append(contentsOf: char.lowercased())
+ } else {
+ // Append as-is, stop accumulating.
+ context.isAccumulatingInitialUppercase = false
+ buffer.append(char)
+ }
+ } else {
+ // This is the last or second to last character,
+ // since we were accumulating capitals, lowercase it.
+ buffer.append(contentsOf: char.lowercased())
+ context.isAccumulatingInitialUppercase = false
+ }
+ }
+ } else {
+ buffer.append(char)
+ }
+ state = .accumulatingFirstWord(context)
+ } else if ["_", "-", " ", "/"].contains(char) {
+ // In the middle of an identifier, these are considered
+ // word separators, so we remove the character and end the current word.
+ state = .waitingForWordStarter
+ } else if ["."].contains(char) {
+ // In the middle of an identifier, these get replaced with
+ // an underscore, but continue the current word.
+ buffer.append("_")
+ state = .accumulatingFirstWord(.init(isAccumulatingInitialUppercase: false))
+ } else if ["{", "}"].contains(char) {
+ // In the middle of an identifier, curly braces are dropped.
+ state = .accumulatingFirstWord(.init(isAccumulatingInitialUppercase: false))
+ } else {
+ // Illegal character, fall back to the defensive strategy.
+ state = .fallback
+ }
+ case .accumulatingWord:
+ if char.isLetter || char.isNumber {
+ if isAllUppercase { buffer.append(contentsOf: char.lowercased()) } else { buffer.append(char) }
+ state = .accumulatingWord
+ } else if Self.wordSeparators.contains(char) {
+ // In the middle of an identifier, these are considered
+ // word separators, so we remove the character and end the current word.
+ state = .waitingForWordStarter
+ } else if ["."].contains(char) {
+ // In the middle of an identifier, these get replaced with
+ // an underscore, but continue the current word.
+ buffer.append("_")
+ state = .accumulatingWord
+ } else if ["{", "}"].contains(char) {
+ // In the middle of an identifier, curly braces are dropped.
+ state = .accumulatingWord
+ } else {
+ // Illegal character, fall back to the defensive strategy.
+ state = .fallback
+ }
+ case .waitingForWordStarter:
+ if ["_", "-", ".", "/", "{", "}"].contains(char) {
+ // Between words, just drop allowed special characters, since
+ // we're already between words anyway.
+ state = .waitingForWordStarter
+ } else if char.isLetter || char.isNumber {
+ // Starting a new word in the middle of the identifier.
+ buffer.append(contentsOf: char.uppercased())
+ state = .accumulatingWord
+ } else {
+ // Illegal character, fall back to the defensive strategy.
+ state = .fallback
+ }
+ case .modifying, .fallback: preconditionFailure("Logic error in \(#function), string: '\(self)'")
+ }
+ precondition(state != .modifying, "Logic error in \(#function), string: '\(self)'")
+ if case .fallback = state { return safeForSwiftCode_defensive(options: options) }
+ }
+ if buffer.isEmpty || state == .preFirstWord { return safeForSwiftCode_defensive(options: options) }
+ // Check for keywords
+ let newString = String(buffer)
+ if Self.keywords.contains(newString) { return "_\(newString)" }
+ return newString | I thought we said we'd always flush the result of the idiomatic strategy through the defensive strategy too. That way it's a two phase process: try to make it pretty, then make it safe. If the first phase made it pretty in a way that was safe, then the second results in the same, but we have a lot of confidence in the defensive strategy and it avoids duplicating the logic here. |
swift-openapi-generator | github_2023 | others | 679 | apple | simonjbeaumont | @@ -35,6 +53,14 @@ public struct Config: Sendable {
/// Filter to apply to the OpenAPI document before generation.
public var filter: DocumentFilter?
+ /// The naming strategy to use for deriving Swift identifiers from OpenAPI identifiers.
+ ///
+ /// Defaults to `defensive`.
+ public var namingStrategy: NamingStrategy?
+
+ /// A map of OpenAPI identifiers to desired Swift identifiers, used instead of the naming strategy.
+ public var nameOverrides: [String: String]? | I think we should have resolved this to an actual, possibly empty, dictionary by this point, which will mean we're not doing so for every call to `asSwiftSafeName`. |
swift-openapi-generator | github_2023 | others | 679 | apple | simonjbeaumont | @@ -47,7 +47,18 @@ protocol FileTranslator {
extension FileTranslator {
/// A new context from the file translator.
- var context: TranslatorContext { TranslatorContext(asSwiftSafeName: { $0.safeForSwiftCode }) }
+ var context: TranslatorContext {
+ let asSwiftSafeName: (String, SwiftNameOptions) -> String
+ switch config.namingStrategy {
+ case .defensive, .none: asSwiftSafeName = { $0.safeForSwiftCode_defensive(options: $1) }
+ case .idiomatic: asSwiftSafeName = { $0.safeForSwiftCode_idiomatic(options: $1) }
+ }
+ let overrides = config.nameOverrides ?? [:] | If this were resolved in the config (see comment in Config.swift), then we won't have to do this on every call. |
swift-openapi-generator | github_2023 | others | 679 | apple | simonjbeaumont | @@ -495,7 +495,8 @@ struct TypeAssigner {
{
typeNameForComponents()
.appending(
- swiftComponent: context.asSwiftSafeName(componentType.openAPIComponentsKey).uppercasingFirstLetter,
+ swiftComponent: context.asSwiftSafeName(componentType.openAPIComponentsKey, .capitalized)
+ .uppercasingFirstLetter, | Why do we need `.uppercasingFirstLetter` still? Is this for when we're still using `defensive`?
And, is this what's returning `Components`? If so, should it be simplified to just do that? |
swift-openapi-generator | github_2023 | others | 679 | apple | simonjbeaumont | @@ -528,14 +529,15 @@ struct TypeAssigner {
case "application/pdf": return "pdf"
case "image/jpeg": return "jpeg"
default:
- let safedType = context.asSwiftSafeName(contentType.originallyCasedType)
- let safedSubtype = context.asSwiftSafeName(contentType.originallyCasedSubtype)
+ let safedType = context.asSwiftSafeName(contentType.originallyCasedType, .noncapitalized)
+ let safedSubtype = context.asSwiftSafeName(contentType.originallyCasedSubtype, .noncapitalized)
let prefix = "\(safedType)_\(safedSubtype)"
let params = contentType.lowercasedParameterPairs
guard !params.isEmpty else { return prefix }
let safedParams =
params.map { pair in
- pair.split(separator: "=").map { context.asSwiftSafeName(String($0)) }.joined(separator: "_")
+ pair.split(separator: "=").map { context.asSwiftSafeName(String($0), .noncapitalized) }
+ .joined(separator: "_")
}
.joined(separator: "_")
return prefix + "_" + safedParams | This looks like it's still returning `type_subtype`. Should it be `typeSubtype`? |
swift-openapi-generator | github_2023 | others | 679 | apple | simonjbeaumont | @@ -35,11 +35,15 @@ The configuration file has the following keys:
- `package`: Generated API is accessible from other modules within the same package or project.
- `internal` (default): Generated API is accessible from the containing module only.
- `additionalImports` (optional): array of strings. Each string value is a Swift module name. An import statement will be added to the generated source files for each module.
-- `filter`: (optional): Filters to apply to the OpenAPI document before generation.
+- `filter` (optional): Filters to apply to the OpenAPI document before generation.
- `operations`: Operations with these operation IDs will be included in the filter.
- `tags`: Operations tagged with these tags will be included in the filter.
- `paths`: Operations for these paths will be included in the filter.
- `schemas`: These (additional) schemas will be included in the filter.
+- `namingStrategy` (optional): a string. Customizes the strategy of converting OpenAPI identifiers into Swift identifiers. | ```suggestion
- `namingStrategy` (optional): a string. The strategy of converting OpenAPI identifiers into Swift identifiers.
```
The "customization" happens with `nameOverrides`. |
swift-openapi-generator | github_2023 | others | 679 | apple | simonjbeaumont | @@ -35,11 +35,15 @@ The configuration file has the following keys:
- `package`: Generated API is accessible from other modules within the same package or project.
- `internal` (default): Generated API is accessible from the containing module only.
- `additionalImports` (optional): array of strings. Each string value is a Swift module name. An import statement will be added to the generated source files for each module.
-- `filter`: (optional): Filters to apply to the OpenAPI document before generation.
+- `filter` (optional): Filters to apply to the OpenAPI document before generation.
- `operations`: Operations with these operation IDs will be included in the filter.
- `tags`: Operations tagged with these tags will be included in the filter.
- `paths`: Operations for these paths will be included in the filter.
- `schemas`: These (additional) schemas will be included in the filter.
+- `namingStrategy` (optional): a string. Customizes the strategy of converting OpenAPI identifiers into Swift identifiers.
+ - `defensive` (default): Produces non-conflicting Swift identifiers for any OpenAPI identifiers. Check out [SOAR-0001](https://swiftpackageindex.com/apple/swift-openapi-generator/documentation/swift-openapi-generator/soar-0001) for details.
+ - `idiomatic`: Produces more idiomatic Swift identifiers for OpenAPI identifiers, might produce name conflicts (in that case, switch back to `defensive`.) Check out [SOAR-0013](https://swiftpackageindex.com/apple/swift-openapi-generator/documentation/swift-openapi-generator/soar-0013) for details. | ```suggestion
- `idiomatic`: Produces more idiomatic Swift identifiers for OpenAPI identifiers. Might produce name conflicts (in that case, switch back to `defensive`). Check out [SOAR-0013](https://swiftpackageindex.com/apple/swift-openapi-generator/documentation/swift-openapi-generator/soar-0013) for details.
``` |
swift-openapi-generator | github_2023 | others | 679 | apple | simonjbeaumont | @@ -1,4 +1,4 @@
-// swift-tools-version: 5.9
+// swift-tools-version: 6.0 | Is this deliberate? It means that only folks on the latest Swift compiler can walk through the tutorial. Seems an unrelated, additional restriction. |
swift-openapi-generator | github_2023 | others | 679 | apple | simonjbeaumont | @@ -1,3 +1,4 @@
generate:
- types
- client
+namingStrategy: idiomatic | While I'm open to us having a specific example showing the idiomatic naming, I'm a little wary of us having non-defaults in our main tutorial. |
swift-openapi-generator | github_2023 | others | 679 | apple | simonjbeaumont | @@ -81,13 +81,15 @@ private func timing<Output>(_ title: String, _ operation: @autoclosure () throws
}
private let sampleConfig = _UserConfig(
- generate: [],
+ generate: [.types, .client],
filter: DocumentFilter(
operations: ["getGreeting"],
tags: ["greetings"],
paths: ["/greeting"],
schemas: ["Greeting"]
- )
+ ),
+ namingStrategy: .idiomatic,
+ nameOverrides: ["SPECIAL_NAME": "SpecialName"] | Why is this in the example config for the `filter` command? |
swift-openapi-generator | github_2023 | others | 679 | apple | simonjbeaumont | @@ -83,6 +75,8 @@ extension _GenerateOptions {
return []
}
+ func resolvedNamingStrategy(_ config: _UserConfig?) -> NamingStrategy { config?.namingStrategy ?? .defensive }
+ func resolvedNameOverrides(_ config: _UserConfig?) -> [String: String] { config?.nameOverrides ?? [:] } | This is great. I think these should be passed in where we turn the config into a proper `Config`. |
swift-openapi-generator | github_2023 | others | 679 | apple | simonjbeaumont | @@ -0,0 +1,148 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+import XCTest
+@testable import _OpenAPIGeneratorCore
+
+final class Test_SwiftSafeNames: Test_Core {
+ func testAsSwiftSafeName() {
+ let cases: [(original: String, defensive: String, idiomaticUpper: String, idiomaticLower: String)] = [
+
+ // Simple
+ ("foo", "foo", "Foo", "foo"),
+
+ // Space
+ ("Hello world", "Hello_space_world", "HelloWorld", "helloWorld"),
+
+ // Mixed capitalization
+ ("My_URL_value", "My_URL_value", "MyURLValue", "myURLValue"),
+
+ // Dashes
+ ("hello-world", "hello_hyphen_world", "HelloWorld", "helloWorld"),
+
+ // Header names
+ ("Retry-After", "Retry_hyphen_After", "RetryAfter", "retryAfter"),
+
+ // All uppercase
+ ("HELLO_WORLD", "HELLO_WORLD", "HelloWorld", "helloWorld"), | Please add a case for all uppercase, without any word separator. |
swift-openapi-generator | github_2023 | others | 679 | apple | simonjbeaumont | @@ -0,0 +1,148 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+import XCTest
+@testable import _OpenAPIGeneratorCore
+
+final class Test_SwiftSafeNames: Test_Core {
+ func testAsSwiftSafeName() {
+ let cases: [(original: String, defensive: String, idiomaticUpper: String, idiomaticLower: String)] = [
+
+ // Simple
+ ("foo", "foo", "Foo", "foo"),
+
+ // Space
+ ("Hello world", "Hello_space_world", "HelloWorld", "helloWorld"),
+
+ // Mixed capitalization
+ ("My_URL_value", "My_URL_value", "MyURLValue", "myURLValue"),
+
+ // Dashes
+ ("hello-world", "hello_hyphen_world", "HelloWorld", "helloWorld"),
+
+ // Header names
+ ("Retry-After", "Retry_hyphen_After", "RetryAfter", "retryAfter"),
+
+ // All uppercase
+ ("HELLO_WORLD", "HELLO_WORLD", "HelloWorld", "helloWorld"),
+
+ // Acronyms
+ ("HTTPProxy", "HTTPProxy", "HTTPProxy", "httpProxy"),
+ ("HTTP_Proxy", "HTTP_Proxy", "HTTPProxy", "httpProxy"),
+ ("HTTP_proxy", "HTTP_proxy", "HTTPProxy", "httpProxy"),
+ ("OneHTTPProxy", "OneHTTPProxy", "OneHTTPProxy", "oneHTTPProxy"), ("iOS", "iOS", "IOS", "iOS"),
+ // Numbers
+ ("version 2.0", "version_space_2_period_0", "Version2_0", "version2_0"),
+ ("V1.2Release", "V1_period_2Release", "V1_2Release", "v1_2Release"),
+
+ // Synthesized operationId from method + path
+ (
+ "get/pets/{petId}/notifications", "get_sol_pets_sol__lcub_petId_rcub__sol_notifications",
+ "GetPetsPetIdNotifications", "getPetsPetIdNotifications"
+ ),
+ (
+ "get/name/v{version}.zip", "get_sol_name_sol_v_lcub_version_rcub__period_zip", "GetNameVversion_zip",
+ "getNameVversion_zip"
+ ),
+
+ // Technical strings
+ ("file/path/to/resource", "file_sol_path_sol_to_sol_resource", "FilePathToResource", "filePathToResource"),
+ (
+ "user.name@domain.com", "user_period_name_commat_domain_period_com",
+ "user_period_name_commat_domain_period_com", "user_period_name_commat_domain_period_com"
+ ), ("hello.world.2023", "hello_period_world_period_2023", "Hello_world_2023", "hello_world_2023"),
+ ("order#123", "order_num_123", "order_num_123", "order_num_123"),
+ ("pressKeys#123", "pressKeys_num_123", "pressKeys_num_123", "pressKeys_num_123"),
+
+ // Non-English characters
+ ("naïve café", "naïve_space_café", "NaïveCafé", "naïveCafé"),
+
+ // Starts with a number
+ ("3foo", "_3foo", "_3foo", "_3foo"),
+
+ // Keyword
+ ("default", "_default", "Default", "_default"),
+
+ // Reserved name
+ ("Type", "_Type", "_Type", "_type"),
+
+ // Empty string
+ ("", "_empty", "_Empty_", "_empty_"),
+
+ // Special Char in middle
+ ("inv@lidName", "inv_commat_lidName", "inv_commat_lidName", "inv_commat_lidName"),
+
+ // Special Char in first position
+ ("!nvalidName", "_excl_nvalidName", "_excl_nvalidName", "_excl_nvalidName"),
+
+ // Special Char in last position
+ ("invalidNam?", "invalidNam_quest_", "invalidNam_quest_", "invalidNam_quest_"),
+
+ // Preserve leading underscores
+ ("__user", "__user", "__User", "__user"),
+
+ // Preserve only leading underscores
+ ("user__name", "user__name", "UserName", "userName"), | To show it's preserving _only_ leading underscores, this test should have both leading and non-leading underscores. |
swift-openapi-generator | github_2023 | others | 679 | apple | simonjbeaumont | @@ -531,19 +531,33 @@ struct TypeAssigner {
default:
let safedType = context.asSwiftSafeName(contentType.originallyCasedType, .noncapitalized)
let safedSubtype = context.asSwiftSafeName(contentType.originallyCasedSubtype, .noncapitalized)
- let prefix = "\(safedType)_\(safedSubtype)"
+ let componentSeparator: String
+ let capitalizeNonFirstWords: Bool
+ switch context.namingStrategy {
+ case .defensive:
+ componentSeparator = "_"
+ capitalizeNonFirstWords = false
+ case .idiomatic:
+ componentSeparator = ""
+ capitalizeNonFirstWords = true
+ }
+ let prettifiedSubtype = capitalizeNonFirstWords ? safedSubtype.uppercasingFirstLetter : safedSubtype
+ let prefix = "\(safedType)\(componentSeparator)\(prettifiedSubtype)" | Seeing this here is giving me pause for concern. We're having one object, the `TypeAssigner` that holds a context containing a _strategy_ (essentially a config option), and then it's either branching in the function (like this one) or it's calling a closure with different arguments (in others).
The `TypeAssigner` seems to have a couple of functions right now: (1) the matching, which involves actually working out the usage of the identifier and its relation to other documented types; and (2) the naming.
I think it might be worth abstracting away (2) behind something that can be passed in to the assigner:
```swift
protocol TypeNamer { // ironically needs a better name
static func swiftName(for documentedName: String, usage: NameUsage) -> String
}
// Or have many witnesses, one per usage, if preferred.
enum NameUsage {
case property
case type
case contentType
// ...
}
enum IdiomaticNamer: Namer { /* ... */ }
enum DefensiveNamer: Namer { /* ... */ }
```
This would make it cleaner to test too, since we can test this in isolation of any other logic.
WDYT? |
swift-openapi-generator | github_2023 | others | 679 | apple | simonjbeaumont | @@ -44,35 +44,50 @@ protocol FileTranslator {
func translateFile(parsedOpenAPI: ParsedOpenAPIRepresentation) throws -> StructuredSwiftRepresentation
}
+/// A generator that allows overriding the documented name.
+struct OverridableSafeNameGenerator: SafeNameGenerator { | This is a really nice win. I hadn't yet thought of layering it this way but it composes nicely :) |
swift-openapi-generator | github_2023 | others | 697 | apple | czechboy0 | @@ -37,7 +37,7 @@ enum PluginError: Swift.Error, CustomStringConvertible, LocalizedError {
let targetNames = targetNames.joined(separator: ", ", lastSeparator: " and ")
return "Found no targets with names \(targetNames)."
case .fileErrors(let fileErrors):
- return "Issues with required files: \(fileErrors.map(\.description).joined(separator: ", and"))."
+ return "Issues with required files:\n\(fileErrors.map { $0 .description.prepended("- ") }.joined(separator: "\n"))." | ```suggestion
return "Issues with required files:\n\(fileErrors.map { "- " + $0.description }.joined(separator: "\n"))."
``` |
swift-openapi-generator | github_2023 | others | 697 | apple | czechboy0 | @@ -37,7 +37,7 @@ enum PluginError: Swift.Error, CustomStringConvertible, LocalizedError {
let targetNames = targetNames.joined(separator: ", ", lastSeparator: " and ")
return "Found no targets with names \(targetNames)."
case .fileErrors(let fileErrors):
- return "Issues with required files: \(fileErrors.map(\.description).joined(separator: ", and"))."
+ return "Issues with required files:\n\(fileErrors.map { "- " + $0 .description }.joined(separator: "\n"))." | ```suggestion
return "Issues with required files:\n\(fileErrors.map { "- " + $0.description }.joined(separator: "\n"))."
```
Nit: extra space after `$0` |
swift-openapi-generator | github_2023 | others | 642 | apple | czechboy0 | @@ -107,6 +107,9 @@ The generated code, runtime library, and transports are supported on more platfo
| Generator plugin and CLI | ✅ 10.15+ | ✅ | ✖️ | ✖️ | ✖️ | ✖️ |
| Generated code and runtime library | ✅ 10.15+ | ✅ | ✅ 13+ | ✅ 13+ | ✅ 6+ | ✅ 1+ |
+> [!NOTE]
+> When using Visual Studio Code or other editors that rely on [SourceKit-LSP](https://github.com/swiftlang/sourcekit-lsp), the editor may not correctly recognize generated code within the same module. As a workaround, consider creating a separate target for code generation and then importing it into your main module. For more details, see the discussion in [swiftlang/sourcekit-lsp#665](https://github.com/swiftlang/sourcekit-lsp/issues/665#issuecomment-2093169169). | The syntax in docc for notes is `> Note: ...` |
swift-openapi-generator | github_2023 | others | 626 | apple | czechboy0 | @@ -0,0 +1,151 @@
+# SOAR-0011: Improved Error Handling
+
+Improve error handling by adding the ability for mapping application errors to HTTP responses.
+
+## Overview
+
+- Proposal: SOAR-0011
+- Author(s): [Gayathri Sairamkrishnan](https://github.com/gayathrisairam)
+- Status: **Awaiting Review**
+- Issue: [apple/swift-openapi-generator#609](https://github.com/apple/swift-openapi-generator/issues/609)
+- Affected components:
+ - runtime
+
+### Introduction
+
+The goal of this proposal to improve the current error handling mechanism in Swift OpenAPI runtime. The proposal
+introduces a way for users to map errors thrown by their handlers to specific HTTP responses.
+
+### Motivation
+
+ When implementing a server with Swift OpenAPI Generator, users implement a type that conforms to a generated protocol, providing one method for each API operation defined in the OpenAPI document. At runtime, if this function throws, the runtime library transforms this into a 500 HTTP response (Internal Error). | ```suggestion
When implementing a server with Swift OpenAPI Generator, users implement a type that conforms to a generated protocol, providing one method for each API operation defined in the OpenAPI document. At runtime, if this function throws, it's up to the server transport to transform it into an HTTP response status code – for example, some transport use `500 Internal Error`.
``` |
swift-openapi-generator | github_2023 | others | 626 | apple | czechboy0 | @@ -0,0 +1,151 @@
+# SOAR-0011: Improved Error Handling
+
+Improve error handling by adding the ability for mapping application errors to HTTP responses.
+
+## Overview
+
+- Proposal: SOAR-0011
+- Author(s): [Gayathri Sairamkrishnan](https://github.com/gayathrisairam)
+- Status: **Awaiting Review**
+- Issue: [apple/swift-openapi-generator#609](https://github.com/apple/swift-openapi-generator/issues/609)
+- Affected components:
+ - runtime
+
+### Introduction
+
+The goal of this proposal to improve the current error handling mechanism in Swift OpenAPI runtime. The proposal
+introduces a way for users to map errors thrown by their handlers to specific HTTP responses.
+
+### Motivation
+
+ When implementing a server with Swift OpenAPI Generator, users implement a type that conforms to a generated protocol, providing one method for each API operation defined in the OpenAPI document. At runtime, if this function throws, the runtime library transforms this into a 500 HTTP response (Internal Error).
+
+Instead, server developers may want to map errors thrown by the application to a more specific HTTP response.
+Currently, this can be achieved by checking for each error type in each handler's catch block, converting it to an
+appropriate HTTP response and returning it.
+
+For example,
+```swift
+func getGreeting(_ input: Operations.getGreeting.Input) async throws -> Operations.getGreeting.Output {
+ do {
+ let response = try callGreetingLib()
+ return .ok(.init(body: response))
+ } catch let error {
+ switch error {
+ case GreetingError.authorizationError:
+ return (HTTPResponse(status: 404), nil) | This needs to be a case from the `Operations.getGreeting.Output`, so e.g. `.notFound(.init())` here? Or since this is `GreetingError.authorizationError`, maybe using `.unauthorized(.init())` is more illustrative? |
swift-openapi-generator | github_2023 | others | 626 | apple | czechboy0 | @@ -0,0 +1,151 @@
+# SOAR-0011: Improved Error Handling
+
+Improve error handling by adding the ability for mapping application errors to HTTP responses.
+
+## Overview
+
+- Proposal: SOAR-0011
+- Author(s): [Gayathri Sairamkrishnan](https://github.com/gayathrisairam)
+- Status: **Awaiting Review**
+- Issue: [apple/swift-openapi-generator#609](https://github.com/apple/swift-openapi-generator/issues/609)
+- Affected components:
+ - runtime
+
+### Introduction
+
+The goal of this proposal to improve the current error handling mechanism in Swift OpenAPI runtime. The proposal
+introduces a way for users to map errors thrown by their handlers to specific HTTP responses.
+
+### Motivation
+
+ When implementing a server with Swift OpenAPI Generator, users implement a type that conforms to a generated protocol, providing one method for each API operation defined in the OpenAPI document. At runtime, if this function throws, the runtime library transforms this into a 500 HTTP response (Internal Error).
+
+Instead, server developers may want to map errors thrown by the application to a more specific HTTP response.
+Currently, this can be achieved by checking for each error type in each handler's catch block, converting it to an
+appropriate HTTP response and returning it.
+
+For example,
+```swift
+func getGreeting(_ input: Operations.getGreeting.Input) async throws -> Operations.getGreeting.Output {
+ do {
+ let response = try callGreetingLib()
+ return .ok(.init(body: response))
+ } catch let error {
+ switch error {
+ case GreetingError.authorizationError:
+ return (HTTPResponse(status: 404), nil)
+ case GreetingError.timeout:
+ return ...
+ }
+ }
+}
+```
+If a user wishes to map many errors, the error handling block scales linearly and introduces a lot of ceremony.
+
+### Proposed solution
+
+The proposed solution is twofold.
+
+1. Provide protocol(s) in `OpenAPIRuntime` to allow users to extend their error types with mappings to HTTP responses.
+
+2. Provide an (opt-in) middleware in OpenAPIRuntime that will call the conversion function on conforming error types when
+constructing the HTTP response.
+
+Vapor has a similar mechanism called [AbortError](https://docs.vapor.codes/basics/errors/).
+
+HummingBird also has an [error handling mechanism](https://docs.hummingbird.codes/2.0/documentation/hummingbird/errorhandling/) | ```suggestion
Hummingbird also has an [error handling mechanism](https://docs.hummingbird.codes/2.0/documentation/hummingbird/errorhandling/)
``` |
swift-openapi-generator | github_2023 | others | 626 | apple | czechboy0 | @@ -0,0 +1,151 @@
+# SOAR-0011: Improved Error Handling
+
+Improve error handling by adding the ability for mapping application errors to HTTP responses.
+
+## Overview
+
+- Proposal: SOAR-0011
+- Author(s): [Gayathri Sairamkrishnan](https://github.com/gayathrisairam)
+- Status: **Awaiting Review**
+- Issue: [apple/swift-openapi-generator#609](https://github.com/apple/swift-openapi-generator/issues/609)
+- Affected components:
+ - runtime
+
+### Introduction
+
+The goal of this proposal to improve the current error handling mechanism in Swift OpenAPI runtime. The proposal
+introduces a way for users to map errors thrown by their handlers to specific HTTP responses.
+
+### Motivation
+
+ When implementing a server with Swift OpenAPI Generator, users implement a type that conforms to a generated protocol, providing one method for each API operation defined in the OpenAPI document. At runtime, if this function throws, the runtime library transforms this into a 500 HTTP response (Internal Error).
+
+Instead, server developers may want to map errors thrown by the application to a more specific HTTP response.
+Currently, this can be achieved by checking for each error type in each handler's catch block, converting it to an
+appropriate HTTP response and returning it.
+
+For example,
+```swift
+func getGreeting(_ input: Operations.getGreeting.Input) async throws -> Operations.getGreeting.Output {
+ do {
+ let response = try callGreetingLib()
+ return .ok(.init(body: response))
+ } catch let error {
+ switch error {
+ case GreetingError.authorizationError:
+ return (HTTPResponse(status: 404), nil)
+ case GreetingError.timeout:
+ return ...
+ }
+ }
+}
+```
+If a user wishes to map many errors, the error handling block scales linearly and introduces a lot of ceremony.
+
+### Proposed solution
+
+The proposed solution is twofold.
+
+1. Provide protocol(s) in `OpenAPIRuntime` to allow users to extend their error types with mappings to HTTP responses.
+
+2. Provide an (opt-in) middleware in OpenAPIRuntime that will call the conversion function on conforming error types when
+constructing the HTTP response.
+
+Vapor has a similar mechanism called [AbortError](https://docs.vapor.codes/basics/errors/).
+
+HummingBird also has an [error handling mechanism](https://docs.hummingbird.codes/2.0/documentation/hummingbird/errorhandling/)
+by allowing users to define a [HTTPError](https://docs.hummingbird.codes/2.0/documentation/hummingbird/httperror)
+
+The proposal aims to provide a transport agnostic error handling mechanism for OpenAPI users.
+
+### Detailed design
+
+#### Proposed Error protocols
+
+Users can choose to conform to one of the protocols described below depending on the level of specificity they would
+like to have in the response.
+
+```swift
+public protocol HTTPStatusConvertible {
+ var httpStatus: HTTPResponse.Status { get }
+}
+
+public protocol HTTPHeadConvertible: HTTPStatusConvertible {
+ var httpHeaderFields: HTTPTypes.HTTPFields { get }
+}
+
+public protocol HTTPResponseConvertible: HTTPHeadConvertible {
+ var httpBody: OpenAPIRuntime.HTTPBody { get }
+}
+```
+
+#### Proposed Error Middleware
+
+The proposed error middleware in OpenAPIRuntime will convert the application error to the appropriate error response.
+```swift
+public struct ErrorMiddleware: ServerMiddleware {
+ func intercept(_ request: HTTPTypes.HTTPRequest,
+ body: OpenAPIRuntime.HTTPBody?,
+ metadata: OpenAPIRuntime.ServerRequestMetadata,
+ operationID: String,
+ next: @Sendable (HTTPTypes.HTTPRequest, OpenAPIRuntime.HTTPBody?, OpenAPIRuntime.ServerRequestMetadata) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?)) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) {
+ do {
+ return try await next(request, body, metadata)
+ } catch let error as ServerError {
+ if let appError = error.underlyingError as? HTTPStatusConvertible else {
+ return (HTTPResponse(status: appError.httpStatus), nil)
+ } else if ... {
+
+ }
+ }
+ }
+}
+```
+
+Please note that the proposal places the responsibility to conform to the documented API in the hands of the user.
+There's no mechanism to prevent the users from inadvertently transforming a thrown error into an undocumented response.
+
+#### Example usage
+
+1. Create an error type that conforms to one of the error protocol(s)
+```swift
+extension MyAppError: HTTPStatusConvertible {
+ var httpStatus: HTTPResponse.Status {
+ switch self {
+ case .invalidInputFormat:
+ HTTPResponse.Status.badRequest
+ case .authorizationError:
+ HTTPResponse.Status.forbidden | Nit: for clarity, we can shorten this
```suggestion
.badRequest
case .authorizationError:
.forbidden
``` |
swift-openapi-generator | github_2023 | others | 626 | apple | czechboy0 | @@ -0,0 +1,151 @@
+# SOAR-0011: Improved Error Handling
+
+Improve error handling by adding the ability for mapping application errors to HTTP responses.
+
+## Overview
+
+- Proposal: SOAR-0011
+- Author(s): [Gayathri Sairamkrishnan](https://github.com/gayathrisairam)
+- Status: **Awaiting Review**
+- Issue: [apple/swift-openapi-generator#609](https://github.com/apple/swift-openapi-generator/issues/609)
+- Affected components:
+ - runtime
+
+### Introduction
+
+The goal of this proposal to improve the current error handling mechanism in Swift OpenAPI runtime. The proposal
+introduces a way for users to map errors thrown by their handlers to specific HTTP responses.
+
+### Motivation
+
+ When implementing a server with Swift OpenAPI Generator, users implement a type that conforms to a generated protocol, providing one method for each API operation defined in the OpenAPI document. At runtime, if this function throws, the runtime library transforms this into a 500 HTTP response (Internal Error).
+
+Instead, server developers may want to map errors thrown by the application to a more specific HTTP response.
+Currently, this can be achieved by checking for each error type in each handler's catch block, converting it to an
+appropriate HTTP response and returning it.
+
+For example,
+```swift
+func getGreeting(_ input: Operations.getGreeting.Input) async throws -> Operations.getGreeting.Output {
+ do {
+ let response = try callGreetingLib()
+ return .ok(.init(body: response))
+ } catch let error {
+ switch error {
+ case GreetingError.authorizationError:
+ return (HTTPResponse(status: 404), nil)
+ case GreetingError.timeout:
+ return ...
+ }
+ }
+}
+```
+If a user wishes to map many errors, the error handling block scales linearly and introduces a lot of ceremony.
+
+### Proposed solution
+
+The proposed solution is twofold.
+
+1. Provide protocol(s) in `OpenAPIRuntime` to allow users to extend their error types with mappings to HTTP responses.
+
+2. Provide an (opt-in) middleware in OpenAPIRuntime that will call the conversion function on conforming error types when
+constructing the HTTP response.
+
+Vapor has a similar mechanism called [AbortError](https://docs.vapor.codes/basics/errors/).
+
+HummingBird also has an [error handling mechanism](https://docs.hummingbird.codes/2.0/documentation/hummingbird/errorhandling/)
+by allowing users to define a [HTTPError](https://docs.hummingbird.codes/2.0/documentation/hummingbird/httperror)
+
+The proposal aims to provide a transport agnostic error handling mechanism for OpenAPI users.
+
+### Detailed design
+
+#### Proposed Error protocols
+
+Users can choose to conform to one of the protocols described below depending on the level of specificity they would
+like to have in the response.
+
+```swift
+public protocol HTTPStatusConvertible {
+ var httpStatus: HTTPResponse.Status { get }
+}
+
+public protocol HTTPHeadConvertible: HTTPStatusConvertible {
+ var httpHeaderFields: HTTPTypes.HTTPFields { get }
+}
+
+public protocol HTTPResponseConvertible: HTTPHeadConvertible {
+ var httpBody: OpenAPIRuntime.HTTPBody { get }
+}
+```
+
+#### Proposed Error Middleware
+
+The proposed error middleware in OpenAPIRuntime will convert the application error to the appropriate error response.
+```swift
+public struct ErrorMiddleware: ServerMiddleware {
+ func intercept(_ request: HTTPTypes.HTTPRequest,
+ body: OpenAPIRuntime.HTTPBody?,
+ metadata: OpenAPIRuntime.ServerRequestMetadata,
+ operationID: String,
+ next: @Sendable (HTTPTypes.HTTPRequest, OpenAPIRuntime.HTTPBody?, OpenAPIRuntime.ServerRequestMetadata) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?)) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) {
+ do {
+ return try await next(request, body, metadata)
+ } catch let error as ServerError {
+ if let appError = error.underlyingError as? HTTPStatusConvertible else {
+ return (HTTPResponse(status: appError.httpStatus), nil)
+ } else if ... {
+
+ }
+ }
+ }
+}
+```
+
+Please note that the proposal places the responsibility to conform to the documented API in the hands of the user.
+There's no mechanism to prevent the users from inadvertently transforming a thrown error into an undocumented response.
+
+#### Example usage
+
+1. Create an error type that conforms to one of the error protocol(s)
+```swift
+extension MyAppError: HTTPStatusConvertible {
+ var httpStatus: HTTPResponse.Status {
+ switch self {
+ case .invalidInputFormat:
+ HTTPResponse.Status.badRequest
+ case .authorizationError:
+ HTTPResponse.Status.forbidden
+ }
+ }
+}
+```
+
+2. Opt in to the error middleware while registering the handler
+
+```swift
+let handler = try await RequestHandler()
+try handler.registerHandlers(on: transport, middlewares: [ErrorHandlingMiddleware()]) | Nit: you're using the name `ErrorMiddleware` earlier, and `ErrorHandlingMiddleware` here. While the name itself will be discussed as part of the review, it might make sense to make them consistent to avoid confusion of whether the names will or will not be the same. |
swift-openapi-generator | github_2023 | others | 626 | apple | czechboy0 | @@ -0,0 +1,151 @@
+# SOAR-0011: Improved Error Handling
+
+Improve error handling by adding the ability for mapping application errors to HTTP responses.
+
+## Overview
+
+- Proposal: SOAR-0011
+- Author(s): [Gayathri Sairamkrishnan](https://github.com/gayathrisairam)
+- Status: **Awaiting Review** | ```suggestion
- Status: **In Review**
``` |
swift-openapi-generator | github_2023 | others | 626 | apple | czechboy0 | @@ -0,0 +1,159 @@
+# SOAR-0011: Improved Error Handling
+
+Improve error handling by adding the ability for mapping application errors to HTTP responses.
+
+## Overview
+
+- Proposal: SOAR-0011
+- Author(s): [Gayathri Sairamkrishnan](https://github.com/gayathrisairam)
+- Status: **In Review** | ```suggestion
- Status: **Ready for Implementation**
``` |
swift-openapi-generator | github_2023 | others | 626 | apple | czechboy0 | @@ -0,0 +1,159 @@
+# SOAR-0011: Improved Error Handling
+
+Improve error handling by adding the ability for mapping application errors to HTTP responses.
+
+## Overview
+
+- Proposal: SOAR-0011
+- Author(s): [Gayathri Sairamkrishnan](https://github.com/gayathrisairam)
+- Status: **Ready for Implementation** | ```suggestion
- Status: **Implemented**
``` |
swift-openapi-generator | github_2023 | others | 674 | apple | simonjbeaumont | @@ -42,32 +59,48 @@ extension FileTranslator {
isNullable: Bool,
allowedValues: [AnyCodable]
) throws -> Declaration {
- let cases: [(String, LiteralDescription)] = try allowedValues.map(\.value)
- .map { anyValue in
- switch backingType {
- case .string:
- // In nullable enum schemas, empty strings are parsed as Void.
- // This is unlikely to be fixed, so handling that case here.
- // https://github.com/apple/swift-openapi-generator/issues/118
- if isNullable && anyValue is Void { return (context.asSwiftSafeName(""), .string("")) }
+ var seen: Set<EnumValue> = []
+ var cases: [(String, LiteralDescription)] = []
+ func shouldAdd(_ value: EnumValue) throws -> Bool { | This maybe-add-to-dictionary flow, that maintains a set seems unnecessarily complex.
We already had an array of key-value pairs, which we can then just pass to `Dictionary.init(_:uniquingKeysWith:)`:
```swift
let dict = Dictionary(cases, uniquingKeysWith: { first, _ in
// emit diagnostic
return first
})
``` |
swift-openapi-generator | github_2023 | others | 674 | apple | simonjbeaumont | @@ -23,6 +23,23 @@ enum RawEnumBackingType {
case integer
}
+/// The extracted enum value.
+private enum EnumValue: Hashable, CustomStringConvertible {
+
+ /// A string value.
+ case string(String)
+
+ /// An integer value.
+ case integer(Int)
+
+ var description: String {
+ switch self {
+ case .string(let value): return "\"\(value)\""
+ case .integer(let value): return String(value)
+ }
+ } | Is `description` the right thing to use to generate the representation we need to be safe in generated code? Should we promote this to a more formally named computed property? |
swift-openapi-generator | github_2023 | others | 656 | apple | czechboy0 | @@ -55,14 +56,34 @@ extension TypesFileTranslator {
}
associatedValues.append(.init(type: .init(responseStructTypeName)))
- let enumCaseDesc = EnumCaseDescription(name: enumCaseName, kind: .nameWithAssociatedValues(associatedValues))
- let enumCaseDecl: Declaration = .commentable(
- responseKind.docComment(
- userDescription: typedResponse.response.description,
- jsonPath: operationJSONPath + "/responses/" + responseKind.jsonPathComponent
- ),
- .enumCase(enumCaseDesc)
+ let enumCaseDocComment = responseKind.docComment(
+ userDescription: typedResponse.response.description,
+ jsonPath: operationJSONPath + "/responses/" + responseKind.jsonPathComponent
)
+ let enumCaseDesc = EnumCaseDescription(name: enumCaseName, kind: .nameWithAssociatedValues(associatedValues))
+ let enumCaseDecl: Declaration = .commentable(enumCaseDocComment, .enumCase(enumCaseDesc))
+
+ var staticMemberDecl: Declaration?
+ let responseHasNoHeaders = typedResponse.response.headers?.isEmpty ?? true
+ let responseHasNoContent = typedResponse.response.content.isEmpty
+ if responseHasNoContent && responseHasNoHeaders && !responseKind.wantsStatusCode {
+ let staticMemberDesc = VariableDescription(
+ accessModifier: config.access,
+ isStatic: true,
+ kind: .var,
+ left: .identifier(.pattern(enumCaseName)),
+ type: .member(["Self"]),
+ getter: [
+ .expression(
+ .functionCall(
+ calledExpression: .dot(enumCaseName),
+ arguments: [.functionCall(calledExpression: .dot("init"))]
+ )
+ )
+ ]
+ )
+ staticMemberDecl = .commentable(enumCaseDocComment, .variable(staticMemberDesc))
+ } | ```suggestion
let staticMemberDecl: Declaration?
let responseHasNoHeaders = typedResponse.response.headers?.isEmpty ?? true
let responseHasNoContent = typedResponse.response.content.isEmpty
if responseHasNoContent && responseHasNoHeaders && !responseKind.wantsStatusCode {
let staticMemberDesc = VariableDescription(
accessModifier: config.access,
isStatic: true,
kind: .var,
left: .identifier(.pattern(enumCaseName)),
type: .member(["Self"]),
getter: [
.expression(
.functionCall(
calledExpression: .dot(enumCaseName),
arguments: [.functionCall(calledExpression: .dot("init"))]
)
)
]
)
staticMemberDecl = .commentable(enumCaseDocComment, .variable(staticMemberDesc))
} else {
staticMemberDecl = nil
}
``` |
swift-openapi-generator | github_2023 | others | 653 | apple | simonjbeaumont | @@ -74,13 +74,13 @@ For details, check out <doc:Configuring-the-generator>.
### How do I enable the build plugin in Xcode and Xcode Cloud?
-By default, build plugins must be explicitly enabled by the adopter.
+By default, you must explicitly enable build plugins before they are allowed to run.
-In Xcode, the first time you add a build plugin as a dependency of your project or package, the build fails and requires you to enable the plugin.
+Before a plugin is enabled, you might encounter a build error with the message _"OpenAPIGenerator" is disabled_. | ```suggestion
Before a plugin is enabled, you will encounter a build error with the message `"OpenAPIGenerator" is disabled`.
``` |
swift-openapi-generator | github_2023 | others | 652 | apple | czechboy0 | @@ -9,23 +9,16 @@ jobs:
name: Soundness
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
with:
- api_breakage_check_enabled: false | I think we want to keep `api_breakage_check_enabled: false`? We recently disabled it, as we don't have any public API from this package, only plugins and executables, and the one library here is explicitly _not_ stable. |
swift-openapi-generator | github_2023 | others | 629 | apple | czechboy0 | @@ -0,0 +1,374 @@
+# SOAR-0012: Generate enums for server variables
+
+Introduce generator logic to generate Swift enums for server variables that define the 'enum' field.
+
+## Overview
+
+- Proposal: SOAR-NNNN | ```suggestion
- Proposal: SOAR-0012
``` |
swift-openapi-generator | github_2023 | others | 629 | apple | czechboy0 | @@ -0,0 +1,374 @@
+# SOAR-0012: Generate enums for server variables
+
+Introduce generator logic to generate Swift enums for server variables that define the 'enum' field.
+
+## Overview
+
+- Proposal: SOAR-NNNN
+- Author(s): [Joshua Asbury](https://github.com/theoriginalbit)
+- Status: **Awaiting Review**
+- Issue: [apple/swift-openapi-generator#628](https://github.com/apple/swift-openapi-generator/issues/628)
+- Implementation:
+ - [apple/swift-openapi-generator#618](https://github.com/apple/swift-openapi-generator/pull/618)
+- Feature flag: `serverVariablesAsEnums`
+- Affected components:
+ - generator
+ - runtime (optional) | ```suggestion
```
You mention the possibility to clean this up in the runtime library later in the proposal, but since we can't do this in v1 (it'd be a breaking change), I think we can just remove it from here. |
swift-openapi-generator | github_2023 | others | 629 | apple | czechboy0 | @@ -0,0 +1,374 @@
+# SOAR-0012: Generate enums for server variables
+
+Introduce generator logic to generate Swift enums for server variables that define the 'enum' field.
+
+## Overview
+
+- Proposal: SOAR-NNNN
+- Author(s): [Joshua Asbury](https://github.com/theoriginalbit)
+- Status: **Awaiting Review** | ```suggestion
- Status: **In Review**
``` |
swift-openapi-generator | github_2023 | others | 629 | apple | czechboy0 | @@ -0,0 +1,428 @@
+# SOAR-0012: Generate enums for server variables
+
+Introduce generator logic to generate Swift enums for server variables that define the 'enum' field.
+
+## Overview
+
+- Proposal: SOAR-0012
+- Author(s): [Joshua Asbury](https://github.com/theoriginalbit)
+- Status: **Ready for Implementation** | ```suggestion
- Status: **Implemented (1.4.0)**
```
This will go out with the next minor. |
swift-openapi-generator | github_2023 | others | 618 | apple | czechboy0 | @@ -28,6 +28,10 @@
public enum FeatureFlag: String, Hashable, Codable, CaseIterable, Sendable {
// needs to be here for the enum to compile
case empty
+
+ /// When enabled any server URL templating variables that have a defined
+ /// enum field will be generated as an enum instead of raw Strings.
+ case serverVariablesAsEnums = "ServerVariablesEnums" | ```suggestion
case serverVariablesAsEnums
```
In the past, we've just used the names directly, rather than capitalize them. |
swift-openapi-generator | github_2023 | others | 618 | apple | czechboy0 | @@ -43,6 +43,11 @@ class FileBasedReferenceTests: XCTestCase {
}
func testPetstore() throws { try _test(referenceProject: .init(name: .petstore)) }
+
+ func testPetstoreWithServerVariablesEnumsFeatureFlag() throws { | I appreciate you trying to improve the test coverage here, but we generally avoid duplicating the file-based reference tests for testing relatively self-contained features - as file-based reference tests are _really_ expensive to maintain.
Please remove these, and instead lean on snippet-based reference tests, which still allow you to test both variants with and without the feature flag. |
swift-openapi-generator | github_2023 | others | 618 | apple | czechboy0 | @@ -5473,6 +5673,21 @@ extension SnippetBasedReferenceTests {
let (registerHandlersDecl, _) = try translator.translateRegisterHandlers(operations)
try XCTAssertSwiftEquivalent(registerHandlersDecl, expectedSwift, file: file, line: line)
}
+
+ func assertServerTranslation(
+ _ serverYAML: String,
+ _ expectedSwift: String,
+ accessModifier: AccessModifier = .public,
+ featureFlags: FeatureFlags = [],
+ file: StaticString = #filePath,
+ line: UInt = #line
+ ) throws {
+ continueAfterFailure = false
+ let server = try YAMLDecoder().decode(OpenAPI.Server.self, from: serverYAML)
+ let translator = try makeTypesTranslator(accessModifier: accessModifier, featureFlags: featureFlags)
+ let translation = translator.translateServers([server])
+ try XCTAssertSwiftEquivalent(translation, expectedSwift, file: file, line: line)
+ } | ```suggestion
func assertServersTranslation(
_ serversYAML: String,
_ expectedSwift: String,
accessModifier: AccessModifier = .public,
featureFlags: FeatureFlags = [],
file: StaticString = #filePath,
line: UInt = #line
) throws {
continueAfterFailure = false
let servers = try YAMLDecoder().decode([OpenAPI.Server].self, from: serversYAML)
let translator = try makeTypesTranslator(accessModifier: accessModifier, featureFlags: featureFlags)
let translation = translator.translateServers(servers)
try XCTAssertSwiftEquivalent(translation, expectedSwift, file: file, line: line)
}
```
If you make this change, you can then pass an array of servers for tests, e.g.
```
- url: ...
description: ...
- url: ...
``` |
swift-openapi-generator | github_2023 | others | 618 | apple | czechboy0 | @@ -64,15 +36,70 @@ extension TypesFileTranslator {
.call([
.init(
label: "validatingOpenAPIServerURL",
- expression: .literal(.string(server.urlTemplate.absoluteString))
- ), .init(label: "variables", expression: .literal(.array(variableInitializers))),
+ expression: .literal(.string(url))
+ ),
+ .init(
+ label: "variables",
+ expression: .literal(.array(variables.map(\.initializer)))
+ )
])
)
)
]
+ ).deprecate(
+ if: isDeprecated,
+ description: .init(message: "Migrate to the new type-safe API for server URLs.") | Could we use the `renamed:` parameter of the deprecation, to allow people to migrate by accepting a Fix-It? |
swift-openapi-generator | github_2023 | others | 618 | apple | czechboy0 | @@ -154,25 +154,87 @@ extension APIProtocol {
/// Server URLs defined in the OpenAPI document.
public enum Servers {
/// Example Petstore implementation service
+ public enum Server1 {
+ public static func url() throws -> Foundation.URL { | We should also generate a comment on the `url()` static function. Might make sense to simply duplicate the user-provided comment that we already put on the namespace (e.g. above `Server1` here) |
swift-openapi-generator | github_2023 | others | 618 | apple | czechboy0 | @@ -154,25 +154,87 @@ extension APIProtocol {
/// Server URLs defined in the OpenAPI document.
public enum Servers {
/// Example Petstore implementation service
+ public enum Server1 {
+ public static func url() throws -> Foundation.URL {
+ try Foundation.URL(
+ validatingOpenAPIServerURL: "https://example.com/api",
+ variables: []
+ )
+ }
+ }
+ /// Example Petstore implementation service
+ @available(*, deprecated, message: "Migrate to the new type-safe API for server URLs.")
public static func server1() throws -> Foundation.URL {
try Foundation.URL(
validatingOpenAPIServerURL: "https://example.com/api",
variables: []
)
}
+ public enum Server2 {
+ public static func url() throws -> Foundation.URL {
+ try Foundation.URL(
+ validatingOpenAPIServerURL: "/api",
+ variables: []
+ )
+ }
+ }
+ @available(*, deprecated, message: "Migrate to the new type-safe API for server URLs.")
public static func server2() throws -> Foundation.URL {
try Foundation.URL(
validatingOpenAPIServerURL: "/api",
variables: []
)
}
/// A custom domain.
+ public enum Server3 {
+ /// The "port" variable defined in the OpenAPI document. The default value is "443".
+ @frozen public enum Port: Swift.String {
+ case _443 = "443"
+ case _8443 = "8443"
+ }
+ ///
+ /// - Parameters:
+ /// - _protocol:
+ /// - subdomain: A subdomain name.
+ /// - port:
+ /// - basePath: The base API path.
+ public static func url(
+ _protocol: Swift.String = "https",
+ subdomain: Swift.String = "test",
+ port: Port = Port._443, | ```suggestion
port: Port = ._443,
```
Can we omit repeating the type, to match what users would type manually? |
swift-openapi-generator | github_2023 | others | 618 | apple | czechboy0 | @@ -14,47 +14,19 @@
import OpenAPIKit
extension TypesFileTranslator {
-
- /// Returns a declaration of a server URL static method defined in
- /// the OpenAPI document.
- /// - Parameters:
- /// - index: The index of the server in the list of servers defined
- /// in the OpenAPI document.
- /// - server: The server URL information.
- /// - Returns: A static method declaration, and a name for the variable to
- /// declare the method under.
- func translateServer(index: Int, server: OpenAPI.Server) -> Declaration {
- let methodName = "\(Constants.ServerURL.propertyPrefix)\(index+1)"
- let safeVariables = server.variables.map { (key, value) in
- (originalKey: key, swiftSafeKey: context.asSwiftSafeName(key), value: value)
- }
- let parameters: [ParameterDescription] = safeVariables.map { (originalKey, swiftSafeKey, value) in
- .init(label: swiftSafeKey, type: .init(TypeName.string), defaultValue: .literal(value.default))
- }
- let variableInitializers: [Expression] = safeVariables.map { (originalKey, swiftSafeKey, value) in
- let allowedValuesArg: FunctionArgumentDescription?
- if let allowedValues = value.enum {
- allowedValuesArg = .init(
- label: "allowedValues",
- expression: .literal(.array(allowedValues.map { .literal($0) }))
- )
- } else {
- allowedValuesArg = nil
- }
- return .dot("init")
- .call(
- [
- .init(label: "name", expression: .literal(originalKey)),
- .init(label: "value", expression: .identifierPattern(swiftSafeKey)),
- ] + (allowedValuesArg.flatMap { [$0] } ?? [])
- )
- }
- let methodDecl = Declaration.commentable(
- .functionComment(abstract: server.description, parameters: safeVariables.map { ($1, $2.description) }),
+ private func translateServerStaticFunction( | Please add a doc comment for this function. |
swift-openapi-generator | github_2023 | others | 618 | apple | czechboy0 | @@ -0,0 +1,214 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+import OpenAPIKit
+
+extension TypesFileTranslator {
+ /// Returns a declaration of a namespace (enum) for a specific server and will define
+ /// one enum member for each of the server's variables in the OpenAPI Document.
+ /// If the server does not define variables, no declaration will be generated.
+ /// - Parameters:
+ /// - index: The index of the server in the list of servers defined
+ /// in the OpenAPI document.
+ /// - server: The server variables information.
+ /// - Returns: A declaration of the server variables namespace, or `nil` if no
+ /// variables are declared.
+ func translateServerVariables(index: Int, server: OpenAPI.Server, generateAsEnum: Bool) -> [any ServerVariableGenerator] {
+ return server.variables.map { (key, variable) in
+ guard generateAsEnum, let enumValues = variable.enum else {
+ return RawStringTranslatedServerVariable(
+ key: key,
+ variable: variable,
+ context: context
+ )
+ }
+
+ return GeneratedEnumTranslatedServerVariable(
+ key: key,
+ variable: variable,
+ enumValues: enumValues,
+ accessModifier: config.access,
+ context: context
+ )
+ }
+ }
+
+ // MARK: Generators
+
+ /// Represents a server variable and the function of generation that should be applied.
+ protocol ServerVariableGenerator {
+ /// Returns the declaration (enum) that should be added to the `Variables.Server#` | ```suggestion
/// Returns the declaration (enum) that should be added to the `Variables.Server`
``` |
swift-openapi-generator | github_2023 | others | 618 | apple | czechboy0 | @@ -0,0 +1,214 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+import OpenAPIKit
+
+extension TypesFileTranslator {
+ /// Returns a declaration of a namespace (enum) for a specific server and will define
+ /// one enum member for each of the server's variables in the OpenAPI Document.
+ /// If the server does not define variables, no declaration will be generated.
+ /// - Parameters:
+ /// - index: The index of the server in the list of servers defined
+ /// in the OpenAPI document.
+ /// - server: The server variables information.
+ /// - Returns: A declaration of the server variables namespace, or `nil` if no
+ /// variables are declared.
+ func translateServerVariables(index: Int, server: OpenAPI.Server, generateAsEnum: Bool) -> [any ServerVariableGenerator] {
+ return server.variables.map { (key, variable) in
+ guard generateAsEnum, let enumValues = variable.enum else {
+ return RawStringTranslatedServerVariable(
+ key: key,
+ variable: variable,
+ context: context
+ )
+ }
+
+ return GeneratedEnumTranslatedServerVariable(
+ key: key,
+ variable: variable,
+ enumValues: enumValues,
+ accessModifier: config.access,
+ context: context
+ )
+ }
+ }
+
+ // MARK: Generators
+
+ /// Represents a server variable and the function of generation that should be applied.
+ protocol ServerVariableGenerator {
+ /// Returns the declaration (enum) that should be added to the `Variables.Server#`
+ /// namespace. If the server variable does not require any codegen then it should
+ /// return `nil`.
+ var declaration: Declaration? { get }
+
+ /// Returns the description of the parameter that will be used to define the variable
+ /// in the static method for a given server.
+ var parameter: ParameterDescription { get }
+
+ /// Returns an expression for the variable initializer that is used in the body of a server's
+ /// static method by passing it along to the URL resolver.
+ var initializer: Expression { get }
+
+ /// Returns the description of this variables documentation for the function comment of
+ /// the server's static method.
+ var functionComment: (name: String, comment: String?) { get }
+ }
+
+ /// Represents a variable that is required to be represented as a `Swift.String`.
+ private struct RawStringTranslatedServerVariable: ServerVariableGenerator {
+ let key: String
+ let swiftSafeKey: String
+ let variable: OpenAPI.Server.Variable | Please add doc comments for the properties. |
swift-openapi-generator | github_2023 | others | 618 | apple | czechboy0 | @@ -0,0 +1,214 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+import OpenAPIKit
+
+extension TypesFileTranslator {
+ /// Returns a declaration of a namespace (enum) for a specific server and will define
+ /// one enum member for each of the server's variables in the OpenAPI Document.
+ /// If the server does not define variables, no declaration will be generated.
+ /// - Parameters:
+ /// - index: The index of the server in the list of servers defined
+ /// in the OpenAPI document.
+ /// - server: The server variables information.
+ /// - Returns: A declaration of the server variables namespace, or `nil` if no
+ /// variables are declared.
+ func translateServerVariables(index: Int, server: OpenAPI.Server, generateAsEnum: Bool) -> [any ServerVariableGenerator] {
+ return server.variables.map { (key, variable) in
+ guard generateAsEnum, let enumValues = variable.enum else {
+ return RawStringTranslatedServerVariable(
+ key: key,
+ variable: variable,
+ context: context
+ )
+ }
+
+ return GeneratedEnumTranslatedServerVariable(
+ key: key,
+ variable: variable,
+ enumValues: enumValues,
+ accessModifier: config.access,
+ context: context
+ )
+ }
+ }
+
+ // MARK: Generators
+
+ /// Represents a server variable and the function of generation that should be applied.
+ protocol ServerVariableGenerator {
+ /// Returns the declaration (enum) that should be added to the `Variables.Server#`
+ /// namespace. If the server variable does not require any codegen then it should
+ /// return `nil`.
+ var declaration: Declaration? { get }
+
+ /// Returns the description of the parameter that will be used to define the variable
+ /// in the static method for a given server.
+ var parameter: ParameterDescription { get }
+
+ /// Returns an expression for the variable initializer that is used in the body of a server's
+ /// static method by passing it along to the URL resolver.
+ var initializer: Expression { get }
+
+ /// Returns the description of this variables documentation for the function comment of
+ /// the server's static method.
+ var functionComment: (name: String, comment: String?) { get }
+ }
+
+ /// Represents a variable that is required to be represented as a `Swift.String`.
+ private struct RawStringTranslatedServerVariable: ServerVariableGenerator {
+ let key: String
+ let swiftSafeKey: String
+ let variable: OpenAPI.Server.Variable
+
+ init(key: String, variable: OpenAPI.Server.Variable, context: TranslatorContext) { | Please add a doc comment for the initializer |
swift-openapi-generator | github_2023 | others | 618 | apple | czechboy0 | @@ -154,25 +154,89 @@ extension APIProtocol {
/// Server URLs defined in the OpenAPI document.
public enum Servers {
/// Example Petstore implementation service
+ public enum Server1 {
+ /// Example Petstore implementation service
+ public static func url() throws -> Foundation.URL {
+ try Foundation.URL(
+ validatingOpenAPIServerURL: "https://example.com/api",
+ variables: []
+ )
+ }
+ }
+ /// Example Petstore implementation service
+ @available(*, deprecated, renamed: "Servers.Server1.url") | ```suggestion
@available(*, deprecated, renamed: "Servers.Server1.url()")
```
Should it also contain the `()` or not? Can you check that accepting the Fix-it does the right thing? |
swift-openapi-generator | github_2023 | others | 618 | apple | czechboy0 | @@ -5181,6 +5181,297 @@ final class SnippetBasedReferenceTests: XCTestCase {
)
}
+ func testServerWithNoVariables() throws {
+ try self.assertServersTranslation(
+ """
+ - url: https://example.com/api
+ """,
+ """
+ public enum Servers {
+ public enum Server1 {
+ public static func url() throws -> Foundation.URL {
+ try Foundation.URL(
+ validatingOpenAPIServerURL: "https://example.com/api",
+ variables: []
+ )
+ }
+ }
+ @available(*, deprecated, renamed: "Servers.Server1.url")
+ public static func server1() throws -> Foundation.URL {
+ try Foundation.URL(
+ validatingOpenAPIServerURL: "https://example.com/api",
+ variables: []
+ )
+ }
+ }
+ """
+ )
+ }
+
+ func testServerWithDefaultVariable() throws {
+ try self.assertServersTranslation(
+ """
+ - url: '{protocol}://example.com/api'
+ description: A custom domain.
+ variables:
+ protocol:
+ default: https
+ description: A network protocol.
+ """,
+ """
+ public enum Servers {
+ public enum Server1 {
+ public static func url(_protocol: Swift.String = "https") throws -> Foundation.URL {
+ try Foundation.URL(
+ validatingOpenAPIServerURL: "{protocol}://example.com/api",
+ variables: [
+ .init(
+ name: "protocol",
+ value: _protocol
+ )
+ ]
+ )
+ }
+ }
+ @available(*, deprecated, renamed: "Servers.Server1.url")
+ public static func server1(_protocol: Swift.String = "https") throws -> Foundation.URL {
+ try Foundation.URL(
+ validatingOpenAPIServerURL: "{protocol}://example.com/api",
+ variables: [
+ .init(
+ name: "protocol",
+ value: _protocol
+ )
+ ]
+ )
+ }
+ }
+ """
+ )
+ }
+
+ func testServerWithDefaultAndEnumVariables() throws {
+ try self.assertServersTranslation(
+ """
+ - url: 'https://{environment}.example.com/api/{version}'
+ description: A custom domain.
+ variables:
+ environment:
+ enum:
+ - production
+ - sandbox
+ default: production
+ version:
+ default: v1
+ """,
+ """
+ public enum Servers {
+ public enum Server1 {
+ @frozen public enum Environment: Swift.String {
+ case production
+ case sandbox
+ }
+ public static func url(
+ environment: Environment = .production,
+ version: Swift.String = "v1"
+ ) throws -> Foundation.URL {
+ try Foundation.URL(
+ validatingOpenAPIServerURL: "https://{environment}.example.com/api/{version}",
+ variables: [
+ .init(
+ name: "environment",
+ value: environment.rawValue
+ ),
+ .init(
+ name: "version",
+ value: version
+ )
+ ]
+ )
+ }
+ }
+ @available(*, deprecated, renamed: "Servers.Server1.url")
+ public static func server1(
+ environment: Swift.String = "production",
+ version: Swift.String = "v1"
+ ) throws -> Foundation.URL {
+ try Foundation.URL(
+ validatingOpenAPIServerURL: "https://{environment}.example.com/api/{version}",
+ variables: [
+ .init(
+ name: "environment",
+ value: environment,
+ allowedValues: [
+ "production",
+ "sandbox"
+ ]
+ ),
+ .init(
+ name: "version",
+ value: version
+ )
+ ]
+ )
+ }
+ }
+ """
+ )
+ }
+
+ func testServersMultipleServers() throws {
+ try self.assertServersTranslation(
+ """
+ - url: 'https://{environment}.example.com/api/{version}'
+ description: A custom domain.
+ variables:
+ environment:
+ enum:
+ - production
+ - sandbox
+ default: production
+ version:
+ default: v1
+ - url: 'https://{environment}.api.example.com/'
+ variables:
+ environment:
+ enum:
+ - sandbox
+ - develop
+ default: develop
+ - url: 'https://example.com/api/{version}'
+ description: Vanity URL for production.example.com/api/{version}
+ variables:
+ version:
+ default: v1
+ - url: 'https://api.example.com/'
+ description: Vanity URL for production.api.example.com
+ """,
+ """
+ public enum Servers {
+ public enum Server1 {
+ @frozen public enum Environment: Swift.String { | Can you also generate the enums as `Sendable`? |
swift-openapi-generator | github_2023 | others | 618 | apple | czechboy0 | @@ -222,14 +222,17 @@ final class Test_Types: XCTestCase {
verifyingJSON: #"{"name":"C","parent":{"nested":{"name":"B","parent":{"nested":{"name":"A"}}}}}"#
)
}
- func testServers_1() throws { XCTAssertEqual(try Servers.server1(), URL(string: "https://example.com/api")) }
- func testServers_2() throws { XCTAssertEqual(try Servers.server2(), URL(string: "/api")) }
+ func testServers_1() throws { XCTAssertEqual(try Servers.Server1.url(), URL(string: "https://example.com/api")) }
+ func testServers_2() throws { XCTAssertEqual(try Servers.Server2.url(), URL(string: "/api")) }
func testServers_3() throws {
- XCTAssertEqual(try Servers.server3(), URL(string: "https://test.example.com:443/v1"))
+ XCTAssertEqual(try Servers.Server3.url(), URL(string: "https://test.example.com:443/v1"))
XCTAssertEqual(
- try Servers.server3(subdomain: "bar", port: "8443", basePath: "v2/staging"),
+ try Servers.Server3.url(subdomain: "bar", port: ._8443, basePath: "v2/staging"),
URL(string: "https://bar.example.com:8443/v2/staging")
)
+ // Intentionally using the deprecated static function to check for regressions.
+ // Once the deprecated functions are no longer being generated this assertion is
+ // unnecessary and can be removed.
XCTAssertThrowsError(try Servers.server3(port: "foo")) { error in | Please just remove the `XCTAssertThrowsError`, we don't want to have that warning in our tests as the goal is to be warning-free and run with warnings-as-errors in CI. The underlying validation is run as part of Swift OpenAPI Runtime tests, so I'm happy for us to drop it here. |
swift-openapi-generator | github_2023 | others | 640 | apple | simonjbeaumont | @@ -69,9 +68,9 @@ struct TypeMatcher {
try Self._tryMatchRecursive(
for: schema.value,
test: { (schema) -> TypeUsage? in
- if let builtinType = Self._tryMatchBuiltinNonRecursive(for: schema) { return builtinType }
+ if let builtinType = _tryMatchBuiltinNonRecursive(for: schema) { return builtinType }
guard case let .reference(ref, _) = schema else { return nil }
- return try TypeAssigner(asSwiftSafeName: asSwiftSafeName).typeName(for: ref).asUsage
+ return try TypeAssigner(context: context).typeName(for: ref).asUsage | Do we need to mint a new `TypeAssigner` on each of these calls? Is this the only place `context` is used? Maybe we're better having the assigner be a stored property instead? WDYT? |
swift-openapi-generator | github_2023 | others | 625 | apple | czechboy0 | @@ -113,6 +113,7 @@ The returned binary body contains the raw events, and the stream can be split up
- encode: `AsyncSequence<some Encodable>.asEncodedJSONSequence(encoder:)`
- Server-sent Events
- decode (if data is JSON): `AsyncSequence<ArraySlice<UInt8>>.asDecodedServerSentEventsWithJSONData(of:decoder:)`
+ - decode (if data is JSON with a non-JSON terminating byte sequence): `AsyncSequence<ArraySlice<UInt8>>.asDecodedServerSentEventsWithJSONData(of:decoder:terminate:)` | ```suggestion
- decode (if data is JSON with a non-JSON terminating byte sequence): `AsyncSequence<ArraySlice<UInt8>>.asDecodedServerSentEventsWithJSONData(of:decoder:while:)`
``` |
swift-openapi-generator | github_2023 | others | 625 | apple | czechboy0 | @@ -113,6 +113,7 @@ The returned binary body contains the raw events, and the stream can be split up
- encode: `AsyncSequence<some Encodable>.asEncodedJSONSequence(encoder:)`
- Server-sent Events
- decode (if data is JSON): `AsyncSequence<ArraySlice<UInt8>>.asDecodedServerSentEventsWithJSONData(of:decoder:)`
+ - decode (if data is JSON with a non-JSON terminating byte sequence): `AsyncSequence<ArraySlice<UInt8>>.asDecodedServerSentEventsWithJSONData(of:decoder:terminate:)`
- encode (if data is JSON): `AsyncSequence<some Encodable>.asEncodedServerSentEventsWithJSONData(encoder:)`
- decode (for other data): `AsyncSequence<ArraySlice<UInt8>>.asDecodedServerSentEvents()` | ```suggestion
- decode (for other data): `AsyncSequence<ArraySlice<UInt8>>.asDecodedServerSentEvents(while:)`
``` |
swift-openapi-generator | github_2023 | others | 604 | apple | simonjbeaumont | @@ -1,12 +1,50 @@
-name: Pull Request
+name: PR
on:
- pull_request:
- types: [opened, reopened, synchronize, ready_for_review]
-
+ pull_request:
+ types: [opened, reopened, synchronize]
+
jobs:
- call-reusable-pull-request-workflow:
- name: Checks
- uses: apple/swift-nio/.github/workflows/reusable_pull_request.yml@main
- with:
- benchmarks_linux_enabled: false
\ No newline at end of file
+ soundness:
+ name: Soundness
+ uses: apple/swift-nio/.github/workflows/soundness.yml@main
+ with:
+ license_header_check_project_name: "SwiftOpenAPIGenerator"
+ unacceptable_language_check_enabled: false
+ shell_check_enabled: false
+
+ unit-tests:
+ name: Unit tests
+ uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
+ with:
+ linux_5_8_enabled: false
+ linux_5_9_arguments_override: "--explicit-target-dependency-import-check error"
+ linux_5_10_arguments_override: "--explicit-target-dependency-import-check error"
+ linux_nightly_6_0_arguments_override: "--explicit-target-dependency-import-check error"
+ linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
+
+ cxx-interop:
+ name: Cxx interop
+ uses: apple/swift-nio/.github/workflows/cxx_interop.yml@main
+ with:
+ linux_5_8_enabled: false | This wasn't something we had before. Do we want it in all projects? |
swift-openapi-generator | github_2023 | others | 604 | apple | simonjbeaumont | @@ -1,12 +1,50 @@
-name: Pull Request
+name: PR
on:
- pull_request:
- types: [opened, reopened, synchronize, ready_for_review]
-
+ pull_request:
+ types: [opened, reopened, synchronize]
+
jobs:
- call-reusable-pull-request-workflow:
- name: Checks
- uses: apple/swift-nio/.github/workflows/reusable_pull_request.yml@main
- with:
- benchmarks_linux_enabled: false
\ No newline at end of file
+ soundness:
+ name: Soundness
+ uses: apple/swift-nio/.github/workflows/soundness.yml@main
+ with:
+ license_header_check_project_name: "SwiftOpenAPIGenerator"
+ unacceptable_language_check_enabled: false
+ shell_check_enabled: false
+
+ unit-tests:
+ name: Unit tests
+ uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
+ with:
+ linux_5_8_enabled: false
+ linux_5_9_arguments_override: "--explicit-target-dependency-import-check error"
+ linux_5_10_arguments_override: "--explicit-target-dependency-import-check error"
+ linux_nightly_6_0_arguments_override: "--explicit-target-dependency-import-check error"
+ linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
+
+ cxx-interop:
+ name: Cxx interop
+ uses: apple/swift-nio/.github/workflows/cxx_interop.yml@main
+ with:
+ linux_5_8_enabled: false
+
+ integration-tests:
+ name: Integration Tests
+ uses: apple/swift-nio/.github/workflows/swift_matrix.yml@main
+ with:
+ name: "Integration tests"
+ matrix_linux_5_8_enabled: false
+ matrix_linux_command: "apt-get update -y -q && apt-get install -y -q jq && ./scripts/run-integration-test.sh"
+
+ example-tests:
+ name: Example Tests
+ uses: apple/swift-nio/.github/workflows/swift_matrix.yml@main
+ with:
+ name: "Example tests"
+ matrix_linux_5_8_enabled: false
+ matrix_linux_command: "./scripts/test-examples.sh" | Starting a thread here to discuss your comment you made at the PR level about the example tests.
The script already uses a shared directory for cache and scratch, which, to be fair, opens it up to not catching a missing dependency in an example that is run later than an earlier one that had it.
You'd be surprised just how long it took if we _didn't_ do the current level of sharing :) |
swift-openapi-generator | github_2023 | others | 604 | apple | simonjbeaumont | @@ -1,12 +1,50 @@
-name: Pull Request
+name: PR
on:
- pull_request:
- types: [opened, reopened, synchronize, ready_for_review]
-
+ pull_request:
+ types: [opened, reopened, synchronize]
+
jobs:
- call-reusable-pull-request-workflow:
- name: Checks
- uses: apple/swift-nio/.github/workflows/reusable_pull_request.yml@main
- with:
- benchmarks_linux_enabled: false
\ No newline at end of file
+ soundness:
+ name: Soundness
+ uses: apple/swift-nio/.github/workflows/soundness.yml@main
+ with:
+ license_header_check_project_name: "SwiftOpenAPIGenerator"
+ unacceptable_language_check_enabled: false
+ shell_check_enabled: false
+
+ unit-tests:
+ name: Unit tests
+ uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
+ with:
+ linux_5_8_enabled: false
+ linux_5_9_arguments_override: "--explicit-target-dependency-import-check error"
+ linux_5_10_arguments_override: "--explicit-target-dependency-import-check error"
+ linux_nightly_6_0_arguments_override: "--explicit-target-dependency-import-check error"
+ linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
+
+ cxx-interop:
+ name: Cxx interop
+ uses: apple/swift-nio/.github/workflows/cxx_interop.yml@main
+ with:
+ linux_5_8_enabled: false
+
+ integration-tests:
+ name: Integration Tests
+ uses: apple/swift-nio/.github/workflows/swift_matrix.yml@main
+ with:
+ name: "Integration tests"
+ matrix_linux_5_8_enabled: false
+ matrix_linux_command: "apt-get update -y -q && apt-get install -y -q jq && ./scripts/run-integration-test.sh"
+
+ example-tests:
+ name: Example Tests
+ uses: apple/swift-nio/.github/workflows/swift_matrix.yml@main
+ with:
+ name: "Example tests"
+ matrix_linux_5_8_enabled: false
+ matrix_linux_command: "./scripts/test-examples.sh"
+
+ swift-6-language-mode:
+ name: Swift 6 Language Mode
+ uses: apple/swift-nio/.github/workflows/swift_6_language_mode.yml@main | We've made no effort to switch to Swift 6 language mode in this project _yet(!)_. Can we have this one be marked as skipped for now? |
swift-openapi-generator | github_2023 | others | 604 | apple | simonjbeaumont | @@ -1,12 +1,50 @@
-name: Pull Request
+name: PR
on:
- pull_request:
- types: [opened, reopened, synchronize, ready_for_review]
-
+ pull_request:
+ types: [opened, reopened, synchronize]
+
jobs:
- call-reusable-pull-request-workflow:
- name: Checks
- uses: apple/swift-nio/.github/workflows/reusable_pull_request.yml@main
- with:
- benchmarks_linux_enabled: false
\ No newline at end of file
+ soundness:
+ name: Soundness
+ uses: apple/swift-nio/.github/workflows/soundness.yml@main
+ with:
+ license_header_check_project_name: "SwiftOpenAPIGenerator"
+ unacceptable_language_check_enabled: false
+ shell_check_enabled: false | I think it's fair to leave the `unacceptable_language_check` pipeline disabled because we need to do a hot-swap with the other pipeline.
But for the shellcheck pipeline, what's the issue. I ask because this project already _has_ a shellcheck pipeline, which is passing. So why can't this one be passing? |
swift-openapi-generator | github_2023 | others | 604 | apple | simonjbeaumont | @@ -1,12 +1,68 @@
-name: Pull Request
+name: PR
on:
- pull_request:
- types: [opened, reopened, synchronize, ready_for_review]
-
+ pull_request:
+ types: [opened, reopened, synchronize]
+
jobs:
- call-reusable-pull-request-workflow:
- name: Checks
- uses: apple/swift-nio/.github/workflows/reusable_pull_request.yml@main
- with:
- benchmarks_linux_enabled: false
\ No newline at end of file
+ soundness:
+ name: Soundness
+ uses: apple/swift-nio/.github/workflows/soundness.yml@main
+ with:
+ api_breakage_check_enabled: true
+ broken_symlink_check_enabled: true
+ docs_check_enabled: true
+ format_check_enabled: true
+ license_header_check_enabled: true
+ license_header_check_project_name: "SwiftOpenAPIGenerator"
+ shell_check_enabled: true
+ unacceptable_language_check_enabled: true
+
+ unit-tests:
+ name: Unit tests
+ uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
+ with:
+ linux_5_8_enabled: false
+ linux_5_9_arguments_override: "--explicit-target-dependency-import-check error"
+ linux_5_10_arguments_override: "--explicit-target-dependency-import-check error"
+ linux_nightly_6_0_arguments_override: "--explicit-target-dependency-import-check error"
+ linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
+
+ integration-test:
+ name: Integration test
+ uses: apple/swift-nio/.github/workflows/swift_matrix.yml@main
+ with:
+ name: "Integration test"
+ matrix_linux_5_8_enabled: false
+ matrix_linux_command: "apt-get update -yq && apt-get install -yq jq && ./scripts/run-integration-test.sh"
+
+ compatibility-test:
+ name: Compatibility test
+ runs-on: ubuntu-latest
+ container:
+ image: swift:latest
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v4
+ with:
+ persist-credentials: false
+ - name: Run OpenAPI document compatibilty test
+ env:
+ SWIFT_OPENAPI_COMPATIBILITY_TEST_ENABLE: "true"
+ SWIFT_OPENAPI_COMPATIBILITY_TEST_SKIP_BUILD: "true"
+ SWIFT_OPENAPI_COMPATIBILITY_TEST_FILTER: OpenAPIGeneratorReferenceTests.CompatibilityTest
+ SWIFT_OPENAPI_COMPATIBILITY_TEST_PARALLEL_CODEGEN: "true"
+ SWIFT_OPENAPI_COMPATIBILITY_TEST_NUM_BUILD_JOBS: 1
+ run: swift test --filter ${SWIFT_OPENAPI_COMPATIBILITY_TEST_FILTER}
+
+ example-packages:
+ name: Example packages
+ uses: apple/swift-nio/.github/workflows/swift_matrix.yml@main | @czechboy0 @FranzBusch do you think we need to do this for all the Swift versions? |
swift-openapi-generator | github_2023 | others | 604 | apple | simonjbeaumont | @@ -1,12 +1,71 @@
-name: Pull Request
+name: PR
on:
- pull_request:
- types: [opened, reopened, synchronize, ready_for_review]
-
+ pull_request:
+ types: [opened, reopened, synchronize]
+
jobs:
- call-reusable-pull-request-workflow:
- name: Checks
- uses: apple/swift-nio/.github/workflows/reusable_pull_request.yml@main
- with:
- benchmarks_linux_enabled: false
\ No newline at end of file
+ soundness:
+ name: Soundness
+ uses: apple/swift-nio/.github/workflows/soundness.yml@main
+ with:
+ api_breakage_check_enabled: true
+ broken_symlink_check_enabled: true
+ docs_check_enabled: true
+ format_check_enabled: true
+ license_header_check_enabled: true
+ license_header_check_project_name: "SwiftOpenAPIGenerator"
+ shell_check_enabled: true
+ unacceptable_language_check_enabled: true | Because it's more visible. The fact that some are default to true and some to false is confusing IMO. I like to be able to see what tests we're running in the YAML. |
swift-openapi-generator | github_2023 | others | 604 | apple | simonjbeaumont | @@ -1,12 +1,71 @@
-name: Pull Request
+name: PR
on:
- pull_request:
- types: [opened, reopened, synchronize, ready_for_review]
-
+ pull_request:
+ types: [opened, reopened, synchronize]
+
jobs:
- call-reusable-pull-request-workflow:
- name: Checks
- uses: apple/swift-nio/.github/workflows/reusable_pull_request.yml@main
- with:
- benchmarks_linux_enabled: false
\ No newline at end of file
+ soundness:
+ name: Soundness
+ uses: apple/swift-nio/.github/workflows/soundness.yml@main
+ with:
+ api_breakage_check_enabled: true
+ broken_symlink_check_enabled: true
+ docs_check_enabled: true
+ format_check_enabled: true
+ license_header_check_enabled: true
+ license_header_check_project_name: "SwiftOpenAPIGenerator"
+ shell_check_enabled: true
+ unacceptable_language_check_enabled: true
+
+ unit-tests:
+ name: Unit tests
+ uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
+ with:
+ linux_5_8_enabled: false
+ linux_5_9_arguments_override: "--explicit-target-dependency-import-check error"
+ linux_5_10_arguments_override: "--explicit-target-dependency-import-check error" | More than happy to. But that's over-and-above what we currently had in this project. We can track it separately. |
swift-openapi-generator | github_2023 | others | 604 | apple | simonjbeaumont | @@ -1,12 +1,71 @@
-name: Pull Request
+name: PR
on:
- pull_request:
- types: [opened, reopened, synchronize, ready_for_review]
-
+ pull_request:
+ types: [opened, reopened, synchronize]
+
jobs:
- call-reusable-pull-request-workflow:
- name: Checks
- uses: apple/swift-nio/.github/workflows/reusable_pull_request.yml@main
- with:
- benchmarks_linux_enabled: false
\ No newline at end of file
+ soundness:
+ name: Soundness
+ uses: apple/swift-nio/.github/workflows/soundness.yml@main
+ with:
+ api_breakage_check_enabled: true
+ broken_symlink_check_enabled: true
+ docs_check_enabled: true
+ format_check_enabled: true
+ license_header_check_enabled: true
+ license_header_check_project_name: "SwiftOpenAPIGenerator"
+ shell_check_enabled: true
+ unacceptable_language_check_enabled: true
+
+ unit-tests:
+ name: Unit tests
+ uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
+ with:
+ linux_5_8_enabled: false
+ linux_5_9_arguments_override: "--explicit-target-dependency-import-check error"
+ linux_5_10_arguments_override: "--explicit-target-dependency-import-check error"
+ linux_nightly_6_0_arguments_override: "--explicit-target-dependency-import-check error"
+ linux_nightly_main_enabled: false
+
+ integration-test:
+ name: Integration test
+ uses: apple/swift-nio/.github/workflows/swift_matrix.yml@main
+ with:
+ name: "Integration test"
+ matrix_linux_command: "apt-get update -yq && apt-get install -yq jq && ./scripts/run-integration-test.sh"
+ matrix_linux_5_8_enabled: false
+ matrix_linux_nightly_main_enabled: false | Because it's materially slower and not blocking a PR. Note that this PR does use the nightly Swift versions in the scheduled workflow so we'll still be alerted. I'd really like to only have PR pipelines that are gating PR merges, especially when we have external contributors. |
swift-openapi-generator | github_2023 | others | 604 | apple | simonjbeaumont | @@ -1,12 +1,71 @@
-name: Pull Request
+name: PR
on:
- pull_request:
- types: [opened, reopened, synchronize, ready_for_review]
-
+ pull_request:
+ types: [opened, reopened, synchronize]
+
jobs:
- call-reusable-pull-request-workflow:
- name: Checks
- uses: apple/swift-nio/.github/workflows/reusable_pull_request.yml@main
- with:
- benchmarks_linux_enabled: false
\ No newline at end of file
+ soundness:
+ name: Soundness
+ uses: apple/swift-nio/.github/workflows/soundness.yml@main
+ with:
+ api_breakage_check_enabled: true
+ broken_symlink_check_enabled: true
+ docs_check_enabled: true
+ format_check_enabled: true
+ license_header_check_enabled: true
+ license_header_check_project_name: "SwiftOpenAPIGenerator"
+ shell_check_enabled: true
+ unacceptable_language_check_enabled: true
+
+ unit-tests:
+ name: Unit tests
+ uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
+ with:
+ linux_5_8_enabled: false
+ linux_5_9_arguments_override: "--explicit-target-dependency-import-check error"
+ linux_5_10_arguments_override: "--explicit-target-dependency-import-check error"
+ linux_nightly_6_0_arguments_override: "--explicit-target-dependency-import-check error"
+ linux_nightly_main_enabled: false
+
+ integration-test:
+ name: Integration test
+ uses: apple/swift-nio/.github/workflows/swift_matrix.yml@main
+ with:
+ name: "Integration test"
+ matrix_linux_command: "apt-get update -yq && apt-get install -yq jq && ./scripts/run-integration-test.sh"
+ matrix_linux_5_8_enabled: false
+ matrix_linux_nightly_main_enabled: false
+
+ compatibility-test:
+ name: Compatibility test
+ runs-on: ubuntu-latest
+ container:
+ image: swift:latest
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v4
+ with:
+ persist-credentials: false
+ - name: Run OpenAPI document compatibilty test
+ env:
+ SWIFT_OPENAPI_COMPATIBILITY_TEST_ENABLE: "true"
+ SWIFT_OPENAPI_COMPATIBILITY_TEST_SKIP_BUILD: "true"
+ SWIFT_OPENAPI_COMPATIBILITY_TEST_FILTER: OpenAPIGeneratorReferenceTests.CompatibilityTest
+ SWIFT_OPENAPI_COMPATIBILITY_TEST_PARALLEL_CODEGEN: "true"
+ SWIFT_OPENAPI_COMPATIBILITY_TEST_NUM_BUILD_JOBS: 1
+ run: swift test --filter ${SWIFT_OPENAPI_COMPATIBILITY_TEST_FILTER}
+
+ example-packages:
+ name: Example packages
+ uses: apple/swift-nio/.github/workflows/swift_matrix.yml@main
+ with:
+ name: "Example packages"
+ matrix_linux_command: "./scripts/test-examples.sh"
+ matrix_linux_5_8_enabled: false
+ matrix_linux_nightly_main_enabled: false | Answered above. |
swift-openapi-generator | github_2023 | others | 604 | apple | simonjbeaumont | @@ -26,25 +26,25 @@ services:
| I hadn't actually considered removing them altogether but I guess the only downside to doing so is that the existing CI will immediately fail because it can't find them. Maybe that's fine since we want it turned off anyway.
@czechboy0 any objections to me just deleting all the docker-based CI files? |
swift-openapi-generator | github_2023 | others | 607 | apple | czechboy0 | @@ -83,7 +83,7 @@ extension _GenerateOptions {
try finalizeDiagnostics()
} catch let error as Diagnostic {
// Emit our nice Diagnostics message instead of relying on ArgumentParser output.
- diagnostics.emit(error)
+ try ErrorThrowingDiagnosticCollector(upstream: diagnostics).emit(error) | We should only create `ErrorThrowingDiagnosticCollector` in one place, not in the translate methods (those will already get a `DiagnosticCollector` value, which will already have this collector).
Just update the block around line 45 to something like:
```swift
let innerDiagnostics: any DiagnosticCollector & Sendable
if let diagnosticsOutputPath {
let _diagnostics = _YamlFileDiagnosticsCollector(url: diagnosticsOutputPath)
finalizeDiagnostics = _diagnostics.finalize
innerDiagnostics = _diagnostics
} else {
innerDiagnostics = StdErrPrintingDiagnosticCollector()
finalizeDiagnostics = {}
}
let diagnostics = ErrorThrowingDiagnosticCollector(upstream: innerDiagnostics)
```
And please remove all the other places where you're creating `ErrorThrowingDiagnosticCollector`. The only changes in the individual translate* files should be the adaptation to the `emit` method now throwing. |
swift-openapi-generator | github_2023 | others | 607 | apple | czechboy0 | @@ -110,7 +110,9 @@ func makeGeneratorPipeline(
}
let validateDoc = { (doc: OpenAPI.Document) -> OpenAPI.Document in
let validationDiagnostics = try validator(doc, config)
- for diagnostic in validationDiagnostics { diagnostics.emit(diagnostic) }
+ for diagnostic in validationDiagnostics {
+ try ErrorThrowingDiagnosticCollector(upstream: diagnostics).emit(diagnostic) | The `diagnostics: any DiagnosticCollector` (line 104) should already be a `ErrorThrowingDiagnosticCollector`, so this shouldn't be necessary (see my other comment at the bottom). |
swift-openapi-generator | github_2023 | others | 607 | apple | czechboy0 | @@ -165,7 +165,33 @@ public protocol DiagnosticCollector {
/// Submits a diagnostic to the collector.
/// - Parameter diagnostic: The diagnostic to submit. | Yup these changes look great 🙏 |
swift-openapi-generator | github_2023 | others | 607 | apple | czechboy0 | @@ -42,17 +42,21 @@ extension _GenerateOptions {
featureFlags: resolvedFeatureFlags
)
}
- let diagnostics: any DiagnosticCollector & Sendable
+ let innerDiagnostics: any DiagnosticCollector & Sendable
let finalizeDiagnostics: () throws -> Void
if let diagnosticsOutputPath {
- let _diagnostics = _YamlFileDiagnosticsCollector(url: diagnosticsOutputPath)
- finalizeDiagnostics = _diagnostics.finalize
- diagnostics = _diagnostics
+ let _diagnostics = preparedDiagnosticsCollector(url: diagnosticsOutputPath)
+ if let yamlCollector = _diagnostics as? _YamlFileDiagnosticsCollector {
+ finalizeDiagnostics = { try yamlCollector.finalize() }
+ } else {
+ finalizeDiagnostics = {}
+ }
+ innerDiagnostics = _diagnostics
} else {
- diagnostics = StdErrPrintingDiagnosticCollector()
+ innerDiagnostics = StdErrPrintingDiagnosticCollector()
finalizeDiagnostics = {}
}
-
+ let diagnostics = ErrorThrowingDiagnosticCollector(upstream: innerDiagnostics) | I was thinking you could move all this logic into the prepare... function, so that it can be called from tests and also from here.
The method would take an optional URL, depending on whether the user provided a diagnostic URL or not. But the whole diagnostics collector construction would happen in that method. |
swift-openapi-generator | github_2023 | others | 607 | apple | czechboy0 | @@ -114,6 +114,14 @@ let package = Package(
swiftSettings: swiftSettings
),
+ // Test Target for swift-openapi-generator
+ .testTarget(
+ name: "OpenAPIGeneratorTests",
+ dependencies: ["swift-openapi-generator"], | You also need to add an explicit dependency on ArgumentParser, the 5.9.0 CI pipeline is failing with:
```
/code/Tests/OpenAPIGeneratorTests/Test_GenerateOptions.swift:39: error: undefined reference to '$s14ArgumentParser17ParsableArgumentsPAAE5parseyxSaySSGSgKFZ'
``` |
swift-openapi-generator | github_2023 | others | 603 | apple | FranzBusch | @@ -5,8 +5,6 @@ on:
types: [opened, reopened, synchronize, ready_for_review]
jobs:
- call-reusable-pull-request-workflow:
- name: Checks
- uses: apple/swift-nio/.github/workflows/reusable_pull_request.yml@main
- with:
- benchmarks_linux_enabled: false
\ No newline at end of file
+ call-pull-request-soundness-workflow: | ```suggestion
soundness:
``` |
swift-openapi-generator | github_2023 | others | 591 | apple | simonjbeaumont | @@ -1,4 +1,4 @@
-#!/usr/bin/env bash
+#!/bin/bash | This is a script that devs or CI run. For devs, they want their environment to be taken into account. For CI we control the environment.
This can be useful for images that may have a Bash 3 and Bash 4, for example. |
swift-openapi-generator | github_2023 | others | 591 | apple | simonjbeaumont | @@ -9,4 +9,6 @@ jobs:
name: Checks
uses: apple/swift-nio/.github/workflows/reusable_pull_request.yml@main
with:
- benchmarks_linux_enabled: false
\ No newline at end of file
+ benchmarks_linux_enabled: false
+ unacceptable_language_check_enabled: false | Are we doing opt-out? Seems like it might be pretty bad to do that since we'll introduce CI breakages for adopters of the reusable workflow when we add new things that they don't want and/or can't use for some reason. |
swift-openapi-generator | github_2023 | others | 595 | apple | czechboy0 | @@ -645,7 +645,12 @@ struct TextBasedRenderer: RendererProtocol {
/// Renders the specified enum declaration.
func renderEnum(_ enumDesc: EnumDescription) {
- if enumDesc.isFrozen {
+ func shouldAnnotateAsFrozen(_ enumDesc: EnumDescription) -> Bool { | Could you break this method out and add unit tests for it, and update the reference tests as well please? |
swift-openapi-generator | github_2023 | others | 592 | apple | czechboy0 | @@ -0,0 +1,41 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+
+extension Components.Schemas.Greeting {
+ package func boxed(maxBoxWidth: Int = 80) -> Self { | 👏 |
swift-openapi-generator | github_2023 | others | 583 | apple | czechboy0 | @@ -0,0 +1,35 @@
+// swift-tools-version:5.9
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+import PackageDescription
+
+let package = Package(
+ name: "event-streams-client-example", | The package name needs updating. |
swift-openapi-generator | github_2023 | others | 583 | apple | czechboy0 | @@ -0,0 +1,38 @@
+// swift-tools-version:5.9
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+import PackageDescription
+
+let package = Package(
+ name: "bidirectional-event-streams-server-example",
+ platforms: [.macOS(.v10_15)],
+ dependencies: [
+ .package(url: "https://github.com/apple/swift-openapi-generator", from: "1.0.0"),
+ .package(url: "https://github.com/apple/swift-openapi-runtime", from: "1.2.0"),
+ // Hummingbird | ```suggestion
``` |
swift-openapi-generator | github_2023 | others | 583 | apple | czechboy0 | @@ -0,0 +1,44 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+import OpenAPIRuntime
+import OpenAPIHummingbird
+import Hummingbird
+import Foundation
+
+struct Handler: APIProtocol {
+
+ private let storage: StreamStorage = .init()
+
+ func getGreetingsStream(_ input: Operations.getGreetingsStream.Input) async throws -> Operations.getGreetingsStream.Output {
+ let eventStream = await self.storage.makeStream(input: input)
+ /// To keep it simple, using JSON Lines, as it most straightforward and easy way to have streams.
+ /// For SSE and JSON Sequences cases please check `event-streams-server-example`.
+ let responseBody = Operations.getGreetingsStream.Output.Ok.Body.application_jsonl(
+ .init(eventStream.asEncodedJSONLines(), length: .unknown, iterationBehavior: .single)
+ )
+ return .ok(.init(body: responseBody))
+ }
+ | ```suggestion
``` |
swift-openapi-generator | github_2023 | others | 468 | apple | PeterAdams-A | @@ -1,62 +1,69 @@
# Examples of using Swift OpenAPI Generator
-This directory contains examples of how to use Swift OpenAPI Generator and
-integrate with other packages in the ecosystem.
+This directory contains examples of how to use and
+integrate Swift OpenAPI Generator with other packages in the ecosystem.
-> **Disclaimer:** Many of these examples have been deliberately simplified and are
-> intended for illustrative purposes only.
+> Important: Many of these examples have been deliberately simplified and are intended for illustrative purposes only.
-## Getting started
+All the examples can be found in the [Examples](https://github.com/apple/swift-openapi-generator/tree/main/Examples) directory of the [Swift OpenAPI Generator](https://github.com/apple/swift-openapi-generator) repository.
-Each of the following packages shows an end-to-end working example with the given transport.
+To run an example locally, for example [hello-world-urlsession-client-example](https://github.com/apple/swift-openapi-generator/tree/main/Examples/hello-world-urlsession-client-example), clone the Swift OpenAPI Generator repository, and run the example. | Feels like it's begging for an "as below" other wise it almost reads as, to run this locally, clone and run it which doesn't sound hugely helpful :-) |
swift-openapi-generator | github_2023 | others | 458 | apple | czechboy0 | @@ -1,4 +1,4 @@
-# Curated Library Client
+# Curated library client module | Have we used the word "module" in any other example? |
swift-openapi-generator | github_2023 | others | 458 | apple | czechboy0 | @@ -1,4 +1,4 @@
-# A command plugin invocation Client
+# Manual code generation using the Swift package plugin | ```suggestion
# Manual code generation using the Swift package command plugin
```
|
swift-openapi-generator | github_2023 | others | 458 | apple | czechboy0 | @@ -1,4 +1,4 @@
-# Swagger UI Endpoints Server
+# Server with Swagger UI Endpoint | ```suggestion
# Server with Swagger UI Endpoints
```
There are 3 endpoints, right? The raw file and the HTML page, plus the redirect. |
swift-openapi-generator | github_2023 | others | 524 | apple | simonjbeaumont | @@ -14,7 +14,7 @@
// Emit a compiler error if this library is linked with a target in an adopter
// project.
-#if !(os(macOS) || os(Linux))
+#if !(os(macOS) || targetEnvironment(macCatalyst) || os(Linux)) | ```suggestion
// When compiling for Mac Catalyst, the plugin is (erroneously?) compiled with os(iOS).
#if !(os(macOS) || os(Linux) || (os(iOS) && targetEnvironment(macCatalyst)))
``` |
swift-openapi-generator | github_2023 | others | 242 | apple | glbrntt | @@ -13,39 +13,66 @@
//===----------------------------------------------------------------------===//
import OpenAPIKit
+/// The backing type of a raw enum.
+enum RawEnumBackingType {
+
+ /// Backed by a `String`.
+ case string
+
+ /// Backed by an `Int`.
+ case integer
+}
+
extension FileTranslator {
- /// Returns a declaration of the specified string-based enum schema.
+ /// Returns a declaration of the specified raw value-based enum schema.
/// - Parameters:
+ /// - backingType: The backing type of the enum.
/// - typeName: The name of the type to give to the declared enum.
/// - userDescription: A user-specified description from the OpenAPI
/// document.
/// - isNullable: Whether the enum schema is nullable.
/// - allowedValues: The enumerated allowed values.
- func translateStringEnum(
+ func translateRawEnum(
+ backingType: RawEnumBackingType,
typeName: TypeName,
userDescription: String?,
isNullable: Bool,
allowedValues: [AnyCodable]
) throws -> Declaration {
- let rawValues = try allowedValues.map(\.value)
+ let cases: [(String, LiteralDescription)] =
+ try allowedValues
+ .map(\.value)
.map { anyValue in
- // In nullable enum schemas, empty strings are parsed as Void.
- // This is unlikely to be fixed, so handling that case here.
- // https://github.com/apple/swift-openapi-generator/issues/118
- if isNullable && anyValue is Void {
- return ""
- }
- guard let string = anyValue as? String else {
- throw GenericError(message: "Disallowed value for a string enum '\(typeName)': \(anyValue)")
+ switch backingType {
+ case .string:
+ // In nullable enum schemas, empty strings are parsed as Void.
+ // This is unlikely to be fixed, so handling that case here.
+ // https://github.com/apple/swift-openapi-generator/issues/118
+ if isNullable && anyValue is Void {
+ return (swiftSafeName(for: ""), .string(""))
+ }
+ guard let rawValue = anyValue as? String else {
+ throw GenericError(message: "Disallowed value for a string enum '\(typeName)': \(anyValue)")
+ }
+ let caseName = swiftSafeName(for: rawValue)
+ return (caseName, .string(rawValue))
+ case .integer:
+ guard let rawValue = anyValue as? Int else {
+ throw GenericError(message: "Disallowed value for an integer enum '\(typeName)': \(anyValue)")
+ }
+ let caseName = "_\(rawValue)" | It feels slightly wrong prefixing the case with an underscore as we typically reserve that for not-actually-public but I don't have a better alternative to suggest. |
swift-openapi-generator | github_2023 | others | 509 | apple | simonjbeaumont | @@ -38,9 +38,7 @@ Another example is the generation of empty structs within the input or output ty
Some generators offer lots of options that affect the code generation process. In order to keep the project streamlined and maintainable, Swift OpenAPI Generator offers very few options.
-One concrete example of this is that users cannot configure the access modifier for generated code, nor does the generated code make any provision for namespace collisions in the target into which it is generated.
-
-Instead, users are advised to generate code into its own target, and use Swift's module system to separate the generated code from code that uses it.
+One concrete example of this is the lack of ability to configure the names of generated types, such as `APIProtocol`, or to customize how Swift names are computed from strings provided in the OpenAPI document. | Although we _do_ now allow configuration of the access modifier, one salient point above, that has been deleted in this patch, is still very relevant: we do not make any provision for namespace collisions in the target into which the code is generated. The advise of using a dedicated Swift module still applies, no? |
swift-openapi-generator | github_2023 | others | 500 | apple | simonjbeaumont | @@ -115,6 +272,9 @@ func validateDoc(_ doc: ParsedOpenAPIRepresentation, config: Config) throws -> [
(try? _OpenAPIGeneratorCore.ContentType(string: contentType)) != nil
}
+ let filteredDoc = try FilteredDocumentBuilder(document: doc).filter() | This filter hasn't been constructed from the user config so isn't quite what we're looking for.
However, it isn't necessary to do it here anyway because this function, `validateDoc(_:config:)`, is called as a post-transition hook after parsing the OpenAPI document _after_ the existing post-transition hook for filtering the doc[^1].
[^1]: https://github.com/apple/swift-openapi-generator/blob/85fec92ea3/Sources/_OpenAPIGeneratorCore/GeneratorPipeline.swift#L120 |
swift-openapi-generator | github_2023 | others | 471 | apple | czechboy0 | @@ -13,6 +13,58 @@
//===----------------------------------------------------------------------===//
import OpenAPIKit
+import Foundation
+
+/// Extracts content types from a ParsedOpenAPIRepresentation.
+///
+/// - Parameter doc: The OpenAPI document representation.
+/// - Returns: An array of strings representing content types extracted from requests and responses.
+func extractContentTypes(from doc: ParsedOpenAPIRepresentation) -> [String] {
+ let contentTypes: [String] = doc.paths.values.flatMap { pathValue -> [OpenAPI.ContentType.RawValue] in
+ guard case .b(let pathItem) = pathValue else { return [] }
+
+ let requestBodyContentTypes: [String] = pathItem.endpoints.map { $0.operation.requestBody }
+ .compactMap { (eitherRequest: Either<OpenAPI.Reference<OpenAPI.Request>, OpenAPI.Request>?) in
+ guard case .b(let actualRequest) = eitherRequest else { return nil }
+ return actualRequest.content.keys.first?.rawValue
+ }
+
+ let responseContentTypes: [String] = pathItem.endpoints.map { $0.operation.responses.values }
+ .flatMap { (response: [Either<OpenAPI.Reference<OpenAPI.Response>, OpenAPI.Response>]) in
+ response.compactMap { (eitherResponse: Either<OpenAPI.Reference<OpenAPI.Response>, OpenAPI.Response>) in
+ guard case .b(let actualResponse) = eitherResponse else { return nil }
+ return actualResponse.content.keys.first?.rawValue
+ }
+ }
+
+ return requestBodyContentTypes + responseContentTypes
+ }
+
+ return contentTypes
+}
+
+/// Validates an array of content types.
+///
+/// - Parameter contentTypes: An array of strings representing content types.
+/// - Throws: A Diagnostic error if any content type is invalid.
+func validateContentTypes(_ contentTypes: [String]) throws {
+ let mediaTypePattern = "^[a-zA-Z]+/[a-zA-Z][a-zA-Z-]*$" | To avoid duplicating similar logic, you can validate whether the content type is valid by trying to create a `_OpenAPIGeneratorCore.ContentType` value from the string, and if it fails, it's an invalid content type. This regex doesn't fully represent the requirements, and we don't want to have to keep multiple pieces of similar logic in sync manually. |
swift-openapi-generator | github_2023 | others | 471 | apple | czechboy0 | @@ -13,6 +13,58 @@
//===----------------------------------------------------------------------===//
import OpenAPIKit
+import Foundation
+
+/// Extracts content types from a ParsedOpenAPIRepresentation.
+///
+/// - Parameter doc: The OpenAPI document representation.
+/// - Returns: An array of strings representing content types extracted from requests and responses.
+func extractContentTypes(from doc: ParsedOpenAPIRepresentation) -> [String] { | You could change this to a visitor pattern, where you provide a closure with the signature `(String) -> Bool`, that returns `true` if the content type is valid. And this method would be responsible for walking all the places that have content types.
That way, you can then emit a good diagnostic about _which_ content type was invalid, and _where_ it was found. That's important for debugging. |
swift-openapi-generator | github_2023 | others | 471 | apple | czechboy0 | @@ -13,6 +13,58 @@
//===----------------------------------------------------------------------===//
import OpenAPIKit
+import Foundation
+
+/// Extracts content types from a ParsedOpenAPIRepresentation.
+///
+/// - Parameter doc: The OpenAPI document representation.
+/// - Returns: An array of strings representing content types extracted from requests and responses.
+func extractContentTypes(from doc: ParsedOpenAPIRepresentation) -> [String] {
+ let contentTypes: [String] = doc.paths.values.flatMap { pathValue -> [OpenAPI.ContentType.RawValue] in
+ guard case .b(let pathItem) = pathValue else { return [] }
+
+ let requestBodyContentTypes: [String] = pathItem.endpoints.map { $0.operation.requestBody }
+ .compactMap { (eitherRequest: Either<OpenAPI.Reference<OpenAPI.Request>, OpenAPI.Request>?) in
+ guard case .b(let actualRequest) = eitherRequest else { return nil }
+ return actualRequest.content.keys.first?.rawValue
+ }
+
+ let responseContentTypes: [String] = pathItem.endpoints.map { $0.operation.responses.values }
+ .flatMap { (response: [Either<OpenAPI.Reference<OpenAPI.Response>, OpenAPI.Response>]) in
+ response.compactMap { (eitherResponse: Either<OpenAPI.Reference<OpenAPI.Response>, OpenAPI.Response>) in
+ guard case .b(let actualResponse) = eitherResponse else { return nil }
+ return actualResponse.content.keys.first?.rawValue
+ }
+ }
+
+ return requestBodyContentTypes + responseContentTypes
+ }
+ | We should also validate the content types in `#/components/requestBodies` and `#/components/responses` here. |
swift-openapi-generator | github_2023 | others | 471 | apple | czechboy0 | @@ -14,6 +14,71 @@
import OpenAPIKit
+/// Validates all content types from an OpenAPI document represented by a ParsedOpenAPIRepresentation.
+///
+/// This function iterates through the paths, endpoints, and components of the OpenAPI document,
+/// checking and reporting any invalid content types using the provided validation closure.
+///
+/// - Parameters:
+/// - doc: The OpenAPI document representation.
+/// - validate: A closure to validate each content type.
+/// - Throws: An error with diagnostic information if any invalid content types are found.
+func validateContentTypes(in doc: ParsedOpenAPIRepresentation, validate: (String) -> Bool) throws {
+ for (path, pathValue) in doc.paths {
+ guard case .b(let pathItem) = pathValue else { continue }
+ for endpoint in pathItem.endpoints {
+
+ if let eitherRequest = endpoint.operation.requestBody {
+ if case .b(let actualRequest) = eitherRequest {
+ for contentType in actualRequest.content.keys {
+ if !validate(contentType.rawValue) {
+ throw Diagnostic.error(
+ message:
+ "Invalid content type string: '\(contentType.rawValue)' found in requestBody at path '\(path.rawValue)'. Must have 2 components separated by a slash '<type>/<subtype>'.\n" | ```suggestion
"Invalid content type string: '\(contentType.rawValue)' found in requestBody at path '\(path.rawValue), method: \(endpoint.method.rawValue)'. Must have 2 components separated by a slash '<type>/<subtype>'.\n"
``` |
swift-openapi-generator | github_2023 | others | 471 | apple | czechboy0 | @@ -14,6 +14,71 @@
import OpenAPIKit
+/// Validates all content types from an OpenAPI document represented by a ParsedOpenAPIRepresentation.
+///
+/// This function iterates through the paths, endpoints, and components of the OpenAPI document,
+/// checking and reporting any invalid content types using the provided validation closure.
+///
+/// - Parameters:
+/// - doc: The OpenAPI document representation.
+/// - validate: A closure to validate each content type.
+/// - Throws: An error with diagnostic information if any invalid content types are found.
+func validateContentTypes(in doc: ParsedOpenAPIRepresentation, validate: (String) -> Bool) throws {
+ for (path, pathValue) in doc.paths {
+ guard case .b(let pathItem) = pathValue else { continue }
+ for endpoint in pathItem.endpoints {
+
+ if let eitherRequest = endpoint.operation.requestBody {
+ if case .b(let actualRequest) = eitherRequest {
+ for contentType in actualRequest.content.keys {
+ if !validate(contentType.rawValue) {
+ throw Diagnostic.error(
+ message:
+ "Invalid content type string: '\(contentType.rawValue)' found in requestBody at path '\(path.rawValue)'. Must have 2 components separated by a slash '<type>/<subtype>'.\n"
+ )
+ }
+ }
+ }
+ }
+
+ for eitherResponse in endpoint.operation.responses.values {
+ if case .b(let actualResponse) = eitherResponse {
+ for contentType in actualResponse.content.keys {
+ if !validate(contentType.rawValue) {
+ throw Diagnostic.error(
+ message:
+ "Invalid content type string: '\(contentType.rawValue)' found in responses at path '\(path.rawValue)'. Must have 2 components separated by a slash '<type>/<subtype>'.\n" | ```suggestion
"Invalid content type string: '\(contentType.rawValue)' found in responses at path '\(path.rawValue), method: \(endpoint.method.rawValue)'. Must have 2 components separated by a slash '<type>/<subtype>'.\n"
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.