├── .gitignore
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── bar
├── gulpfile.js
└── package.json
├── build_tools
├── BUILD
├── install_npm_dependencies.py
├── npm.bzl
├── npm_installer.sh
└── npm_packer.sh
├── foo
└── package.json
└── npm-bazel-gen.py
/.gitignore:
--------------------------------------------------------------------------------
1 | bazel-*
2 | node_modules
3 | target
4 | build_tools/npm-thirdparty
5 | build_tools/npm_version_cache
6 | build_tools/npm_dependency_cache
7 | BUILD
8 | WORKSPACE
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as
6 | contributors and maintainers pledge to making participation in our project and
7 | our community a harassment-free experience for everyone, regardless of age, body
8 | size, disability, ethnicity, gender identity and expression, level of experience,
9 | nationality, personal appearance, race, religion, or sexual identity and
10 | orientation.
11 |
12 | ## Our Standards
13 |
14 | Examples of behavior that contributes to creating a positive environment
15 | include:
16 |
17 | * Using welcoming and inclusive language
18 | * Being respectful of differing viewpoints and experiences
19 | * Gracefully accepting constructive criticism
20 | * Focusing on what is best for the community
21 | * Showing empathy towards other community members
22 |
23 | Examples of unacceptable behavior by participants include:
24 |
25 | * The use of sexualized language or imagery and unwelcome sexual attention or
26 | advances
27 | * Trolling, insulting/derogatory comments, and personal or political attacks
28 | * Public or private harassment
29 | * Publishing others' private information, such as a physical or electronic
30 | address, without explicit permission
31 | * Other conduct which could reasonably be considered inappropriate in a
32 | professional setting
33 |
34 | ## Our Responsibilities
35 |
36 | Project maintainers are responsible for clarifying the standards of acceptable
37 | behavior and are expected to take appropriate and fair corrective action in
38 | response to any instances of unacceptable behavior.
39 |
40 | Project maintainers have the right and responsibility to remove, edit, or
41 | reject comments, commits, code, wiki edits, issues, and other contributions
42 | that are not aligned to this Code of Conduct, or to ban temporarily or
43 | permanently any contributor for other behaviors that they deem inappropriate,
44 | threatening, offensive, or harmful.
45 |
46 | ## Scope
47 |
48 | This Code of Conduct applies both within project spaces and in public spaces
49 | when an individual is representing the project or its community. Examples of
50 | representing a project or community include using an official project e-mail
51 | address, posting via an official social media account, or acting as an appointed
52 | representative at an online or offline event. Representation of a project may be
53 | further defined and clarified by project maintainers.
54 |
55 | ## Enforcement
56 |
57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
58 | reported by contacting the project team at opensource@redfin.com. All
59 | complaints will be reviewed and investigated and will result in a response that
60 | is deemed necessary and appropriate to the circumstances. The project team is
61 | obligated to maintain confidentiality with regard to the reporter of an incident.
62 | Further details of specific enforcement policies may be posted separately.
63 |
64 | Project maintainers who do not follow or enforce the Code of Conduct in good
65 | faith may face temporary or permanent repercussions as determined by other
66 | members of the project's leadership.
67 |
68 | ## Attribution
69 |
70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71 | available at [http://contributor-covenant.org/version/1/4][version]
72 |
73 | [homepage]: http://contributor-covenant.org
74 | [version]: http://contributor-covenant.org/version/1/4/
75 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | ## Contributor License Agreement
2 |
3 | To get started, please [sign the Contributor License
4 | Agreement](https://cla-assistant.io/redfin/npm-bazel). The purpose
5 | of this license is to protect contributors, Redfin, as well as users
6 | of this software project. Signing this agreement does not affect your
7 | rights to use your contributions for any other purpose.
8 |
9 | ## Code of Conduct
10 |
11 | Please note that this project is released with a [Contributor Code of
12 | Conduct](/CODE_OF_CONDUCT.md).
13 | By participating in this project you agree to abide by its terms.
14 |
15 | ## Thanks!
16 |
17 | Thanks for contributing!
18 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | This project provides a generator tool, `npm-bazel-gen.py`, to generate `WORKSPACE` rules and `BUILD` files for [npm](https://www.npmjs.com/) modules. It also provides Skylark rules in `build_tools/npm.bzl` to build `npm` modules in Bazel's sandbox.
2 |
3 | # Stability: prototype
4 |
5 | This is a public clone of code that we're using internally at [Redfin](https://www.redfin.com/). The version we actually use seems to be working, but we cannot guarantee that this repository will be stable/maintained. (But hope springs eternal, and if people seem to like it, we could stabilize it further.)
6 |
7 | # Getting Started
8 |
9 | Generate the `WORKSPACE` and `BUILD` files using the Python script, then build the example projects.
10 |
11 | ```
12 | python npm-bazel-gen.py
13 | bazel build foo
14 | ```
15 |
16 | # Background
17 |
18 | ## Required knowledge
19 |
20 | * What `npm install` kinda does, a little about how node_modules work
21 | * What a Bazel Skylark rule does http://bazel.io/docs/skylark/index.html
22 | * This is a bit tougher to come by, but you can get pretty far by reading these three docs in order:
23 | * http://bazel.io/docs/skylark/concepts.html
24 | * http://bazel.io/docs/skylark/rules.html
25 | * http://bazel.io/docs/skylark/cookbook.html
26 | * And then read them again, starting with "concepts"
27 |
28 | ## What does `npm install` do?
29 |
30 | `npm install` with no arguments does two-and-a-half things.
31 |
32 | 1. "Install dependencies"
33 | 1. "Download" dependencies declared in `package.json` into `./node_modules` (de-duping dependencies and resolving circular dependencies as needed)
34 | 2. "Rebuild" those downloaded dependencies. (You can `npm rebuild` to re-run this.)
35 | * Compile native code: if any of those deps had native code in them, they need to be recompiled. There are no limitations on what this build step is allowed to do.
36 | * Symlink scripts: if any of the deps provided executable scripts to run in the "bin" section of package.json, ("gulp" is especially important,) then node will symlink them into `node_modules/.bin`
37 |
38 | For example, `node_modules/.bin/gulp` will be a symlink to `node_modules/gulp/bin/gulp.js`
39 | 2. "Prepublish" current project: if `package.json` declares a `scripts.prepublish` step, it'll run that. A common scripts.prepublish step is: "gulp prepublish". (npm automatically adds `node_modules/.bin` to the path when running this script.)
40 |
41 | To generate a `.tgz` output file, we can run `npm pack`, which does two things:
42 |
43 |
44 | - Prepublish: runs (re-runs) the "prepublish" step
45 | - Tar: It tars up everything in the current directory, except for anything explicitly ignored by `.npmignore`.
46 |
47 |
48 |
49 | Some of these steps violate Bazel's sandbox.
50 |
51 | * 1a "Download": Obviously, this uses the network.
52 | * 1b "Rebuild": The rebuild scripts are, in principle, allowed to do anything, including access the network, and sometimes they do that. In particular, the way to generate bindings from node to native code is to run `node-gyp`, which tries to download header files on first launch and caches them in `~/.node-gyp`.
53 | * 2 "Prepublish": This script may try to access the network. For example, lots of modules use [`nsp`](https://www.npmjs.com/package/nsp) to query for known Node security vulnerabilities. (`nsp` has an offline mode, but it's "unofficial, unsupported.")
54 |
55 | ## How we implemented that in Bazel
56 |
57 | 1. Install phase: `build_tools/npm_installer.sh`
58 | 1. Download:
59 | * `npm-bazel-gen.py` scans all package.json files, finding the full dependency tree (tree of trees? forest?) and declares all external dependencies as rules in the `WORKSPACE` file
60 | * `build_tools/install-npm-dependencies.py` is a script that simulates what `npm install` would have done, including de-duping dependencies and handling circular dependencies. (`npm` allows circular dependencies! 😮) **BEWARE This script is currently imperfect! It doesn't do exactly what `npm` would have done.**
61 | 2. Rebuild:
62 | * We run `npm rebuild` directly after we run `install_npm_dependencies`.
63 | * To avoid sandbox violations, we set `HOME=/tmp` and pre-install `/tmp/.node-gyp`
64 | 3. We do _not_ run prepublish during this "install" phase, because we plan to run it during packaging.
65 | 4. We then tar up the generated `node_modules` folder.
66 | 2. Pack phase: `build_tools/npm_packer.sh`
67 | 1. Setup: We're not allowed to modify source files directly, so we setup by:
68 | * rsyncing source files to a work directory
69 | * untar the generated `node_modules` folder into the work directory
70 | 2. We run `npm pack` which runs the prepublish script, if any, and generates the final output.
71 |
72 | ## `npm.bzl`
73 |
74 | `npm.bzl` defines two rules, `external_npm_module` and `internal_npm_module`. "external" means "third party," as opposed to "internal" modules being built by Bazel.
75 |
76 | The `internal_npm_module` rule is responsible for running `npm_installer.sh` and then `npm_packer.sh` as `ctx.action`s.
77 |
78 | The majority of `npm.bzl` is a bunch of code to marshall the correct list of inputs and outputs for the "install" phase and then the "pack" phase. Both types of rules return a `struct()` containing three fields:
79 |
80 | * `internal` (boolean): `external_npm_module` sets this to false, internal_npm_module sets this to true
81 | * `transitive_external_deps` (list): the full set of external dependency modules for the current module (including indirect dependencies)
82 | * `transitive_internal_deps` (list): the full set of internal dependency modules for the current module (including indirect dependencies). `external_npm_module` returns an empty list for this.
83 |
84 | In addition, internal modules return these two fields:
85 |
86 | * `tarball` (file): The generated tarball file for this module
87 | * `package_json` (file): The `package.json` file input (used by other rules to compute the dependency tree)
88 |
89 | Skylark calls this system of a rule returning a `struct()` a "provider" in Skylark. http://bazel.io/docs/skylark/rules.html (Cmd-F for the "Providers" section)
90 |
91 | Skylark's documentation on providers is pretty light, but all it means is: rules can return a `struct()` of data to _provide_ it to dependent rules.
92 |
93 | The top of `npm.bzl` is taking the list of `deps` and the list of `dev_deps`, sorting them into internal and external dependencies, and assembling four lists:
94 |
95 | * `transitive_internal_deps`
96 | * `transitive_external_deps`
97 | * `transitive_internal_dev_deps`
98 | * `transitive_external_dev_deps`
99 |
100 | It then creates an `internal_modules.json` file using the two "internal" lists, so `install_npm_dependencies.py` knows where to look for internal modules.
101 |
102 | It then runs two `ctx.action` commands:
103 |
104 | 1. the "install" phase, which runs `build_tools/npm_installer.sh` to generate `foo_node_modules.tar.gz` with these inputs:
105 | 1. All dependencies
106 | 2. `package.json` files for all internal dependencies
107 | 3. `internal_modules.json`
108 | 2. the "pack" phase, which runs `build_tools/npm_packer.sh` to generate `foo.tgz` with these inputs:
109 | 1. foo_node_modules.tar.gz
110 | 2. All of the source files in the current working directory
111 |
112 |
113 | ## Non-standard projects
114 |
115 | In our project at Redfin, we have a bunch of projects that do weird/non-standard stuff, usually during the "pack" phase, but sometimes during the "install" phase.
116 |
117 | The `internal_npm_module` rule has `install_tool` and `pack_tool` attributes, which default to `build_tools:npm_installer` and `build_tools:npm_packer` but you can override them to anything you want, including defining a `sh_binary` with arbitrary dependencies. (You have to hack in special cases to `npm-bazel-gen.py` to make it add those for you, when you want it.)
118 |
119 | In addition, the default packer tool looks for a `./extra-bazel-script` file in the current directory, and if it finds one, it just runs whatever it sees there. In some cases, that's enough pluggability.
120 |
121 | ## Next steps
122 |
123 | * Shouldn't I use the new remote repository rule thingy? I should learn more about how that works
124 | * The generator script generates the `@node` WORKSPACE differently on OS X and Linux. How do we make a single target that DTRT on other platforms?
125 | * Windows?!
--------------------------------------------------------------------------------
/bar/gulpfile.js:
--------------------------------------------------------------------------------
1 | var gulp = require("gulp");
2 | var src = ["**/*.js", "!node_modules/**", "!target/**"];
3 | gulp.task("compile", function() {
4 | gulp.src(src)
5 | // pointless example, but this could babelify or whatever
6 | .pipe(gulp.dest('target/'));
7 | });
8 |
--------------------------------------------------------------------------------
/bar/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "bar",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1",
8 | "prepublish": "gulp compile"
9 | },
10 | "keywords": [],
11 | "author": "",
12 | "license": "Apache License 2.0",
13 | "dependencies": {
14 | "gulp": "^3.9.1"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/build_tools/BUILD:
--------------------------------------------------------------------------------
1 | py_binary(
2 | name='install_npm_dependencies',
3 | srcs=['install_npm_dependencies.py'],
4 | data=['npm_version_cache'],
5 | visibility = ['//visibility:public'],
6 | )
7 |
8 | sh_binary(
9 | name='npm_installer',
10 | srcs=['npm_installer.sh'],
11 | data=['install_npm_dependencies', '@node//:raw', '@node_headers//:gyp-package'],
12 | visibility = ['//visibility:public'],
13 | )
14 |
15 | sh_binary(
16 | name='npm_packer',
17 | srcs=['npm_packer.sh'],
18 | data=['@node//:raw'],
19 | visibility = ['//visibility:public'],
20 | )
21 |
22 | filegroup(
23 | name='npm_cache',
24 | srcs=['npm_version_cache'],
25 | visibility = ["//visibility:public"],
26 | )
27 |
--------------------------------------------------------------------------------
/build_tools/install_npm_dependencies.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | import os, json, sys, re, shutil, tarfile, tempfile, contextlib, subprocess
3 |
4 | @contextlib.contextmanager
5 | def tempdir():
6 | dirpath = tempfile.mkdtemp()
7 | def cleanup():
8 | shutil.rmtree(dirpath)
9 | try:
10 | yield dirpath
11 | finally:
12 | cleanup()
13 | pass
14 |
15 | package_file = sys.argv[1]
16 | output_dir = sys.argv[2]
17 | internal_modules_file = sys.argv[3]
18 | version_cache_file = sys.argv[4]
19 |
20 | def is_url(str):
21 | return str.startswith('http://') or str.startswith('https://')
22 |
23 | def get_rule_name(name, version):
24 | raw_key = name + "_" + version;
25 | if is_url(version):
26 | raw_key = name + "_tarball"
27 | return re.sub(r'[^A-Za-z0-9_]+', "_", raw_key)
28 |
29 | def recursive_symlink(source, target):
30 | source = os.path.abspath(source)
31 | target = os.path.abspath(target)
32 | target_dirname = os.path.dirname(target)
33 | if not os.path.exists(target_dirname):
34 | os.makedirs(target_dirname)
35 | subprocess.check_call(['rsync', '--archive', '--copy-unsafe-links', '--link-dest='+source, source+'/', target+'/'])
36 |
37 | def get_external_dep_dir(name, version):
38 | rule_name = get_rule_name(name, version)
39 | external_dep_dir = 'external/' + rule_name
40 | sub_dirs = [f for f in os.listdir(external_dep_dir) if os.path.isdir(external_dep_dir+'/'+f)]
41 | if len(sub_dirs) != 1:
42 | raise Exception("There were {} subdirectories of external package dir {}".format(
43 | len(sub_dirs),
44 | os.path.abspath(external_dep_dir)
45 | ))
46 | return (external_dep_dir, sub_dirs[0])
47 |
48 |
49 | def symlink_shrinkwrap(directory, name, node):
50 | target = '{}/{}'.format(directory, name)
51 | if name in internal_modules:
52 | with tempdir() as tmp:
53 | target_dir = os.path.dirname(target)
54 | if not os.path.isdir(target_dir):
55 | os.makedirs(target_dir)
56 | with tarfile.open(internal_modules[name]["tarball"]) as tar: tar.extractall(tmp)
57 | os.system('mv ' + tmp + '/package ' + target)
58 | else:
59 | version = node["version"]
60 | external_dep_dir, external_dep_sub_dir = get_external_dep_dir(name, version)
61 | recursive_symlink('{}/{}'.format(external_dep_dir, external_dep_sub_dir), target)
62 | if "dependencies" in node:
63 | for dep_name, dep in node["dependencies"].viewitems():
64 | symlink_shrinkwrap('{}/{}/node_modules'.format(directory, name), dep_name, dep)
65 |
66 | def get_path(node):
67 | if id(node) in parents:
68 | return get_path(parents[id(node)]) + '/' + names[id(node)]
69 | else:
70 | return "."
71 |
72 | names = {}
73 | parents = {}
74 | def dedupe_tree(node, name):
75 | names[id(node)] = name
76 | #print("starting {} at {}".format(name, get_path(node)))
77 | if (id(node) in parents and id(parents[id(node)]) in parents):
78 | #print("raising '{}@{}'".format(name, node["version"]))
79 | parent = parents[id(node)]
80 | ancestor = parent
81 | while(id(ancestor) in parents):
82 | ancestor = parents[id(ancestor)]
83 | if name in ancestor["dependencies"]:
84 | if ancestor["dependencies"][name]["version"] == node["version"]:
85 | del parent["dependencies"][name]
86 | #print('{} provides {}@{}'.format(get_path(ancestor), name, ancestor["dependencies"][name]["version"]))
87 | #print('ended up at ' + get_path(ancestor["dependencies"][name]))
88 | return
89 | else:
90 | pass
91 | #print('{} provides {}@{}'.format(get_path(ancestor), name, ancestor["dependencies"][name]["version"]))
92 | #print('ended up at ' + get_path(node))
93 | break
94 | else:
95 | del parent["dependencies"][name]
96 | parent = ancestor
97 | parents[id(node)] = parent
98 | parent["dependencies"][name] = node
99 | #print('ended up at ' + get_path(node))
100 | if "dependencies" in node:
101 | for child_name in sorted(node["dependencies"].keys()):
102 | dependency = node["dependencies"][child_name]
103 | parents[id(dependency)] = node
104 | dedupe_tree(dependency, child_name)
105 |
106 | version_cache = {}
107 | with open(version_cache_file) as x: version_cache = json.load(x)
108 |
109 | internal_modules = {}
110 |
111 | with open(internal_modules_file) as x:
112 | internal_modules_json = json.load(x)
113 | for internal_package_file in internal_modules_json:
114 | with open(internal_package_file) as y:
115 | internal_package_json = json.load(y)
116 | internal_modules[internal_package_json["name"]] = {"package_file":internal_package_file, "tarball":internal_modules_json[internal_package_file]}
117 |
118 | def add_dependencies(node, package, key, parents):
119 | #print("\t" * len(parents) + key + ": " + node["name"]+"@"+node["version"])
120 | if key in package:
121 | for name in sorted(package[key]):
122 | version = package[key][name]
123 | code = name + '@' + version
124 | if code in version_cache:
125 | version = version_cache[code]
126 | code = name + '@' + version
127 | if code in parents:
128 | continue
129 | sub_parents = set(parents)
130 | sub_parents.add(code)
131 | if name in internal_modules:
132 | node["dependencies"][name] = build_supershrink(internal_modules[name]["package_file"], sub_parents)
133 | else:
134 | external_dep_dir, external_dep_sub_dir = get_external_dep_dir(name, version)
135 | node["dependencies"][name] = build_supershrink('{}/{}/package.json'.format(external_dep_dir, external_dep_sub_dir), sub_parents)
136 | node["dependencies"][name]["version"] = version
137 |
138 | def build_supershrink(package_json, parents):
139 | with open(package_json) as x: package = json.load(x)
140 | node = {"name": package["name"], "version": package["version"], "dependencies": {}}
141 | add_dependencies(node, package, "dependencies", parents)
142 | if len(parents) == 0 and "devDependencies" in package:
143 | add_dependencies(node, package, "devDependencies", parents)
144 | return node
145 |
146 | shutil.rmtree(output_dir + '/node_modules', ignore_errors=True)
147 | os.makedirs(output_dir + '/node_modules')
148 |
149 | supershrink = build_supershrink(package_file, set())
150 |
151 | dedupe_tree(supershrink, "")
152 |
153 | for name, shrinkwrap in supershrink["dependencies"].viewitems():
154 | symlink_shrinkwrap(output_dir + '/node_modules', name, shrinkwrap)
--------------------------------------------------------------------------------
/build_tools/npm.bzl:
--------------------------------------------------------------------------------
1 | def _internal_npm_module_impl(ctx):
2 | transitive_external_deps = []
3 | transitive_internal_deps = []
4 | transitive_internal_dev_deps = []
5 | transitive_external_dev_deps = []
6 | dep_files = []
7 | for dep in ctx.attr.deps:
8 | if dep.internal:
9 | transitive_internal_deps.append(dep)
10 | else:
11 | transitive_external_deps.append(dep)
12 | transitive_external_deps.extend(dep.transitive_external_deps)
13 | transitive_internal_deps.extend(dep.transitive_internal_deps)
14 |
15 | for dep in ctx.attr.dev_deps:
16 | if dep.internal:
17 | transitive_internal_dev_deps.append(dep)
18 | else:
19 | transitive_external_dev_deps.append(dep)
20 | transitive_external_dev_deps.extend(dep.transitive_external_deps)
21 | transitive_internal_dev_deps.extend(dep.transitive_internal_deps)
22 |
23 | for dep in transitive_external_deps + transitive_internal_deps + transitive_internal_dev_deps + transitive_external_dev_deps:
24 | dep_files.extend(list(dep.files))
25 |
26 | internal_modules = ctx.new_file("internal_modules.json")
27 | internal_deps = struct(**{
28 | dep.package_json.path: dep.tarball.path
29 | for dep in transitive_internal_deps + transitive_internal_dev_deps
30 | })
31 | for dep in transitive_internal_deps + transitive_internal_dev_deps:
32 | dep_files.append(dep.package_json)
33 |
34 | ctx.file_action(
35 | content=internal_deps.to_json() + '\n',
36 | output = internal_modules
37 | )
38 |
39 | ctx.action(
40 | executable = ctx.executable.install_tool,
41 | arguments = [
42 | ctx.file.package_json.path,
43 | internal_modules.path,
44 | ctx.outputs.node_modules.path,
45 | ],
46 | inputs = dep_files + [ctx.file.package_json, internal_modules],
47 | outputs = [ctx.outputs.node_modules],
48 | progress_message = "npm installing " + ctx.label.name,
49 | )
50 |
51 | source_dir = ctx.file.package_json.dirname
52 |
53 | pack_inputs = ctx.files.srcs + [ctx.outputs.node_modules]
54 |
55 | ctx.action(
56 | executable = ctx.executable.pack_tool,
57 | arguments = [
58 | source_dir,
59 | ctx.outputs.node_modules.path,
60 | ctx.outputs.tarball.path,
61 | ],
62 | inputs = pack_inputs,
63 | outputs = [ctx.outputs.tarball],
64 | progress_message = "npm packing " + ctx.label.name,
65 | )
66 |
67 | return struct(
68 | internal = True,
69 | tarball = ctx.outputs.tarball,
70 | package_json = ctx.file.package_json,
71 | transitive_internal_deps = transitive_internal_deps,
72 | transitive_external_deps = transitive_external_deps
73 | )
74 |
75 | def _external_npm_module(ctx):
76 | return struct(
77 | internal = False,
78 | transitive_internal_deps = [],
79 | transitive_external_deps = [ctx.attr.raw_target] + ctx.attr.runtime_deps
80 | )
81 |
82 | internal_npm_module = rule(
83 | implementation = _internal_npm_module_impl,
84 | attrs = {
85 | "package_json": attr.label(allow_files=True, single_file=True, mandatory=True),
86 | "srcs": attr.label_list(allow_files=True),
87 | "dev_deps": attr.label_list(allow_files=True),
88 | "deps": attr.label_list(allow_files=True),
89 | "install_tool": attr.label(executable=True, allow_files=True,
90 | default=Label("//build_tools:npm_installer")),
91 | "pack_tool": attr.label(executable=True, allow_files=True,
92 | default=Label("//build_tools:npm_packer")),
93 | },
94 | outputs = {
95 | "tarball": "%{name}.tgz",
96 | "node_modules": "%{name}_node_modules.tar.gz"
97 | }
98 | )
99 |
100 | external_npm_module = rule(
101 | implementation = _external_npm_module,
102 | attrs = {
103 | "raw_target": attr.label(allow_files = True),
104 | "runtime_deps": attr.label_list(allow_files = True)
105 | },
106 | )
107 |
108 |
--------------------------------------------------------------------------------
/build_tools/npm_installer.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash -eux
2 |
3 | START_DIR=`pwd`
4 | RUNFILES=$START_DIR/${BASH_SOURCE[0]}.runfiles/__main__
5 |
6 | PACKAGE_FILE=$1
7 | INTERNAL_MODULES_FILE=$2
8 | NODE_MODULES_OUTPUT=$3
9 |
10 | OUTPUT_DIR=`dirname $NODE_MODULES_OUTPUT`
11 | OUTPUT_NAME=`basename $NODE_MODULES_OUTPUT`
12 |
13 | $RUNFILES/build_tools/install_npm_dependencies.py $PACKAGE_FILE $OUTPUT_DIR $INTERNAL_MODULES_FILE $RUNFILES/build_tools/npm_version_cache
14 |
15 | safelink() {
16 | SRC=$1
17 | DEST=$2
18 | if [ ! -L $DEST ]; then
19 | mkdir -p `dirname $DEST`
20 | # On non-sandbox machines, there could be a race condition
21 | # Try creating the symlink, allowing failure
22 | set +e
23 | ln -s $SRC $DEST
24 | set -e
25 | # if the file's still not there, try it with halt-on-failure
26 | if [ ! -L $DEST ]; then
27 | ln -s $SRC $DEST
28 | fi
29 | fi
30 | }
31 |
32 | # the real npm is a symlink to npm-cli.js, but the runfiles npm is a hardlink? real file? whatever
33 | safelink $RUNFILES/../node/bin/node /tmp/npm-bin/node
34 | safelink $RUNFILES/../node/lib/node_modules/npm/bin/npm-cli.js /tmp/npm-bin/npm
35 |
36 | export PATH=/tmp/npm-bin:$RUNFILES/../node/bin:$PATH
37 |
38 | if [ ! -d /tmp/.node-gyp ]; then
39 | mkdir -p /tmp
40 | tar xf $RUNFILES/../node_headers/gyp-package.tar.gz -C /tmp
41 | fi
42 |
43 | cd $OUTPUT_DIR
44 | HOME=/tmp npm --cache=$START_DIR/bazel-npm-cache rebuild
45 | tar zcf $OUTPUT_NAME node_modules
46 |
--------------------------------------------------------------------------------
/build_tools/npm_packer.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash -eux
2 |
3 | export START_DIR=`pwd`
4 | RUNFILES=${RUNFILES:-}
5 | if [ -z "$RUNFILES" ]; then
6 | RUNFILES=$START_DIR/${BASH_SOURCE[0]}.runfiles/__main__
7 | fi
8 |
9 | SRCS_DIR=$1
10 | NODE_MODULES_TAR=$2
11 | OUTPUT=$3
12 |
13 | OUTPUT_DIR=`dirname $OUTPUT`
14 |
15 | # the real npm is a symlink to npm-cli.js, but the runfiles npm is a hardlink? real file? whatever
16 | mkdir -p /tmp/npm-bin
17 | if [ ! -L /tmp/npm-bin/node ]; then
18 | ln -s $RUNFILES/../node/bin/node /tmp/npm-bin/node
19 | fi
20 | if [ ! -L /tmp/npm-bin/npm ]; then
21 | ln -s $RUNFILES/../node/lib/node_modules/npm/bin/npm-cli.js /tmp/npm-bin/npm
22 | fi
23 |
24 | export PATH=/tmp/npm-bin:$RUNFILES/../node/bin:$PATH
25 |
26 | rsync --archive --copy-unsafe-links --link-dest=$START_DIR/$SRCS_DIR $START_DIR/$SRCS_DIR/ $START_DIR/$OUTPUT_DIR/
27 |
28 | cd $OUTPUT_DIR
29 |
30 | tar xf $START_DIR/$NODE_MODULES_TAR
31 |
32 | if [ -f extra-bazel-script ]; then
33 | ./extra-bazel-script
34 | fi
35 |
36 | if [ -f .npmignore ]; then
37 | # break hard link, so we don't modify source files
38 | cp .npmignore npmignore
39 | rm .npmignore
40 | mv npmignore .npmignore
41 | fi
42 |
43 | echo >> .npmignore
44 | echo `basename $NODE_MODULES_TAR` >> .npmignore
45 |
46 | npm --cache=$START_DIR/bazel-npm-cache pack
47 |
48 | mv *.tgz $START_DIR/$OUTPUT
49 |
--------------------------------------------------------------------------------
/foo/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "foo",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "keywords": [],
10 | "author": "",
11 | "license": "Apache License 2.0",
12 | "dependencies": {
13 | "bar": "^1.0.0",
14 | "react": "^0.14.8",
15 | "react-dom": "^0.14.8",
16 | "react-server": "^0.2.10",
17 | "superagent": "^1.2.0"
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/npm-bazel-gen.py:
--------------------------------------------------------------------------------
1 | import json, subprocess, os, re, shutil, sys
2 | from Queue import Queue
3 | from threading import Thread
4 |
5 | registry = "https://registry.npmjs.org/"
6 |
7 | packages = subprocess.check_output(['git', 'ls-files', '*/package.json']).strip().split('\n')
8 | #print '\n'.join(packages)
9 |
10 | internal_modules = {}
11 | external_dependencies = set()
12 |
13 | print("-- scanning packages")
14 | for package_file in packages:
15 | print(package_file)
16 | package_dir = os.path.dirname(package_file)
17 | with open(package_file) as x: package = json.load(x)
18 | internal_modules[package["name"]] = package_dir
19 | if "dependencies" in package:
20 | for name, version in package["dependencies"].viewitems():
21 | external_dependencies.add(name + "@" + version)
22 | if "devDependencies" in package:
23 | for name, version in package["devDependencies"].viewitems():
24 | external_dependencies.add(name + "@" + version)
25 |
26 | version_cache = {}
27 | dependency_cache = {}
28 |
29 | if os.path.exists('build_tools/npm_version_cache'):
30 | with open('build_tools/npm_version_cache') as x: version_cache = json.load(x)
31 | if os.path.exists('build_tools/npm_dependency_cache'):
32 | with open('build_tools/npm_dependency_cache') as x: dependency_cache = json.load(x)
33 |
34 | workspace_urls = {}
35 |
36 | def is_url(str):
37 | return str.startswith('http://') or str.startswith('https://')
38 |
39 | def get_version(name, version):
40 | code = name + '@' + version
41 | if re.match(r'^[\d.]+\.[\d.]+\.[\d.]+$', version):
42 | #print(" -- version seems exact: " + code)
43 | return version
44 | elif is_url(version):
45 | #print(" -- version seems to be a url: " + code)
46 | return version
47 | elif code in version_cache:
48 | #print(" -- version cache hit: " + code + " = " + version_cache[code])
49 | return version_cache[code]
50 | print(" -- version: " + code)
51 | output = subprocess.check_output(['npm', '--registry', registry, 'view', code, 'version']).strip().split('\n')
52 | if len(output) > 1:
53 | last_line = output[-1]
54 | new_code = last_line.split(' ')[0]
55 | resolved_version = re.match(r'^(.+)@([^@]+)$', new_code).groups()[1]
56 | else:
57 | resolved_version = output[0]
58 | print(" -- recording {}@{} = {}".format(name, version, resolved_version))
59 | version_cache[code] = resolved_version
60 | with open('build_tools/npm_version_cache', 'w') as x: json.dump(version_cache, x, indent=2, separators=(',', ': '), sort_keys=True)
61 | return resolved_version
62 |
63 | def get_dependencies(name, version):
64 | code = name + '@' + version
65 | if code in dependency_cache:
66 | return dependency_cache[code]
67 | print(" -- dependencies: " + code)
68 | result_string = subprocess.check_output(['npm', '--registry', registry, 'view', '--json', name+'@'+version, 'dependencies'])
69 | if not result_string:
70 | output = {}
71 | else:
72 | try:
73 | output = json.loads(result_string)
74 | except ValueError as e:
75 | raise Exception("error reading dependencies for {}@{}: <{}>\nCaused by: {}: {}".format(name, version, result_string, type(e).__name__, str(e))), None, sys.exc_info()[2]
76 |
77 | print(" -- " + json.dumps(output))
78 | dependency_cache[code] = output
79 | with open('build_tools/npm_dependency_cache', 'w') as x: json.dump(dependency_cache, x, indent=2, separators=(',', ': '), sort_keys=True)
80 | return output
81 |
82 | def get_rule_name(name, version):
83 | raw_key = name + "_" + version;
84 | if is_url(version):
85 | raw_key = name + "_tarball"
86 | return re.sub(r'[^A-Za-z0-9_]+', "_", raw_key)
87 |
88 | def add_workspace_url(name, version):
89 | rule_name = get_rule_name(name, version)
90 | if is_url(version):
91 | workspace_urls[rule_name] = version
92 | else:
93 | workspace_urls[rule_name] = '{repo_url}/{name}/-/{name}-{version}.tgz'.format(
94 | repo_url = registry,
95 | name = name,
96 | version = version
97 | )
98 |
99 | def get_transitive_dependencies(parent_name, parent_version, dependencies):
100 | add_workspace_url(parent_name, parent_version)
101 | for name, version in get_dependencies(parent_name, parent_version).viewitems():
102 | resolved_version = get_version(name, version)
103 | add_workspace_url(name, resolved_version)
104 | code = name+'@'+resolved_version
105 | if code in dependencies:
106 | continue
107 | dependencies.add(code)
108 | get_transitive_dependencies(name, resolved_version, dependencies)
109 |
110 | print('-- writing thirdparty BUILD file')
111 |
112 | external_npm_module_template = """external_npm_module(
113 | name='{}@{}',
114 | raw_target='{}',{}
115 | visibility = ["//visibility:public"],
116 | )
117 | """
118 |
119 | def worker():
120 | while True:
121 | parent_name, parent_version, dependencies = q.get()
122 | resolved_parent_version = get_version(parent_name, parent_version)
123 | for name, version in get_dependencies(parent_name, resolved_parent_version).viewitems():
124 | resolved_version = get_version(name, version)
125 | code = name+'@'+resolved_version
126 | if code in dependencies:
127 | continue
128 | dependencies.add(code)
129 | q.put((name, resolved_version, dependencies))
130 | q.task_done()
131 |
132 | q = Queue()
133 |
134 | num_worker_threads = 16
135 |
136 | for i in range(num_worker_threads):
137 | t = Thread(target=worker)
138 | t.daemon = True
139 | t.start()
140 |
141 | resolved_external_dependencies = set()
142 | for code in external_dependencies:
143 | name, version = re.match(r'^(.+)@([^@]+)$', code).groups()
144 | if name in internal_modules:
145 | continue
146 | if is_url(version):
147 | version = "tarball"
148 | resolved_version = get_version(name, version)
149 | resolved_external_dependencies.add(name+'@'+resolved_version)
150 | transitive_dependencies = set()
151 | q.put((name, version, transitive_dependencies))
152 |
153 | q.join()
154 | if not os.path.exists('build_tools/npm-thirdparty'):
155 | os.makedirs('build_tools/npm-thirdparty')
156 |
157 | with open('build_tools/npm-thirdparty/BUILD', 'w') as BUILD:
158 | BUILD.write("load('/build_tools/npm', 'external_npm_module')\n\n");
159 | for code in sorted(resolved_external_dependencies):
160 | name, version = re.match(r'^(.+)@([^@]+)$', code).groups()
161 | print("-- " + code)
162 | transitive_dependencies = set()
163 | get_transitive_dependencies(name, version, transitive_dependencies)
164 | raw_target = "@{}//:raw".format(get_rule_name(name, version))
165 | depstring = ""
166 | if len(transitive_dependencies):
167 | deps = []
168 | for dep in sorted(transitive_dependencies):
169 | dep_name, dep_version = re.match(r'^(.+)@([^@]+)$', dep).groups()
170 | deps.append("'@{}//:raw'".format(get_rule_name(dep_name, dep_version)))
171 | depstring = "\n\truntime_deps=[\n\t\t" + ",\n\t\t".join(deps) + "\n\t],\n"
172 | BUILD.write(external_npm_module_template.format(
173 | name,
174 | version,
175 | raw_target,
176 | depstring
177 | ))
178 |
179 | print('-- writing workspace')
180 |
181 | workspace_template = """new_http_archive(
182 | name='{rule_name}',
183 | url='{url}',
184 | build_file_content="filegroup(name='raw', srcs=glob(['*'], exclude_directories=0), visibility=['//visibility:public'])",
185 | )
186 | """
187 |
188 | if sys.platform == 'darwin':
189 | node_platform = 'darwin'
190 | phantom_platform = 'macosx'
191 | phantom_file_extension = 'zip'
192 | else:
193 | node_platform = 'linux'
194 | phantom_platform = 'linux-x86_64'
195 | phantom_file_extension = 'tgz'
196 |
197 | workspace_preamble = """
198 | new_http_archive(
199 | name='node',
200 | url='https://nodejs.org/download/release/v4.3.1/node-v4.3.1-{node_platform}-x64.tar.gz',
201 | strip_prefix='node-v4.3.1-{node_platform}-x64',
202 | build_file_content="filegroup(name='raw', data=glob(['*'], exclude_directories = 0), visibility=['//visibility:public'])"
203 | )
204 |
205 | new_http_archive(
206 | name='phantomjs',
207 | url='http://thirdpartyrepository.redfintest.com/com/redfin/phantomjs/2.1.1/phantomjs-2.1.1-{phantom_platform}.{phantom_file_extension}',
208 | strip_prefix='phantomjs-2.1.1-{phantom_platform}',
209 | build_file_content="filegroup(name='executable', data=glob(['bin/phantomjs']), visibility=['//visibility:public'])"
210 | )
211 |
212 | new_http_archive(
213 | name='node_headers',
214 | url='https://nodejs.org/download/release/v4.3.1/node-v4.3.1-headers.tar.gz',
215 | build_file_content=r\"""
216 | genrule(
217 | name='gyp-package',
218 | srcs=glob(['**']),
219 | outs=['gyp-package.tar.gz'],
220 | visibility=['//visibility:public'],
221 | cmd='''
222 | rm -rf $(@D)/.node-gyp
223 | mkdir -p $(@D)/.node-gyp
224 | cp -r external/node_headers/node-v4.3.1 $(@D)/.node-gyp/4.3.1
225 | echo 9 > $(@D)/.node-gyp/4.3.1/installVersion
226 | tar zcf $@ -C $(@D) .node-gyp
227 | '''
228 | )
229 | \"""
230 | )
231 |
232 |
233 | """.format(node_platform=node_platform, phantom_platform=phantom_platform, phantom_file_extension=phantom_file_extension)
234 |
235 |
236 |
237 | with open('WORKSPACE', 'w') as WORKSPACE:
238 | WORKSPACE.write(workspace_preamble)
239 | for rule_name in sorted(workspace_urls.keys()):
240 | url = workspace_urls[rule_name]
241 | WORKSPACE.write(workspace_template.format(rule_name=rule_name, url=url))
242 |
243 | print("-- writing internal BUILD files")
244 | for package_file in packages:
245 | package_dir = os.path.dirname(package_file)
246 | with open(package_file) as x: package = json.load(x)
247 | dependencies = []
248 | if "dependencies" in package:
249 | for name in sorted(package["dependencies"].keys()):
250 | dependencies.append((name, package["dependencies"][name]))
251 | if "devDependencies" in package:
252 | for name in sorted(package["devDependencies"].keys()):
253 | dependencies.append((name, package["devDependencies"][name]))
254 |
255 | with open(package_dir+'/BUILD', 'w') as BUILD:
256 | BUILD.write("load('/build_tools/npm', 'internal_npm_module')\n\n");
257 | BUILD.write("internal_npm_module(\n name='")
258 | currentName = os.path.basename(package_dir)
259 | BUILD.write(currentName)
260 | BUILD.write("',\n srcs=glob(['**'], exclude=['node_modules/**', 'target/**'")
261 | # add custom exclusions here
262 | BUILD.write("]),\n package_json='"+os.path.basename(package_file)+"',\n ")
263 | # configure custom install/pack scripts here
264 | BUILD.write("deps=[\n")
265 | if "dependencies" in package:
266 | for name in sorted(package["dependencies"].keys()):
267 | version = package["dependencies"][name]
268 | if name in internal_modules:
269 | BUILD.write(" '//{}',\n".format(internal_modules[name]))
270 | else:
271 | resolved_version = get_version(name, version)
272 | BUILD.write(" '//build_tools/npm-thirdparty:{}@{}',\n".format(name, resolved_version))
273 | BUILD.write(" ],\n dev_deps = [\n")
274 | if "devDependencies" in package:
275 | for name in sorted(package["devDependencies"].keys()):
276 | version = package["devDependencies"][name]
277 | if name in internal_modules:
278 | BUILD.write(" '//{}',\n".format(internal_modules[name]))
279 | else:
280 | resolved_version = get_version(name, version)
281 | BUILD.write(" '//build_tools/npm-thirdparty:{}@{}',\n".format(name, resolved_version))
282 | BUILD.write(" ],\n visibility=['//visibility:public'],")
283 | BUILD.write("\n)\n")
284 |
285 | # add extra custom rules here
286 |
--------------------------------------------------------------------------------