-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfs.cpp
92 lines (75 loc) · 2.32 KB
/
fs.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include "xlua.h"
#include <filesystem>
#include <cstdlib>
#define luaFS "fs"
typedef int (*lua_CFunction) (lua_State* L);
namespace fs = std::filesystem;
static int is_directory(lua_State* L) { // is_directory(path: string) -> bool
const char* path = luaL_checkstring(L, 1);
lua_pushboolean(L, fs::is_directory(path));
return 1;
}
static int is_file(lua_State* L) { // is_file(path: string) -> bool
const char* path = luaL_checkstring(L, 1);
lua_pushboolean(L, fs::is_regular_file(path));
return 1;
}
static int file_exists(lua_State* L) { // file_exists(path: string) -> bool
const char* path = luaL_checkstring(L, 1);
struct stat buffer;
lua_pushboolean(L,stat(path, &buffer) == 0);
return 1;
}
static int listdir(lua_State* L) { // listdir(path: string, type: integer) -> table[integer, string]
const char* dir_path = luaL_checkstring(L, 1);
int type = 0;
if (lua_gettop(L) == 2) {
type = luaL_checknumber(L, 2);
}
int index = 1; // start from 1
if (!(fs::is_directory(dir_path))) {
return luaL_error(L, "expected a vaild dir path (got %s)", dir_path);
}
lua_newtable(L);
for (const auto& entry : fs::directory_iterator(dir_path)) {
if (type == 1 && !(fs::is_directory(entry))) {
continue;
}
else if (type == 2 && !(fs::is_regular_file(entry))) {
continue;
}
lua_pushnumber(L, index); // push the index
lua_pushstring(L, entry.path().string().c_str()); // Push the entry path
lua_settable(L, -3); // set the entry in the table
index++;
}
return 1;
}
static int get_cwd(lua_State* L) { // get_cwd() -> string
lua_pushstring(L, fs::current_path().string().c_str());
return 1;
}
static inline void registerCfunction(lua_State* L, lua_CFunction func, const char* name, int stack = -2) {
int base = lua_gettop(L);
if (base <= 0)
return;
lua_pushcfunction(L, func);
lua_setfield(L, stack, name);
}
extern "C" __declspec(dllexport) int luaopen_fs (lua_State *L) {
lua_newtable(L);
lua_setglobal(L, luaFS);
lua_getglobal(L, luaFS);
registerCfunction(L, is_directory, "is_directory");
registerCfunction(L, is_file, "is_file");
registerCfunction(L, file_exists, "file_exists");
registerCfunction(L, listdir, "listdir");
// values
lua_pushnumber(L, 0);
lua_setfield(L, -2, "BOTH");
lua_pushnumber(L, 1);
lua_setfield(L, -2, "DIRS");
lua_pushnumber(L, 2);
lua_setfield(L, -2, "FILES");
return 0;
}