forked from krzyzanowskim/Natalie
-
Notifications
You must be signed in to change notification settings - Fork 0
/
natalie.swift
executable file
·967 lines (835 loc) · 31.8 KB
/
natalie.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
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
#!/usr/bin/env xcrun -sdk macosx swift
//
// Natalie - Storyboard Generator Script
//
// Generate swift file based on storyboard files
//
// Usage:
// natalie.swift Main.storyboard > Storyboards.swift
// natalie.swift path/toproject/with/storyboards > Storyboards.swift
//
// Licence: MIT
// Author: Marcin Krzyżanowski http://blog.krzyzanowskim.com
//
//MARK: SWXMLHash
//
// SWXMLHash.swift
//
// Copyright (c) 2014 David Mohundro
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
let rootElementName = "SWXMLHash_Root_Element"
/// Simple XML parser.
public class SWXMLHash {
/**
Method to parse XML passed in as a string.
:param: xml The XML to be parsed
:returns: An XMLIndexer instance that is used to look up elements in the XML
*/
class public func parse(xml: String) -> XMLIndexer {
return parse((xml as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
}
/**
Method to parse XML passed in as an NSData instance.
:param: xml The XML to be parsed
:returns: An XMLIndexer instance that is used to look up elements in the XML
*/
class public func parse(data: NSData) -> XMLIndexer {
var parser = XMLParser()
return parser.parse(data)
}
class public func lazy(xml: String) -> XMLIndexer {
return lazy((xml as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
}
class public func lazy(data: NSData) -> XMLIndexer {
var parser = LazyXMLParser()
return parser.parse(data)
}
}
struct Stack<T> {
var items = [T]()
mutating func push(item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()
}
mutating func removeAll() {
items.removeAll(keepCapacity: false)
}
func top() -> T {
return items[items.count - 1]
}
}
class LazyXMLParser : NSObject, NSXMLParserDelegate {
override init() {
super.init()
}
var root = XMLElement(name: rootElementName)
var parentStack = Stack<XMLElement>()
var elementStack = Stack<String>()
var data: NSData?
var ops: [IndexOp] = []
func parse(data: NSData) -> XMLIndexer {
self.data = data
return XMLIndexer(self)
}
func startParsing(ops: [IndexOp]) {
// clear any prior runs of parse... expected that this won't be necessary, but you never know
parentStack.removeAll()
root = XMLElement(name: rootElementName)
parentStack.push(root)
self.ops = ops
let parser = NSXMLParser(data: data!)
parser.delegate = self
parser.parse()
}
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [NSObject : AnyObject]) {
elementStack.push(elementName)
if !onMatch() {
return
}
let currentNode = parentStack.top().addElement(elementName, withAttributes: attributeDict)
parentStack.push(currentNode)
}
func parser(parser: NSXMLParser, foundCharacters string: String?) {
if !onMatch() {
return
}
let current = parentStack.top()
if current.text == nil {
current.text = ""
}
parentStack.top().text! += string!
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
let match = onMatch()
elementStack.pop()
if match {
parentStack.pop()
}
}
func onMatch() -> Bool {
// we typically want to compare against the elementStack to see if it matches ops, *but*
// if we're on the first element, we'll instead compare the other direction.
if elementStack.items.count > ops.count {
return startsWith(elementStack.items, ops.map { $0.key })
}
else {
return startsWith(ops.map { $0.key }, elementStack.items)
}
}
}
/// The implementation of NSXMLParserDelegate and where the parsing actually happens.
class XMLParser : NSObject, NSXMLParserDelegate {
override init() {
super.init()
}
var root = XMLElement(name: rootElementName)
var parentStack = Stack<XMLElement>()
func parse(data: NSData) -> XMLIndexer {
// clear any prior runs of parse... expected that this won't be necessary, but you never know
parentStack.removeAll()
parentStack.push(root)
let parser = NSXMLParser(data: data)
parser.delegate = self
parser.parse()
return XMLIndexer(root)
}
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [NSObject : AnyObject]) {
let currentNode = parentStack.top().addElement(elementName, withAttributes: attributeDict)
parentStack.push(currentNode)
}
func parser(parser: NSXMLParser, foundCharacters string: String?) {
let current = parentStack.top()
if current.text == nil {
current.text = ""
}
parentStack.top().text! += string!
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
parentStack.pop()
}
}
public class IndexOp {
var index: Int
let key: String
init(_ key: String) {
self.key = key
self.index = -1
}
func toString() -> String {
if index >= 0 {
return key + " " + index.description
}
return key
}
}
public class IndexOps {
var ops: [IndexOp] = []
let parser: LazyXMLParser
init(parser: LazyXMLParser) {
self.parser = parser
}
func findElements() -> XMLIndexer {
parser.startParsing(ops)
let indexer = XMLIndexer(parser.root)
var childIndex = indexer
for op in ops {
childIndex = childIndex[op.key]
if op.index >= 0 {
childIndex = childIndex[op.index]
}
}
ops.removeAll(keepCapacity: false)
return childIndex
}
func stringify() -> String {
var s = ""
for op in ops {
s += "[" + op.toString() + "]"
}
return s
}
}
/// Returned from SWXMLHash, allows easy element lookup into XML data.
public enum XMLIndexer : SequenceType {
case Element(XMLElement)
case List([XMLElement])
case Stream(IndexOps)
case Error(NSError)
/// The underlying XMLElement at the currently indexed level of XML.
public var element: XMLElement? {
get {
switch self {
case .Element(let elem):
return elem
case .Stream(let ops):
let list = ops.findElements()
return list.element
default:
return nil
}
}
}
/// All elements at the currently indexed level
public var all: [XMLIndexer] {
get {
switch self {
case .List(let list):
var xmlList = [XMLIndexer]()
for elem in list {
xmlList.append(XMLIndexer(elem))
}
return xmlList
case .Element(let elem):
return [XMLIndexer(elem)]
case .Stream(let ops):
let list = ops.findElements()
return list.all
default:
return []
}
}
}
/// All child elements from the currently indexed level
public var children: [XMLIndexer] {
get {
var list = [XMLIndexer]()
for elem in all.map({ $0.element! }) {
for elem in elem.children {
list.append(XMLIndexer(elem))
}
}
return list
}
}
/**
Allows for element lookup by matching attribute values.
:param: attr should the name of the attribute to match on
:param: _ should be the value of the attribute to match on
:returns: instance of XMLIndexer
*/
public func withAttr(attr: String, _ value: String) -> XMLIndexer {
let attrUserInfo = [NSLocalizedDescriptionKey: "XML Attribute Error: Missing attribute [\"\(attr)\"]"]
let valueUserInfo = [NSLocalizedDescriptionKey: "XML Attribute Error: Missing attribute [\"\(attr)\"] with value [\"\(value)\"]"]
switch self {
case .Stream(let opStream):
opStream.stringify()
let match = opStream.findElements()
return match.withAttr(attr, value)
case .List(let list):
if let elem = list.filter({$0.attributes[attr] == value}).first {
return .Element(elem)
}
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: valueUserInfo))
case .Element(let elem):
if let attr = elem.attributes[attr] {
if attr == value {
return .Element(elem)
}
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: valueUserInfo))
}
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: attrUserInfo))
default:
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: attrUserInfo))
}
}
/**
Initializes the XMLIndexer
:param: _ should be an instance of XMLElement, but supports other values for error handling
:returns: instance of XMLIndexer
*/
public init(_ rawObject: AnyObject) {
switch rawObject {
case let value as XMLElement:
self = .Element(value)
case let value as LazyXMLParser:
self = .Stream(IndexOps(parser: value))
default:
self = .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: nil))
}
}
/**
Find an XML element at the current level by element name
:param: key The element name to index by
:returns: instance of XMLIndexer to match the element (or elements) found by key
*/
public subscript(key: String) -> XMLIndexer {
get {
let userInfo = [NSLocalizedDescriptionKey: "XML Element Error: Incorrect key [\"\(key)\"]"]
switch self {
case .Stream(let opStream):
let op = IndexOp(key)
opStream.ops.append(op)
return .Stream(opStream)
case .Element(let elem):
let match = elem.children.filter({ $0.name == key })
if match.count > 0 {
if match.count == 1 {
return .Element(match[0])
}
else {
return .List(match)
}
}
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo))
default:
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo))
}
}
}
/**
Find an XML element by index within a list of XML Elements at the current level
:param: index The 0-based index to index by
:returns: instance of XMLIndexer to match the element (or elements) found by key
*/
public subscript(index: Int) -> XMLIndexer {
get {
let userInfo = [NSLocalizedDescriptionKey: "XML Element Error: Incorrect index [\"\(index)\"]"]
switch self {
case .Stream(let opStream):
opStream.ops[opStream.ops.count - 1].index = index
return .Stream(opStream)
case .List(let list):
if index <= list.count {
return .Element(list[index])
}
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo))
case .Element(let elem):
if index == 0 {
return .Element(elem)
}
else {
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo))
}
default:
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo))
}
}
}
typealias GeneratorType = XMLIndexer
public func generate() -> IndexingGenerator<[XMLIndexer]> {
return all.generate()
}
}
/// XMLIndexer extensions
extension XMLIndexer: BooleanType {
/// True if a valid XMLIndexer, false if an error type
public var boolValue: Bool {
get {
switch self {
case .Error:
return false
default:
return true
}
}
}
}
extension XMLIndexer: Printable {
public var description: String {
get {
switch self {
case .List(let list):
return "\n".join(list.map { $0.description })
case .Element(let elem):
if elem.name == rootElementName {
return "\n".join(elem.children.map { $0.description })
}
return elem.description
default:
return ""
}
}
}
}
/// Models an XML element, including name, text and attributes
public class XMLElement {
/// The name of the element
public let name: String
/// The inner text of the element, if it exists
public var text: String?
/// The attributes of the element
public var attributes = [String:String]()
var children = [XMLElement]()
var count: Int = 0
var index: Int
/**
Initialize an XMLElement instance
:param: name The name of the element to be initialized
:returns: a new instance of XMLElement
*/
init(name: String, index: Int = 0) {
self.name = name
self.index = index
}
/**
Adds a new XMLElement underneath this instance of XMLElement
:param: name The name of the new element to be added
:param: withAttributes The attributes dictionary for the element being added
:returns: The XMLElement that has now been added
*/
func addElement(name: String, withAttributes attributes: NSDictionary) -> XMLElement {
let element = XMLElement(name: name, index: count)
count++
children.append(element)
for (keyAny,valueAny) in attributes {
let key = keyAny as! String
let value = valueAny as! String
element.attributes[key] = value
}
return element
}
}
extension XMLElement: Printable {
public var description:String {
get {
var attributesStringList = [String]()
if !attributes.isEmpty {
for (key, val) in attributes {
attributesStringList.append("\(key)=\"\(val)\"")
}
}
var attributesString = " ".join(attributesStringList)
if (!attributesString.isEmpty) {
attributesString = " " + attributesString
}
if children.count > 0 {
var xmlReturn = [String]()
xmlReturn.append("<\(name)\(attributesString)>")
for child in children {
xmlReturn.append(child.description)
}
xmlReturn.append("</\(name)>")
return "\n".join(xmlReturn)
}
if text != nil {
return "<\(name)\(attributesString)>\(text!)</\(name)>"
}
else {
return "<\(name)\(attributesString)/>"
}
}
}
}
private func searchAll(root: XMLIndexer, attributeKey: String, attributeValue: String) -> [XMLIndexer]? {
var result = Array<XMLIndexer>()
for child in root.children {
if let element = child.element where element.attributes[attributeKey] == attributeValue {
return [child]
}
if let found = searchAll(child, attributeKey, attributeValue) {
result += found
}
}
return result.count > 0 ? result : nil
}
//MARK: Objects
enum OS: String, Printable{
case iOS = "iOS"
case OSX = "OSX"
static func fromString(string: String) -> OS? {
for os in OS.allValues {
if NSString(string: os.rawValue).caseInsensitiveCompare(string) == NSComparisonResult.OrderedSame {
return os
}
}
return nil
}
static func fromTargetRuntime(targetRuntime: String) -> OS? {
for os in OS.allValues {
if os.targetRuntime == targetRuntime {
return os
}
}
return nil
}
static let allValues = [iOS, OSX]
var description: String {return self.rawValue}
var framework: String {
switch self {
case iOS: return "UIKit"
case OSX: return "Cocoa"
}
}
var targetRuntime: String {
switch self {
case iOS: return "iOS.CocoaTouch"
case OSX: return "MacOSX.Cocoa"
}
}
var typePrefix: String {
switch self {
case iOS: return "UI"
case OSX: return "NS"
}
}
var storyboardType: String {
return typePrefix + "Storyboard"
}
var storyboardSegueType: String {
return typePrefix + "StoryboardSegue"
}
var storyboardTypeUnwrap: String {
switch self {
case iOS: return ""
case OSX: return "!"
}
}
var storyboardControllerTypes: [String] {
switch self {
case iOS: return ["UIViewController"]
case OSX: return ["NSViewController", "NSWindowController"]
}
}
var storyboardControllerSignatureType: String {
switch self {
case iOS: return "ViewController"
case OSX: return "Controller" // NSViewController or NSWindowController
}
}
var storyboardControllerReturnType: String {
switch self {
case iOS: return "UIViewController"
case OSX: return "AnyObject" // NSViewController or NSWindowController
}
}
var storyboardControllerInitialReturnTypeCast: String {
switch self {
case iOS: return "as? \(self.storyboardControllerReturnType)"
case OSX: return ""
}
}
var storyboardControllerReturnTypeCast: String {
switch self {
case iOS: return " as! \(self.storyboardControllerReturnType)"
case OSX: return "!"
}
}
func storyboardControllerInitialReturnTypeCast(initialClass: String) -> String {
switch self {
case iOS: return "as! \(initialClass)"
case OSX: return ""
}
}
func controllerTypeForElementName(name: String) -> String? {
switch self {
case iOS:
switch name {
case "navigationController":
return "UINavigationController"
case "tableViewController":
return "UITableViewController"
case "tabBarController":
return "UITabBarViewController"
case "splitViewController":
return "UISplitViewController"
case "pageViewController":
return "UIPageViewController"
default:
return nil
}
case OSX:
switch name {
case "pagecontroller":
return "NSPageController"
case "tabViewController":
return "NSTabViewController"
case "splitViewController":
return "NSSplitViewController"
default:
return nil
}
}
}
}
class StoryboardFile {
let filePath: String
init(filePath: String){
self.filePath = filePath
}
lazy var storyboardName: String = self.filePath.lastPathComponent.stringByDeletingPathExtension
lazy var data: NSData? = NSData(contentsOfFile: self.filePath)
lazy var xml: XMLIndexer? = {
if let d = self.data {
return SWXMLHash.parse(d)
}
return nil
}()
lazy var os:OS = self.initOS() ?? OS.iOS
private func initOS() -> OS? {
if let xml = self.xml, targetRuntime = xml["document"].element?.attributes["targetRuntime"] {
return OS.fromTargetRuntime(targetRuntime)
}
return nil
}
lazy var initialViewControllerClass: String? = self.initOInitialViewControllerClass()
private func initOInitialViewControllerClass() -> String? {
if let xml = self.xml,
initialViewControllerId = xml["document"].element?.attributes["initialViewController"],
vc = searchAll(xml["document"], "id",initialViewControllerId)?.first {
if let customClassName = vc.element?.attributes["customClass"] {
return customClassName
}
if let controllerType = os.controllerTypeForElementName(vc.element!.name) {
return controllerType
}
}
return nil
}
func processStoryboard() {
if let xml = self.xml, viewControllers = searchAll(xml, "sceneMemberID", "viewController") {
for viewController in viewControllers {
if let customClass = viewController.element?.attributes["customClass"] {
let segues = viewController["connections"]["segue"].all.filter({ return $0.element?.attributes["identifier"] != nil })
if segues.count > 0 {
println("extension \(os.storyboardSegueType) {")
println(" func selection() -> \(customClass).Segue? {")
println(" if let identifier = self.identifier {")
println(" return \(customClass).Segue(rawValue: identifier)")
println(" }")
println(" return nil")
println(" }")
println("}")
}
println()
println("//MARK: - \(customClass)")
if let identifierExtenstionString = storyboardIdentifierExtension(viewController) {
println()
println(identifierExtenstionString)
println()
}
if segues.count > 0 {
println("extension \(customClass) { ")
println()
println(" enum Segue: String, Printable, SegueProtocol {")
for segue in segues {
if let identifier = segue.element?.attributes["identifier"]
{
println(" case \(identifier) = \"\(identifier)\"")
}
}
println()
println(" var kind: SegueKind? {")
println(" switch (self) {")
for segue in segues {
if let identifier = segue.element?.attributes["identifier"],
let kind = segue.element?.attributes["kind"] {
println(" case \(identifier):")
println(" return SegueKind(rawValue: \"\(kind)\")")
}
}
println(" default:")
println(" preconditionFailure(\"Invalid value\")")
println(" break")
println(" }")
println(" }")
println()
println(" var destination: \(self.os.storyboardControllerReturnType).Type? {")
println(" switch (self) {")
for segue in segues {
if let identifier = segue.element?.attributes["identifier"],
let destination = segue.element?.attributes["destination"],
let destinationCustomClass = searchAll(xml, "id", destination)?.first?.element?.attributes["customClass"] {
// let dstCustomClass = destinationViewController.element!.attributes["customClass"]
println(" case \(identifier):")
println(" return \(destinationCustomClass).self")
}
}
println(" default:")
println(" assertionFailure(\"Unknown destination\")")
println(" return nil")
println(" }")
println(" }")
println()
println(" var identifier: String { return self.description } ")
println(" var description: String { return self.rawValue }")
println(" }")
println()
println("}\n")
}
}
}
}
}
private func storyboardIdentifierExtension(viewController: XMLIndexer) -> String? {
var result:String? = nil
if let customClass = viewController.element?.attributes["customClass"] {
var output = String()
//check if the customModule belongs to the main application target, if so the import isn't necessary
let targetModule = viewController.element?.attributes["customModuleProvider"]
if let customModule = viewController.element?.attributes["customModule"] where targetModule == nil {
output += "import \(customModule)\n"
}
output += "extension \(customClass) {\n"
if let viewControllerId = viewController.element?.attributes["storyboardIdentifier"] {
output += " override class var storyboardIdentifier:String? { return \"\(viewControllerId)\" }\n"
}
output += "}"
result = output
}
return result
}
}
//MARK: Functions Storyboards
func findStoryboards(rootPath: String, suffix: String) -> [String]? {
var result = Array<String>()
let fm = NSFileManager.defaultManager()
var error:NSError?
if let paths = fm.subpathsAtPath(rootPath) as? [String] {
let storyboardPaths = paths.filter({ return $0.hasSuffix(suffix)})
// result = storyboardPaths
for p in storyboardPaths {
result.append(rootPath.stringByAppendingPathComponent(p))
}
}
return result.count > 0 ? result : nil
}
func processStoryboards(storyboards: [StoryboardFile], os: OS) {
println("//")
println("// Autogenerated by Natalie - Storyboard Generator Script.")
println("// http://blog.krzyzanowskim.com")
println("//")
println()
println("import \(os.framework)")
println()
println("//MARK: - Storyboards")
println("enum Storyboards: String {")
for storyboard in storyboards {
let storyboardName = storyboard.storyboardName
println(" case \(storyboardName) = \"\(storyboardName)\"")
}
println()
println(" private var instance:\(os.storyboardType) {")
println(" return \(os.storyboardType)(name: self.rawValue, bundle: nil)\(os.storyboardTypeUnwrap)")
println(" }")
println()
println(" func instantiateInitial\(os.storyboardControllerSignatureType)() -> \(os.storyboardControllerReturnType)? {")
println(" switch (self) {")
for storyboard in storyboards {
if let initialViewControllerClass = storyboard.initialViewControllerClass {
let storyboardName = storyboard.storyboardName
println(" case \(storyboardName):")
println(" return self.instance.instantiateInitial\(os.storyboardControllerSignatureType)() \(os.storyboardControllerInitialReturnTypeCast(initialViewControllerClass))")
}
}
println(" default:")
println(" return self.instance.instantiateInitial\(os.storyboardControllerSignatureType)() \(os.storyboardControllerInitialReturnTypeCast)")
println(" }")
println(" }")
println()
println(" func instantiate\(os.storyboardControllerSignatureType)WithIdentifier(identifier: String) -> \(os.storyboardControllerReturnType) {")
println(" return self.instance.instantiate\(os.storyboardControllerSignatureType)WithIdentifier(identifier)\(os.storyboardControllerReturnTypeCast)")
println(" }")
println("}")
println()
println("//MARK: - SegueKind")
println("enum SegueKind: String, Printable { ")
println(" case Relationship = \"relationship\" ")
println(" case Show = \"show\" ")
println(" case Presentation = \"presentation\" ")
println(" case Embed = \"embed\" ")
println(" case Unwind = \"unwind\" ")
println()
println(" var description: String { return self.rawValue } ")
println("}")
println()
println("//MARK: - SegueProtocol")
println("protocol SegueProtocol {")
println(" var identifier: String { get }")
println("}")
println()
for controllerType in os.storyboardControllerTypes {
println("//MARK: - \(controllerType) extension")
println("extension \(controllerType) {")
println(" class var storyboardIdentifier:String? { return nil }")
println(" func performSegue(segue: SegueProtocol, sender: AnyObject?) {")
println(" performSegueWithIdentifier(segue.identifier, sender: sender)")
println(" }")
println("}")
println()
}
for storyboard in storyboards {
storyboard.processStoryboard()
}
}
//MARK: MAIN()
if Process.arguments.count == 1 {
println("Invalid usage. Missing path to storyboard.")
exit(0)
}
let argument = Process.arguments[1]
var storyboards:[String] = []
let storyboardSuffix = ".storyboard"
if argument.hasSuffix(storyboardSuffix) {
storyboards = [argument]
} else if let s = findStoryboards(argument, storyboardSuffix) {
storyboards = s
}
let storyboardFiles: [StoryboardFile] = storyboards.map { StoryboardFile(filePath: $0) }
for os in OS.allValues {
var storyboardsForOS = storyboardFiles.filter { $0.os == os }
if !storyboardsForOS.isEmpty {
if storyboardsForOS.count != storyboardFiles.count { println("#if os(\(os.rawValue))") }
processStoryboards(storyboardsForOS, os)
if storyboardsForOS.count != storyboardFiles.count { println("#endif") }
}
}