| # Copyright 2019 The Bazel Authors. All rights reserved. |
| # |
| # Licensed under the Apache License, Version 2.0 (the "License"); |
| # you may not use this file except in compliance with the License. |
| # You may obtain a copy of the License at |
| # |
| # http://www.apache.org/licenses/LICENSE-2.0 |
| # |
| # Unless required by applicable law or agreed to in writing, software |
| # distributed under the License is distributed on an "AS IS" BASIS, |
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| # See the License for the specific language governing permissions and |
| # limitations under the License. |
| """ NPM package manager interaction mock |
| """ |
| |
| def _generate_fine_grained_node_modules(rctx): |
| print("--fetch--") |
| package_json_path = rctx.path(rctx.attr.package_json) |
| |
| rctx.file( |
| "script.sh", |
| """ |
| root_dir="$1/node_modules" |
| mkdir $root_dir |
| mkdir $root_dir/example-module |
| cat > "$root_dir/example-module/package.json" <<EOF |
| { |
| "license": "MIT", |
| "main": "example-module.js", |
| "name": "example-module", |
| "repository": { |
| "type": "git", |
| "url": "aaa" |
| }, |
| "version": "0.2.0" |
| } |
| EOF |
| echo "ok" |
| """, |
| executable = True, |
| ) |
| cmd(rctx, "echo $DEBUG_ID > debug_id && echo 'ok'") |
| cmd(rctx, "./script.sh " + str(package_json_path.dirname)) |
| |
| node_modules_root = rctx.path(str(package_json_path) + "/../node_modules") |
| build_file_lines = [] |
| for path_ in node_modules_root.readdir(): |
| name = path_.basename |
| rctx.symlink(path_, rctx.path(name)) |
| build_file_lines += ["""filegroup(name = "{name}", srcs = glob(["{name}/**"]), visibility = ["//visibility:public"])""".format(name = name)] |
| |
| rctx.file("BUILD", "\n".join(build_file_lines)) |
| |
| generate_fine_grained_node_modules = repository_rule( |
| implementation = _generate_fine_grained_node_modules, |
| attrs = { |
| "package_json": attr.label(), |
| }, |
| ) |
| |
| def cmd( |
| repository_ctx, |
| command, |
| environment = None): |
| """Executes a command, returns stdout if succeed and throw an error if it fails. |
| |
| Doesn't escape the result! |
| |
| Args: |
| repository_ctx: repository context |
| command: command parts array |
| environment: dict with environment variables |
| |
| Returns: |
| process stdout as a string |
| """ |
| if environment: |
| result = repository_ctx.execute(["bash", "-c", command], environment = environment) |
| else: |
| result = repository_ctx.execute(["bash", "-c", command]) |
| if result.return_code != 0: |
| fail("non-zero exit code: %d, command %s, stderr: (%s)" % ( |
| result.return_code, |
| command, |
| result.stderr, |
| )) |
| stripped_stdout = result.stdout.strip() |
| if not stripped_stdout: |
| fail( |
| "empty output from command %s, stderr: (%s)" % (command, result.stderr), |
| ) |
| return stripped_stdout |