blob: 9b579e10a311dfe19ed13aabbeed3b5612a29f5f [file] [log] [blame]
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -08001#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3# Copyright 2021 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6""" This script cleans up the vendor directory.
7"""
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -07008import argparse
George Burgess IV635f7262022-08-09 21:32:20 -07009import collections
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +000010import hashlib
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -080011import json
12import os
13import pathlib
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -070014import re
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -070015import shutil
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +000016import subprocess
George Burgess IV04833702022-08-09 22:00:38 -070017import textwrap
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -070018import toml
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +000019
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -070020# We only care about crates we're actually going to use and that's usually
21# limited to ones with cfg(linux). For running `cargo metadata`, limit results
22# to only this platform
23DEFAULT_PLATFORM_FILTER = "x86_64-unknown-linux-gnu"
24
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +000025
26def _rerun_checksums(package_path):
27 """Re-run checksums for given package.
28
29 Writes resulting checksums to $package_path/.cargo-checksum.json.
30 """
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -070031 hashes = dict()
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +000032 checksum_path = os.path.join(package_path, '.cargo-checksum.json')
33 if not pathlib.Path(checksum_path).is_file():
34 return False
35
36 with open(checksum_path, 'r') as fread:
37 contents = json.load(fread)
38
39 for root, _, files in os.walk(package_path, topdown=True):
40 for f in files:
41 # Don't checksum an existing checksum file
42 if f == ".cargo-checksum.json":
43 continue
44
45 file_path = os.path.join(root, f)
46 with open(file_path, 'rb') as frb:
47 m = hashlib.sha256()
48 m.update(frb.read())
49 d = m.hexdigest()
50
51 # Key is relative to the package path so strip from beginning
52 key = os.path.relpath(file_path, package_path)
53 hashes[key] = d
54
55 if hashes:
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -070056 print("{} regenerated {} hashes".format(package_path,
57 len(hashes.keys())))
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +000058 contents['files'] = hashes
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +000059 with open(checksum_path, 'w') as fwrite:
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -070060 json.dump(contents, fwrite, sort_keys=True)
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +000061
62 return True
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -080063
64
65def _remove_OWNERS_checksum(root):
66 """ Delete all OWNERS files from the checksum file.
67
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +000068 Args:
69 root: Root directory for the vendored crate.
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -080070
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +000071 Returns:
72 True if OWNERS was found and cleaned up. Otherwise False.
73 """
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -080074 checksum_path = os.path.join(root, '.cargo-checksum.json')
75 if not pathlib.Path(checksum_path).is_file():
76 return False
77
78 with open(checksum_path, 'r') as fread:
79 contents = json.load(fread)
80
81 del_keys = []
82 for cfile in contents['files']:
83 if 'OWNERS' in cfile:
84 del_keys.append(cfile)
85
86 for key in del_keys:
87 del contents['files'][key]
88
89 if del_keys:
90 print('{} deleted: {}'.format(root, del_keys))
91 with open(checksum_path, 'w') as fwrite:
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -070092 json.dump(contents, fwrite, sort_keys=True)
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -080093
94 return bool(del_keys)
95
96
97def cleanup_owners(vendor_path):
98 """ Remove owners checksums from the vendor directory.
99
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000100 We currently do not check in the OWNERS files from vendored crates because
101 they interfere with the find-owners functionality in gerrit. This cleanup
102 simply finds all instances of "OWNERS" in the checksum files within and
103 removes them.
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -0800104
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000105 Args:
106 vendor_path: Absolute path to vendor directory.
107 """
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -0800108 deps_cleaned = []
109 for root, dirs, _ in os.walk(vendor_path):
110 for d in dirs:
111 removed = _remove_OWNERS_checksum(os.path.join(root, d))
112 if removed:
113 deps_cleaned.append(d)
114
115 if deps_cleaned:
116 print('Cleanup owners:\n {}'.format("\n".join(deps_cleaned)))
117
118
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000119def apply_single_patch(patch, workdir):
120 """Apply a single patch and return whether it was successful.
121
122 Returns:
123 True if successful. False otherwise.
124 """
George Burgess IV635f7262022-08-09 21:32:20 -0700125 print(f"-- Applying {patch} to {workdir}")
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000126 proc = subprocess.run(["patch", "-p1", "-i", patch], cwd=workdir)
127 return proc.returncode == 0
128
129
George Burgess IV635f7262022-08-09 21:32:20 -0700130def determine_vendor_crates(vendor_path):
131 """Returns a map of {crate_name: [directory]} at the given vendor_path."""
132 result = collections.defaultdict(list)
133 for crate_name_plus_ver in os.listdir(vendor_path):
George Burgess IV40cc91c2022-08-15 13:07:40 -0700134 name, _ = crate_name_plus_ver.rsplit('-', 1)
135 result[name].append(crate_name_plus_ver)
George Burgess IV635f7262022-08-09 21:32:20 -0700136
137 for crate_list in result.values():
George Burgess IV40cc91c2022-08-15 13:07:40 -0700138 crate_list.sort()
George Burgess IV635f7262022-08-09 21:32:20 -0700139 return result
140
141
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000142def apply_patches(patches_path, vendor_path):
143 """Finds patches and applies them to sub-folders in the vendored crates.
144
145 Args:
146 patches_path: Path to folder with patches. Expect all patches to be one
147 level down (matching the crate name).
148 vendor_path: Root path to vendored crates directory.
149 """
150 checksums_for = {}
151
152 # Don't bother running if patches directory is empty
153 if not pathlib.Path(patches_path).is_dir():
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700154 return
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000155
George Burgess IV635f7262022-08-09 21:32:20 -0700156 vendor_crate_map = determine_vendor_crates(vendor_path)
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000157 # Look for all patches and apply them
158 for d in os.listdir(patches_path):
159 dir_path = os.path.join(patches_path, d)
160
161 # We don't process patches in root dir
162 if not os.path.isdir(dir_path):
163 continue
164
George Burgess IV635f7262022-08-09 21:32:20 -0700165 for patch in os.listdir(dir_path):
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000166 file_path = os.path.join(dir_path, patch)
167
168 # Skip if not a patch file
169 if not os.path.isfile(file_path) or not patch.endswith(".patch"):
170 continue
171
George Burgess IV635f7262022-08-09 21:32:20 -0700172 # We accept one of two forms here:
173 # - direct targets (these name # `${crate_name}-${version}`)
174 # - simply the crate name (which applies to all versions of the
175 # crate)
176 direct_target = os.path.join(vendor_path, d)
177 if os.path.isdir(direct_target):
178 # If there are any patches, queue checksums for that folder.
179 checksums_for[d] = True
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000180
George Burgess IV635f7262022-08-09 21:32:20 -0700181 # Apply the patch. Exit from patch loop if patching failed.
182 if not apply_single_patch(file_path, direct_target):
183 print("Failed to apply patch: {}".format(patch))
184 break
185 elif d in vendor_crate_map:
186 for crate in vendor_crate_map[d]:
187 checksums_for[crate] = True
188 target = os.path.join(vendor_path, crate)
189 if not apply_single_patch(file_path, target):
190 print(f'Failed to apply patch {patch} to {target}')
191 break
192 else:
193 raise RuntimeError(f'Unknown crate in {vendor_path}: {d}')
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000194
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000195 # Re-run checksums for all modified packages since we applied patches.
196 for key in checksums_for.keys():
197 _rerun_checksums(os.path.join(vendor_path, key))
198
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700199
George Burgess IV40cc91c2022-08-15 13:07:40 -0700200def fetch_project_cargo_toml_files(working_dir):
201 """Returns all Cargo.toml files under working_dir."""
202 projects = working_dir / 'projects'
203 return sorted(projects.glob('**/Cargo.toml'))
204
205
Abhishek Pandit-Subedifa902382021-08-20 11:04:33 -0700206def run_cargo_vendor(working_dir):
207 """Runs cargo vendor.
208
209 Args:
210 working_dir: Directory to run inside. This should be the directory where
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -0700211 Cargo.toml is kept.
Abhishek Pandit-Subedifa902382021-08-20 11:04:33 -0700212 """
George Burgess IV635f7262022-08-09 21:32:20 -0700213 # Cargo will refuse to revendor into versioned directories, which leads to
214 # repeated `./vendor.py` invocations trying to apply patches to
215 # already-patched sources. Remove the existing vendor directory to avoid
216 # this.
217 vendor_dir = working_dir / 'vendor'
218 if vendor_dir.exists():
George Burgess IV40cc91c2022-08-15 13:07:40 -0700219 shutil.rmtree(vendor_dir)
220
221 cargo_cmdline = ['cargo', 'vendor', '--versioned-dirs', '-v']
222 for i, cargo_toml in enumerate(fetch_project_cargo_toml_files(working_dir)):
223 # `cargo vendor` requires a 'root' manifest; select an arbitrary one,
224 # then tack other manifests on to it. Order doesn't really matter.
225 if i == 0:
226 cargo_cmdline.append('--manifest-path')
227 else:
228 cargo_cmdline.append('-s')
229 cargo_cmdline.append(str(cargo_toml))
230
231 # Autocreate src/lib.rs if necessary.
232 lib_rs = cargo_toml.parent / 'src' / 'lib.rs'
233 if not lib_rs.exists():
234 lib_rs.parent.mkdir(exist_ok=True)
235 lib_rs.write_bytes(b'')
236
237 # Always place vendor/ at the top-level directory.
238 cargo_cmdline += ('--', 'vendor')
239 subprocess.check_call(cargo_cmdline, cwd=working_dir)
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000240
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -0700241
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700242def load_metadata(working_dir, filter_platform=DEFAULT_PLATFORM_FILTER):
George Burgess IV40cc91c2022-08-15 13:07:40 -0700243 """Load metadata for all projects under a given directory.
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700244
245 Args:
George Burgess IV40cc91c2022-08-15 13:07:40 -0700246 working_dir: Base directory to run from.
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700247 filter_platform: Filter packages to ones configured for this platform.
248 """
George Burgess IV40cc91c2022-08-15 13:07:40 -0700249 metadata_objects = []
250 for manifest_path in fetch_project_cargo_toml_files(working_dir):
251 cmd = [
252 'cargo', 'metadata', '--format-version', '1', '--manifest-path',
253 manifest_path
254 ]
255 # Conditionally add platform filter
256 if filter_platform:
257 cmd += ("--filter-platform", filter_platform)
258 output = subprocess.check_output(cmd, cwd=working_dir)
259 metadata_objects.append(json.loads(output))
260 return metadata_objects
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700261
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700262
George Burgess IV40cc91c2022-08-15 13:07:40 -0700263def load_all_metadata_packages(working_dir,
264 filter_platform=DEFAULT_PLATFORM_FILTER,
265 unique=False):
266 """Returns a list of all packages returned by load_metadata."""
267 results = []
268 for metadata in load_metadata(working_dir, filter_platform):
269 results += metadata['packages']
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700270
George Burgess IV40cc91c2022-08-15 13:07:40 -0700271 if not unique:
272 return results
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700273
George Burgess IV40cc91c2022-08-15 13:07:40 -0700274 new_results = []
275 seen_keys = set()
276 for item in results:
277 key = item['id']
278 if key in seen_keys:
279 continue
280 seen_keys.add(key)
281 new_results.append(item)
282 return new_results
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700283
284class LicenseManager:
285 """ Manage consolidating licenses for all packages."""
286
287 # These are all the licenses we support. Keys are what is seen in metadata and
288 # values are what is expected by the ebuild.
289 SUPPORTED_LICENSES = {
290 'Apache-2.0': 'Apache-2.0',
291 'MIT': 'MIT',
292 'BSD-3-Clause': 'BSD-3',
George Burgess IV4ae42062022-08-15 18:54:51 -0700293 'ISC': 'ISC',
294 'unicode': 'unicode',
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700295 }
296
297 # Prefer to take attribution licenses in this order. All these require that
298 # we actually use the license file found in the package so they MUST have
299 # a license file set.
300 PREFERRED_ATTRIB_LICENSE_ORDER = ['MIT', 'BSD-3', 'ISC']
301
302 # If Apache license is found, always prefer it (simplifies attribution)
303 APACHE_LICENSE = 'Apache-2.0'
304
305 # Regex for license files found in the vendored directories. Search for
306 # these files with re.IGNORECASE.
307 #
308 # These will be searched in order with the earlier entries being preferred.
309 LICENSE_NAMES_REGEX = [
310 r'^license-mit$',
311 r'^copyright$',
312 r'^licen[cs]e.*$',
313 ]
314
315 # Some crates have their license file in other crates. This usually occurs
316 # because multiple crates are published from the same git repository and the
317 # license isn't updated in each sub-crate. In these cases, we can just
318 # ignore these packages.
319 MAP_LICENSE_TO_OTHER = {
320 'failure_derive': 'failure',
321 'grpcio-compiler': 'grpcio',
322 'grpcio-sys': 'grpcio',
323 'rustyline-derive': 'rustyline',
324 }
325
326 # Map a package to a specific license and license file. Only use this if
327 # a package doesn't have an easily discoverable license or exports its
328 # license in a weird way. Prefer to patch the project with a license and
329 # upstream the patch instead.
330 STATIC_LICENSE_MAP = {
331 # "package name": ( "license name", "license file relative location")
332 }
333
334 def __init__(self, working_dir, vendor_dir):
335 self.working_dir = working_dir
336 self.vendor_dir = vendor_dir
337
338 def _find_license_in_dir(self, search_dir):
339 for p in os.listdir(search_dir):
340 # Ignore anything that's not a file
341 if not os.path.isfile(os.path.join(search_dir, p)):
342 continue
343
344 # Now check if the name matches any of the regexes
345 # We'll return the first matching file.
346 for regex in self.LICENSE_NAMES_REGEX:
347 if re.search(regex, p, re.IGNORECASE):
348 yield os.path.join(search_dir, p)
349 break
350
351 def _guess_license_type(self, license_file):
352 if '-MIT' in license_file:
353 return 'MIT'
354 elif '-APACHE' in license_file:
355 return 'APACHE'
356 elif '-BSD' in license_file:
357 return 'BSD-3'
358
359 with open(license_file, 'r') as f:
360 lines = f.read()
361 if 'MIT' in lines:
362 return 'MIT'
363 elif 'Apache' in lines:
364 return 'APACHE'
365 elif 'BSD 3-Clause' in lines:
366 return 'BSD-3'
367
368 return ''
369
George Burgess IV04833702022-08-09 22:00:38 -0700370 def generate_license(self, skip_license_check, print_map_to_file,
371 license_shorthand_file):
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700372 """Generate single massive license file from metadata."""
George Burgess IV40cc91c2022-08-15 13:07:40 -0700373 all_packages = load_all_metadata_packages(self.working_dir, unique=True)
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700374
375 has_license_types = set()
376 bad_licenses = {}
377
378 # Keep license map ordered so it generates a consistent license map
379 license_map = {}
380
381 skip_license_check = skip_license_check or []
George Burgess IV4ae42062022-08-15 18:54:51 -0700382 has_unicode_license = False
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700383
George Burgess IV40cc91c2022-08-15 13:07:40 -0700384 for package in all_packages:
385 # Skip the synthesized Cargo.toml packages that exist solely to
386 # list dependencies.
387 if 'path+file:///' in package['id']:
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700388 continue
389
George Burgess IV40cc91c2022-08-15 13:07:40 -0700390 pkg_name = package['name']
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700391 if pkg_name in skip_license_check:
392 print(
393 "Skipped license check on {}. Reason: Skipped from command line"
394 .format(pkg_name))
395 continue
396
397 if pkg_name in self.MAP_LICENSE_TO_OTHER:
398 print(
399 'Skipped license check on {}. Reason: License already in {}'
400 .format(pkg_name, self.MAP_LICENSE_TO_OTHER[pkg_name]))
401 continue
402
403 # Check if we have a static license map for this package. Use the
404 # static values if we have it already set.
405 if pkg_name in self.STATIC_LICENSE_MAP:
406 (license, license_file) = self.STATIC_LICENSE_MAP[pkg_name]
407 license_map[pkg_name] = {
408 "license": license,
409 "license_file": license_file,
410 }
411 continue
412
413 license_files = []
George Burgess IV93ba4732022-08-13 14:10:10 -0700414 # use `or ''` instead of get's default, since `package` may have a
415 # None value for 'license'.
416 license = package.get('license') or ''
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700417
418 # We ignore the metadata for license file because most crates don't
419 # have it set. Just scan the source for licenses.
George Burgess IV635f7262022-08-09 21:32:20 -0700420 pkg_version = package['version']
George Burgess IV40cc91c2022-08-15 13:07:40 -0700421 license_files = list(self._find_license_in_dir(
422 os.path.join(self.vendor_dir, f'{pkg_name}-{pkg_version}')))
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700423
George Burgess IV4ae42062022-08-15 18:54:51 -0700424 # FIXME(b/240953811): The code later in this loop is only
425 # structured to handle ORs, not ANDs. Fortunately, this license in
426 # particular is `AND`ed between a super common license (Apache) and
427 # a more obscure one (unicode). This hack is specifically intended
428 # for the `unicode-ident` crate, though no crate name check is
429 # made, since it's OK other crates happen to have this license.
430 if license == '(MIT OR Apache-2.0) AND Unicode-DFS-2016':
431 has_unicode_license = True
432 # We'll check later to be sure MIT or Apache-2.0 is represented
433 # properly.
434 for x in license_files:
435 if os.path.basename(x) == 'LICENSE-UNICODE':
436 license_file = x
437 break
438 else:
439 raise ValueError('No LICENSE-UNICODE found in '
440 f'{license_files}')
441 license_map[pkg_name] = {
442 "license": license,
443 "license_file": license_file,
444 }
445 has_license_types.add('unicode')
446 continue
447
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700448 # If there are multiple licenses, they are delimited with "OR" or "/"
449 delim = ' OR ' if ' OR ' in license else '/'
George Burgess IV40cc91c2022-08-15 13:07:40 -0700450 found = [x.strip() for x in license.split(delim)]
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700451
452 # Filter licenses to ones we support
453 licenses_or = [
454 self.SUPPORTED_LICENSES[f] for f in found
455 if f in self.SUPPORTED_LICENSES
456 ]
457
458 # If apache license is found, always prefer it because it simplifies
459 # license attribution (we can use existing Apache notice)
460 if self.APACHE_LICENSE in licenses_or:
461 has_license_types.add(self.APACHE_LICENSE)
462 license_map[pkg_name] = {'license': self.APACHE_LICENSE}
463
464 # Handle single license that has at least one license file
465 # We pick the first license file and the license
466 elif len(licenses_or) == 1:
467 if license_files:
468 l = licenses_or[0]
469 lf = license_files[0]
470
471 has_license_types.add(l)
472 license_map[pkg_name] = {
473 'license': l,
474 'license_file': os.path.relpath(lf, self.working_dir),
475 }
476 else:
477 bad_licenses[pkg_name] = "{} missing license file".format(
478 licenses_or[0])
479 # Handle multiple licenses
480 elif len(licenses_or) > 1:
481 # Check preferred licenses in order
482 license_found = False
483 for l in self.PREFERRED_ATTRIB_LICENSE_ORDER:
484 if not l in licenses_or:
485 continue
486
487 for f in license_files:
488 if self._guess_license_type(f) == l:
489 license_found = True
490 has_license_types.add(l)
491 license_map[pkg_name] = {
492 'license':
493 l,
494 'license_file':
495 os.path.relpath(f, self.working_dir),
496 }
497 break
498
499 # Break out of loop if license is found
500 if license_found:
501 break
502 else:
503 bad_licenses[pkg_name] = license
504
505 # If we had any bad licenses, we need to abort
506 if bad_licenses:
507 for k in bad_licenses.keys():
508 print("{} had no acceptable licenses: {}".format(
509 k, bad_licenses[k]))
510 raise Exception("Bad licenses in vendored packages.")
511
512 # Write license map to file
513 if print_map_to_file:
514 with open(os.path.join(self.working_dir, print_map_to_file),
515 'w') as lfile:
516 json.dump(license_map, lfile, sort_keys=True)
517
518 # Raise missing licenses unless we have a valid reason to ignore them
519 raise_missing_license = False
520 for name, v in license_map.items():
521 if 'license_file' not in v and v.get('license',
522 '') != self.APACHE_LICENSE:
523 raise_missing_license = True
524 print(" {}: Missing license file. Fix or add to ignorelist.".
525 format(name))
526
527 if raise_missing_license:
528 raise Exception(
529 "Unhandled missing license file. "
530 "Make sure all are accounted for before continuing.")
531
George Burgess IV4ae42062022-08-15 18:54:51 -0700532 if has_unicode_license:
533 if self.APACHE_LICENSE not in has_license_types:
534 raise ValueError('Need the apache license; currently have: '
535 f'{sorted(has_license_types)}')
536
George Burgess IV04833702022-08-09 22:00:38 -0700537 sorted_licenses = sorted(has_license_types)
538 print("Add the following licenses to the ebuild:\n",
539 sorted_licenses)
540 header = textwrap.dedent("""\
541 # File to describe the licenses used by this registry.
542 # Used to it's easy to automatically verify ebuilds are updated.
543 # Each line is a license. Lines starting with # are comments.
544 """)
545 with open(license_shorthand_file, 'w', encoding='utf-8') as f:
546 f.write(header)
547 f.write('\n'.join(sorted_licenses))
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700548
549
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -0700550# TODO(abps) - This needs to be replaced with datalog later. We should compile
551# all crab files into datalog and query it with our requirements
552# instead.
553class CrabManager:
554 """Manage audit files."""
555 def __init__(self, working_dir, crab_dir):
556 self.working_dir = working_dir
557 self.crab_dir = crab_dir
558
559 def _check_bad_traits(self, crabdata):
560 """Checks that a package's crab audit meets our requirements.
561
562 Args:
563 crabdata: Dict with crab keys in standard templated format.
564 """
565 common = crabdata['common']
566 # TODO(b/200578411) - Figure out what conditions we should enforce as
567 # part of the audit.
568 conditions = [
569 common.get('deny', None),
570 ]
571
572 # If any conditions are true, this crate is not acceptable.
573 return any(conditions)
574
575 def verify_traits(self):
576 """ Verify that all required CRAB traits for this repository are met.
577 """
George Burgess IV40cc91c2022-08-15 13:07:40 -0700578 all_packages = load_all_metadata_packages(self.working_dir, unique=True)
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -0700579
580 failing_crates = {}
581
582 # Verify all packages have a CRAB file associated with it and they meet
583 # all our required traits
George Burgess IV40cc91c2022-08-15 13:07:40 -0700584 for package in all_packages:
585 # Skip the synthesized Cargo.toml packages that exist solely to
586 # list dependencies.
587 if 'path+file:///' in package['id']:
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -0700588 continue
589
590 crabname = "{}-{}".format(package['name'], package['version'])
591 filename = os.path.join(self.crab_dir, "{}.toml".format(crabname))
592
593 # If crab file doesn't exist, the crate fails
594 if not os.path.isfile(filename):
595 failing_crates[crabname] = "No crab file".format(filename)
596 continue
597
598 with open(filename, 'r') as f:
599 crabdata = toml.loads(f.read())
600
601 # If crab file's crate_name and version keys don't match this
602 # package, it also fails. This is just housekeeping...
603 if package['name'] != crabdata['crate_name'] or package[
604 'version'] != crabdata['version']:
605 failing_crates[crabname] = "Crate name or version don't match"
606 continue
607
608 if self._check_bad_traits(crabdata):
609 failing_crates[crabname] = "Failed bad traits check"
610
611 # If we had any failing crates, list them now
612 if failing_crates:
613 print('Failed CRAB audit:')
614 for k, v in failing_crates.items():
615 print(' {}: {}'.format(k, v))
616
617
George Burgess IV0313d782022-08-15 23:45:44 -0700618def remove_all_target_dependencies_in_place(cargo_toml):
619 """Removes all `target.*.dependencies` from `toml`."""
620 target = cargo_toml.get('target')
621 if not target:
622 return
623
624 empty_keys = []
625 deps_key = 'dependencies'
626 for key, values in target.items():
627 if deps_key not in values:
628 continue
629
630 del values[deps_key]
631 if not values:
632 empty_keys.append(key)
633
634 if len(empty_keys) == len(target):
635 del cargo_toml['target']
636 else:
637 for key in empty_keys:
638 del target[key]
639
640
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700641class CrateDestroyer():
642 LIB_RS_BODY = """compile_error!("This crate cannot be built for this configuration.");\n"""
643
644 def __init__(self, working_dir, vendor_dir):
645 self.working_dir = working_dir
646 self.vendor_dir = vendor_dir
647
648 def _modify_cargo_toml(self, pkg_path):
649 with open(os.path.join(pkg_path, "Cargo.toml"), "r") as cargo:
650 contents = toml.load(cargo)
651
652 # Change description, license and delete license key
653 contents["package"]["description"] = "Empty crate that should not build."
654 contents["package"]["license"] = "Apache-2.0"
655 if contents["package"].get("license_file"):
656 del contents["package"]["license_file"]
657
George Burgess IV0313d782022-08-15 23:45:44 -0700658 # Some packages have cfg-specific dependencies. Remove them here; we
659 # don't care about the dependencies of an empty package.
660 #
661 # This is a load-bearing optimization: `dev-python/toml` doesn't
662 # always round-trip dumps(loads(x)) correctly when `x` has keys with
663 # strings (b/242589711#comment3). The place this has bitten us so far
664 # is target dependencies, which can be harmlessly removed for now.
665 remove_all_target_dependencies_in_place(contents)
666
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700667 with open(os.path.join(pkg_path, "Cargo.toml"), "w") as cargo:
668 toml.dump(contents, cargo)
669
670 def _replace_source_contents(self, package_path):
671 # First load the checksum file before starting
672 checksum_file = os.path.join(package_path, ".cargo-checksum.json")
673 with open(checksum_file, 'r') as csum:
674 checksum_contents = json.load(csum)
675
676 # Also load the cargo.toml file which we need to write back
677 cargo_file = os.path.join(package_path, "Cargo.toml")
George Burgess IV3e344e42022-08-09 21:07:04 -0700678 with open(cargo_file, 'rb') as cfile:
679 cargo_contents = cfile.read()
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700680
681 shutil.rmtree(package_path)
682
683 # Make package and src dirs and replace lib.rs
684 os.makedirs(os.path.join(package_path, "src"), exist_ok=True)
685 with open(os.path.join(package_path, "src", "lib.rs"), "w") as librs:
686 librs.write(self.LIB_RS_BODY)
687
688 # Restore cargo.toml
George Burgess IV3e344e42022-08-09 21:07:04 -0700689 with open(cargo_file, 'wb') as cfile:
690 cfile.write(cargo_contents)
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700691
692 # Restore checksum
693 with open(checksum_file, 'w') as csum:
694 json.dump(checksum_contents, csum)
695
696 def destroy_unused_crates(self):
George Burgess IV40cc91c2022-08-15 13:07:40 -0700697 all_packages = load_all_metadata_packages(self.working_dir,
698 filter_platform=None,
699 unique=True)
700 used_packages = {p["name"]
701 for p in load_all_metadata_packages(self.working_dir)}
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700702
703 cleaned_packages = []
George Burgess IV40cc91c2022-08-15 13:07:40 -0700704 # Since we're asking for _all_ metadata packages, we may see
705 # duplication.
706 for package in all_packages:
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700707 # Skip used packages
708 if package["name"] in used_packages:
709 continue
710
711 # Detect the correct package path to destroy
712 pkg_path = os.path.join(self.vendor_dir, "{}-{}".format(package["name"], package["version"]))
713 if not os.path.isdir(pkg_path):
George Burgess IV635f7262022-08-09 21:32:20 -0700714 print(f'Crate {package["name"]} not found at {pkg_path}')
715 continue
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700716
717 self._replace_source_contents(pkg_path)
718 self._modify_cargo_toml(pkg_path)
719 _rerun_checksums(pkg_path)
720 cleaned_packages.append(package["name"])
721
722 for pkg in cleaned_packages:
George Burgess IV635f7262022-08-09 21:32:20 -0700723 print("Removed unused crate", pkg)
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700724
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700725def main(args):
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -0800726 current_path = pathlib.Path(__file__).parent.absolute()
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000727 patches = os.path.join(current_path, "patches")
728 vendor = os.path.join(current_path, "vendor")
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -0700729 crab_dir = os.path.join(current_path, "crab", "crates")
George Burgess IV04833702022-08-09 22:00:38 -0700730 license_shorthand_file = os.path.join(current_path, "licenses_used.txt")
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -0800731
Abhishek Pandit-Subedifa902382021-08-20 11:04:33 -0700732 # First, actually run cargo vendor
733 run_cargo_vendor(current_path)
734
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000735 # Order matters here:
736 # - Apply patches (also re-calculates checksums)
737 # - Cleanup any owners files (otherwise, git check-in or checksums are
738 # unhappy)
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700739 # - Destroy unused crates
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000740 apply_patches(patches, vendor)
741 cleanup_owners(vendor)
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700742 destroyer = CrateDestroyer(current_path, vendor)
743 destroyer.destroy_unused_crates()
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -0800744
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700745 # Combine license file and check for any bad licenses
746 lm = LicenseManager(current_path, vendor)
George Burgess IV04833702022-08-09 22:00:38 -0700747 lm.generate_license(args.skip_license_check, args.license_map,
748 license_shorthand_file)
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700749
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -0700750 # Run crab audit on all packages
751 crab = CrabManager(current_path, crab_dir)
752 crab.verify_traits()
753
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -0800754
755if __name__ == '__main__':
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700756 parser = argparse.ArgumentParser(description='Vendor packages properly')
757 parser.add_argument('--skip-license-check',
758 '-s',
759 help='Skip the license check on a specific package',
760 action='append')
761 parser.add_argument('--license-map', help='Write license map to this file')
762 args = parser.parse_args()
763
764 main(args)