aboutsummaryrefslogtreecommitdiff
path: root/src/shell.c
blob: 5fb18bc0d2da369acb6db6ccc2d1d9b0219c9a0d (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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include "shell.h"

static void             cleanwhitespaces(char *line);
static int              parseline(char *line, char **v);

static void
cleanwhitespaces(char *line)
{
	char *i;

	for (i = line; *i != 0; i++)
		if (*i == '\t' || *i == '\n')
			*i = ' ';
}

/* This function assumes that **v is large enough */
static int
parseline(char *line, char **v)
{
	char *t;
	int n = 0;
	
	cleanwhitespaces(line);

	for (t = strtok(line, " "); t != NULL; t = strtok(NULL, " "))
		strcpy(v[n++], t);

	return n;
}

void
exec_args(int c, char **v)
{
	int i;
	Command *cmd = NULL;
	CommandArgs *args;

	for (i = 0; i < NCOMMANDS; i++)
		if (commands[i] != NULL && !strcmp(v[0], commands[i]->name))
			cmd = commands[i];

	if (cmd == NULL) {
		fprintf(stderr, "%s: command not found\n", v[0]);
		return;
	}

	args = cmd->parse_args(c-1, &v[1]);
	if (!args->success) {
		fprintf(stderr, "usage: %s\n", cmd->usage);
		return;
	}

	cmd->exec(args);
	free_args(args);
}

void
launch(bool batchmode)
{
	int i, shell_argc;
	char line[MAXLINELEN], **shell_argv;

	shell_argv = malloc(MAXNTOKENS * sizeof(char *));
	for (i = 0; i < MAXNTOKENS; i++)
		shell_argv[i] = malloc((MAXTOKENLEN+1) * sizeof(char));

	if (!batchmode) {
		fprintf(stderr, "Welcome to Nissy "VERSION".\n"
				"Type \"commands\" for a list of commands.\n");
	}

	while (true) {
		if (!batchmode) {
			fprintf(stdout, "nissy-# ");
		}

		if (fgets(line, MAXLINELEN, stdin) == NULL)
			break;

		if (batchmode) {
			printf(">>>\n"
			       ">>> Executing command: %s"
			       ">>>\n", line);
		}

		shell_argc = parseline(line, shell_argv);

		if (shell_argc > 0)
			exec_args(shell_argc, shell_argv);
	}

	for (i = 0; i < MAXNTOKENS; i++)
		free(shell_argv[i]);
	free(shell_argv);
}

int
main(int argc, char *argv[])
{
	if (argc > 1) {
		if (!strcmp(argv[1], "-b")) {
			launch(true);
		} else {
			exec_args(argc-1, &argv[1]);
		}
	} else {
		launch(false);
	}

	return 0;
}

Generated with cgit - Back to sebastiano.tronto.net