aboutsummaryrefslogtreecommitdiff
path: root/src/shell.c
blob: 6e67e0ad1c8f2bd00239c9ad7f73e3136985111d (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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#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;
	char line[MAXLINELEN];
	Command *cmd = NULL;
	CommandArgs *args;
	Alg *scramble;

	for (i = 0; commands[i] != NULL; i++)
		if (!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;
	}

	if (args->scrstdin) {
		while (true) {
			if (fgets(line, MAXLINELEN, stdin) == NULL) {
				clearerr(stdin);
				break;
			}
			
			scramble = new_alg(line);

			printf(">>> Line: %s", line);

			if (scramble != NULL && scramble->len > 0) {
				args->scramble = scramble;
				cmd->exec(args);
				free_alg(scramble);
				args->scramble = NULL;
			} 
		}
	} else {
		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