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