blob: 985cfa55f67bb2bc89c753de033495684f176d3f [file] [log] [blame]
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -07001#!/usr/bin/env python3
2#
3# Copyright (C) 2020 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16"""Add files to a Rust package for third party review."""
17
Thiébaud Weksteen8da49112021-02-19 11:59:49 +010018import collections
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -070019import datetime
Thiébaud Weksteen8da49112021-02-19 11:59:49 +010020import enum
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -070021import glob
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -070022import json
23import os
24import pathlib
25import re
26
27# patterns to match keys in Cargo.toml
28NAME_PATTERN = r"^name *= *\"(.+)\""
29NAME_MATCHER = re.compile(NAME_PATTERN)
30VERSION_PATTERN = r"^version *= *\"(.+)\""
31VERSION_MATCHER = re.compile(VERSION_PATTERN)
32DESCRIPTION_PATTERN = r"^description *= *(\".+\")"
33DESCRIPTION_MATCHER = re.compile(DESCRIPTION_PATTERN)
34# NOTE: This description one-liner pattern fails to match
35# multi-line descriptions in some Rust crates, e.g. shlex.
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -070036LICENSE_PATTERN = r"^license *= *\"(.+)\""
37LICENSE_MATCHER = re.compile(LICENSE_PATTERN)
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -070038
39# patterns to match year/month/day in METADATA
40YMD_PATTERN = r"^ +(year|month|day): (.+)$"
41YMD_MATCHER = re.compile(YMD_PATTERN)
42YMD_LINE_PATTERN = r"^.* year: *([^ ]+) +month: *([^ ]+) +day: *([^ ]+).*$"
43YMD_LINE_MATCHER = re.compile(YMD_LINE_PATTERN)
44
Matt Schulte38d199e2023-12-20 10:05:57 -080045# patterns to match different licence types in LICENSE*
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -070046APACHE_PATTERN = r"^.*Apache License.*$"
47APACHE_MATCHER = re.compile(APACHE_PATTERN)
48MIT_PATTERN = r"^.*MIT License.*$"
49MIT_MATCHER = re.compile(MIT_PATTERN)
50BSD_PATTERN = r"^.*BSD .*License.*$"
51BSD_MATCHER = re.compile(BSD_PATTERN)
Matt Schulte055ccb32023-10-30 14:07:27 -070052MPL_PATTERN = r"^.Mozilla Public License.*$"
53MPL_MATCHER = re.compile(MPL_PATTERN)
Matt Schulte38d199e2023-12-20 10:05:57 -080054ZERO_BSD_PATTERN = r"^.*Zero-Clause BSD.*$"
55ZERO_BSD_MATCHER = re.compile(ZERO_BSD_PATTERN)
Thiébaud Weksteen8da49112021-02-19 11:59:49 +010056MULTI_LICENSE_COMMENT = ("# Dual-licensed, using the least restrictive "
57 "per go/thirdpartylicenses#same.\n ")
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -070058
59# default owners added to OWNERS
Stephen Hinesce488a72023-10-19 00:34:53 -070060DEFAULT_OWNERS = "include platform/prebuilts/rust:main:/OWNERS\n"
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -070061
62# See b/159487435 Official policy for rust imports METADATA URLs.
63# "license_type: NOTICE" might be optional,
64# but it is already used in most rust crate METADATA.
65# This line format should match the output of external_updater.
Thiébaud Weksteen8da49112021-02-19 11:59:49 +010066METADATA_CONTENT = """name: "{name}"
67description: {description}
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -070068third_party {{
Jeongik Cha4e8edb42023-08-29 11:26:17 +090069 identifier {{
70 type: "crates.io"
Thiébaud Weksteen8da49112021-02-19 11:59:49 +010071 value: "https://crates.io/crates/{name}"
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -070072 }}
Jeongik Cha4e8edb42023-08-29 11:26:17 +090073 identifier {{
74 type: "Archive"
Thiébaud Weksteen8da49112021-02-19 11:59:49 +010075 value: "https://static.crates.io/crates/{name}/{name}-{version}.crate"
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -070076 }}
Thiébaud Weksteen8da49112021-02-19 11:59:49 +010077 version: "{version}"
Matt Schulte055ccb32023-10-30 14:07:27 -070078 {license_comment}license_type: {license_type}
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -070079 last_upgrade_date {{
Thiébaud Weksteen8da49112021-02-19 11:59:49 +010080 year: {year}
81 month: {month}
82 day: {day}
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -070083 }}
84}}
85"""
86
87
88def get_metadata_date():
89 """Return last_upgrade_date in METADATA or today."""
90 # When applied to existing directories to normalize METADATA,
91 # we don't want to change the last_upgrade_date.
92 year, month, day = "", "", ""
93 if os.path.exists("METADATA"):
94 with open("METADATA", "r") as inf:
95 for line in inf:
96 match = YMD_MATCHER.match(line)
97 if match:
98 if match.group(1) == "year":
99 year = match.group(2)
100 elif match.group(1) == "month":
101 month = match.group(2)
102 elif match.group(1) == "day":
103 day = match.group(2)
104 else:
105 match = YMD_LINE_MATCHER.match(line)
106 if match:
107 year, month, day = match.group(1), match.group(2), match.group(3)
108 if year and month and day:
109 print("### Reuse date in METADATA:", year, month, day)
110 return int(year), int(month), int(day)
111 today = datetime.date.today()
112 return today.year, today.month, today.day
113
114
Matt Schulte055ccb32023-10-30 14:07:27 -0700115def add_metadata(name, version, description, license_group, multi_license):
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700116 """Update or add METADATA file."""
117 if os.path.exists("METADATA"):
118 print("### Updating METADATA")
119 else:
120 print("### Adding METADATA")
121 year, month, day = get_metadata_date()
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100122 license_comment = ""
123 if multi_license:
124 license_comment = MULTI_LICENSE_COMMENT
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700125 with open("METADATA", "w") as outf:
126 outf.write(METADATA_CONTENT.format(
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100127 name=name, description=description, version=version,
Matt Schulte055ccb32023-10-30 14:07:27 -0700128 license_comment=license_comment, license_type=license_group, year=year, month=month, day=day))
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700129
130
131def grep_license_keyword(license_file):
132 """Find familiar patterns in a file and return the type."""
133 with open(license_file, "r") as input_file:
134 for line in input_file:
135 if APACHE_MATCHER.match(line):
Matt Schulte055ccb32023-10-30 14:07:27 -0700136 return License(LicenseType.APACHE2, LicenseGroup.NOTICE, license_file)
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700137 if MIT_MATCHER.match(line):
Matt Schulte055ccb32023-10-30 14:07:27 -0700138 return License(LicenseType.MIT, LicenseGroup.NOTICE, license_file)
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700139 if BSD_MATCHER.match(line):
Matt Schulte055ccb32023-10-30 14:07:27 -0700140 return License(LicenseType.BSD_LIKE, LicenseGroup.NOTICE, license_file)
Matt Schulte362d7f42023-12-20 07:54:03 -0800141 if MPL_MATCHER.match(line):
Matt Schulte055ccb32023-10-30 14:07:27 -0700142 return License(LicenseType.MPL, LicenseGroup.RECIPROCAL, license_file)
Matt Schulte38d199e2023-12-20 10:05:57 -0800143 if ZERO_BSD_MATCHER.match(line):
144 return License(LicenseType.ZERO_BSD, LicenseGroup.PERMISSIVE, license_file)
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700145 print("ERROR: cannot decide license type in", license_file,
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100146 "assume BSD_LIKE")
Matt Schulte055ccb32023-10-30 14:07:27 -0700147 return License(LicenseType.BSD_LIKE, LicenseGroup.NOTICE, license_file)
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100148
149
150class LicenseType(enum.IntEnum):
151 """A type of license.
152
153 An IntEnum is used to be able to sort by preference. This is mainly the case
154 for dual-licensed Apache/MIT code, for which we prefer the Apache license.
155 The enum name is used to generate the corresponding MODULE_LICENSE_* file.
156 """
157 APACHE2 = 1
158 MIT = 2
159 BSD_LIKE = 3
160 ISC = 4
Matt Schulte055ccb32023-10-30 14:07:27 -0700161 MPL = 5
Matt Schulte38d199e2023-12-20 10:05:57 -0800162 ZERO_BSD = 6
Matt Schulte055ccb32023-10-30 14:07:27 -0700163
164class LicenseGroup(enum.Enum):
165 """A group of license as defined by go/thirdpartylicenses#types
166
167 Note, go/thirdpartylicenses#types calls them "types". But LicenseType was
168 already taken so this script calls them groups.
169 """
170 RESTRICTED = 1
171 RESTRICTED_IF_STATICALLY_LINKED = 2
172 RECIPROCAL = 3
173 NOTICE = 4
174 PERMISSIVE = 5
175 BY_EXCEPTION_ONLY = 6
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100176
177
Matt Schulte055ccb32023-10-30 14:07:27 -0700178License = collections.namedtuple('License', ['type', 'group', 'filename'])
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700179
180
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700181def decide_license_type(cargo_license):
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100182 """Check LICENSE* files to determine the license type.
183
184 Returns: A list of Licenses. The first element is the license we prefer.
185 """
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700186 # Most crates.io packages have both APACHE and MIT.
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700187 # Some crate like time-macros-impl uses lower case names like LICENSE-Apache.
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100188 licenses = []
189 license_file = None
Matthew Maurer51ec0162022-08-10 15:29:24 -0700190 for license_file in glob.glob("LICENSE*") + glob.glob("COPYING*"):
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700191 lowered_name = license_file.lower()
192 if lowered_name == "license-apache":
Matt Schulte055ccb32023-10-30 14:07:27 -0700193 licenses.append(License(LicenseType.APACHE2, LicenseGroup.NOTICE, license_file))
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700194 elif lowered_name == "license-mit":
Matt Schulte055ccb32023-10-30 14:07:27 -0700195 licenses.append(License(LicenseType.MIT, LicenseGroup.NOTICE, license_file))
Matt Schulte38d199e2023-12-20 10:05:57 -0800196 elif lowered_name == "license-0bsd":
197 licenses.append(License(LicenseType.ZERO_BSD, LicenseGroup.PERMISSIVE, license_file))
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100198 if licenses:
199 licenses.sort(key=lambda l: l.type)
200 return licenses
201 if not license_file:
202 raise FileNotFoundError("No license file has been found.")
Matthew Maurer51ec0162022-08-10 15:29:24 -0700203 # There is a LICENSE* or COPYING* file, use cargo_license found in
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100204 # Cargo.toml.
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700205 if "Apache" in cargo_license:
Matt Schulte055ccb32023-10-30 14:07:27 -0700206 return [License(LicenseType.APACHE2, LicenseGroup.NOTICE, license_file)]
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700207 if "MIT" in cargo_license:
Matt Schulte055ccb32023-10-30 14:07:27 -0700208 return [License(LicenseType.MIT, LicenseGroup.NOTICE, license_file)]
Matt Schulte38d199e2023-12-20 10:05:57 -0800209 if "0BSD" in cargo_license:
210 return [License(LicenseType.ZERO_BSD, LicenseGroup.PERMISSIVE, license_file)]
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700211 if "BSD" in cargo_license:
Matt Schulte055ccb32023-10-30 14:07:27 -0700212 return [License(LicenseType.BSD_LIKE, LicenseGroup.NOTICE, license_file)]
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700213 if "ISC" in cargo_license:
Matt Schulte055ccb32023-10-30 14:07:27 -0700214 return [License(LicenseType.ISC, LicenseGroup.NOTICE, license_file)]
215 if "MPL" in cargo_license:
216 return [License(LicenseType.MPL, LicenseGroup.RECIPROCAL, license_file)]
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100217 return [grep_license_keyword(license_file)]
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700218
219
220def add_notice():
221 if not os.path.exists("NOTICE"):
222 if os.path.exists("LICENSE"):
223 os.symlink("LICENSE", "NOTICE")
224 print("Created link from NOTICE to LICENSE")
225 else:
226 print("ERROR: missing NOTICE and LICENSE")
227
228
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700229def check_license_link(target):
230 """Check the LICENSE link, must bet the given target."""
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700231 if not os.path.islink("LICENSE"):
232 print("ERROR: LICENSE file is not a link")
233 return
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700234 found_target = os.readlink("LICENSE")
235 if target != found_target and found_target != "LICENSE.txt":
236 print("ERROR: found LICENSE link to", found_target,
237 "but expected", target)
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700238
239
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700240def add_license(target):
241 """Add LICENSE link to give target."""
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700242 if os.path.exists("LICENSE"):
243 if os.path.islink("LICENSE"):
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700244 check_license_link(target)
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700245 else:
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100246 print("NOTE: found LICENSE and it is not a link.")
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700247 return
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700248 print("### Creating LICENSE link to", target)
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700249 os.symlink(target, "LICENSE")
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700250
251
252def add_module_license(license_type):
253 """Touch MODULE_LICENSE_type file."""
254 # Do not change existing MODULE_* files.
Matt Schulte38d199e2023-12-20 10:05:57 -0800255 for suffix in ["MIT", "APACHE", "APACHE2", "BSD_LIKE", "MPL", "0BSD"]:
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700256 module_file = "MODULE_LICENSE_" + suffix
257 if os.path.exists(module_file):
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100258 if license_type.name != suffix:
259 raise Exception("Found unexpected license " + module_file)
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700260 return
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100261 module_file = "MODULE_LICENSE_" + license_type.name.upper()
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700262 pathlib.Path(module_file).touch()
263 print("### Touched", module_file)
264
265
266def found_line(file_name, line):
267 """Returns true if the given line is found in a file."""
268 with open(file_name, "r") as input_file:
269 return line in input_file
270
271
272def add_owners():
273 """Create or append OWNERS with the default owner line."""
274 # Existing OWNERS file might contain more than the default owners.
275 # Only append missing default owners to existing OWNERS.
276 if os.path.isfile("OWNERS"):
277 if found_line("OWNERS", DEFAULT_OWNERS):
278 print("### No change to OWNERS, which has already default owners.")
279 return
280 else:
281 print("### Append default owners to OWNERS")
282 mode = "a"
283 else:
284 print("### Creating OWNERS with default owners")
285 mode = "w"
286 with open("OWNERS", mode) as outf:
287 outf.write(DEFAULT_OWNERS)
288
289
290def toml2json(line):
291 """Convert a quoted toml string to a json quoted string for METADATA."""
292 if line.startswith("\"\"\""):
293 return "\"()\"" # cannot handle broken multi-line description
294 # TOML string escapes: \b \t \n \f \r \" \\ (no unicode escape)
295 line = line[1:-1].replace("\\\\", "\n").replace("\\b", "")
296 line = line.replace("\\t", " ").replace("\\n", " ").replace("\\f", " ")
297 line = line.replace("\\r", "").replace("\\\"", "\"").replace("\n", "\\")
298 # replace a unicode quotation mark, used in the libloading crate
299 line = line.replace("’", "'")
300 # strip and escape single quotes
301 return json.dumps(line.strip()).replace("'", "\\'")
302
303
304def parse_cargo_toml(cargo):
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700305 """get name, version, description, license string from Cargo.toml."""
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700306 name = ""
307 version = ""
308 description = ""
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700309 cargo_license = ""
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700310 with open(cargo, "r") as toml:
311 for line in toml:
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700312 if not name and NAME_MATCHER.match(line):
313 name = NAME_MATCHER.match(line).group(1)
314 elif not version and VERSION_MATCHER.match(line):
315 version = VERSION_MATCHER.match(line).group(1)
316 elif not description and DESCRIPTION_MATCHER.match(line):
317 description = toml2json(DESCRIPTION_MATCHER.match(line).group(1))
318 elif not cargo_license and LICENSE_MATCHER.match(line):
319 cargo_license = LICENSE_MATCHER.match(line).group(1)
320 if name and version and description and cargo_license:
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700321 break
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700322 return name, version, description, cargo_license
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700323
324
325def main():
326 """Add 3rd party review files."""
327 cargo = "Cargo.toml"
328 if not os.path.isfile(cargo):
329 print("ERROR: ", cargo, "is not found")
330 return
331 if not os.access(cargo, os.R_OK):
332 print("ERROR: ", cargo, "is not readable")
333 return
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700334 name, version, description, cargo_license = parse_cargo_toml(cargo)
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700335 if not name or not version or not description:
336 print("ERROR: Cannot find name, version, or description in", cargo)
337 return
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700338 print("### Cargo.toml license:", cargo_license)
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100339 licenses = decide_license_type(cargo_license)
340 preferred_license = licenses[0]
Matt Schulte055ccb32023-10-30 14:07:27 -0700341 add_metadata(name, version, description, preferred_license.group.name, len(licenses) > 1)
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700342 add_owners()
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100343 add_license(preferred_license.filename)
344 add_module_license(preferred_license.type)
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700345 # It is unclear yet if a NOTICE file is required.
346 # add_notice()
347
348
349if __name__ == "__main__":
350 main()