/* * src/builtin.c * * HUSH builtin commands module * CISC 301 -- Operating Systems, Project 2 * * Copyright (C) 2025 Douglas B. Rumbaugh * * Distributed under the Modified BSD License * */ #include "builtin.h" #include "variables.h" #include 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; }