blob: 046f49c398461583a8090f28ac0af3c7f8285957 [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()
George Burgess IV7dffc252022-08-31 14:37:01 -070032 checksum_path = os.path.join(package_path, ".cargo-checksum.json")
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +000033 if not pathlib.Path(checksum_path).is_file():
34 return False
35
George Burgess IV7dffc252022-08-31 14:37:01 -070036 with open(checksum_path, "r") as fread:
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +000037 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)
George Burgess IV7dffc252022-08-31 14:37:01 -070046 with open(file_path, "rb") as frb:
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +000047 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:
George Burgess IV7dffc252022-08-31 14:37:01 -070056 print(
57 "{} regenerated {} hashes".format(package_path, len(hashes.keys()))
58 )
59 contents["files"] = hashes
60 with open(checksum_path, "w") as fwrite:
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -070061 json.dump(contents, fwrite, sort_keys=True)
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +000062
63 return True
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -080064
65
66def _remove_OWNERS_checksum(root):
George Burgess IV7dffc252022-08-31 14:37:01 -070067 """Delete all OWNERS files from the checksum file.
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -080068
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +000069 Args:
70 root: Root directory for the vendored crate.
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -080071
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +000072 Returns:
73 True if OWNERS was found and cleaned up. Otherwise False.
74 """
George Burgess IV7dffc252022-08-31 14:37:01 -070075 checksum_path = os.path.join(root, ".cargo-checksum.json")
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -080076 if not pathlib.Path(checksum_path).is_file():
77 return False
78
George Burgess IV7dffc252022-08-31 14:37:01 -070079 with open(checksum_path, "r") as fread:
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -080080 contents = json.load(fread)
81
82 del_keys = []
George Burgess IV7dffc252022-08-31 14:37:01 -070083 for cfile in contents["files"]:
84 if "OWNERS" in cfile:
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -080085 del_keys.append(cfile)
86
87 for key in del_keys:
George Burgess IV7dffc252022-08-31 14:37:01 -070088 del contents["files"][key]
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -080089
90 if del_keys:
George Burgess IV7dffc252022-08-31 14:37:01 -070091 print("{} deleted: {}".format(root, del_keys))
92 with open(checksum_path, "w") as fwrite:
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -070093 json.dump(contents, fwrite, sort_keys=True)
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -080094
95 return bool(del_keys)
96
97
98def cleanup_owners(vendor_path):
George Burgess IV7dffc252022-08-31 14:37:01 -070099 """Remove owners checksums from the vendor directory.
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -0800100
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000101 We currently do not check in the OWNERS files from vendored crates because
102 they interfere with the find-owners functionality in gerrit. This cleanup
103 simply finds all instances of "OWNERS" in the checksum files within and
104 removes them.
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -0800105
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000106 Args:
107 vendor_path: Absolute path to vendor directory.
108 """
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -0800109 deps_cleaned = []
110 for root, dirs, _ in os.walk(vendor_path):
111 for d in dirs:
112 removed = _remove_OWNERS_checksum(os.path.join(root, d))
113 if removed:
114 deps_cleaned.append(d)
115
116 if deps_cleaned:
George Burgess IV7dffc252022-08-31 14:37:01 -0700117 print("Cleanup owners:\n {}".format("\n".join(deps_cleaned)))
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -0800118
119
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000120def apply_single_patch(patch, workdir):
121 """Apply a single patch and return whether it was successful.
122
123 Returns:
124 True if successful. False otherwise.
125 """
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 IV30c5c362022-08-19 17:05:02 -0700130def apply_patch_script(script, workdir):
131 """Run the given patch script, returning whether it exited cleanly.
132
133 Returns:
134 True if successful. False otherwise.
135 """
136 return subprocess.run([script], cwd=workdir).returncode == 0
137
138
George Burgess IV635f7262022-08-09 21:32:20 -0700139def determine_vendor_crates(vendor_path):
140 """Returns a map of {crate_name: [directory]} at the given vendor_path."""
141 result = collections.defaultdict(list)
142 for crate_name_plus_ver in os.listdir(vendor_path):
George Burgess IV7dffc252022-08-31 14:37:01 -0700143 name, _ = crate_name_plus_ver.rsplit("-", 1)
George Burgess IV40cc91c2022-08-15 13:07:40 -0700144 result[name].append(crate_name_plus_ver)
George Burgess IV635f7262022-08-09 21:32:20 -0700145
146 for crate_list in result.values():
George Burgess IV40cc91c2022-08-15 13:07:40 -0700147 crate_list.sort()
George Burgess IV635f7262022-08-09 21:32:20 -0700148 return result
149
150
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000151def apply_patches(patches_path, vendor_path):
152 """Finds patches and applies them to sub-folders in the vendored crates.
153
154 Args:
155 patches_path: Path to folder with patches. Expect all patches to be one
156 level down (matching the crate name).
157 vendor_path: Root path to vendored crates directory.
158 """
159 checksums_for = {}
160
161 # Don't bother running if patches directory is empty
162 if not pathlib.Path(patches_path).is_dir():
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700163 return
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000164
George Burgess IV30c5c362022-08-19 17:05:02 -0700165 patches_failed = False
George Burgess IV635f7262022-08-09 21:32:20 -0700166 vendor_crate_map = determine_vendor_crates(vendor_path)
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000167 # Look for all patches and apply them
168 for d in os.listdir(patches_path):
169 dir_path = os.path.join(patches_path, d)
170
171 # We don't process patches in root dir
172 if not os.path.isdir(dir_path):
173 continue
174
George Burgess IV30c5c362022-08-19 17:05:02 -0700175 # We accept one of two forms here:
176 # - direct targets (these name # `${crate_name}-${version}`)
177 # - simply the crate name (which applies to all versions of the
178 # crate)
179 direct_target = os.path.join(vendor_path, d)
180 if os.path.isdir(direct_target):
181 patch_targets = [d]
182 elif d in vendor_crate_map:
183 patch_targets = vendor_crate_map[d]
184 else:
George Burgess IV7dffc252022-08-31 14:37:01 -0700185 raise RuntimeError(f"Unknown crate in {vendor_path}: {d}")
George Burgess IV30c5c362022-08-19 17:05:02 -0700186
George Burgess IV635f7262022-08-09 21:32:20 -0700187 for patch in os.listdir(dir_path):
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000188 file_path = os.path.join(dir_path, patch)
189
190 # Skip if not a patch file
George Burgess IV30c5c362022-08-19 17:05:02 -0700191 if not os.path.isfile(file_path):
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000192 continue
193
George Burgess IV30c5c362022-08-19 17:05:02 -0700194 if patch.endswith(".patch"):
195 apply = apply_single_patch
196 elif os.access(file_path, os.X_OK):
197 apply = apply_patch_script
George Burgess IV635f7262022-08-09 21:32:20 -0700198 else:
George Burgess IV30c5c362022-08-19 17:05:02 -0700199 # Unrecognized. Skip it.
200 continue
201
202 for target_name in patch_targets:
203 checksums_for[target_name] = True
204 target = os.path.join(vendor_path, target_name)
205 print(f"-- Applying {file_path} to {target}")
206 if not apply(file_path, target):
207 print(f"Failed to apply {file_path} to {target}")
208 patches_failed = True
209
210 # Do this late, so we can report all of the failing patches in one
211 # invocation.
212 if patches_failed:
George Burgess IV7dffc252022-08-31 14:37:01 -0700213 raise ValueError("Patches failed; please see above logs")
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000214
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000215 # Re-run checksums for all modified packages since we applied patches.
216 for key in checksums_for.keys():
217 _rerun_checksums(os.path.join(vendor_path, key))
218
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700219
George Burgess IV18af5632022-08-30 14:10:53 -0700220def get_workspace_cargo_toml(working_dir):
George Burgess IV40cc91c2022-08-15 13:07:40 -0700221 """Returns all Cargo.toml files under working_dir."""
George Burgess IV7dffc252022-08-31 14:37:01 -0700222 return [working_dir / "projects" / "Cargo.toml"]
George Burgess IV40cc91c2022-08-15 13:07:40 -0700223
224
Abhishek Pandit-Subedifa902382021-08-20 11:04:33 -0700225def run_cargo_vendor(working_dir):
226 """Runs cargo vendor.
227
228 Args:
229 working_dir: Directory to run inside. This should be the directory where
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -0700230 Cargo.toml is kept.
Abhishek Pandit-Subedifa902382021-08-20 11:04:33 -0700231 """
George Burgess IV635f7262022-08-09 21:32:20 -0700232 # Cargo will refuse to revendor into versioned directories, which leads to
233 # repeated `./vendor.py` invocations trying to apply patches to
234 # already-patched sources. Remove the existing vendor directory to avoid
235 # this.
George Burgess IV7dffc252022-08-31 14:37:01 -0700236 vendor_dir = working_dir / "vendor"
George Burgess IV635f7262022-08-09 21:32:20 -0700237 if vendor_dir.exists():
George Burgess IV40cc91c2022-08-15 13:07:40 -0700238 shutil.rmtree(vendor_dir)
239
George Burgess IV18af5632022-08-30 14:10:53 -0700240 cargo_cmdline = [
George Burgess IV7dffc252022-08-31 14:37:01 -0700241 "cargo",
242 "vendor",
243 "--versioned-dirs",
244 "-v",
245 "--manifest-path=projects/Cargo.toml",
246 "--",
247 "vendor",
George Burgess IV18af5632022-08-30 14:10:53 -0700248 ]
George Burgess IV40cc91c2022-08-15 13:07:40 -0700249 subprocess.check_call(cargo_cmdline, cwd=working_dir)
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000250
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -0700251
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700252def load_metadata(working_dir, filter_platform=DEFAULT_PLATFORM_FILTER):
George Burgess IV40cc91c2022-08-15 13:07:40 -0700253 """Load metadata for all projects under a given directory.
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700254
255 Args:
George Burgess IV40cc91c2022-08-15 13:07:40 -0700256 working_dir: Base directory to run from.
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700257 filter_platform: Filter packages to ones configured for this platform.
258 """
George Burgess IV40cc91c2022-08-15 13:07:40 -0700259 metadata_objects = []
George Burgess IV18af5632022-08-30 14:10:53 -0700260 cmd = [
George Burgess IV7dffc252022-08-31 14:37:01 -0700261 "cargo",
262 "metadata",
263 "--format-version=1",
264 "--manifest-path=projects/Cargo.toml",
George Burgess IV18af5632022-08-30 14:10:53 -0700265 ]
266 # Conditionally add platform filter
267 if filter_platform:
268 cmd += ("--filter-platform", filter_platform)
269 output = subprocess.check_output(cmd, cwd=working_dir)
270 return json.loads(output)
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700271
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700272
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700273class LicenseManager:
George Burgess IV7dffc252022-08-31 14:37:01 -0700274 """Manage consolidating licenses for all packages."""
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700275
George Burgess IV124e6a12022-09-09 10:44:29 -0700276 # These are all the licenses we support. Keys are what is seen in metadata
277 # and values are what is expected by ebuilds.
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700278 SUPPORTED_LICENSES = {
George Burgess IV7dffc252022-08-31 14:37:01 -0700279 "0BSD": "0BSD",
280 "Apache-2.0": "Apache-2.0",
281 "BSD-3-Clause": "BSD-3",
282 "ISC": "ISC",
283 "MIT": "MIT",
284 "MPL-2.0": "MPL-2.0",
285 "unicode": "unicode",
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700286 }
287
288 # Prefer to take attribution licenses in this order. All these require that
289 # we actually use the license file found in the package so they MUST have
290 # a license file set.
George Burgess IV7dffc252022-08-31 14:37:01 -0700291 PREFERRED_ATTRIB_LICENSE_ORDER = ["MIT", "BSD-3", "ISC"]
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700292
293 # If Apache license is found, always prefer it (simplifies attribution)
George Burgess IV7dffc252022-08-31 14:37:01 -0700294 APACHE_LICENSE = "Apache-2.0"
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700295
296 # Regex for license files found in the vendored directories. Search for
297 # these files with re.IGNORECASE.
298 #
299 # These will be searched in order with the earlier entries being preferred.
300 LICENSE_NAMES_REGEX = [
George Burgess IV7dffc252022-08-31 14:37:01 -0700301 r"^license-mit$",
302 r"^copyright$",
303 r"^licen[cs]e.*$",
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700304 ]
305
306 # Some crates have their license file in other crates. This usually occurs
307 # because multiple crates are published from the same git repository and the
308 # license isn't updated in each sub-crate. In these cases, we can just
309 # ignore these packages.
310 MAP_LICENSE_TO_OTHER = {
George Burgess IV7dffc252022-08-31 14:37:01 -0700311 "failure_derive": "failure",
312 "grpcio-compiler": "grpcio",
313 "grpcio-sys": "grpcio",
314 "rustyline-derive": "rustyline",
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700315 }
316
317 # Map a package to a specific license and license file. Only use this if
318 # a package doesn't have an easily discoverable license or exports its
319 # license in a weird way. Prefer to patch the project with a license and
320 # upstream the patch instead.
321 STATIC_LICENSE_MAP = {
322 # "package name": ( "license name", "license file relative location")
George Burgess IVf4a5e362022-08-30 14:30:36 -0700323 # Patch for adding this is upstream, but the patch application doesn't
324 # apply to `cargo metadata`. This is presumably because it can't detect
325 # our vendor directory.
326 # https://gitlab.freedesktop.org/slirp/libslirp-sys/-/merge_requests/6
George Burgess IV7dffc252022-08-31 14:37:01 -0700327 "libslirp-sys": ("MIT", "LICENSE"),
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700328 }
329
330 def __init__(self, working_dir, vendor_dir):
331 self.working_dir = working_dir
332 self.vendor_dir = vendor_dir
333
334 def _find_license_in_dir(self, search_dir):
335 for p in os.listdir(search_dir):
336 # Ignore anything that's not a file
337 if not os.path.isfile(os.path.join(search_dir, p)):
338 continue
339
340 # Now check if the name matches any of the regexes
341 # We'll return the first matching file.
342 for regex in self.LICENSE_NAMES_REGEX:
343 if re.search(regex, p, re.IGNORECASE):
344 yield os.path.join(search_dir, p)
345 break
346
347 def _guess_license_type(self, license_file):
George Burgess IV7dffc252022-08-31 14:37:01 -0700348 if "-MIT" in license_file:
349 return "MIT"
350 elif "-APACHE" in license_file:
351 return "APACHE"
352 elif "-BSD" in license_file:
353 return "BSD-3"
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700354
George Burgess IV7dffc252022-08-31 14:37:01 -0700355 with open(license_file, "r") as f:
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700356 lines = f.read()
George Burgess IV7dffc252022-08-31 14:37:01 -0700357 if "MIT" in lines:
358 return "MIT"
359 elif "Apache" in lines:
360 return "APACHE"
361 elif "BSD 3-Clause" in lines:
362 return "BSD-3"
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700363
George Burgess IV7dffc252022-08-31 14:37:01 -0700364 return ""
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700365
George Burgess IV7dffc252022-08-31 14:37:01 -0700366 def generate_license(
367 self, skip_license_check, print_map_to_file, license_shorthand_file
368 ):
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700369 """Generate single massive license file from metadata."""
George Burgess IV18af5632022-08-30 14:10:53 -0700370 metadata = load_metadata(self.working_dir)
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700371
372 has_license_types = set()
373 bad_licenses = {}
374
375 # Keep license map ordered so it generates a consistent license map
376 license_map = {}
377
378 skip_license_check = skip_license_check or []
George Burgess IV4ae42062022-08-15 18:54:51 -0700379 has_unicode_license = False
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700380
George Burgess IV18af5632022-08-30 14:10:53 -0700381 for package in metadata["packages"]:
George Burgess IV40cc91c2022-08-15 13:07:40 -0700382 # Skip the synthesized Cargo.toml packages that exist solely to
383 # list dependencies.
George Burgess IV7dffc252022-08-31 14:37:01 -0700384 if "path+file:///" in package["id"]:
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700385 continue
386
George Burgess IV7dffc252022-08-31 14:37:01 -0700387 pkg_name = package["name"]
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700388 if pkg_name in skip_license_check:
389 print(
George Burgess IV7dffc252022-08-31 14:37:01 -0700390 "Skipped license check on {}. Reason: Skipped from command line".format(
391 pkg_name
392 )
393 )
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700394 continue
395
396 if pkg_name in self.MAP_LICENSE_TO_OTHER:
397 print(
George Burgess IV7dffc252022-08-31 14:37:01 -0700398 "Skipped license check on {}. Reason: License already in {}".format(
399 pkg_name, self.MAP_LICENSE_TO_OTHER[pkg_name]
400 )
401 )
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700402 continue
403
404 # Check if we have a static license map for this package. Use the
405 # static values if we have it already set.
406 if pkg_name in self.STATIC_LICENSE_MAP:
407 (license, license_file) = self.STATIC_LICENSE_MAP[pkg_name]
408 license_map[pkg_name] = {
409 "license": license,
410 "license_file": license_file,
411 }
412 continue
413
414 license_files = []
George Burgess IV93ba4732022-08-13 14:10:10 -0700415 # use `or ''` instead of get's default, since `package` may have a
416 # None value for 'license'.
George Burgess IV7dffc252022-08-31 14:37:01 -0700417 license = package.get("license") or ""
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700418
419 # We ignore the metadata for license file because most crates don't
420 # have it set. Just scan the source for licenses.
George Burgess IV7dffc252022-08-31 14:37:01 -0700421 pkg_version = package["version"]
422 license_files = list(
423 self._find_license_in_dir(
424 os.path.join(self.vendor_dir, f"{pkg_name}-{pkg_version}")
425 )
426 )
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700427
George Burgess IV4ae42062022-08-15 18:54:51 -0700428 # FIXME(b/240953811): The code later in this loop is only
429 # structured to handle ORs, not ANDs. Fortunately, this license in
430 # particular is `AND`ed between a super common license (Apache) and
431 # a more obscure one (unicode). This hack is specifically intended
432 # for the `unicode-ident` crate, though no crate name check is
433 # made, since it's OK other crates happen to have this license.
George Burgess IV7dffc252022-08-31 14:37:01 -0700434 if license == "(MIT OR Apache-2.0) AND Unicode-DFS-2016":
George Burgess IV4ae42062022-08-15 18:54:51 -0700435 has_unicode_license = True
436 # We'll check later to be sure MIT or Apache-2.0 is represented
437 # properly.
438 for x in license_files:
George Burgess IV7dffc252022-08-31 14:37:01 -0700439 if os.path.basename(x) == "LICENSE-UNICODE":
George Burgess IV4ae42062022-08-15 18:54:51 -0700440 license_file = x
441 break
442 else:
George Burgess IV7dffc252022-08-31 14:37:01 -0700443 raise ValueError(
444 "No LICENSE-UNICODE found in " f"{license_files}"
445 )
George Burgess IV4ae42062022-08-15 18:54:51 -0700446 license_map[pkg_name] = {
447 "license": license,
448 "license_file": license_file,
449 }
George Burgess IV7dffc252022-08-31 14:37:01 -0700450 has_license_types.add("unicode")
George Burgess IV4ae42062022-08-15 18:54:51 -0700451 continue
452
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700453 # If there are multiple licenses, they are delimited with "OR" or "/"
George Burgess IV7dffc252022-08-31 14:37:01 -0700454 delim = " OR " if " OR " in license else "/"
George Burgess IV40cc91c2022-08-15 13:07:40 -0700455 found = [x.strip() for x in license.split(delim)]
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700456
457 # Filter licenses to ones we support
458 licenses_or = [
George Burgess IV7dffc252022-08-31 14:37:01 -0700459 self.SUPPORTED_LICENSES[f]
460 for f in found
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700461 if f in self.SUPPORTED_LICENSES
462 ]
463
464 # If apache license is found, always prefer it because it simplifies
465 # license attribution (we can use existing Apache notice)
466 if self.APACHE_LICENSE in licenses_or:
467 has_license_types.add(self.APACHE_LICENSE)
George Burgess IV7dffc252022-08-31 14:37:01 -0700468 license_map[pkg_name] = {"license": self.APACHE_LICENSE}
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700469
470 # Handle single license that has at least one license file
471 # We pick the first license file and the license
472 elif len(licenses_or) == 1:
473 if license_files:
474 l = licenses_or[0]
475 lf = license_files[0]
476
477 has_license_types.add(l)
478 license_map[pkg_name] = {
George Burgess IV7dffc252022-08-31 14:37:01 -0700479 "license": l,
480 "license_file": os.path.relpath(lf, self.working_dir),
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700481 }
482 else:
483 bad_licenses[pkg_name] = "{} missing license file".format(
George Burgess IV7dffc252022-08-31 14:37:01 -0700484 licenses_or[0]
485 )
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700486 # Handle multiple licenses
487 elif len(licenses_or) > 1:
488 # Check preferred licenses in order
489 license_found = False
490 for l in self.PREFERRED_ATTRIB_LICENSE_ORDER:
491 if not l in licenses_or:
492 continue
493
494 for f in license_files:
495 if self._guess_license_type(f) == l:
496 license_found = True
497 has_license_types.add(l)
498 license_map[pkg_name] = {
George Burgess IV7dffc252022-08-31 14:37:01 -0700499 "license": l,
500 "license_file": os.path.relpath(
501 f, self.working_dir
502 ),
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700503 }
504 break
505
506 # Break out of loop if license is found
507 if license_found:
508 break
509 else:
510 bad_licenses[pkg_name] = license
511
512 # If we had any bad licenses, we need to abort
513 if bad_licenses:
514 for k in bad_licenses.keys():
George Burgess IV7dffc252022-08-31 14:37:01 -0700515 print(
516 "{} had no acceptable licenses: {}".format(
517 k, bad_licenses[k]
518 )
519 )
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700520 raise Exception("Bad licenses in vendored packages.")
521
522 # Write license map to file
523 if print_map_to_file:
George Burgess IV7dffc252022-08-31 14:37:01 -0700524 with open(
525 os.path.join(self.working_dir, print_map_to_file), "w"
526 ) as lfile:
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700527 json.dump(license_map, lfile, sort_keys=True)
528
529 # Raise missing licenses unless we have a valid reason to ignore them
530 raise_missing_license = False
531 for name, v in license_map.items():
George Burgess IV7dffc252022-08-31 14:37:01 -0700532 if (
533 "license_file" not in v
534 and v.get("license", "") != self.APACHE_LICENSE
535 ):
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700536 raise_missing_license = True
George Burgess IV7dffc252022-08-31 14:37:01 -0700537 print(
538 " {}: Missing license file. Fix or add to ignorelist.".format(
539 name
540 )
541 )
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700542
543 if raise_missing_license:
544 raise Exception(
545 "Unhandled missing license file. "
George Burgess IV7dffc252022-08-31 14:37:01 -0700546 "Make sure all are accounted for before continuing."
547 )
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700548
George Burgess IV4ae42062022-08-15 18:54:51 -0700549 if has_unicode_license:
550 if self.APACHE_LICENSE not in has_license_types:
George Burgess IV7dffc252022-08-31 14:37:01 -0700551 raise ValueError(
552 "Need the apache license; currently have: "
553 f"{sorted(has_license_types)}"
554 )
George Burgess IV4ae42062022-08-15 18:54:51 -0700555
George Burgess IV04833702022-08-09 22:00:38 -0700556 sorted_licenses = sorted(has_license_types)
George Burgess IV124e6a12022-09-09 10:44:29 -0700557 print("The following licenses are in use:", sorted_licenses)
George Burgess IV7dffc252022-08-31 14:37:01 -0700558 header = textwrap.dedent(
559 """\
George Burgess IV04833702022-08-09 22:00:38 -0700560 # File to describe the licenses used by this registry.
Daniel Verkampd9d085b2022-09-07 10:52:27 -0700561 # Used so it's easy to automatically verify ebuilds are updated.
George Burgess IV04833702022-08-09 22:00:38 -0700562 # Each line is a license. Lines starting with # are comments.
George Burgess IV7dffc252022-08-31 14:37:01 -0700563 """
564 )
565 with open(license_shorthand_file, "w", encoding="utf-8") as f:
George Burgess IV04833702022-08-09 22:00:38 -0700566 f.write(header)
George Burgess IV7dffc252022-08-31 14:37:01 -0700567 f.write("\n".join(sorted_licenses))
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700568
569
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -0700570# TODO(abps) - This needs to be replaced with datalog later. We should compile
571# all crab files into datalog and query it with our requirements
572# instead.
573class CrabManager:
574 """Manage audit files."""
George Burgess IV7dffc252022-08-31 14:37:01 -0700575
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -0700576 def __init__(self, working_dir, crab_dir):
577 self.working_dir = working_dir
578 self.crab_dir = crab_dir
579
580 def _check_bad_traits(self, crabdata):
581 """Checks that a package's crab audit meets our requirements.
582
583 Args:
584 crabdata: Dict with crab keys in standard templated format.
585 """
George Burgess IV7dffc252022-08-31 14:37:01 -0700586 common = crabdata["common"]
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -0700587 # TODO(b/200578411) - Figure out what conditions we should enforce as
588 # part of the audit.
589 conditions = [
George Burgess IV7dffc252022-08-31 14:37:01 -0700590 common.get("deny", None),
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -0700591 ]
592
593 # If any conditions are true, this crate is not acceptable.
594 return any(conditions)
595
596 def verify_traits(self):
George Burgess IV7dffc252022-08-31 14:37:01 -0700597 """Verify that all required CRAB traits for this repository are met."""
George Burgess IV18af5632022-08-30 14:10:53 -0700598 metadata = load_metadata(self.working_dir)
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -0700599
600 failing_crates = {}
601
602 # Verify all packages have a CRAB file associated with it and they meet
603 # all our required traits
George Burgess IV18af5632022-08-30 14:10:53 -0700604 for package in metadata["packages"]:
George Burgess IV40cc91c2022-08-15 13:07:40 -0700605 # Skip the synthesized Cargo.toml packages that exist solely to
606 # list dependencies.
George Burgess IV7dffc252022-08-31 14:37:01 -0700607 if "path+file:///" in package["id"]:
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -0700608 continue
609
George Burgess IV7dffc252022-08-31 14:37:01 -0700610 crabname = "{}-{}".format(package["name"], package["version"])
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -0700611 filename = os.path.join(self.crab_dir, "{}.toml".format(crabname))
612
613 # If crab file doesn't exist, the crate fails
614 if not os.path.isfile(filename):
615 failing_crates[crabname] = "No crab file".format(filename)
616 continue
617
George Burgess IV7dffc252022-08-31 14:37:01 -0700618 with open(filename, "r") as f:
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -0700619 crabdata = toml.loads(f.read())
620
621 # If crab file's crate_name and version keys don't match this
622 # package, it also fails. This is just housekeeping...
George Burgess IV7dffc252022-08-31 14:37:01 -0700623 if (
624 package["name"] != crabdata["crate_name"]
625 or package["version"] != crabdata["version"]
626 ):
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -0700627 failing_crates[crabname] = "Crate name or version don't match"
628 continue
629
630 if self._check_bad_traits(crabdata):
631 failing_crates[crabname] = "Failed bad traits check"
632
633 # If we had any failing crates, list them now
634 if failing_crates:
George Burgess IV7dffc252022-08-31 14:37:01 -0700635 print("Failed CRAB audit:")
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -0700636 for k, v in failing_crates.items():
George Burgess IV7dffc252022-08-31 14:37:01 -0700637 print(" {}: {}".format(k, v))
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -0700638
639
George Burgess IVd4ff0502022-08-14 23:27:57 -0700640def clean_features_in_place(cargo_toml):
641 """Removes all side-effects of features in `cargo_toml`."""
George Burgess IV7dffc252022-08-31 14:37:01 -0700642 features = cargo_toml.get("features")
George Burgess IVd4ff0502022-08-14 23:27:57 -0700643 if not features:
644 return
645
646 for name, value in features.items():
George Burgess IV7dffc252022-08-31 14:37:01 -0700647 if name != "default":
George Burgess IVd4ff0502022-08-14 23:27:57 -0700648 features[name] = []
649
650
George Burgess IV0313d782022-08-15 23:45:44 -0700651def remove_all_target_dependencies_in_place(cargo_toml):
George Burgess IVd4ff0502022-08-14 23:27:57 -0700652 """Removes all `target.*.dependencies` from `cargo_toml`."""
George Burgess IV7dffc252022-08-31 14:37:01 -0700653 target = cargo_toml.get("target")
George Burgess IVd4ff0502022-08-14 23:27:57 -0700654 if not target:
655 return
George Burgess IV0313d782022-08-15 23:45:44 -0700656
George Burgess IVd4ff0502022-08-14 23:27:57 -0700657 empty_keys = []
658 for key, values in target.items():
George Burgess IV7dffc252022-08-31 14:37:01 -0700659 values.pop("dependencies", None)
660 values.pop("dev-dependencies", None)
George Burgess IVd4ff0502022-08-14 23:27:57 -0700661 if not values:
662 empty_keys.append(key)
George Burgess IV0313d782022-08-15 23:45:44 -0700663
George Burgess IVd4ff0502022-08-14 23:27:57 -0700664 if len(empty_keys) == len(target):
George Burgess IV7dffc252022-08-31 14:37:01 -0700665 del cargo_toml["target"]
George Burgess IVd4ff0502022-08-14 23:27:57 -0700666 else:
667 for key in empty_keys:
668 del target[key]
George Burgess IV0313d782022-08-15 23:45:44 -0700669
670
George Burgess IV7dffc252022-08-31 14:37:01 -0700671class CrateDestroyer:
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700672 LIB_RS_BODY = """compile_error!("This crate cannot be built for this configuration.");\n"""
673
674 def __init__(self, working_dir, vendor_dir):
675 self.working_dir = working_dir
676 self.vendor_dir = vendor_dir
677
678 def _modify_cargo_toml(self, pkg_path):
George Burgess IV7dffc252022-08-31 14:37:01 -0700679 with open(os.path.join(pkg_path, "Cargo.toml"), "r") as cargo:
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700680 contents = toml.load(cargo)
681
George Burgess IV7dffc252022-08-31 14:37:01 -0700682 package = contents["package"]
George Burgess IVd4ff0502022-08-14 23:27:57 -0700683
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700684 # Change description, license and delete license key
George Burgess IV7dffc252022-08-31 14:37:01 -0700685 package["description"] = "Empty crate that should not build."
686 package["license"] = "Apache-2.0"
George Burgess IVd4ff0502022-08-14 23:27:57 -0700687
George Burgess IV7dffc252022-08-31 14:37:01 -0700688 package.pop("license_file", None)
George Burgess IVd4ff0502022-08-14 23:27:57 -0700689 # If there's no build.rs but we specify `links = "foo"`, Cargo gets
690 # upset.
George Burgess IV7dffc252022-08-31 14:37:01 -0700691 package.pop("links", None)
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700692
George Burgess IV0313d782022-08-15 23:45:44 -0700693 # Some packages have cfg-specific dependencies. Remove them here; we
694 # don't care about the dependencies of an empty package.
695 #
696 # This is a load-bearing optimization: `dev-python/toml` doesn't
697 # always round-trip dumps(loads(x)) correctly when `x` has keys with
698 # strings (b/242589711#comment3). The place this has bitten us so far
699 # is target dependencies, which can be harmlessly removed for now.
George Burgess IVd4ff0502022-08-14 23:27:57 -0700700 #
701 # Cleaning features in-place is also necessary, since we're removing
702 # dependencies, and a feature can enable features in dependencies.
703 # Cargo errors out on `[features] foo = "bar/baz"` if `bar` isn't a
704 # dependency.
705 clean_features_in_place(contents)
George Burgess IV0313d782022-08-15 23:45:44 -0700706 remove_all_target_dependencies_in_place(contents)
707
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700708 with open(os.path.join(pkg_path, "Cargo.toml"), "w") as cargo:
709 toml.dump(contents, cargo)
710
711 def _replace_source_contents(self, package_path):
712 # First load the checksum file before starting
713 checksum_file = os.path.join(package_path, ".cargo-checksum.json")
George Burgess IV7dffc252022-08-31 14:37:01 -0700714 with open(checksum_file, "r") as csum:
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700715 checksum_contents = json.load(csum)
716
717 # Also load the cargo.toml file which we need to write back
718 cargo_file = os.path.join(package_path, "Cargo.toml")
George Burgess IV7dffc252022-08-31 14:37:01 -0700719 with open(cargo_file, "rb") as cfile:
George Burgess IV3e344e42022-08-09 21:07:04 -0700720 cargo_contents = cfile.read()
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700721
722 shutil.rmtree(package_path)
723
724 # Make package and src dirs and replace lib.rs
725 os.makedirs(os.path.join(package_path, "src"), exist_ok=True)
726 with open(os.path.join(package_path, "src", "lib.rs"), "w") as librs:
727 librs.write(self.LIB_RS_BODY)
728
729 # Restore cargo.toml
George Burgess IV7dffc252022-08-31 14:37:01 -0700730 with open(cargo_file, "wb") as cfile:
George Burgess IV3e344e42022-08-09 21:07:04 -0700731 cfile.write(cargo_contents)
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700732
733 # Restore checksum
George Burgess IV7dffc252022-08-31 14:37:01 -0700734 with open(checksum_file, "w") as csum:
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700735 json.dump(checksum_contents, csum)
736
737 def destroy_unused_crates(self):
George Burgess IV18af5632022-08-30 14:10:53 -0700738 metadata = load_metadata(self.working_dir, filter_platform=None)
George Burgess IV7dffc252022-08-31 14:37:01 -0700739 used_packages = {
740 p["name"] for p in load_metadata(self.working_dir)["packages"]
741 }
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700742
743 cleaned_packages = []
George Burgess IV40cc91c2022-08-15 13:07:40 -0700744 # Since we're asking for _all_ metadata packages, we may see
745 # duplication.
George Burgess IV18af5632022-08-30 14:10:53 -0700746 for package in metadata["packages"]:
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700747 # Skip used packages
748 if package["name"] in used_packages:
749 continue
750
751 # Detect the correct package path to destroy
George Burgess IV7dffc252022-08-31 14:37:01 -0700752 pkg_path = os.path.join(
753 self.vendor_dir,
754 "{}-{}".format(package["name"], package["version"]),
755 )
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700756 if not os.path.isdir(pkg_path):
George Burgess IV635f7262022-08-09 21:32:20 -0700757 print(f'Crate {package["name"]} not found at {pkg_path}')
758 continue
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700759
760 self._replace_source_contents(pkg_path)
761 self._modify_cargo_toml(pkg_path)
762 _rerun_checksums(pkg_path)
763 cleaned_packages.append(package["name"])
764
765 for pkg in cleaned_packages:
George Burgess IV635f7262022-08-09 21:32:20 -0700766 print("Removed unused crate", pkg)
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700767
George Burgess IV7dffc252022-08-31 14:37:01 -0700768
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700769def main(args):
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -0800770 current_path = pathlib.Path(__file__).parent.absolute()
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000771 patches = os.path.join(current_path, "patches")
772 vendor = os.path.join(current_path, "vendor")
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -0700773 crab_dir = os.path.join(current_path, "crab", "crates")
George Burgess IV04833702022-08-09 22:00:38 -0700774 license_shorthand_file = os.path.join(current_path, "licenses_used.txt")
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -0800775
Abhishek Pandit-Subedifa902382021-08-20 11:04:33 -0700776 # First, actually run cargo vendor
777 run_cargo_vendor(current_path)
778
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000779 # Order matters here:
780 # - Apply patches (also re-calculates checksums)
781 # - Cleanup any owners files (otherwise, git check-in or checksums are
782 # unhappy)
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700783 # - Destroy unused crates
Abhishek Pandit-Subedi5065a0f2021-06-13 20:38:55 +0000784 apply_patches(patches, vendor)
785 cleanup_owners(vendor)
Abhishek Pandit-Subedif0eb6e02021-09-24 16:36:12 -0700786 destroyer = CrateDestroyer(current_path, vendor)
787 destroyer.destroy_unused_crates()
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -0800788
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700789 # Combine license file and check for any bad licenses
790 lm = LicenseManager(current_path, vendor)
George Burgess IV7dffc252022-08-31 14:37:01 -0700791 lm.generate_license(
792 args.skip_license_check, args.license_map, license_shorthand_file
793 )
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700794
Abhishek Pandit-Subedice0f5b22021-09-10 15:50:08 -0700795 # Run crab audit on all packages
796 crab = CrabManager(current_path, crab_dir)
797 crab.verify_traits()
798
Abhishek Pandit-Subedib75bd562021-02-25 15:32:22 -0800799
George Burgess IV7dffc252022-08-31 14:37:01 -0700800if __name__ == "__main__":
801 parser = argparse.ArgumentParser(description="Vendor packages properly")
802 parser.add_argument(
803 "--skip-license-check",
804 "-s",
805 help="Skip the license check on a specific package",
806 action="append",
807 )
808 parser.add_argument("--license-map", help="Write license map to this file")
Abhishek Pandit-Subedie393cb72021-08-22 10:41:13 -0700809 args = parser.parse_args()
810
811 main(args)