aboutsummaryrefslogtreecommitdiff
path: root/src/main.c
blob: 7e823365fd181273226ec671220451676daaf4c9 (plain) (blame)
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
// Copyright (c) 2024, Marvin Borner <dev@marvinborner.de>
// SPDX-License-Identifier: MIT

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

#include <target.h>
#include <term.h>
#include <log.h>
#include <parse.h>

// automatically generated using gengetopt
#include "cmdline.h"

#define BUF_SIZE 1024
static char *read_stdin(void)
{
	debug("reading from stdin\n");
	freopen(NULL, "rb", stdin);
	size_t size = 1;
	char *string = malloc(sizeof(char) * BUF_SIZE);
	if (!string)
		fatal("out of memory!\n");

	char ch;
	while (fread(&ch, sizeof(char), 1, stdin) == 1) {
		if (size % BUF_SIZE == 0) {
			string = realloc(string,
					 sizeof(char) * (size + BUF_SIZE));
			if (!string)
				fatal("out of memory!\n");
		}
		string[size - 1] = ch;
		size++;
	}
	string[size - 1] = '\0';

	if (ferror(stdin)) {
		free(string);
		fatal("can't read from stdin\n");
	}
	return string;
}

static char *read_file(FILE *f)
{
	fseek(f, 0, SEEK_END);
	long fsize = ftell(f);
	fseek(f, 0, SEEK_SET);

	char *string = malloc(fsize + 1);
	if (!string)
		fatal("out of memory!\n");
	int ret = fread(string, fsize, 1, f);

	if (ret != 1) {
		free(string);
		fatal("can't read file: %s\n", strerror(errno));
	}

	string[fsize] = 0;
	return string;
}

static char *read_path(const char *path)
{
	debug("reading from %s\n", path);
	FILE *f = fopen(path, "rb");
	if (!f)
		fatal("can't open file %s: %s\n", path, strerror(errno));
	char *string = read_file(f);
	fclose(f);
	return string;
}

int main(int argc, char **argv)
{
	struct gengetopt_args_info args;
	if (cmdline_parser(argc, argv, &args))
		exit(1);

	debug_enable(args.verbose_flag);

	char *input;
	if (args.input_arg[0] == '-') {
		input = read_stdin();
	} else {
		input = read_path(args.input_arg);
	}

	if (!input)
		return 1;

	if (args.target_arg) {
		struct bloc_parsed *bloc = parse_bloc(input);

		FILE *file =
			args.output_arg ? fopen(args.output_arg, "wb") : stdout;
		exec_target(args.target_arg, bloc, file);
		fclose(file);

		free(input);
		free_bloc(bloc);
		return 0;
	}

	fatal("invalid options: use --help for information\n");
	return 1;
}