team-ljyzipelo

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