/
StencilSwiftTemplate.swift
49 lines (44 loc) · 1.74 KB
/
StencilSwiftTemplate.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
//
// StencilSwiftKit
// Copyright © 2022 SwiftGen
// MIT Licence
//
import Foundation
import Stencil
#if os(Linux) && !swift(>=3.1)
typealias NSRegularExpression = RegularExpression
#endif
// Workaround until Stencil fixes https://github.com/stencilproject/Stencil/issues/22
@available(*, deprecated, message: "No longer needed with Stencil whitespace control features")
open class StencilSwiftTemplate: Template {
public required init(templateString: String, environment: Environment? = nil, name: String? = nil) {
let templateStringWithMarkedNewlines = templateString
.replacingOccurrences(of: "\n\n", with: "\n\u{000b}\n")
.replacingOccurrences(of: "\n\n", with: "\n\u{000b}\n")
super.init(templateString: templateStringWithMarkedNewlines, environment: environment, name: name)
}
// swiftlint:disable:next discouraged_optional_collection
override open func render(_ dictionary: [String: Any]? = nil) throws -> String {
try removeExtraLines(from: super.render(dictionary))
}
// Workaround until Stencil fixes https://github.com/stencilproject/Stencil/issues/22
private func removeExtraLines(from str: String) -> String {
let extraLinesRE: NSRegularExpression = {
do {
return try NSRegularExpression(pattern: "\\n([ \\t]*\\n)+", options: [])
} catch {
fatalError("Regular Expression pattern error: \(error)")
}
}()
let compact = extraLinesRE.stringByReplacingMatches(
in: str,
options: [],
range: NSRange(location: 0, length: str.utf16.count),
withTemplate: "\n"
)
let unmarkedNewlines = compact
.replacingOccurrences(of: "\n\u{000b}\n", with: "\n\n")
.replacingOccurrences(of: "\n\u{000b}\n", with: "\n\n")
return unmarkedNewlines
}
}