Dave Borowitz | cfd221e | 2015-11-11 13:59:05 -0500 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | # Copyright (C) 2015 The Android Open Source Project |
| 3 | # |
| 4 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | # you may not use this file except in compliance with the License. |
| 6 | # You may obtain a copy of the License at |
| 7 | # |
| 8 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | # |
| 10 | # Unless required by applicable law or agreed to in writing, software |
| 11 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | # See the License for the specific language governing permissions and |
| 14 | # limitations under the License. |
| 15 | |
| 16 | from __future__ import print_function |
| 17 | |
| 18 | import atexit |
| 19 | import json |
| 20 | import os |
| 21 | import shutil |
| 22 | import subprocess |
| 23 | import sys |
| 24 | import tarfile |
| 25 | import tempfile |
| 26 | |
| 27 | |
| 28 | def is_bundled(tar): |
| 29 | # No entries for directories, so scan for a matching prefix. |
| 30 | for entry in tar.getmembers(): |
| 31 | if entry.name.startswith('package/node_modules/'): |
| 32 | return True |
| 33 | return False |
| 34 | |
| 35 | |
| 36 | def bundle_dependencies(): |
| 37 | with open('package.json') as f: |
| 38 | package = json.load(f) |
David Ostrovsky | de255d9 | 2018-01-14 11:09:43 +0100 | [diff] [blame] | 39 | package['bundledDependencies'] = list(package['dependencies'].keys()) |
Dave Borowitz | cfd221e | 2015-11-11 13:59:05 -0500 | [diff] [blame] | 40 | with open('package.json', 'w') as f: |
| 41 | json.dump(package, f) |
| 42 | |
| 43 | |
| 44 | def main(args): |
| 45 | if len(args) != 2: |
| 46 | print('Usage: %s <package> <version>' % sys.argv[0], file=sys.stderr) |
| 47 | return 1 |
| 48 | |
| 49 | name, version = args |
| 50 | filename = '%s-%s.tgz' % (name, version) |
| 51 | url = 'http://registry.npmjs.org/%s/-/%s' % (name, filename) |
| 52 | |
| 53 | tmpdir = tempfile.mkdtemp(); |
| 54 | tgz = os.path.join(tmpdir, filename) |
| 55 | atexit.register(lambda: shutil.rmtree(tmpdir)) |
| 56 | |
| 57 | subprocess.check_call(['curl', '--proxy-anyauth', '-ksfo', tgz, url]) |
| 58 | with tarfile.open(tgz, 'r:gz') as tar: |
| 59 | if is_bundled(tar): |
| 60 | print('%s already has bundled node_modules' % filename) |
| 61 | return 1 |
| 62 | tar.extractall(path=tmpdir) |
| 63 | |
| 64 | oldpwd = os.getcwd() |
| 65 | os.chdir(os.path.join(tmpdir, 'package')) |
| 66 | bundle_dependencies() |
| 67 | subprocess.check_call(['npm', 'install']) |
| 68 | subprocess.check_call(['npm', 'pack']) |
| 69 | shutil.copy(filename, os.path.join(oldpwd, filename)) |
| 70 | return 0 |
| 71 | |
| 72 | |
| 73 | if __name__ == '__main__': |
| 74 | sys.exit(main(sys.argv[1:])) |