| | | 1 | | using System.Text.RegularExpressions; |
| | | 2 | | using YamlDotNet.Core; |
| | | 3 | | using YamlDotNet.Serialization; |
| | | 4 | | using YamlDotNet.Serialization.EventEmitters; |
| | | 5 | | |
| | | 6 | | namespace Kestrun.Utilities.Yaml; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// YAML emitter that quotes strings that might be misinterpreted as other types |
| | | 10 | | /// </summary> |
| | | 11 | | /// <param name="next">The next event emitter in the chain</param> |
| | 21 | 12 | | public partial class StringQuotingEmitter(IEventEmitter next) : ChainedEventEmitter(next) |
| | | 13 | | { |
| | | 14 | | // Patterns from https://yaml.org/spec/1.2/spec.html#id2804356 |
| | 1 | 15 | | private static readonly Regex quotedRegex = MyRegex(); |
| | | 16 | | |
| | | 17 | | /// <summary> |
| | | 18 | | /// Emit a scalar event, quoting strings that might be misinterpreted as other types |
| | | 19 | | /// </summary> |
| | | 20 | | /// <param name="eventInfo">The event information</param> |
| | | 21 | | /// <param name="emitter">The YAML emitter</param> |
| | | 22 | | public override void Emit(ScalarEventInfo eventInfo, IEmitter emitter) |
| | | 23 | | { |
| | 91 | 24 | | var typeCode = eventInfo.Source.Value != null |
| | 91 | 25 | | ? Type.GetTypeCode(eventInfo.Source.Type) |
| | 91 | 26 | | : TypeCode.Empty; |
| | | 27 | | |
| | | 28 | | switch (typeCode) |
| | | 29 | | { |
| | | 30 | | case TypeCode.Char: |
| | 0 | 31 | | if (eventInfo.Source.Value is char c && char.IsDigit(c)) |
| | | 32 | | { |
| | 0 | 33 | | eventInfo.Style = ScalarStyle.DoubleQuoted; |
| | | 34 | | } |
| | 0 | 35 | | break; |
| | | 36 | | case TypeCode.String: |
| | 62 | 37 | | var val = eventInfo.Source.Value?.ToString() ?? string.Empty; |
| | 62 | 38 | | var tagVal = eventInfo.Tag.IsEmpty ? null : eventInfo.Tag.Value; |
| | | 39 | | // Standard YAML null tag with empty value -> leave blank plain scalar (no quotes or 'null' literal) |
| | 62 | 40 | | if (string.Equals(tagVal, "tag:yaml.org,2002:null", StringComparison.Ordinal) && val.Length == 0) |
| | | 41 | | { |
| | 0 | 42 | | eventInfo.Style = ScalarStyle.Plain; |
| | | 43 | | // Remove tag to avoid explicit tag output; blank value implies null |
| | 0 | 44 | | eventInfo.Tag = TagName.Empty; |
| | 0 | 45 | | break; |
| | | 46 | | } |
| | 62 | 47 | | if (val.Length > 0 && quotedRegex.IsMatch(val)) |
| | | 48 | | { |
| | 4 | 49 | | eventInfo.Style = ScalarStyle.DoubleQuoted; |
| | | 50 | | } |
| | 58 | 51 | | else if (val.IndexOf('\n') > -1) |
| | | 52 | | { |
| | 0 | 53 | | eventInfo.Style = ScalarStyle.Literal; |
| | | 54 | | } |
| | | 55 | | break; |
| | | 56 | | } |
| | | 57 | | |
| | 91 | 58 | | base.Emit(eventInfo, emitter); |
| | 91 | 59 | | } |
| | | 60 | | |
| | | 61 | | [GeneratedRegex(@"^(\~|null|true|false|on|off|yes|no|y|n|[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?|[-+]?(\ |
| | | 62 | | private static partial Regex MyRegex(); |
| | | 63 | | } |