Skip to content

Commit

Permalink
feat: explicit allCases list
Browse files Browse the repository at this point in the history
Adds an explicit `allCases` list when the enum contains cases that
have a deprecation annotation. In that case, the compiler cannot
synthesize the list automatically as usual, requiring the codegen
to provide an explicit list.
  • Loading branch information
TizianoCoroneo committed Oct 5, 2022
1 parent e4c13f5 commit 853b23d
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
30 changes: 30 additions & 0 deletions Sources/ApolloCodegenLib/Templates/EnumTemplate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,32 @@ struct EnumTemplate: TemplateRenderer {
\(graphqlEnum.values.compactMap({
enumCase(for: $0)
}), separator: "\n")
\(if: containsDeprecationAnnotations, allCasesList)
}
"""
)
}

private var containsDeprecationAnnotations: Bool {
config.options.deprecatedEnumCases == .include
&& config.options.warningsOnDeprecatedUsage == .include
&& !graphqlEnum.values.allSatisfy { !$0.isDeprecated }
}

private var allCasesList: TemplateString {
"""
static var allCases: [\(graphqlEnum.name.firstUppercased)] {
[
\(graphqlEnum.values.compactMap({
enumCaseValue(for: $0)
}), separator: ",\n")
]
}
"""
}

private func enumCase(for graphqlEnumValue: GraphQLEnumValue) -> TemplateString? {
if config.options.deprecatedEnumCases == .exclude && graphqlEnumValue.isDeprecated {
return nil
Expand All @@ -39,6 +59,16 @@ struct EnumTemplate: TemplateRenderer {
"""
}

private func enumCaseValue(for graphqlEnumValue: GraphQLEnumValue) -> TemplateString? {
if config.options.deprecatedEnumCases == .exclude && graphqlEnumValue.isDeprecated {
return nil
}

return """
.\(graphqlEnumValue.name.rendered(as: .swiftEnumCase, config: config.config))
"""
}

private func caseDefinition(for graphqlEnumValue: GraphQLEnumValue) -> TemplateString {
"""
case \(graphqlEnumValue.name.rendered(as: .swiftEnumCase, config: config.config))\
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,14 @@ class EnumTemplateTests: XCTestCase {
@available(*, deprecated, message: "Deprecated for tests")
case two = "TWO"
case three = "THREE"
static var allCases: [TestEnum] {
[
.one,
.two,
.three
]
}
}
"""
Expand Down Expand Up @@ -523,6 +531,14 @@ class EnumTemplateTests: XCTestCase {
case two = "TWO"
@available(*, deprecated, message: "Deprecated for tests")
case three = "THREE"
static var allCases: [TestEnum] {
[
.one,
.two,
.three
]
}
}
"""
Expand Down

0 comments on commit 853b23d

Please sign in to comment.