lazybox.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. #include <unistd.h>
  2. #include <dirent.h>
  3. #include <stdarg.h>
  4. #include <stdint.h>
  5. #include <stdio.h>
  6. #include <string.h>
  7. struct applet {
  8. const char* name;
  9. int (*func)(const char** args);
  10. };
  11. int lazybox_version(const char** _)
  12. {
  13. (void)_;
  14. printf("lazybox by greatbridf\n");
  15. return 0;
  16. }
  17. int pwd(const char** _)
  18. {
  19. (void)_;
  20. char buf[256];
  21. if (getcwd(buf, sizeof(buf)) == 0) {
  22. printf("cannot get cwd\n");
  23. return -1;
  24. }
  25. puts(buf);
  26. return 0;
  27. }
  28. int ls(const char** args)
  29. {
  30. const char* path = args[0];
  31. DIR* dir = NULL;
  32. if (path == NULL) {
  33. char buf[256];
  34. if (getcwd(buf, sizeof(buf)) == 0)
  35. return -1;
  36. dir = opendir(buf);
  37. } else {
  38. dir = opendir(args[0]);
  39. }
  40. if (!dir)
  41. return -1;
  42. struct dirent* dp = NULL;
  43. while ((dp = readdir(dir)) != NULL) {
  44. printf("%s ", dp->d_name);
  45. }
  46. printf("\n");
  47. return 0;
  48. }
  49. struct applet applets[] = {
  50. {
  51. "lazybox",
  52. lazybox_version,
  53. },
  54. {
  55. "pwd",
  56. pwd,
  57. },
  58. {
  59. "ls",
  60. ls,
  61. }
  62. };
  63. static inline int tolower(int c)
  64. {
  65. if (c >= 'A' && c <= 'Z')
  66. return c - 'A' + 'a';
  67. return c;
  68. }
  69. int strcmpi(const char* a, const char* b)
  70. {
  71. int ret = 0;
  72. while (*a && *b) {
  73. if (tolower(*a) != tolower(*b)) {
  74. ret = 1;
  75. break;
  76. }
  77. ++a, ++b;
  78. }
  79. if ((*a && !*b) || (*b && !*a)) {
  80. ret = 1;
  81. }
  82. return ret;
  83. }
  84. const char* find_file_name(const char* path)
  85. {
  86. const char* last = path + strlen(path);
  87. for (; last != path; --last) {
  88. if (*last == '/')
  89. break;
  90. }
  91. return last == path ? path : last + 1;
  92. }
  93. int parse_applet(const char* name)
  94. {
  95. if (!name)
  96. return -1;
  97. for (size_t i = 0; i < (sizeof(applets) / sizeof(struct applet)); ++i) {
  98. if (strcmpi(applets[i].name, name) == 0) {
  99. return i;
  100. }
  101. }
  102. return -1;
  103. }
  104. int main(int argc, const char** argv)
  105. {
  106. (void)argc;
  107. int offset = 0;
  108. const char* name = find_file_name(argv[offset++]);
  109. int type = -1;
  110. run:
  111. type = parse_applet(name);
  112. if (type == -1) {
  113. printf("applet not found: %s\n", name);
  114. return -1;
  115. }
  116. if (type == 0 && offset == 1 && argv[1]) {
  117. name = argv[offset++];
  118. goto run;
  119. }
  120. return applets[type].func(argv + offset);
  121. }