162 lines
7.9 KiB
Python
162 lines
7.9 KiB
Python
#!/usr/bin/env python3
|
|
"""Generate core/THIRD_PARTY_NOTICES.md from `cargo metadata` (all target platforms).
|
|
|
|
Run from anywhere: `python core/tools/third_party_notices.py`. Requires cargo on PATH and the
|
|
dependency sources fetched (`cargo fetch`). Covers every crate reachable through normal
|
|
(non-dev, non-build) dependencies on any platform, plus the libopus sources that
|
|
audiopus_sys builds and links statically.
|
|
"""
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
|
|
CORE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
OUT = os.path.join(CORE, "THIRD_PARTY_NOTICES.md")
|
|
|
|
MIT_TEXT = """Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
of this software and associated documentation files (the "Software"), to deal
|
|
in the Software without restriction, including without limitation the rights
|
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
copies of the Software, and to permit persons to whom the Software is
|
|
furnished to do so, subject to the following conditions:
|
|
|
|
The above copyright notice and this permission notice shall be included in all
|
|
copies or substantial portions of the Software.
|
|
|
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
SOFTWARE."""
|
|
|
|
BSD3_TEXT = """Redistribution and use in source and binary forms, with or without
|
|
modification, are permitted provided that the following conditions are met:
|
|
|
|
1. Redistributions of source code must retain the above copyright notice, this
|
|
list of conditions and the following disclaimer.
|
|
|
|
2. Redistributions in binary form must reproduce the above copyright notice,
|
|
this list of conditions and the following disclaimer in the documentation
|
|
and/or other materials provided with the distribution.
|
|
|
|
3. Neither the name of the copyright holder nor the names of its
|
|
contributors may be used to endorse or promote products derived from
|
|
this software without specific prior written permission.
|
|
|
|
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."""
|
|
|
|
|
|
def fallback_text(pkg):
|
|
"""Standard text for a crate that ships no license file, or None if not MIT/BSD-3-Clause."""
|
|
lic = pkg.get("license") or ""
|
|
holders = ", ".join(pkg.get("authors") or []) or f'the {pkg["name"]} authors ({pkg.get("repository") or "see crates.io"})'
|
|
if "MIT" in lic:
|
|
return "MIT", f"Copyright (c) {holders}\n\n{MIT_TEXT}"
|
|
if "BSD-3-Clause" in lic:
|
|
return "BSD-3-Clause", f"Copyright (c) {holders}\n\n{BSD3_TEXT}"
|
|
return None
|
|
LICENSE_RE = re.compile(r"^(licen[cs]e|copying|notice|copyright|unlicense)", re.IGNORECASE)
|
|
|
|
|
|
def license_files(directory, stop):
|
|
"""License files in the package dir; for crates inside a git checkout, walk up to its root."""
|
|
d = directory
|
|
while True:
|
|
try:
|
|
names = sorted(n for n in os.listdir(d) if LICENSE_RE.match(n) and os.path.isfile(os.path.join(d, n)))
|
|
except OSError:
|
|
names = []
|
|
if names:
|
|
return [os.path.join(d, n) for n in names]
|
|
parent = os.path.dirname(d)
|
|
if d == stop or parent == d or not d.startswith(stop):
|
|
return []
|
|
d = parent
|
|
|
|
|
|
def main():
|
|
meta = json.loads(subprocess.check_output(["cargo", "metadata", "--format-version", "1"], cwd=CORE))
|
|
pkgs = {p["id"]: p for p in meta["packages"]}
|
|
nodes = {n["id"]: n for n in meta["resolve"]["nodes"]}
|
|
root = meta["resolve"]["root"]
|
|
seen, stack = set(), [root]
|
|
while stack:
|
|
nid = stack.pop()
|
|
for dep in nodes[nid]["deps"]:
|
|
if any(k["kind"] is None for k in dep["dep_kinds"]) and dep["pkg"] not in seen:
|
|
seen.add(dep["pkg"])
|
|
stack.append(dep["pkg"])
|
|
|
|
git_root = os.path.join(os.path.expanduser("~"), ".cargo", "git", "checkouts")
|
|
crates, groups, missing = [], {}, []
|
|
for pid in sorted(seen, key=lambda i: (pkgs[i]["name"], pkgs[i]["version"])):
|
|
p = pkgs[pid]
|
|
pdir = os.path.dirname(p["manifest_path"])
|
|
stop = pdir
|
|
if pdir.startswith(git_root):
|
|
stop = git_root
|
|
elif os.path.abspath(pdir).startswith(os.path.join(CORE, "vendor")):
|
|
stop = pdir
|
|
files = license_files(pdir, stop)
|
|
source = p.get("source") or "vendored (core/vendor)"
|
|
crates.append((p["name"], p["version"], p.get("license") or "see files", source))
|
|
if not files:
|
|
missing.append(f'{p["name"]} {p["version"]}')
|
|
fb = fallback_text(p)
|
|
if fb is None:
|
|
sys.exit(f'{p["name"]} {p["version"]}: no license file and no known standard text for {p.get("license")!r}')
|
|
spdx, text = fb
|
|
key = hashlib.sha256(text.encode()).hexdigest()
|
|
groups.setdefault(key, (text, []))[1].append(
|
|
f'{p["name"]} {p["version"]} (no license file in package; standard {spdx} text, license {p.get("license")})')
|
|
for f in files:
|
|
with open(f, "rb") as fh:
|
|
text = fh.read().decode("utf-8", "replace").replace("\r\n", "\n").strip()
|
|
key = hashlib.sha256(text.encode()).hexdigest()
|
|
groups.setdefault(key, (text, []))[1].append(f'{p["name"]} {p["version"]} ({os.path.basename(f)})')
|
|
|
|
opus = None
|
|
for p in pkgs.values():
|
|
if p["name"] == "audiopus_sys" and p["id"] in seen:
|
|
opus = os.path.join(os.path.dirname(p["manifest_path"]), "opus", "COPYING")
|
|
|
|
out = ["# Third-party notices for teamspeach-core", "",
|
|
"Generated by `core/tools/third_party_notices.py` from `cargo metadata`. Lists every crate",
|
|
"reachable through normal dependencies on any target platform (a superset of what a single",
|
|
"platform build links), followed by the license texts shipped with those crates.", "",
|
|
"| Crate | Version | License | Source |", "|---|---|---|---|"]
|
|
for name, ver, lic, src in crates:
|
|
out.append(f"| {name} | {ver} | {lic} | {src} |")
|
|
if missing:
|
|
out += ["", "Crates whose package ships no license file (standard texts of their declared license are "
|
|
"included below with the authors from their Cargo.toml): " + ", ".join(missing) + "."]
|
|
if opus:
|
|
with open(opus, "rb") as fh:
|
|
out += ["", "## libopus (bundled in audiopus_sys, statically linked)", "", "```",
|
|
fh.read().decode("utf-8", "replace").replace("\r\n", "\n").strip(), "```"]
|
|
out += ["", "## License texts", ""]
|
|
for text, users in sorted(groups.values(), key=lambda g: g[1][0]):
|
|
out += ["### " + "; ".join(users), "", "```", text.replace("```", "'''"), "```", ""]
|
|
with open(OUT, "w", encoding="utf-8", newline="\n") as fh:
|
|
fh.write("\n".join(out) + "\n")
|
|
print(f"wrote {OUT}: {len(crates)} crates, {len(groups)} distinct license texts, "
|
|
f"{len(missing)} without files: {', '.join(missing)}", file=sys.stderr)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|