2020-05-11 16:12:21 -05:00
|
|
|
using System;
|
|
|
|
|
using System.Text.RegularExpressions;
|
|
|
|
|
using YamlDotNet.Core;
|
|
|
|
|
using YamlDotNet.Serialization;
|
|
|
|
|
using YamlDotNet.Serialization.EventEmitters;
|
|
|
|
|
|
|
|
|
|
namespace k8s
|
|
|
|
|
{
|
|
|
|
|
// adapted from https://github.com/cloudbase/powershell-yaml/blob/master/powershell-yaml.psm1
|
|
|
|
|
public class StringQuotingEmitter : ChainedEventEmitter
|
|
|
|
|
{
|
|
|
|
|
// Patterns from https://yaml.org/spec/1.2/spec.html#id2804356
|
2020-11-01 12:24:51 -08:00
|
|
|
private static readonly Regex QuotedRegex =
|
2020-05-11 16:12:21 -05:00
|
|
|
new Regex(@"^(\~|null|true|false|-?(0|[1-9][0-9]*)(\.[0-9]*)?([eE][-+]?[0-9]+)?)?$");
|
|
|
|
|
|
2020-11-01 12:24:51 -08:00
|
|
|
public StringQuotingEmitter(IEventEmitter next)
|
|
|
|
|
: base(next)
|
2020-05-11 16:12:21 -05:00
|
|
|
{
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <inheritdoc/>
|
|
|
|
|
public override void Emit(ScalarEventInfo eventInfo, IEmitter emitter)
|
|
|
|
|
{
|
|
|
|
|
var typeCode = eventInfo.Source.Value != null
|
|
|
|
|
? Type.GetTypeCode(eventInfo.Source.Type)
|
|
|
|
|
: TypeCode.Empty;
|
|
|
|
|
switch (typeCode)
|
|
|
|
|
{
|
|
|
|
|
case TypeCode.Char:
|
|
|
|
|
if (char.IsDigit((char)eventInfo.Source.Value))
|
|
|
|
|
{
|
|
|
|
|
eventInfo.Style = ScalarStyle.DoubleQuoted;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
break;
|
|
|
|
|
case TypeCode.String:
|
|
|
|
|
var val = eventInfo.Source.Value.ToString();
|
2020-11-01 12:24:51 -08:00
|
|
|
if (QuotedRegex.IsMatch(val))
|
2020-05-11 16:12:21 -05:00
|
|
|
{
|
|
|
|
|
eventInfo.Style = ScalarStyle.DoubleQuoted;
|
|
|
|
|
}
|
|
|
|
|
else if (val.IndexOf('\n') > -1)
|
|
|
|
|
{
|
|
|
|
|
eventInfo.Style = ScalarStyle.Literal;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
base.Emit(eventInfo, emitter);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|