hook_init.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include <dirent.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <lub/string.h>
  5. #include "hook.h"
  6. static bool_t
  7. load_scripts(lua_State *L, char *path)
  8. {
  9. struct dirent *entry;
  10. DIR *dir = opendir(path);
  11. bool_t result = BOOL_FALSE;
  12. int res = 0;
  13. const char *ext_lua = ".lua";
  14. const char *ext_bin = ".bin";
  15. if (!dir) {
  16. printf("%s: Failed to open '%s' directory\n", __func__, path);
  17. return BOOL_FALSE;
  18. }
  19. for (entry = readdir(dir); entry; entry = readdir(dir)) {
  20. const char *extension = strrchr(entry->d_name, '.');
  21. /* check the filename */
  22. if ((extension) &&
  23. ((!strcmp(ext_lua, extension)) ||
  24. (!strcmp(ext_bin, extension)))) {
  25. char *filename = NULL;
  26. lub_string_cat(&filename, path);
  27. lub_string_cat(&filename, "/");
  28. lub_string_cat(&filename, entry->d_name);
  29. result = BOOL_FALSE;
  30. if ((res = luaL_loadfile(L, filename))) {
  31. l_print_error(L, __func__, "load", res);
  32. } else if ((res = lua_pcall(L, 0, 0, 0))) {
  33. l_print_error(L, __func__, "exec", res);
  34. } else
  35. result = BOOL_TRUE;
  36. lub_string_free(filename);
  37. /* Shouldn't happen, but we can't be too sure ;-) */
  38. while(lua_gettop(L))
  39. lua_pop(L, 1);
  40. if (!result)
  41. break;
  42. }
  43. }
  44. closedir(dir);
  45. return result;
  46. }
  47. CLISH_HOOK_INIT(clish_plugin_hook_init)
  48. {
  49. clish_context_t *context = (clish_context_t *) clish_context;
  50. clish_shell_t *shell = (clish_shell_t *) context->shell;
  51. lua_State *L = NULL;
  52. char *scripts_path = getenv("CLISH_SCRIPTS_PATH");
  53. if (!scripts_path)
  54. if(!(scripts_path = getenv("CLISH_PATH"))) {
  55. printf("%s: Lua scripts dir not specified\n", __func__);
  56. return (-1);
  57. }
  58. if (!(L = luaL_newstate())) {
  59. printf("%s: Failed to instantiate Lua interpreter\n", __func__);
  60. return (-1);
  61. }
  62. luaL_openlibs(L);
  63. if (!load_scripts(L, scripts_path)) {
  64. return (-1);
  65. }
  66. clish_shell__set_udata(shell, LUA_UDATA, L);
  67. lua_pushlightuserdata(L, shell);
  68. lua_setglobal(L, "clish_shell");
  69. return (0);
  70. }