aboutsummaryrefslogtreecommitdiffstats
path: root/src/builtin.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/builtin.c')
-rw-r--r--src/builtin.c75
1 files changed, 75 insertions, 0 deletions
diff --git a/src/builtin.c b/src/builtin.c
new file mode 100644
index 0000000..f22ce33
--- /dev/null
+++ b/src/builtin.c
@@ -0,0 +1,75 @@
+/*
+ *
+ */
+#include "builtin.h"
+#include "variables.h"
+#include <unistd.h>
+
+struct builtin {
+ char *name;
+ int (*builtin_func)(const char **);
+};
+
+static int builtin_cd(const char *args[]) {
+ const char *dir = (args[1]) ? args[1] : get_variable("$HOME");
+ int res = chdir(dir);
+
+ if (res != 0) {
+ perror("cd:");
+ return 0;
+ }
+
+ return 1;
+}
+
+static int builtin_export(const char *args[]) {
+ const char *key = args[1];
+
+ if (!key) {
+ fprintf(stderr, "export: no variable name specified\n");
+ return 0;
+ }
+
+ if (!promote_variable_to_env(key)) {
+ perror("export:");
+ return 0;
+ }
+
+ return 1;
+}
+
+static int builtin_pwd(const char *args[]) {
+ char buffer[PATH_MAX];
+ char *path = getcwd(buffer, PATH_MAX);
+ if (path) {
+ fprintf(stdout, "%s\n", path);
+ return 1;
+ }
+
+ perror("pwd:");
+ return 0;
+}
+
+static int builtin_exit(const char *args[]) { exit(EXIT_SUCCESS); }
+
+#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
+
+static struct builtin builtin_lookup[] = {
+ {.name = "cd", .builtin_func = builtin_cd},
+ {.name = "export", .builtin_func = builtin_export},
+ {.name = "pwd", .builtin_func = builtin_pwd},
+ {.name = "exit", .builtin_func = builtin_exit}};
+
+static const size_t BUILTIN_CNT = ARRAY_SIZE(builtin_lookup);
+
+bool run_builtin(command *cmd) {
+
+ for (size_t i = 0; i < BUILTIN_CNT; i++) {
+ if (!strcmp(cmd->command, builtin_lookup[i].name)) {
+ builtin_lookup[i].builtin_func(cmd->args);
+ return true;
+ }
+ }
+
+ return false;
+}