From 66edcba18579c22ec14fabc5048147b56018bf63 Mon Sep 17 00:00:00 2001 From: Adam Fowler Date: Mon, 15 Mar 2021 18:24:06 +0000 Subject: [PATCH] swift format --- Sources/HummingbirdMustache/Context.swift | 15 +- Sources/HummingbirdMustache/Lambda.swift | 2 +- .../Library+FileSystem.swift | 2 +- Sources/HummingbirdMustache/Library.swift | 8 +- Sources/HummingbirdMustache/Method.swift | 32 ++-- Sources/HummingbirdMustache/Mirror.swift | 1 - Sources/HummingbirdMustache/Parent.swift | 1 - Sources/HummingbirdMustache/Parser.swift | 178 +++++++++--------- Sources/HummingbirdMustache/Sequence.swift | 13 +- Sources/HummingbirdMustache/String.swift | 2 +- .../HummingbirdMustache/Template+Parser.swift | 4 +- .../HummingbirdMustache/Template+Render.swift | 24 +-- Sources/HummingbirdMustache/Template.swift | 11 +- .../LibraryTests.swift | 4 +- .../MethodTests.swift | 115 ++++++----- .../PartialTests.swift | 55 +++--- .../TemplateParserTests.swift | 12 +- .../TemplateRendererTests.swift | 140 +++++++------- 18 files changed, 306 insertions(+), 313 deletions(-) diff --git a/Sources/HummingbirdMustache/Context.swift b/Sources/HummingbirdMustache/Context.swift index f70f454..6c445b5 100644 --- a/Sources/HummingbirdMustache/Context.swift +++ b/Sources/HummingbirdMustache/Context.swift @@ -4,11 +4,11 @@ struct HBMustacheContext: HBMustacheMethods { var first: Bool var last: Bool var index: Int - + init(first: Bool = false, last: Bool = false) { self.first = first self.last = last - self.index = 0 + index = 0 } /// Apply method to `HBMustacheContext`. These are available when processing elements @@ -25,18 +25,17 @@ struct HBMustacheContext: HBMustacheMethods { func runMethod(_ name: String) -> Any? { switch name { case "first": - return self.first + return first case "last": - return self.last + return last case "index": - return self.index + return index case "even": - return (self.index & 1) == 0 + return (index & 1) == 0 case "odd": - return (self.index & 1) == 1 + return (index & 1) == 1 default: return nil } } - } diff --git a/Sources/HummingbirdMustache/Lambda.swift b/Sources/HummingbirdMustache/Lambda.swift index 58b32ae..3d977e9 100644 --- a/Sources/HummingbirdMustache/Lambda.swift +++ b/Sources/HummingbirdMustache/Lambda.swift @@ -27,7 +27,7 @@ public struct HBMustacheLambda { /// Initialize `HBMustacheLambda` /// - Parameter cb: function to be called by lambda public init(_ cb: @escaping Callback) { - self.callback = cb + callback = cb } internal func run(_ object: Any, _ template: HBMustacheTemplate) -> String { diff --git a/Sources/HummingbirdMustache/Library+FileSystem.swift b/Sources/HummingbirdMustache/Library+FileSystem.swift index 07472d1..1234fbe 100644 --- a/Sources/HummingbirdMustache/Library+FileSystem.swift +++ b/Sources/HummingbirdMustache/Library+FileSystem.swift @@ -13,7 +13,7 @@ extension HBMustacheLibrary { guard let enumerator = fs.enumerator(atPath: directory) else { return } for case let path as String in enumerator { guard path.hasSuffix(extWithDot) else { continue } - guard let data = fs.contents(atPath: directory + path) else { continue} + guard let data = fs.contents(atPath: directory + path) else { continue } let string = String(decoding: data, as: Unicode.UTF8.self) guard let template = try? HBMustacheTemplate(string: string) else { logger?.error("Failed to load \(path)") diff --git a/Sources/HummingbirdMustache/Library.swift b/Sources/HummingbirdMustache/Library.swift index 0c48900..2593949 100644 --- a/Sources/HummingbirdMustache/Library.swift +++ b/Sources/HummingbirdMustache/Library.swift @@ -9,7 +9,7 @@ import Logging public class HBMustacheLibrary { /// Initialize empty library public init() { - self.templates = [:] + templates = [:] } /// Initialize library with contents of folder. @@ -19,8 +19,8 @@ public class HBMustacheLibrary { /// - Parameter directory: Directory to look for mustache templates /// - Parameter extension: Extension of files to look for public init(directory: String, withExtension extension: String = "mustache", logger: Logger? = nil) { - self.templates = [:] - self.loadTemplates(from: directory, withExtension: `extension`, logger: logger) + templates = [:] + loadTemplates(from: directory, withExtension: `extension`, logger: logger) } /// Register template under name @@ -48,6 +48,6 @@ public class HBMustacheLibrary { guard let template = templates[name] else { return nil } return template.render(object) } - + private var templates: [String: HBMustacheTemplate] } diff --git a/Sources/HummingbirdMustache/Method.swift b/Sources/HummingbirdMustache/Method.swift index dcc2dd7..fc5ff6d 100644 --- a/Sources/HummingbirdMustache/Method.swift +++ b/Sources/HummingbirdMustache/Method.swift @@ -17,22 +17,22 @@ public protocol HBMustacheMethods { func runMethod(_ name: String) -> Any? } -extension StringProtocol { +public extension StringProtocol { /// Apply method to String/Substring /// /// Methods available are `capitalized`, `lowercased`, `uppercased` and `reversed` /// - Parameter name: Method name /// - Returns: Result - public func runMethod(_ name: String) -> Any? { + func runMethod(_ name: String) -> Any? { switch name { case "capitalized": - return self.capitalized + return capitalized case "lowercased": - return self.lowercased() + return lowercased() case "uppercased": - return self.uppercased() + return uppercased() case "reversed": - return self.reversed() + return reversed() default: return nil } @@ -57,13 +57,13 @@ extension Array: HBMustacheMethods { public func runMethod(_ name: String) -> Any? { switch name { case "first": - return self.first + return first case "last": - return self.last + return last case "reversed": - return self.reversed() + return reversed() case "count": - return self.count + return count default: if let comparableSeq = self as? HBComparableSequence { return comparableSeq.runComparableMethod(name) @@ -77,7 +77,7 @@ extension Array: HBComparableSequence where Element: Comparable { func runComparableMethod(_ name: String) -> Any? { switch name { case "sorted": - return self.sorted() + return sorted() default: return nil } @@ -94,9 +94,9 @@ extension Dictionary: HBMustacheMethods { public func runMethod(_ name: String) -> Any? { switch name { case "count": - return self.count + return count case "enumerated": - return self.map { (key: $0.key, value: $0.value) } + return map { (key: $0.key, value: $0.value) } default: if let comparableSeq = self as? HBComparableSequence { return comparableSeq.runComparableMethod(name) @@ -110,20 +110,20 @@ extension Dictionary: HBComparableSequence where Key: Comparable { func runComparableMethod(_ name: String) -> Any? { switch name { case "sorted": - return self.map { (key: $0.key, value: $0.value) }.sorted { $0.key < $1.key } + return map { (key: $0.key, value: $0.value) }.sorted { $0.key < $1.key } default: return nil } } } -extension FixedWidthInteger { +public extension FixedWidthInteger { /// Apply method to FixedWidthInteger /// /// Methods available are `plusone`, `minusone`, `odd`, `even` /// - Parameter name: method name /// - Returns: Result - public func runMethod(_ name: String) -> Any? { + func runMethod(_ name: String) -> Any? { switch name { case "plusone": return self + 1 diff --git a/Sources/HummingbirdMustache/Mirror.swift b/Sources/HummingbirdMustache/Mirror.swift index e169942..7d9fa41 100644 --- a/Sources/HummingbirdMustache/Mirror.swift +++ b/Sources/HummingbirdMustache/Mirror.swift @@ -17,4 +17,3 @@ private func unwrapOptional(_ object: Any) -> Any? { guard let first = mirror.children.first else { return nil } return first.value } - diff --git a/Sources/HummingbirdMustache/Parent.swift b/Sources/HummingbirdMustache/Parent.swift index 85206f4..afd55c4 100644 --- a/Sources/HummingbirdMustache/Parent.swift +++ b/Sources/HummingbirdMustache/Parent.swift @@ -10,4 +10,3 @@ protocol HBMustacheParent { extension Dictionary: HBMustacheParent where Key == String { func child(named: String) -> Any? { return self[named] } } - diff --git a/Sources/HummingbirdMustache/Parser.swift b/Sources/HummingbirdMustache/Parser.swift index 8abd359..2f7f8c9 100644 --- a/Sources/HummingbirdMustache/Parser.swift +++ b/Sources/HummingbirdMustache/Parser.swift @@ -23,10 +23,10 @@ struct HBParser { if let buffer = utf8Data as? [UInt8] { self.buffer = buffer } else { - self.buffer = Array(utf8Data) + buffer = Array(utf8Data) } - self.index = 0 - self.range = 0..) { - self.buffer = parser.buffer - self.index = range.startIndex + buffer = parser.buffer + index = range.startIndex self.range = range - precondition(range.startIndex >= 0 && range.endIndex <= self.buffer.endIndex) - precondition(self.buffer[range.startIndex] & 0xC0 != 0x80) // check we arent in the middle of a UTF8 character + precondition(range.startIndex >= 0 && range.endIndex <= buffer.endIndex) + precondition(buffer[range.startIndex] & 0xC0 != 0x80) // check we arent in the middle of a UTF8 character } /// initialise a parser that parses a section of the buffer attached to this parser @@ -79,7 +79,7 @@ extension HBParser { /// - Throws: .overflow /// - Returns: Current character mutating func character() throws -> Unicode.Scalar { - guard !self.reachedEnd() else { throw Error.overflow } + guard !reachedEnd() else { throw Error.overflow } return unsafeCurrentAndAdvance() } @@ -88,9 +88,9 @@ extension HBParser { /// - Throws: .overflow /// - Returns: If current character was the one we expected mutating func read(_ char: Unicode.Scalar) throws -> Bool { - let initialIndex = self.index + let initialIndex = index let c = try character() - guard c == char else { self.index = initialIndex; return false } + guard c == char else { index = initialIndex; return false } return true } @@ -99,9 +99,9 @@ extension HBParser { /// - Throws: .overflow /// - Returns: If current character is in character set mutating func read(_ characterSet: Set) throws -> Bool { - let initialIndex = self.index + let initialIndex = index let c = try character() - guard characterSet.contains(c) else { self.index = initialIndex; return false } + guard characterSet.contains(c) else { index = initialIndex; return false } return true } @@ -110,10 +110,10 @@ extension HBParser { /// - Throws: .overflow, .emptyString /// - Returns: If characters at current position equal string mutating func read(_ string: String) throws -> Bool { - let initialIndex = self.index + let initialIndex = index guard string.count > 0 else { throw Error.emptyString } let subString = try read(count: string.count) - guard subString.string == string else { self.index = initialIndex; return false } + guard subString.string == string else { index = initialIndex; return false } return true } @@ -123,14 +123,14 @@ extension HBParser { /// - Returns: The string read from the buffer mutating func read(count: Int) throws -> HBParser { var count = count - var readEndIndex = self.index + var readEndIndex = index while count > 0 { - guard readEndIndex != self.range.endIndex else { throw Error.overflow } + guard readEndIndex != range.endIndex else { throw Error.overflow } readEndIndex = skipUTF8Character(at: readEndIndex) count -= 1 } - let result = self.subParser(self.index.. HBParser { - let startIndex = self.index - while !self.reachedEnd() { + let startIndex = index + while !reachedEnd() { if unsafeCurrent() == until { - return self.subParser(startIndex.., throwOnOverflow: Bool = true) throws -> HBParser { - let startIndex = self.index - while !self.reachedEnd() { + let startIndex = index + while !reachedEnd() { if characterSet.contains(unsafeCurrent()) { - return self.subParser(startIndex.. Bool, throwOnOverflow: Bool = true) throws -> HBParser { - let startIndex = self.index - while !self.reachedEnd() { + let startIndex = index + while !reachedEnd() { if until(unsafeCurrent()) { - return self.subParser(startIndex.., throwOnOverflow: Bool = true) throws -> HBParser { - let startIndex = self.index - while !self.reachedEnd() { + let startIndex = index + while !reachedEnd() { if unsafeCurrent()[keyPath: keyPath] { - return self.subParser(startIndex.. HBParser { - let startIndex = self.index - self.index = self.range.endIndex - return self.subParser(startIndex.. Int { var count = 0 - while !self.reachedEnd(), + while !reachedEnd(), unsafeCurrent() == `while` { unsafeAdvance() @@ -276,39 +276,39 @@ extension HBParser { /// - Parameter while: character set to check /// - Returns: String read from buffer @discardableResult mutating func read(while characterSet: Set) -> HBParser { - let startIndex = self.index - while !self.reachedEnd(), + let startIndex = index + while !reachedEnd(), characterSet.contains(unsafeCurrent()) { unsafeAdvance() } - return self.subParser(startIndex.. Bool) -> HBParser { - let startIndex = self.index - while !self.reachedEnd(), + let startIndex = index + while !reachedEnd(), `while`(unsafeCurrent()) { unsafeAdvance() } - return self.subParser(startIndex..) -> HBParser { - let startIndex = self.index - while !self.reachedEnd(), + let startIndex = index + while !reachedEnd(), unsafeCurrent()[keyPath: keyPath] { unsafeAdvance() } - return self.subParser(startIndex.. [HBParser] { var subParsers: [HBParser] = [] - while !self.reachedEnd() { + while !reachedEnd() { do { let section = try read(until: separator) subParsers.append(section) unsafeAdvance() } catch { - if !self.reachedEnd() { - subParsers.append(self.readUntilTheEnd()) + if !reachedEnd() { + subParsers.append(readUntilTheEnd()) } } } @@ -333,7 +333,7 @@ extension HBParser { /// Return whether we have reached the end of the buffer /// - Returns: Have we reached the end func reachedEnd() -> Bool { - return self.index == self.range.endIndex + return index == range.endIndex } } @@ -343,15 +343,15 @@ extension HBParser { /// - Throws: .overflow /// - Returns: Unicode.Scalar func current() -> Unicode.Scalar { - guard !self.reachedEnd() else { return Unicode.Scalar(0) } + guard !reachedEnd() else { return Unicode.Scalar(0) } return unsafeCurrent() } /// Move forward one character /// - Throws: .overflow mutating func advance() throws { - guard !self.reachedEnd() else { throw Error.overflow } - return self.unsafeAdvance() + guard !reachedEnd() else { throw Error.overflow } + return unsafeAdvance() } /// Move forward so many character @@ -360,8 +360,8 @@ extension HBParser { mutating func advance(by amount: Int) throws { var amount = amount while amount > 0 { - guard !self.reachedEnd() else { throw Error.overflow } - self.index = skipUTF8Character(at: self.index) + guard !reachedEnd() else { throw Error.overflow } + index = skipUTF8Character(at: index) amount -= 1 } } @@ -369,8 +369,8 @@ extension HBParser { /// Move backwards one character /// - Throws: .overflow mutating func retreat() throws { - guard self.index > self.range.startIndex else { throw Error.overflow } - self.index = backOneUTF8Character(at: self.index) + guard index > range.startIndex else { throw Error.overflow } + index = backOneUTF8Character(at: index) } /// Move back so many characters @@ -379,20 +379,20 @@ extension HBParser { mutating func retreat(by amount: Int) throws { var amount = amount while amount > 0 { - guard self.index > self.range.startIndex else { throw Error.overflow } - self.index = backOneUTF8Character(at: self.index) + guard index > range.startIndex else { throw Error.overflow } + index = backOneUTF8Character(at: index) amount -= 1 } } mutating func unsafeAdvance() { - self.index = skipUTF8Character(at: self.index) + index = skipUTF8Character(at: index) } mutating func unsafeAdvance(by amount: Int) { var amount = amount while amount > 0 { - self.index = skipUTF8Character(at: self.index) + index = skipUTF8Character(at: index) amount -= 1 } } @@ -416,8 +416,8 @@ extension HBParser: Sequence { } mutating func next() -> Unicode.Scalar? { - guard !self.parser.reachedEnd() else { return nil } - return self.parser.unsafeCurrentAndAdvance() + guard !parser.reachedEnd() else { return nil } + return parser.unsafeCurrentAndAdvance() } } } @@ -425,7 +425,7 @@ extension HBParser: Sequence { // internal versions without checks private extension HBParser { func unsafeCurrent() -> Unicode.Scalar { - return decodeUTF8Character(at: self.index).0 + return decodeUTF8Character(at: index).0 } mutating func unsafeCurrentAndAdvance() -> Unicode.Scalar { @@ -477,16 +477,16 @@ extension HBParser { } func skipUTF8Character(at index: Int) -> Int { - if self.buffer[index] & 0x80 != 0x80 { return index + 1 } - if self.buffer[index + 1] & 0xC0 == 0x80 { return index + 2 } - if self.buffer[index + 2] & 0xC0 == 0x80 { return index + 3 } + if buffer[index] & 0x80 != 0x80 { return index + 1 } + if buffer[index + 1] & 0xC0 == 0x80 { return index + 2 } + if buffer[index + 2] & 0xC0 == 0x80 { return index + 3 } return index + 4 } func backOneUTF8Character(at index: Int) -> Int { - if self.buffer[index - 1] & 0xC0 != 0x80 { return index - 1 } - if self.buffer[index - 2] & 0xC0 != 0x80 { return index - 2 } - if self.buffer[index - 3] & 0xC0 != 0x80 { return index - 3 } + if buffer[index - 1] & 0xC0 != 0x80 { return index - 1 } + if buffer[index - 2] & 0xC0 != 0x80 { return index - 2 } + if buffer[index - 3] & 0xC0 != 0x80 { return index - 3 } return index - 4 } @@ -526,9 +526,9 @@ extension HBParser { /// return if the buffer is valid UTF8 func validateUTF8() -> Bool { - var index = self.range.startIndex - while index < self.range.endIndex { - let (scalar, newIndex) = self.validateUTF8Character(at: index) + var index = range.startIndex + while index < range.endIndex { + let (scalar, newIndex) = validateUTF8Character(at: index) guard scalar != nil else { return false } index = newIndex } @@ -598,17 +598,17 @@ extension HBParser { return newIndex } - guard self.index != self.range.endIndex else { return "" } + guard index != range.endIndex else { return "" } do { if #available(macOS 11, *) { return try String(unsafeUninitializedCapacity: range.endIndex - index) { bytes -> Int in - return try _percentDecode(self.buffer[self.index.. String } -extension Sequence { +public extension Sequence { /// Render section using template - public func renderSection(with template: HBMustacheTemplate) -> String { + func renderSection(with template: HBMustacheTemplate) -> String { var string = "" var context = HBMustacheContext(first: true) - var iterator = self.makeIterator() + var iterator = makeIterator() guard var currentObject = iterator.next() else { return "" } while let object = iterator.next() { @@ -24,19 +24,18 @@ extension Sequence { context.last = true string += template.render(currentObject, context: context) - + return string } - + /// Render inverted section using template - public func renderInvertedSection(with template: HBMustacheTemplate) -> String { + func renderInvertedSection(with template: HBMustacheTemplate) -> String { var iterator = makeIterator() if iterator.next() == nil { return template.render(self) } return "" } - } extension Array: HBMustacheSequence {} diff --git a/Sources/HummingbirdMustache/String.swift b/Sources/HummingbirdMustache/String.swift index 4d6408f..c67d778 100644 --- a/Sources/HummingbirdMustache/String.swift +++ b/Sources/HummingbirdMustache/String.swift @@ -10,7 +10,7 @@ extension String { /// HTML escape string. Replace '<', '>' and '&' with HTML escaped versions func htmlEscape() -> String { var newString = "" - newString.reserveCapacity(self.count) + newString.reserveCapacity(count) // currently doing this by going through each character could speed // this us by treating as an array of UInt8's for c in self { diff --git a/Sources/HummingbirdMustache/Template+Parser.swift b/Sources/HummingbirdMustache/Template+Parser.swift index 191fce9..2c29c07 100644 --- a/Sources/HummingbirdMustache/Template+Parser.swift +++ b/Sources/HummingbirdMustache/Template+Parser.swift @@ -83,7 +83,7 @@ extension HBMustacheTemplate { /// parse variable name static func parseName(_ parser: inout HBParser) throws -> (String, String?) { parser.read(while: \.isWhitespace) - var text = parser.read(while: sectionNameChars ) + var text = parser.read(while: sectionNameChars) parser.read(while: \.isWhitespace) guard try parser.read("}"), try parser.read("}") else { throw Error.unfinishedName } // does the name include brackets. If so this is a method call @@ -106,7 +106,7 @@ extension HBMustacheTemplate { let text = try parser.read(untilString: "}}", throwOnOverflow: true, skipToEnd: true) return text.string } - + private static let sectionNameCharsWithoutBrackets = Set("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ._?") private static let sectionNameChars = Set("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ._?()") } diff --git a/Sources/HummingbirdMustache/Template+Render.swift b/Sources/HummingbirdMustache/Template+Render.swift index aca2f0c..cb54ce3 100644 --- a/Sources/HummingbirdMustache/Template+Render.swift +++ b/Sources/HummingbirdMustache/Template+Render.swift @@ -9,9 +9,9 @@ extension HBMustacheTemplate { var string = "" for token in tokens { switch token { - case .text(let text): + case let .text(text): string += text - case .variable(let variable, let method): + case let .variable(variable, method): if let child = getChild(named: variable, from: object, method: method, context: context) { if let template = child as? HBMustacheTemplate { string += template.render(object) @@ -19,19 +19,19 @@ extension HBMustacheTemplate { string += String(describing: child).htmlEscape() } } - case .unescapedVariable(let variable, let method): + case let .unescapedVariable(variable, method): if let child = getChild(named: variable, from: object, method: method, context: context) { string += String(describing: child) } - case .section(let variable, let method, let template): + case let .section(variable, method, template): let child = getChild(named: variable, from: object, method: method, context: context) string += renderSection(child, parent: object, with: template) - - case .invertedSection(let variable, let method, let template): + + case let .invertedSection(variable, method, template): let child = getChild(named: variable, from: object, method: method, context: context) string += renderInvertedSection(child, parent: object, with: template) - - case .partial(let name): + + case let .partial(name): if let text = library?.render(object, withTemplate: name) { string += text } @@ -54,13 +54,13 @@ extension HBMustacheTemplate { return bool ? template.render(parent) : "" case let lambda as HBMustacheLambda: return lambda.run(parent, template) - case .some(let value): + case let .some(value): return template.render(value) case .none: return "" } } - + /// Render an inverted section /// - Parameters: /// - child: Object to render section for @@ -111,7 +111,8 @@ extension HBMustacheTemplate { // if we want to run a method and the current child can have methods applied to it then // run method on the current child if let method = method, - let runnable = child as? HBMustacheMethods { + let runnable = child as? HBMustacheMethods + { if let result = runnable.runMethod(method) { return result } @@ -119,4 +120,3 @@ extension HBMustacheTemplate { return child } } - diff --git a/Sources/HummingbirdMustache/Template.swift b/Sources/HummingbirdMustache/Template.swift index a85d48c..c2e5c54 100644 --- a/Sources/HummingbirdMustache/Template.swift +++ b/Sources/HummingbirdMustache/Template.swift @@ -4,16 +4,16 @@ public class HBMustacheTemplate { /// - Parameter string: Template text /// - Throws: HBMustacheTemplate.Error public init(string: String) throws { - self.tokens = try Self.parse(string) + tokens = try Self.parse(string) } /// Render object using this template /// - Parameter object: Object to render /// - Returns: Rendered text public func render(_ object: Any) -> String { - self.render(object, context: nil) + render(object, context: nil) } - + internal init(_ tokens: [Token]) { self.tokens = tokens } @@ -22,14 +22,14 @@ public class HBMustacheTemplate { self.library = library for token in tokens { switch token { - case .section(_, _, let template), .invertedSection(_, _, let template): + case let .section(_, _, template), let .invertedSection(_, _, template): template.setLibrary(library) default: break } } } - + enum Token { case text(String) case variable(name: String, method: String? = nil) @@ -42,4 +42,3 @@ public class HBMustacheTemplate { let tokens: [Token] var library: HBMustacheLibrary? } - diff --git a/Tests/HummingbirdMustacheTests/LibraryTests.swift b/Tests/HummingbirdMustacheTests/LibraryTests.swift index 2cb1929..f23bfbb 100644 --- a/Tests/HummingbirdMustacheTests/LibraryTests.swift +++ b/Tests/HummingbirdMustacheTests/LibraryTests.swift @@ -1,5 +1,5 @@ -import XCTest @testable import HummingbirdMustache +import XCTest final class LibraryTests: XCTestCase { func testDirectoryLoad() throws { @@ -10,7 +10,7 @@ final class LibraryTests: XCTestCase { defer { XCTAssertNoThrow(try fs.removeItem(atPath: "templates")) } try data.write(to: URL(fileURLWithPath: "templates/test.mustache")) defer { XCTAssertNoThrow(try fs.removeItem(atPath: "templates/test.mustache")) } - + let library = HBMustacheLibrary(directory: "./templates") let object = ["value": ["value1", "value2"]] XCTAssertEqual(library.render(object, withTemplate: "test"), "value1value2") diff --git a/Tests/HummingbirdMustacheTests/MethodTests.swift b/Tests/HummingbirdMustacheTests/MethodTests.swift index 6a8ac17..a6e9cd0 100644 --- a/Tests/HummingbirdMustacheTests/MethodTests.swift +++ b/Tests/HummingbirdMustacheTests/MethodTests.swift @@ -1,117 +1,117 @@ -import XCTest import HummingbirdMustache +import XCTest final class MethodTests: XCTestCase { func testLowercased() throws { let template = try HBMustacheTemplate(string: """ - {{ lowercased(name) }} - """) + {{ lowercased(name) }} + """) let object: [String: Any] = ["name": "Test"] XCTAssertEqual(template.render(object), "test") } func testUppercased() throws { let template = try HBMustacheTemplate(string: """ - {{ uppercased(name) }} - """) + {{ uppercased(name) }} + """) let object: [String: Any] = ["name": "Test"] XCTAssertEqual(template.render(object), "TEST") } func testFirstLast() throws { let template = try HBMustacheTemplate(string: """ - {{#repo}} - {{#first()}}first: {{/}}{{#last()}}last: {{/}}{{ name }} - {{/repo}} - """) + {{#repo}} + {{#first()}}first: {{/}}{{#last()}}last: {{/}}{{ name }} + {{/repo}} + """) let object: [String: Any] = ["repo": [["name": "resque"], ["name": "hub"], ["name": "rip"]]] XCTAssertEqual(template.render(object), """ - first: resque - hub - last: rip + first: resque + hub + last: rip - """) + """) } func testIndex() throws { let template = try HBMustacheTemplate(string: """ - {{#repo}} - {{#index()}}{{plusone(.)}}{{/}}) {{ name }} - {{/repo}} - """) + {{#repo}} + {{#index()}}{{plusone(.)}}{{/}}) {{ name }} + {{/repo}} + """) let object: [String: Any] = ["repo": [["name": "resque"], ["name": "hub"], ["name": "rip"]]] XCTAssertEqual(template.render(object), """ - 1) resque - 2) hub - 3) rip + 1) resque + 2) hub + 3) rip - """) + """) } func testEvenOdd() throws { let template = try HBMustacheTemplate(string: """ - {{#repo}} - {{index()}}) {{#even()}}even {{/}}{{#odd()}}odd {{/}}{{ name }} - {{/repo}} - """) + {{#repo}} + {{index()}}) {{#even()}}even {{/}}{{#odd()}}odd {{/}}{{ name }} + {{/repo}} + """) let object: [String: Any] = ["repo": [["name": "resque"], ["name": "hub"], ["name": "rip"]]] XCTAssertEqual(template.render(object), """ - 0) even resque - 1) odd hub - 2) even rip + 0) even resque + 1) odd hub + 2) even rip - """) + """) } func testReversed() throws { let template = try HBMustacheTemplate(string: """ - {{#reversed(repo)}} - {{ name }} - {{/repo}} - """) + {{#reversed(repo)}} + {{ name }} + {{/repo}} + """) let object: [String: Any] = ["repo": [["name": "resque"], ["name": "hub"], ["name": "rip"]]] XCTAssertEqual(template.render(object), """ - rip - hub - resque + rip + hub + resque - """) + """) } func testArrayIndex() throws { let template = try HBMustacheTemplate(string: """ - {{#repo}} - {{ index() }}) {{ name }} - {{/repo}} - """) + {{#repo}} + {{ index() }}) {{ name }} + {{/repo}} + """) let object: [String: Any] = ["repo": [["name": "resque"], ["name": "hub"], ["name": "rip"]]] XCTAssertEqual(template.render(object), """ - 0) resque - 1) hub - 2) rip + 0) resque + 1) hub + 2) rip - """) + """) } func testArraySorted() throws { let template = try HBMustacheTemplate(string: """ - {{#sorted(repo)}} - {{ index() }}) {{ . }} - {{/repo}} - """) + {{#sorted(repo)}} + {{ index() }}) {{ . }} + {{/repo}} + """) let object: [String: Any] = ["repo": ["resque", "hub", "rip"]] XCTAssertEqual(template.render(object), """ - 0) hub - 1) resque - 2) rip + 0) hub + 1) resque + 2) rip - """) + """) } func testDictionaryEnumerated() throws { let template = try HBMustacheTemplate(string: """ - {{#enumerated(.)}}{{ key }} = {{ value }}{{/.}} - """) + {{#enumerated(.)}}{{ key }} = {{ value }}{{/.}} + """) let object: [String: Any] = ["one": 1, "two": 2] let result = template.render(object) XCTAssertTrue(result == "one = 1two = 2" || result == "two = 2one = 1") @@ -119,11 +119,10 @@ final class MethodTests: XCTestCase { func testDictionarySortedByKey() throws { let template = try HBMustacheTemplate(string: """ - {{#sorted(.)}}{{ key }} = {{ value }}{{/.}} - """) + {{#sorted(.)}}{{ key }} = {{ value }}{{/.}} + """) let object: [String: Any] = ["one": 1, "two": 2, "three": 3] let result = template.render(object) XCTAssertEqual(result, "one = 1three = 3two = 2") } - } diff --git a/Tests/HummingbirdMustacheTests/PartialTests.swift b/Tests/HummingbirdMustacheTests/PartialTests.swift index cb6c5b8..73fa726 100644 --- a/Tests/HummingbirdMustacheTests/PartialTests.swift +++ b/Tests/HummingbirdMustacheTests/PartialTests.swift @@ -1,54 +1,53 @@ -import XCTest @testable import HummingbirdMustache +import XCTest final class PartialTests: XCTestCase { - /// Testing partials func testMustacheManualExample9() throws { let library = HBMustacheLibrary() let template = try HBMustacheTemplate(string: """ -

Names

- {{#names}} - {{> user}} - {{/names}} - """) +

Names

+ {{#names}} + {{> user}} + {{/names}} + """) let template2 = try HBMustacheTemplate(string: """ - {{.}} - """) + {{.}} + """) library.register(template, named: "base") library.register(template2, named: "user") - + let object: [String: Any] = ["names": ["john", "adam", "claire"]] XCTAssertEqual(library.render(object, withTemplate: "base"), """ -

Names

- john - adam - claire +

Names

+ john + adam + claire - """) + """) } /// Testing dynamic partials func testDynamicPartials() throws { let library = HBMustacheLibrary() let template = try HBMustacheTemplate(string: """ -

Names

- {{partial}} - """) +

Names

+ {{partial}} + """) let template2 = try HBMustacheTemplate(string: """ - {{#names}} - {{.}} - {{/names}} - """) + {{#names}} + {{.}} + {{/names}} + """) library.register(template, named: "base") - + let object: [String: Any] = ["names": ["john", "adam", "claire"], "partial": template2] XCTAssertEqual(library.render(object, withTemplate: "base"), """ -

Names

- john - adam - claire +

Names

+ john + adam + claire - """) + """) } } diff --git a/Tests/HummingbirdMustacheTests/TemplateParserTests.swift b/Tests/HummingbirdMustacheTests/TemplateParserTests.swift index 410d0b5..5e84d32 100644 --- a/Tests/HummingbirdMustacheTests/TemplateParserTests.swift +++ b/Tests/HummingbirdMustacheTests/TemplateParserTests.swift @@ -1,5 +1,5 @@ -import XCTest @testable import HummingbirdMustache +import XCTest final class TemplateParserTests: XCTestCase { func testText() throws { @@ -75,15 +75,15 @@ extension HBMustacheTemplate: Equatable { extension HBMustacheTemplate.Token: Equatable { public static func == (lhs: HBMustacheTemplate.Token, rhs: HBMustacheTemplate.Token) -> Bool { switch (lhs, rhs) { - case (.text(let lhs), .text(let rhs)): + case let (.text(lhs), .text(rhs)): return lhs == rhs - case (.variable(let lhs, let lhs2), .variable(let rhs, let rhs2)): + case let (.variable(lhs, lhs2), .variable(rhs, rhs2)): return lhs == rhs && lhs2 == rhs2 - case (.section(let lhs1, let lhs2, let lhs3), .section(let rhs1, let rhs2, let rhs3)): + case let (.section(lhs1, lhs2, lhs3), .section(rhs1, rhs2, rhs3)): return lhs1 == rhs1 && lhs2 == rhs2 && lhs3 == rhs3 - case (.invertedSection(let lhs1, let lhs2, let lhs3), .invertedSection(let rhs1, let rhs2, let rhs3)): + case let (.invertedSection(lhs1, lhs2, lhs3), .invertedSection(rhs1, rhs2, rhs3)): return lhs1 == rhs1 && lhs2 == rhs2 && lhs3 == rhs3 - case (.partial(let name1), .partial(let name2)): + case let (.partial(name1), .partial(name2)): return name1 == name2 default: return false diff --git a/Tests/HummingbirdMustacheTests/TemplateRendererTests.swift b/Tests/HummingbirdMustacheTests/TemplateRendererTests.swift index e18d651..40f374b 100644 --- a/Tests/HummingbirdMustacheTests/TemplateRendererTests.swift +++ b/Tests/HummingbirdMustacheTests/TemplateRendererTests.swift @@ -1,5 +1,5 @@ -import XCTest @testable import HummingbirdMustache +import XCTest final class TemplateRendererTests: XCTestCase { func testText() throws { @@ -67,7 +67,7 @@ final class TemplateRendererTests: XCTestCase { XCTAssertEqual(template.render(Test(string: "string")), "test string") XCTAssertEqual(template.render(Test(string: nil)), "test ") } - + func testOptionalSequence() throws { struct Test { let string: String? @@ -79,7 +79,7 @@ final class TemplateRendererTests: XCTestCase { XCTAssertEqual(template2.render(Test(string: "string")), "test ") XCTAssertEqual(template2.render(Test(string: nil)), "test *") } - + func testStructureInStructure() throws { struct SubTest { let string: String? @@ -95,134 +95,134 @@ final class TemplateRendererTests: XCTestCase { /// variables func testMustacheManualExample1() throws { let template = try HBMustacheTemplate(string: """ - Hello {{name}} - You have just won {{value}} dollars! - {{#in_ca}} - Well, {{taxed_value}} dollars, after taxes. - {{/in_ca}} - """) + Hello {{name}} + You have just won {{value}} dollars! + {{#in_ca}} + Well, {{taxed_value}} dollars, after taxes. + {{/in_ca}} + """) let object: [String: Any] = ["name": "Chris", "value": 10000, "taxed_value": 10000 - (10000 * 0.4), "in_ca": true] XCTAssertEqual(template.render(object), """ - Hello Chris - You have just won 10000 dollars! - Well, 6000.0 dollars, after taxes. + Hello Chris + You have just won 10000 dollars! + Well, 6000.0 dollars, after taxes. - """) + """) } /// test esacped and unescaped text func testMustacheManualExample2() throws { let template = try HBMustacheTemplate(string: """ - *{{name}} - *{{age}} - *{{company}} - *{{{company}}} - """) + *{{name}} + *{{age}} + *{{company}} + *{{{company}}} + """) let object: [String: Any] = ["name": "Chris", "company": "GitHub"] XCTAssertEqual(template.render(object), """ - *Chris - * - *<b>GitHub</b> - *GitHub - """) + *Chris + * + *<b>GitHub</b> + *GitHub + """) } /// test boolean func testMustacheManualExample3() throws { let template = try HBMustacheTemplate(string: """ - Shown. - {{#person}} - Never shown! - {{/person}} - """) + Shown. + {{#person}} + Never shown! + {{/person}} + """) let object: [String: Any] = ["person": false] XCTAssertEqual(template.render(object), """ - Shown. + Shown. - """) + """) } /// test non-empty lists func testMustacheManualExample4() throws { let template = try HBMustacheTemplate(string: """ - {{#repo}} - {{name}} - {{/repo}} - """) + {{#repo}} + {{name}} + {{/repo}} + """) let object: [String: Any] = ["repo": [["name": "resque"], ["name": "hub"], ["name": "rip"]]] XCTAssertEqual(template.render(object), """ - resque - hub - rip + resque + hub + rip - """) + """) } - + /// test lambdas func testMustacheManualExample5() throws { let template = try HBMustacheTemplate(string: """ - {{#wrapped}}{{name}} is awesome.{{/wrapped}} - """) + {{#wrapped}}{{name}} is awesome.{{/wrapped}} + """) func wrapped(object: Any, template: HBMustacheTemplate) -> String { return "\(template.render(object))" } let object: [String: Any] = ["name": "Willy", "wrapped": HBMustacheLambda(wrapped)] XCTAssertEqual(template.render(object), """ - Willy is awesome. - """) + Willy is awesome. + """) } - + /// test setting context object func testMustacheManualExample6() throws { let template = try HBMustacheTemplate(string: """ - {{#person?}} - Hi {{name}}! - {{/person?}} - """) + {{#person?}} + Hi {{name}}! + {{/person?}} + """) let object: [String: Any] = ["person?": ["name": "Jon"]] XCTAssertEqual(template.render(object), """ - Hi Jon! + Hi Jon! - """) + """) } - + /// test inverted sections func testMustacheManualExample7() throws { let template = try HBMustacheTemplate(string: """ - {{#repo}} - {{name}} - {{/repo}} - {{^repo}} - No repos :( - {{/repo}} - """) + {{#repo}} + {{name}} + {{/repo}} + {{^repo}} + No repos :( + {{/repo}} + """) let object: [String: Any] = ["repo": []] XCTAssertEqual(template.render(object), """ - No repos :( + No repos :( - """) + """) } - + /// test comments func testMustacheManualExample8() throws { let template = try HBMustacheTemplate(string: """ -

Today{{! ignore me }}.

- """) +

Today{{! ignore me }}.

+ """) let object: [String: Any] = ["repo": []] XCTAssertEqual(template.render(object), """ -

Today.

- """) +

Today.

+ """) } func testPerformance() throws { let template = try HBMustacheTemplate(string: """ - {{#repo}} - {{name}} - {{/repo}} - """) + {{#repo}} + {{name}} + {{/repo}} + """) let object: [String: Any] = ["repo": [["name": "resque"], ["name": "hub"], ["name": "rip"]]] let date = Date() - for _ in 1...10000 { + for _ in 1 ... 10000 { _ = template.render(object) } print(-date.timeIntervalSinceNow)