blob: ae27564a21976aab540350fbe38f4d0f12979f08 [file] [log] [blame]
"""Utilities for working with node_modules."""
def node_module_tar(name, package, package_dir = "", owner = "0.0", mode = None):
"""Creates a target which packages the given node module into a tarball.
Args:
name: Name of the rule to create.
package: Name of the node_module directory to package.
package_dir: Optional, directory prefix to place the contents inside
the tarball.
owner: uid and gid of the owner for the files, eg. "2000.2000".
mode: permissions bits for the files, eg. "755", or "a+x", or None to
use default.
"""
uid, gid = owner.split(".")
# TODO(borenet): Can/should we use `tar` provided by rules_pkg?
cmd = """
PWD="$$(pwd)"
mkdir -p tar/node_modules
# Find python3.
PYTHON=""
for path in $(locations @python_3_11//:py3_runtime); do
if [[ "$$path" == *"/bin/python3" ]]; then
PYTHON="$$path"
break
fi
done
# Run the script to strip all but the desired package from our package.json and
# package-lock.json files.
$$PYTHON $(execpath //bazel:strip-package-lock.py) --input=. --output=./tar --package={package}
NPM="$$PWD/$(execpath @nodejs//:npm_bin)"
export PATH="$$PWD/$$(dirname $(execpath @nodejs//:node_bin)):$$PWD/$$(dirname $$NPM):$$PATH"
# Install the package and its dependencies.
export PUPPETEER_SKIP_DOWNLOAD=1
NPM_CACHE="$$PWD/.npm-cache"
$$NPM ci --cache=$$NPM_CACHE --prefix=$$PWD/tar
# Because we used our own package.json/package-lock.json, the package in
# question is not the "main" package and is therefore inside the node_modules
# directory. "Hoist" it up a level.
cp -rL ./tar/node_modules/{package}/* ./tar
rm -rf ./tar/node_modules/{package}
# Package the resulting directory.
tar -chf $@ --owner={uid} --group={gid} --transform 's,tar,{package_dir},' {mode_flag} tar
""".format(
package_dir = package_dir,
uid = uid,
gid = gid,
mode_flag = "--mode=%s" % mode if mode else "",
package = package,
)
native.genrule(
name = name,
srcs = ["//:package.json", "//:package-lock.json"],
outs = [package + ".tar"],
cmd = cmd,
tools = [
"@nodejs//:node_bin",
"@nodejs//:npm_bin",
"@nodejs//:npm_files",
"@python_3_11//:py3_runtime",
"//bazel:strip-package-lock.py",
],
visibility = ["//visibility:public"],
)