robin/maivi
a tiny cute lua web framework
git clone https://git.robinwobin.dev/robin/maivi
6e07b35
main
1const std =@import ( "std" ); 2const Io =std . Io ; 3 4const zlua =@import ( "zlua" ); 5pub const Lua =zlua . Lua ; 6 7const maivi =@import ( "../root.zig" ); 8const helpers =maivi . helpers ; 9 10/// * Pops from Stack: `0` 11/// * Pushes to Stack: `1` 12pub fn read ( l : * Lua , io : Io , path : [] const u8 ) ! void { 13const dir =try Io . Dir . openDirAbsolute ( io , maivi . config . root , .{}); 14defer dir . close ( io ); 15const contents =try helpers . read_file ( io , maivi . allocator , dir , path ); 16defer maivi . allocator . free ( contents ); 17 18var ctx : Context =.{ 19. path =path , 20. content =contents , 21}; 22try maivi . lua . trigger ( l , Context , & ctx , . read_data , .{ 23. path =path , 24. pattern =path , 25}); 26 27if ( ctx . content_ref ) | ref | { 28_ = l . getIndexRaw ( zlua . registry_index , ref ); 29} else _ = l . pushString ( contents ); 30} 31 32const Context =struct { 33path : [] const u8 , 34content : [] const u8 , 35content_ref : ? i32 =null , 36ref : ? i32 =null , // reusable lua ref for hooks 37 38pub fn toLua ( self : Context , l : * Lua ) ! void { 39// { url = ..., path = ..., content = ... } 40l . createTable ( 0 , 2 ); 41 42// path 43_ = l . pushString ( self . path ); 44l . setField ( - 2 , "path" ); // path 45 46// content 47_ = l . pushString ( self . content ); 48l . setField ( - 2 , "content" ); // content 49 50// metatable 51try maivi . lua . setMethodTable ( l , MT ); 52} 53 54pub const MT =struct { 55pub fn use ( l : * Lua ) ! i32 { 56l . argCheck ( l . isTable ( 1 ), 1 , "ctx" ); 57l . argCheck ( l . isString ( 2 ), 2 , "string" ); 58// -1 => content, -2 => ctx 59 60const ctx =blk : { 61const ltype_ptr =l . getField ( 1 , "ptr" ); 62defer l . pop ( 1 ); 63if ( ltype_ptr != . light_userdata ) return error . InvalidPtr ; 64break : blk try l . toUserdata ( Context , - 1 ); 65}; 66 67ctx . content_ref = maivi . lua . toRef ( l , - 1 ); 68 69return 0 ; 70} 71}; 72};