flua: lposix: add fnmatch function

The fnmatch function matches a string against a shell-style filename
pattern. It is a complex function and cannot easily be implenented
using regular expressions. Adding fnmatch to flua increases the amd64
binary by less than 1 KB.

Approved by:	markj
MFC after:	3 days
Differential Revision:	https://reviews.freebsd.org/D46849
This commit is contained in:
Stefan Eßer 2024-10-28 16:22:08 +01:00
parent b74aaa1a21
commit f35ccf46c7
3 changed files with 43 additions and 0 deletions

View File

@ -57,6 +57,7 @@ static const luaL_Reg loadedlibs[] = {
#endif
/* FreeBSD Extensions */
{"lfs", luaopen_lfs},
{"posix.fnmatch", luaopen_posix_fnmatch},
{"posix.libgen", luaopen_posix_libgen},
{"posix.stdlib", luaopen_posix_stdlib},
{"posix.sys.stat", luaopen_posix_sys_stat},

View File

@ -9,6 +9,7 @@
#include <sys/wait.h>
#include <errno.h>
#include <fnmatch.h>
#include <grp.h>
#include <libgen.h>
#include <pwd.h>
@ -164,6 +165,23 @@ err:
}
static int
lua_fnmatch(lua_State *L)
{
const char *pattern, *string;
int flags, n;
n = lua_gettop(L);
luaL_argcheck(L, n == 2 || n == 3, 4, "need 2 or 3 arguments");
pattern = luaL_checkstring(L, 1);
string = luaL_checkstring(L, 2);
flags = luaL_optinteger(L, 3, 0);
lua_pushinteger(L, fnmatch(pattern, string, flags));
return (1);
}
static int
lua_uname(lua_State *L)
{
@ -462,6 +480,11 @@ static const struct luaL_Reg stdliblib[] = {
{ NULL, NULL },
};
static const struct luaL_Reg fnmatchlib[] = {
REG_SIMPLE(fnmatch),
{ NULL, NULL },
};
static const struct luaL_Reg sys_statlib[] = {
REG_SIMPLE(chmod),
{ NULL, NULL },
@ -506,6 +529,24 @@ luaopen_posix_stdlib(lua_State *L)
return (1);
}
int
luaopen_posix_fnmatch(lua_State *L)
{
luaL_newlib(L, fnmatchlib);
#define setkv(f) do { \
lua_pushinteger(L, f); \
lua_setfield(L, -2, #f); \
} while (0)
setkv(FNM_PATHNAME);
setkv(FNM_NOESCAPE);
setkv(FNM_NOMATCH);
setkv(FNM_PERIOD);
#undef setkv
return 1;
}
int
luaopen_posix_sys_stat(lua_State *L)
{

View File

@ -7,6 +7,7 @@
#include <lua.h>
int luaopen_posix_fnmatch(lua_State *L);
int luaopen_posix_libgen(lua_State *L);
int luaopen_posix_stdlib(lua_State *L);
int luaopen_posix_sys_stat(lua_State *L);