forked from Code52/pretzel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathYamlExtensions.cs
115 lines (99 loc) · 3.3 KB
/
YamlExtensions.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using YamlDotNet.RepresentationModel;
using System.IO;
using System.Linq;
using YamlDotNet.Serialization;
namespace Pretzel.Logic.Extensions
{
public static class YamlExtensions
{
static readonly Regex r = new Regex(@"(?s:^---(.*?)---)");
public static IDictionary<string, object> YamlHeader(this string text, bool skipHeader = false)
{
StringReader input;
var results = new Dictionary<string, object>();
if (!skipHeader)
{
var m = r.Matches(text);
if (m.Count == 0)
return results;
input = new StringReader(m[0].Groups[1].Value);
}
else
{
input = new StringReader(text);
}
var yaml = new YamlStream();
yaml.Load(input);
if (yaml.Documents.Count == 0)
return results;
var root = yaml.Documents[0].RootNode;
var collection = root as YamlMappingNode;
if (collection != null)
{
foreach (var entry in collection.Children)
{
var node = entry.Key as YamlScalarNode;
if (node != null)
{
results.Add(node.Value, GetValue(entry.Value));
}
}
}
return results;
}
private static object GetValue(YamlNode value)
{
var collection = value as YamlMappingNode;
if (collection != null)
{
var results = new Dictionary<string, object>();
foreach (var entry in collection.Children)
{
var node = entry.Key as YamlScalarNode;
if (node != null)
{
results.Add(node.Value, GetValue(entry.Value));
}
}
return results;
}
var list = value as YamlSequenceNode;
if (list != null)
{
var listResults = new List<string>();
foreach (var entry in list.Children)
{
var node = entry as YamlScalarNode;
if (node != null)
{
listResults.Add(node.Value);
}
}
return listResults;
}
bool valueBool;
if (bool.TryParse(value.ToString(), out valueBool))
{
return valueBool;
}
return value.ToString();
}
public static string ToYaml<T>(this T model)
{
var stringWriter = new StringWriter();
var serializer = new Serializer();
serializer.Serialize(stringWriter, model, typeof(T));
return stringWriter.ToString();
}
public static string ExcludeHeader(this string text)
{
var m = r.Matches(text);
if (m.Count == 0)
return text;
return text.Replace(m[0].Groups[0].Value, "").TrimStart('\r', '\n').TrimEnd();
}
}
}