Skip to content

Commit 491436e

Browse files
authored
Merge pull request #8 from vapor/alternate-file-types
work with non leaf documents as raw bytes #2
2 parents ec4c13e + d62c3ac commit 491436e

File tree

3 files changed

+42
-5
lines changed

3 files changed

+42
-5
lines changed

Resources/random-file.any

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
This file #(won't) be #rendered() {}

Sources/Leaf/Stem+Spawn.swift

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,28 @@ extension Stem {
1212
}
1313

1414
public func spawnLeaf(named name: String) throws -> Leaf {
15-
if let existing = cache?[name] { return existing }
15+
var name = name
16+
if name.hasPrefix("/") {
17+
name = String(name.characters.dropFirst())
18+
}
1619

17-
var subpath = name.finished(with: SUFFIX)
18-
if subpath.hasPrefix("/") {
19-
subpath = String(subpath.characters.dropFirst())
20+
// non-leaf document. rendered as pure bytes
21+
if name.characters.contains("."), !name.hasSuffix(".leaf") {
22+
if let existing = cache?[name] { return existing }
23+
let path = workingDirectory + name
24+
let bytes = try Bytes.load(path: path)
25+
let component = Leaf.Component.raw(bytes)
26+
let leaf = Leaf(raw: bytes.string, components: [component])
27+
cache(leaf, named: name)
28+
return leaf
2029
}
21-
let path = workingDirectory + subpath
2230

31+
name = name.finished(with: SUFFIX)
32+
33+
// add suffix if necessary
34+
if let existing = cache?[name] { return existing }
35+
36+
let path = workingDirectory + name
2337
let raw = try Bytes.load(path: path)
2438
let leaf = try spawnLeaf(raw: raw)
2539
cache(leaf, named: name)
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import Foundation
2+
import XCTest
3+
@testable import Leaf
4+
5+
class FileLoadTests: XCTestCase {
6+
static let allTests = [
7+
("testLoadRawBytes", testLoadRawBytes),
8+
]
9+
10+
func testLoadRawBytes() throws {
11+
let leaf = try stem.spawnLeaf(named: "random-file.any")
12+
XCTAssert(Array(leaf.components).count == 1)
13+
14+
let rendered = try stem.render(leaf, with: Context([])).string
15+
// tags are not parsed in non-leaf document
16+
let expectation = "This file #(won't) be #rendered() {}\n"
17+
XCTAssertEqual(rendered, expectation)
18+
19+
// test cache
20+
_ = try stem.spawnLeaf(named: "random-file.any")
21+
}
22+
}

0 commit comments

Comments
 (0)