summaryrefslogtreecommitdiff
path: root/tools/scan_includes.c
blob: b6fcca03a5f14c4f8b98e81ad0394c229725cd1e (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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <getopt.h>

void usage(void) {
	printf("Usage: scan_includes [-h] [-s] filename\n"
	       "-h, --help\n"
	       "    Print usage and exit\n"
	       "-s, --strict\n"
	       "    Fail if a file cannot be read\n");
}

struct Options {
	bool help;
	bool strict;
};

struct Options Options = {0};


void scan_file(char* filename) {
	FILE* f;
	long size;
	char* orig;
	char* buffer;
	char* include;
	int length;

	f = fopen(filename, "r");
	if (!f) {
		if (Options.strict) {
			fprintf(stderr, "Could not open file: '%s'\n", filename);
			exit(1);
		} else {
			return;
		}
	}

	fseek(f, 0, SEEK_END);
	size = ftell(f);
	rewind(f);

	buffer = malloc(size + 1);
	orig = buffer;
	fread(buffer, 1, size, f);
	buffer[size] = '\0';
	fclose(f);

	for (; buffer && (buffer - orig < size); buffer++) {
		if (buffer[0] == ';') {
			buffer = strchr(buffer, '\n');
			if (!buffer) {
				fprintf(stderr, "%s: no newline at end of file\n", filename);
				break;
			}
			continue;
		}
		bool is_include = false;
		bool is_incbin = false;
		if ((strncmp(buffer, "INCBIN", 6) == 0) || (strncmp(buffer, "incbin", 6) == 0)) {
			is_incbin = true;
		} else if ((strncmp(buffer, "INCLUDE", 7) == 0) || (strncmp(buffer, "include", 7) == 0)) {
			is_include = true;
		}
		if (is_incbin || is_include) {
			buffer = strchr(buffer, '"') + 1;
			if (!buffer) {
				break;
			}
			length = strcspn(buffer, "\"");
			include = malloc(length + 1);
			strncpy(include, buffer, length);
			include[length] = '\0';
			printf("%s ", include);
			if (is_include) {
				scan_file(include);
			}
			free(include);
		}
	}

	free(orig);
}

void get_args(int argc, char *argv[]) {
	while (1) {
		struct option long_options[] = {
			{"strict", no_argument, 0, 's'},
			{"help", no_argument, 0, 'h'},
			{0}
		};
		int i = 0;
		int opt = getopt_long(argc, argv, "sh", long_options, &i);

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

		switch (opt) {
		case 's':
			Options.strict = true;
			break;
		case 'h':
			Options.help = true;
			break;
		default:
			usage();
			exit(1);
			break;
		}
	}
}

int main(int argc, char* argv[]) {
	get_args(argc, argv);
	argc -= optind;
	argv += optind;
	if (Options.help) {
		usage();
		return 0;
	}
	if (argc < 1) {
		usage();
		exit(1);
	}
	scan_file(argv[0]);
	return 0;
}