add a script to build an isolated node_modules

This commit is contained in:
Brian Hicks 2023-05-01 14:45:08 -05:00
parent e78a393163
commit cbe8944b74
No known key found for this signature in database
GPG Key ID: C4F324B9CAAB0D50
3 changed files with 66 additions and 0 deletions

View File

@ -34,3 +34,8 @@ genrule(
visibility = ["PUBLIC"],
executable = True,
)
export_file(
name = "build_node_modules.py",
visibility = ["PUBLIC"],
)

View File

@ -0,0 +1,56 @@
#!/usr/bin/env python3
"""
Make a fresh `node_modules` directory in an isolated directory.
This script assumes it has `npm` and its dependencies in the right `PATH` and
`NODE_PATH`. Make sure that's set up properly using whatever installation method
is necessary!
"""
import argparse
import os
import subprocess
import sys
import shutil
import tempfile
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("out", help="Where you want node_modules to end up")
parser.add_argument(
"--package",
help="The package.json to install dependencies from",
default="package.json",
)
parser.add_argument(
"--package-lock",
help="The package-lock.json corresponding to package.json",
default="package-lock.json",
)
parser.add_argument(
"--no-ignore-scripts",
action="store_true",
help="Don't run package post-install scripts",
)
args = parser.parse_args()
with tempfile.TemporaryDirectory() as tempdir:
# npm wants these to be real files for whatever reason, and will throw
# errors if they're symlinks.
shutil.copy(args.package, os.path.join(tempdir, "package.json"))
shutil.copy(args.package_lock, os.path.join(tempdir, "package-lock.json"))
cmd = ["npm", "clean-install"]
if not args.no_ignore_scripts:
cmd.append("--ignore-scripts")
proc = subprocess.Popen(cmd, cwd=tempdir)
proc.communicate()
if proc.returncode == 0:
os.rename(
os.path.join(tempdir, "node_modules"),
args.out,
)
sys.exit(proc.returncode)

View File

@ -1,6 +1,7 @@
NodeToolchainInfo = provider(fields=[
"bin",
"node",
"build_node_modules",
])
def _node_toolchain_impl(ctx) -> [[DefaultInfo.type, NodeToolchainInfo.type]]:
@ -13,6 +14,7 @@ def _node_toolchain_impl(ctx) -> [[DefaultInfo.type, NodeToolchainInfo.type]]:
NodeToolchainInfo(
bin = ctx.attrs.bin[DefaultInfo].default_outputs,
node = ctx.attrs.node[RunInfo],
build_node_modules = ctx.attrs._build_node_modules,
),
]
@ -26,6 +28,9 @@ node_toolchain = rule(
providers = [RunInfo],
default="prelude-nri//node:node"
),
"_build_node_modules": attrs.dep(
default="prelude-nri//node:build_node_modules.py",
),
},
is_toolchain_rule = True,
)