|
| 1 | +_js_filetype = FileType([".js"]) |
| 2 | + |
| 3 | +SCRIPT_TEMPLATE = """ |
| 4 | +#!/usr/bin/env bash |
| 5 | +set -e |
| 6 | +export NODE_PATH={node_paths} |
| 7 | +"{node_bin}" "{script_path}" $@ |
| 8 | +""" |
| 9 | + |
| 10 | + |
| 11 | +def _get_global_node_modules_dir(ctx): |
| 12 | + node_bin = str(ctx.file.node_tool) |
| 13 | + node_parts = node_bin.partition("[source]]") |
| 14 | + node_prefix = node_parts[0][len("Artifact:["):] |
| 15 | + node_suffix_parts = node_parts[2].split("/") |
| 16 | + node_lib = "/".join([node_prefix] + node_suffix_parts[0:-2] + ["lib", "node_modules"]) |
| 17 | + return node_lib |
| 18 | + |
| 19 | + |
| 20 | +def node_binary_impl(ctx): |
| 21 | + inputs = [] |
| 22 | + node_paths = [_get_global_node_modules_dir(ctx)] |
| 23 | + for dep in ctx.attr.npm_deps: |
| 24 | + lib = dep.npm_library |
| 25 | + inputs.append(lib.package_marker) |
| 26 | + |
| 27 | + script = SCRIPT_TEMPLATE.format( |
| 28 | + node_bin = ctx.file.node_tool.short_path, |
| 29 | + script_path = ctx.file.main_script.short_path, |
| 30 | + node_paths = ":".join(node_paths), |
| 31 | + ) |
| 32 | + |
| 33 | + ctx.file_action( |
| 34 | + output = ctx.outputs.executable, |
| 35 | + content = script, |
| 36 | + executable = True, |
| 37 | + ) |
| 38 | + |
| 39 | + runfiles = [ctx.file.node_tool, ctx.file.main_script] + inputs |
| 40 | + |
| 41 | + return struct( |
| 42 | + runfiles = ctx.runfiles( |
| 43 | + files = runfiles, |
| 44 | + ), |
| 45 | + ) |
| 46 | + |
| 47 | + |
| 48 | +node_binary = rule( |
| 49 | + node_binary_impl, |
| 50 | + attrs = { |
| 51 | + "main_script": attr.label( |
| 52 | + single_file = True, |
| 53 | + allow_files = _js_filetype, |
| 54 | + ), |
| 55 | + "node_tool": attr.label( |
| 56 | + default = Label("//node/toolchain:node_tool"), |
| 57 | + single_file = True, |
| 58 | + allow_files = True, |
| 59 | + executable = True, |
| 60 | + cfg = "host", |
| 61 | + ), |
| 62 | + # "deps": attr.label_list( |
| 63 | + # providers = ["node_library"], |
| 64 | + # ), |
| 65 | + "npm_deps": attr.label_list( |
| 66 | + providers = ["npm_library"], |
| 67 | + ), |
| 68 | + }, |
| 69 | + executable = True, |
| 70 | +) |
0 commit comments