blob: b0784b96636180ffcd26336bf83ede3303e95946 [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 """
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000125 proc = subprocess.run(["patch", "-p1", "-i", patch], cwd=workdir)
126 return proc.returncode == 0
127
128
George Burgess IV30c5c362022-08-19 17:05:02 -0700129def apply_patch_script(script, workdir):
130 """Run the given patch script, returning whether it exited cleanly.
131
132 Returns:
133 True if successful. False otherwise.
134 """
135 return subprocess.run([script], cwd=workdir).returncode == 0
136
137
George Burgess IV635f7262022-08-09 21:32:20 -0700138def determine_vendor_crates(vendor_path):
139 """Returns a map of {crate_name: [directory]} at the given vendor_path."""
140 result = collections.defaultdict(list)
141 for crate_name_plus_ver in os.listdir(vendor_path):
George Burgess IV40cc91c2022-08-15 13:07:40 -0700142 name, _ = crate_name_plus_ver.rsplit('-', 1)
143 result[name].append(crate_name_plus_ver)
George Burgess IV635f7262022-08-09 21:32:20 -0700144
145 for crate_list in result.values():
George Burgess IV40cc91c2022-08-15 13:07:40 -0700146 crate_list.sort()
George Burgess IV635f7262022-08-09 21:32:20 -0700147 return result
148
149
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000150def apply_patches(patches_path, vendor_path):
151 """Finds patches and applies them to sub-folders in the vendored crates.
152
153 Args:
154 patches_path: Path to folder with patches. Expect all patches to be one
155 level down (matching the crate name).
156 vendor_path: Root path to vendored crates directory.
157 """
158 checksums_for = {}
159
160 # Don't bother running if patches directory is empty
161 if not pathlib.Path(patches_path).is_dir():
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700162 return
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000163
George Burgess IV30c5c362022-08-19 17:05:02 -0700164 patches_failed = False
George Burgess IV635f7262022-08-09 21:32:20 -0700165 vendor_crate_map = determine_vendor_crates(vendor_path)
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000166 # Look for all patches and apply them
167 for d in os.listdir(patches_path):
168 dir_path = os.path.join(patches_path, d)
169
170 # We don't process patches in root dir
171 if not os.path.isdir(dir_path):
172 continue
173
George Burgess IV30c5c362022-08-19 17:05:02 -0700174 # We accept one of two forms here:
175 # - direct targets (these name # `${crate_name}-${version}`)
176 # - simply the crate name (which applies to all versions of the
177 # crate)
178 direct_target = os.path.join(vendor_path, d)
179 if os.path.isdir(direct_target):
180 patch_targets = [d]
181 elif d in vendor_crate_map:
182 patch_targets = vendor_crate_map[d]
183 else:
184 raise RuntimeError(f'Unknown crate in {vendor_path}: {d}')
185
George Burgess IV635f7262022-08-09 21:32:20 -0700186 for patch in os.listdir(dir_path):
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000187 file_path = os.path.join(dir_path, patch)
188
189 # Skip if not a patch file
George Burgess IV30c5c362022-08-19 17:05:02 -0700190 if not os.path.isfile(file_path):
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000191 continue
192
George Burgess IV30c5c362022-08-19 17:05:02 -0700193 if patch.endswith(".patch"):
194 apply = apply_single_patch
195 elif os.access(file_path, os.X_OK):
196 apply = apply_patch_script
George Burgess IV635f7262022-08-09 21:32:20 -0700197 else:
George Burgess IV30c5c362022-08-19 17:05:02 -0700198 # Unrecognized. Skip it.
199 continue
200
201 for target_name in patch_targets:
202 checksums_for[target_name] = True
203 target = os.path.join(vendor_path, target_name)
204 print(f"-- Applying {file_path} to {target}")
205 if not apply(file_path, target):
206 print(f"Failed to apply {file_path} to {target}")
207 patches_failed = True
208
209 # Do this late, so we can report all of the failing patches in one
210 # invocation.
211 if patches_failed:
212 raise ValueError('Patches failed; please see above logs')
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000213
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000214 # Re-run checksums for all modified packages since we applied patches.
215 for key in checksums_for.keys():
216 _rerun_checksums(os.path.join(vendor_path, key))
217
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700218
George Burgess IV18af5632022-08-30 14:10:53 -0700219def get_workspace_cargo_toml(working_dir):
George Burgess IV40cc91c2022-08-15 13:07:40 -0700220 """Returns all Cargo.toml files under working_dir."""
George Burgess IV18af5632022-08-30 14:10:53 -0700221 return [working_dir / 'projects' / 'Cargo.toml']
George Burgess IV40cc91c2022-08-15 13:07:40 -0700222
223
Abhishek Pandit-Subedifa902382021-08-20 11:04:33 -0700224def run_cargo_vendor(working_dir):
225 """Runs cargo vendor.
226
227 Args:
228 working_dir: Directory to run inside. This should be the directory where
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -0700229 Cargo.toml is kept.
Abhishek Pandit-Subedifa902382021-08-20 11:04:33 -0700230 """
George Burgess IV635f7262022-08-09 21:32:20 -0700231 # Cargo will refuse to revendor into versioned directories, which leads to
232 # repeated `./vendor.py` invocations trying to apply patches to
233 # already-patched sources. Remove the existing vendor directory to avoid
234 # this.
235 vendor_dir = working_dir / 'vendor'
236 if vendor_dir.exists():
George Burgess IV40cc91c2022-08-15 13:07:40 -0700237 shutil.rmtree(vendor_dir)
238
George Burgess IV18af5632022-08-30 14:10:53 -0700239 cargo_cmdline = [
240 'cargo',
241 'vendor',
242 '--versioned-dirs',
243 '-v',
244 '--manifest-path=projects/Cargo.toml',
245 '--',
246 'vendor',
247 ]
George Burgess IV40cc91c2022-08-15 13:07:40 -0700248 subprocess.check_call(cargo_cmdline, cwd=working_dir)
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000249
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -0700250
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700251def load_metadata(working_dir, filter_platform=DEFAULT_PLATFORM_FILTER):
George Burgess IV40cc91c2022-08-15 13:07:40 -0700252 """Load metadata for all projects under a given directory.
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700253
254 Args:
George Burgess IV40cc91c2022-08-15 13:07:40 -0700255 working_dir: Base directory to run from.
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700256 filter_platform: Filter packages to ones configured for this platform.
257 """
George Burgess IV40cc91c2022-08-15 13:07:40 -0700258 metadata_objects = []
George Burgess IV18af5632022-08-30 14:10:53 -0700259 cmd = [
260 'cargo',
261 'metadata',
262 '--format-version=1',
263 '--manifest-path=projects/Cargo.toml',
264 ]
265 # Conditionally add platform filter
266 if filter_platform:
267 cmd += ("--filter-platform", filter_platform)
268 output = subprocess.check_output(cmd, cwd=working_dir)
269 return json.loads(output)
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700270
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700271
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700272class LicenseManager:
273 """ Manage consolidating licenses for all packages."""
274
275 # These are all the licenses we support. Keys are what is seen in metadata and
276 # values are what is expected by the ebuild.
277 SUPPORTED_LICENSES = {
278 'Apache-2.0': 'Apache-2.0',
279 'MIT': 'MIT',
280 'BSD-3-Clause': 'BSD-3',
George Burgess IV4ae42062022-08-15 18:54:51 -0700281 'ISC': 'ISC',
282 'unicode': 'unicode',
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700283 }
284
285 # Prefer to take attribution licenses in this order. All these require that
286 # we actually use the license file found in the package so they MUST have
287 # a license file set.
288 PREFERRED_ATTRIB_LICENSE_ORDER = ['MIT', 'BSD-3', 'ISC']
289
290 # If Apache license is found, always prefer it (simplifies attribution)
291 APACHE_LICENSE = 'Apache-2.0'
292
293 # Regex for license files found in the vendored directories. Search for
294 # these files with re.IGNORECASE.
295 #
296 # These will be searched in order with the earlier entries being preferred.
297 LICENSE_NAMES_REGEX = [
298 r'^license-mit$',
299 r'^copyright$',
300 r'^licen[cs]e.*$',
301 ]
302
303 # Some crates have their license file in other crates. This usually occurs
304 # because multiple crates are published from the same git repository and the
305 # license isn't updated in each sub-crate. In these cases, we can just
306 # ignore these packages.
307 MAP_LICENSE_TO_OTHER = {
308 'failure_derive': 'failure',
309 'grpcio-compiler': 'grpcio',
310 'grpcio-sys': 'grpcio',
311 'rustyline-derive': 'rustyline',
312 }
313
314 # Map a package to a specific license and license file. Only use this if
315 # a package doesn't have an easily discoverable license or exports its
316 # license in a weird way. Prefer to patch the project with a license and
317 # upstream the patch instead.
318 STATIC_LICENSE_MAP = {
319 # "package name": ( "license name", "license file relative location")
320 }
321
322 def __init__(self, working_dir, vendor_dir):
323 self.working_dir = working_dir
324 self.vendor_dir = vendor_dir
325
326 def _find_license_in_dir(self, search_dir):
327 for p in os.listdir(search_dir):
328 # Ignore anything that's not a file
329 if not os.path.isfile(os.path.join(search_dir, p)):
330 continue
331
332 # Now check if the name matches any of the regexes
333 # We'll return the first matching file.
334 for regex in self.LICENSE_NAMES_REGEX:
335 if re.search(regex, p, re.IGNORECASE):
336 yield os.path.join(search_dir, p)
337 break
338
339 def _guess_license_type(self, license_file):
340 if '-MIT' in license_file:
341 return 'MIT'
342 elif '-APACHE' in license_file:
343 return 'APACHE'
344 elif '-BSD' in license_file:
345 return 'BSD-3'
346
347 with open(license_file, 'r') as f:
348 lines = f.read()
349 if 'MIT' in lines:
350 return 'MIT'
351 elif 'Apache' in lines:
352 return 'APACHE'
353 elif 'BSD 3-Clause' in lines:
354 return 'BSD-3'
355
356 return ''
357
George Burgess IV04833702022-08-09 22:00:38 -0700358 def generate_license(self, skip_license_check, print_map_to_file,
359 license_shorthand_file):
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700360 """Generate single massive license file from metadata."""
George Burgess IV18af5632022-08-30 14:10:53 -0700361 metadata = load_metadata(self.working_dir)
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700362
363 has_license_types = set()
364 bad_licenses = {}
365
366 # Keep license map ordered so it generates a consistent license map
367 license_map = {}
368
369 skip_license_check = skip_license_check or []
George Burgess IV4ae42062022-08-15 18:54:51 -0700370 has_unicode_license = False
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700371
George Burgess IV18af5632022-08-30 14:10:53 -0700372 for package in metadata["packages"]:
George Burgess IV40cc91c2022-08-15 13:07:40 -0700373 # Skip the synthesized Cargo.toml packages that exist solely to
374 # list dependencies.
375 if 'path+file:///' in package['id']:
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700376 continue
377
George Burgess IV40cc91c2022-08-15 13:07:40 -0700378 pkg_name = package['name']
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700379 if pkg_name in skip_license_check:
380 print(
381 "Skipped license check on {}. Reason: Skipped from command line"
382 .format(pkg_name))
383 continue
384
385 if pkg_name in self.MAP_LICENSE_TO_OTHER:
386 print(
387 'Skipped license check on {}. Reason: License already in {}'
388 .format(pkg_name, self.MAP_LICENSE_TO_OTHER[pkg_name]))
389 continue
390
391 # Check if we have a static license map for this package. Use the
392 # static values if we have it already set.
393 if pkg_name in self.STATIC_LICENSE_MAP:
394 (license, license_file) = self.STATIC_LICENSE_MAP[pkg_name]
395 license_map[pkg_name] = {
396 "license": license,
397 "license_file": license_file,
398 }
399 continue
400
401 license_files = []
George Burgess IV93ba4732022-08-13 14:10:10 -0700402 # use `or ''` instead of get's default, since `package` may have a
403 # None value for 'license'.
404 license = package.get('license') or ''
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700405
406 # We ignore the metadata for license file because most crates don't
407 # have it set. Just scan the source for licenses.
George Burgess IV635f7262022-08-09 21:32:20 -0700408 pkg_version = package['version']
George Burgess IV40cc91c2022-08-15 13:07:40 -0700409 license_files = list(self._find_license_in_dir(
410 os.path.join(self.vendor_dir, f'{pkg_name}-{pkg_version}')))
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700411
George Burgess IV4ae42062022-08-15 18:54:51 -0700412 # FIXME(b/240953811): The code later in this loop is only
413 # structured to handle ORs, not ANDs. Fortunately, this license in
414 # particular is `AND`ed between a super common license (Apache) and
415 # a more obscure one (unicode). This hack is specifically intended
416 # for the `unicode-ident` crate, though no crate name check is
417 # made, since it's OK other crates happen to have this license.
418 if license == '(MIT OR Apache-2.0) AND Unicode-DFS-2016':
419 has_unicode_license = True
420 # We'll check later to be sure MIT or Apache-2.0 is represented
421 # properly.
422 for x in license_files:
423 if os.path.basename(x) == 'LICENSE-UNICODE':
424 license_file = x
425 break
426 else:
427 raise ValueError('No LICENSE-UNICODE found in '
428 f'{license_files}')
429 license_map[pkg_name] = {
430 "license": license,
431 "license_file": license_file,
432 }
433 has_license_types.add('unicode')
434 continue
435
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700436 # If there are multiple licenses, they are delimited with "OR" or "/"
437 delim = ' OR ' if ' OR ' in license else '/'
George Burgess IV40cc91c2022-08-15 13:07:40 -0700438 found = [x.strip() for x in license.split(delim)]
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700439
440 # Filter licenses to ones we support
441 licenses_or = [
442 self.SUPPORTED_LICENSES[f] for f in found
443 if f in self.SUPPORTED_LICENSES
444 ]
445
446 # If apache license is found, always prefer it because it simplifies
447 # license attribution (we can use existing Apache notice)
448 if self.APACHE_LICENSE in licenses_or:
449 has_license_types.add(self.APACHE_LICENSE)
450 license_map[pkg_name] = {'license': self.APACHE_LICENSE}
451
452 # Handle single license that has at least one license file
453 # We pick the first license file and the license
454 elif len(licenses_or) == 1:
455 if license_files:
456 l = licenses_or[0]
457 lf = license_files[0]
458
459 has_license_types.add(l)
460 license_map[pkg_name] = {
461 'license': l,
462 'license_file': os.path.relpath(lf, self.working_dir),
463 }
464 else:
465 bad_licenses[pkg_name] = "{} missing license file".format(
466 licenses_or[0])
467 # Handle multiple licenses
468 elif len(licenses_or) > 1:
469 # Check preferred licenses in order
470 license_found = False
471 for l in self.PREFERRED_ATTRIB_LICENSE_ORDER:
472 if not l in licenses_or:
473 continue
474
475 for f in license_files:
476 if self._guess_license_type(f) == l:
477 license_found = True
478 has_license_types.add(l)
479 license_map[pkg_name] = {
480 'license':
481 l,
482 'license_file':
483 os.path.relpath(f, self.working_dir),
484 }
485 break
486
487 # Break out of loop if license is found
488 if license_found:
489 break
490 else:
491 bad_licenses[pkg_name] = license
492
493 # If we had any bad licenses, we need to abort
494 if bad_licenses:
495 for k in bad_licenses.keys():
496 print("{} had no acceptable licenses: {}".format(
497 k, bad_licenses[k]))
498 raise Exception("Bad licenses in vendored packages.")
499
500 # Write license map to file
501 if print_map_to_file:
502 with open(os.path.join(self.working_dir, print_map_to_file),
503 'w') as lfile:
504 json.dump(license_map, lfile, sort_keys=True)
505
506 # Raise missing licenses unless we have a valid reason to ignore them
507 raise_missing_license = False
508 for name, v in license_map.items():
509 if 'license_file' not in v and v.get('license',
510 '') != self.APACHE_LICENSE:
511 raise_missing_license = True
512 print(" {}: Missing license file. Fix or add to ignorelist.".
513 format(name))
514
515 if raise_missing_license:
516 raise Exception(
517 "Unhandled missing license file. "
518 "Make sure all are accounted for before continuing.")
519
George Burgess IV4ae42062022-08-15 18:54:51 -0700520 if has_unicode_license:
521 if self.APACHE_LICENSE not in has_license_types:
522 raise ValueError('Need the apache license; currently have: '
523 f'{sorted(has_license_types)}')
524
George Burgess IV04833702022-08-09 22:00:38 -0700525 sorted_licenses = sorted(has_license_types)
526 print("Add the following licenses to the ebuild:\n",
527 sorted_licenses)
528 header = textwrap.dedent("""\
529 # File to describe the licenses used by this registry.
530 # Used to it's easy to automatically verify ebuilds are updated.
531 # Each line is a license. Lines starting with # are comments.
532 """)
533 with open(license_shorthand_file, 'w', encoding='utf-8') as f:
534 f.write(header)
535 f.write('\n'.join(sorted_licenses))
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700536
537
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -0700538# TODO(abps) - This needs to be replaced with datalog later. We should compile
539# all crab files into datalog and query it with our requirements
540# instead.
541class CrabManager:
542 """Manage audit files."""
543 def __init__(self, working_dir, crab_dir):
544 self.working_dir = working_dir
545 self.crab_dir = crab_dir
546
547 def _check_bad_traits(self, crabdata):
548 """Checks that a package's crab audit meets our requirements.
549
550 Args:
551 crabdata: Dict with crab keys in standard templated format.
552 """
553 common = crabdata['common']
554 # TODO(b/200578411) - Figure out what conditions we should enforce as
555 # part of the audit.
556 conditions = [
557 common.get('deny', None),
558 ]
559
560 # If any conditions are true, this crate is not acceptable.
561 return any(conditions)
562
563 def verify_traits(self):
564 """ Verify that all required CRAB traits for this repository are met.
565 """
George Burgess IV18af5632022-08-30 14:10:53 -0700566 metadata = load_metadata(self.working_dir)
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -0700567
568 failing_crates = {}
569
570 # Verify all packages have a CRAB file associated with it and they meet
571 # all our required traits
George Burgess IV18af5632022-08-30 14:10:53 -0700572 for package in metadata["packages"]:
George Burgess IV40cc91c2022-08-15 13:07:40 -0700573 # Skip the synthesized Cargo.toml packages that exist solely to
574 # list dependencies.
575 if 'path+file:///' in package['id']:
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -0700576 continue
577
578 crabname = "{}-{}".format(package['name'], package['version'])
579 filename = os.path.join(self.crab_dir, "{}.toml".format(crabname))
580
581 # If crab file doesn't exist, the crate fails
582 if not os.path.isfile(filename):
583 failing_crates[crabname] = "No crab file".format(filename)
584 continue
585
586 with open(filename, 'r') as f:
587 crabdata = toml.loads(f.read())
588
589 # If crab file's crate_name and version keys don't match this
590 # package, it also fails. This is just housekeeping...
591 if package['name'] != crabdata['crate_name'] or package[
592 'version'] != crabdata['version']:
593 failing_crates[crabname] = "Crate name or version don't match"
594 continue
595
596 if self._check_bad_traits(crabdata):
597 failing_crates[crabname] = "Failed bad traits check"
598
599 # If we had any failing crates, list them now
600 if failing_crates:
601 print('Failed CRAB audit:')
602 for k, v in failing_crates.items():
603 print(' {}: {}'.format(k, v))
604
605
George Burgess IVd4ff0502022-08-14 23:27:57 -0700606def clean_features_in_place(cargo_toml):
607 """Removes all side-effects of features in `cargo_toml`."""
608 features = cargo_toml.get('features')
609 if not features:
610 return
611
612 for name, value in features.items():
613 if name != 'default':
614 features[name] = []
615
616
George Burgess IV0313d782022-08-15 23:45:44 -0700617def remove_all_target_dependencies_in_place(cargo_toml):
George Burgess IVd4ff0502022-08-14 23:27:57 -0700618 """Removes all `target.*.dependencies` from `cargo_toml`."""
619 target = cargo_toml.get('target')
620 if not target:
621 return
George Burgess IV0313d782022-08-15 23:45:44 -0700622
George Burgess IVd4ff0502022-08-14 23:27:57 -0700623 empty_keys = []
624 for key, values in target.items():
625 values.pop('dependencies', None)
626 values.pop('dev-dependencies', None)
627 if not values:
628 empty_keys.append(key)
George Burgess IV0313d782022-08-15 23:45:44 -0700629
George Burgess IVd4ff0502022-08-14 23:27:57 -0700630 if len(empty_keys) == len(target):
631 del cargo_toml['target']
632 else:
633 for key in empty_keys:
634 del target[key]
George Burgess IV0313d782022-08-15 23:45:44 -0700635
636
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700637class CrateDestroyer():
638 LIB_RS_BODY = """compile_error!("This crate cannot be built for this configuration.");\n"""
639
640 def __init__(self, working_dir, vendor_dir):
641 self.working_dir = working_dir
642 self.vendor_dir = vendor_dir
643
644 def _modify_cargo_toml(self, pkg_path):
George Burgess IVd4ff0502022-08-14 23:27:57 -0700645 with open(os.path.join(pkg_path, 'Cargo.toml'), 'r') as cargo:
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700646 contents = toml.load(cargo)
647
George Burgess IVd4ff0502022-08-14 23:27:57 -0700648 package = contents['package']
649
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700650 # Change description, license and delete license key
George Burgess IVd4ff0502022-08-14 23:27:57 -0700651 package['description'] = 'Empty crate that should not build.'
652 package['license'] = 'Apache-2.0'
653
654 package.pop('license_file', None)
655 # If there's no build.rs but we specify `links = "foo"`, Cargo gets
656 # upset.
657 package.pop('links', None)
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700658
George Burgess IV0313d782022-08-15 23:45:44 -0700659 # Some packages have cfg-specific dependencies. Remove them here; we
660 # don't care about the dependencies of an empty package.
661 #
662 # This is a load-bearing optimization: `dev-python/toml` doesn't
663 # always round-trip dumps(loads(x)) correctly when `x` has keys with
664 # strings (b/242589711#comment3). The place this has bitten us so far
665 # is target dependencies, which can be harmlessly removed for now.
George Burgess IVd4ff0502022-08-14 23:27:57 -0700666 #
667 # Cleaning features in-place is also necessary, since we're removing
668 # dependencies, and a feature can enable features in dependencies.
669 # Cargo errors out on `[features] foo = "bar/baz"` if `bar` isn't a
670 # dependency.
671 clean_features_in_place(contents)
George Burgess IV0313d782022-08-15 23:45:44 -0700672 remove_all_target_dependencies_in_place(contents)
673
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700674 with open(os.path.join(pkg_path, "Cargo.toml"), "w") as cargo:
675 toml.dump(contents, cargo)
676
677 def _replace_source_contents(self, package_path):
678 # First load the checksum file before starting
679 checksum_file = os.path.join(package_path, ".cargo-checksum.json")
680 with open(checksum_file, 'r') as csum:
681 checksum_contents = json.load(csum)
682
683 # Also load the cargo.toml file which we need to write back
684 cargo_file = os.path.join(package_path, "Cargo.toml")
George Burgess IV3e344e42022-08-09 21:07:04 -0700685 with open(cargo_file, 'rb') as cfile:
686 cargo_contents = cfile.read()
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700687
688 shutil.rmtree(package_path)
689
690 # Make package and src dirs and replace lib.rs
691 os.makedirs(os.path.join(package_path, "src"), exist_ok=True)
692 with open(os.path.join(package_path, "src", "lib.rs"), "w") as librs:
693 librs.write(self.LIB_RS_BODY)
694
695 # Restore cargo.toml
George Burgess IV3e344e42022-08-09 21:07:04 -0700696 with open(cargo_file, 'wb') as cfile:
697 cfile.write(cargo_contents)
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700698
699 # Restore checksum
700 with open(checksum_file, 'w') as csum:
701 json.dump(checksum_contents, csum)
702
703 def destroy_unused_crates(self):
George Burgess IV18af5632022-08-30 14:10:53 -0700704 metadata = load_metadata(self.working_dir, filter_platform=None)
George Burgess IV40cc91c2022-08-15 13:07:40 -0700705 used_packages = {p["name"]
George Burgess IV18af5632022-08-30 14:10:53 -0700706 for p in load_metadata(self.working_dir)["packages"]}
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700707
708 cleaned_packages = []
George Burgess IV40cc91c2022-08-15 13:07:40 -0700709 # Since we're asking for _all_ metadata packages, we may see
710 # duplication.
George Burgess IV18af5632022-08-30 14:10:53 -0700711 for package in metadata["packages"]:
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700712 # Skip used packages
713 if package["name"] in used_packages:
714 continue
715
716 # Detect the correct package path to destroy
717 pkg_path = os.path.join(self.vendor_dir, "{}-{}".format(package["name"], package["version"]))
718 if not os.path.isdir(pkg_path):
George Burgess IV635f7262022-08-09 21:32:20 -0700719 print(f'Crate {package["name"]} not found at {pkg_path}')
720 continue
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700721
722 self._replace_source_contents(pkg_path)
723 self._modify_cargo_toml(pkg_path)
724 _rerun_checksums(pkg_path)
725 cleaned_packages.append(package["name"])
726
727 for pkg in cleaned_packages:
George Burgess IV635f7262022-08-09 21:32:20 -0700728 print("Removed unused crate", pkg)
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700729
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700730def main(args):
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -0800731 current_path = pathlib.Path(__file__).parent.absolute()
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000732 patches = os.path.join(current_path, "patches")
733 vendor = os.path.join(current_path, "vendor")
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -0700734 crab_dir = os.path.join(current_path, "crab", "crates")
George Burgess IV04833702022-08-09 22:00:38 -0700735 license_shorthand_file = os.path.join(current_path, "licenses_used.txt")
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -0800736
Abhishek Pandit-Subedifa902382021-08-20 11:04:33 -0700737 # First, actually run cargo vendor
738 run_cargo_vendor(current_path)
739
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000740 # Order matters here:
741 # - Apply patches (also re-calculates checksums)
742 # - Cleanup any owners files (otherwise, git check-in or checksums are
743 # unhappy)
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700744 # - Destroy unused crates
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000745 apply_patches(patches, vendor)
746 cleanup_owners(vendor)
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700747 destroyer = CrateDestroyer(current_path, vendor)
748 destroyer.destroy_unused_crates()
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -0800749
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700750 # Combine license file and check for any bad licenses
751 lm = LicenseManager(current_path, vendor)
George Burgess IV04833702022-08-09 22:00:38 -0700752 lm.generate_license(args.skip_license_check, args.license_map,
753 license_shorthand_file)
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700754
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -0700755 # Run crab audit on all packages
756 crab = CrabManager(current_path, crab_dir)
757 crab.verify_traits()
758
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -0800759
760if __name__ == '__main__':
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700761 parser = argparse.ArgumentParser(description='Vendor packages properly')
762 parser.add_argument('--skip-license-check',
763 '-s',
764 help='Skip the license check on a specific package',
765 action='append')
766 parser.add_argument('--license-map', help='Write license map to this file')
767 args = parser.parse_args()
768
769 main(args)