diff options
Diffstat (limited to 'src/package.c')
| -rw-r--r-- | src/package.c | 125 |
1 files changed, 125 insertions, 0 deletions
diff --git a/src/package.c b/src/package.c index e69de29..2e571e9 100644 --- a/src/package.c +++ b/src/package.c @@ -0,0 +1,125 @@ +#include "package.h" + +#include "lauxlib.h" +#include "lualib.h" +#include "malloc.h" +#include "pow_lua.h" +#include "stdio.h" +#include "string.h" + +int extract_package_info(lua_State *L, pow_package *pkg) { + lua_getfield(L, -1, "name"); + + if (!lua_isstring(L, -1)) { + printf("invalid package, name is not string (or doesn't exist)\n"); + + return 1; + } + + pkg->name = strdup(lua_tostring(L, -1)); + + if (!pkg->name) { + printf("strdup failed trying to get package name\n"); + + return 1; + } + + lua_pop(L, 1); + + lua_getfield(L, -1, "version"); + + if (!lua_isstring(L, -1)) { + printf("invalid package, version is not string (or doesn't exist)\n"); + + return 1; + } + + pkg->version = strdup(lua_tostring(L, -1)); + + if (!pkg->version) { + printf("strdup failed trying to get package name\n"); + } + + return 0; +} + +int package_open(pow_package *pkg, const char *path) { + FILE *fp; + int c; + int err; + + fp = fopen(path, "r"); + + if (!fp) { + printf("error opening package definition, doesn't exist?\n"); + + return 1; + } + + char *package_buffer = malloc(4096); + + size_t total = 0; + size_t capacity = 4096; + + while ((c = fgetc(fp)) != EOF) { + if (total + 1 >= capacity) { + capacity *= 2; + + char *tmp = realloc(package_buffer, capacity); + + if (!tmp) { + fclose(fp); + + printf("failed to realloc package buffer\n"); + + return 1; + } + + printf("reallocated package buffer due to size constraints\n"); + + package_buffer = tmp; + } + + package_buffer[total++] = c; + } + + package_buffer[total] = '\0'; + + lua_State *L = luaL_newstate(); + + pkg->L = L; + + luaL_openlibs(L); + pow_lua_load(L); + + luaL_loadstring(L, package_buffer); + + err = lua_pcall(L, 0, 1, 0); + + free(package_buffer); + + if (err) { + printf("%s\n", lua_tostring(L, -1)); + + return 1; + } + + if (!lua_istable(L, -1)) { + printf("invalid package, scripts must return table\n"); + + return 1; + } + + extract_package_info(L, pkg); + + return 0; +} + +int package_close(pow_package *pkg) { + free(pkg->name); + free(pkg->version); + + lua_close(pkg->L); + + return 0; +} |
