fmt/yaml.bend

cswap-bend-cli@0.1.0.0 · 33 lines · 5 definitions

1import Base
2import cswap-bend-cli@0.1.0.0/json.bend as Json
3import cswap-bend-cli@0.1.0.0/fmt/yamlw.bend as W
4import cswap-bend-cli@0.1.0.0/fmt/yamlr.bend as R
5
6# YAML for the JSON data model: `emit` writes block style (yamlw.bend),
7# `parse` reads the subset cswap writes plus plain block maps, lists and
8# scalars (yamlr.bend).
9
10def emit(j: Json.Json) -> String:
11  W.emit(j)
12
13def flowy(+s: String) -> Bool:
14  String.starts_with(String.trim_start(s), "{") || String.starts_with(String.trim_start(s), "[")
15
16# JSON is YAML: a document that opens with `{` or `[` is read as JSON when it
17# is JSON (nested flow collections, quoted keys), else by the block reader.
18def parse.json(r: Result<&2, &2, String, Json.Json>, +s: String) -> Result<&2, &2, String, Json.Json>:
19  match r:
20    case Done{j}:
21      Done{j}
22    case Fail{e}:
23      R.parse(s)
24
25def parse.pick(flow: Bool, +s: String) -> Result<&2, &2, String, Json.Json>:
26  match flow:
27    case True{}:
28      parse.json(Json.parse(s), s)
29    case False{}:
30      R.parse(s)
31
32def parse(+s: String) -> Result<&2, &2, String, Json.Json>:
33  parse.pick(flowy(s), s)