aboutsummaryrefslogtreecommitdiff
path: root/src/shell.c
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--src/shell.c93
1 files changed, 93 insertions, 0 deletions
diff --git a/src/shell.c b/src/shell.c
new file mode 100644
index 0000000..0880f8a
--- /dev/null
+++ b/src/shell.c
@@ -0,0 +1,93 @@
1#include "shell.h"
2
3static void cleanwhitespaces(char *line);
4static int parseline(char *line, char **v);
5
6static void
7cleanwhitespaces(char *line)
8{
9 char *i;
10
11 for (i = line; *i != 0; i++)
12 if (*i == '\t' || *i == '\n')
13 *i = ' ';
14}
15
16/* This function assumes that **v is large enough */
17static int
18parseline(char *line, char **v)
19{
20 char *t;
21 int n = 0;
22
23 cleanwhitespaces(line);
24
25 for (t = strtok(line, " "); t != NULL; t = strtok(NULL, " "))
26 strcpy(v[n++], t);
27
28 return n;
29}
30
31void
32exec_args(int c, char **v)
33{
34 int i;
35 Command *cmd = NULL;
36 CommandArgs *args;
37
38 for (i = 0; i < NCOMMANDS; i++)
39 if (commands[i] != NULL && !strcmp(v[0], commands[i]->name))
40 cmd = commands[i];
41
42 if (cmd == NULL) {
43 fprintf(stderr, "%s: command not found\n", v[0]);
44 return;
45 }
46
47 args = cmd->parse_args(c-1, &v[1]);
48 if (!args->success) {
49 fprintf(stderr, "usage: %s\n", cmd->usage);
50 return;
51 }
52
53 cmd->exec(args);
54 free_args(args);
55}
56
57void
58launch()
59{
60 int i, shell_argc;
61 char line[MAXLINELEN], **shell_argv;
62
63 shell_argv = malloc(MAXNTOKENS * sizeof(char *));
64 for (i = 0; i < MAXNTOKENS; i++)
65 shell_argv[i] = malloc((MAXTOKENLEN+1) * sizeof(char));
66
67 fprintf(stderr, "Welcome to Nissy "VERSION".\n");
68 fprintf(stderr, "Type 'help' for a list.\n");
69
70 while (true) {
71 fprintf(stderr, "nissy-# ");
72 if (fgets(line, MAXLINELEN, stdin) == NULL)
73 break;
74 shell_argc = parseline(line, shell_argv);
75 if (shell_argc > 0)
76 exec_args(shell_argc, shell_argv);
77 }
78
79 for (i = 0; i < MAXNTOKENS; i++)
80 free(shell_argv[i]);
81 free(shell_argv);
82}
83
84int
85main(int argc, char *argv[])
86{
87 if (argc > 1)
88 exec_args(argc-1, &argv[1]);
89 else
90 launch();
91
92 return 0;
93}

Generated with cgit - Back to sebastiano.tronto.net