Skip to content

Allow substituting types #764

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,21 @@ extension TypesFileTranslator {
)
)
}
if let substituteTypeName = schema.vendorExtensions["x-swift-open-api-substitute-type"]?.value
as? String
{
try diagnostics.emit(.note(message: "Substituting type \(typeName) with \(substituteTypeName)"))
let substitutedType = TypeName(swiftKeyPath: substituteTypeName.components(separatedBy: ".")).asUsage

let typealiasDecl = try translateTypealias(
named: typeName,
userDescription: overrides.userDescription ?? schema.description,
to: substitutedType.withOptional(
overrides.isOptional ?? typeMatcher.isOptional(schema, components: components)
)
)
return [typealiasDecl]
}

// If this type maps to a referenceable schema, define a typealias
if let builtinType = try typeMatcher.tryMatchReferenceableType(for: schema, components: components) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,30 @@ class Test_translateSchemas: Test_Core {
XCTAssertEqual(collector.diagnostics.map(\.description), diagnosticDescriptions)
}
}

func testSchemaTypeSubstitution() throws {
let typeName = TypeName(swiftKeyPath: ["Foo"])

let schema = try loadSchemaFromYAML(
#"""
type: string
x-swift-open-api-substitute-type: MyLibrary.MyCustomType
"""#
)
let collector = AccumulatingDiagnosticCollector()
let translator = makeTranslator(diagnostics: collector)
let translated = try translator.translateSchema(typeName: typeName, schema: schema, overrides: .none)

XCTAssertEqual(
collector.diagnostics.map(\.description),
["note: Substituting type Foo with MyLibrary.MyCustomType"]
)
XCTAssertTrue(translated.count == 1, "Should have one translated schema")
guard case let .typealias(typeAliasDescription) = translated.first?.strippingTopComment else {
XCTFail("Expected typealias description got")
return
}
XCTAssertEqual(typeAliasDescription.name, "Foo")
XCTAssertEqual(typeAliasDescription.existingType, .member(["MyLibrary", "MyCustomType"]))
}
}