team-ljyzipelo

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