-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathbuild.zig
More file actions
276 lines (240 loc) · 9.12 KB
/
build.zig
File metadata and controls
276 lines (240 loc) · 9.12 KB
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
const std = @import("std");
const std_compat = @import("src/compat.zig");
const builtin = @import("builtin");
const GeneratedUiAssetsPath = ".generated_ui_assets.zig";
const EmptyUiAssetsSource =
\\const std = @import("std");
\\
\\pub const Asset = struct {
\\ path: []const u8,
\\ bytes: []const u8,
\\};
\\
\\pub const assets = [_]Asset{};
\\
\\pub fn get(path: []const u8) ?Asset {
\\ _ = path;
\\ return null;
\\}
\\
\\pub fn hasAssets() bool {
\\ return false;
\\}
;
const UiFile = struct {
fs_path: []const u8,
web_path: []const u8,
};
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const app_version = b.option([]const u8, "version", "Version string embedded in the binary") orelse "dev";
const embed_ui = b.option(bool, "embed-ui", "Embed the Svelte UI into the binary") orelse true;
const build_ui = b.option(bool, "build-ui", "Build the UI before embedding it") orelse embed_ui;
if (embed_ui) {
if (build_ui) ensureUiBuildReady(b);
ensureUiBuildExists();
}
var build_options = b.addOptions();
build_options.addOption([]const u8, "version", app_version);
const build_options_module = build_options.createModule();
const ui_assets_module = createUiAssetsModule(b, embed_ui);
const compat_module = b.createModule(.{
.root_source_file = b.path("src/compat.zig"),
.target = target,
.optimize = optimize,
.link_libc = true,
});
const exe_module = b.createModule(.{
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
.link_libc = true,
});
exe_module.addImport("build_options", build_options_module);
exe_module.addImport("ui_assets", ui_assets_module);
exe_module.addImport("compat", compat_module);
const exe = b.addExecutable(.{
.name = "nullhub",
.root_module = exe_module,
});
b.installArtifact(exe);
const run_cmd = b.addRunArtifact(exe);
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run", "Run nullhub");
run_step.dependOn(&run_cmd.step);
const test_module = b.createModule(.{
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
.link_libc = true,
});
test_module.addImport("build_options", build_options_module);
test_module.addImport("ui_assets", ui_assets_module);
test_module.addImport("compat", compat_module);
const exe_unit_tests = b.addTest(.{
.root_module = test_module,
});
const run_tests = b.addRunArtifact(exe_unit_tests);
const test_step = b.step("test", "Run unit tests");
test_step.dependOn(&run_tests.step);
const integration_test_module = b.createModule(.{
.root_source_file = b.path("src/integration_tests.zig"),
.target = target,
.optimize = optimize,
.link_libc = true,
});
integration_test_module.addImport("build_options", build_options_module);
integration_test_module.addImport("ui_assets", ui_assets_module);
integration_test_module.addImport("compat", compat_module);
const integration_tests = b.addTest(.{
.root_module = integration_test_module,
});
const run_integration_tests = b.addRunArtifact(integration_tests);
run_integration_tests.step.dependOn(b.getInstallStep());
run_integration_tests.setCwd(b.path("."));
const integration_bin_name = b.fmt("nullhub{s}", .{target.result.exeFileExt()});
run_integration_tests.setEnvironmentVariable("NULLHUB_INTEGRATION_BIN", b.getInstallPath(.bin, integration_bin_name));
const integration_test_step = b.step("test-integration", "Run integration tests");
integration_test_step.dependOn(&run_integration_tests.step);
}
fn createUiAssetsModule(b: *std.Build, embed_ui: bool) *std.Build.Module {
const source = if (embed_ui)
generateUiAssetsSource(b.allocator) catch |err| std.debug.panic("failed to generate embedded UI assets: {s}", .{@errorName(err)})
else
b.allocator.dupe(u8, EmptyUiAssetsSource) catch @panic("OOM");
writeGeneratedUiAssetsSource(source) catch |err| std.debug.panic("failed to write generated UI assets module: {s}", .{@errorName(err)});
return b.createModule(.{ .root_source_file = b.path(GeneratedUiAssetsPath) });
}
fn ensureUiBuildReady(b: *std.Build) void {
if (pathExists("ui/build")) return;
if (!pathExists("ui/node_modules")) {
runCommandOrPanic(b, &.{ npmCommand(), "--prefix", "ui", "ci", "--no-audit", "--no-fund" });
}
runCommandOrPanic(b, &.{ npmCommand(), "--prefix", "ui", "run", "build" });
}
fn ensureUiBuildExists() void {
if (!pathExists("ui/build")) {
std.debug.panic("embedded UI assets are missing; run `npm --prefix ui run build`, build with -Dbuild-ui=true, or disable embedding with -Dembed-ui=false for backend-only tests", .{});
}
}
fn runCommandOrPanic(b: *std.Build, argv: []const []const u8) void {
const io = b.graph.io;
var child = std.process.spawn(io, .{
.argv = argv,
.environ_map = &b.graph.environ_map,
.stdin = .ignore,
.stdout = .inherit,
.stderr = .inherit,
.create_no_window = true,
}) catch |err| std.debug.panic("failed to spawn {s}: {s}", .{ argv[0], @errorName(err) });
const term = child.wait(io) catch |err| std.debug.panic("failed to wait {s}: {s}", .{ argv[0], @errorName(err) });
switch (term) {
.exited => |code| {
if (code != 0) std.debug.panic("command failed with exit code {d}: {s}", .{ code, argv[0] });
},
else => std.debug.panic("command did not exit cleanly: {s}", .{argv[0]}),
}
}
fn npmCommand() []const u8 {
return if (builtin.os.tag == .windows) "npm.cmd" else "npm";
}
fn pathExists(path: []const u8) bool {
std_compat.fs.cwd().access(path, .{}) catch return false;
return true;
}
fn generateUiAssetsSource(allocator: std.mem.Allocator) ![]u8 {
var dir = try std_compat.fs.cwd().openDir("ui/build", .{ .iterate = true });
defer dir.close();
var walker = try dir.walk(allocator);
defer walker.deinit();
var files: std.ArrayListUnmanaged(UiFile) = .empty;
defer {
for (files.items) |file| {
allocator.free(file.fs_path);
allocator.free(file.web_path);
}
files.deinit(allocator);
}
while (try walker.next()) |entry| {
if (entry.kind != .file) continue;
const fs_path = try allocator.dupe(u8, entry.path);
errdefer allocator.free(fs_path);
const web_path = try normalizeWebPath(allocator, entry.path);
errdefer allocator.free(web_path);
try files.append(allocator, .{
.fs_path = fs_path,
.web_path = web_path,
});
}
std.mem.sort(UiFile, files.items, {}, struct {
fn lessThan(_: void, lhs: UiFile, rhs: UiFile) bool {
return std.mem.lessThan(u8, lhs.web_path, rhs.web_path);
}
}.lessThan);
var buf = std.array_list.Managed(u8).init(allocator);
errdefer buf.deinit();
try buf.appendSlice(
\\const std = @import("std");
\\
\\pub const Asset = struct {
\\ path: []const u8,
\\ bytes: []const u8,
\\};
\\
\\pub const assets = [_]Asset{
\\
);
for (files.items) |file| {
try buf.appendSlice(" .{ .path = ");
try appendZigStringLiteral(&buf, file.web_path);
try buf.appendSlice(", .bytes = @embedFile(");
const embed_path = try std.fmt.allocPrint(allocator, "ui/build/{s}", .{file.fs_path});
defer allocator.free(embed_path);
try appendZigStringLiteral(&buf, embed_path);
try buf.appendSlice(") },\n");
}
try buf.appendSlice(
\\};
\\
\\pub fn get(path: []const u8) ?Asset {
\\ inline for (assets) |asset| {
\\ if (std.mem.eql(u8, path, asset.path)) return asset;
\\ }
\\ return null;
\\}
\\
\\pub fn hasAssets() bool {
\\ return assets.len > 0;
\\}
\\
);
return buf.toOwnedSlice();
}
fn writeGeneratedUiAssetsSource(source: []const u8) !void {
const file = try std_compat.fs.cwd().createFile(GeneratedUiAssetsPath, .{ .truncate = true });
defer file.close();
try file.writeAll(source);
}
fn normalizeWebPath(allocator: std.mem.Allocator, input: []const u8) ![]u8 {
const duped = try allocator.dupe(u8, input);
for (duped) |*char| {
if (char.* == '\\') char.* = '/';
}
return duped;
}
fn appendZigStringLiteral(buf: *std.array_list.Managed(u8), value: []const u8) !void {
try buf.append('"');
for (value) |char| switch (char) {
'\\' => try buf.appendSlice("\\\\"),
'"' => try buf.appendSlice("\\\""),
'\n' => try buf.appendSlice("\\n"),
'\r' => try buf.appendSlice("\\r"),
'\t' => try buf.appendSlice("\\t"),
else => try buf.append(char),
};
try buf.append('"');
}