This repository was archived by the owner on Mar 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathQueryKit.swift
210 lines (168 loc) · 5.31 KB
/
QueryKit.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
import Darwin.libc
import CoreData
import Commander
import PathKit
import Stencil
extension Path {
static var processPath: Path {
if ProcessInfo.processInfo.arguments[0].components(separatedBy: Path.separator).count > 1 {
return Path.current + ProcessInfo.processInfo.arguments[0]
}
let PATH = ProcessInfo.processInfo.environment["PATH"]!
let paths = PATH.components(separatedBy: ":").map {
Path($0) + ProcessInfo.processInfo.arguments[0]
}.filter { $0.exists }
return paths.first!
}
public static var defaultTemplatePath: Path {
return processPath + "../../share/querykit/template.swift"
}
}
func compileCoreDataModel(_ source: Path) -> Path {
let destinationExtension = source.`extension`!.hasSuffix("d") ? ".momd" : ".mom"
let filename = source.lastComponentWithoutExtension + destinationExtension
let destination = try! Path.uniqueTemporary() + Path(filename)
Process.launchedProcess(
launchPath: "/usr/bin/xcrun",
arguments: ["momc", source.absolute().string, destination.absolute().string]
).waitUntilExit()
return destination
}
struct AttributeDescription {
let name: String
let type: String
init(name: String, type: String) {
self.name = name
self.type = type
}
}
extension NSAttributeDescription {
var qkClassName: String? {
switch attributeType {
case .booleanAttributeType:
return "Bool"
case .stringAttributeType:
return "String"
default:
return attributeValueClassName
}
}
var qkAttributeDescription: AttributeDescription? {
if let className = qkClassName {
return AttributeDescription(name: name, type: className)
}
return nil
}
}
extension NSRelationshipDescription {
var qkAttributeDescription: AttributeDescription? {
if let destinationEntity = destinationEntity {
var type = destinationEntity.qk_className
if isToMany {
type = "Set<\(type)>"
if isOrdered {
type = "NSOrderedSet"
}
}
return AttributeDescription(name: name, type: type)
}
return nil
}
}
extension NSEntityDescription {
var qk_className: String {
if managedObjectClassName.hasPrefix(".") {
// "Current Module"
return managedObjectClassName.substring(from: managedObjectClassName.index(after: managedObjectClassName.startIndex))
}
return managedObjectClassName
}
func qk_hasSuperProperty(_ name: String) -> Bool {
if let superentity = superentity {
if superentity.qk_className != "NSManagedObject" && superentity.propertiesByName[name] != nil {
return true
}
return superentity.qk_hasSuperProperty(name)
}
return false
}
}
class CommandError : Error {
let description: String
init(description: String) {
self.description = description
}
}
func render(entity: NSEntityDescription, destination: Path, template: Template) throws {
let attributes = entity.properties.compactMap { property -> AttributeDescription? in
if entity.qk_hasSuperProperty(property.name) {
return nil
}
if let attribute = property as? NSAttributeDescription {
return attribute.qkAttributeDescription
} else if let relationship = property as? NSRelationshipDescription {
return relationship.qkAttributeDescription
}
return nil
}
let context: [String: Any] = [
"className": entity.qk_className,
"isAbstract": entity.isAbstract,
"attributes": attributes,
"entityName": entity.name ?? "Unknown",
]
try destination.write(try template.render(context))
}
func render(model: NSManagedObjectModel, destination: Path, templatePath: Path) throws {
if !destination.exists {
try destination.mkpath()
}
for entity in model.entities {
let loader = FileSystemLoader(paths: [templatePath.parent().absolute()])
let environment = Environment(loader: loader)
let template = try environment.loadTemplate(name: templatePath.lastComponent)
let className = entity.qk_className
if className == "NSManagedObject" {
let name = entity.name ?? "Unknown"
print("-> Skipping entity '\(name)', doesn't use a custom class.")
continue
}
let destinationFile = destination + (className + "+QueryKit.swift")
do {
try render(entity: entity, destination: destinationFile, template: template)
print("-> Generated '\(className)' '\(destinationFile)'")
} catch {
print(error)
}
}
}
public func generate(model: Path, output: Path, template: Path) throws {
let compiledModel = compileCoreDataModel(model)
let modelURL = URL(fileURLWithPath: compiledModel.description)
let model = NSManagedObjectModel(contentsOf: modelURL)!
try render(model: model, destination: output, templatePath: template)
}
extension Path: ArgumentConvertible {
public init(parser: ArgumentParser) throws {
if let path = parser.shift() {
self.init(path)
} else {
throw ArgumentError.missingValue(argument: nil)
}
}
}
public func isReadable(_ path: Path) -> Path {
if !path.isReadable {
print("'\(path)' does not exist or is not readable.")
exit(1)
}
return path
}
public func isCoreDataModel(_ path: Path) -> Path {
let ext = path.`extension`
if ext == "xcdatamodel" || ext == "xcdatamodeld" {
return isReadable(path)
}
print("'\(path)' is not a Core Data model.")
exit(1)
}