Refactor spawn.c

This moves some code of parse_command() out into a new helper function.
No functional changes intended.

Signed-off-by: Uli Schlachter <psychon@znc.in>
This commit is contained in:
Uli Schlachter 2017-08-12 16:32:27 +02:00 committed by Daniel Hahler
parent cc0871498c
commit aac519b946
1 changed files with 43 additions and 26 deletions

69
spawn.c
View File

@ -369,6 +369,48 @@ spawn_callback(gpointer user_data)
unsetenv("DESKTOP_STARTUP_ID");
}
/** Convert a Lua table of string to a char** array.
* \param L The Lua VM state.
* \param idx The index of the table that we should parse
* \return The argv array.
*/
static gchar **
parse_table_array(lua_State *L, int idx, GError **error)
{
gchar **argv = NULL;
size_t i, len;
luaL_checktype(L, idx, LUA_TTABLE);
idx = luaA_absindex(L, idx);
len = luaA_rawlen(L, idx);
/* First verify that the table is sane: All integer keys must contain
* strings. Do this by pushing them all onto the stack.
*/
for (i = 0; i < len; i++)
{
lua_rawgeti(L, idx, i+1);
if (lua_type(L, -1) != LUA_TSTRING)
{
g_set_error(error, G_SPAWN_ERROR, 0,
"Non-string argument at table index %zd", i+1);
return NULL;
}
}
/* From this point on nothing can go wrong and so we can safely allocate
* memory.
*/
argv = g_new0(gchar *, len + 1);
for (i = 0; i < len; i++)
{
argv[len - i - 1] = g_strdup(lua_tostring(L, -1));
lua_pop(L, 1);
}
return argv;
}
/** Parse a command line.
* \param L The Lua VM state.
* \param idx The index of the argument that we should parse
@ -378,7 +420,6 @@ static gchar **
parse_command(lua_State *L, int idx, GError **error)
{
gchar **argv = NULL;
idx = luaA_absindex(L, idx);
if (lua_isstring(L, idx))
{
@ -388,31 +429,7 @@ parse_command(lua_State *L, int idx, GError **error)
}
else if (lua_istable(L, idx))
{
size_t i, len = luaA_rawlen(L, idx);
/* First verify that the table is sane: All integer keys must contain
* strings. Do this by pushing them all onto the stack.
*/
for (i = 0; i < len; i++)
{
lua_rawgeti(L, idx, i+1);
if (lua_type(L, -1) != LUA_TSTRING)
{
g_set_error(error, G_SPAWN_ERROR, 0,
"Non-string argument at table index %zd", i+1);
return NULL;
}
}
/* From this point on nothing can go wrong and so we can safely allocate
* memory.
*/
argv = g_new0(gchar *, len + 1);
for (i = 0; i < len; i++)
{
argv[len - i - 1] = g_strdup(lua_tostring(L, -1));
lua_pop(L, 1);
}
argv = parse_table_array(L, idx, error);
}
else
{