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#include "toys.h"
41
42
43int do_test(char **args, int *count)
44{
45 char c, *s;
46 int i;
47
48 if (*count>=3) {
49 *count = 3;
50 char *s = args[1], *ss = "eqnegtgeltle";
51 if (!strcmp(s, "=") || !strcmp(s, "==")) return !strcmp(args[0], args[2]);
52 if (!strcmp(s, "!=")) return strcmp(args[0], args[2]);
53 if (*s=='-' && strlen(s)==3 && (s = strstr(ss, s+1)) && !((i = s-ss)&1)) {
54 long long a = atolx(args[0]), b = atolx(args[2]);
55
56 if (!i) return a == b;
57 if (i==2) return a != b;
58 if (i==4) return a > b;
59 if (i==6) return a >= b;
60 if (i==8) return a < b;
61 if (i==10) return a<= b;
62 }
63 }
64 s = *args;
65 if (*count>=2 && *s == '-' && s[1] && !s[2]) {
66 *count = 2;
67 c = s[1];
68 if (-1 != (i = stridx("hLbcdefgpSusxwr", c))) {
69 struct stat st;
70
71
72 if (-1 == ((i<2) ? lstat : stat)(args[1], &st)) return 0;
73 if (i>=12) return !!(st.st_mode&(0x111<<(i-12)));
74 if (c == 's') return !!st.st_size;
75
76
77 if ((i = (unsigned short []){80,80,48,16,32,0,64,2,8,96,4}[i]<<9)>=4096)
78 return (st.st_mode&S_IFMT) == i;
79 else return (st.st_mode & i) == i;
80 } else if (c == 'z') return !*args[1];
81 else if (c == 'n') return *args[1];
82 else if (c == 't') return isatty(atolx(args[1]));
83 }
84 return *count = 0;
85}
86
87#define NOT 1
88#define AND 2
89#define OR 4
90void test_main(void)
91{
92 char *s;
93 int pos, paren, pstack, result = 0;
94
95 toys.exitval = 2;
96 if (!strcmp("[", toys.which->name))
97 if (!toys.optc || strcmp("]", toys.optargs[--toys.optc]))
98 error_exit("Missing ']'");
99
100
101 if (toys.optc) for (pos = paren = pstack = 0; ; pos++) {
102 int len = toys.optc-pos;
103
104 if (!toys.optargs[pos]) perror_exit("need arg @%d", pos);
105
106
107 result = do_test(toys.optargs+pos, &len);
108 pos += len;
109
110 if (!len) {
111 if (toys.optargs[pos+1]) {
112 if (!strcmp("!", toys.optargs[pos])) {
113 pstack ^= NOT;
114 continue;
115 }
116 if (!strcmp("(", toys.optargs[pos])) {
117 if (++paren>9) perror_exit("bad (");
118 pstack <<= 3;
119 continue;
120 }
121 }
122 result = *toys.optargs[pos++];
123 }
124 s = toys.optargs[pos];
125 for (;;) {
126
127
128 if (pstack&NOT) result = !result;
129 pstack &= ~NOT;
130 if (pstack&OR) result = 1;
131 else if (pstack&AND) result = 0;
132
133
134 if (!paren || !s || strcmp(")", s)) break;
135 paren--;
136 pstack >>= 3;
137 s = toys.optargs[++pos];
138 }
139
140
141 if (!s) {
142 if (paren) perror_exit("need )");
143 break;
144 }
145
146
147
148 if (!strcmp("-a", s)) {
149 if (!result) pstack |= AND;
150 } else if (!strcmp("-o", s)) {
151
152 pstack &=~AND;
153 if (result) pstack |= OR;
154 } else error_exit("too many arguments");
155 }
156
157
158 toys.exitval = !result;
159}
160