685613fbdcccad36dd9afd1c0964ac74d566464a
[project/luci.git] / libs / web / src / template_lualib.c
1 /*
2  * LuCI Template - Lua binding
3  *
4  *   Copyright (C) 2009 Jo-Philipp Wich <xm@subsignal.org>
5  *
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  */
18
19 #include "template_lualib.h"
20
21 int template_L_parse(lua_State *L)
22 {
23         const char *file = luaL_checkstring(L, 1);
24         struct template_parser parser;
25         int lua_status;
26
27         if( (parser.fd = open(file, O_RDONLY)) > 0 )
28         {
29                 parser.flags   = 0;
30                 parser.bufsize = 0;
31                 parser.state   = T_STATE_TEXT_NEXT;
32                 
33                 if( !(lua_status = lua_load(L, template_reader, &parser, file)) )
34                 {
35                         return 1;
36                 }
37                 else
38                 {
39                         lua_pushnil(L);
40                         lua_pushinteger(L, lua_status);
41                         lua_pushlstring(L, parser.out, parser.outsize);
42                         return 3;
43                 }
44         }
45
46         lua_pushnil(L);
47         lua_pushinteger(L, 255);
48         lua_pushstring(L, "No such file or directory");
49         return 3;
50 }
51
52 /* module table */
53 static const luaL_reg R[] = {
54         {"parse",       template_L_parse},
55         {NULL,          NULL}
56 };
57
58 LUALIB_API int luaopen_luci_template_parser(lua_State *L) {
59         luaL_register(L, TEMPLATE_LUALIB_META, R);
60         return 1;
61 }
62