274 lines
10 KiB
Python
Executable File
274 lines
10 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Collect deterministic license notices from an installed npm dependency tree."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import shutil
|
|
import stat
|
|
import sys
|
|
import tempfile
|
|
from typing import Any
|
|
from urllib.parse import quote
|
|
|
|
|
|
NOTICE_FILE_PATTERN = re.compile(
|
|
r"^(?:licen[cs]e|copying|notice|copyright)(?:$|[._-].*)",
|
|
re.IGNORECASE,
|
|
)
|
|
|
|
|
|
class CollectionError(RuntimeError):
|
|
"""Raised when dependency metadata cannot produce a trustworthy notice."""
|
|
|
|
|
|
def is_package_root(package_json: Path, node_modules: Path) -> bool:
|
|
relative_parts = package_json.parent.relative_to(node_modules).parts
|
|
node_modules_indices = [
|
|
index
|
|
for index, component in enumerate(relative_parts)
|
|
if component == "node_modules"
|
|
]
|
|
package_start = node_modules_indices[-1] + 1 if node_modules_indices else 0
|
|
package_parts = relative_parts[package_start:]
|
|
if len(package_parts) == 1:
|
|
return not package_parts[0].startswith("@")
|
|
return (
|
|
len(package_parts) == 2
|
|
and package_parts[0].startswith("@")
|
|
and len(package_parts[0]) > 1
|
|
)
|
|
|
|
|
|
def package_json_files(node_modules: Path) -> list[Path]:
|
|
def fail_walk(error: OSError) -> None:
|
|
raise CollectionError(f"cannot scan {error.filename}: {error.strerror}")
|
|
|
|
package_files: list[Path] = []
|
|
for directory, child_directories, filenames in os.walk(
|
|
node_modules, followlinks=False, onerror=fail_walk
|
|
):
|
|
child_directories.sort()
|
|
filenames.sort()
|
|
if "package.json" not in filenames:
|
|
continue
|
|
candidate = Path(directory, "package.json")
|
|
if not stat.S_ISREG(candidate.lstat().st_mode):
|
|
continue
|
|
if is_package_root(candidate, node_modules):
|
|
package_files.append(candidate)
|
|
return package_files
|
|
|
|
|
|
def require_metadata_text(metadata: dict[str, Any], field: str, source: Path) -> str:
|
|
value = metadata.get(field)
|
|
if not isinstance(value, str) or not value.strip():
|
|
raise CollectionError(f"{source}: {field!r} must be a non-empty string")
|
|
value = value.strip()
|
|
if any(ord(character) < 32 or ord(character) == 127 for character in value):
|
|
raise CollectionError(f"{source}: {field!r} contains control characters")
|
|
return value
|
|
|
|
|
|
def require_plain_text(value: Any, description: str, source: Path) -> str:
|
|
if not isinstance(value, str) or not value.strip():
|
|
raise CollectionError(f"{source}: {description} must be a non-empty string")
|
|
value = value.strip()
|
|
if any(ord(character) < 32 or ord(character) == 127 for character in value):
|
|
raise CollectionError(f"{source}: {description} contains control characters")
|
|
return value
|
|
|
|
|
|
def validate_package_name(name: str, source: Path) -> None:
|
|
components = name.split("/")
|
|
valid_scope = (
|
|
len(components) == 2
|
|
and components[0].startswith("@")
|
|
and len(components[0]) > 1
|
|
)
|
|
if not (len(components) == 1 and not name.startswith("@")) and not valid_scope:
|
|
raise CollectionError(f"{source}: invalid npm package name {name!r}")
|
|
if any(component in {"", ".", ".."} for component in components):
|
|
raise CollectionError(f"{source}: invalid npm package name {name!r}")
|
|
if "\\" in name:
|
|
raise CollectionError(f"{source}: invalid npm package name {name!r}")
|
|
|
|
|
|
def describe_license_entry(value: Any, source: Path) -> str:
|
|
if isinstance(value, str):
|
|
return require_plain_text(value, "license", source)
|
|
if isinstance(value, dict):
|
|
description = require_plain_text(
|
|
value.get("type"), "license object type", source
|
|
)
|
|
license_url = value.get("url")
|
|
if license_url is not None:
|
|
description += (
|
|
f" ({require_plain_text(license_url, 'license URL', source)})"
|
|
)
|
|
return description
|
|
raise CollectionError(f"{source}: license metadata has an unsupported form")
|
|
|
|
|
|
def declared_license(metadata: dict[str, Any], source: Path) -> str:
|
|
if "license" in metadata:
|
|
return describe_license_entry(metadata["license"], source)
|
|
|
|
legacy_licenses = metadata.get("licenses")
|
|
if not isinstance(legacy_licenses, list) or not legacy_licenses:
|
|
raise CollectionError(f"{source}: package has no declared license")
|
|
descriptions = sorted(
|
|
{describe_license_entry(value, source) for value in legacy_licenses}
|
|
)
|
|
return "; ".join(descriptions)
|
|
|
|
|
|
def notice_files(package_root: Path) -> dict[str, bytes]:
|
|
notices: dict[str, bytes] = {}
|
|
with os.scandir(package_root) as entries:
|
|
for entry in sorted(entries, key=lambda candidate: candidate.name):
|
|
if not NOTICE_FILE_PATTERN.match(entry.name):
|
|
continue
|
|
if not entry.is_file(follow_symlinks=False):
|
|
continue
|
|
notices[entry.name] = Path(entry.path).read_bytes()
|
|
return notices
|
|
|
|
|
|
def output_component(value: str, *, safe: str) -> str:
|
|
return quote(value, safe=safe)
|
|
|
|
|
|
def collect(node_modules: Path, destination: Path) -> int:
|
|
if not node_modules.is_dir():
|
|
raise CollectionError(f"node_modules directory does not exist: {node_modules}")
|
|
|
|
packages: dict[tuple[str, str], tuple[str, dict[str, bytes], Path]] = {}
|
|
for package_file in package_json_files(node_modules):
|
|
try:
|
|
metadata = json.loads(package_file.read_text(encoding="utf-8"))
|
|
except (OSError, UnicodeError, json.JSONDecodeError) as error:
|
|
raise CollectionError(f"cannot read {package_file}: {error}") from error
|
|
if not isinstance(metadata, dict):
|
|
raise CollectionError(f"{package_file}: package metadata must be an object")
|
|
|
|
name = require_metadata_text(metadata, "name", package_file)
|
|
version = require_metadata_text(metadata, "version", package_file)
|
|
validate_package_name(name, package_file)
|
|
license_description = declared_license(metadata, package_file)
|
|
notices = notice_files(package_file.parent)
|
|
key = (name, version)
|
|
|
|
previous = packages.get(key)
|
|
if previous is not None:
|
|
previous_license, previous_notices, previous_source = previous
|
|
if previous_license != license_description or previous_notices != notices:
|
|
raise CollectionError(
|
|
f"conflicting contents for {name}@{version}: "
|
|
f"{previous_source} and {package_file}"
|
|
)
|
|
continue
|
|
packages[key] = (license_description, notices, package_file)
|
|
|
|
if not packages:
|
|
raise CollectionError(f"no npm packages found below {node_modules}")
|
|
|
|
destination_parent = destination.parent
|
|
destination_parent.mkdir(parents=True, exist_ok=True)
|
|
temporary = Path(
|
|
tempfile.mkdtemp(prefix=f".{destination.name}.", dir=destination_parent)
|
|
)
|
|
try:
|
|
temporary.chmod(0o755)
|
|
notice_lines = [
|
|
"Echoion frontend third-party notices",
|
|
"",
|
|
"Generated from the installed npm dependency tree.",
|
|
"Packages are sorted by name and version.",
|
|
"",
|
|
]
|
|
output_directories: set[str] = set()
|
|
for (name, version), (license_description, notices, _) in sorted(
|
|
packages.items()
|
|
):
|
|
directory_name = (
|
|
output_component(name, safe="@._+-")
|
|
+ "@"
|
|
+ output_component(version, safe="._+-")
|
|
)
|
|
if directory_name in output_directories:
|
|
raise CollectionError(
|
|
f"output-name collision while collecting {name}@{version}"
|
|
)
|
|
output_directories.add(directory_name)
|
|
|
|
package_destination = temporary / directory_name
|
|
package_destination.mkdir(mode=0o755)
|
|
package_destination.chmod(0o755)
|
|
copied_files: list[str] = []
|
|
for filename, contents in sorted(notices.items()):
|
|
output_name = output_component(filename, safe="._+-")
|
|
target = package_destination / output_name
|
|
target.write_bytes(contents)
|
|
target.chmod(0o644)
|
|
copied_files.append(f"{directory_name}/{output_name}")
|
|
|
|
notice_lines.append(f"Package: {name}@{version}")
|
|
notice_lines.append(f"Declared license: {license_description}")
|
|
if copied_files:
|
|
notice_lines.append("Notice files:")
|
|
notice_lines.extend(f" {filename}" for filename in copied_files)
|
|
else:
|
|
notice_lines.append("Notice files: none published at package root")
|
|
notice_lines.append("")
|
|
|
|
notices_path = temporary / "THIRD-PARTY-NOTICES.txt"
|
|
notices_path.write_text("\n".join(notice_lines), encoding="utf-8", newline="\n")
|
|
notices_path.chmod(0o644)
|
|
|
|
if destination.is_symlink() or (
|
|
destination.exists() and not destination.is_dir()
|
|
):
|
|
raise CollectionError(
|
|
f"destination is not a regular directory: {destination}"
|
|
)
|
|
if destination.exists():
|
|
shutil.rmtree(destination)
|
|
os.replace(temporary, destination)
|
|
except BaseException:
|
|
shutil.rmtree(temporary, ignore_errors=True)
|
|
raise
|
|
|
|
return len(packages)
|
|
|
|
|
|
def parse_arguments() -> argparse.Namespace:
|
|
parser = argparse.ArgumentParser(
|
|
description="collect npm dependency licenses for an Echoion release"
|
|
)
|
|
parser.add_argument("--node-modules", required=True, type=Path)
|
|
parser.add_argument("--output", required=True, type=Path)
|
|
return parser.parse_args()
|
|
|
|
|
|
def main() -> int:
|
|
arguments = parse_arguments()
|
|
try:
|
|
count = collect(
|
|
arguments.node_modules.resolve(),
|
|
Path(os.path.abspath(arguments.output)),
|
|
)
|
|
except (CollectionError, OSError) as error:
|
|
print(f"collect-frontend-licenses: {error}", file=sys.stderr)
|
|
return 2
|
|
print(f"Collected notices for {count} frontend npm packages.")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|