diff --git a/Sources/Parsers/XIBParser.swift b/Sources/Parsers/XIBParser.swift new file mode 100644 index 0000000..f3f85a7 --- /dev/null +++ b/Sources/Parsers/XIBParser.swift @@ -0,0 +1,49 @@ +// +// SwiftGenKit +// Copyright (c) 2017 SwiftGen +// MIT Licence +// + +import Foundation +import PathKit + +public final class XIBParser { + var xibs: [String: (customClass: String?, module: String?)] = [:] + + public init() {} + + private class ParserDelegate: NSObject, XMLParserDelegate { + fileprivate var fileOwnerClass: String? + fileprivate var fileOwnerModule: String? + + func parser(_ parser: XMLParser, didStartElement elementName: String, + namespaceURI: String?, qualifiedName qName: String?, + attributes attributeDict: [String: String]) { + if elementName == "placeholder" && attributeDict["placeholderIdentifier"] == "IBFilesOwner" { + self.fileOwnerClass = attributeDict["customClass"] + self.fileOwnerModule = attributeDict["customModule"] + } + } + } + + public func addXIB(at path: Path) throws { + let parser = XMLParser(data: try path.read()) + + let delegate = ParserDelegate() + parser.delegate = delegate + parser.parse() + + let xibName = path.lastComponentWithoutExtension + self.xibs[xibName] = (delegate.fileOwnerClass, delegate.fileOwnerModule) + } + + public func parseDirectory(at path: Path) throws { + let iterator = path.makeIterator() + + while let subPath = iterator.next() { + if subPath.extension == "xib" { + try addXIB(at: subPath) + } + } + } +} diff --git a/Sources/Stencil/XIBContext.swift b/Sources/Stencil/XIBContext.swift new file mode 100644 index 0000000..42d44a0 --- /dev/null +++ b/Sources/Stencil/XIBContext.swift @@ -0,0 +1,31 @@ +// +// SwiftGenKit +// Copyright (c) 2017 SwiftGen +// MIT Licence +// + +import Foundation + +/* + - `xibs`: `Array` — List of xibs + - `name`: `String` — Name of the xib + - `owner`: `String` — The custom class of the scene + - `customModule`: `String` — The custom module of the scene (absent if no custom class) + */ +extension XIBParser { + public func stencilContext() -> [String: Any] { + let xibNames = Set(xibs.keys).sorted(by: <) + let xibsMap = xibNames.map { (xibName: String) -> [String: String] in + guard let (owner, module) = xibs[xibName] else { + return [:] + } + + var xibInformation = ["name": xibName] + xibInformation["customOwner"] = owner + xibInformation["customModule"] = module + return xibInformation + } + + return ["xibs": xibsMap] + } +}