| # Copyright 2022 Google LLC |
| # |
| # This program is free software; you can redistribute it and/or |
| # modify it under the terms of the GNU General Public License |
| # version 2 as published by the Free Software Foundation. |
| # |
| # This program is distributed in the hope that it will be useful, |
| # but WITHOUT ANY WARRANTY; without even the implied warranty of |
| # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| # GNU General Public License for more details. |
| # |
| |
| # This script is used to parse licenses of a package. |
| |
| import re |
| import os |
| |
| # Parse LICENSE is a ebuild. |
| def parse_gentoo_license(line): |
| license_set = set() |
| use_or = False |
| res = "" |
| for e in line.strip().split(" "): |
| if e == "||": |
| use_or = True |
| elif e == "(": |
| if res: |
| res += "AND (" |
| else: |
| res += "(" |
| elif e == ")": |
| res = f"{res[:-1]}) " |
| use_or = False |
| else: |
| license_set.add(e) |
| if not res or res.endswith("("): |
| res += f"{e} " |
| elif use_or: |
| res += f"OR {e} " |
| else: |
| res += f"AND {e} " |
| return res.strip(), license_set |
| |
| |
| # If a license is in license.yaml but not LICENSE, |
| # add it to the result. |
| def parse_license_yaml(yaml, res, license_set): |
| lines = yaml.strip().split("\n") |
| idx = lines.index(" - license_names") + 1 |
| match = re.findall("\{(.*?)\}", lines[idx], re.DOTALL) |
| if not match: |
| return res |
| found = [] |
| for m in match: |
| for part in m.split(","): |
| found.append(part.split(":")[0]) |
| for license in found: |
| license = license.strip() |
| if license and not license in license_set: |
| license_set.add(license) |
| res += f" AND {license}" |
| return res |
| |
| |
| def get_licenses(build_info_dir): |
| if not os.path.exists(os.path.join(build_info_dir, "LICENSE")): |
| return "" |
| with open(os.path.join(build_info_dir, "LICENSE"), "r") as f: |
| res, license_set = parse_gentoo_license(f.read()) |
| with open(os.path.join(build_info_dir, "license.yaml"), "r") as y: |
| return parse_license_yaml(y.read(), res, license_set) |