11using NativeCodeGen . Core . Models ;
2+ using YamlDotNet . Serialization ;
3+ using YamlDotNet . Serialization . NamingConventions ;
24
35namespace NativeCodeGen . Core . Registry ;
46
7+ public class SharedExampleFrontmatter
8+ {
9+ public string ? Title { get ; set ; }
10+ }
11+
512public class SharedExampleRegistry
613{
714 private readonly Dictionary < string , SharedExample > _examples = new ( StringComparer . OrdinalIgnoreCase ) ;
15+ private readonly IDeserializer _deserializer ;
816
917 public int Count => _examples . Count ;
1018
19+ public SharedExampleRegistry ( )
20+ {
21+ _deserializer = new DeserializerBuilder ( )
22+ . WithNamingConvention ( CamelCaseNamingConvention . Instance )
23+ . IgnoreUnmatchedProperties ( )
24+ . Build ( ) ;
25+ }
26+
1127 public void LoadExamples ( string directory )
1228 {
1329 if ( ! Directory . Exists ( directory ) )
@@ -18,19 +34,54 @@ public void LoadExamples(string directory)
1834 var name = Path . GetFileNameWithoutExtension ( file ) ;
1935 var content = File . ReadAllText ( file ) ;
2036
21- // Extract language and code content from markdown code block
22- var ( language , code ) = ParseCodeBlock ( content ) ;
37+ // Extract frontmatter and code content
38+ var ( frontmatter , body ) = ParseFrontmatter ( content ) ;
39+ var ( language , code ) = ParseCodeBlock ( body ) ;
2340
2441 _examples [ name ] = new SharedExample
2542 {
2643 Name = name ,
44+ Title = frontmatter ? . Title ,
2745 Content = code ,
2846 Language = language ,
2947 SourceFile = file
3048 } ;
3149 }
3250 }
3351
52+ private ( SharedExampleFrontmatter ? frontmatter , string body ) ParseFrontmatter ( string content )
53+ {
54+ var lines = content . Split ( '\n ' ) ;
55+ if ( lines . Length == 0 || lines [ 0 ] . Trim ( ) != "---" )
56+ return ( null , content ) ;
57+
58+ int endIndex = - 1 ;
59+ for ( int i = 1 ; i < lines . Length ; i ++ )
60+ {
61+ if ( lines [ i ] . Trim ( ) == "---" )
62+ {
63+ endIndex = i ;
64+ break ;
65+ }
66+ }
67+
68+ if ( endIndex == - 1 )
69+ return ( null , content ) ;
70+
71+ var yamlContent = string . Join ( '\n ' , lines . Skip ( 1 ) . Take ( endIndex - 1 ) ) ;
72+ var body = string . Join ( "\n " , lines . Skip ( endIndex + 1 ) ) ;
73+
74+ try
75+ {
76+ var frontmatter = _deserializer . Deserialize < SharedExampleFrontmatter > ( yamlContent ) ;
77+ return ( frontmatter , body ) ;
78+ }
79+ catch
80+ {
81+ return ( null , body ) ;
82+ }
83+ }
84+
3485 private static ( string ? language , string content ) ParseCodeBlock ( string content )
3586 {
3687 var lines = content . Split ( '\n ' ) ;
0 commit comments