#include "pmake.h" #ifdef _WIN32 #include #else #include #endif static duk_ret_t js_fs_glob(duk_context* self) { int top = duk_get_top(self); int i; int arr = duk_push_array(self); int c = 0; for(i = 0; i < top; i++) { #ifdef _WIN32 WIN32_FIND_DATA ffd; HANDLE h; const char* p = duk_to_string(self, i); if((h = FindFirstFile(p, &ffd)) != INVALID_HANDLE_VALUE) { do { char* s = malloc(strlen(p) + 1 + strlen(ffd.cFileName) + 1); char* l; strcpy(s, p); if((l = strchr(s, '*')) != NULL) { l[0] = 0; } if(s[strlen(s) - 1] == '/' || s[strlen(s) - 1] == '\\') { } else if(strchr(p, '/') != NULL) { strcat(s, "/"); } else { strcat(s, "\\"); } strcat(s, ffd.cFileName); duk_push_string(self, s); duk_put_prop_index(self, arr, c); c++; free(s); } while(FindNextFile(h, &ffd) != 0); FindClose(h); } #else glob_t g; if(glob(duk_to_string(self, i), 0, NULL, &g) == 0) { int j; for(j = 0; j < g.gl_matchc; j++) { duk_push_string(self, g.gl_pathv[j]); duk_put_prop_index(self, arr, c); c++; } globfree(&g); } #endif } return 1; } static duk_ret_t js_fs_open(duk_context* self) { const char* path = duk_to_string(self, 0); const char* mode = duk_to_string(self, 1); FILE* f = fopen(path, mode); if(f == NULL) return 0; duk_push_pointer(self, f); return 1; } static duk_ret_t js_fs_write(duk_context* self) { FILE* f = duk_to_pointer(self, 0); const char* str = duk_to_string(self, 1); fwrite(str, 1, strlen(str), f); return 0; } static duk_ret_t js_fs_close(duk_context* self) { FILE* f = duk_to_pointer(self, 0); fclose(f); return 0; } static duk_ret_t js_fs_cwd(duk_context* self) { char path[1024]; getcwd(path, 1024); duk_push_string(self, path); return 1; } void js_fs_init(void) { int obj; obj = duk_push_object(js_ctx); duk_push_c_function(js_ctx, js_fs_glob, DUK_VARARGS); duk_put_prop_string(js_ctx, obj, "glob"); duk_push_c_function(js_ctx, js_fs_open, 2); duk_put_prop_string(js_ctx, obj, "open"); duk_push_c_function(js_ctx, js_fs_write, 2); duk_put_prop_string(js_ctx, obj, "write"); duk_push_c_function(js_ctx, js_fs_close, 1); duk_put_prop_string(js_ctx, obj, "close"); duk_push_c_function(js_ctx, js_fs_cwd, 0); duk_put_prop_string(js_ctx, obj, "cwd"); duk_put_prop_string(js_ctx, 0, "fs"); }