team-ljyzipelo

공개
293줄14 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# 미리보기 디코더는 MIT 조건을 선택하며 원문 고지를 함께 수집함.
15LICENSE_CHOICES = {
16 # userdb 응답은 직접 파서를 만들지 않고 검증된 JSON 해석기를 사용함.
17 ("serde", "1.0.229"): "MIT",
18 ("serde_core", "1.0.229"): "MIT",
19 ("serde_json", "1.0.154"): "MIT",
20 ("png", "0.18.1"): "MIT",
21 ("zune-jpeg", "0.5.15"): "MIT",
22 ("zipelo-jpeg", "0.5.15"): "MIT",
23 ("zune-core", "0.5.3"): "MIT",
24}
25
26
27def identity(package):
28 return package["name"], package["version"], package.get("source") or "workspace"
29
30
31def metadata(manifest):
32 result = subprocess.run(
33 ["cargo", "+1.99.1", "metadata", "--format-version", "1", "--locked", "--offline",
34 "--all-features", "--manifest-path", str(manifest)],
35 check=True, capture_output=True, text=True,
36 )
37 return json.loads(result.stdout)["packages"]
38
39
40def is_license(path):
41 path = Path(path)
42 name = path.name.upper()
43 return (
44 name.startswith(("LICENSE", "LICENCE", "COPYING", "COPYRIGHT", "NOTICE", "UNLICENSE", "OFL"))
45 or any(part.lower() in {"license", "licenses", "licence", "licences"} for part in path.parts[:-1])
46 ) and path.suffix.lower() not in {".rs", ".c", ".h", ".cpp", ".py", ".json"}
47
48
49def registry_files(package, locked):
50 root = Path(package["manifest_path"]).parent.resolve()
51 archive = root.parents[2] / "cache" / root.parent.name / (root.name + ".crate")
52 if hashlib.sha256(archive.read_bytes()).hexdigest() != locked["checksum"]:
53 raise ValueError(f"crate 체크섬 불일치: {root.name}")
54 explicit = package.get("license_file")
55 if explicit:
56 explicit = Path(explicit)
57 if not explicit.is_absolute():
58 explicit = root / explicit
59 explicit = explicit.resolve().relative_to(root).as_posix()
60 records = []
61 with tarfile.open(archive, "r:gz") as source:
62 for member in sorted(source.getmembers(), key=lambda member: member.name):
63 name = Path(member.name)
64 if name.parts[0] != root.name or ".." in name.parts:
65 raise ValueError(f"crate 경로 오류: {root.name}")
66 relative = Path(*name.parts[1:])
67 if not (is_license(relative) or relative.as_posix() == explicit):
68 continue
69 if not member.isfile():
70 if member.isdir():
71 continue
72 raise ValueError(f"라이선스가 일반 파일이 아님: {member.name}")
73 local = root / relative
74 if local.is_symlink() or not local.resolve().is_relative_to(root):
75 raise ValueError(f"라이선스 경로 이탈: {relative}")
76 content = local.read_bytes()
77 if content != source.extractfile(member).read():
78 raise ValueError(f"라이선스 원문 변경: {root.name}/{relative}")
79 records.append({
80 "path": relative.as_posix(),
81 "sha256": hashlib.sha256(content).hexdigest(),
82 "text": content.decode("utf-8"),
83 })
84 return records
85
86
87def supplemental_files(package, supplement_path):
88 data = json.loads(Path(supplement_path).read_text(encoding="utf-8"))
89 candidates = [row for row in data["packages"]
90 if (row["name"], row["version"]) == (package["name"], package["version"])]
91 if not candidates:
92 return []
93 if len(candidates) != 1:
94 raise ValueError("보충 항목 중복")
95 row = candidates[0]
96 if row["license"] != package["license"]:
97 raise ValueError(f"보충 SPDX 불일치: {package['name']}")
98 root = Path(package["manifest_path"]).parent.resolve()
99 archive = root.parents[2] / "cache" / root.parent.name / (root.name + ".crate")
100 with tarfile.open(archive, "r:gz") as source:
101 vcs = json.load(source.extractfile(root.name + "/.cargo_vcs_info.json"))
102 manifest_bytes = source.extractfile(root.name + "/Cargo.toml").read()
103 if vcs["git"]["sha1"] != row["rev"]:
104 raise ValueError(f"보충 버전 커밋 불일치: {package['name']}")
105 def checked_file(url):
106 file = data["files"][url]
107 if file["url"] != url or hashlib.sha256(file["text"].encode("utf-8")).hexdigest() != file["sha256"]:
108 raise ValueError(f"보충 원문 해시 불일치: {url}")
109 return file
110
111 if row.get("standard_license"):
112 chosen = row["standard_license"]
113 alternatives = package["license"].split(" OR ")
114 if chosen != "MIT" or chosen not in alternatives:
115 raise ValueError("표준 원문 SPDX 선택 불일치")
116 url = data["standards"][chosen]
117 if not re.fullmatch(r"https://raw\.githubusercontent\.com/spdx/license-list-data/v[0-9]+\.[0-9]+\.[0-9]+/text/MIT\.txt", url):
118 raise ValueError("표준 원문 출처 고정 오류")
119 standard = checked_file(url)
120 attribution_url = row["attribution_source"]
121 attribution = checked_file(attribution_url)
122 manifest = tomllib.loads(attribution["text"])
123 if attribution_url.startswith("crate:"):
124 if (attribution_url != "crate:" + root.name + "/Cargo.toml"
125 or attribution["text"].encode("utf-8") != manifest_bytes):
126 raise ValueError("게시 crate 저자 원문 불일치")
127 authors = manifest["package"].get("authors")
128 else:
129 expected = "https://raw.githubusercontent.com/madsmtm/objc2/" + row["rev"] + "/Cargo.toml"
130 if attribution_url != expected or manifest["workspace"]["package"]["version"] != row["version"]:
131 raise ValueError("upstream 저자 출처 불일치")
132 authors = manifest["workspace"]["package"].get("authors")
133 if not authors or authors != row["authors"]:
134 raise ValueError("저자 고지 불일치")
135 note = ("upstream에 원문이 없어 표준 원문으로 보충함\n"
136 + "Selected license: " + chosen + "\n"
137 + "Authors (Cargo.toml): " + ", ".join(authors) + "\n"
138 + "Attribution source: " + attribution_url + "\n"
139 + "Attribution SHA-256: " + attribution["sha256"])
140 return [{"path": url, "sha256": standard["sha256"], "text": standard["text"], "note": note}]
141
142 records = []
143 for url in row["files"]:
144 file = data["files"][url]
145 parts = url.split("/")
146 if (len(parts) < 7 or parts[:3] != ["https:", "", "raw.githubusercontent.com"]
147 or parts[5] != row["upstream_ref"]
148 or row["upstream_ref"] not in {row["rev"], row["version"]}):
149 raise ValueError(f"보충 출처 고정 오류: {url}")
150 content = file["text"].encode("utf-8")
151 if file["url"] != url or hashlib.sha256(content).hexdigest() != file["sha256"]:
152 raise ValueError(f"보충 원문 해시 불일치: {url}")
153 records.append({"path": url, "sha256": file["sha256"], "text": file["text"]})
154 return records
155
156
157def repository_root(manifest):
158 result = subprocess.run(
159 ["git", "-C", str(manifest.parent), "rev-parse", "--show-toplevel"],
160 check=True, capture_output=True, text=True,
161 )
162 return Path(result.stdout.strip()).resolve(strict=True)
163
164
165def inventory(manifests, project_root=None, supplement_path=ROOT / "packaging/license-supplements.json"):
166 records = {}
167 for manifest in manifests:
168 manifest = Path(manifest).resolve(strict=True)
169 lock = tomllib.loads(manifest.with_name("Cargo.lock").read_text())
170 locked = {identity(package): package for package in lock["package"]}
171 packages = {identity(package): package for package in metadata(manifest)}
172 if set(locked) != set(packages):
173 raise ValueError(f"Cargo.lock/metadata 불일치: 누락 {sorted(set(locked) - set(packages))}, "
174 f"추가 {sorted(set(packages) - set(locked))}")
175 root = None
176 for key, package in sorted(packages.items()):
177 if package.get("source"):
178 if not package["source"].startswith("registry+"):
179 raise ValueError(f"지원하지 않는 원문 저장소: {key}")
180 files = registry_files(package, locked[key])
181 if not files and Path(supplement_path).is_file():
182 files = supplemental_files(package, supplement_path)
183 else:
184 if root is None:
185 root = Path(project_root).resolve() if project_root else repository_root(manifest)
186 if (package["license"] != "MIT"
187 or not Path(package["manifest_path"]).resolve().is_relative_to(root)):
188 raise ValueError(f"프로젝트 라이선스 범위 확인 필요: {key}")
189 license_file = root / "LICENSE"
190 if package.get("license_file"):
191 package_root = Path(package["manifest_path"]).parent.resolve()
192 license_file = package_root / package["license_file"]
193 if (license_file.is_symlink()
194 or not license_file.resolve().is_relative_to(package_root)):
195 raise ValueError(f"프로젝트 라이선스 경로 이탈: {key}")
196 content = license_file.read_bytes()
197 files = [{"path": "project/" + license_file.relative_to(root).as_posix(),
198 "sha256": hashlib.sha256(content).hexdigest(),
199 "text": content.decode("utf-8")}]
200 if key in records:
201 if records[key]["license"] != package["license"]:
202 raise ValueError(f"입력 저장소 간 SPDX 불일치: {key}")
203 for file in files:
204 if file not in records[key]["files"]:
205 records[key]["files"].append(file)
206 else:
207 records[key] = {"name": key[0], "version": key[1], "source": key[2],
208 "license": package["license"], "files": files}
209 for record in records.values():
210 selected = LICENSE_CHOICES.get((record["name"], record["version"]))
211 if selected:
212 if selected not in record["license"].split(" OR "):
213 raise ValueError(f"선택한 라이선스 불일치: {record['name']}")
214 record["selected_license"] = selected
215 return [records[key] for key in sorted(records)]
216
217
218# 앱에 그대로 포함하는 Rust crate 밖의 자산. 원문 고지가 없으면 배포를 중단함.
219BUNDLED = [
220 {
221 "kind": "Font",
222 "name": "Pretendard",
223 "version": "1.3.9",
224 "license": "OFL-1.1",
225 "source": "https://github.com/orioncactus/pretendard/releases/tag/v1.3.9",
226 "asset": "experiments/rust-ui-memory-app/src/assets/fonts/Pretendard-Regular.ttf",
227 "license_file": "experiments/rust-ui-memory-app/src/assets/fonts/OFL.txt",
228 },
229]
230
231
232def bundled_records(root=ROOT):
233 records = []
234 for item in BUNDLED:
235 asset = root / item["asset"]
236 license_file = root / item["license_file"]
237 if not asset.is_file() or not license_file.is_file():
238 raise ValueError(f"포함 자산 또는 원문 누락: {item['name']}")
239 content = license_file.read_bytes()
240 records.append({
241 "kind": item["kind"], "name": item["name"], "version": item["version"],
242 "source": item["source"], "license": item["license"],
243 "files": [{
244 "path": item["license_file"], "sha256": hashlib.sha256(content).hexdigest(),
245 "note": f"Asset: {item['asset']} (SHA-256 {hashlib.sha256(asset.read_bytes()).hexdigest()})",
246 "text": content.decode("utf-8"),
247 }],
248 })
249 return records
250
251
252def render(records):
253 missing = [f'{record["name"]}@{record["version"]}' for record in records if not record["files"]]
254 if missing:
255 raise ValueError(f"라이선스 원문 누락 {len(missing)}개: " + ", ".join(missing))
256 lines = ["Zipelo third-party licenses", "Cargo.lock 전체 의존성과 앱에 포함한 자산의 원문 고지 (로컬 registry 및 고정 upstream 보충)", ""]
257 for record in records:
258 lines.extend(["=" * 72, f'{record.get("kind", "Crate")}: {record["name"]} {record["version"]}',
259 f'Source: {record["source"]}', f'License: {record["license"]}', f'Version: {record["version"]}', ""])
260 if record.get("selected_license"):
261 lines.extend([f'Selected license: {record["selected_license"]}', ""])
262 for file in record["files"]:
263 lines.extend([f'File: {file["path"]}', f'SHA-256: {file["sha256"]}'])
264 if file.get("note"):
265 lines.append(file["note"])
266 lines.extend(["", file["text"], ""])
267 return "\n".join(lines)
268
269
270def generate(manifests, output, audit=None):
271 records = inventory(manifests) + bundled_records()
272 if audit:
273 Path(audit).write_text(json.dumps(records, ensure_ascii=False, indent=4) + "\n", encoding="utf-8")
274 text = render(records)
275 Path(output).write_text(text, encoding="utf-8", newline="")
276 return records
277
278
279def main():
280 parser = argparse.ArgumentParser(description=__doc__)
281 parser.add_argument("--manifest", type=Path, action="append", required=True)
282 parser.add_argument("--output", type=Path, required=True)
283 parser.add_argument("--audit", type=Path)
284 args = parser.parse_args()
285 try:
286 records = generate(args.manifest, args.output, args.audit)
287 except (ValueError, OSError, subprocess.CalledProcessError) as error:
288 parser.exit(1, str(error) + "\n")
289 print(f"라이선스 {len(records)}개, 누락 0개")
290
291
292if __name__ == "__main__":
293 main()