f91b19ceb85c07f1778771cc29d72b1adfa94feb
[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                 lua_status = lua_load(L, template_reader, &parser, file);
34
35                 (void) close(parser.fd);
36
37
38                 if( lua_status == 0 )
39                 {
40                         return 1;
41                 }
42                 else
43                 {
44                         lua_pushnil(L);
45                         lua_pushinteger(L, lua_status);
46                         lua_pushlstring(L, parser.out, parser.outsize);
47                         return 3;
48                 }
49         }
50
51         lua_pushnil(L);
52         lua_pushinteger(L, 255);
53         lua_pushstring(L, "No such file or directory");
54         return 3;
55 }
56
57 /* module table */
58 static const luaL_reg R[] = {
59         {"parse",       template_L_parse},
60         {NULL,          NULL}
61 };
62
63 LUALIB_API int luaopen_luci_template_parser(lua_State *L) {
64         luaL_register(L, TEMPLATE_LUALIB_META, R);
65         return 1;
66 }
67