-
Notifications
You must be signed in to change notification settings - Fork 301
/
Copy pathStringQuotingEmitter.cs
52 lines (46 loc) · 1.81 KB
/
StringQuotingEmitter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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 and https://yaml.org/type/bool.html (spec v1.1)
private static readonly Regex QuotedRegex =
new Regex(@"^(\~|null|Null|NULL|true|True|TRUE|false|False|FALSE|y|Y|yes|Yes|YES|on|On|ON|n|N|no|No|NO|off|Off|OFF|-?(0|[0-9]*)(\.[0-9]*)?([eE][-+]?[0-9]+)?)?$");
public StringQuotingEmitter(IEventEmitter next)
: base(next)
{
}
/// <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();
if (QuotedRegex.IsMatch(val))
{
eventInfo.Style = ScalarStyle.DoubleQuoted;
}
else if (val.IndexOf('\n') > -1)
{
eventInfo.Style = ScalarStyle.Literal;
}
break;
}
base.Emit(eventInfo, emitter);
}
}
}