| 1 |
#!/usr/bin/python3 |
| 2 |
# generate debian/copyright from debian/copyright.template and node_modules |
| 3 |
# |
| 4 |
# Copyright (C) 2025 Red Hat, Inc. |
| 5 |
# SPDX-License-Identifier: LGPL-2.1-or-later |
| 6 |
|
| 7 |
import json |
| 8 |
import re |
| 9 |
import sys |
| 10 |
import tarfile |
| 11 |
from collections import defaultdict |
| 12 |
from pathlib import Path |
| 13 |
from typing import Any |
| 14 |
|
| 15 |
|
| 16 |
def template_licenses(template: str) -> set[str]: |
| 17 |
"""Return set of existing License: short names""" |
| 18 |
return { |
| 19 |
line.split(None, 1)[1].lower() |
| 20 |
for line in template.splitlines() |
| 21 |
if line.startswith('License:') |
| 22 |
} |
| 23 |
|
| 24 |
|
| 25 |
# Patterns for skipping invalid copyright statements |
| 26 |
skip_patterns = [ |
| 27 |
# Generic license template text |
| 28 |
r'^owner', r'^holder', r'^license', r'^notice', r'^statement', r'^law', r'^and', r'^or\b', r'^the\b', |
| 29 |
r'^contributors?', r'^information', r'^disclaimer', |
| 30 |
# License boilerplate phrases |
| 31 |
r'^//', r'liable', r'warranty', r'condition', r'permission', r'granted', |
| 32 |
# Template year placeholders |
| 33 |
r'\[yyyy\]', r'\{yyyy\}', |
| 34 |
# Just a year or just numbers/punctuation |
| 35 |
r'^\d{4}\s*$', r'^[\d\s,;.\-]+$', |
| 36 |
# Incomplete copyright statements |
| 37 |
r'^[\d\s,;.\-]+(All Rights|Reserved)\.?$', |
| 38 |
] |
| 39 |
|
| 40 |
|
| 41 |
def find_copyright_in_license_text(content: str) -> set[str]: |
| 42 |
"""Heuristically extract copyrights from LICENSE file content""" |
| 43 |
def is_valid_copyright(text: str) -> bool: |
| 44 |
"""Check if copyright text is valid""" |
| 45 |
if any(re.search(pattern, text, re.IGNORECASE) for pattern in skip_patterns): |
| 46 |
return False |
| 47 |
# Only accept if it looks like an actual copyright (has year or name) |
| 48 |
return (re.search(r'\d{4}', text) or len(text.split()) >= 2) and len(text) < 200 |
| 49 |
|
| 50 |
return { |
| 51 |
match.group(1).strip() |
| 52 |
for match in re.finditer(r'Copyright\s+(?:\(c\)\s*)?(.+)$', content, re.MULTILINE | re.IGNORECASE) |
| 53 |
if is_valid_copyright(match.group(1).strip()) |
| 54 |
} |
| 55 |
|
| 56 |
|
| 57 |
def normalize_spdx_license(license_text: str, license_ids: set[str]) -> str: |
| 58 |
"""Normalize license to SPDX identifier using pattern-based substitutions""" |
| 59 |
# Handle license expressions - normalize to lowercase "and" per Debian spec |
| 60 |
# https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/#license-short-name |
| 61 |
license_text = license_text.replace(' AND ', ' and ') |
| 62 |
|
| 63 |
def normalize_part(part: str) -> str: |
| 64 |
"""Normalize a single license identifier""" |
| 65 |
part = part.strip().strip('()') |
| 66 |
# Strip " License" suffix (e.g., "ISC License" -> "ISC") |
| 67 |
part = re.sub(r'\s+License$', '', part) |
| 68 |
# Convert e.g. "GPL-2.0+" → "GPL-2.0-or-later" |
| 69 |
part = re.sub(r'\+$', '-or-later', part) |
| 70 |
# Normalize specific licenses |
| 71 |
part = part.replace('MIT/X11', 'MIT') |
| 72 |
part = re.sub(r'^Apache[- ]2(?:\.0)?$', 'Apache-2.0', part) |
| 73 |
part = re.sub(r'^BSD$', 'BSD-3-Clause', part) |
| 74 |
part = re.sub(r'^Python-2\.0\.1$', 'Python-2.0', part) |
| 75 |
# Handle -only suffix (e.g., "LGPL-2.1" -> "LGPL-2.1-only") |
| 76 |
if re.match(r'^(L?GPL)-\d+\.\d+$', part): |
| 77 |
part += '-only' |
| 78 |
return part |
| 79 |
|
| 80 |
# Split "and"ed licenses |
| 81 |
parts = [p.strip() for p in license_text.split(' and ')] |
| 82 |
|
| 83 |
normalized_parts: list[str] = [] |
| 84 |
for part in parts: |
| 85 |
normalized = normalize_part(part) |
| 86 |
if normalized.lower() not in license_ids: |
| 87 |
sys.exit(f"ERROR: License '{normalized}' is not defined in the template\n" |
| 88 |
f"Original license text: '{license_text}'\n" |
| 89 |
"Please add a License: paragraph for this license to the template.") |
| 90 |
normalized_parts.append(normalized) |
| 91 |
|
| 92 |
return ' and '.join(normalized_parts) |
| 93 |
|
| 94 |
|
| 95 |
def extract_author_name(author: str | dict[str, Any]) -> str: |
| 96 |
"""Extract author name from package.json author field""" |
| 97 |
if isinstance(author, dict): |
| 98 |
return str(author.get('name', '')) |
| 99 |
# Parse "Name <email>" format |
| 100 |
return re.sub(r'\s*<[^>]+>\s*', '', str(author)).strip() |
| 101 |
|
| 102 |
|
| 103 |
def get_legalese(tarball_path: Path, license_ids: set[str]) -> dict[str, tuple[str, set[str]]]: |
| 104 |
"""Extract licenses and copyrights from node_modules tarball. |
| 105 |
|
| 106 |
Returns: {package_path -> (license, copyrights)} |
| 107 |
""" |
| 108 |
# Map package_path to license (from package.json) |
| 109 |
package_licenses: dict[str, str] = {} |
| 110 |
# Map package_path to copyrights |
| 111 |
copyrights: dict[str, set[str]] = {} |
| 112 |
|
| 113 |
with tarfile.open(tarball_path) as tar: |
| 114 |
for member in tar.getmembers(): |
| 115 |
if not member.isfile() or not member.name.startswith('node_modules/'): |
| 116 |
continue |
| 117 |
|
| 118 |
f = tar.extractfile(member) |
| 119 |
assert f |
| 120 |
|
| 121 |
if Path(member.name).name == 'package.json': |
| 122 |
pkg_data = json.load(f) |
| 123 |
if pkg_license := pkg_data.get('license'): |
| 124 |
package_path = str(Path(member.name).parent.relative_to('node_modules')) |
| 125 |
package_licenses[package_path] = pkg_license |
| 126 |
if author := pkg_data.get('author'): |
| 127 |
if author_name := extract_author_name(author): |
| 128 |
copyrights.setdefault(package_path, set()).add(author_name) |
| 129 |
|
| 130 |
# Scan all files for copyright statements (associate with top-level package) |
| 131 |
if copyright_statements := find_copyright_in_license_text(f.read().decode(errors='ignore')): |
| 132 |
toplevel = member.name.split('/')[1] |
| 133 |
copyrights.setdefault(toplevel, set()).update(copyright_statements) |
| 134 |
|
| 135 |
# Build package legal info |
| 136 |
return { |
| 137 |
path: (normalize_spdx_license(lic, license_ids), |
| 138 |
copyrights.get(path) or copyrights.get(path.split('/')[0], {f"Authors of {path}"})) |
| 139 |
for path, lic in package_licenses.items() |
| 140 |
} |
| 141 |
|
| 142 |
|
| 143 |
# |
| 144 |
# main |
| 145 |
# |
| 146 |
|
| 147 |
if len(sys.argv) != 3: |
| 148 |
sys.exit(f"Usage: {sys.argv[0]} <copyright-template> <node-cache-tarball>") |
| 149 |
|
| 150 |
template_file = Path(sys.argv[1]) |
| 151 |
node_cache_path = Path(sys.argv[2]) |
| 152 |
|
| 153 |
template = template_file.read_text() |
| 154 |
license_ids = template_licenses(template) |
| 155 |
packages_legal = get_legalese(node_cache_path, license_ids) |
| 156 |
|
| 157 |
# Merge siblings with the same license into their parent |
| 158 |
by_parent = defaultdict(list) |
| 159 |
for path in list(packages_legal.keys()): |
| 160 |
if parent := '/'.join(path.split('/')[:-1]): |
| 161 |
by_parent[parent].append(path) |
| 162 |
|
| 163 |
for parent, children in by_parent.items(): |
| 164 |
if len(children) > 1 and len(licenses := {packages_legal[c][0] for c in children}) == 1: |
| 165 |
copyrights = set().union(*(packages_legal[c][1] for c in children)) |
| 166 |
for child in children: |
| 167 |
del packages_legal[child] |
| 168 |
packages_legal[parent] = (licenses.pop(), copyrights) |
| 169 |
|
| 170 |
# Generate paragraphs, skipping entries covered by a parent with the same license |
| 171 |
paragraphs: list[str] = [] |
| 172 |
for package_path in sorted(packages_legal.keys()): |
| 173 |
license_text, copyrights = packages_legal[package_path] |
| 174 |
|
| 175 |
# Check if any parent path has the same license (if so, skip - already covered) |
| 176 |
covered_by_parent = any( |
| 177 |
parent_path != package_path |
| 178 |
and package_path.startswith(parent_path + '/') |
| 179 |
and packages_legal[parent_path][0] == license_text |
| 180 |
for parent_path in packages_legal |
| 181 |
) |
| 182 |
|
| 183 |
if not covered_by_parent: |
| 184 |
copyright_text = '\n '.join(sorted(copyrights)) |
| 185 |
paragraphs.append(f"Files: node/{package_path}/*\nCopyright: {copyright_text}\nLicense: {license_text}") |
| 186 |
|
| 187 |
# Assemble copyright file |
| 188 |
npm_content = '\n\n'.join(paragraphs) |
| 189 |
print('\n'.join(npm_content if '#NPM' in line else line for line in template.splitlines())) |