Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFrontmatterParser.cs
More file actions
Latest commit
69 lines (59 loc) · 2.08 KB
/
Copy pathFrontmatterParser.cs
File metadata and controls
69 lines (59 loc) · 2.08 KB
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
usingYamlDotNet.Serialization;
namespaceShellDocs.Core;
publicstaticclassFrontmatterParser
{
privatestaticreadonlystring[]LineSeparators=new[]{"\r\n","\n"};
privatestaticreadonlyIDeserializerYamlDeserializer=newDeserializerBuilder().Build();
publicstaticParsedDocumentParse(stringsource)
{
if(string.IsNullOrEmpty(source))
{
returnnewParsedDocument(newDictionary<string,object?>(),source??"");
}
varlines=source.Split(LineSeparators,StringSplitOptions.None);
if(lines.Length<2||lines[0].TrimEnd()!="---")
{
returnnewParsedDocument(newDictionary<string,object?>(),source);
}
varclosingIndex=-1;
for(vari=1;i<lines.Length;i++)
{
if(lines[i].TrimEnd()=="---")
{
closingIndex=i;
break;
}
}
if(closingIndex==-1)
{
returnnewParsedDocument(newDictionary<string,object?>(),source);
}
varyaml=string.Join("\n",lines[1..closingIndex]);
varbody=string.Join("\n",lines[(closingIndex+1)..]);
Dictionary<string,object?>frontmatter;
try
{
frontmatter=YamlDeserializer.Deserialize<Dictionary<string,object?>>(yaml)
??newDictionary<string,object?>();
}
catch(YamlDotNet.Core.YamlException)
{
frontmatter=newDictionary<string,object?>();
}
returnnewParsedDocument(frontmatter,body);
}
publicstaticT?GetValue<T>(thisIReadOnlyDictionary<string,object?>frontmatter,stringkey)
{
if(!frontmatter.TryGetValue(key,outvarraw)||rawisnull)returndefault;
if(rawisTtyped)returntyped;
try
{
return(T)Convert.ChangeType(raw,typeof(T));
}
catch
{
returndefault;
}
}
}
publicrecordParsedDocument(IReadOnlyDictionary<string,object?>Frontmatter,stringBody);