-
Notifications
You must be signed in to change notification settings - Fork 763
Expand file tree
/
Copy pathContexts.swift
More file actions
416 lines (372 loc) · 13.9 KB
/
Contexts.swift
File metadata and controls
416 lines (372 loc) · 13.9 KB
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//
// GenumKit
// Copyright (c) 2015 Olivier Halligon
// MIT Licence
//
import Stencil
private func uppercaseFirst(_ string: String) -> String {
guard let first = string.characters.first else {
return string
}
return String(first).uppercased() + String(string.characters.dropFirst())
}
private extension String {
var newlineEscaped: String {
return self
.replacingOccurrences(of: "\n", with: "\\n")
.replacingOccurrences(of: "\r", with: "\\r")
}
}
/* MARK: - Stencil Context for Colors
- `enumName`: `String` — name of the enum to generate
- `colors`: `Array` of:
- `name` : `String` — name of each color
- `rgb` : `String` — hex value of the form RRGGBB (like "ff6600")
- `rgba` : `String` — hex value of the form RRGGBBAA (like "ff6600cc")
- `red` : `String` — hex value of the red component
- `green`: `String` — hex value of the green component
- `blue` : `String` — hex value of the blue component
- `alpha`: `String` — hex value of the alpha component
*/
extension ColorsFileParser {
public func stencilContext(enumName: String = "ColorName") -> Context {
let colorMap = colors.map({ (color: (name: String, value: UInt32)) -> [String:String] in
let name = color.name.trimmingCharacters(in: CharacterSet.whitespaces)
let hex = "00000000" + String(color.value, radix: 16)
let hexChars = Array(hex.characters.suffix(8))
let comps = (0..<4).map { idx in String(hexChars[idx*2...idx*2+1]) }
return [
"name": name,
"rgba": String(hexChars[0..<8]),
"rgb": String(hexChars[0..<6]),
"red": comps[0],
"green": comps[1],
"blue": comps[2],
"alpha": comps[3],
]
}).sorted { $0["name"] ?? "" < $1["name"] ?? "" }
return Context(dictionary: ["enumName": enumName, "colors": colorMap], namespace: GenumNamespace())
}
}
/* MARK: - Stencil Context for Images
- `enumName`: `String` — name of the enum to generate
- `images`: `Array<String>` — list of image names
*/
extension AssetsCatalogParser {
public func stencilContext(enumName: String = "Asset") -> Context {
let images = justValues(entries: entries)
let imagesStructured = structure(entries: entries)
return Context(
dictionary: [
"enumName": enumName,
"images": images,
"structuredImages": imagesStructured
],
namespace: GenumNamespace()
)
}
private func justValues(entries: [Entry]) -> [String] {
var result = [String]()
for entry in entries {
switch entry {
case let .namespace(name: name, items: items):
result += justValues(entries: items)
case let .image(name: _, value: value):
result += [value]
}
}
return result
}
private func structure(entries: [Entry], currentLevel: Int = 0, maxLevel: Int = 5) -> [[String: Any]] {
return entries.map { entry in
switch entry {
case let .namespace(name: name, items: items):
if currentLevel + 1 >= maxLevel {
return [
"name": name,
"items": flatten(entries: items)
]
} else {
return [
"name": name,
"items": structure(entries: items, currentLevel: currentLevel + 1, maxLevel: maxLevel)
]
}
case let .image(name: name, value: value):
return [
"name": name,
"value": value
]
}
}
}
private func flatten(entries: [Entry]) -> [[String: Any]] {
var result = [[String: Any]]()
for entry in entries {
switch entry {
case let .namespace(name: name, items: items):
result += flatten(entries: items).map { item in
return [
"name": "\(name)/\(item["name"]!)",
"value": item["value"]!
]
}
case let .image(name: name, value: value):
result += [[
"name": name,
"value": value
]]
}
}
return result
}
}
/* MARK: - Stencil Context for Storyboards
- `sceneEnumName`: `String`
- `segueEnumName`: `String`
- `extraImports`: `Array` of `String`
- `storyboards`: `Array` of:
- `name`: `String`
- `initialScene`: `Dictionary` (absent if not specified)
- `customClass`: `String` (absent if generic UIViewController/NSViewController)
- `isBaseViewController`: `Bool`, indicate if the baseType is 'viewController' or anything else
- `baseType`: `String` (absent if class is a custom class).
The base class type on which the initial scene is base.
Possible values include 'ViewController', 'NavigationController', 'TableViewController'…
- `scenes`: `Array` (absent if empty)
- `identifier`: `String`
- `customClass`: `String` (absent if generic UIViewController/NSViewController)
- `isBaseViewController`: `Bool`, indicate if the baseType is 'ViewController' or anything else
- `baseType`: `String` (absent if class is a custom class). The base class type on which a scene is base.
Possible values include 'ViewController', 'NavigationController', 'TableViewController'…
- `segues`: `Array` (absent if empty)
- `identifier`: `String`
- `class`: `String` (absent if generic UIStoryboardSegue)
*/
extension StoryboardParser {
public func stencilContext(sceneEnumName: String = "StoryboardScene",
segueEnumName: String = "StoryboardSegue",
extraImports: [String] = []) -> Context {
let storyboards = Set(storyboardsScenes.keys).union(storyboardsSegues.keys).sorted(by: <)
let storyboardsMap = storyboards.map { (storyboardName: String) -> [String:Any] in
var sbMap: [String:Any] = ["name": storyboardName]
// Initial Scene
if let initialScene = initialScenes[storyboardName] {
let initial: [String:Any]
if let customClass = initialScene.customClass {
initial = ["customClass": customClass]
} else {
initial = [
"baseType": uppercaseFirst(initialScene.tag),
"isBaseViewController": initialScene.tag == "viewController"
]
}
sbMap["initialScene"] = initial
}
// All Scenes
if let scenes = storyboardsScenes[storyboardName] {
sbMap["scenes"] = scenes
.sorted(by: {$0.storyboardID < $1.storyboardID})
.map { (scene: Scene) -> [String:Any] in
if let customClass = scene.customClass {
return ["identifier": scene.storyboardID, "customClass": customClass]
} else if scene.tag == "viewController" {
return [
"identifier": scene.storyboardID,
"baseType": uppercaseFirst(scene.tag),
"isBaseViewController": scene.tag == "viewController"
]
}
return ["identifier": scene.storyboardID, "baseType": uppercaseFirst(scene.tag)]
}
}
// All Segues
if let segues = storyboardsSegues[storyboardName] {
sbMap["segues"] = segues
.sorted(by: {$0.segueID < $1.segueID})
.map { (segue: Segue) -> [String:String] in
["identifier": segue.segueID, "customClass": segue.customClass ?? ""]
}
}
return sbMap
}
return Context(
dictionary: [
"sceneEnumName": sceneEnumName,
"segueEnumName": segueEnumName,
"extraImports": extraImports,
"storyboards": storyboardsMap
],
namespace: GenumNamespace()
)
}
}
/* MARK: - Stencil Context for Strings
- `enumName`: `String`
- `tableName`: `String` - name of the `.strings` file (usually `"Localizable"`)
- `strings`: `Array`
- `key`: `String`
- `translation`: `String`
- `params`: `Dictionary` — defined only if localized string has parameters; contains the following entries:
- `count`: `Int` — number of parameters
- `types`: `Array<String>` containing types like `"String"`, `"Int"`, etc
- `declarations`: `Array<String>` containing declarations like `"let p0"`, `"let p1"`, etc
- `names`: `Array<String>` containing parameter names like `"p0"`, `"p1"`, etc
- `typednames`: Array<String>` containing typed declarations like `"let p0: String`", `"let p1: Int"`, etc
- `keytail`: `String` containing the rest of the key after the next first `.`
(useful to do recursion when splitting keys against `.` for structured templates)
- `structuredStrings`: `Dictionary` - contains strings structured by keys separated by '.' syntax
*/
extension StringsFileParser {
public func stencilContext(enumName: String = "L10n", tableName: String = "Localizable") -> Context {
let entryToStringMapper = { (entry: Entry, keyPath: [String]) -> [String: Any] in
var keyStructure = entry.keyStructure
Array(0..<keyPath.count).forEach { _ in keyStructure.removeFirst() }
let keytail = keyStructure.joined(separator: ".")
if entry.types.count > 0 {
let params: [String: Any] = [
"count": entry.types.count,
"types": entry.types.map { $0.rawValue },
"declarations": entry.types.indices.map { "let p\($0)" },
"names": entry.types.indices.map { "p\($0)" },
"typednames": entry.types.enumerated().map { "p\($0): \($1.rawValue)" }
]
return ["key": entry.key,
"translation": entry.translation.newlineEscaped,
"params": params,
"keytail": keytail
]
} else {
return ["key": entry.key,
"translation": entry.translation.newlineEscaped,
"keytail": keytail
]
}
}
let strings = entries
.sorted { $0.key.caseInsensitiveCompare($1.key) == .orderedAscending }
.map { entryToStringMapper($0, []) }
let structuredStrings = structure(
entries: entries,
usingMapper: entryToStringMapper,
currentLevel: 0,
maxLevel: 5
)
return Context(dictionary:
[
"enumName": enumName,
"tableName": tableName,
"strings": strings,
"structuredStrings": structuredStrings
],
namespace: GenumNamespace()
)
}
private func normalize(_ string: String) -> String {
let components = string.components(separatedBy: CharacterSet(charactersIn: "-_"))
return components.map { $0.capitalized }.joined(separator: "")
}
typealias Mapper = (_ entry: Entry, _ keyPath: [String]) -> [String: Any]
private func structure(
entries: [Entry],
atKeyPath keyPath: [String] = [],
usingMapper mapper: @escaping Mapper,
currentLevel: Int,
maxLevel: Int) -> [String: Any] {
var structuredStrings: [String: Any] = [:]
let strings = entries
.filter { $0.keyStructure.count == keyPath.count+1 }
.sorted { $0.key.lowercased() < $1.key.lowercased() }
.map { mapper($0, keyPath) }
if !strings.isEmpty {
structuredStrings["strings"] = strings
}
if let lastKeyPathComponent = keyPath.last {
structuredStrings["name"] = lastKeyPathComponent
}
var subenums: [[String: Any]] = []
let nextLevelKeyPaths: [[String]] = entries
.filter({ $0.keyStructure.count > keyPath.count+1 })
.map({ Array($0.keyStructure.prefix(keyPath.count+1)) })
// make key paths unique
let uniqueNextLevelKeyPaths = Array(Set(
nextLevelKeyPaths.map { keyPath in
keyPath.map({
$0.capitalized.replacingOccurrences(of: "-", with: "_")
}).joined(separator: ".")
}))
.sorted()
.map { $0.components(separatedBy: ".") }
for nextLevelKeyPath in uniqueNextLevelKeyPaths {
let entriesInKeyPath = entries.filter {
Array($0.keyStructure.map(normalize).prefix(nextLevelKeyPath.count)) == nextLevelKeyPath.map(normalize)
}
if currentLevel >= maxLevel {
subenums.append(
flattenedStrings(fromEnteries: entries,
atKeyPath: nextLevelKeyPath,
usingMapper: mapper,
level: currentLevel+1
)
)
} else {
subenums.append(
structure(entries: entriesInKeyPath,
atKeyPath: nextLevelKeyPath,
usingMapper: mapper,
currentLevel: currentLevel+1,
maxLevel: maxLevel)
)
}
}
if !subenums.isEmpty {
structuredStrings["subenums"] = subenums
}
return structuredStrings
}
private func flattenedStrings(
fromEnteries entries: [Entry],
atKeyPath keyPath: [String],
usingMapper mapper: @escaping Mapper,
level: Int) -> [String: Any] {
var structuredStrings: [String: Any] = [:]
let strings = entries
.filter { $0.keyStructure.count >= keyPath.count+1 }
.map { mapper($0, keyPath) }
if !strings.isEmpty {
structuredStrings["strings"] = strings
}
if let lastKeyPathComponent = keyPath.last {
structuredStrings["name"] = lastKeyPathComponent
}
return structuredStrings
}
}
/* MARK: - Stencil Context for Fonts
- `enumName`: `String`
- `families`: `Array`
- `name`: `String`
- `fonts`: `Array`
- `style`: `String`
- `name`: `String`
*/
extension FontsFileParser {
public func stencilContext(enumName: String = "FontFamily") -> Context {
// turn into array of dictionaries
let families = entries.map { (name: String, family: Set<Font>) -> [String: Any] in
let fonts = family.map { (font: Font) -> [String: String] in
// Font
return [
"style": font.style,
"fontName": font.postScriptName
]
}.sorted { $0["fontName"] ?? "" < $1["fontName"] ?? "" }
// Family
return [
"name": name,
"fonts": fonts
]
}.sorted { $0["name"] as? String ?? "" < $1["name"] as? String ?? "" }
return Context(dictionary: ["enumName": enumName, "families": families], namespace: GenumNamespace())
}
}