Repository navigation
pkl for working with existing configs not yet in pkl format #2018
|
Hi! I'm trying to write a config file based SSG (yes another static site generator, I know I know) using pkl as the config files format. This is using swift-pkl. For new content with proper pkl formatting out of the gate it works great so far for zipping through the front matter to create different micro formats, but I'd like to be able to point this at old content which are a mix of front matter types (one ssg to rule them all, heh). Leaving aside the date as a Date for another day, is there a way to access the YAML parser (for example) to make code somewhat like the below work? There wasn't in 2024, I saw. struct ArticleHeader: Codable {
let title:String
let date:String
let priority: 1
}
public static func testHeader() async throws {
let fm_yaml = """
date: "2026-11-23"
title: "This is the title of the file"
priority: 1
"""
let res = try await withEvaluator { evaluator in
//how to use a different parser?
try await evaluator.evaluateModule(source: .text(fm_yaml), as: ArticleHeader.self, using: .ymlParser)
}
print(res)
}Thank you for your time looking at my very toy problem. |
Replies: 2 comments 2 replies
|
let source = """
import "pkl:yaml"
parsed = new yaml.Parser {}.parse(#\"\"\"
\(fm_yaml)
\"\"\"#)
"""
let res = try await evaluator.evaluateExpression(
source: .text(source),
expression: "parsed",
as: ArticleHeader.self
)To avoid string-escaping edge cases with arbitrary front matter, pass the raw text through |
|
Neat idea! @LucasValeQueiroz's suggestion is solid and likely how I'd approach this myself, but depending on the details, another way you might approach this is by decoding the YAML front matter directly into the Pkl-generated types using your favorite |
pkl-swiftdoesn't have ausing:parser parameter onevaluateModule, but Pkl's stdlib shipspkl:yaml(stdlib/yaml.pkl:57, 90) andpkl:json. You can wrap the front matter in a tiny Pkl snippet and decode the parsed result directly withevaluateExpression:To avoid string-escaping edge cases with arbitrary front matter, pass the raw text through
EvaluatorOptions.properties(e.g.properties: ["fm": fm_yaml]) and callnew yaml.Parser {}.parse(read("prop:fm")).