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
|
// SPDX-License-Identifier: MIT
// Copyright (c) 2015-2021 Zig Contributors
// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const std = @import("../std.zig");
const builtin = std.builtin;
const build = std.build;
const Step = build.Step;
const Builder = build.Builder;
const LibExeObjStep = build.LibExeObjStep;
const WriteFileStep = build.WriteFileStep;
const fs = std.fs;
const mem = std.mem;
const process = std.process;
const ArrayList = std.ArrayList;
const BufMap = std.BufMap;
const warn = std.debug.warn;
const max_stdout_size = 1 * 1024 * 1024; // 1 MiB
pub const RunStep = struct {
step: Step,
builder: *Builder,
/// See also addArg and addArgs to modifying this directly
argv: ArrayList(Arg),
/// Set this to modify the current working directory
cwd: ?[]const u8,
/// Override this field to modify the environment, or use setEnvironmentVariable
env_map: ?*BufMap,
stdout_action: StdIoAction = .inherit,
stderr_action: StdIoAction = .inherit,
stdin_behavior: std.ChildProcess.StdIo = .Inherit,
expected_exit_code: u8 = 0,
pub const StdIoAction = union(enum) {
inherit,
ignore,
expect_exact: []const u8,
expect_matches: []const []const u8,
};
pub const Arg = union(enum) {
Artifact: *LibExeObjStep,
WriteFile: struct {
step: *WriteFileStep,
file_name: []const u8,
},
Bytes: []u8,
};
pub fn create(builder: *Builder, name: []const u8) *RunStep {
const self = builder.allocator.create(RunStep) catch unreachable;
self.* = RunStep{
.builder = builder,
.step = Step.init(.Run, name, builder.allocator, make),
.argv = ArrayList(Arg).init(builder.allocator),
.cwd = null,
.env_map = null,
};
return self;
}
pub fn addArtifactArg(self: *RunStep, artifact: *LibExeObjStep) void {
self.argv.append(Arg{ .Artifact = artifact }) catch unreachable;
self.step.dependOn(&artifact.step);
}
pub fn addWriteFileArg(self: *RunStep, write_file: *WriteFileStep, file_name: []const u8) void {
self.argv.append(Arg{
.WriteFile = .{
.step = write_file,
.file_name = file_name,
},
}) catch unreachable;
self.step.dependOn(&write_file.step);
}
pub fn addArg(self: *RunStep, arg: []const u8) void {
self.argv.append(Arg{ .Bytes = self.builder.dupe(arg) }) catch unreachable;
}
pub fn addArgs(self: *RunStep, args: []const []const u8) void {
for (args) |arg| {
self.addArg(arg);
}
}
pub fn clearEnvironment(self: *RunStep) void {
const new_env_map = self.builder.allocator.create(BufMap) catch unreachable;
new_env_map.* = BufMap.init(self.builder.allocator);
self.env_map = new_env_map;
}
pub fn addPathDir(self: *RunStep, search_path: []const u8) void {
const env_map = self.getEnvMap();
var key: []const u8 = undefined;
var prev_path: ?[]const u8 = undefined;
if (builtin.os.tag == .windows) {
key = "Path";
prev_path = env_map.get(key);
if (prev_path == null) {
key = "PATH";
prev_path = env_map.get(key);
}
} else {
key = "PATH";
prev_path = env_map.get(key);
}
if (prev_path) |pp| {
const new_path = self.builder.fmt("{s}" ++ [1]u8{fs.path.delimiter} ++ "{s}", .{ pp, search_path });
env_map.set(key, new_path) catch unreachable;
} else {
env_map.set(key, search_path) catch unreachable;
}
}
pub fn getEnvMap(self: *RunStep) *BufMap {
return self.env_map orelse {
const env_map = self.builder.allocator.create(BufMap) catch unreachable;
env_map.* = process.getEnvMap(self.builder.allocator) catch unreachable;
self.env_map = env_map;
return env_map;
};
}
pub fn setEnvironmentVariable(self: *RunStep, key: []const u8, value: []const u8) void {
const env_map = self.getEnvMap();
env_map.set(key, value) catch unreachable;
}
pub fn expectStdErrEqual(self: *RunStep, bytes: []const u8) void {
self.stderr_action = .{ .expect_exact = bytes };
}
pub fn expectStdOutEqual(self: *RunStep, bytes: []const u8) void {
self.stdout_action = .{ .expect_exact = bytes };
}
fn stdIoActionToBehavior(action: StdIoAction) std.ChildProcess.StdIo {
return switch (action) {
.ignore => .Ignore,
.inherit => .Inherit,
.expect_exact, .expect_matches => .Pipe,
};
}
fn make(step: *Step) !void {
const self = @fieldParentPtr(RunStep, "step", step);
const cwd = if (self.cwd) |cwd| self.builder.pathFromRoot(cwd) else self.builder.build_root;
var argv_list = ArrayList([]const u8).init(self.builder.allocator);
for (self.argv.items) |arg| {
switch (arg) {
Arg.Bytes => |bytes| try argv_list.append(bytes),
Arg.WriteFile => |file| {
try argv_list.append(file.step.getOutputPath(file.file_name));
},
Arg.Artifact => |artifact| {
if (artifact.target.isWindows()) {
// On Windows we don't have rpaths so we have to add .dll search paths to PATH
self.addPathForDynLibs(artifact);
}
const executable_path = artifact.installed_path orelse artifact.getOutputPath();
try argv_list.append(executable_path);
},
}
}
const argv = argv_list.items;
const child = std.ChildProcess.init(argv, self.builder.allocator) catch unreachable;
defer child.deinit();
child.cwd = cwd;
child.env_map = self.env_map orelse self.builder.env_map;
child.stdin_behavior = self.stdin_behavior;
child.stdout_behavior = stdIoActionToBehavior(self.stdout_action);
child.stderr_behavior = stdIoActionToBehavior(self.stderr_action);
child.spawn() catch |err| {
warn("Unable to spawn {s}: {s}\n", .{ argv[0], @errorName(err) });
return err;
};
// TODO need to poll to read these streams to prevent a deadlock (or rely on evented I/O).
var stdout: ?[]const u8 = null;
defer if (stdout) |s| self.builder.allocator.free(s);
switch (self.stdout_action) {
.expect_exact, .expect_matches => {
stdout = child.stdout.?.reader().readAllAlloc(self.builder.allocator, max_stdout_size) catch unreachable;
},
.inherit, .ignore => {},
}
var stderr: ?[]const u8 = null;
defer if (stderr) |s| self.builder.allocator.free(s);
switch (self.stderr_action) {
.expect_exact, .expect_matches => {
stderr = child.stderr.?.reader().readAllAlloc(self.builder.allocator, max_stdout_size) catch unreachable;
},
.inherit, .ignore => {},
}
const term = child.wait() catch |err| {
warn("Unable to spawn {s}: {s}\n", .{ argv[0], @errorName(err) });
return err;
};
switch (term) {
.Exited => |code| {
if (code != self.expected_exit_code) {
warn("The following command exited with error code {} (expected {}):\n", .{
code,
self.expected_exit_code,
});
printCmd(cwd, argv);
return error.UncleanExit;
}
},
else => {
warn("The following command terminated unexpectedly:\n", .{});
printCmd(cwd, argv);
return error.UncleanExit;
},
}
switch (self.stderr_action) {
.inherit, .ignore => {},
.expect_exact => |expected_bytes| {
if (!mem.eql(u8, expected_bytes, stderr.?)) {
warn(
\\
\\========= Expected this stderr: =========
\\{s}
\\========= But found: ====================
\\{s}
\\
, .{ expected_bytes, stderr.? });
printCmd(cwd, argv);
return error.TestFailed;
}
},
.expect_matches => |matches| for (matches) |match| {
if (mem.indexOf(u8, stderr.?, match) == null) {
warn(
\\
\\========= Expected to find in stderr: =========
\\{s}
\\========= But stderr does not contain it: =====
\\{s}
\\
, .{ match, stderr.? });
printCmd(cwd, argv);
return error.TestFailed;
}
},
}
switch (self.stdout_action) {
.inherit, .ignore => {},
.expect_exact => |expected_bytes| {
if (!mem.eql(u8, expected_bytes, stdout.?)) {
warn(
\\
\\========= Expected this stdout: =========
\\{s}
\\========= But found: ====================
\\{s}
\\
, .{ expected_bytes, stdout.? });
printCmd(cwd, argv);
return error.TestFailed;
}
},
.expect_matches => |matches| for (matches) |match| {
if (mem.indexOf(u8, stdout.?, match) == null) {
warn(
\\
\\========= Expected to find in stdout: =========
\\{s}
\\========= But stdout does not contain it: =====
\\{s}
\\
, .{ match, stdout.? });
printCmd(cwd, argv);
return error.TestFailed;
}
},
}
}
fn printCmd(cwd: ?[]const u8, argv: []const []const u8) void {
if (cwd) |yes_cwd| warn("cd {s} && ", .{yes_cwd});
for (argv) |arg| {
warn("{s} ", .{arg});
}
warn("\n", .{});
}
fn addPathForDynLibs(self: *RunStep, artifact: *LibExeObjStep) void {
for (artifact.link_objects.items) |link_object| {
switch (link_object) {
.OtherStep => |other| {
if (other.target.isWindows() and other.isDynamicLibrary()) {
self.addPathDir(fs.path.dirname(other.getOutputPath()).?);
self.addPathForDynLibs(other);
}
},
else => {},
}
}
}
};
|