| | | 1 | | using YamlDotNet.Core; |
| | | 2 | | using YamlDotNet.RepresentationModel; |
| | | 3 | | |
| | | 4 | | namespace Kestrun.Utilities.Yaml; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Utility class for loading and parsing YAML documents |
| | | 8 | | /// </summary> |
| | | 9 | | public static class YamlLoader |
| | | 10 | | { |
| | | 11 | | /// <summary> |
| | | 12 | | /// Parses one or more YAML documents from a string and returns a YamlStream. |
| | | 13 | | /// Set <paramref name="useMergingParser"/> to true to enable YAML anchors/aliases mergehandling. |
| | | 14 | | /// </summary> |
| | | 15 | | /// <param name="yaml">The YAML string to parse.</param> |
| | | 16 | | /// <param name="useMergingParser">Whether to use a merging parser to handle anchors and aliases.</param> |
| | | 17 | | /// <returns>A YamlStream containing the parsed documents.</returns> |
| | | 18 | | /// <exception cref="ArgumentNullException">Thrown if the input YAML string is null.</exception> |
| | | 19 | | public static YamlStream GetYamlDocuments(string yaml, bool useMergingParser = false) |
| | | 20 | | { |
| | 3 | 21 | | ArgumentNullException.ThrowIfNull(yaml); |
| | | 22 | | |
| | 3 | 23 | | using var reader = new StringReader(yaml); |
| | | 24 | | |
| | 3 | 25 | | IParser parser = new Parser(reader); // YamlDotNet.Core.Parser |
| | 3 | 26 | | if (useMergingParser) |
| | | 27 | | { |
| | | 28 | | // YamlDotNet.Core.MergingParser wraps an existing parser |
| | 1 | 29 | | parser = new MergingParser(parser); |
| | | 30 | | } |
| | | 31 | | |
| | 3 | 32 | | var stream = new YamlStream(); // YamlDotNet.RepresentationModel.YamlStream |
| | 3 | 33 | | stream.Load(parser); // parse the stream (may contain multiple docs) |
| | 3 | 34 | | return stream; |
| | 3 | 35 | | } |
| | | 36 | | |
| | | 37 | | /// <summary> |
| | | 38 | | /// Convenience: returns each document's root node from a yaml string. |
| | | 39 | | /// </summary> |
| | | 40 | | public static IReadOnlyList<YamlNode> GetRootNodes(string yaml, bool useMergingParser = false) |
| | | 41 | | { |
| | 2 | 42 | | var ys = GetYamlDocuments(yaml, useMergingParser); |
| | 5 | 43 | | return [.. ys.Documents.Select(d => d.RootNode)]; |
| | | 44 | | } |
| | | 45 | | |
| | | 46 | | /// <summary> |
| | | 47 | | /// Convenience: fully convert to .NET objects using your converter (mapping→dict, seq→array, scalar→typed). |
| | | 48 | | /// </summary> |
| | | 49 | | public static IReadOnlyList<object?> DeserializeToObjects(string yaml, bool useMergingParser = false) |
| | | 50 | | { |
| | 1 | 51 | | var ys = GetYamlDocuments(yaml, useMergingParser); |
| | 1 | 52 | | var result = new List<object?>(ys.Documents.Count); |
| | 4 | 53 | | foreach (var doc in ys.Documents) |
| | | 54 | | { |
| | 1 | 55 | | result.Add(YamlTypeConverter.ConvertYamlDocumentToPSObject(doc.RootNode, ordered: false)); |
| | | 56 | | } |
| | 1 | 57 | | return result; |
| | | 58 | | } |
| | | 59 | | } |