Skip to main content

Module yaml

Module yaml 

Source
Expand description

The layer’s YAML subset, as docs/SCHEMAS.md and the shell tool’s mj_yaml_flatten define it: key: value, nested maps by two-space indent, block lists (- item), lists of maps (- key: value plus indented keys), inline lists [a, b], single or double quotes, comments. Tabs, odd indentation, anchors, multi-line scalars and flow maps are refused with the line named (the shell parser reads an anchor or alias as text; this one refuses it, which is the stricter reading of the same contract). A scalar is a string unless it is an unquoted integer or true/false; nothing else is interpreted.

use majordomus_cli::metadata::yaml;

let text = "\
version: 1
sources:
  - id: policy
    kind: policy
    required: true
tags: [rust, quality]
";
let map = yaml::parse_mapping(text).unwrap();
assert_eq!(map["version"], 1, "an unquoted integer is a number");
assert_eq!(map["sources"][0]["kind"], "policy");
assert_eq!(map["sources"][0]["required"], true);
assert_eq!(map["tags"][1], "quality", "an inline list is a list");

// every key path, which is how an unknown key is found and reported
assert!(yaml::key_paths(&map).contains(&"sources.0.kind".to_string()));

// what the subset refuses, it refuses with the line named rather than guessing
assert!(yaml::parse_mapping("a: &anchor 1\n").is_err());
assert!(yaml::parse_mapping("a:\n\tb: 1\n").is_err(), "tabs are not indentation");

This is not a general YAML parser and does not try to be: the repository’s files are written in this subset so that a person, an awk script and this executable read them identically, and a construct outside it is a mistake in the file, not a gap here.

Functions§

key_paths
Every leaf key path of a value, in document order, as the allow-lists are written: a.b.0.c. An empty list is itself a leaf, so that tags: [] flattens to tags.
parse_into
Parse and deserialize into a typed value.
parse_mapping
Parse a document of the subset into an ordered mapping.
render
Render a JSON value as a YAML document in the layer’s subset wherever the value fits it, and in a conservative quoted style wherever it does not.
render_with_banner
Render a value as a YAML document under a comment banner, one # line per line of banner. The banner is a comment and never part of the data.
scalar_string
A scalar as the string an identity or title uses; None for a list or mapping.