-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathenvini.c
100 lines (88 loc) · 2.2 KB
/
envini.c
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
#include <unistd.h>
#include "byte.h"
#include "open.h"
#include "error.h"
#include "direntry.h"
#include "stralloc.h"
#include "openreadclose.h"
#include "strerr.h"
#include "pathexec.h"
#include "sgetopt.h"
#define FATAL "envini: fatal: "
void die_usage(void)
{
strerr_die1x(111,"envini: usage: envini [ -p prefix ] inifile child");
}
void nomem(void)
{
strerr_die2x(111,FATAL,"out of memory");
}
static stralloc sa;
static stralloc name;
static stralloc section;
static stralloc value;
const char *prefix = "";
static int is_space(int ch)
{
return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r';
}
static void parse(void)
{
int start;
int end;
int nl;
int i;
for (start = 0; start < sa.len; start = nl + 1) {
nl = start + byte_chr(sa.s+start,sa.len-start,'\n');
end = nl;
while (end > start && is_space(sa.s[end-1]))
--end;
while (end > start && is_space(sa.s[start]))
++start;
if (end > start) {
if (sa.s[start] == '[' && sa.s[end-1] == ']') {
if (!stralloc_copyb(§ion,sa.s+start+1,end-start-2)) nomem();
if (!stralloc_append(§ion,'_')) nomem();
}
else if (sa.s[start] == ';')
;
else {
i = start;
while (i < end && sa.s[i] != '=' && !is_space(sa.s[i]))
++i;
if (!stralloc_copys(&name,prefix)) nomem();
if (!stralloc_cat(&name,§ion)) nomem();
if (!stralloc_catb(&name,sa.s+start,i-start)) nomem();
if (!stralloc_0(&name)) nomem();
while (i < end && is_space(sa.s[i]))
++i;
if (i >= end || sa.s[i++] != '=')
continue; /* Ignore misformatted lines */
while (i < end && is_space(sa.s[i]))
++i;
if (!stralloc_copyb(&value,sa.s+i,end-i)) nomem();
if (!stralloc_0(&value)) nomem();
if (!pathexec_env(name.s,value.s)) nomem();
}
}
}
}
int main(int argc,const char *const *argv)
{
const char *fn;
int opt;
while ((opt = getopt(argc,argv,"p:")) != opteof)
switch (opt) {
case 'p': prefix = optarg; break;
default: die_usage();
}
argv += optind;
if (!*argv) die_usage();
fn = *argv;
if (!*++argv) die_usage();
if (openreadclose(fn,&sa,1024) == -1)
strerr_die3sys(111,FATAL,"unable to read ",fn);
parse();
pathexec(argv);
strerr_die3sys(111,FATAL,"unable to run ",*argv);
}