about summary refs log tree commit diff
path: root/atxec.c
blob: b40fd745eb12017d44a742278ff4fd8cdc0d81ed (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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
/*
 * atxec - run command expanding arguments from file or environment
 *
 * To the extent possible under law, Leah Neukirchen <leah@vuxu.org>
 * has waived all copyright and related or neighboring rights to this work.
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

// '''' => '

// # line comment (space or beginning of line before #)
// @file
// @$ENV
// @@argwithone@
// fallbacks?

#include <sys/stat.h>

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define MAXARGS 2048
int narg;
char *args[MAXARGS];

static void
push_arg(char *s)
{
	if (narg >= MAXARGS) {
		fprintf(stderr, "atxec: too many arguments\n");
		exit(111);
	}

	args[narg++] = s;
}

void
arg_splice(char *s)
{
	char *beg;
	char *t;

	if (!s)
		return;

	while (1) {
		while (isspace(*s) || *s == '#')
			if (*s == '#')  /* skip line comment */
				while (*s && *s != '\n')
					s++;
			else
				s++;

		if (!*s)
			break;

		if (*s == '\'') {  /* rc-quoted string */
			s++;
			beg = t = s;

			while (*s)
				if (*s == '\'') {
					*t++ = *s++;
					if (*s == '\'') {
						s++;
					} else {
						*--t = 0;
						if (!*s)
							beg--;
						break;
					}
				} else {
					*t++ = *s++;
				}
		} else {  /* bareword, may contain # without whitespace */
			beg = s;
			while (*s && !isspace(*s))
				s++;
		}

		push_arg(beg);

		if (*s) {
			*s = 0;
			s++;
		} 
	}
}

void
file_splice(char *file)
{
	struct stat st;
	char *s;

	FILE *f = fopen(file, "rb");
	if (!f)
		return;   /* ignore file does not exist */

	fstat(fileno(f), &st);

	s = calloc(1, st.st_size + 1);
	if (!s) {
		fclose(f);
		return;
	}
	fread(s, 1, st.st_size, f);
	fclose(f);

	arg_splice(s);

	/* leak string, args points into it! */
}

int
main(int argc, char *argv[])
{
	if (argc == 1) {
		fprintf(stderr, "usage\n");
		return 1;
	}

	for (int i = 1; i < argc; i++)
		if (argv[i][0] == '@') {
			if (argv[i][1] == '@')
				push_arg(argv[i]+1);
			if (argv[i][1] == '$')
				arg_splice(getenv(argv[i]+2));
			else
				file_splice(argv[i]+1);
		} else {
			push_arg(argv[i]);
		}

	execvp(args[0], args);

	perror("argsplice: exec");
	return 111;
}