| 1 | """잠금 의존성의 로컬 원문을 모으고 누락 시 배포를 중단함.""" |
| 2 | |
| 3 | import argparse |
| 4 | import hashlib |
| 5 | import json |
| 6 | import re |
| 7 | from pathlib import Path |
| 8 | import subprocess |
| 9 | import tarfile |
| 10 | import tomllib |
| 11 | |
| 12 | ROOT = Path(__file__).resolve().parents[1] |
| 13 | |
| 14 | |
| 15 | def identity(package): |
| 16 | return package["name"], package["version"], package.get("source") or "workspace" |
| 17 | |
| 18 | |
| 19 | def metadata(manifest): |
| 20 | result = subprocess.run( |
| 21 | ["cargo", "+1.99.1", "metadata", "--format-version", "1", "--locked", "--offline", |
| 22 | "--all-features", "--manifest-path", str(manifest)], |
| 23 | check=True, capture_output=True, text=True, |
| 24 | ) |
| 25 | return json.loads(result.stdout)["packages"] |
| 26 | |
| 27 | |
| 28 | def is_license(path): |
| 29 | path = Path(path) |
| 30 | name = path.name.upper() |
| 31 | return ( |
| 32 | name.startswith(("LICENSE", "LICENCE", "COPYING", "COPYRIGHT", "NOTICE", "UNLICENSE", "OFL")) |
| 33 | or any(part.lower() in {"license", "licenses", "licence", "licences"} for part in path.parts[:-1]) |
| 34 | ) and path.suffix.lower() not in {".rs", ".c", ".h", ".cpp", ".py", ".json"} |
| 35 | |
| 36 | |
| 37 | def registry_files(package, locked): |
| 38 | root = Path(package["manifest_path"]).parent.resolve() |
| 39 | archive = root.parents[2] / "cache" / root.parent.name / (root.name + ".crate") |
| 40 | if hashlib.sha256(archive.read_bytes()).hexdigest() != locked["checksum"]: |
| 41 | raise ValueError(f"crate 체크섬 불일치: {root.name}") |
| 42 | explicit = package.get("license_file") |
| 43 | if explicit: |
| 44 | explicit = Path(explicit) |
| 45 | if not explicit.is_absolute(): |
| 46 | explicit = root / explicit |
| 47 | explicit = explicit.resolve().relative_to(root).as_posix() |
| 48 | records = [] |
| 49 | with tarfile.open(archive, "r:gz") as source: |
| 50 | for member in sorted(source.getmembers(), key=lambda member: member.name): |
| 51 | name = Path(member.name) |
| 52 | if name.parts[0] != root.name or ".." in name.parts: |
| 53 | raise ValueError(f"crate 경로 오류: {root.name}") |
| 54 | relative = Path(*name.parts[1:]) |
| 55 | if not (is_license(relative) or relative.as_posix() == explicit): |
| 56 | continue |
| 57 | if not member.isfile(): |
| 58 | if member.isdir(): |
| 59 | continue |
| 60 | raise ValueError(f"라이선스가 일반 파일이 아님: {member.name}") |
| 61 | local = root / relative |
| 62 | if local.is_symlink() or not local.resolve().is_relative_to(root): |
| 63 | raise ValueError(f"라이선스 경로 이탈: {relative}") |
| 64 | content = local.read_bytes() |
| 65 | if content != source.extractfile(member).read(): |
| 66 | raise ValueError(f"라이선스 원문 변경: {root.name}/{relative}") |
| 67 | records.append({ |
| 68 | "path": relative.as_posix(), |
| 69 | "sha256": hashlib.sha256(content).hexdigest(), |
| 70 | "text": content.decode("utf-8"), |
| 71 | }) |
| 72 | return records |
| 73 | |
| 74 | |
| 75 | def supplemental_files(package, supplement_path): |
| 76 | data = json.loads(Path(supplement_path).read_text(encoding="utf-8")) |
| 77 | candidates = [row for row in data["packages"] |
| 78 | if (row["name"], row["version"]) == (package["name"], package["version"])] |
| 79 | if not candidates: |
| 80 | return [] |
| 81 | if len(candidates) != 1: |
| 82 | raise ValueError("보충 항목 중복") |
| 83 | row = candidates[0] |
| 84 | if row["license"] != package["license"]: |
| 85 | raise ValueError(f"보충 SPDX 불일치: {package['name']}") |
| 86 | root = Path(package["manifest_path"]).parent.resolve() |
| 87 | archive = root.parents[2] / "cache" / root.parent.name / (root.name + ".crate") |
| 88 | with tarfile.open(archive, "r:gz") as source: |
| 89 | vcs = json.load(source.extractfile(root.name + "/.cargo_vcs_info.json")) |
| 90 | manifest_bytes = source.extractfile(root.name + "/Cargo.toml").read() |
| 91 | if vcs["git"]["sha1"] != row["rev"]: |
| 92 | raise ValueError(f"보충 버전 커밋 불일치: {package['name']}") |
| 93 | def checked_file(url): |
| 94 | file = data["files"][url] |
| 95 | if file["url"] != url or hashlib.sha256(file["text"].encode("utf-8")).hexdigest() != file["sha256"]: |
| 96 | raise ValueError(f"보충 원문 해시 불일치: {url}") |
| 97 | return file |
| 98 | |
| 99 | if row.get("standard_license"): |
| 100 | chosen = row["standard_license"] |
| 101 | alternatives = package["license"].split(" OR ") |
| 102 | if chosen != "MIT" or chosen not in alternatives: |
| 103 | raise ValueError("표준 원문 SPDX 선택 불일치") |
| 104 | url = data["standards"][chosen] |
| 105 | if not re.fullmatch(r"https://raw\.githubusercontent\.com/spdx/license-list-data/v[0-9]+\.[0-9]+\.[0-9]+/text/MIT\.txt", url): |
| 106 | raise ValueError("표준 원문 출처 고정 오류") |
| 107 | standard = checked_file(url) |
| 108 | attribution_url = row["attribution_source"] |
| 109 | attribution = checked_file(attribution_url) |
| 110 | manifest = tomllib.loads(attribution["text"]) |
| 111 | if attribution_url.startswith("crate:"): |
| 112 | if (attribution_url != "crate:" + root.name + "/Cargo.toml" |
| 113 | or attribution["text"].encode("utf-8") != manifest_bytes): |
| 114 | raise ValueError("게시 crate 저자 원문 불일치") |
| 115 | authors = manifest["package"].get("authors") |
| 116 | else: |
| 117 | expected = "https://raw.githubusercontent.com/madsmtm/objc2/" + row["rev"] + "/Cargo.toml" |
| 118 | if attribution_url != expected or manifest["workspace"]["package"]["version"] != row["version"]: |
| 119 | raise ValueError("upstream 저자 출처 불일치") |
| 120 | authors = manifest["workspace"]["package"].get("authors") |
| 121 | if not authors or authors != row["authors"]: |
| 122 | raise ValueError("저자 고지 불일치") |
| 123 | note = ("upstream에 원문이 없어 표준 원문으로 보충함\n" |
| 124 | + "Selected license: " + chosen + "\n" |
| 125 | + "Authors (Cargo.toml): " + ", ".join(authors) + "\n" |
| 126 | + "Attribution source: " + attribution_url + "\n" |
| 127 | + "Attribution SHA-256: " + attribution["sha256"]) |
| 128 | return [{"path": url, "sha256": standard["sha256"], "text": standard["text"], "note": note}] |
| 129 | |
| 130 | records = [] |
| 131 | for url in row["files"]: |
| 132 | file = data["files"][url] |
| 133 | parts = url.split("/") |
| 134 | if (len(parts) < 7 or parts[:3] != ["https:", "", "raw.githubusercontent.com"] |
| 135 | or parts[5] != row["upstream_ref"] |
| 136 | or row["upstream_ref"] not in {row["rev"], row["version"]}): |
| 137 | raise ValueError(f"보충 출처 고정 오류: {url}") |
| 138 | content = file["text"].encode("utf-8") |
| 139 | if file["url"] != url or hashlib.sha256(content).hexdigest() != file["sha256"]: |
| 140 | raise ValueError(f"보충 원문 해시 불일치: {url}") |
| 141 | records.append({"path": url, "sha256": file["sha256"], "text": file["text"]}) |
| 142 | return records |
| 143 | |
| 144 | |
| 145 | def inventory(manifests, project_root=ROOT, supplement_path=ROOT / "packaging/license-supplements.json"): |
| 146 | locked = {} |
| 147 | packages = {} |
| 148 | for manifest in manifests: |
| 149 | manifest = Path(manifest).resolve(strict=True) |
| 150 | lock = tomllib.loads(manifest.with_name("Cargo.lock").read_text()) |
| 151 | locked.update({identity(package): package for package in lock["package"]}) |
| 152 | packages.update({identity(package): package for package in metadata(manifest)}) |
| 153 | if set(locked) != set(packages): |
| 154 | raise ValueError(f"Cargo.lock/metadata 불일치: 누락 {sorted(set(locked) - set(packages))}, " |
| 155 | f"추가 {sorted(set(packages) - set(locked))}") |
| 156 | records = [] |
| 157 | for key, package in sorted(packages.items()): |
| 158 | if package.get("source"): |
| 159 | if not package["source"].startswith("registry+"): |
| 160 | raise ValueError(f"지원하지 않는 원문 저장소: {key}") |
| 161 | files = registry_files(package, locked[key]) |
| 162 | if not files and Path(supplement_path).is_file(): |
| 163 | files = supplemental_files(package, supplement_path) |
| 164 | else: |
| 165 | root = Path(project_root).resolve() |
| 166 | if package["license"] != "MIT" or not Path(package["manifest_path"]).resolve().is_relative_to(root): |
| 167 | raise ValueError(f"프로젝트 라이선스 범위 확인 필요: {key}") |
| 168 | content = (root / "LICENSE").read_bytes() |
| 169 | files = [{"path": "project/LICENSE", "sha256": hashlib.sha256(content).hexdigest(), |
| 170 | "text": content.decode("utf-8")}] |
| 171 | records.append({"name": key[0], "version": key[1], "source": key[2], |
| 172 | "license": package["license"], "files": files}) |
| 173 | return records |
| 174 | |
| 175 | |
| 176 | def render(records): |
| 177 | missing = [f'{record["name"]}@{record["version"]}' for record in records if not record["files"]] |
| 178 | if missing: |
| 179 | raise ValueError(f"라이선스 원문 누락 {len(missing)}개: " + ", ".join(missing)) |
| 180 | lines = ["Zipelo third-party licenses", "Cargo.lock 전체 의존성의 원문 고지 (로컬 registry 및 고정 upstream 보충)", ""] |
| 181 | for record in records: |
| 182 | lines.extend(["=" * 72, f'Crate: {record["name"]} {record["version"]}', |
| 183 | f'Source: {record["source"]}', f'License: {record["license"]}', f'Version: {record["version"]}', ""]) |
| 184 | for file in record["files"]: |
| 185 | lines.extend([f'File: {file["path"]}', f'SHA-256: {file["sha256"]}']) |
| 186 | if file.get("note"): |
| 187 | lines.append(file["note"]) |
| 188 | lines.extend(["", file["text"], ""]) |
| 189 | return "\n".join(lines) |
| 190 | |
| 191 | |
| 192 | def generate(manifests, output, audit=None): |
| 193 | records = inventory(manifests) |
| 194 | if audit: |
| 195 | Path(audit).write_text(json.dumps(records, ensure_ascii=False, indent=4) + "\n", encoding="utf-8") |
| 196 | text = render(records) |
| 197 | Path(output).write_text(text, encoding="utf-8", newline="") |
| 198 | return records |
| 199 | |
| 200 | |
| 201 | def main(): |
| 202 | parser = argparse.ArgumentParser(description=__doc__) |
| 203 | parser.add_argument("--manifest", type=Path, action="append", required=True) |
| 204 | parser.add_argument("--output", type=Path, required=True) |
| 205 | parser.add_argument("--audit", type=Path) |
| 206 | args = parser.parse_args() |
| 207 | try: |
| 208 | records = generate(args.manifest, args.output, args.audit) |
| 209 | except (ValueError, OSError, subprocess.CalledProcessError) as error: |
| 210 | parser.exit(1, str(error) + "\n") |
| 211 | print(f"라이선스 {len(records)}개, 누락 0개") |
| 212 | |
| 213 | |
| 214 | if __name__ == "__main__": |
| 215 | main() |