aboutsummaryrefslogtreecommitdiff
path: root/smash/main.c
blob: 4d81f18b81cd412227ef8bb08a20c5ad1581565f (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
#include "exec.h"
#include "comment.h"

#include "../lib/sys/io.h"
#include "../lib/cstr/cstr.h"
#include "../lib/sys/dup2.h"
#include "../lib/sys/exit.h"

#include "../lib/io/io.h"
#include "../lib/sys/errno.h"

#define BUFSIZ 16384

char buf[BUFSIZ] = {0};
int getline(int fd, char *linebuf)
{
	u64 size = 0;
	char *line = buf;

	while (*line && *line != '\n') line++;

	if (!*line) {
		u64 s = cstr_length(buf);
		s = read(fd, buf + s, BUFSIZ - s - 1);

		if (s == 0) {
			return -1;
		}

		buf[s] = 0;
		while (*line && *line != '\n') line++;

		if (!*line) {
			wf(STDERR_FD, "line too long to handle, exiting.\n");
			exit(-1);
		}
	}

	*line = 0;
	++line;

	size = cstr_length(buf);
	for (int i = 0; buf[i]; ++i) linebuf[i] = buf[i];
	linebuf[size] = 0;

	buf[0] = 0;
	for (int i = 0; *line; ++i) {
		buf[i] = *line;
		buf[i + 1] = 0;
		++line;
	}

	return size;
}

int main(int argc, char *argv[], char *envp[])
{
	char prompt[] = "$ ";
	i64 line_length;
	int fd = STDIN_FD;
	char linebuf[BUFSIZ];

	if (argc == 2) {
		fd = open(argv[1], OPEN_READ_ONLY, 0);

		if (fd < 0) {
			wff(STDERR_FD, "smash: %s\n", errstr[-fd]);
			return -1;
		}
	}

	while (1) {
		if (fd == STDIN_FD)
			wstd(prompt);

		line_length = getline(fd, linebuf);

		if (line_length == -1) {
			break;
		}

		remove_comment(linebuf);
		line_length = cstr_length(linebuf);

		if (line_length > 0) {
			exec(linebuf);
		}
	}

	if (fd != STDOUT_FD)
		close(fd);
}