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

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

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

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

	init_arg_env(argc, (const char**)argv);

	if (argc > 1) {
		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 = get_next_line_from_fd(fd, linebuf);

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

		remove_comment(linebuf);
		line = new_line_and_replace_vars(linebuf, BUFSIZ);
		line_exec = setup_variable_line_context(line);
		line_length = cstr_length(line_exec);

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

		cleanup_variable_line_context();

		free(line);
	}

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