blob: 7821e2c6ea55df8ff14143fc607055e41dbdb5a0 [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
45# patterns to match Apache/MIT licence in LICENSE*
46APACHE_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)
Thiébaud Weksteen8da49112021-02-19 11:59:49 +010054MULTI_LICENSE_COMMENT = ("# Dual-licensed, using the least restrictive "
55 "per go/thirdpartylicenses#same.\n ")
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -070056
57# default owners added to OWNERS
Stephen Hinesce488a72023-10-19 00:34:53 -070058DEFAULT_OWNERS = "include platform/prebuilts/rust:main:/OWNERS\n"
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -070059
60# See b/159487435 Official policy for rust imports METADATA URLs.
61# "license_type: NOTICE" might be optional,
62# but it is already used in most rust crate METADATA.
63# This line format should match the output of external_updater.
Thiébaud Weksteen8da49112021-02-19 11:59:49 +010064METADATA_CONTENT = """name: "{name}"
65description: {description}
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -070066third_party {{
Jeongik Cha4e8edb42023-08-29 11:26:17 +090067 identifier {{
68 type: "crates.io"
Thiébaud Weksteen8da49112021-02-19 11:59:49 +010069 value: "https://crates.io/crates/{name}"
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -070070 }}
Jeongik Cha4e8edb42023-08-29 11:26:17 +090071 identifier {{
72 type: "Archive"
Thiébaud Weksteen8da49112021-02-19 11:59:49 +010073 value: "https://static.crates.io/crates/{name}/{name}-{version}.crate"
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -070074 }}
Thiébaud Weksteen8da49112021-02-19 11:59:49 +010075 version: "{version}"
Matt Schulte055ccb32023-10-30 14:07:27 -070076 {license_comment}license_type: {license_type}
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -070077 last_upgrade_date {{
Thiébaud Weksteen8da49112021-02-19 11:59:49 +010078 year: {year}
79 month: {month}
80 day: {day}
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -070081 }}
82}}
83"""
84
85
86def get_metadata_date():
87 """Return last_upgrade_date in METADATA or today."""
88 # When applied to existing directories to normalize METADATA,
89 # we don't want to change the last_upgrade_date.
90 year, month, day = "", "", ""
91 if os.path.exists("METADATA"):
92 with open("METADATA", "r") as inf:
93 for line in inf:
94 match = YMD_MATCHER.match(line)
95 if match:
96 if match.group(1) == "year":
97 year = match.group(2)
98 elif match.group(1) == "month":
99 month = match.group(2)
100 elif match.group(1) == "day":
101 day = match.group(2)
102 else:
103 match = YMD_LINE_MATCHER.match(line)
104 if match:
105 year, month, day = match.group(1), match.group(2), match.group(3)
106 if year and month and day:
107 print("### Reuse date in METADATA:", year, month, day)
108 return int(year), int(month), int(day)
109 today = datetime.date.today()
110 return today.year, today.month, today.day
111
112
Matt Schulte055ccb32023-10-30 14:07:27 -0700113def add_metadata(name, version, description, license_group, multi_license):
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700114 """Update or add METADATA file."""
115 if os.path.exists("METADATA"):
116 print("### Updating METADATA")
117 else:
118 print("### Adding METADATA")
119 year, month, day = get_metadata_date()
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100120 license_comment = ""
121 if multi_license:
122 license_comment = MULTI_LICENSE_COMMENT
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700123 with open("METADATA", "w") as outf:
124 outf.write(METADATA_CONTENT.format(
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100125 name=name, description=description, version=version,
Matt Schulte055ccb32023-10-30 14:07:27 -0700126 license_comment=license_comment, license_type=license_group, year=year, month=month, day=day))
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700127
128
129def grep_license_keyword(license_file):
130 """Find familiar patterns in a file and return the type."""
131 with open(license_file, "r") as input_file:
132 for line in input_file:
133 if APACHE_MATCHER.match(line):
Matt Schulte055ccb32023-10-30 14:07:27 -0700134 return License(LicenseType.APACHE2, LicenseGroup.NOTICE, license_file)
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700135 if MIT_MATCHER.match(line):
Matt Schulte055ccb32023-10-30 14:07:27 -0700136 return License(LicenseType.MIT, LicenseGroup.NOTICE, license_file)
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700137 if BSD_MATCHER.match(line):
Matt Schulte055ccb32023-10-30 14:07:27 -0700138 return License(LicenseType.BSD_LIKE, LicenseGroup.NOTICE, license_file)
139 if MPL_MATCHER(LicenseType.MPL, license_file):
140 return License(LicenseType.MPL, LicenseGroup.RECIPROCAL, license_file)
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700141 print("ERROR: cannot decide license type in", license_file,
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100142 "assume BSD_LIKE")
Matt Schulte055ccb32023-10-30 14:07:27 -0700143 return License(LicenseType.BSD_LIKE, LicenseGroup.NOTICE, license_file)
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100144
145
146class LicenseType(enum.IntEnum):
147 """A type of license.
148
149 An IntEnum is used to be able to sort by preference. This is mainly the case
150 for dual-licensed Apache/MIT code, for which we prefer the Apache license.
151 The enum name is used to generate the corresponding MODULE_LICENSE_* file.
152 """
153 APACHE2 = 1
154 MIT = 2
155 BSD_LIKE = 3
156 ISC = 4
Matt Schulte055ccb32023-10-30 14:07:27 -0700157 MPL = 5
158
159class LicenseGroup(enum.Enum):
160 """A group of license as defined by go/thirdpartylicenses#types
161
162 Note, go/thirdpartylicenses#types calls them "types". But LicenseType was
163 already taken so this script calls them groups.
164 """
165 RESTRICTED = 1
166 RESTRICTED_IF_STATICALLY_LINKED = 2
167 RECIPROCAL = 3
168 NOTICE = 4
169 PERMISSIVE = 5
170 BY_EXCEPTION_ONLY = 6
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100171
172
Matt Schulte055ccb32023-10-30 14:07:27 -0700173License = collections.namedtuple('License', ['type', 'group', 'filename'])
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700174
175
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700176def decide_license_type(cargo_license):
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100177 """Check LICENSE* files to determine the license type.
178
179 Returns: A list of Licenses. The first element is the license we prefer.
180 """
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700181 # Most crates.io packages have both APACHE and MIT.
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700182 # Some crate like time-macros-impl uses lower case names like LICENSE-Apache.
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100183 licenses = []
184 license_file = None
Matthew Maurer51ec0162022-08-10 15:29:24 -0700185 for license_file in glob.glob("LICENSE*") + glob.glob("COPYING*"):
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700186 lowered_name = license_file.lower()
187 if lowered_name == "license-apache":
Matt Schulte055ccb32023-10-30 14:07:27 -0700188 licenses.append(License(LicenseType.APACHE2, LicenseGroup.NOTICE, license_file))
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700189 elif lowered_name == "license-mit":
Matt Schulte055ccb32023-10-30 14:07:27 -0700190 licenses.append(License(LicenseType.MIT, LicenseGroup.NOTICE, license_file))
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100191 if licenses:
192 licenses.sort(key=lambda l: l.type)
193 return licenses
194 if not license_file:
195 raise FileNotFoundError("No license file has been found.")
Matthew Maurer51ec0162022-08-10 15:29:24 -0700196 # There is a LICENSE* or COPYING* file, use cargo_license found in
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100197 # Cargo.toml.
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700198 if "Apache" in cargo_license:
Matt Schulte055ccb32023-10-30 14:07:27 -0700199 return [License(LicenseType.APACHE2, LicenseGroup.NOTICE, license_file)]
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700200 if "MIT" in cargo_license:
Matt Schulte055ccb32023-10-30 14:07:27 -0700201 return [License(LicenseType.MIT, LicenseGroup.NOTICE, license_file)]
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700202 if "BSD" in cargo_license:
Matt Schulte055ccb32023-10-30 14:07:27 -0700203 return [License(LicenseType.BSD_LIKE, LicenseGroup.NOTICE, license_file)]
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700204 if "ISC" in cargo_license:
Matt Schulte055ccb32023-10-30 14:07:27 -0700205 return [License(LicenseType.ISC, LicenseGroup.NOTICE, license_file)]
206 if "MPL" in cargo_license:
207 return [License(LicenseType.MPL, LicenseGroup.RECIPROCAL, license_file)]
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100208 return [grep_license_keyword(license_file)]
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700209
210
211def add_notice():
212 if not os.path.exists("NOTICE"):
213 if os.path.exists("LICENSE"):
214 os.symlink("LICENSE", "NOTICE")
215 print("Created link from NOTICE to LICENSE")
216 else:
217 print("ERROR: missing NOTICE and LICENSE")
218
219
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700220def check_license_link(target):
221 """Check the LICENSE link, must bet the given target."""
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700222 if not os.path.islink("LICENSE"):
223 print("ERROR: LICENSE file is not a link")
224 return
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700225 found_target = os.readlink("LICENSE")
226 if target != found_target and found_target != "LICENSE.txt":
227 print("ERROR: found LICENSE link to", found_target,
228 "but expected", target)
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700229
230
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700231def add_license(target):
232 """Add LICENSE link to give target."""
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700233 if os.path.exists("LICENSE"):
234 if os.path.islink("LICENSE"):
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700235 check_license_link(target)
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700236 else:
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100237 print("NOTE: found LICENSE and it is not a link.")
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700238 return
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700239 print("### Creating LICENSE link to", target)
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700240 os.symlink(target, "LICENSE")
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700241
242
243def add_module_license(license_type):
244 """Touch MODULE_LICENSE_type file."""
245 # Do not change existing MODULE_* files.
Matt Schulte055ccb32023-10-30 14:07:27 -0700246 for suffix in ["MIT", "APACHE", "APACHE2", "BSD_LIKE", "MPL"]:
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700247 module_file = "MODULE_LICENSE_" + suffix
248 if os.path.exists(module_file):
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100249 if license_type.name != suffix:
250 raise Exception("Found unexpected license " + module_file)
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700251 return
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100252 module_file = "MODULE_LICENSE_" + license_type.name.upper()
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700253 pathlib.Path(module_file).touch()
254 print("### Touched", module_file)
255
256
257def found_line(file_name, line):
258 """Returns true if the given line is found in a file."""
259 with open(file_name, "r") as input_file:
260 return line in input_file
261
262
263def add_owners():
264 """Create or append OWNERS with the default owner line."""
265 # Existing OWNERS file might contain more than the default owners.
266 # Only append missing default owners to existing OWNERS.
267 if os.path.isfile("OWNERS"):
268 if found_line("OWNERS", DEFAULT_OWNERS):
269 print("### No change to OWNERS, which has already default owners.")
270 return
271 else:
272 print("### Append default owners to OWNERS")
273 mode = "a"
274 else:
275 print("### Creating OWNERS with default owners")
276 mode = "w"
277 with open("OWNERS", mode) as outf:
278 outf.write(DEFAULT_OWNERS)
279
280
281def toml2json(line):
282 """Convert a quoted toml string to a json quoted string for METADATA."""
283 if line.startswith("\"\"\""):
284 return "\"()\"" # cannot handle broken multi-line description
285 # TOML string escapes: \b \t \n \f \r \" \\ (no unicode escape)
286 line = line[1:-1].replace("\\\\", "\n").replace("\\b", "")
287 line = line.replace("\\t", " ").replace("\\n", " ").replace("\\f", " ")
288 line = line.replace("\\r", "").replace("\\\"", "\"").replace("\n", "\\")
289 # replace a unicode quotation mark, used in the libloading crate
290 line = line.replace("’", "'")
291 # strip and escape single quotes
292 return json.dumps(line.strip()).replace("'", "\\'")
293
294
295def parse_cargo_toml(cargo):
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700296 """get name, version, description, license string from Cargo.toml."""
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700297 name = ""
298 version = ""
299 description = ""
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700300 cargo_license = ""
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700301 with open(cargo, "r") as toml:
302 for line in toml:
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700303 if not name and NAME_MATCHER.match(line):
304 name = NAME_MATCHER.match(line).group(1)
305 elif not version and VERSION_MATCHER.match(line):
306 version = VERSION_MATCHER.match(line).group(1)
307 elif not description and DESCRIPTION_MATCHER.match(line):
308 description = toml2json(DESCRIPTION_MATCHER.match(line).group(1))
309 elif not cargo_license and LICENSE_MATCHER.match(line):
310 cargo_license = LICENSE_MATCHER.match(line).group(1)
311 if name and version and description and cargo_license:
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700312 break
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700313 return name, version, description, cargo_license
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700314
315
316def main():
317 """Add 3rd party review files."""
318 cargo = "Cargo.toml"
319 if not os.path.isfile(cargo):
320 print("ERROR: ", cargo, "is not found")
321 return
322 if not os.access(cargo, os.R_OK):
323 print("ERROR: ", cargo, "is not readable")
324 return
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700325 name, version, description, cargo_license = parse_cargo_toml(cargo)
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700326 if not name or not version or not description:
327 print("ERROR: Cannot find name, version, or description in", cargo)
328 return
Chih-Hung Hsieh03f14e42020-10-19 18:38:30 -0700329 print("### Cargo.toml license:", cargo_license)
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100330 licenses = decide_license_type(cargo_license)
331 preferred_license = licenses[0]
Matt Schulte055ccb32023-10-30 14:07:27 -0700332 add_metadata(name, version, description, preferred_license.group.name, len(licenses) > 1)
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700333 add_owners()
Thiébaud Weksteen8da49112021-02-19 11:59:49 +0100334 add_license(preferred_license.filename)
335 add_module_license(preferred_license.type)
Chih-Hung Hsieh3d24aed2020-10-05 15:29:11 -0700336 # It is unclear yet if a NOTICE file is required.
337 # add_notice()
338
339
340if __name__ == "__main__":
341 main()