builtins.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <limits.h>
  6. #ifdef __linux__
  7. #include <linux/limits.h>
  8. #endif
  9. #include "reporting.h"
  10. #include "region.h"
  11. #include "stringport.h"
  12. #include "parser.h"
  13. #include "interpreter.h"
  14. #include "builtins.h"
  15. char cwd[PATH_MAX];
  16. int perform_builtin(struct AST *n)
  17. {
  18. if (n->type == NODE_COMMAND && n->node.tokens[0]) {
  19. if (!strcmp("cd", n->node.tokens[0]))
  20. builtin_cd(n->node.tokens);
  21. else if (!strcmp("set", n->node.tokens[0]))
  22. builtin_set(n->node.tokens);
  23. else if (!strcmp("unset", n->node.tokens[0]))
  24. builtin_unset(n->node.tokens);
  25. else if (!strcmp("source", n->node.tokens[0]))
  26. builtin_source(n->node.tokens);
  27. else return 0;
  28. return 1;
  29. }
  30. return 0;
  31. }
  32. void builtin_cd(char **args)
  33. {
  34. char *dir;
  35. if (!(dir = args[1])) {
  36. if (!(dir = getenv("HOME"))) {
  37. report("invalid $HOME\n");
  38. return;
  39. }
  40. }
  41. if (chdir(dir)) {
  42. report("could not change directory to [%s]\n", dir);
  43. }
  44. else {
  45. getcwd(cwd, PATH_MAX);
  46. setenv("PWD", cwd, 1);
  47. }
  48. }
  49. void builtin_set(char **argv) {
  50. if (argv[1] && argv[2])
  51. setenv(argv[1], argv[2], INT_MAX);
  52. else
  53. report("set requires two arguments\n");
  54. }
  55. void builtin_unset(char **argv) {
  56. if (argv[1])
  57. unsetenv(argv[1]);
  58. else
  59. report("unset requires an argument\n");
  60. }
  61. void builtin_source(char **argv) {
  62. FILE *f;
  63. int mode;
  64. if (!argv[1]) {
  65. report("source requires an argument\n");
  66. }
  67. else if (!(f = fopen(argv[1], "r"))) {
  68. report("source open() failed\n");
  69. return;
  70. }
  71. mode = interactive_mode;
  72. interactive_mode = 0;
  73. loop(f);
  74. interactive_mode = mode;
  75. }