| #!/usr/bin/env vpython3 | |
| # | |
| # Copyright 2019 The Chromium Authors | |
| # Use of this source code is governed by a BSD-style license that can be | |
| # found in the LICENSE file. | |
| """ | |
| Use this script to update node_modules instead of running npm install | |
| manually. To upgrade a dependency, change the version number in package.json | |
| and run `./dt install-deps`. | |
| node_modules is not checked into git: `gclient sync` extracts it from the | |
| archive pinned by the `node_modules` entry in DEPS | |
| (gs://chromium-nodejs/devtools-frontend/<sha256>). This script produces that | |
| archive. Without options it runs `npm install`, post-processes the tree, | |
| checks licenses, applies scripts/deps/npm_exclude.txt (rsync filter rules | |
| that drop files the build and tests don't need), verifies that every | |
| node_modules/ path referenced from GN or Python build files still exists and | |
| writes a deterministic out/node_modules.tar.gz. | |
| --upload Also upload the archive to GCS (a no-op when it already | |
| exists) and point the `node_modules` entry in DEPS at it. | |
| --check Only rebuild the archive from node_modules and compare it | |
| with the `node_modules` entry in DEPS. | |
| --skip-install Don't run `npm install`; operate on the existing tree. | |
| A typical dependency bump is: | |
| ./dt install-deps # or --upload, if you have access to the bucket | |
| ./dt build && ./dt test # verify the new tree | |
| git cl upload # package.json, package-lock.json and DEPS | |
| """ | |
| import argparse | |
| from dataclasses import dataclass | |
| import gzip | |
| import hashlib | |
| import json | |
| import os | |
| import os.path as path | |
| import re | |
| import shutil | |
| import subprocess | |
| import sys | |
| import tarfile | |
| import urllib.error | |
| import urllib.request | |
| from collections import OrderedDict | |
| scripts_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| sys.path.append(scripts_path) | |
| import devtools_paths | |
| LICENSES = [ | |
| "MIT", | |
| "Apache-2.0", | |
| "BSD", | |
| "BSD-2-Clause", | |
| "BSD-3-Clause", | |
| "CC0-1.0", | |
| "CC-BY-3.0", | |
| "CC-BY-4.0", | |
| "ISC", | |
| "MPL-2.0", | |
| "Python-2.0", | |
| "W3C", | |
| "BlueOak-1.0.0", | |
| ] | |
| # Where the node_modules archive lives in Google Cloud Storage. The bucket is | |
| # shared with the Node binaries (see DEPS) and other Chromium projects; the | |
| # prefix namespaces our objects. Objects are named by their sha256, so they are | |
| # immutable and re-uploading the same archive is a no-op. | |
| GCS_BUCKET = 'chromium-nodejs' | |
| GCS_PREFIX = 'devtools-frontend' | |
| GCS_PUBLIC_URL = 'https://storage.googleapis.com' | |
| # Name of the gcs dependency in DEPS that `--upload` updates. | |
| DEPS_ENTRY_NAME = 'node_modules' | |
| NODE_MODULE_PATCHES = [ | |
| "scripts/deps/node_module_patches/karma-mocha.patch", | |
| # Removes the global declarations of the Mocha test interface (`describe`, | |
| # `it`, ...). Tests have to import them explicitly instead. | |
| "scripts/deps/node_module_patches/types-mocha.patch", | |
| ] | |
| REFERENCE_SKIP_DIRS = frozenset( | |
| ['.git', 'node_modules', 'out', 'third_party', '__pycache__']) | |
| @dataclass(frozen=True) | |
| class NodeDepsTarget: | |
| name: str | |
| rel_dir: str | |
| deps_entry: str | |
| gcs_prefix: str | |
| default_archive_name: str | |
| patches: tuple = () | |
| fix_chai: bool = False | |
| remove_dependencies: bool = False | |
| reference_skip_dirs: frozenset = REFERENCE_SKIP_DIRS | |
| deps_condition: str = 'non_git_source' | |
| def root_dir(self): | |
| root = devtools_paths.devtools_root_path() | |
| return path.join(root, self.rel_dir) if self.rel_dir else root | |
| def package_json_path(self): | |
| return (path.join(self.root_dir(), 'package.json') | |
| if self.rel_dir else devtools_paths.package_json_path()) | |
| def package_json_relpath(self): | |
| return f'{self.rel_dir}/package.json' if self.rel_dir else 'package.json' | |
| def lockfile_relpath(self): | |
| return f'{self.rel_dir}/package-lock.json' if self.rel_dir else 'package-lock.json' | |
| def node_modules_path(self): | |
| return (path.join(self.root_dir(), 'node_modules') | |
| if self.rel_dir else devtools_paths.node_modules_path()) | |
| def default_archive_path(self): | |
| return path.join(devtools_paths.devtools_root_path(), 'out', | |
| self.default_archive_name) | |
| def exists(self): | |
| return path.isfile(self.package_json_path()) | |
| ROOT_TARGET = NodeDepsTarget('root', | |
| '', | |
| DEPS_ENTRY_NAME, | |
| GCS_PREFIX, | |
| 'node_modules.tar.gz', | |
| patches=tuple(NODE_MODULE_PATCHES), | |
| fix_chai=True, | |
| remove_dependencies=True, | |
| reference_skip_dirs=REFERENCE_SKIP_DIRS | |
| | {'for_agents'}) | |
| # Files inside node_modules/ that gclient writes when it manages the directory | |
| # as a gcs dependency, plus the archive itself. They must never end up inside | |
| # a new archive, regardless of the exclude list. | |
| GCLIENT_ARTIFACT_PATTERNS = re.compile( | |
| r'^(node_modules\.tar\.gz|\..*_hash|\..*_is_first_class_gcs|' | |
| r'\..*_content_names)$') | |
| def exclude_file_path(): | |
| return path.join(devtools_paths.devtools_root_path(), 'scripts', 'deps', | |
| 'npm_exclude.txt') | |
| def default_archive_path(): | |
| return path.join(devtools_paths.devtools_root_path(), 'out', | |
| 'node_modules.tar.gz') | |
| def deps_file_path(): | |
| return path.join(devtools_paths.devtools_root_path(), 'DEPS') | |
| def depot_tools_path(): | |
| return path.join(devtools_paths.devtools_root_path(), 'third_party', | |
| 'depot_tools') | |
| def load_json_file(location): | |
| # By default, json load uses a standard Python dictionary, which is not ordered. | |
| # To prevent subsequent invocations of this script to erroneously alter the order | |
| # of keys defined in package.json files, we should use an `OrderedDict`. This | |
| # ensures not only that we use a strict ordering, it will also make sure we maintain | |
| # the order defined by the NPM packages themselves. That in turn is important, since | |
| # NPM packages can define `exports`, where the order of entrypoints is crucial for | |
| # how an NPM package is loaded. If you would change the order, it could break loading | |
| # that package. | |
| return json.load(location, object_pairs_hook=OrderedDict) | |
| # The parts of package.json that affect node_modules (not `scripts` etc.). | |
| PACKAGE_JSON_DEPENDENCY_KEYS = ('dependencies', 'devDependencies', | |
| 'optionalDependencies', 'peerDependencies', | |
| 'overrides') | |
| _SEMVER_EXACT = r'\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?' | |
| _NPM_PACKAGE_NAME = r'(?:@[a-z0-9][a-z0-9._-]*/)?[a-z0-9][a-z0-9._-]*' | |
| EXACT_VERSION_PATTERN = re.compile( | |
| rf'^(?:npm:{_NPM_PACKAGE_NAME}@)?{_SEMVER_EXACT}$') | |
| def _collect_unpinned(section, mapping, unpinned): | |
| for name, value in mapping.items(): | |
| if isinstance(value, dict): | |
| _collect_unpinned(f'{section}.{name}', value, unpinned) | |
| elif not isinstance(value, | |
| str) or not EXACT_VERSION_PATTERN.match(value): | |
| unpinned.append((section, name, value)) | |
| def find_unpinned_dependencies(pkg_data): | |
| """Returns [(section, name, value)] for non-exact version specs.""" | |
| unpinned = [] | |
| for section in PACKAGE_JSON_DEPENDENCY_KEYS: | |
| entries = pkg_data.get(section) | |
| if isinstance(entries, dict): | |
| _collect_unpinned(section, entries, unpinned) | |
| return unpinned | |
| def exec_command(cmd, cwd=None, env=None): | |
| try: | |
| new_env = os.environ.copy() if env is None else env | |
| subprocess.check_call(cmd, | |
| cwd=cwd or devtools_paths.devtools_root_path(), | |
| env=new_env) | |
| except Exception as error: | |
| print(error) | |
| return True | |
| return False | |
| def ensure_licenses(target=ROOT_TARGET): | |
| cmd = [ | |
| devtools_paths.node_path(), | |
| devtools_paths.license_checker_path(), | |
| '--start', | |
| target.root_dir(), | |
| '--onlyAllow', | |
| ('%s' % (';'.join(LICENSES))), | |
| ] | |
| return exec_command(cmd) | |
| def remove_package_json_entries(target=ROOT_TARGET): | |
| pkg_path = target.package_json_path() | |
| with open(pkg_path, 'r+', encoding='utf-8') as pkg_file: | |
| try: | |
| pkg_data = load_json_file(pkg_file) | |
| # Remove the dependencies and devDependencies from the root package.json | |
| # so that they can't be used to overwrite the node_modules managed by this file. | |
| for key in list(pkg_data.keys()): | |
| if key.find('dependencies') == 0: | |
| pkg_data.pop(key) | |
| pkg_file.truncate(0) | |
| pkg_file.seek(0) | |
| json.dump(pkg_data, pkg_file, indent=2, separators=(',', ': ')) | |
| pkg_file.write('\n') | |
| except: | |
| print('Unable to fix: %s' % pkg_path) | |
| return True | |
| return False | |
| def fixChaiExports(target=ROOT_TARGET): | |
| file_path = path.join(target.node_modules_path(), 'chai', 'package.json') | |
| with open(file_path, 'r+', encoding='utf-8') as pkg_json: | |
| content = pkg_json.read() | |
| pkg_json.seek(0) | |
| # Buggy export in the current chai version. Can be removed once the chai version is fixed. | |
| content = content.replace('"./": "./"', '"./*": "./*.js"') | |
| pkg_json.write(content) | |
| pkg_json.truncate() | |
| def apply_patch(patch_path): | |
| cwd = devtools_paths.devtools_root_path() | |
| env = os.environ.copy() | |
| # Check if the patch can be applied. | |
| check_cmd = ["git", "apply", "--check", patch_path] | |
| if subprocess.run(check_cmd, cwd=cwd, env=env, | |
| capture_output=True).returncode == 0: | |
| return exec_command(["git", "apply", patch_path]) | |
| # If it cannot be applied, check if it is already applied. | |
| reverse_check_cmd = ["git", "apply", "--reverse", "--check", patch_path] | |
| if subprocess.run(reverse_check_cmd, cwd=cwd, env=env, | |
| capture_output=True).returncode == 0: | |
| return False | |
| # If it's neither applicable nor already applied, run it for real to report the error. | |
| return exec_command(["git", "apply", patch_path]) | |
| def apply_patches(patches=NODE_MODULE_PATCHES): | |
| return any(apply_patch(patch_path) for patch_path in patches) | |
| def check_npm_version(): | |
| try: | |
| new_env = os.environ.copy() | |
| version_str = subprocess.check_output( | |
| ['npm', '--version'], | |
| cwd=devtools_paths.devtools_root_path(), | |
| env=new_env, | |
| text=True).strip() | |
| except Exception as error: | |
| print(f'Failed to run "npm --version": {error}') | |
| return True | |
| if version_str.startswith('v'): | |
| version_str = version_str[1:] | |
| base_version = version_str.split('-')[0].split('+')[0] | |
| try: | |
| version_parts = [int(x) for x in base_version.split('.')] | |
| except ValueError: | |
| print(f'Invalid npm version format: {version_str}') | |
| return True | |
| required_parts = [11, 10, 0] | |
| while len(version_parts) < 3: | |
| version_parts.append(0) | |
| if version_parts < required_parts: | |
| print( | |
| f'npm version {version_str} is too old. DevTools requires at least 11.10.0.' | |
| ) | |
| return True | |
| return False | |
| def run_npm_command(target=ROOT_TARGET): | |
| """Runs `npm install` and all post-processing steps. Returns True on error.""" | |
| if check_npm_version(): | |
| return True | |
| with open(target.package_json_path(), 'r', encoding='utf-8') as pkg_file: | |
| pkg_data = load_json_file(pkg_file) | |
| unpinned = find_unpinned_dependencies(pkg_data) | |
| if unpinned: | |
| for section, name, version in unpinned: | |
| print(f'{target.package_json_relpath()} ({section}.{name}): ' | |
| f'version {version!r} must be pinned to an exact version.') | |
| return True | |
| # Modern npm versions do not cause extra updates so it is not necessary to | |
| # run clean install. Explicitly pass the repo root .npmrc via --userconfig | |
| # and strip npm_config_* environment variables so sub-targets (e.g. | |
| # for_agents/) inherit all supply-chain settings (ignore-scripts, registry, | |
| # min-release-age) without being overridden by ~/.npmrc or env vars. | |
| npmrc_path = path.join(devtools_paths.devtools_root_path(), '.npmrc') | |
| npm_env = { | |
| key: value | |
| for key, value in os.environ.items() | |
| if not key.lower().startswith('npm_config_') | |
| } | |
| if exec_command(['npm', 'install', f'--userconfig={npmrc_path}'], | |
| cwd=target.root_dir(), | |
| env=npm_env): | |
| return True | |
| if target.remove_dependencies and remove_package_json_entries(target): | |
| return True | |
| if target.fix_chai: | |
| fixChaiExports(target) | |
| if apply_patches(target.patches): | |
| return True | |
| return ensure_licenses(target) | |
| # --- Archive production ----------------------------------------------------- | |
| def tree_stats(directory): | |
| """Returns (file_count, total_bytes) for regular files below directory.""" | |
| count = 0 | |
| total = 0 | |
| for root, _, files in os.walk(directory): | |
| for name in files: | |
| full = path.join(root, name) | |
| if path.islink(full): | |
| continue | |
| count += 1 | |
| total += path.getsize(full) | |
| return count, total | |
| def filter_node_modules(exclude_file=None, node_modules=None, staging=None): | |
| """Removes everything matched by the exclude list from node_modules. | |
| The rules are rsync filter rules (the same mechanism WebUI and | |
| chromium-bidi use for their archives): `+ pattern` keeps, `pattern` | |
| excludes, first match wins. The filtered tree is produced next to | |
| node_modules and then swapped into place, so after this step developers | |
| run with exactly the tree bots will download. | |
| Returns True on error. | |
| """ | |
| exclude_file = exclude_file or exclude_file_path() | |
| node_modules = (node_modules | |
| or devtools_paths.node_modules_path()).rstrip(os.sep) | |
| # Stage next to node_modules rather than under out/: out/ may live on a | |
| # different filesystem, where os.rename() fails with EXDEV. | |
| staging = staging or node_modules + '.filtered' | |
| old = node_modules + '.old' | |
| if not path.isfile(exclude_file): | |
| print(f'Exclude list {exclude_file} does not exist.') | |
| return True | |
| if not path.isdir(node_modules): | |
| print(f'{node_modules} does not exist; run without --skip-install.') | |
| return True | |
| rsync = shutil.which('rsync') | |
| if not rsync: | |
| print('Filtering node_modules requires rsync (run on Linux or macOS).') | |
| return True | |
| for leftover in (staging, old): | |
| if path.lexists(leftover): | |
| shutil.rmtree(leftover) | |
| os.makedirs(staging) | |
| cmd = [ | |
| rsync, | |
| '-rlp', | |
| f'--exclude-from={exclude_file}', | |
| '--prune-empty-dirs', | |
| node_modules + os.sep, | |
| staging + os.sep, | |
| ] | |
| before = tree_stats(node_modules) | |
| try: | |
| subprocess.check_call(cmd) | |
| except (OSError, subprocess.CalledProcessError) as error: | |
| print(f'rsync failed: {error}') | |
| shutil.rmtree(staging, ignore_errors=True) | |
| return True | |
| after = tree_stats(staging) | |
| # Swap the filtered tree into place, restoring the original if the swap | |
| # fails so the checkout is never left without node_modules. | |
| os.rename(node_modules, old) | |
| try: | |
| os.rename(staging, node_modules) | |
| except OSError as error: | |
| os.rename(old, node_modules) | |
| shutil.rmtree(staging, ignore_errors=True) | |
| print(f'Could not move the filtered tree into place: {error}') | |
| return True | |
| shutil.rmtree(old) | |
| print('Filtered node_modules with %s:' % | |
| path.relpath(exclude_file, devtools_paths.devtools_root_path())) | |
| print(' before: %6d files, %6.1f MB' % (before[0], before[1] / 1e6)) | |
| print(' after: %6d files, %6.1f MB' % (after[0], after[1] / 1e6)) | |
| return False | |
| # A node_modules/ path, optionally preceded by a GN root-relative prefix | |
| # (`//.../`) or relative path segments (`../../`, `extensions/e2e/`, ...) so | |
| # that references to *other* node_modules directories can be distinguished from | |
| # references to our node_modules/. | |
| REFERENCE_PATTERN = re.compile( | |
| r'(?P<prefix>(?://(?:[\w.\-]+/)*|(?:[\w.\-]+/)+))?' | |
| r'node_modules/(?P<reference>[A-Za-z0-9@._\-/]+)') | |
| REFERENCE_FILE_SUFFIXES = ('.gn', '.gni', '.py') | |
| REFERENCE_SKIP_FILE_SUFFIXES = ('_unittest.py', '_test.py') | |
| def _reference_matches_target(prefix, dirpath, root_abs, target): | |
| """Returns True if the prefix before `node_modules/` points at target.""" | |
| if not prefix: | |
| return not target.rel_dir or dirpath == root_abs | |
| if prefix.startswith('//'): | |
| return prefix[2:].rstrip('/') == target.rel_dir | |
| stripped = prefix.rstrip('/') | |
| if target.rel_dir and stripped == target.rel_dir: | |
| return True | |
| if all(part in ('.', '..') for part in stripped.split('/')): | |
| return path.normpath(path.join(dirpath, stripped)) == root_abs | |
| return False | |
| def referenced_node_module_paths(root=None, target=ROOT_TARGET): | |
| """Collects node_modules/ paths mentioned in GN and Python build files.""" | |
| root = root or target.root_dir() | |
| references = set() | |
| if not path.isdir(root): | |
| return references | |
| root_abs = path.abspath(root) | |
| for dirpath, dirnames, filenames in os.walk(root_abs): | |
| dirnames[:] = sorted(d for d in dirnames | |
| if d not in target.reference_skip_dirs) | |
| for filename in filenames: | |
| if (not filename.endswith(REFERENCE_FILE_SUFFIXES) | |
| or filename.endswith(REFERENCE_SKIP_FILE_SUFFIXES)): | |
| continue | |
| try: | |
| with open(path.join(dirpath, filename), | |
| encoding='utf-8', | |
| errors='replace') as f: | |
| content = f.read() | |
| except OSError: | |
| continue | |
| for match in REFERENCE_PATTERN.finditer(content): | |
| prefix = match.group('prefix') or '' | |
| if not _reference_matches_target(prefix, dirpath, root_abs, | |
| target): | |
| continue # Some other node_modules directory. | |
| reference = match.group('reference').rstrip('/') | |
| # Skip globs and fragments like `node_modules/${name}`. | |
| if reference and not reference.endswith(('*', '.')): | |
| references.add(reference) | |
| return references | |
| def verify_references(node_modules=None, root=None, target=ROOT_TARGET): | |
| """Fails if a node_modules path referenced by the build is missing. | |
| Returns True on error. | |
| """ | |
| node_modules = node_modules or target.node_modules_path() | |
| references = referenced_node_module_paths(root, target) | |
| missing = sorted(reference for reference in references | |
| if not path.lexists(path.join(node_modules, reference))) | |
| print('Checked %d node_modules paths referenced from GN/Python files.' % | |
| len(references)) | |
| if missing: | |
| print('Missing from %s:' % node_modules) | |
| for reference in missing: | |
| print(' ' + reference) | |
| return True | |
| return False | |
| def normalize_tar_info(info): | |
| """Drops everything from a TarInfo that varies between machines.""" | |
| info.uid = 0 | |
| info.gid = 0 | |
| info.uname = '' | |
| info.gname = '' | |
| info.mtime = 0 | |
| if info.isdir(): | |
| info.mode = 0o755 | |
| elif info.isreg(): | |
| info.mode = 0o755 if info.mode & 0o111 else 0o644 | |
| else: | |
| info.mode = 0o777 | |
| return info | |
| def iter_archive_entries(src_dir): | |
| """Returns the sorted relative paths to archive below src_dir. | |
| gclient-managed stamp files and a stale archive are skipped so that an | |
| archive rebuilt from an extracted tree is identical to the original. | |
| """ | |
| entries = [] | |
| for dirpath, dirnames, filenames in os.walk(src_dir): | |
| rel_dir = path.relpath(dirpath, src_dir) | |
| if rel_dir == '.': | |
| rel_dir = '' | |
| filenames = [ | |
| f for f in filenames if not GCLIENT_ARTIFACT_PATTERNS.match(f) | |
| ] | |
| for name in dirnames + filenames: | |
| entries.append(path.join(rel_dir, name) if rel_dir else name) | |
| # Sort on the archive name so the order is the same on every platform. | |
| entries.sort(key=lambda entry: entry.replace(os.sep, '/')) | |
| return entries | |
| class HashingWriter: | |
| """File-like wrapper that hashes everything written through it.""" | |
| def __init__(self, target): | |
| self._target = target | |
| self._offset = 0 | |
| self.sha256 = hashlib.sha256() | |
| def write(self, data): | |
| self.sha256.update(data) | |
| self._offset += len(data) | |
| return self._target.write(data) | |
| def tell(self): | |
| return self._offset | |
| def flush(self): | |
| self._target.flush() | |
| def create_archive(src_dir, out_path): | |
| """Writes a deterministic tar.gz of src_dir to out_path. | |
| The archive contains the *contents* of src_dir at its root (gclient | |
| extracts it straight into the dependency directory). Ownership, times and | |
| permission noise are normalized so that the same tree always produces the | |
| same bytes, which makes the sha256 in DEPS reproducible by reviewers and | |
| re-uploads idempotent. | |
| Returns (sha256 of the .tar.gz, sha256 of the uncompressed tar stream). | |
| The latter does not depend on the zlib build used for compression. | |
| """ | |
| src_dir = path.abspath(src_dir) | |
| src_real = path.realpath(src_dir) | |
| if not path.isdir(src_dir): | |
| raise ValueError(f'{src_dir} is not a directory') | |
| entries = iter_archive_entries(src_dir) | |
| if not entries: | |
| # Otherwise a clean checkout would produce (and could upload) an | |
| # empty archive without any error. | |
| raise ValueError(f'{src_dir} is empty; nothing to archive') | |
| os.makedirs(path.dirname(path.abspath(out_path)), exist_ok=True) | |
| with open(out_path, 'wb') as out_file: | |
| with gzip.GzipFile(filename='', | |
| mode='wb', | |
| fileobj=out_file, | |
| compresslevel=6, | |
| mtime=0) as gz: | |
| tar_stream = HashingWriter(gz) | |
| with tarfile.open(fileobj=tar_stream, | |
| mode='w', | |
| format=tarfile.GNU_FORMAT) as tar: | |
| for entry in entries: | |
| full = path.join(src_dir, entry) | |
| arcname = entry.replace(os.sep, '/') | |
| if path.islink(full): | |
| # gclient refuses archives whose links escape the | |
| # archive, and a dangling link means the exclude list | |
| # removed a target that is still needed. | |
| target = path.realpath(full) | |
| if not path.exists(full) or not ( | |
| target + os.sep).startswith(src_real + os.sep): | |
| raise ValueError( | |
| f'{arcname} is a symlink that does not resolve ' | |
| f'inside {src_dir}') | |
| info = normalize_tar_info( | |
| tar.gettarinfo(full, arcname=arcname)) | |
| if info.isreg(): | |
| with open(full, 'rb') as f: | |
| tar.addfile(info, f) | |
| else: | |
| tar.addfile(info) | |
| return sha256sum(out_path), tar_stream.sha256.hexdigest() | |
| def sha256sum(filename): | |
| sha = hashlib.sha256() | |
| with open(filename, 'rb') as f: | |
| for chunk in iter(lambda: f.read(1024 * 1024), b''): | |
| sha.update(chunk) | |
| return sha.hexdigest() | |
| def tar_stream_sha256(stream): | |
| """Returns the sha256 of the gzip-decompressed contents of stream.""" | |
| sha = hashlib.sha256() | |
| with gzip.GzipFile(fileobj=stream, mode='rb') as gz: | |
| for chunk in iter(lambda: gz.read(1024 * 1024), b''): | |
| sha.update(chunk) | |
| return sha.hexdigest() | |
| def archive_node_modules(archive_path, | |
| node_modules=None, | |
| gcs_prefix=GCS_PREFIX): | |
| """Builds the archive and prints its identity. | |
| Returns (sha256 of the archive, sha256 of the tar stream). | |
| """ | |
| node_modules = node_modules or devtools_paths.node_modules_path() | |
| digest, tar_digest = create_archive(node_modules, archive_path) | |
| size = path.getsize(archive_path) | |
| print('Created %s' % archive_path) | |
| print(' sha256: %s' % digest) | |
| print(' size: %d bytes (%.1f MB)' % (size, size / 1e6)) | |
| print(' object: gs://%s/%s/%s' % (GCS_BUCKET, gcs_prefix, digest)) | |
| return digest, tar_digest | |
| # --- DEPS and GCS ----------------------------------------------------------- | |
| def parse_deps_entry(deps_text, entry_name=DEPS_ENTRY_NAME): | |
| """Returns the gcs object pinned for entry_name in DEPS, or None. | |
| DEPS mixes single and double quotes, so both are accepted. | |
| """ | |
| q = r'[\'"]' | |
| match = re.search(r'^\s*%s%s%s\s*:\s*{' % (q, re.escape(entry_name), q), | |
| deps_text, re.MULTILINE) | |
| if not match: | |
| return None | |
| # Entries are dicts at two-space indentation; the block ends at the first | |
| # closing brace with that indentation. | |
| end = deps_text.find('\n }', match.end()) | |
| block = deps_text[match.end():end if end != -1 else None] | |
| if not re.search(r'%sdep_type%s\s*:\s*%sgcs%s' % (q, q, q, q), block): | |
| return None | |
| fields = {} | |
| for key, pattern in ( | |
| ('object_name', r'%sobject_name%s\s*:\s*%s([^\'"]+)%s' % (q, q, q, q)), | |
| ('sha256sum', | |
| r'%ssha256sum%s\s*:\s*%s([0-9a-f]{64})%s' % (q, q, q, q)), | |
| ('size_bytes', r'%ssize_bytes%s\s*:\s*(\d+)' % (q, q)), | |
| ('generation', r'%sgeneration%s\s*:\s*(\d+)' % (q, q)), | |
| ): | |
| field = re.search(pattern, block) | |
| if not field: | |
| return None | |
| value = field.group(1) | |
| fields[key] = int(value) if key in ('size_bytes', | |
| 'generation') else value | |
| return fields | |
| def format_deps_entry(object_name, | |
| digest, | |
| size, | |
| generation, | |
| entry_name=DEPS_ENTRY_NAME, | |
| condition='non_git_source'): | |
| """Renders the DEPS entry in the style used by the rest of DEPS.""" | |
| return '\n'.join([ | |
| " '%s': {" % entry_name, | |
| " 'dep_type': 'gcs',", | |
| " 'bucket': '%s'," % GCS_BUCKET, | |
| " 'condition': '%s'," % condition, | |
| " 'objects': [", | |
| " {", | |
| " 'object_name': '%s'," % object_name, | |
| " 'sha256sum': '%s'," % digest, | |
| " 'size_bytes': %d," % size, | |
| " 'generation': %d," % generation, | |
| " 'output_file': 'node_modules.tar.gz',", | |
| " },", | |
| " ],", | |
| " },", | |
| ]) | |
| def gcs_object_url(object_name): | |
| return '%s/%s/%s' % (GCS_PUBLIC_URL, GCS_BUCKET, object_name) | |
| def gcs_object_info(object_name): | |
| """Returns (size_bytes, generation) if the public object exists, else None.""" | |
| request = urllib.request.Request(gcs_object_url(object_name), | |
| method='HEAD') | |
| try: | |
| with urllib.request.urlopen(request, timeout=60) as response: | |
| size = int(response.headers.get('Content-Length', '0')) | |
| generation = int(response.headers.get('x-goog-generation', '0')) | |
| return size, generation | |
| except urllib.error.HTTPError as error: | |
| if error.code in (403, 404): | |
| return None | |
| raise | |
| def extract_json_blob(output): | |
| """Pulls the DEPS blob out of upload_to_google_storage_first_class output.""" | |
| start = output.find('{') | |
| if start == -1: | |
| raise ValueError('No JSON blob found in: %s' % output) | |
| return json.loads(output[start:]) | |
| def upload_archive(archive_path, deps_file=None, target=ROOT_TARGET): | |
| """Uploads the archive (if needed) and updates DEPS. Returns True on error.""" | |
| deps_file = deps_file or deps_file_path() | |
| digest = sha256sum(archive_path) | |
| size = path.getsize(archive_path) | |
| object_name = '%s/%s' % (target.gcs_prefix, digest) | |
| info = gcs_object_info(object_name) | |
| if info: | |
| remote_size, generation = info | |
| if remote_size != size: | |
| print('gs://%s/%s exists with size %d, expected %d' % | |
| (GCS_BUCKET, object_name, remote_size, size)) | |
| return True | |
| print('gs://%s/%s already exists, not uploading.' % | |
| (GCS_BUCKET, object_name)) | |
| else: | |
| uploader = path.join(depot_tools_path(), | |
| 'upload_to_google_storage_first_class.py') | |
| cmd = [ | |
| shutil.which('vpython3') or sys.executable, uploader, '--bucket', | |
| GCS_BUCKET, '--prefix', target.gcs_prefix, archive_path | |
| ] | |
| try: | |
| output = subprocess.check_output(cmd, text=True) | |
| except (OSError, subprocess.CalledProcessError) as error: | |
| print(f'Upload failed: {error}') | |
| return True | |
| print(output) | |
| try: | |
| uploaded = extract_json_blob(output)['path']['objects'][0] | |
| except (ValueError, KeyError, IndexError) as error: | |
| print(f'Could not parse the uploader output: {error}') | |
| return True | |
| if uploaded['object_name'] != object_name or uploaded[ | |
| 'sha256sum'] != digest: | |
| print('Uploader reported an unexpected object: %s' % uploaded) | |
| return True | |
| generation = int(uploaded['generation']) | |
| return update_deps(deps_file, | |
| object_name, | |
| digest, | |
| size, | |
| generation, | |
| entry_name=target.deps_entry, | |
| condition=target.deps_condition) | |
| def update_deps(deps_file, | |
| object_name, | |
| digest, | |
| size, | |
| generation, | |
| entry_name=DEPS_ENTRY_NAME, | |
| condition='non_git_source'): | |
| """Points the node_modules gcs entry in DEPS at the object. | |
| Returns True on error. | |
| """ | |
| with open(deps_file, encoding='utf-8') as f: | |
| deps_text = f.read() | |
| current = parse_deps_entry(deps_text, entry_name) | |
| if current is None: | |
| print('DEPS has no gcs entry named %r yet. Add this to `deps`:' % | |
| entry_name) | |
| print( | |
| format_deps_entry(object_name, digest, size, generation, | |
| entry_name, condition)) | |
| return False | |
| if current['object_name'] == object_name: | |
| print('DEPS already points at %s.' % object_name) | |
| return False | |
| cmd = [ | |
| shutil.which('vpython3') or sys.executable, | |
| path.join(depot_tools_path(), 'gclient.py'), | |
| 'setdep', | |
| '-r', | |
| '%s@%s,%s,%d,%d' % (entry_name, object_name, digest, size, generation), | |
| '--deps-file=%s' % deps_file, | |
| ] | |
| try: | |
| subprocess.check_call(cmd, cwd=devtools_paths.devtools_root_path()) | |
| except (OSError, subprocess.CalledProcessError) as error: | |
| print(f'gclient setdep failed: {error}') | |
| return True | |
| print('Updated %s to %s.' % (path.basename(deps_file), object_name)) | |
| return False | |
| def check_archive(archive_path, | |
| deps_file=None, | |
| node_modules=None, | |
| target=ROOT_TARGET): | |
| """Rebuilds the archive and compares it with DEPS. Returns True on error. | |
| The .tar.gz hash is compared first. Gzip output can differ between zlib | |
| builds even for identical input, so on a mismatch the pinned object is | |
| downloaded and the uncompressed tar streams are compared instead. | |
| """ | |
| deps_file = deps_file or deps_file_path() | |
| with open(deps_file, encoding='utf-8') as f: | |
| pinned = parse_deps_entry(f.read(), target.deps_entry) | |
| if pinned is None: | |
| print('DEPS has no gcs entry named %r.' % target.deps_entry) | |
| return True | |
| node_modules = node_modules or target.node_modules_path() | |
| digest, tar_digest = archive_node_modules(archive_path, node_modules, | |
| target.gcs_prefix) | |
| size = path.getsize(archive_path) | |
| if digest == pinned['sha256sum'] and size == pinned['size_bytes']: | |
| print('%s matches the archive pinned in DEPS.' % target.deps_entry) | |
| return False | |
| print('Archive differs from DEPS (%s, %d bytes); comparing contents with ' | |
| 'the pinned object...' % (pinned['sha256sum'], pinned['size_bytes'])) | |
| try: | |
| with urllib.request.urlopen(gcs_object_url(pinned['object_name']), | |
| timeout=600) as response: | |
| pinned_tar_digest = tar_stream_sha256(response) | |
| except (urllib.error.URLError, OSError) as error: | |
| print(f'Could not download the pinned object: {error}') | |
| return True | |
| if pinned_tar_digest != tar_digest: | |
| print('%s does not match DEPS:' % target.deps_entry) | |
| print(' DEPS tar stream: %s' % pinned_tar_digest) | |
| print(' local tar stream: %s' % tar_digest) | |
| return True | |
| print('%s matches the archive pinned in DEPS ' | |
| '(same contents, different gzip encoding).' % target.deps_entry) | |
| return False | |
| # --- Presubmit support ------------------------------------------------------ | |
| # Files whose content determines what ends up in the archive. PRESUBMIT.py | |
| # requires the DEPS entry to change together with them. | |
| ARCHIVE_INPUT_FILES = ('package-lock.json', 'scripts/deps/npm_exclude.txt') | |
| ARCHIVE_INPUT_DIRS = ('scripts/deps/node_module_patches/', ) | |
| def package_json_dependencies(text): | |
| data = json.loads(text) | |
| return {key: data.get(key) for key in PACKAGE_JSON_DEPENDENCY_KEYS} | |
| def archive_inputs_changed(changed_files, | |
| old_package_json=None, | |
| new_package_json=None): | |
| """Returns the changed repo-relative paths that require a new archive. | |
| old/new_package_json are the file contents when package.json changed. | |
| """ | |
| hits = [ | |
| f for f in changed_files | |
| if f in ARCHIVE_INPUT_FILES or f.startswith(ARCHIVE_INPUT_DIRS) | |
| ] | |
| if old_package_json is not None and ( | |
| package_json_dependencies(old_package_json) | |
| != package_json_dependencies(new_package_json)): | |
| hits.append('package.json') | |
| return sorted(hits) | |
| def deps_entry_changed(old_deps_text, new_deps_text): | |
| return parse_deps_entry(old_deps_text) != parse_deps_entry(new_deps_text) | |
| def check_deps_entry(deps_text): | |
| """Returns problems with the node_modules entry, as strings.""" | |
| entry = parse_deps_entry(deps_text) | |
| if entry is None: | |
| return ['DEPS has no gcs entry named %r.' % DEPS_ENTRY_NAME] | |
| expected = '%s/%s' % (GCS_PREFIX, entry['sha256sum']) | |
| if entry['object_name'] != expected: | |
| return [ | |
| 'DEPS: %r object_name must be %s (objects are named by their ' | |
| 'sha256).' % (DEPS_ENTRY_NAME, expected) | |
| ] | |
| return [] | |
| # --- Entry point ------------------------------------------------------------ | |
| def parse_args(argv): | |
| parser = argparse.ArgumentParser( | |
| description=__doc__, | |
| formatter_class=argparse.RawDescriptionHelpFormatter) | |
| parser.add_argument('--skip-install', | |
| action='store_true', | |
| help="Don't run npm install; use the existing tree.") | |
| parser.add_argument('--exclude-file', | |
| default=None, | |
| help='Exclude list ' | |
| '(default: scripts/deps/npm_exclude.txt).') | |
| parser.add_argument('--archive-path', | |
| default=None, | |
| help='Where to write the archive ' | |
| '(default: out/node_modules.tar.gz).') | |
| parser.add_argument('--upload', | |
| action='store_true', | |
| help='Upload the archive to GCS and update DEPS.') | |
| parser.add_argument('--check', | |
| action='store_true', | |
| help='Only compare a rebuilt archive with DEPS.') | |
| parser.add_argument('--deps-file', | |
| default=None, | |
| help='DEPS file to read/update (default: ./DEPS).') | |
| return parser.parse_args(argv) | |
| def main(argv=None): | |
| args = parse_args(argv if argv is not None else sys.argv[1:]) | |
| archive_path = args.archive_path or default_archive_path() | |
| try: | |
| if args.check: | |
| return 1 if check_archive(archive_path, args.deps_file) else 0 | |
| if not args.skip_install and run_npm_command(): | |
| print('npm command failed') | |
| return 1 | |
| if filter_node_modules(args.exclude_file): | |
| return 1 | |
| if verify_references(): | |
| return 1 | |
| archive_node_modules(archive_path) | |
| except ValueError as error: | |
| # Raised by create_archive() for a missing/empty tree or a symlink | |
| # that gclient would refuse; never upload such an archive. | |
| print(f'Cannot archive node_modules: {error}') | |
| return 1 | |
| if args.upload and upload_archive(archive_path, args.deps_file): | |
| return 1 | |
| return 0 | |
| if __name__ == '__main__': | |
| sys.exit(main()) |