forked from opendlang/opend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdshell_prebuilt.d
340 lines (318 loc) · 8.99 KB
/
dshell_prebuilt.d
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
/**
A small library to help write D shell-like test scripts.
*/
module dshell_prebuilt;
public import core.stdc.stdlib : exit;
public import core.time;
public import core.thread;
public import std.meta;
public import std.exception;
public import std.array;
public import std.string;
public import std.format;
public import std.path;
public import std.file;
public import std.regex;
public import std.stdio;
public import std.process;
/**
Emulates bash environment variables. Variables set here will be availble for BASH-like expansion.
*/
struct Vars
{
private static __gshared string[string] map;
static void set(string name, string value)
in { assert(value !is null); } do
{
const expanded = shellExpand(value);
assert(expanded !is null, "codebug");
map[name] = expanded;
}
static string get(const(char)[] name)
{
auto result = map.get(cast(string)name, null);
if (result is null)
assert(0, "Unknown variable '" ~ name ~ "'");
return result;
}
static string opDispatch(string name)() { return get(name); }
static void opDispatch(string name)(string value) { set(name, value); }
}
private alias requiredEnvVars = AliasSeq!(
"MODEL", "RESULTS_DIR",
"EXE", "OBJ",
"DMD", "DFLAGS",
"OS", "SEP", "DSEP",
"BUILD"
);
private alias optionalEnvVars = AliasSeq!(
"CC", "PIC_FLAG"
);
private alias allVars = AliasSeq!(
requiredEnvVars,
optionalEnvVars,
"TEST_DIR", "TEST_NAME",
"RESULTS_TEST_DIR",
"OUTPUT_BASE", "EXTRA_FILES",
"LIBEXT", "SOEXT"
);
static foreach (var; allVars)
{
mixin(`string ` ~ var ~ `() { return Vars.` ~ var ~ `; }`);
}
/// called from the dshell module to initialize environment
void dshellPrebuiltInit(string testDir, string testName)
{
foreach (var; requiredEnvVars)
{
Vars.set(var, requireEnv(var));
}
foreach (var; optionalEnvVars)
{
Vars.set(var, environment.get(var, ""));
}
Vars.set("TEST_DIR", testDir);
Vars.set("TEST_NAME", testName);
// reference to the resulting test_dir folder, e.g .test_results/runnable
Vars.set("RESULTS_TEST_DIR", buildPath(RESULTS_DIR, TEST_DIR));
// reference to the resulting files without a suffix, e.g. test_results/runnable/test123import test);
Vars.set("OUTPUT_BASE", buildPath(RESULTS_TEST_DIR, TEST_NAME));
// reference to the extra files directory
Vars.set("EXTRA_FILES", buildPath(TEST_DIR, "extra-files"));
// reference to the imports directory
Vars.set("IMPORT_FILES", buildPath(TEST_DIR, "imports"));
version (Windows)
{
Vars.set("LIBEXT", ".lib");
Vars.set("SOEXT", ".dll");
}
else version (OSX)
{
Vars.set("LIBEXT", ".a");
Vars.set(`SOEXT`, `.dylib`);
}
else
{
Vars.set("LIBEXT", ".a");
Vars.set("SOEXT", ".so");
}
}
private string requireEnv(string name)
{
const result = environment.get(name, null);
if (result is null)
{
writefln("Error: missing required environment variable '%s'", name);
exit(1);
}
return result;
}
/// Exit code to return if the test is disabled for the current platform
enum DISABLED = 125;
/// Remove one or more files
void rm(scope const(char[])[] args...)
{
foreach (arg; args)
{
auto expanded = shellExpand(arg);
if (exists(expanded))
{
writeln("rm '", expanded, "'");
// Use loop to workaround issue in windows with removing
// executables after running then
for (int sleepMsecs = 10; ; sleepMsecs *= 2)
{
try {
std.file.remove(expanded);
break;
} catch (Exception e) {
if (sleepMsecs >= 3000)
throw e;
Thread.sleep(dur!"msecs"(sleepMsecs));
}
}
}
}
}
/// Make all parent directories needed to create the given `filename`
void mkdirFor(string filename)
{
auto dir = dirName(filename);
if (!exists(dir))
{
writefln("[INFO] mkdir -p '%s'", dir);
mkdirRecurse(dir);
}
}
/**
Run the given command. The `tryRun` variants return the exit code, whereas the `run` variants
will assert on a non-zero exit code.
*/
int tryRun(scope const(char[])[] args, File stdout = std.stdio.stdout,
File stderr = std.stdio.stderr, string[string] env = null)
{
std.stdio.stdout.write("[RUN]");
if (env)
{
foreach (pair; env.byKeyValue)
{
std.stdio.stdout.write(" ", pair.key, "=", pair.value);
}
}
std.stdio.write(" ", escapeShellCommand(args));
if (stdout != std.stdio.stdout)
{
std.stdio.stdout.write(" > ", stdout.name);
}
// "Commit" all output from the tester
std.stdio.stdout.writeln();
std.stdio.stdout.flush();
std.stdio.stderr.writeln();
std.stdio.stderr.flush();
auto proc = spawnProcess(args, stdin, stdout, stderr, env);
return wait(proc);
}
/// ditto
int tryRun(string cmd, File stdout = std.stdio.stdout,
File stderr = std.stdio.stderr, string[string] env = null)
{
return tryRun(parseCommand(cmd), stdout, stderr, env);
}
/// ditto
void run(scope const(char[])[] args, File stdout = std.stdio.stdout,
File stderr = std.stdio.stderr, string[string] env = null)
{
const exitCode = tryRun(args, stdout, stderr, env);
if (exitCode != 0)
{
writefln("Error: last command exited with code %s", exitCode);
assert(0, "last command failed");
}
}
/// ditto
void run(string cmd, File stdout = std.stdio.stdout,
File stderr = std.stdio.stderr, string[string] env = null)
{
// TODO: option to disable this?
if (SEP != "/")
cmd = cmd.replace("/", SEP);
run(parseCommand(cmd), stdout, stderr, env);
}
/**
Parse the given string `s` as a command. Performs BASH-like variable expansion.
*/
string[] parseCommand(string s)
{
auto rawArgs = s.split();
auto args = appender!(string[])();
foreach (rawArg; rawArgs)
{
const exp = shellExpand(rawArg);
if (exp.length)
args.put(exp);
}
return args.data;
}
/// Expand the given string using BASH-like variable expansion.
string shellExpand(const(char)[] s)
{
auto expanded = appender!(char[])();
for (size_t i = 0; i < s.length;)
{
if (s[i] != '$')
{
expanded.put(s[i]);
i++;
}
else
{
i++;
assert(i < s.length, "lone '$' at end of string");
auto start = i;
if (s[i] == '{')
{
start++;
for (;;)
{
i++;
assert(i < s.length, "unterminated ${...");
if (s[i] == '}') break;
}
expanded.put(Vars.get(s[start .. i]));
i++;
}
else
{
assert(validVarChar(s[i]), "invalid sequence $'" ~ s[i]);
for (;;)
{
i++;
if (i >= s.length || !validVarChar(s[i]))
break;
}
expanded.put(Vars.get(s[start .. i]));
}
}
}
auto result = expanded.data;
return (result is null) ? "" : result.assumeUnique;
}
// [a-zA-Z0-9_]
private bool validVarChar(const char c)
{
import std.ascii : isAlphaNum;
return c.isAlphaNum || c == '_';
}
struct GrepResult
{
string[] matches;
void enforceMatches(string message)
{
if (matches.length == 0)
{
assert(0, message);
}
}
}
/**
grep the given `file` for the given `pattern`.
*/
GrepResult grep(string file, string pattern)
{
const patternExpanded = shellExpand(pattern);
const fileExpanded = shellExpand(file);
writefln("[GREP] file='%s' pattern='%s'", fileExpanded, patternExpanded);
return grepLines(File(fileExpanded, "r").byLine, patternExpanded);
}
/// ditto
GrepResult grep(GrepResult lastResult, string pattern)
{
auto patternExpanded = shellExpand(pattern);
writefln("[GREP] (%s lines from last grep) pattern='%s'", lastResult.matches.length, patternExpanded);
return grepLines(lastResult.matches, patternExpanded);
}
private GrepResult grepLines(T)(T lineRange, string finalPattern)
{
auto matches = appender!(string[])();
foreach(line; lineRange)
{
if (matchFirst(line, finalPattern))
{
static if (is(typeof(lineRange.front()) == string))
matches.put(line);
else
matches.put(line.idup);
}
}
writefln("[GREP] matched %s lines", matches.data.length);
return GrepResult(matches.data);
}
/**
remove \r and the compiler debug header from the given string.
*/
string filterCompilerOutput(string output)
{
output = std.string.replace(output, "\r", "");
output = std.regex.replaceAll(output, regex(`^DMD v2\.[0-9]+.*\n? DEBUG\n`, "m"), "");
return output;
}