2 * libuci plugin for Lua
3 * Copyright (C) 2008 Felix Fietkau <nbd@openwrt.org>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2
7 * as published by the Free Software Foundation
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
15 #include <sys/types.h>
30 #define DPRINTF(...) fprintf(stderr, __VA_ARGS__)
32 #define DPRINTF(...) do {} while (0)
35 static struct uci_context *ctx = NULL;
37 static struct uci_package *
38 find_package(const char *name)
40 struct uci_package *p = NULL;
41 struct uci_element *e;
42 uci_foreach_element(&ctx->root, e) {
43 if (strcmp(e->name, name) != 0)
46 p = uci_to_package(e);
52 static void uci_lua_perror(lua_State *L, char *name)
54 lua_getfield(L, LUA_GLOBALSINDEX, "uci");
55 lua_getfield(L, -1, "warn");
56 if (!lua_isboolean(L, -1))
58 if (lua_toboolean(L, -1) != 1)
60 uci_perror(ctx, name);
66 uci_lua_load(lua_State *L)
68 struct uci_package *p;
72 s = lua_tostring(L, -1);
78 if (uci_load(ctx, s, &p)) {
79 uci_lua_perror(L, "uci.load");
80 lua_pushboolean(L, 0);
82 lua_pushboolean(L, 1);
89 uci_lua_get(lua_State *L)
91 struct uci_lua_context *f;
92 struct uci_element *e = NULL;
93 struct uci_package *p = NULL;
98 int err = UCI_ERR_MEM;
101 s = strdup(lua_tostring(L, -1));
105 if ((err = uci_parse_tuple(ctx, s, &package, §ion, &option, NULL)))
108 if (section == NULL) {
113 p = find_package(package);
115 err = UCI_ERR_NOTFOUND;
119 if ((err = uci_lookup(ctx, &e, p, section, option)))
123 case UCI_TYPE_SECTION:
124 lua_pushstring(L, uci_to_section(e)->type);
126 case UCI_TYPE_OPTION:
127 lua_pushstring(L, uci_to_option(e)->value);
140 uci_lua_perror(L, "uci.get");
142 case UCI_ERR_NOTFOUND:
151 static const luaL_Reg uci[] = {
152 { "load", uci_lua_load },
153 { "get", uci_lua_get },
159 luaopen_uci(lua_State *L)
161 ctx = uci_alloc_context();
163 luaL_error(L, "Cannot allocate UCI context\n");
164 luaL_register(L, MODNAME, uci);