forked from groue/GRMustache.swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TemplateRepository.swift
556 lines (485 loc) · 24.3 KB
/
TemplateRepository.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
// The MIT License
//
// Copyright (c) 2015 Gwendal Roué
//
// 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
/// See the documentation of the `TemplateRepositoryDataSource` protocol.
public typealias TemplateID = String
/// The protocol for a TemplateRepository's dataSource.
///
/// The dataSource's responsability is to provide Mustache template strings for
/// template and partial names.
public protocol TemplateRepositoryDataSource {
/// Returns a template ID, that is to say a string that uniquely identifies
/// a template or a template partial.
///
/// The meaning of this String is opaque: your implementation of a
/// `TemplateRepositoryDataSource` would define, for itself, how strings
/// would identity a template or a partial. For example, a file-based data
/// source may use paths to the templates.
///
/// The return value of this method can be nil: the library user will then
/// eventually catch a missing template error.
///
/// ### Template hierarchies
///
/// Whenever relevant, template and partial hierarchies are supported via
/// the baseTemplateID parameter: it contains the template ID of the
/// enclosing template, or nil when the data source is asked for a
/// template ID from a raw template string (see
/// TemplateRepository.template(string:error:)).
///
/// Not all data sources have to implement hierarchies: they can simply
/// ignore this parameter.
///
/// *Well-behaved* data sources that support hierarchies should support
/// "absolute paths to partials". For example, the built-in directory-based
/// data source lets users write both `{{> relative/path/to/partial}}` and
/// `{{> /absolute/path/tp/partial}}`tags.
///
/// ### Unique IDs
///
/// Each template must be identified by a single template ID. For example, a
/// file-based data source which uses path IDs must normalize paths. Not
/// following this rule yields undefined behavior.
///
/// - parameter name: The name of the template or template partial.
/// - parameter baseTemplateID: The template ID of the enclosing template.
/// - returns: A template ID.
func templateIDForName(_ name: String, relativeToTemplateID baseTemplateID: TemplateID?) -> TemplateID?
/// Returns the Mustache template string that matches the template ID.
///
/// - parameter templateID: The template ID of the template.
/// - throws: MustacheError
/// - returns: A Mustache template string.
func templateStringForTemplateID(_ templateID: TemplateID) throws -> String
}
/// A template repository represents a set of sibling templates and partials.
///
/// You don't have to instanciate template repositories, because GRMustache
/// provides implicit ones whenever you load templates with methods like
/// `Template(named:error:)`, for example.
///
/// However, you may like to use one for your profit. Template repositories
/// provide:
///
/// - custom template data source
/// - custom `Configuration`
/// - a cache of template parsings
/// - absolute paths to ease loading of partial templates in a hierarchy of
/// directories and template files
final public class TemplateRepository {
// =========================================================================
// MARK: - Creating Template Repositories
/// Creates a TemplateRepository which loads template through the provided
/// dataSource.
///
/// The dataSource is optional, but repositories without dataSource can not
/// load templates by name, and can only parse template strings that do not
/// contain any `{{> partial }}` tag.
///
/// let repository = TemplateRepository()
/// let template = try! repository.template(string: "Hello {{name}}")
public init(dataSource: TemplateRepositoryDataSource? = nil, configuration: Configuration = .default) {
self.configuration = configuration
templateASTCache = [:]
self.dataSource = dataSource
}
/// Creates a TemplateRepository that loads templates from a dictionary.
///
/// let templates = ["template": "Hulk Hogan has a Mustache."]
/// let repository = TemplateRepository(templates: templates)
///
/// // Renders "Hulk Hogan has a Mustache." twice
/// try! repository.template(named: "template").render()
/// try! repository.template(string: "{{>template}}").render()
///
/// - parameter templates: A dictionary whose keys are template names and
/// values template strings.
/// - parameter configuration: The configuration for rendering. If the configuration is not specified, `Configuration.default` is used.
convenience public init(templates: [String: String], configuration: Configuration = .default) {
self.init(dataSource: DictionaryDataSource(templates: templates), configuration: configuration)
}
/// Creates a TemplateRepository that loads templates from a directory.
///
/// let repository = TemplateRepository(directoryPath: "/path/to/templates")
///
/// // Loads /path/to/templates/template.mustache
/// let template = try! repository.template(named: "template")
///
///
/// Eventual partial tags in template files refer to sibling template files.
///
/// If the target directory contains a hierarchy of template files and
/// sub-directories, you can navigate through this hierarchy with both
/// relative and absolute paths to partials. For example, given the
/// following hierarchy:
///
/// - /path/to/templates
/// - a.mustache
/// - partials
/// - b.mustache
///
/// The a.mustache template can embed b.mustache with both
/// `{{> partials/b }}` and `{{> /partials/b }}` partial tags.
///
/// The b.mustache template can embed a.mustache with both `{{> ../a }}` and
/// `{{> /a }}` partial tags.
///
///
/// - parameter directoryPath: The path to the directory containing
/// template files.
/// - parameter templateExtension: The extension of template files. Default
/// extension is "mustache".
/// - parameter encoding: The encoding of template files. Default encoding
/// is UTF-8.
/// - parameter configuration: The configuration for rendering. If the configuration is not specified, `Configuration.default` is used.
convenience public init(directoryPath: String, templateExtension: String? = "mustache", encoding: String.Encoding = String.Encoding.utf8, configuration: Configuration = .default) {
self.init(dataSource: URLDataSource(baseURL: URL(fileURLWithPath: directoryPath, isDirectory: true), templateExtension: templateExtension, encoding: encoding), configuration: configuration)
}
/// Creates a TemplateRepository that loads templates from a URL.
///
/// let templatesURL = NSURL.fileURLWithPath("/path/to/templates")!
/// let repository = TemplateRepository(baseURL: templatesURL)
///
/// // Loads /path/to/templates/template.mustache
/// let template = try! repository.template(named: "template")
///
///
/// Eventual partial tags in template files refer to sibling template files.
///
/// If the target directory contains a hierarchy of template files and
/// sub-directories, you can navigate through this hierarchy with both
/// relative and absolute paths to partials. For example, given the
/// following hierarchy:
///
/// - /path/to/templates
/// - a.mustache
/// - partials
/// - b.mustache
///
/// The a.mustache template can embed b.mustache with both `{{> partials/b }}`
/// and `{{> /partials/b }}` partial tags.
///
/// The b.mustache template can embed a.mustache with both `{{> ../a }}` and
/// `{{> /a }}` partial tags.
///
///
/// - parameter baseURL: The base URL where to look for templates.
/// - parameter templateExtension: The extension of template resources.
/// Default extension is "mustache".
/// - parameter encoding: The encoding of template resources. Default
/// encoding is UTF-8.
/// - parameter configuration: The configuration for rendering. If the configuration is not specified, `Configuration.default` is used.
convenience public init(baseURL: URL, templateExtension: String? = "mustache", encoding: String.Encoding = String.Encoding.utf8, configuration: Configuration = .default) {
self.init(dataSource: URLDataSource(baseURL: baseURL, templateExtension: templateExtension, encoding: encoding), configuration: configuration)
}
/// Creates a TemplateRepository that loads templates stored as resources in
/// a bundle.
///
/// let repository = TemplateRepository(bundle: nil)
///
/// // Loads the template.mustache resource of the main bundle:
/// let template = try! repository.template(named: "template")
///
/// - parameter bundle: The bundle that stores templates resources. Nil
/// stands for the main bundle.
/// - parameter templateExtension: The extension of template resources.
/// Default extension is "mustache".
/// - parameter encoding: The encoding of template resources. Default
/// encoding is UTF-8.
/// - parameter configuration: The configuration for rendering. If the configuration is not specified, `Configuration.default` is used.
convenience public init(bundle: Bundle?, templateExtension: String? = "mustache", encoding: String.Encoding = String.Encoding.utf8, configuration: Configuration = .default) {
self.init(dataSource: BundleDataSource(bundle: bundle ?? Bundle.main, templateExtension: templateExtension, encoding: encoding), configuration: configuration)
}
// =========================================================================
// MARK: - Configuring Template Repositories
/// The configuration for all templates and partials built by
/// the repository.
///
/// It is initialized with `Mustache.DefaultConfiguration`.
///
/// You can alter the repository's configuration, or set it to another
/// value, before you load templates:
///
/// // Reset the configuration to a factory configuration and change tag delimiters:
/// let repository = TemplateRepository()
/// repository.configuration = Configuration()
/// repository.configuration.tagDelimiterPair = ("<%", "%>")
///
/// // Renders "Hello Luigi"
/// let template = try! repository.template(string: "Hello <%name%>")
/// try! template.render(["name": "Luigi"])
///
/// Changing the configuration has no effect after the repository has loaded
/// one template.
public var configuration: Configuration
// =========================================================================
// MARK: - Loading Templates from a Repository
/// The template repository data source, responsible for loading template
/// strings.
public let dataSource: TemplateRepositoryDataSource?
/// Creates a template from a template string.
///
/// Depending on the way the repository has been created, partial tags such
/// as `{{>partial}}` load partial templates from URLs, file paths, keys in
/// a dictionary, or whatever is relevant to the repository's data source.
///
/// - parameter templateString: A Mustache template string.
/// - throws: MustacheError
/// - returns: A Mustache Template.
public func template(string: String) throws -> Template {
let templateAST = try self.templateAST(string: string)
return Template(repository: self, templateAST: templateAST, baseContext: lockedConfiguration.baseContext)
}
/// Creates a template, identified by its name.
///
/// Depending on the repository's data source, the name identifies a bundle
/// resource, a URL, a file path, a key in a dictionary, etc.
///
/// Template repositories cache the parsing of their templates. However this
/// method always return new Template instances, which you can further
/// configure independently.
///
/// - parameter name: The template name.
/// - throws: MustacheError
/// - returns: A Mustache Template.
///
/// - seealso: reloadTemplates()
public func template(named name: String) throws -> Template {
let templateAST = try self.templateAST(named: name, relativeToTemplateID: nil)
return Template(repository: self, templateAST: templateAST, baseContext: lockedConfiguration.baseContext)
}
/// Clears the cache of parsed template strings.
///
/// // May reuse a cached parsing:
/// let template = try! repository.template(named:"profile")
///
/// // Forces the reloading of the template:
/// repository.reloadTemplates();
/// let template = try! repository.template(named:"profile")
///
/// Note that previously created Template instances are not reloaded.
public func reloadTemplates() {
templateASTCache.removeAll()
}
// =========================================================================
// MARK: - Not public
func templateAST(named name: String, relativeToTemplateID baseTemplateID: TemplateID? = nil) throws -> TemplateAST {
guard let dataSource = self.dataSource else {
throw MustacheError(kind: .templateNotFound, message: "Missing dataSource", templateID: baseTemplateID)
}
guard let templateID = dataSource.templateIDForName(name, relativeToTemplateID: baseTemplateID) else {
if let baseTemplateID = baseTemplateID {
throw MustacheError(kind: .templateNotFound, message: "Template not found: \"\(name)\" from \(baseTemplateID)", templateID: baseTemplateID)
} else {
throw MustacheError(kind: .templateNotFound, message: "Template not found: \"\(name)\"")
}
}
if let templateAST = templateASTCache[templateID] {
// Return cached AST
return templateAST
}
let templateString = try dataSource.templateStringForTemplateID(templateID)
// Cache an empty AST for that name so that we support recursive
// partials.
let templateAST = TemplateAST()
templateASTCache[templateID] = templateAST
do {
let compiledAST = try self.templateAST(string: templateString, templateID: templateID)
// Success: update the empty AST
templateAST.updateFromTemplateAST(compiledAST)
return templateAST
} catch {
// Failure: remove the empty AST
templateASTCache.removeValue(forKey: templateID)
throw error
}
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, *)
func templateAST(named name: String, relativeToTemplateID baseTemplateID: TemplateID? = nil) async throws -> TemplateAST {
guard let dataSource = self.dataSource else {
throw MustacheError(kind: .templateNotFound, message: "Missing dataSource", templateID: baseTemplateID)
}
guard let templateID = dataSource.templateIDForName(name, relativeToTemplateID: baseTemplateID) else {
if let baseTemplateID = baseTemplateID {
throw MustacheError(kind: .templateNotFound, message: "Template not found: \"\(name)\" from \(baseTemplateID)", templateID: baseTemplateID)
} else {
throw MustacheError(kind: .templateNotFound, message: "Template not found: \"\(name)\"")
}
}
if let templateAST = templateASTCache[templateID] {
// Return cached AST
return templateAST
}
let templateString = try await dataSource.templateStringForTemplateID(templateID)
// Cache an empty AST for that name so that we support recursive
// partials.
let templateAST = TemplateAST()
templateASTCache[templateID] = templateAST
do {
let compiledAST = try self.templateAST(string: templateString, templateID: templateID)
// Success: update the empty AST
templateAST.updateFromTemplateAST(compiledAST)
return templateAST
} catch {
// Failure: remove the empty AST
templateASTCache.removeValue(forKey: templateID)
throw error
}
}
func templateAST(string: String, templateID: TemplateID? = nil) throws -> TemplateAST {
// A Compiler
let compiler = TemplateCompiler(
contentType: lockedConfiguration.contentType,
repository: self,
templateID: templateID)
// A Parser that feeds the compiler
let parser = TemplateParser(
tokenConsumer: compiler,
tagDelimiterPair: lockedConfiguration.tagDelimiterPair)
// Parse...
parser.parse(string, templateID: templateID)
// ...and extract the result from the Compiler
return try compiler.templateAST()
}
fileprivate var _lockedConfiguration: Configuration?
fileprivate var lockedConfiguration: Configuration {
// Changing mutable values within the repository's configuration no
// longer has any effect.
if _lockedConfiguration == nil {
_lockedConfiguration = configuration
}
return _lockedConfiguration!
}
fileprivate var templateASTCache: [TemplateID: TemplateAST]
// -------------------------------------------------------------------------
// MARK: DictionaryDataSource
fileprivate class DictionaryDataSource: TemplateRepositoryDataSource {
let templates: [String: String]
init(templates: [String: String]) {
self.templates = templates
}
func templateIDForName(_ name: String, relativeToTemplateID baseTemplateID: TemplateID?) -> TemplateID? {
return name
}
func templateStringForTemplateID(_ templateID: TemplateID) throws -> String {
if let string = templates[templateID] {
return string
} else {
throw MustacheError(kind: .templateNotFound, templateID: templateID)
}
}
}
// -------------------------------------------------------------------------
// MARK: URLDataSource
fileprivate class URLDataSource: TemplateRepositoryDataSource {
let baseURLAbsoluteString: String
let baseURL: URL
let templateExtension: String?
let encoding: String.Encoding
init(baseURL: URL, templateExtension: String?, encoding: String.Encoding) {
self.baseURL = baseURL
self.baseURLAbsoluteString = baseURL.standardizedFileURL.absoluteString
self.templateExtension = templateExtension
self.encoding = encoding
}
func templateIDForName(_ name: String, relativeToTemplateID baseTemplateID: TemplateID?) -> TemplateID? {
// Rebase template names starting with a /
let normalizedName: String
let normalizedBaseTemplateID: TemplateID?
if !name.isEmpty && name[name.startIndex] == "/" {
normalizedName = String(name[name.index(after: name.startIndex)...])
normalizedBaseTemplateID = nil
} else {
normalizedName = name
normalizedBaseTemplateID = baseTemplateID
}
if normalizedName.isEmpty {
return normalizedBaseTemplateID
}
let templateFilename: String
if let templateExtension = self.templateExtension , !templateExtension.isEmpty {
templateFilename = (normalizedName as NSString).appendingPathExtension(templateExtension)!
} else {
templateFilename = normalizedName
}
let templateBaseURL: URL
if let normalizedBaseTemplateID = normalizedBaseTemplateID {
templateBaseURL = URL(string: normalizedBaseTemplateID)!
} else {
templateBaseURL = self.baseURL
}
let encodedURLPath = templateFilename.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!
let templateURL = URL(string: encodedURLPath, relativeTo: templateBaseURL)!.standardizedFileURL
let templateAbsoluteString = templateURL.absoluteString
// Make sure partial relative paths can not escape repository root
if templateAbsoluteString.range(of: baseURLAbsoluteString)?.lowerBound == templateAbsoluteString.startIndex {
return templateAbsoluteString
} else {
return nil
}
}
func templateStringForTemplateID(_ templateID: TemplateID) throws -> String {
return try NSString(contentsOf: URL(string: templateID)!, encoding: encoding.rawValue) as String
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, *)
func templateStringForTemplateID(_ templateID: TemplateID) async throws -> String {
let (data, _) = try await URLSession.shared.data(from: URL(string: templateID)!)
return (NSString(data: data, encoding: encoding.rawValue) ?? "") as String
}
}
// -------------------------------------------------------------------------
// MARK: BundleDataSource
fileprivate class BundleDataSource: TemplateRepositoryDataSource {
let bundle: Bundle
let templateExtension: String?
let encoding: String.Encoding
init(bundle: Bundle, templateExtension: String?, encoding: String.Encoding) {
self.bundle = bundle
self.templateExtension = templateExtension
self.encoding = encoding
}
func templateIDForName(_ name: String, relativeToTemplateID baseTemplateID: TemplateID?) -> TemplateID? {
// Rebase template names starting with a /
let normalizedName: String
let normalizedBaseTemplateID: TemplateID?
if !name.isEmpty && name[name.startIndex] == "/" {
normalizedName = String(name[name.index(after: name.startIndex)...])
normalizedBaseTemplateID = nil
} else {
normalizedName = name
normalizedBaseTemplateID = baseTemplateID
}
if normalizedName.isEmpty {
return normalizedBaseTemplateID
}
if let normalizedBaseTemplateID = normalizedBaseTemplateID {
let relativePath = (normalizedBaseTemplateID as NSString).deletingLastPathComponent.replacingOccurrences(of: bundle.resourcePath!, with:"")
return bundle.path(forResource: normalizedName, ofType: templateExtension, inDirectory: relativePath)
} else {
return bundle.path(forResource: normalizedName, ofType: templateExtension)
}
}
func templateStringForTemplateID(_ templateID: TemplateID) throws -> String {
return try NSString(contentsOfFile: templateID, encoding: encoding.rawValue) as String
}
}
}