team-ljyzipelo

공개
231줄11 KB
1"""잠금 의존성의 로컬 원문을 모으고 누락 시 배포를 중단함."""
2
3import argparse
4import hashlib
5import json
6import re
7from pathlib import Path
8import subprocess
9import tarfile
10import tomllib
11
12ROOT = Path(__file__).resolve().parents[1]
13
14
15def identity(package):
16 return package["name"], package["version"], package.get("source") or "workspace"
17
18
19def 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
28def 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
37def 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
75def 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
145def repository_root(manifest):
146 result = subprocess.run(
147 ["git", "-C", str(manifest.parent), "rev-parse", "--show-toplevel"],
148 check=True, capture_output=True, text=True,
149 )
150 return Path(result.stdout.strip()).resolve(strict=True)
151
152
153def inventory(manifests, project_root=None, supplement_path=ROOT / "packaging/license-supplements.json"):
154 records = {}
155 for manifest in manifests:
156 manifest = Path(manifest).resolve(strict=True)
157 lock = tomllib.loads(manifest.with_name("Cargo.lock").read_text())
158 locked = {identity(package): package for package in lock["package"]}
159 packages = {identity(package): package for package in metadata(manifest)}
160 if set(locked) != set(packages):
161 raise ValueError(f"Cargo.lock/metadata 불일치: 누락 {sorted(set(locked) - set(packages))}, "
162 f"추가 {sorted(set(packages) - set(locked))}")
163 root = None
164 for key, package in sorted(packages.items()):
165 if package.get("source"):
166 if not package["source"].startswith("registry+"):
167 raise ValueError(f"지원하지 않는 원문 저장소: {key}")
168 files = registry_files(package, locked[key])
169 if not files and Path(supplement_path).is_file():
170 files = supplemental_files(package, supplement_path)
171 else:
172 if root is None:
173 root = Path(project_root).resolve() if project_root else repository_root(manifest)
174 if (package["license"] != "MIT"
175 or not Path(package["manifest_path"]).resolve().is_relative_to(root)):
176 raise ValueError(f"프로젝트 라이선스 범위 확인 필요: {key}")
177 content = (root / "LICENSE").read_bytes()
178 files = [{"path": "project/LICENSE", "sha256": hashlib.sha256(content).hexdigest(),
179 "text": content.decode("utf-8")}]
180 if key in records:
181 if records[key]["license"] != package["license"]:
182 raise ValueError(f"입력 저장소 간 SPDX 불일치: {key}")
183 for file in files:
184 if file not in records[key]["files"]:
185 records[key]["files"].append(file)
186 else:
187 records[key] = {"name": key[0], "version": key[1], "source": key[2],
188 "license": package["license"], "files": files}
189 return [records[key] for key in sorted(records)]
190
191
192def render(records):
193 missing = [f'{record["name"]}@{record["version"]}' for record in records if not record["files"]]
194 if missing:
195 raise ValueError(f"라이선스 원문 누락 {len(missing)}개: " + ", ".join(missing))
196 lines = ["Zipelo third-party licenses", "Cargo.lock 전체 의존성의 원문 고지 (로컬 registry 및 고정 upstream 보충)", ""]
197 for record in records:
198 lines.extend(["=" * 72, f'Crate: {record["name"]} {record["version"]}',
199 f'Source: {record["source"]}', f'License: {record["license"]}', f'Version: {record["version"]}', ""])
200 for file in record["files"]:
201 lines.extend([f'File: {file["path"]}', f'SHA-256: {file["sha256"]}'])
202 if file.get("note"):
203 lines.append(file["note"])
204 lines.extend(["", file["text"], ""])
205 return "\n".join(lines)
206
207
208def generate(manifests, output, audit=None):
209 records = inventory(manifests)
210 if audit:
211 Path(audit).write_text(json.dumps(records, ensure_ascii=False, indent=4) + "\n", encoding="utf-8")
212 text = render(records)
213 Path(output).write_text(text, encoding="utf-8", newline="")
214 return records
215
216
217def main():
218 parser = argparse.ArgumentParser(description=__doc__)
219 parser.add_argument("--manifest", type=Path, action="append", required=True)
220 parser.add_argument("--output", type=Path, required=True)
221 parser.add_argument("--audit", type=Path)
222 args = parser.parse_args()
223 try:
224 records = generate(args.manifest, args.output, args.audit)
225 except (ValueError, OSError, subprocess.CalledProcessError) as error:
226 parser.exit(1, str(error) + "\n")
227 print(f"라이선스 {len(records)}개, 누락 0개")
228
229
230if __name__ == "__main__":
231 main()