59 lines
1.9 KiB
Swift
59 lines
1.9 KiB
Swift
import Foundation
|
|
|
|
protocol Template {
|
|
|
|
associatedtype Key where Key: RawRepresentable, Key.RawValue == String, Key: CaseIterable, Key: Hashable
|
|
|
|
static var templateName: String { get }
|
|
|
|
var raw: String { get }
|
|
|
|
init(raw: String)
|
|
|
|
}
|
|
|
|
extension Template {
|
|
|
|
init(in folder: URL) throws {
|
|
let url = folder.appendingPathComponent(Self.templateName)
|
|
try self.init(from: url)
|
|
}
|
|
|
|
init(from url: URL) throws {
|
|
let raw = try String(contentsOf: url)
|
|
self.init(raw: raw)
|
|
}
|
|
|
|
func generate(_ content: [Key : String], to url: URL) -> Bool {
|
|
let content = generate(content)
|
|
return files.write(content, to: url)
|
|
}
|
|
|
|
func generate(_ content: [Key : String], shouldIndent: Bool = false) -> String {
|
|
var result = raw.components(separatedBy: "\n")
|
|
|
|
Key.allCases.forEach { key in
|
|
let newContent = content[key]?.withoutEmptyLines ?? ""
|
|
let stringMarker = "<!--\(key.rawValue)-->"
|
|
let indices = result.enumerated().filter { $0.element.contains(stringMarker) }
|
|
.map { $0.offset }
|
|
guard !indices.isEmpty else {
|
|
return
|
|
}
|
|
for index in indices {
|
|
let old = result[index].components(separatedBy: stringMarker)
|
|
// Add indentation to all added lines
|
|
let indentation = old.first!
|
|
guard shouldIndent, indentation.trimmingCharacters(in: .whitespaces).isEmpty else {
|
|
// Prefix is not indentation, so just insert new content
|
|
result[index] = old.joined(separator: newContent)
|
|
continue
|
|
}
|
|
let indentedReplacements = newContent.indented(by: indentation)
|
|
result[index] = old.joined(separator: indentedReplacements)
|
|
}
|
|
}
|
|
return result.joined(separator: "\n").withoutEmptyLines
|
|
}
|
|
}
|