~emersion/mrsh

ref: 9371d6094e78645f0ec0c85b6cd5b6c8ec9638fc mrsh/main.c -rw-r--r-- 1.4 KiB
9371d609Drew DeVault Implement times, : builtins 3 years ago
                                                                                
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
#define _POSIX_C_SOURCE 200809L
#include <assert.h>
#include <errno.h>
#include <mrsh/ast.h>
#include <mrsh/parser.h>
#include <mrsh/shell.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
	bool noexec = false;

	struct mrsh_state state = {0};
	mrsh_state_init(&state);

	FILE *input = stdin;

	int opt;
	while ((opt = getopt(argc, argv, "c:ns")) != -1) {
		switch (opt) {
		case 'n':
			noexec = true;
			break;
		case 'c':
			input = fmemopen(optarg, strlen(optarg), "r");
			if (!input) {
				fprintf(stderr, "fmemopen failed: %s", strerror(errno));
				return EXIT_FAILURE;
			}
			break;
		case 's':
			input = stdin;
			break;
		default:
			return EXIT_FAILURE;
		}
	}

	if (optind < argc) {
		input = fopen(argv[optind], "r");
		if (!input) {
			fprintf(stderr, "could not open %s for reading: %s",
					argv[optind], strerror(errno));
			return EXIT_FAILURE;
		}
		assert(optind + 1 >= argc && "additional args not yet supported");
	}

	struct mrsh_parser *parser = mrsh_parser_create(input);
	while (state.exit == -1) {
		struct mrsh_program *prog = mrsh_parse_line(parser);
		if (prog == NULL) {
			state.exit = EXIT_SUCCESS;
			break;
		}
		if (noexec) {
			mrsh_program_print(prog);
		} else {
			mrsh_run_program(&state, prog);
		}
		mrsh_program_destroy(prog);
	}

	mrsh_parser_destroy(parser);
	fclose(input);
	return state.exit;
}