aboutsummaryrefslogtreecommitdiffstats
path: root/src/builtin.c
blob: f22ce33da64d6a6dbc7c1b8f98a6c889914299e6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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;
}