From 96d9a5bb157a29c85a26605c155926ef025dc7d4 Mon Sep 17 00:00:00 2001 From: Matt Nathan Date: Mon, 8 Apr 2019 18:54:10 +0100 Subject: [PATCH] Name bazel rules in a valid way In addition if you are outputting the generated files into a folder that looks like the npm package name then omit the prefix part to simplify importing in bazel. For example if you npm package is `@vue/cli` and your output dir is `~/myrepo/vue/cli` then the generated rule name will now be `cli` which will allow importing like `//myrepo/vue/cli`. If the output dir doesn't match the package name then any `/` will be replaced by '_' in the rule name. --- node/tools/npm/gen_build_npm.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/node/tools/npm/gen_build_npm.py b/node/tools/npm/gen_build_npm.py index 5b629b2..1bab2ae 100644 --- a/node/tools/npm/gen_build_npm.py +++ b/node/tools/npm/gen_build_npm.py @@ -35,6 +35,18 @@ def encode_npm_name(name): ''' return 'npm-gen-' + name.replace('/', '-').replace('@', 'at_') +def encode_rule_name(pkg, name): + ''' + Encode `name` so that it's a valid bazel rule name. If pkg ends + with the same path segments as the name then they will be removed + so that pkg:my/module, name:@my/module will return just 'module' + ''' + name = name.replace('@', '') + if pkg.replace('\\', '/').endswith(name): + name = name.split('/')[-1] + return name.replace('/', '_') + + def get_npm_library_contents(target_dir, npm_req): ''' Return a list of the contents of the npm module and its dependencies. ''' name = get_dep_name(npm_req) @@ -204,7 +216,7 @@ def generate_build_file_and_shrinkwrap(npm_req, output): contents = get_npm_library_contents(output, npm_req) - name = get_dep_name(npm_req) + name = encode_rule_name(output, get_dep_name(npm_req)) npm_rule = BazelRule( attr_map = {