| | | 1 | | using System.Text.RegularExpressions; |
| | | 2 | | |
| | | 3 | | namespace Kestrun.Utilities.Yaml; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// Provides helper methods for serializing and deserializing YAML content, with special handling for PowerShell objects |
| | | 7 | | /// </summary> |
| | | 8 | | public static partial class YamlHelper |
| | | 9 | | { |
| | | 10 | | /// <summary> |
| | | 11 | | /// Serializes any PowerShell object to YAML format, with specified serialization options. |
| | | 12 | | /// </summary> |
| | | 13 | | /// <param name="input">The PowerShell object to serialize. Can be null.</param> |
| | | 14 | | /// <param name="options">The serialization options to apply.</param> |
| | | 15 | | /// <returns>A string containing the YAML representation of the input object.</returns> |
| | | 16 | | public static string ToYaml(object? input, SerializationOptions? options = null) |
| | | 17 | | { |
| | 16 | 18 | | var wrt = new StringWriter(); |
| | | 19 | | // Default options intentionally omit Roundtrip to allow serialization of anonymous types |
| | | 20 | | // without requiring default constructors (Roundtrip enforces reconstructable object graphs). |
| | 16 | 21 | | options ??= SerializationOptions.DisableAliases | SerializationOptions.EmitDefaults | SerializationOptions.WithI |
| | 16 | 22 | | var serializer = YamlSerializerFactory.GetSerializer(options.Value); |
| | | 23 | | |
| | 16 | 24 | | serializer.Serialize(wrt, input); |
| | | 25 | | // Post-process: convert null dictionary entries serialized as '' into blank null form (key: \n) |
| | | 26 | | // Safe regex: only targets single-quoted empty string immediately after colon with optional space. |
| | 16 | 27 | | return MyRegex().Replace(wrt.ToString(), "${k}:"); |
| | | 28 | | } |
| | | 29 | | |
| | | 30 | | // This regex matches dictionary entries in YAML that have a key followed by a colon and a single-quoted empty strin |
| | | 31 | | // It captures the key name in the named group 'k'. The replacement string "${k}:" rewrites such entries to the blan |
| | | 32 | | // which is the preferred YAML representation for null values. This post-processing step ensures that null dictionar |
| | | 33 | | [GeneratedRegex(@"^(?<k>[^:\r\n]+):\s*''\s*$", RegexOptions.Multiline)] |
| | | 34 | | private static partial Regex MyRegex(); |
| | | 35 | | } |