-
Notifications
You must be signed in to change notification settings - Fork 190
/
Metadata.swift
74 lines (58 loc) · 1.98 KB
/
Metadata.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
/**
* Ink
* Copyright (c) John Sundell 2019
* MIT license, see LICENSE file for details
*/
internal struct Metadata: Readable {
var values = [String : String]()
static func read(using reader: inout Reader) throws -> Metadata {
try require(reader.readCount(of: "-") == 3)
try reader.read("\n")
var metadata = Metadata()
var lastKey: String?
while !reader.didReachEnd {
reader.discardWhitespacesAndNewlines()
guard reader.currentCharacter != "-" else {
try require(reader.readCount(of: "-") == 3)
return metadata
}
let key = try trim(reader.read(until: ":", required: false))
guard reader.previousCharacter == ":" else {
if let lastKey = lastKey {
metadata.values[lastKey]?.append(" " + key)
}
continue
}
let value = trim(reader.readUntilEndOfLine())
if !value.isEmpty {
metadata.values[key] = value
lastKey = key
}
}
throw Reader.Error()
}
func applyingModifiers(_ modifiers: ModifierCollection) -> Self {
var modified = self
modifiers.applyModifiers(for: .metadataKeys) { modifier in
for (key, value) in modified.values {
let newKey = modifier.closure((key, Substring(key)))
modified.values[key] = nil
modified.values[newKey] = value
}
}
modifiers.applyModifiers(for: .metadataValues) { modifier in
modified.values = modified.values.mapValues { value in
modifier.closure((value, Substring(value)))
}
}
return modified
}
}
private extension Metadata {
static func trim(_ string: Substring) -> String {
String(string
.trimmingLeadingWhitespaces()
.trimmingTrailingWhitespaces()
)
}
}