Skip to content

Commit

Permalink
add static "make" method
Browse files Browse the repository at this point in the history
  • Loading branch information
gereons committed May 22, 2024
1 parent e699cff commit a47874b
Show file tree
Hide file tree
Showing 6 changed files with 91 additions and 2 deletions.
49 changes: 49 additions & 0 deletions Sources/Generator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,26 @@ final class Generator {
generateEnum(name: modelName, cases: cases)
}

private func joinAllProperties(for modelName: String, allOf: [RefOrSchema], parentSchema: Schema) -> [SwiftProperty] {
var properties = [SwiftProperty]()
for refOrSchema in allOf {
switch refOrSchema {
case .schema(let schema):
properties.append(contentsOf: schema.swiftProperties(for: modelName, parentRequired: parentSchema.required))
case .ref(let ref):
let refType = ref.swiftType()
guard let schema = schemas[refType.name] else {
fatalError("\(modelName): no schema for \(refType) found")
}
if schema.allOf != nil {
fatalError("\(modelName): multi-level interitance is not supported")
}
properties.append(contentsOf: schema.swiftProperties(for: modelName, parentRequired: parentSchema.required))
}
}
return properties
}

private func generateAllOf(for modelName: String,
allOf: [RefOrSchema],
addComment: Bool,
Expand Down Expand Up @@ -160,6 +180,9 @@ final class Generator {
generateTypeEnums(schema: schema)
}
}

// static func make()
generateMakeMethod(joinAllProperties(for: modelName, allOf: allOf, parentSchema: schema))
}

if let ref = getRef(from: allOf) {
Expand Down Expand Up @@ -191,6 +214,25 @@ final class Generator {
generateInitFromDecoder(properties)

generateTypeEnums(schema: schema)

// make method
generateMakeMethod(properties)
}
}

private func generateMakeMethod(_ properties: [SwiftProperty]) {
print("")
print("public static func make(", terminator: "")
let params = properties
.map {
"\($0.name): \($0.type.propertyType) = \($0.type.defaultValue)"
}
.joined(separator: ", ")
print(params, terminator: "")
block(") -> Self") {
print("self.init(", terminator: "")
print(properties.map { "\($0.name): \($0.name)"}.joined(separator: ", "), terminator: "")
print(")")
}
}

Expand Down Expand Up @@ -304,6 +346,13 @@ final class Generator {
}
print("}")
}

// make method
print("")
block("public static func make() -> Self") {
guard let first = discriminatorCases.first else { return }
print(".\(first.enumCase)(.make())")
}
}

print("")
Expand Down
2 changes: 1 addition & 1 deletion Sources/ModelGen.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import ArgumentParser

@main
struct ModelGen: ParsableCommand {
static let version = "v0.1.8"
static let version = "v0.1.9"

@Option(name: .shortAndLong, help: "name of the input file")
var input: String = "~/Developer/onvista/modelgen/swagger.json"
Expand Down
17 changes: 17 additions & 0 deletions Sources/SwiftProperty.swift
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,21 @@ struct SwiftType {
let closeBracket = (isArray ? "]" : "")
return "\(openBracket)\(name)\(closeBracket)"
}

var defaultValue: String {
if isOptional {
return "nil"
}
if isArray {
return "[]"
}
switch name {
case "Int": return "0"
case "Double": return "0.0"
case "Bool": return "false"
case "String": return "\"\""
case "Date": return ".init()"
default: return ".make()"
}
}
}
8 changes: 8 additions & 0 deletions Tests/InheritanceTest1.swift
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,10 @@ final class InheritanceTest1: XCTestCase {
case .dog(let obj): try obj.encode(to: encoder)
}
}
public static func make() -> Self {
.cat(.make())
}
}
public protocol AnimalProtocol {
Expand Down Expand Up @@ -122,6 +126,10 @@ public struct Dog: Codable {
self.status = try container.decode(AnimalType.self, forKey: .status)
self.barks = try container.decode(Bool.self, forKey: .barks)
}
public static func make(status: AnimalType = .make(), barks: Bool = false) -> Self {
self.init(status: status, barks: barks)
}
}
extension Dog: AnimalProtocol {}
Expand Down
12 changes: 12 additions & 0 deletions Tests/InheritanceTest2.swift
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,10 @@ final class InheritanceTest2: XCTestCase {
case .animal(let obj): try obj.encode(to: encoder)
}
}
public static func make() -> Self {
.cat(.make())
}
}
public protocol AnimalProtocol {
Expand Down Expand Up @@ -125,6 +129,10 @@ final class InheritanceTest2: XCTestCase {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.status = try container.decode(String.self, forKey: .status)
}
public static func make(status: String = "") -> Self {
self.init(status: status)
}
}
extension AnimalBase: AnimalProtocol {}
Expand Down Expand Up @@ -175,6 +183,10 @@ public struct Dog: Codable {
case _unknownCase
public static let unknownCase = Self._unknownCase
}
public static func make(status: String = "", array: [Foo]? = nil, barks: Bool = false, foobar: Foobar? = nil) -> Self {
self.init(status: status, array: array, barks: barks, foobar: foobar)
}
}
extension Dog: AnimalProtocol {}
Expand Down
5 changes: 4 additions & 1 deletion Tests/PODTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,10 @@ final class PODTest: XCTestCase {
case _unknownCase
public static let unknownCase = Self._unknownCase
}
public static func make(bool: Bool = false, double: Double? = nil, foobar: Foobar? = nil, ints: [Int] = [], lossy: [Foo]? = nil, ref: Object? = nil, string: String? = nil) -> Self {
self.init(bool: bool, double: double, foobar: foobar, ints: ints, lossy: lossy, ref: ref, string: string)
}
}
"""

Expand All @@ -119,5 +123,4 @@ final class PODTest: XCTestCase {
let output = String(generator.buffer.dropLast(1))
XCTAssertEqual(output, multiline: expected)
}

}

0 comments on commit a47874b

Please sign in to comment.