20 Commits

Author SHA1 Message Date
T. R. Bernstein
6ff4a6b85d chore: Update PathKit dependency
Some checks failed
Danger / Danger Check (push) Has been cancelled
Lint Cocoapods / Pod Lint (push) Has been cancelled
SwiftLint / SwiftLint (push) Has been cancelled
Test SPM / Test SPM Linux (push) Has been cancelled
Test SPM / Test SPM macOS (push) Has been cancelled
Publish on Tag / GitHub Release (push) Has been cancelled
2026-04-17 04:24:51 +02:00
T. R. Bernstein
02f61d55a4 chore: release 0.15.2
Some checks failed
Danger / Danger Check (push) Has been cancelled
Lint Cocoapods / Pod Lint (push) Has been cancelled
SwiftLint / SwiftLint (push) Has been cancelled
Test SPM / Test SPM Linux (push) Has been cancelled
Test SPM / Test SPM macOS (push) Has been cancelled
Publish on Tag / GitHub Release (push) Has been cancelled
2025-09-30 23:14:57 +02:00
T. R. Bernstein
c25b7a52e7 feat: Allow tokens to be escaped 2025-09-30 23:13:05 +02:00
T. R. Bernstein
25d1507159 refactor: Use tabs for indent 2025-09-30 23:13:04 +02:00
T. R. Bernstein
6811c71bd6 refactor: Adapt to new repository 2025-09-30 23:12:59 +02:00
twodayslate
17af3bace1 docs: fix code example syntax (#348) 2024-12-22 12:54:30 +00:00
David Jennes
1aeeced65d Merge pull request #342 from art-divin/master
Prefer DynamicMemberLookup over KVC
2023-08-28 02:34:58 +02:00
Ruslan Alikhamov
ea58733eb6 added new version in CHANGELOG 2023-08-26 05:10:17 +00:00
Ruslan Alikhamov
003341d94c Merge branch 'master' of https://github.com/art-divin/Stencil 2023-08-26 05:08:36 +00:00
Ruslan Alikhamov
930db33028 updated changelog 2023-08-26 05:07:29 +00:00
Ruslan Alikhamov
6b6d6c2730 changed order of condition to make positive case first 2023-08-26 01:03:49 -04:00
Ruslan Alikhamov
973609e141 Update Variable.swift - Fixed a typo for objc runtime check 2023-08-20 15:05:35 +04:00
Ruslan Alikhamov
644687b885 prefer DynamicMemberLookup over KVC 2023-08-20 10:28:27 +00:00
David Jennes
4f222ac85d Merge pull request #329 from stencilproject/release/0.15.1
Some checks failed
Publish on Tag / Push To CocoaPods (push) Has been cancelled
Publish on Tag / GitHub Release (push) Has been cancelled
Release 0.15.1
2022-07-31 23:07:25 +02:00
David Jennes
3a98d1ef7d Bump version to 0.15.1 2022-07-31 23:05:06 +02:00
David Jennes
95a24b950f Small docs fix 2022-07-31 23:03:40 +02:00
David Jennes
a3df900bd2 Merge pull request #328 from stencilproject/feature/fix-lazy
Fix `LazyValueWrapper`
2022-07-31 22:58:06 +02:00
David Jennes
59b0c176c7 Changelog entry 2022-07-31 22:54:47 +02:00
David Jennes
bc5051ffe3 Fix implementation of lazy value wrapper 2022-07-31 22:53:24 +02:00
David Jennes
9444ee5c86 Reset changelog 2022-07-30 00:30:18 +02:00
68 changed files with 5654 additions and 6010 deletions

View File

@@ -2,7 +2,8 @@ name: Danger
on: on:
push: push:
branches: master branches:
- main
pull_request: pull_request:
jobs: jobs:

View File

@@ -2,7 +2,8 @@ name: Lint Cocoapods
on: on:
push: push:
branches: master branches:
- main
pull_request: pull_request:
jobs: jobs:

View File

@@ -2,7 +2,8 @@ name: SwiftLint
on: on:
push: push:
branches: master branches:
- main
pull_request: pull_request:
jobs: jobs:

View File

@@ -7,24 +7,6 @@ on:
workflow_dispatch: workflow_dispatch:
jobs: jobs:
cocoapods:
name: Push To CocoaPods
runs-on: ubuntu-latest
steps:
-
name: Checkout
uses: actions/checkout@v3
-
name: Set up Ruby
uses: ruby/setup-ruby@v1
with:
bundler-cache: true
-
name: Push to CocoaPods
run: bundle exec rake release:cocoapods
env:
COCOAPODS_TRUNK_TOKEN: ${{secrets.COCOAPODS_TRUNK_TOKEN}}
github: github:
name: GitHub Release name: GitHub Release
runs-on: ubuntu-latest runs-on: ubuntu-latest

View File

@@ -2,7 +2,8 @@ name: Test SPM
on: on:
push: push:
branches: master branches:
- main
pull_request: pull_request:
jobs: jobs:

View File

@@ -1,4 +1,4 @@
swiftlint_version: 0.48.0 swiftlint_version: 0.61.0
opt_in_rules: opt_in_rules:
- accessibility_label_for_image - accessibility_label_for_image
@@ -104,14 +104,6 @@ closure_body_length:
conditional_returns_on_newline: conditional_returns_on_newline:
if_only: true if_only: true
file_header:
required_pattern: |
\/\/
\/\/ Stencil
\/\/ Copyright © 2022 Stencil
\/\/ MIT Licence
\/\/
indentation_width: indentation_width:
indentation_width: 2 indentation_width: 2

View File

@@ -1,3 +1,21 @@
## 0.15.2
### Enhancements
- Prefer `DynamicMemberLookup` over KVC.
[##342](https://github.com/stencilproject/Stencil/pull/342)
[@art-divin](https://github.com/art-divin)
- Allow tokens to be escaped by a backslash, i.e. `\{{ something }}` would render to `{{ something }}`.
## 0.15.1
### Bug Fixes
- Fix bug in `LazyValueWrapper`, causing it to never resolve.
[David Jennes](https://github.com/djbe)
[#328](https://github.com/stencilproject/Stencil/pull/328)
## 0.15.0 ## 0.15.0
### Breaking ### Breaking

View File

@@ -4,13 +4,13 @@ source 'https://rubygems.org'
# The bare minimum for building, e.g. in Homebrew # The bare minimum for building, e.g. in Homebrew
group :build do group :build do
gem 'base64', '~> 0.3'
gem 'rake', '~> 13.0' gem 'rake', '~> 13.0'
gem 'xcpretty', '~> 0.3' gem 'xcpretty', '~> 0.3'
end end
# In addition to :build, for contributing # In addition to :build, for contributing
group :development do group :development do
gem 'cocoapods', '~> 1.11'
gem 'danger', '~> 8.4' gem 'danger', '~> 8.4'
gem 'rubocop', '~> 1.22' gem 'rubocop', '~> 1.22'
end end

View File

@@ -1,65 +1,16 @@
GEM GEM
remote: https://rubygems.org/ remote: https://rubygems.org/
specs: specs:
CFPropertyList (3.0.5) addressable (2.8.7)
rexml public_suffix (>= 2.0.2, < 7.0)
activesupport (6.1.6.1) ast (2.4.3)
concurrent-ruby (~> 1.0, >= 1.0.2) base64 (0.3.0)
i18n (>= 1.6, < 2)
minitest (>= 5.1)
tzinfo (~> 2.0)
zeitwerk (~> 2.3)
addressable (2.8.0)
public_suffix (>= 2.0.2, < 5.0)
algoliasearch (1.27.5)
httpclient (~> 2.8, >= 2.8.3)
json (>= 1.5.1)
ast (2.4.2)
atomos (0.1.3)
claide (1.1.0) claide (1.1.0)
claide-plugins (0.9.2) claide-plugins (0.9.2)
cork cork
nap nap
open4 (~> 1.3) open4 (~> 1.3)
cocoapods (1.11.3)
addressable (~> 2.8)
claide (>= 1.0.2, < 2.0)
cocoapods-core (= 1.11.3)
cocoapods-deintegrate (>= 1.0.3, < 2.0)
cocoapods-downloader (>= 1.4.0, < 2.0)
cocoapods-plugins (>= 1.0.0, < 2.0)
cocoapods-search (>= 1.0.0, < 2.0)
cocoapods-trunk (>= 1.4.0, < 2.0)
cocoapods-try (>= 1.1.0, < 2.0)
colored2 (~> 3.1)
escape (~> 0.0.4)
fourflusher (>= 2.3.0, < 3.0)
gh_inspector (~> 1.0)
molinillo (~> 0.8.0)
nap (~> 1.0)
ruby-macho (>= 1.0, < 3.0)
xcodeproj (>= 1.21.0, < 2.0)
cocoapods-core (1.11.3)
activesupport (>= 5.0, < 7)
addressable (~> 2.8)
algoliasearch (~> 1.0)
concurrent-ruby (~> 1.1)
fuzzy_match (~> 2.0.4)
nap (~> 1.0)
netrc (~> 0.11)
public_suffix (~> 4.0)
typhoeus (~> 1.0)
cocoapods-deintegrate (1.0.5)
cocoapods-downloader (1.6.3)
cocoapods-plugins (1.0.0)
nap
cocoapods-search (1.0.1)
cocoapods-trunk (1.6.0)
nap (>= 0.8, < 2.0)
netrc (~> 0.11)
cocoapods-try (1.2.0)
colored2 (3.1.2) colored2 (3.1.2)
concurrent-ruby (1.1.10)
cork (0.3.0) cork (0.3.0)
colored2 (~> 3.1) colored2 (~> 3.1)
danger (8.6.1) danger (8.6.1)
@@ -75,10 +26,7 @@ GEM
no_proxy_fix no_proxy_fix
octokit (~> 4.7) octokit (~> 4.7)
terminal-table (>= 1, < 4) terminal-table (>= 1, < 4)
escape (0.0.4) faraday (1.10.4)
ethon (0.15.0)
ffi (>= 1.15.0)
faraday (1.10.0)
faraday-em_http (~> 1.0) faraday-em_http (~> 1.0)
faraday-em_synchrony (~> 1.0) faraday-em_synchrony (~> 1.0)
faraday-excon (~> 1.1) faraday-excon (~> 1.1)
@@ -91,94 +39,89 @@ GEM
faraday-retry (~> 1.0) faraday-retry (~> 1.0)
ruby2_keywords (>= 0.0.4) ruby2_keywords (>= 0.0.4)
faraday-em_http (1.0.0) faraday-em_http (1.0.0)
faraday-em_synchrony (1.0.0) faraday-em_synchrony (1.0.1)
faraday-excon (1.1.0) faraday-excon (1.1.0)
faraday-http-cache (2.4.0) faraday-http-cache (2.5.1)
faraday (>= 0.8) faraday (>= 0.8)
faraday-httpclient (1.0.1) faraday-httpclient (1.0.1)
faraday-multipart (1.0.4) faraday-multipart (1.1.1)
multipart-post (~> 2) multipart-post (~> 2.0)
faraday-net_http (1.0.1) faraday-net_http (1.0.2)
faraday-net_http_persistent (1.2.0) faraday-net_http_persistent (1.2.0)
faraday-patron (1.0.0) faraday-patron (1.0.0)
faraday-rack (1.0.0) faraday-rack (1.0.0)
faraday-retry (1.0.3) faraday-retry (1.0.3)
ffi (1.15.5) git (1.19.1)
fourflusher (2.3.1) addressable (~> 2.8)
fuzzy_match (2.0.4)
gh_inspector (1.1.3)
git (1.11.0)
rchardet (~> 1.8) rchardet (~> 1.8)
httpclient (2.8.3) json (2.15.0)
i18n (1.12.0) kramdown (2.5.1)
concurrent-ruby (~> 1.0) rexml (>= 3.3.9)
json (2.6.2)
kramdown (2.4.0)
rexml
kramdown-parser-gfm (1.1.0) kramdown-parser-gfm (1.1.0)
kramdown (~> 2.0) kramdown (~> 2.0)
minitest (5.16.2) language_server-protocol (3.17.0.5)
molinillo (0.8.0) lint_roller (1.1.0)
multipart-post (2.2.3) multipart-post (2.4.1)
nanaimo (0.3.0)
nap (1.1.0) nap (1.1.0)
netrc (0.11.0)
no_proxy_fix (0.1.2) no_proxy_fix (0.1.2)
octokit (4.25.1) octokit (4.25.1)
faraday (>= 1, < 3) faraday (>= 1, < 3)
sawyer (~> 0.9) sawyer (~> 0.9)
open4 (1.3.4) open4 (1.3.4)
parallel (1.22.1) parallel (1.27.0)
parser (3.1.2.0) parser (3.3.9.0)
ast (~> 2.4.1) ast (~> 2.4.1)
racc
prism (1.5.1)
public_suffix (4.0.7) public_suffix (4.0.7)
racc (1.8.1)
rainbow (3.1.1) rainbow (3.1.1)
rake (13.0.6) rake (13.3.0)
rchardet (1.8.0) rchardet (1.10.0)
regexp_parser (2.5.0) regexp_parser (2.11.3)
rexml (3.2.5) rexml (3.4.4)
rouge (2.0.7) rouge (3.28.0)
rubocop (1.32.0) rubocop (1.81.1)
json (~> 2.3) json (~> 2.3)
language_server-protocol (~> 3.17.0.2)
lint_roller (~> 1.1.0)
parallel (~> 1.10) parallel (~> 1.10)
parser (>= 3.1.0.0) parser (>= 3.3.0.2)
rainbow (>= 2.2.2, < 4.0) rainbow (>= 2.2.2, < 4.0)
regexp_parser (>= 1.8, < 3.0) regexp_parser (>= 2.9.3, < 3.0)
rexml (>= 3.2.5, < 4.0) rubocop-ast (>= 1.47.1, < 2.0)
rubocop-ast (>= 1.19.1, < 2.0)
ruby-progressbar (~> 1.7) ruby-progressbar (~> 1.7)
unicode-display_width (>= 1.4.0, < 3.0) unicode-display_width (>= 2.4.0, < 4.0)
rubocop-ast (1.19.1) rubocop-ast (1.47.1)
parser (>= 3.1.1.0) parser (>= 3.3.7.2)
ruby-macho (2.5.1) prism (~> 1.4)
ruby-progressbar (1.11.0) ruby-progressbar (1.13.0)
ruby2_keywords (0.0.5) ruby2_keywords (0.0.5)
sawyer (0.9.2) sawyer (0.9.2)
addressable (>= 2.3.5) addressable (>= 2.3.5)
faraday (>= 0.17.3, < 3) faraday (>= 0.17.3, < 3)
terminal-table (3.0.2) terminal-table (1.6.0)
unicode-display_width (>= 1.1.1, < 3) unicode-display_width (3.2.0)
typhoeus (1.4.0) unicode-emoji (~> 4.1)
ethon (>= 0.9.0) unicode-emoji (4.1.0)
tzinfo (2.0.5) xcpretty (0.4.1)
concurrent-ruby (~> 1.0) rouge (~> 3.28.0)
unicode-display_width (2.2.0)
xcodeproj (1.22.0)
CFPropertyList (>= 2.3.3, < 4.0)
atomos (~> 0.1.3)
claide (>= 1.0.2, < 2.0)
colored2 (~> 3.1)
nanaimo (~> 0.3.0)
rexml (~> 3.2.4)
xcpretty (0.3.0)
rouge (~> 2.0.7)
zeitwerk (2.6.0)
PLATFORMS PLATFORMS
aarch64-linux-gnu
aarch64-linux-musl
arm-linux-gnu
arm-linux-musl
arm64-darwin
ruby ruby
x86-linux-gnu
x86-linux-musl
x86_64-darwin
x86_64-linux-gnu
x86_64-linux-musl
DEPENDENCIES DEPENDENCIES
cocoapods (~> 1.11) base64 (~> 0.3)
danger (~> 8.4) danger (~> 8.4)
octokit (~> 4.7) octokit (~> 4.7)
rake (~> 13.0) rake (~> 13.0)
@@ -186,4 +129,4 @@ DEPENDENCIES
xcpretty (~> 0.3) xcpretty (~> 0.3)
BUNDLED WITH BUNDLED WITH
2.2.33 2.7.2

View File

@@ -1,4 +1,5 @@
Copyright (c) 2022, Kyle Fuller Copyright (c) 2022, Kyle Fuller as the original author
Copyright (c) 2025, Astzweig GmbH & Co. KG
All rights reserved. All rights reserved.
Redistribution and use in source and binary forms, with or without Redistribution and use in source and binary forms, with or without

View File

@@ -1,15 +1,6 @@
{ {
"object": { "object": {
"pins": [ "pins": [
{
"package": "PathKit",
"repositoryURL": "https://github.com/kylef/PathKit.git",
"state": {
"branch": null,
"revision": "3bfd2737b700b9a36565a8c94f4ad2b050a5e574",
"version": "1.0.1"
}
},
{ {
"package": "Spectre", "package": "Spectre",
"repositoryURL": "https://github.com/kylef/Spectre.git", "repositoryURL": "https://github.com/kylef/Spectre.git",
@@ -18,6 +9,15 @@
"revision": "26cc5e9ae0947092c7139ef7ba612e34646086c7", "revision": "26cc5e9ae0947092c7139ef7ba612e34646086c7",
"version": "0.10.1" "version": "0.10.1"
} }
},
{
"package": "swiftpm-pathkit",
"repositoryURL": "https://github.com/astzweig/swiftpm-pathkit.git",
"state": {
"branch": null,
"revision": "1280d78aa2c1532800d7e820607f123236dc5f54",
"version": "1.5.1"
}
} }
] ]
}, },

View File

@@ -7,7 +7,7 @@ let package = Package(
.library(name: "Stencil", targets: ["Stencil"]) .library(name: "Stencil", targets: ["Stencil"])
], ],
dependencies: [ dependencies: [
.package(url: "https://github.com/kylef/PathKit.git", from: "1.0.1"), .package(url: "https://github.com/astzweig/swiftpm-pathkit.git", from: "1.5.1"),
.package(url: "https://github.com/kylef/Spectre.git", from: "0.10.1") .package(url: "https://github.com/kylef/Spectre.git", from: "0.10.1")
], ],
targets: [ targets: [

View File

@@ -34,9 +34,7 @@ namespace :files do
) )
docs_package = Utils.first_match_in_file('docs/installation.rst', /\.package\(url: .+ from: "(.+)"/, 1) docs_package = Utils.first_match_in_file('docs/installation.rst', /\.package\(url: .+ from: "(.+)"/, 1)
replace("docs/installation.rst", replace("docs/installation.rst",
/\.package\(url: .+, from: "(.+)"/ => %Q(.package\(url: "https://github.com/stencilproject/Stencil.git", from: "#{version}"), /\.package\(url: .+, from: "(.+)"/ => %Q(.package\(url: "https://github.com/swiftstencil/swiftpm-stencil.git", from: "#{version}")
/pod 'Stencil', '.*'/ => %Q(pod 'Stencil', '~> #{version}'),
/github "stencilproject\/Stencil" ~> .*/ => %Q(github "stencilproject/Stencil" ~> #{version})
) )
end end

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
/// A container for template variables. /// A container for template variables.
public class Context { public class Context {
var dictionaries: [[String: Any?]] var dictionaries: [[String: Any?]]
@@ -61,6 +55,7 @@ public class Context {
/// Pop the last level off of the Context /// Pop the last level off of the Context
/// ///
/// - returns: The popped level /// - returns: The popped level
// swiftlint:disable:next discouraged_optional_collection
fileprivate func pop() -> [String: Any?]? { fileprivate func pop() -> [String: Any?]? {
dictionaries.popLast() dictionaries.popLast()
} }

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
/// Marker protocol so we can know which types support `@dynamicMemberLookup`. Add this to your own types that support /// Marker protocol so we can know which types support `@dynamicMemberLookup`. Add this to your own types that support
/// lookup by String. /// lookup by String.
public protocol DynamicMemberLookup { public protocol DynamicMemberLookup {

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
/// Container for environment data, such as registered extensions /// Container for environment data, such as registered extensions
public struct Environment { public struct Environment {
/// The class for loading new templates /// The class for loading new templates

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
public class TemplateDoesNotExist: Error, CustomStringConvertible { public class TemplateDoesNotExist: Error, CustomStringConvertible {
let templateNames: [String] let templateNames: [String]
let loader: Loader? let loader: Loader?

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
public protocol Expression: CustomStringConvertible, Resolvable { public protocol Expression: CustomStringConvertible, Resolvable {
func evaluate(context: Context) throws -> Bool func evaluate(context: Context) throws -> Bool
} }

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
/// Container for registered tags and filters /// Container for registered tags and filters
open class Extension { open class Extension {
typealias TagParser = (TokenParser, Token) throws -> NodeType typealias TagParser = (TokenParser, Token) throws -> NodeType

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
class FilterNode: NodeType { class FilterNode: NodeType {
let resolvable: Resolvable let resolvable: Resolvable
let nodes: [NodeType] let nodes: [NodeType]

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
func capitalise(_ value: Any?) -> Any? { func capitalise(_ value: Any?) -> Any? {
if let array = value as? [Any?] { if let array = value as? [Any?] {
return array.map { stringify($0).capitalized } return array.map { stringify($0).capitalized }

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import Foundation import Foundation
class ForNode: NodeType { class ForNode: NodeType {
@@ -231,7 +225,7 @@ struct LoopTerminationNode: NodeType {
self.token = token self.token = token
} }
static func parse(_ parser: TokenParser, token: Token) throws -> LoopTerminationNode { static func parse(_ parser: TokenParser, token: Token) throws -> Self {
let components = token.components let components = token.components
guard components.count <= 2 else { guard components.count <= 2 else {
@@ -241,7 +235,7 @@ struct LoopTerminationNode: NodeType {
throw TemplateSyntaxError("'\(token.contents)' can be used only inside loop body") throw TemplateSyntaxError("'\(token.contents)' can be used only inside loop body")
} }
return LoopTerminationNode(name: components[0], label: components.count == 2 ? components[1] : nil, token: token) return Self(name: components[0], label: components.count == 2 ? components[1] : nil, token: token)
} }
func render(_ context: Context) throws -> String { func render(_ context: Context) throws -> String {

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
enum Operator { enum Operator {
case infix(String, Int, InfixOperator.Type) case infix(String, Int, InfixOperator.Type)
case prefix(String, Int, PrefixOperator.Type) case prefix(String, Int, PrefixOperator.Type)
@@ -17,7 +11,7 @@ enum Operator {
} }
} }
static let all: [Operator] = [ static let all: [Self] = [
.infix("in", 5, InExpression.self), .infix("in", 5, InExpression.self),
.infix("or", 6, OrExpression.self), .infix("or", 6, OrExpression.self),
.infix("and", 7, AndExpression.self), .infix("and", 7, AndExpression.self),
@@ -118,6 +112,7 @@ final class IfExpressionParser {
private init(components: ArraySlice<String>, environment: Environment, token: Token) throws { private init(components: ArraySlice<String>, environment: Environment, token: Token) throws {
var parsedComponents = Set<Int>() var parsedComponents = Set<Int>()
var bracketsBalance = 0 var bracketsBalance = 0
// swiftlint:disable:next closure_body_length
self.tokens = try zip(components.indices, components).compactMap { index, component in self.tokens = try zip(components.indices, components).compactMap { index, component in
guard !parsedComponents.contains(index) else { return nil } guard !parsedComponents.contains(index) else { return nil }

View File

@@ -1,11 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import PathKit
class IncludeNode: NodeType { class IncludeNode: NodeType {
let templateName: Variable let templateName: Variable
let includeContext: String? let includeContext: String?

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
class BlockContext { class BlockContext {
class var contextKey: String { "block_context" } class var contextKey: String { "block_context" }
@@ -62,7 +56,7 @@ class ExtendsNode: NodeType {
} }
let parsedNodes = try parser.parse() let parsedNodes = try parser.parse()
guard (parsedNodes.any { $0 is ExtendsNode }) == nil else { guard (parsedNodes.any { $0 is Self }) == nil else {
throw TemplateSyntaxError("'extends' cannot appear more than once in the same template") throw TemplateSyntaxError("'extends' cannot appear more than once in the same template")
} }

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import Foundation import Foundation
/// A structure used to represent a template variable, and to resolve it in a given context. /// A structure used to represent a template variable, and to resolve it in a given context.

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
/// Used to lazily set context data. Useful for example if you have some data that requires heavy calculations, and may /// Used to lazily set context data. Useful for example if you have some data that requires heavy calculations, and may
/// not be used in every render possiblity. /// not be used in every render possiblity.
public final class LazyValueWrapper { public final class LazyValueWrapper {
@@ -61,9 +55,3 @@ extension LazyValueWrapper: Resolvable {
return try (value as? Resolvable)?.resolve(context) ?? value return try (value as? Resolvable)?.resolve(context) ?? value
} }
} }
extension LazyValueWrapper: Normalizable {
public func normalize() -> Any? {
(cachedValue as? Normalizable)?.normalize() ?? cachedValue
}
}

View File

@@ -1,12 +1,10 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import Foundation import Foundation
// swiftlint:disable large_tuple
typealias Line = (content: String, number: UInt, range: Range<String.Index>) typealias Line = (content: String, number: UInt, range: Range<String.Index>)
/// Location in some content (text)
public typealias ContentLocation = (content: String, lineNumber: UInt, lineOffset: Int)
// swiftlint:enable large_tuple
struct Lexer { struct Lexer {
let templateName: String? let templateName: String?
@@ -64,7 +62,7 @@ struct Lexer {
/// - string: The content string of the token /// - string: The content string of the token
/// - range: The range within the template content, used for smart /// - range: The range within the template content, used for smart
/// error reporting /// error reporting
func createToken(string: String, at range: Range<String.Index>) -> Token { func createToken(string: String, at range: Range<String.Index>, _ isInEscapeMode: Bool = false) -> Token {
func strip(length: (Int, Int) = (Self.tagLength, Self.tagLength)) -> String { func strip(length: (Int, Int) = (Self.tagLength, Self.tagLength)) -> String {
guard string.count > (length.0 + length.1) else { return "" } guard string.count > (length.0 + length.1) else { return "" }
let trimmed = String(string.dropFirst(length.0).dropLast(length.1)) let trimmed = String(string.dropFirst(length.0).dropLast(length.1))
@@ -75,7 +73,7 @@ struct Lexer {
return trimmed return trimmed
} }
if string.hasPrefix("{{") || string.hasPrefix("{%") || string.hasPrefix("{#") { if !isInEscapeMode && (string.hasPrefix("{{") || string.hasPrefix("{%") || string.hasPrefix("{#")) {
let behaviour = string.hasPrefix("{%") ? behaviour(string: string, tagLength: Self.tagLength) : .unspecified let behaviour = string.hasPrefix("{%") ? behaviour(string: string, tagLength: Self.tagLength) : .unspecified
let stripLengths = ( let stripLengths = (
Self.tagLength + (behaviour.leading != .unspecified ? 1 : 0), Self.tagLength + (behaviour.leading != .unspecified ? 1 : 0),
@@ -110,14 +108,14 @@ struct Lexer {
let scanner = Scanner(templateString) let scanner = Scanner(templateString)
while !scanner.isEmpty { while !scanner.isEmpty {
if let (char, text) = scanner.scanForTokenStart(Self.tokenChars) { if let (char, text, isInEscapeMode) = scanner.scanForTokenStart(Self.tokenChars) {
if !text.isEmpty { if !text.isEmpty {
tokens.append(createToken(string: text, at: scanner.range)) tokens.append(createToken(string: text, at: scanner.range))
} }
guard let end = Self.tokenCharMap[char] else { continue } guard let end = Self.tokenCharMap[char] else { continue }
let result = scanner.scanForTokenEnd(end) let result = scanner.scanForTokenEnd(end)
tokens.append(createToken(string: result, at: scanner.range)) tokens.append(createToken(string: result, at: scanner.range, isInEscapeMode))
} else { } else {
tokens.append(createToken(string: scanner.content, at: scanner.range)) tokens.append(createToken(string: scanner.content, at: scanner.range))
scanner.content = "" scanner.content = ""
@@ -150,6 +148,7 @@ class Scanner {
private static let tokenStartDelimiter: Unicode.Scalar = "{" private static let tokenStartDelimiter: Unicode.Scalar = "{"
/// And the corresponding end delimiter for a token. /// And the corresponding end delimiter for a token.
private static let tokenEndDelimiter: Unicode.Scalar = "}" private static let tokenEndDelimiter: Unicode.Scalar = "}"
private static let tokenDelimiterEscape: Unicode.Scalar = "\\"
init(_ content: String) { init(_ content: String) {
self.originalContent = content self.originalContent = content
@@ -205,18 +204,25 @@ class Scanner {
/// - Parameter tokenChars: List of token start characters to search for. /// - Parameter tokenChars: List of token start characters to search for.
/// - Returns: The found token start character, together with the content /// - Returns: The found token start character, together with the content
/// before the token, or nil of no token start was found. /// before the token, or nil of no token start was found.
func scanForTokenStart(_ tokenChars: [Unicode.Scalar]) -> (Unicode.Scalar, String)? { // swiftlint:disable:next large_tuple
func scanForTokenStart(_ tokenChars: [Unicode.Scalar]) -> (Unicode.Scalar, String, Bool)? {
var foundBrace = false var foundBrace = false
var isInEscapeMode = false
var lastChar: Unicode.Scalar = " "
range = range.upperBound..<range.upperBound range = range.upperBound..<range.upperBound
for (index, char) in zip(0..., content.unicodeScalars) { for (index, char) in zip(0..., content.unicodeScalars) {
if foundBrace && tokenChars.contains(char) { if foundBrace && tokenChars.contains(char) {
let result = String(content.unicodeScalars.prefix(index - 1)) let prefixOffset = isInEscapeMode ? 1 : 0
let prefix = String(content.unicodeScalars.prefix(index - 1 - prefixOffset))
content = String(content.unicodeScalars.dropFirst(index - 1)) content = String(content.unicodeScalars.dropFirst(index - 1))
range = range.upperBound..<originalContent.unicodeScalars.index(range.upperBound, offsetBy: index - 1) range = range.upperBound..<originalContent.unicodeScalars.index(range.upperBound, offsetBy: index - 1)
return (char, result)
return (char, prefix, isInEscapeMode)
} else { } else {
foundBrace = (char == Self.tokenStartDelimiter) foundBrace = (char == Self.tokenStartDelimiter)
isInEscapeMode = (lastChar == Self.tokenDelimiterEscape)
lastChar = char
} }
} }
@@ -257,6 +263,3 @@ extension String {
return String(self[first..<last]) return String(self[first..<last])
} }
} }
/// Location in some content (text)
public typealias ContentLocation = (content: String, lineNumber: UInt, lineOffset: Int)

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import Foundation import Foundation
import PathKit import PathKit
@@ -41,8 +35,8 @@ public class FileSystemLoader: Loader, CustomStringConvertible {
} }
public init(bundle: [Bundle]) { public init(bundle: [Bundle]) {
self.paths = bundle.map { bundle in self.paths = bundle.compactMap { bundle in
Path(bundle.bundlePath) Path(bundle.path)
} }
} }
@@ -52,13 +46,13 @@ public class FileSystemLoader: Loader, CustomStringConvertible {
public func loadTemplate(name: String, environment: Environment) throws -> Template { public func loadTemplate(name: String, environment: Environment) throws -> Template {
for path in paths { for path in paths {
let templatePath = try path.safeJoin(path: Path(name)) let templatePath = try path.safeJoin(path: name)
if !templatePath.exists { if !templatePath.exists {
continue continue
} }
let content: String = try templatePath.read() let content: String = try String(contentsOf: templatePath)
return environment.templateClass.init(templateString: content, environment: environment, name: name) return environment.templateClass.init(templateString: content, environment: environment, name: name)
} }
@@ -68,10 +62,10 @@ public class FileSystemLoader: Loader, CustomStringConvertible {
public func loadTemplate(names: [String], environment: Environment) throws -> Template { public func loadTemplate(names: [String], environment: Environment) throws -> Template {
for path in paths { for path in paths {
for templateName in names { for templateName in names {
let templatePath = try path.safeJoin(path: Path(templateName)) let templatePath = try path.safeJoin(path: templateName)
if templatePath.exists { if templatePath.exists {
let content: String = try templatePath.read() let content: String = try String(contentsOf: templatePath)
return environment.templateClass.init(templateString: content, environment: environment, name: templateName) return environment.templateClass.init(templateString: content, environment: environment, name: templateName)
} }
} }
@@ -108,10 +102,10 @@ public class DictionaryLoader: Loader {
} }
extension Path { extension Path {
func safeJoin(path: Path) throws -> Path { func safeJoin(path: String) throws -> Path {
let newPath = self + path let newPath = self / path
if !newPath.absolute().description.hasPrefix(absolute().description) { if !newPath.string.hasPrefix(self.string) {
throw SuspiciousFileOperation(basePath: self, path: newPath) throw SuspiciousFileOperation(basePath: self, path: newPath)
} }

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import Foundation import Foundation
/// Represents a parsed node /// Represents a parsed node
@@ -184,6 +178,8 @@ func unwrap(_ array: [Any?]) -> [Any] {
} else { } else {
return item return item
} }
} else { return item as Any } } else {
return item as Any
}
} }
} }

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
#if !os(Linux) #if !os(Linux)
import Foundation import Foundation

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
/// Creates a checker that will stop parsing if it encounters a list of tags. /// Creates a checker that will stop parsing if it encounters a list of tags.
/// Useful for example for scanning until a given "end"-node. /// Useful for example for scanning until a given "end"-node.
public func until(_ tags: [String]) -> ((TokenParser, Token) -> Bool) { public func until(_ tags: [String]) -> ((TokenParser, Token) -> Bool) {

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import Foundation import Foundation
import PathKit import PathKit
@@ -47,13 +41,17 @@ open class Template: ExpressibleByStringLiteral {
/// Create a template with a file found at the given URL /// Create a template with a file found at the given URL
@available(*, deprecated, message: "Use Environment/FileSystemLoader instead") @available(*, deprecated, message: "Use Environment/FileSystemLoader instead")
public convenience init(URL: Foundation.URL) throws { public convenience init(URL: Foundation.URL) throws {
try self.init(path: Path(URL.path)) guard let path = Path(url: URL) else {
throw TemplateDoesNotExist(templateNames: [URL.lastPathComponent])
}
try self.init(path: path)
} }
/// Create a template with a file found at the given path /// Create a template with a file found at the given path
@available(*, deprecated, message: "Use Environment/FileSystemLoader instead") @available(*, deprecated, message: "Use Environment/FileSystemLoader instead")
public convenience init(path: Path, environment: Environment? = nil, name: String? = nil) throws { public convenience init(path: Path, environment: Environment? = nil, name: String? = nil) throws {
self.init(templateString: try path.read(), environment: environment, name: name) let value = try String(contentsOf: path)
self.init(templateString: value, environment: environment, name: name)
} }
// MARK: ExpressibleByStringLiteral // MARK: ExpressibleByStringLiteral
@@ -81,8 +79,8 @@ open class Template: ExpressibleByStringLiteral {
return try renderNodes(nodes, context) return try renderNodes(nodes, context)
} }
// swiftlint:disable discouraged_optional_collection
/// Render the given template /// Render the given template
// swiftlint:disable:next discouraged_optional_collection
open func render(_ dictionary: [String: Any]? = nil) throws -> String { open func render(_ dictionary: [String: Any]? = nil) throws -> String {
try render(Context(dictionary: dictionary ?? [:], environment: environment)) try render(Context(dictionary: dictionary ?? [:], environment: environment))
} }

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import Foundation import Foundation
extension String { extension String {
@@ -83,9 +77,9 @@ public struct SourceMap: Equatable {
self.location = location self.location = location
} }
static let unknown = SourceMap() static let unknown = Self()
public static func == (lhs: SourceMap, rhs: SourceMap) -> Bool { public static func == (lhs: Self, rhs: Self) -> Bool {
lhs.filename == rhs.filename && lhs.location == rhs.location lhs.filename == rhs.filename && lhs.location == rhs.location
} }
} }
@@ -100,7 +94,7 @@ public struct WhitespaceBehaviour: Equatable {
let leading: Behaviour let leading: Behaviour
let trailing: Behaviour let trailing: Behaviour
public static let unspecified = WhitespaceBehaviour(leading: .unspecified, trailing: .unspecified) public static let unspecified = Self(leading: .unspecified, trailing: .unspecified)
} }
public class Token: Equatable { public class Token: Equatable {

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import Foundation import Foundation
public struct TrimBehaviour: Equatable { public struct TrimBehaviour: Equatable {
@@ -30,13 +24,13 @@ public struct TrimBehaviour: Equatable {
} }
/// doesn't touch newlines /// doesn't touch newlines
public static let nothing = TrimBehaviour(leading: .nothing, trailing: .nothing) public static let nothing = Self(leading: .nothing, trailing: .nothing)
/// removes whitespace before a block and whitespace and a single newline after a block /// removes whitespace before a block and whitespace and a single newline after a block
public static let smart = TrimBehaviour(leading: .whitespace, trailing: .whitespaceAndOneNewLine) public static let smart = Self(leading: .whitespace, trailing: .whitespaceAndOneNewLine)
/// removes all whitespace and newlines before and after a block /// removes all whitespace and newlines before and after a block
public static let all = TrimBehaviour(leading: .whitespaceAndNewLines, trailing: .whitespaceAndNewLines) public static let all = Self(leading: .whitespaceAndNewLines, trailing: .whitespaceAndNewLines)
static func leadingRegex(trim: Trim) -> NSRegularExpression { static func leadingRegex(trim: Trim) -> NSRegularExpression {
switch trim { switch trim {
@@ -64,13 +58,18 @@ public struct TrimBehaviour: Equatable {
} }
} }
// swiftlint:disable force_try // swiftlint:disable:next force_try
private static let leadingWhitespaceAndNewlines = try! NSRegularExpression(pattern: "^\\s+") private static let leadingWhitespaceAndNewlines = try! NSRegularExpression(pattern: "^\\s+")
// swiftlint:disable:next force_try
private static let trailingWhitespaceAndNewLines = try! NSRegularExpression(pattern: "\\s+$") private static let trailingWhitespaceAndNewLines = try! NSRegularExpression(pattern: "\\s+$")
// swiftlint:disable:next force_try
private static let leadingWhitespaceAndOneNewLine = try! NSRegularExpression(pattern: "^[ \t]*\n") private static let leadingWhitespaceAndOneNewLine = try! NSRegularExpression(pattern: "^[ \t]*\n")
// swiftlint:disable:next force_try
private static let trailingWhitespaceAndOneNewLine = try! NSRegularExpression(pattern: "\n[ \t]*$") private static let trailingWhitespaceAndOneNewLine = try! NSRegularExpression(pattern: "\n[ \t]*$")
// swiftlint:disable:next force_try
private static let leadingWhitespace = try! NSRegularExpression(pattern: "^[ \t]*") private static let leadingWhitespace = try! NSRegularExpression(pattern: "^[ \t]*")
// swiftlint:disable:next force_try
private static let trailingWhitespace = try! NSRegularExpression(pattern: "[ \t]*$") private static let trailingWhitespace = try! NSRegularExpression(pattern: "[ \t]*$")
} }

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import Foundation import Foundation
typealias Number = Float typealias Number = Float
@@ -110,16 +104,16 @@ public struct Variable: Equatable, Resolvable {
return resolve(bit: bit, collection: array) return resolve(bit: bit, collection: array)
} else if let string = context as? String { } else if let string = context as? String {
return resolve(bit: bit, collection: string) return resolve(bit: bit, collection: string)
} else if let value = context as? DynamicMemberLookup {
return value[dynamicMember: bit]
} else if let object = context as? NSObject { // NSKeyValueCoding } else if let object = context as? NSObject { // NSKeyValueCoding
#if os(Linux) #if canImport(ObjectiveC)
return nil
#else
if object.responds(to: Selector(bit)) { if object.responds(to: Selector(bit)) {
return object.value(forKey: bit) return object.value(forKey: bit)
} }
#else
return nil
#endif #endif
} else if let value = context as? DynamicMemberLookup {
return value[dynamicMember: bit]
} else if let value = context { } else if let value = context {
return Mirror(reflecting: value).getValue(for: bit) return Mirror(reflecting: value).getValue(for: bit)
} }

View File

@@ -1,19 +1,18 @@
{ {
"name": "Stencil", "name": "Stencil",
"version": "0.15.0", "version": "0.15.2",
"summary": "Stencil is a simple and powerful template language for Swift.", "summary": "Stencil is a simple and powerful template language for Swift.",
"homepage": "https://stencil.fuller.li",
"license": { "license": {
"type": "BSD", "type": "BSD",
"file": "LICENSE" "file": "LICENSE"
}, },
"authors": { "authors": {
"Kyle Fuller": "kyle@fuller.li" "Thomas Bernstein": "developer@astzweig.kg"
}, },
"social_media_url": "https://twitter.com/kylefuller", "social_media_url": "https://twitter.com/trbernstein",
"source": { "source": {
"git": "https://github.com/stencilproject/Stencil.git", "git": "https://github.com/swiftstencil/swiftpm-stencil.git",
"tag": "0.15.0" "tag": "0.15.2"
}, },
"source_files": [ "source_files": [
"Sources/Stencil/*.swift" "Sources/Stencil/*.swift"
@@ -23,14 +22,13 @@
"osx": "10.9", "osx": "10.9",
"tvos": "9.0" "tvos": "9.0"
}, },
"cocoapods_version": ">= 1.7.0",
"swift_versions": [ "swift_versions": [
"5.0" "5.0"
], ],
"requires_arc": true, "requires_arc": true,
"dependencies": { "dependencies": {
"PathKit": [ "PathKit": [
"~> 1.0.0" "~> 1.5.0"
] ]
} }
} }

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import Spectre import Spectre
@testable import Stencil @testable import Stencil
import XCTest import XCTest

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import PathKit import PathKit
import Spectre import Spectre
@testable import Stencil @testable import Stencil
@@ -17,7 +11,7 @@ final class EnvironmentBaseAndChildTemplateTests: XCTestCase {
override func setUp() { override func setUp() {
super.setUp() super.setUp()
let path = Path(#file as String) + ".." + "fixtures" let path = Path(#file as String)! / ".." / "fixtures"
let loader = FileSystemLoader(paths: [path]) let loader = FileSystemLoader(paths: [path])
environment = Environment(loader: loader) environment = Environment(loader: loader)
childTemplate = "" childTemplate = ""

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import PathKit import PathKit
import Spectre import Spectre
@testable import Stencil @testable import Stencil
@@ -17,7 +11,7 @@ final class EnvironmentIncludeTemplateTests: XCTestCase {
override func setUp() { override func setUp() {
super.setUp() super.setUp()
let path = Path(#file as String) + ".." + "fixtures" let path = Path(#file as String)! / ".." / "fixtures"
let loader = FileSystemLoader(paths: [path]) let loader = FileSystemLoader(paths: [path])
environment = Environment(loader: loader) environment = Environment(loader: loader)
template = "" template = ""

View File

@@ -1,10 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import PathKit
import Spectre import Spectre
@testable import Stencil @testable import Stencil
import XCTest import XCTest

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import Spectre import Spectre
@testable import Stencil @testable import Stencil
import XCTest import XCTest
@@ -11,7 +5,7 @@ import XCTest
final class ExpressionsTests: XCTestCase { final class ExpressionsTests: XCTestCase {
private let parser = TokenParser(tokens: [], environment: Environment()) private let parser = TokenParser(tokens: [], environment: Environment())
private func makeExpression(_ components: [String]) -> Expression { private func makeExpression(_ components: [String]) -> Stencil.Expression {
do { do {
let parser = try IfExpressionParser.parser( let parser = try IfExpressionParser.parser(
components: components, components: components,

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import Spectre import Spectre
@testable import Stencil @testable import Stencil
import XCTest import XCTest

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import Spectre import Spectre
import Stencil import Stencil
import XCTest import XCTest

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import Spectre import Spectre
@testable import Stencil @testable import Stencil
import XCTest import XCTest

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import PathKit import PathKit
import Spectre import Spectre
@testable import Stencil @testable import Stencil
@@ -11,7 +5,7 @@ import XCTest
extension Expectation { extension Expectation {
@discardableResult @discardableResult
func toThrow<T: Error>() throws -> T { func toThrow<E: Error>() throws -> E {
var thrownError: Error? var thrownError: Error?
do { do {
@@ -21,7 +15,7 @@ extension Expectation {
} }
if let thrownError = thrownError { if let thrownError = thrownError {
if let thrownError = thrownError as? T { if let thrownError = thrownError as? E {
return thrownError return thrownError
} else { } else {
throw failure("\(thrownError) is not \(T.self)") throw failure("\(thrownError) is not \(T.self)")

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import Spectre import Spectre
@testable import Stencil @testable import Stencil
import XCTest import XCTest

View File

@@ -1,16 +1,10 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import PathKit import PathKit
import Spectre import Spectre
@testable import Stencil @testable import Stencil
import XCTest import XCTest
final class IncludeTests: XCTestCase { final class IncludeTests: XCTestCase {
private let path = Path(#file as String) + ".." + "fixtures" private let path = Path(#file as String)! / ".." / "fixtures"
private lazy var loader = FileSystemLoader(paths: [path]) private lazy var loader = FileSystemLoader(paths: [path])
private lazy var environment = Environment(loader: loader) private lazy var environment = Environment(loader: loader)

View File

@@ -1,16 +1,10 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import PathKit import PathKit
import Spectre import Spectre
import Stencil import Stencil
import XCTest import XCTest
final class InheritanceTests: XCTestCase { final class InheritanceTests: XCTestCase {
private let path = Path(#file as String) + ".." + "fixtures" private let path = Path(#file as String)! / ".." / "fixtures"
private lazy var loader = FileSystemLoader(paths: [path]) private lazy var loader = FileSystemLoader(paths: [path])
private lazy var environment = Environment(loader: loader) private lazy var environment = Environment(loader: loader)

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import PathKit import PathKit
import Spectre import Spectre
@testable import Stencil @testable import Stencil
@@ -26,6 +20,22 @@ final class LexerTests: XCTestCase {
try expect(tokens.first) == .comment(value: "Comment", at: makeSourceMap("Comment", for: lexer)) try expect(tokens.first) == .comment(value: "Comment", at: makeSourceMap("Comment", for: lexer))
} }
func testEscapedVariableToken() throws {
let lexer = Lexer(templateString: "\\{{ Variable }}")
let tokens = lexer.tokenize()
try expect(tokens.count) == 1
try expect(tokens.first) == .text(value: "{{ Variable }}", at: makeSourceMap("{{ Variable }}", for: lexer))
}
func testEscapedBehaviourToken() throws {
let lexer = Lexer(templateString: "\\{% Variable %}")
let tokens = lexer.tokenize()
try expect(tokens.count) == 1
try expect(tokens.first) == .text(value: "{% Variable %}", at: makeSourceMap("{% Variable %}", for: lexer))
}
func testVariable() throws { func testVariable() throws {
let lexer = Lexer(templateString: "{{ Variable }}") let lexer = Lexer(templateString: "{{ Variable }}")
let tokens = lexer.tokenize() let tokens = lexer.tokenize()
@@ -140,8 +150,8 @@ final class LexerTests: XCTestCase {
} }
func testPerformance() throws { func testPerformance() throws {
let path = Path(#file as String) + ".." + "fixtures" + "huge.html" let path = Path(#file as String)! / ".." / "fixtures" / "huge.html"
let content: String = try path.read() let content: String = try NSString(contentsOfFile: path.string, encoding: String.Encoding.utf8.rawValue).substring(from: 0) as String
measure { measure {
let lexer = Lexer(templateString: content) let lexer = Lexer(templateString: content)

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import PathKit import PathKit
import Spectre import Spectre
import Stencil import Stencil
@@ -11,7 +5,7 @@ import XCTest
final class TemplateLoaderTests: XCTestCase { final class TemplateLoaderTests: XCTestCase {
func testFileSystemLoader() { func testFileSystemLoader() {
let path = Path(#file as String) + ".." + "fixtures" let path = Path(#file as String)! / ".." / "fixtures"
let loader = FileSystemLoader(paths: [path]) let loader = FileSystemLoader(paths: [path])
let environment = Environment(loader: loader) let environment = Environment(loader: loader)

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import Spectre import Spectre
@testable import Stencil @testable import Stencil
import XCTest import XCTest

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import Spectre import Spectre
@testable import Stencil @testable import Stencil
import XCTest import XCTest

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import Spectre import Spectre
@testable import Stencil @testable import Stencil
import XCTest import XCTest

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import Spectre import Spectre
import Stencil import Stencil
import XCTest import XCTest

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import Spectre import Spectre
@testable import Stencil @testable import Stencil
import XCTest import XCTest
@@ -21,5 +15,11 @@ final class TemplateTests: XCTestCase {
let result = try template.render([ "name": "Kyle" ]) let result = try template.render([ "name": "Kyle" ])
try expect(result) == "Hello World" try expect(result) == "Hello World"
} }
it("can render a template with escaped token") {
let template: Template = "Hello \\{{ name }}"
let result = try template.render([ "name": "Kyle" ])
try expect(result) == "Hello {{ name }}"
}
} }
} }

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import Spectre import Spectre
@testable import Stencil @testable import Stencil
import XCTest import XCTest

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import Spectre import Spectre
import Stencil import Stencil
import XCTest import XCTest

View File

@@ -1,9 +1,3 @@
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import Spectre import Spectre
@testable import Stencil @testable import Stencil
import XCTest import XCTest

View File

@@ -2,7 +2,7 @@
<p> <p>
<iframe <iframe
src="https://ghbtns.com/github-btn.html?user=stencilproject&repo=Stencil&type=watch&count=true&size=large" src="https://ghbtns.com/github-btn.html?user=swiftstencil&repo=swiftpm-stencil&type=watch&count=true&size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="200px" height="35px"> allowtransparency="true" frameborder="0" scrolling="0" width="200px" height="35px">
</iframe> </iframe>
</p> </p>
@@ -12,22 +12,8 @@
<div class="social"> <div class="social">
<p> <p>
<iframe <iframe
src="https://ghbtns.com/github-btn.html?user=kylef&type=follow&count=false" src="https://ghbtns.com/github-btn.html?user=swiftstencil&type=follow&count=false"
allowtransparency="true" frameborder="0" scrolling="0" width="200" height="20"> allowtransparency="true" frameborder="0" scrolling="0" width="200" height="20">
</iframe> </iframe>
</p> </p>
<p>
<a href="https://twitter.com/kylefuller" class="twitter-follow-button" data-show-count="false">Follow @kylefuller</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
</p>
</div> </div>
<h3>Other Projects</h3>
<p>More <a href="https://fuller.li/">Kyle Fuller</a> projects:</p>
<ul>
<li><a href="https://github.com/kylef/Commander">Commander</a></li>
<li><a href="https://curassow.fuller.li/">Curassow</a></li>
<li><a href="https://github.com/kylef/Spectre">Spectre</a></li>
<li><a href="https://github.com/kylef/heroku-buildpack-swift">Heroku Swift buildpack</a></li>
</ul>

View File

@@ -50,7 +50,7 @@ master_doc = 'index'
# General information about the project. # General information about the project.
project = 'Stencil' project = 'Stencil'
copyright = '2022, Kyle Fuller' copyright = [ '2022, Kyle Fuller', '2025, Astzweig GmbH & Co. KG' ]
author = 'Kyle Fuller' author = 'Kyle Fuller'
# The version info for the project you're documenting, acts as replacement for # The version info for the project you're documenting, acts as replacement for
@@ -58,9 +58,9 @@ author = 'Kyle Fuller'
# built documents. # built documents.
# #
# The short X.Y version. # The short X.Y version.
version = '0.15.0' version = '0.15.2'
# The full version, including alpha/beta/rc tags. # The full version, including alpha/beta/rc tags.
release = '0.15.0' release = '0.15.2'
# The language for content autogenerated by Sphinx. Refer to documentation # The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages. # for a list of supported languages.

View File

@@ -31,7 +31,7 @@ feel right at home with Stencil.
] ]
] ]
let environment = Environment(loader: FileSystemLoader(paths: ["templates/"]) let environment = Environment(loader: FileSystemLoader(paths: ["templates/"]))
let rendered = try environment.renderTemplate(name: "articles.html", context: context) let rendered = try environment.renderTemplate(name: "articles.html", context: context)
print(rendered) print(rendered)

View File

@@ -14,39 +14,6 @@ dependencies inside ``Package.swift``.
let package = Package( let package = Package(
name: "MyApplication", name: "MyApplication",
dependencies: [ dependencies: [
.package(url: "https://github.com/stencilproject/Stencil.git", from: "0.15.0"), .package(url: "https://github.com/swiftstencil/swiftpm-stencil.git", from: "0.15.2"),
] ]
) )
CocoaPods
---------
If you're using CocoaPods, you can add Stencil to your ``Podfile`` and then run
``pod install``.
.. code-block:: ruby
pod 'Stencil', '~> 0.15.0'
Carthage
--------
.. note:: Use at your own risk. We don't offer support for Carthage and instead recommend you use Swift Package Manager.
1) Add ``Stencil`` to your ``Cartfile``:
.. code-block:: text
github "stencilproject/Stencil" ~> 0.15.0
2) Checkout your dependencies, generate the Stencil Xcode project, and then use Carthage to build Stencil:
.. code-block:: shell
$ carthage update
$ (cd Carthage/Checkouts/Stencil && swift package generate-xcodeproj)
$ carthage build
3) Follow the Carthage steps to add the built frameworks to your project.
To learn more about this approach see `Using Swift Package Manager with Carthage <https://fuller.li/posts/using-swift-package-manager-with-carthage/>`_.

View File

@@ -113,12 +113,10 @@ To comment out part of your template, you can use the following syntax:
{# My comment is completely hidden #} {# My comment is completely hidden #}
.. _template-inheritance:
Whitespace Control Whitespace Control
------------------ ------------------
Stencil supports the same syntax as Jinja for whitespace control, see [their docs for more information](https://jinja.palletsprojects.com/en/3.1.x/templates/#whitespace-control). Stencil supports the same syntax as Jinja for whitespace control, see `their docs for more information <https://jinja.palletsprojects.com/en/3.1.x/templates/#whitespace-control>`_.
Essentially, Stencil will **not** trim whitespace by default. However you can: Essentially, Stencil will **not** trim whitespace by default. However you can:
@@ -126,6 +124,8 @@ Essentially, Stencil will **not** trim whitespace by default. However you can:
- You can disable this per-block using the `+` control character. For example `{{+ if … }}` to preserve whitespace before. - You can disable this per-block using the `+` control character. For example `{{+ if … }}` to preserve whitespace before.
- You can force trimming per-block by using the `-` control character. For example `{{ if … -}}` to trim whitespace after. - You can force trimming per-block by using the `-` control character. For example `{{ if … -}}` to trim whitespace after.
.. _template-inheritance:
Template inheritance Template inheritance
-------------------- --------------------

View File

@@ -42,7 +42,7 @@ def check_changelog
# Now, check that links [#nn](.../nn) have matching numbers in link title & URL # Now, check that links [#nn](.../nn) have matching numbers in link title & URL
wrong_links = line.scan(links).reject do |m| wrong_links = line.scan(links).reject do |m|
slug = m[0] || "stencilproject/#{current_repo}" slug = m[0] || "stencilproject/Stencil"
(slug == m[2]) && (m[1] == m[4]) (slug == m[2]) && (m[1] == m[4])
end end
all_warnings.concat Array(wrong_links.map do |m| all_warnings.concat Array(wrong_links.map do |m|

View File

@@ -5,7 +5,7 @@
namespace :lint do namespace :lint do
SWIFTLINT = 'rakelib/lint.sh' SWIFTLINT = 'rakelib/lint.sh'
SWIFTLINT_VERSION = '0.48.0' SWIFTLINT_VERSION = '0.61.0'
task :install do |task| task :install do |task|
next if check_version next if check_version

View File

@@ -7,7 +7,7 @@ require 'json'
namespace :release do namespace :release do
desc 'Create a new release' desc 'Create a new release'
task :new => [:check_versions, :check_tag_and_ask_to_release, 'spm:test', :github, :cocoapods] task :new => [:check_versions, :check_tag_and_ask_to_release, 'spm:test', :github]
desc 'Check if all versions from the podspecs and CHANGELOG match' desc 'Check if all versions from the podspecs and CHANGELOG match'
task :check_versions do task :check_versions do
@@ -15,7 +15,7 @@ namespace :release do
Utils.table_header('Check', 'Status') Utils.table_header('Check', 'Status')
# Check if bundler is installed first, as we'll need it for the cocoapods task (and we prefer to fail early) # Check if bundler is installed first (we prefer to fail early)
`which bundler` `which bundler`
results << Utils.table_result( results << Utils.table_result(
$CHILD_STATUS.success?, $CHILD_STATUS.success?,
@@ -40,18 +40,14 @@ namespace :release do
# Check docs installation # Check docs installation
docs_package = Utils.first_match_in_file('docs/installation.rst', /\.package\(url: .+ from: "(.+)"/, 1) docs_package = Utils.first_match_in_file('docs/installation.rst', /\.package\(url: .+ from: "(.+)"/, 1)
docs_cocoapods = Utils.first_match_in_file('docs/installation.rst', /pod 'Stencil', '~> (.+)'/, 1)
docs_carthage = Utils.first_match_in_file('docs/installation.rst', /github ".+\/Stencil" ~> (.+)/, 1)
results << Utils.table_result(docs_package == v, 'Docs, package updated', 'Update the package version in docs/installation.rst') results << Utils.table_result(docs_package == v, 'Docs, package updated', 'Update the package version in docs/installation.rst')
results << Utils.table_result(docs_cocoapods == v, 'Docs, cocoapods updated', 'Update the cocoapods version in docs/installation.rst')
results << Utils.table_result(docs_carthage == v, 'Docs, carthage updated', 'Update the carthage version in docs/installation.rst')
# Check if entry present in CHANGELOG # Check if entry present in CHANGELOG
changelog_entry = Utils.first_match_in_file('CHANGELOG.md', /^## #{Regexp.quote(v)}$/) changelog_entry = Utils.first_match_in_file('CHANGELOG.md', /^## #{Regexp.quote(v)}$/)
results << Utils.table_result(changelog_entry, 'CHANGELOG, Entry added', "Add an entry for #{v} in CHANGELOG.md") results << Utils.table_result(changelog_entry, 'CHANGELOG, Entry added', "Add an entry for #{v} in CHANGELOG.md")
changelog_has_stable = system("grep -qi '^## Master' CHANGELOG.md") changelog_has_stable = system("grep -qi '^## Master' CHANGELOG.md")
results << Utils.table_result(!changelog_has_stable, 'CHANGELOG, No master', 'Remove section for master branch in CHANGELOG') results << Utils.table_result(!changelog_has_stable, 'CHANGELOG, No master', 'Remove section for main branch in CHANGELOG')
exit 1 unless results.all? exit 1 unless results.all?
end end
@@ -82,16 +78,10 @@ namespace :release do
tag = Utils.top_changelog_version tag = Utils.top_changelog_version
body = Utils.top_changelog_entry body = Utils.top_changelog_entry
raise 'Must be a valid version' if tag == 'Master' raise 'Must be a valid version' if tag == 'main'
repo_name = File.basename(`git remote get-url origin`.chomp, '.git').freeze repo_name = File.basename(`git remote get-url origin`.chomp, '.git').freeze
puts "Pushing release notes for tag #{tag}" puts "Pushing release notes for tag #{tag}"
client.create_release("stencilproject/#{repo_name}", tag, name: tag, body: body) client.create_release("swiftstencil/#{repo_name}", tag, name: tag, body: body)
end
desc "pod trunk push #{POD_NAME} to CocoaPods"
task :cocoapods do
Utils.print_header 'Pushing pod to CocoaPods Trunk'
sh "bundle exec pod trunk push #{POD_NAME}.podspec.json"
end end
end end