This repository has been archived by the owner on Jun 5, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
/
rule.bzl
355 lines (328 loc) · 12.1 KB
/
rule.bzl
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
load("//internal/js_library:rule.bzl", "JsLibraryInfo")
load("//internal/js_module:rule.bzl", "JsModuleInfo")
load("//internal/npm_packages:rule.bzl", "NpmPackagesInfo")
def _web_bundle_impl(ctx):
webpack_config = _create_webpack_config(ctx)
# Compile using the Webpack config.
ctx.actions.run(
inputs = [
ctx.file._web_bundle_compile_script,
ctx.attr._internal_packages[NpmPackagesInfo].installed_dir,
ctx.attr.lib[JsLibraryInfo].npm_packages_installed_dir,
ctx.attr.lib[JsLibraryInfo].compiled_javascript_dir,
webpack_config,
] + [
module[JsLibraryInfo].compiled_javascript_dir
for module in ctx.attr.modules
] + ctx.files.html_template,
outputs = [
ctx.outputs.bundle_dir,
],
executable = ctx.file._internal_nodejs,
env = {
"NODE_PATH": ctx.attr._internal_packages[NpmPackagesInfo].installed_dir.path + "/node_modules",
"GENDIR": ctx.var["GENDIR"],
},
arguments = [
# Run `node web_bundle/compile.js`.
ctx.file._web_bundle_compile_script.path,
# Template index.html for Webpack.
ctx.file.html_template.path if ctx.file.html_template else "",
# Directory containing internal NPM dependencies (for build tools).
ctx.attr._internal_packages[NpmPackagesInfo].installed_dir.path,
# Directory containing external NPM dependencies the code depends on.
ctx.attr.lib[JsLibraryInfo].npm_packages_installed_dir.path,
# Directory containing the compiled source code of the js_library.
ctx.attr.lib[JsLibraryInfo].compiled_javascript_dir.path,
# Modules to expose to Webpack through aliases.
("|".join([
module[JsModuleInfo].name + ":" + module[JsLibraryInfo].compiled_javascript_dir.path + "/" + _strip_buildfile(module[JsLibraryInfo].build_file_path) + ("/" + module[JsModuleInfo].single_file if module[JsModuleInfo].single_file else "")
for module in ctx.attr.modules
])),
# Environment variables to set in compiled JavaScript.
("|".join([
key + ":" + value
for key, value in ctx.attr.env.items()
])),
# Directory in which to place the compiled JavaScript.
ctx.outputs.bundle_dir.path,
# Path of the webpack config file.
webpack_config.path,
],
)
def _web_bundle_dev_server_impl(ctx):
webpack_config = _create_webpack_config(ctx)
# Serve using Webpack development server.
webpack_devserver_js = ctx.actions.declare_file(ctx.label.name + ".serve.js")
ctx.actions.write(
output = webpack_devserver_js,
content = """
const fs = require("fs-extra");
const path = require("path");
const chokidar = require("chokidar");
// We cannot build directly from the source directory as Webpack struggles to
// watch it correctly. Instead, we watch the source directory ourselves with
// chokidar (below), and copy it whenever it changes.
const bazelSrcDir = "{source_dir}";
const srcDir = "devserver-src";
const aliases = {{{aliases}}};
const env = {{{env}}};
// copySrcSoon() will ensures that copySrc() is only called at most once per
// second.
let copySoonTimeout = null;
function copySrcSoon() {{
if (copySoonTimeout) {{
clearTimeout(copySoonTimeout);
}}
copySoonTimeout = setTimeout(copySrc, 1000);
}}
// copySrc() copies files from Bazel's source to our source, which will be
// picked up by Webpack.
function copySrc() {{
if (!fs.existsSync(bazelSrcDir)) {{
// Try again later.
console.warn("Source directory is gone, trying again soon...");
copySrcSoon();
return;
}}
try {{
fs.copySync(bazelSrcDir, srcDir, {{
dereference: true,
overwrite: true,
}});
console.log("Source directory updated successfully.")
}} catch (e) {{
console.warn("Error copying, trying again soon...");
copySrcSoon();
}}
}}
chokidar.watch(bazelSrcDir, {{
ignoreInitial: true,
followSymlinks: true,
}}).on("all", copySrcSoon);
copySrc();
const configGenerator = require(path.resolve("{webpack_config}"));
const config = configGenerator(
srcDir,
aliases,
env,
"{output_bundle_dir}",
path.resolve("{dependencies_packages_dir}"),
"{internal_packages_dir}",
"{html_template}",
);
if (config.mode === "production") {{
console.error("Development server is not available when mode is 'production'.");
process.exit(1);
}}
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const port = 8080;
var options = require(path.resolve("{dev_server_options}"));
options.publicPath = config.output.publicPath;
const server = new WebpackDevServer(webpack(config), options);
server.listen(port, 'localhost', function (err) {{
if (err) {{
console.log(err);
}} else {{
console.log('WebpackDevServer listening at localhost:', port);
}}
}});
""".format(
webpack_config = webpack_config.short_path,
# Directory containing the compiled source code of the js_library.
source_dir = ctx.attr.lib[JsLibraryInfo].compiled_javascript_dir.short_path,
# Modules to expose to Webpack through aliases.
aliases = (",".join([
"'" + module[JsModuleInfo].name + "': path.resolve('" + module[JsLibraryInfo].compiled_javascript_dir.short_path + "/" + _strip_buildfile(module[JsLibraryInfo].build_file_path) + ("/" + module[JsModuleInfo].single_file if module[JsModuleInfo].single_file else "") + "')"
for module in ctx.attr.modules
])),
# Environment variables to set in compiled JavaScript.
env = (",".join([
"'" + key + "': JSON.stringify('" + value + "')"
for key, value in ctx.attr.env.items()
])),
# Unused output bundle directory.
output_bundle_dir = "",
# Directory containing external NPM dependencies the code depends on.
dependencies_packages_dir = ctx.attr.lib[JsLibraryInfo].npm_packages_installed_dir.short_path,
# Directory containing internal NPM dependencies (for build tools).
internal_packages_dir = ctx.attr._internal_packages[NpmPackagesInfo].installed_dir.short_path,
# Template index.html for Webpack.
html_template = ctx.file.html_template.short_path if ctx.file.html_template else "",
dev_server_options = ctx.file.dev_server_options.short_path,
),
)
ctx.actions.write(
output = ctx.outputs.devserver,
is_executable = True,
content = "NODE_PATH=" + ctx.attr._internal_packages[NpmPackagesInfo].installed_dir.short_path + "/node_modules " + ctx.file._internal_nodejs.path + " " + webpack_devserver_js.short_path,
)
return [
DefaultInfo(
executable = ctx.outputs.devserver,
runfiles = ctx.runfiles(
files = [
ctx.file.dev_server_options,
ctx.file._internal_nodejs,
ctx.file._web_bundle_compile_script,
webpack_devserver_js,
ctx.attr._internal_packages[NpmPackagesInfo].installed_dir,
ctx.attr.lib[JsLibraryInfo].npm_packages_installed_dir,
ctx.attr.lib[JsLibraryInfo].compiled_javascript_dir,
webpack_config,
] + [
module[JsLibraryInfo].compiled_javascript_dir
for module in ctx.attr.modules
] + ctx.files.html_template,
),
),
]
def _strip_buildfile(path):
if path.endswith("/BUILD.bazel"):
return path[:-12]
elif path.endswith("/BUILD"):
return path[:-6]
else:
return path
def _create_webpack_config(ctx):
webpack_config = ctx.actions.declare_file(ctx.label.name + ".webpack.config.js")
mode_arg = ctx.attr.mode
mode_arg = ctx.expand_make_variables("mode", mode_arg, {})
# Create the Webpack config file.
ctx.actions.run(
inputs = [
ctx.file._web_bundle_create_webpack_config_script,
ctx.attr._internal_packages[NpmPackagesInfo].installed_dir,
ctx.attr.lib[JsLibraryInfo].npm_packages_installed_dir,
ctx.attr.lib[JsLibraryInfo].compiled_javascript_dir,
],
outputs = [
webpack_config,
],
executable = ctx.file._internal_nodejs,
env = {
"NODE_PATH": ctx.attr._internal_packages[NpmPackagesInfo].installed_dir.path + "/node_modules",
"GENDIR": ctx.var["GENDIR"],
},
arguments = [
# Run `node web_bundle/create_webpack_config.js`.
ctx.file._web_bundle_create_webpack_config_script.path,
# Path of the directory containing the lib's BUILD.bazel file.
ctx.attr.lib[JsLibraryInfo].build_file_path,
# Entry point for Webpack (e.g. "main.ts").
ctx.attr.entry,
# Output file name (e.g. "bundle.js").
ctx.attr.output,
# Mode for Webpack.
mode_arg,
# Library for Webpack (optional).
ctx.attr.library_name + "/" + ctx.attr.library_target if ctx.attr.library_name else "",
# Enable split chunks or not.
"1" if ctx.attr.split_chunks else "0",
# Public path of web assets
ctx.attr.public_path,
# Path where to create the Webpack config.
webpack_config.path,
# Externals definitions
("|".join([
key + ":" + value
for key, value in ctx.attr.externals.items()
])),
],
)
return webpack_config
# Shared attributes between bundle and devserver rules.
_ATTRS = {
"lib": attr.label(
providers = [JsLibraryInfo],
mandatory = True,
),
"modules": attr.label_list(
providers = [JsModuleInfo],
),
"env": attr.string_dict(),
"externals": attr.string_dict(),
"entry": attr.string(
mandatory = True,
),
"output": attr.string(
default = "bundle.js",
),
"mode": attr.string(
default = "none",
),
"split_chunks": attr.bool(
default = False,
),
"public_path": attr.string(
default = "/",
),
"html_template": attr.label(
allow_single_file = True,
),
"library_name": attr.string(),
"library_target": attr.string(
values = [
"var",
"assign",
"this",
"window",
"global",
"commonjs",
"commonjs2",
"amd",
"umd",
"jsonp",
],
default = "umd",
),
"dev_server_options": attr.label(
allow_single_file = True,
default = Label("//internal/web_bundle:dev_server_options.js"),
),
"_internal_nodejs": attr.label(
allow_single_file = True,
default = Label("@nodejs//:node"),
),
"_internal_packages": attr.label(
default = Label("//internal:packages"),
),
"_web_bundle_compile_script": attr.label(
allow_single_file = True,
default = Label("//internal/web_bundle:compile.js"),
),
"_web_bundle_create_webpack_config_script": attr.label(
allow_single_file = True,
default = Label("//internal/web_bundle:create_webpack_config.js"),
),
}
_web_bundle = rule(
attrs = _ATTRS,
outputs = {
"bundle_dir": "%{name}_bundle",
},
implementation = _web_bundle_impl,
)
_web_bundle_dev_server = rule(
attrs = _ATTRS,
executable = True,
outputs = {
"devserver": "%{name}_devserver",
},
implementation = _web_bundle_dev_server_impl,
)
def web_bundle(name, tags = [], **kwargs):
_web_bundle(
name = name,
tags = tags,
**kwargs
)
_web_bundle_dev_server(
name = name + "_server",
tags = tags + [
"ibazel_notify_changes",
"ibazel_live_reload",
],
**kwargs
)