| 1 | import argparse |
| 2 | import json |
| 3 | import os |
| 4 | import re |
| 5 | from pathlib import Path |
| 6 | import shutil |
| 7 | import subprocess |
| 8 | import sys |
| 9 | import tomllib |
| 10 | |
| 11 | |
| 12 | ROOT = Path(__file__).resolve().parents[2] |
| 13 | TOOLCHAIN = "+1.99.1" |
| 14 | WINDOWS_TARGET = "x86_64-pc-windows-gnu" |
| 15 | LINUX_ONLY = {"rust-ui-system-font-regressions"} |
| 16 | JOB_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]{0,63}\Z") |
| 17 | LITERAL_SOURCE_PATH = re.compile( |
| 18 | r'(?:\binclude(?:_str|_bytes)?!\s*\(\s*|#\s*\[\s*path\s*=\s*)"([^"]+)"' |
| 19 | ) |
| 20 | |
| 21 | |
| 22 | def work_directory(root, name): |
| 23 | if not JOB_NAME.fullmatch(name): |
| 24 | raise ValueError("작업명은 영숫자로 시작하는 영숫자, 밑줄, 하이픈만 허용함") |
| 25 | common = Path(subprocess.check_output( |
| 26 | ["git", "rev-parse", "--path-format=absolute", "--git-common-dir"], |
| 27 | cwd=root, text=True, |
| 28 | ).strip()).resolve() |
| 29 | project = common.parent if common.name == ".git" else root.resolve() |
| 30 | tests = project / "tests" |
| 31 | base = tests / "work" |
| 32 | if tests.is_symlink() or not tests.is_dir(): |
| 33 | raise ValueError(f"안전한 작업 디렉터리가 필요함: {tests}") |
| 34 | if base.is_symlink() or (base.exists() and not base.is_dir()): |
| 35 | raise ValueError(f"안전한 작업 디렉터리가 필요함: {base}") |
| 36 | base.mkdir(mode=0o700, exist_ok=True) |
| 37 | if base.resolve() != base: |
| 38 | raise ValueError(f"안전한 작업 디렉터리가 필요함: {base}") |
| 39 | path = base / name |
| 40 | if path.is_symlink() or (path.exists() and not path.is_dir()): |
| 41 | raise ValueError(f"안전한 작업 디렉터리가 필요함: {path}") |
| 42 | path.mkdir(mode=0o700, exist_ok=True) |
| 43 | if path.resolve() != path: |
| 44 | raise ValueError(f"안전한 작업 디렉터리가 필요함: {path}") |
| 45 | return path |
| 46 | |
| 47 | |
| 48 | def output_directory(work, name, create=False): |
| 49 | path = work / name |
| 50 | if not path.resolve().is_relative_to(work) or (path.exists() and not path.is_dir()): |
| 51 | raise ValueError(f"작업 폴더 밖의 출력 경로는 허용하지 않음: {path}") |
| 52 | if create: |
| 53 | path.mkdir(mode=0o700, exist_ok=True) |
| 54 | return path |
| 55 | |
| 56 | |
| 57 | def test_work_directory(root): |
| 58 | configured = os.environ.get("ZIPELO_TEST_WORK_DIR") |
| 59 | if configured: |
| 60 | return Path(configured) |
| 61 | return work_directory(root, os.environ.get("ZIPELO_CI_JOB", "rust-local")) |
| 62 | |
| 63 | |
| 64 | |
| 65 | |
| 66 | def manifests(root): |
| 67 | paths = sorted(root.glob("experiments/*/Cargo.toml")) |
| 68 | if not paths: |
| 69 | raise ValueError("experiments/ Rust crate를 찾지 못함") |
| 70 | paths += sorted(root.glob("tests/*/Cargo.toml")) |
| 71 | for path in paths: |
| 72 | if not path.with_name("Cargo.lock").is_file(): |
| 73 | raise ValueError(f"고정 Cargo.lock이 없음: {path}") |
| 74 | return paths |
| 75 | |
| 76 | |
| 77 | def changed_files(root): |
| 78 | try: |
| 79 | base = subprocess.check_output( |
| 80 | ["git", "merge-base", "origin/main", "HEAD"], cwd=root, text=True |
| 81 | ).strip() |
| 82 | tracked = subprocess.check_output( |
| 83 | ["git", "diff", "--no-renames", "--name-only", "-z", base], cwd=root |
| 84 | ) |
| 85 | untracked = subprocess.check_output( |
| 86 | ["git", "ls-files", "--others", "--exclude-standard", "-z"], cwd=root |
| 87 | ) |
| 88 | except subprocess.CalledProcessError as error: |
| 89 | raise ValueError("origin/main과 변경 파일을 비교할 수 없음") from error |
| 90 | changes = {os.fsdecode(path) for path in (tracked + untracked).split(b"\0") if path} |
| 91 | work = os.environ.get("ZIPELO_TEST_WORK_DIR") |
| 92 | if work and Path(work).resolve() == root.resolve(): |
| 93 | outputs = {"target", "tools", "tmp", "fixtures"} |
| 94 | changes = { |
| 95 | path for path in changes |
| 96 | if path.split("/", 1)[0] not in outputs |
| 97 | and not re.fullmatch(r"(local|build|test|cross-build)-results\.json", path) |
| 98 | } |
| 99 | return changes |
| 100 | |
| 101 | |
| 102 | def path_dependencies(document): |
| 103 | for key, value in document.items(): |
| 104 | if key in {"dependencies", "dev-dependencies", "build-dependencies"}: |
| 105 | for dependency in value.values(): |
| 106 | if isinstance(dependency, dict) and isinstance(dependency.get("path"), str): |
| 107 | yield dependency["path"] |
| 108 | elif isinstance(value, dict): |
| 109 | yield from path_dependencies(value) |
| 110 | |
| 111 | |
| 112 | def manifest_sources(root, manifest, document): |
| 113 | sources = {manifest.parent.resolve()} |
| 114 | for section in ("lib", "bin", "test", "bench", "example"): |
| 115 | entries = document.get(section, []) |
| 116 | if isinstance(entries, dict): |
| 117 | entries = [entries] |
| 118 | for entry in entries: |
| 119 | path = entry.get("path") |
| 120 | if isinstance(path, str): |
| 121 | source = (manifest.parent / path).resolve().parent |
| 122 | if source.is_relative_to(root): |
| 123 | sources.add(source) |
| 124 | return sources |
| 125 | |
| 126 | |
| 127 | def literal_source_inputs(root, directories): |
| 128 | pending = [ |
| 129 | source |
| 130 | for directory in directories |
| 131 | for source in directory.rglob("*.rs") |
| 132 | ] |
| 133 | checked = set() |
| 134 | inputs = set() |
| 135 | while pending: |
| 136 | source = pending.pop().resolve() |
| 137 | if source in checked or not source.is_relative_to(root) or not source.is_file(): |
| 138 | continue |
| 139 | checked.add(source) |
| 140 | for relative in LITERAL_SOURCE_PATH.findall(source.read_text(encoding="utf-8")): |
| 141 | dependency = (source.parent / relative).resolve() |
| 142 | if dependency.is_relative_to(root): |
| 143 | inputs.add(dependency) |
| 144 | if dependency.suffix == ".rs": |
| 145 | pending.append(dependency) |
| 146 | return inputs |
| 147 | |
| 148 | |
| 149 | def select_manifests(root, paths, changes): |
| 150 | root = root.resolve() |
| 151 | documents = { |
| 152 | manifest: tomllib.loads(manifest.read_text(encoding="utf-8")) |
| 153 | for manifest in paths |
| 154 | } |
| 155 | owners = { |
| 156 | manifest: manifest_sources(root, manifest, document) |
| 157 | for manifest, document in documents.items() |
| 158 | } |
| 159 | literal_inputs = { |
| 160 | manifest: literal_source_inputs(root, directories) |
| 161 | for manifest, directories in owners.items() |
| 162 | } |
| 163 | by_directory = {manifest.parent.resolve(): manifest for manifest in paths} |
| 164 | dependents = {manifest: set() for manifest in paths} |
| 165 | for manifest, document in documents.items(): |
| 166 | for dependency in path_dependencies(document): |
| 167 | target = (manifest.parent / dependency).resolve() |
| 168 | if target in by_directory: |
| 169 | dependents[by_directory[target]].add(manifest) |
| 170 | |
| 171 | selected = set() |
| 172 | for change in changes: |
| 173 | changed_path = (root / change).resolve() |
| 174 | direct = { |
| 175 | manifest for manifest, directories in owners.items() |
| 176 | if any(changed_path.is_relative_to(directory) for directory in directories) |
| 177 | or changed_path in literal_inputs[manifest] |
| 178 | } |
| 179 | if direct: |
| 180 | selected.update(direct) |
| 181 | elif change.startswith("docs/") or change.endswith(".md") or change == "LICENSE": |
| 182 | continue |
| 183 | else: |
| 184 | return paths |
| 185 | |
| 186 | pending = list(selected) |
| 187 | while pending: |
| 188 | for dependent in dependents[pending.pop()] - selected: |
| 189 | selected.add(dependent) |
| 190 | pending.append(dependent) |
| 191 | return [manifest for manifest in paths if manifest in selected] |
| 192 | |
| 193 | |
| 194 | def command(manifest, phase): |
| 195 | arguments = [ |
| 196 | "cargo", |
| 197 | TOOLCHAIN, |
| 198 | "build" if phase == "cross-build" else phase, |
| 199 | "--manifest-path", |
| 200 | str(manifest), |
| 201 | "--locked", |
| 202 | "--all-targets", |
| 203 | "--all-features", |
| 204 | ] |
| 205 | if phase == "cross-build": |
| 206 | arguments += ["--target", WINDOWS_TARGET] |
| 207 | if phase == "test": |
| 208 | arguments += ["--", "--test-threads=1"] |
| 209 | return arguments |
| 210 | |
| 211 | |
| 212 | def prepare_fixtures(root): |
| 213 | skipped = {} |
| 214 | work = test_work_directory(root) |
| 215 | if work.resolve() != work: |
| 216 | raise ValueError(f"안전한 작업 디렉터리가 필요함: {work}") |
| 217 | work.mkdir(mode=0o700, parents=True, exist_ok=True) |
| 218 | output_directory(work, "fixtures", create=True) |
| 219 | return skipped |
| 220 | |
| 221 | |
| 222 | def run(root, phase, selected=None): |
| 223 | paths = manifests(root) if selected is None else selected |
| 224 | skipped = {} |
| 225 | if phase == "test" and sys.platform == "linux": |
| 226 | skipped = prepare_fixtures(root) |
| 227 | results = [] |
| 228 | for manifest in paths: |
| 229 | relative = manifest.relative_to(root).as_posix() |
| 230 | if manifest.parent.parent.name == "tests" and manifest.parent.name in skipped: |
| 231 | reason = skipped[manifest.parent.name] |
| 232 | results.append({ |
| 233 | "manifest": relative, |
| 234 | "status": "not-applicable", |
| 235 | "reason": reason, |
| 236 | }) |
| 237 | print(f"NOT APPLICABLE: {relative} ({reason})", flush=True) |
| 238 | continue |
| 239 | if ( |
| 240 | phase == "test" |
| 241 | and sys.platform != "linux" |
| 242 | and manifest.parent.parent.name == "tests" |
| 243 | and manifest.parent.name in LINUX_ONLY |
| 244 | ): |
| 245 | results.append({ |
| 246 | "manifest": relative, |
| 247 | "status": "not-applicable", |
| 248 | "reason": "Linux-only cfg", |
| 249 | }) |
| 250 | print(f"NOT APPLICABLE: {relative} (Linux-only cfg)", flush=True) |
| 251 | continue |
| 252 | print(f"::group::{phase}: {relative}", flush=True) |
| 253 | completed = subprocess.run(command(manifest, phase), cwd=root, check=False) |
| 254 | results.append({ |
| 255 | "manifest": relative, |
| 256 | "status": "passed" if completed.returncode == 0 else "failed", |
| 257 | "exit_code": completed.returncode, |
| 258 | }) |
| 259 | print("::endgroup::", flush=True) |
| 260 | return results |
| 261 | |
| 262 | |
| 263 | def prepare_tools(root): |
| 264 | configured = os.environ.get("ZIPELO_CI_TOOLS") |
| 265 | if configured: |
| 266 | directories = [Path(configured).resolve()] |
| 267 | else: |
| 268 | directories = [test_work_directory(root) / "tools"] |
| 269 | common = Path(subprocess.check_output( |
| 270 | ["git", "rev-parse", "--path-format=absolute", "--git-common-dir"], |
| 271 | cwd=root, text=True, |
| 272 | ).strip()) |
| 273 | # 같은 저장소의 기본 worktree에 준비한 도구를 재사용함. |
| 274 | if common.name == ".git": |
| 275 | directories.append(common.parent / "tests/ci/tools") |
| 276 | for tools in directories: |
| 277 | if (tools / "rustup/toolchains/1.99.1-x86_64-unknown-linux-gnu").is_dir(): |
| 278 | os.environ.setdefault("RUSTUP_HOME", str(tools / "rustup")) |
| 279 | bins = [str(tools / "mingw/usr/bin") for tools in directories |
| 280 | if (tools / "mingw/usr/bin").is_dir()] |
| 281 | if bins: |
| 282 | os.environ["PATH"] = os.pathsep.join(bins + [os.environ.get("PATH", "")]) |
| 283 | |
| 284 | |
| 285 | def prepare_cross_build(): |
| 286 | for variable, names in ( |
| 287 | ("CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER", [ |
| 288 | "x86_64-w64-mingw32-gcc", "x86_64-w64-mingw32-gcc-posix", |
| 289 | ]), |
| 290 | ("CC_x86_64_pc_windows_gnu", [ |
| 291 | "x86_64-w64-mingw32-gcc", "x86_64-w64-mingw32-gcc-posix", |
| 292 | ]), |
| 293 | ("CXX_x86_64_pc_windows_gnu", [ |
| 294 | "x86_64-w64-mingw32-g++", "x86_64-w64-mingw32-g++-posix", |
| 295 | ]), |
| 296 | ): |
| 297 | candidate = os.environ.get(variable) |
| 298 | if not candidate: |
| 299 | candidate = next((shutil.which(name) for name in names if shutil.which(name)), None) |
| 300 | if not candidate or not shutil.which(candidate): |
| 301 | raise ValueError( |
| 302 | f"Windows 교차 컴파일 도구가 없음: {variable}. " |
| 303 | "bash tests/ci/setup_windows.sh 실행 또는 ZIPELO_CI_TOOLS 지정이 필요함" |
| 304 | ) |
| 305 | os.environ[variable] = candidate |
| 306 | |
| 307 | |
| 308 | def prepare_local_tools(root): |
| 309 | try: |
| 310 | prepare_cross_build() |
| 311 | except ValueError: |
| 312 | print("Windows 교차 도구를 프로젝트 내부에 준비함: tests/ci/setup_windows.sh", flush=True) |
| 313 | environment = dict(os.environ, ZIPELO_CI_TOOLS=str(test_work_directory(root) / "tools")) |
| 314 | subprocess.run(["bash", str(root / "tests/ci/setup_windows.sh")], |
| 315 | cwd=root, env=environment, check=True) |
| 316 | os.environ["ZIPELO_CI_TOOLS"] = environment["ZIPELO_CI_TOOLS"] |
| 317 | prepare_tools(root) |
| 318 | prepare_cross_build() |
| 319 | |
| 320 | |
| 321 | def execute_phases(root, phases, selected=None): |
| 322 | results = [] |
| 323 | for phase in phases: |
| 324 | try: |
| 325 | if phase == "cross-build" and selected != []: |
| 326 | prepare_cross_build() |
| 327 | rows = run(root, phase, selected) |
| 328 | except (OSError, ValueError, subprocess.CalledProcessError) as error: |
| 329 | rows = [{"manifest": "preflight", "status": "failed", "reason": str(error)}] |
| 330 | for row in rows: |
| 331 | results.append({"phase": phase, **row}) |
| 332 | return results |
| 333 | |
| 334 | |
| 335 | def main(): |
| 336 | parser = argparse.ArgumentParser(description="로컬 Linux 시험과 Windows 교차 빌드") |
| 337 | parser.add_argument("phase", choices=["local", "build", "test", "cross-build"]) |
| 338 | parser.add_argument("--job", default=os.environ.get("ZIPELO_CI_JOB", "rust-local")) |
| 339 | parser.add_argument("--changed", action="store_true", |
| 340 | help="origin/main과 비교해 영향받는 crate만 실행함") |
| 341 | args = parser.parse_args() |
| 342 | if args.phase == "local" and sys.platform != "linux": |
| 343 | parser.error("local 모드는 Linux에서 실행해야 함") |
| 344 | work = work_directory(ROOT, args.job) |
| 345 | temporary = output_directory(work, "tmp", create=True) |
| 346 | target = output_directory(work, "target") |
| 347 | cargo = output_directory(output_directory(work, "tools", create=True), |
| 348 | "cargo", create=True) |
| 349 | os.environ["ZIPELO_CI_JOB"] = args.job |
| 350 | os.environ["ZIPELO_TEST_WORK_DIR"] = str(work) |
| 351 | os.environ["TMPDIR"] = str(temporary) |
| 352 | os.environ["TMP"] = str(temporary) |
| 353 | os.environ["TEMP"] = str(temporary) |
| 354 | os.environ["PYTHONDONTWRITEBYTECODE"] = "1" |
| 355 | os.environ.setdefault("CARGO_BUILD_JOBS", "2") |
| 356 | os.environ["CARGO_TARGET_DIR"] = str(target) |
| 357 | os.environ["CARGO_HOME"] = str(cargo) |
| 358 | prepare_tools(ROOT) |
| 359 | phases = ["build", "test", "cross-build"] if args.phase == "local" else [args.phase] |
| 360 | selected = None |
| 361 | selection_error = None |
| 362 | if args.changed: |
| 363 | try: |
| 364 | selected = select_manifests(ROOT, manifests(ROOT), changed_files(ROOT)) |
| 365 | except (OSError, ValueError) as error: |
| 366 | selection_error = str(error) |
| 367 | checks = subprocess.run( |
| 368 | [sys.executable, "-m", "unittest", "discover", "-s", "tests/ci", "-p", "test_*.py"], |
| 369 | cwd=ROOT, check=False, |
| 370 | ) |
| 371 | if checks.returncode != 0: |
| 372 | results = [{ |
| 373 | "phase": "self-check", |
| 374 | "manifest": "tests/ci", |
| 375 | "status": "failed", |
| 376 | "exit_code": checks.returncode, |
| 377 | }] |
| 378 | elif selection_error is not None: |
| 379 | results = [{ |
| 380 | "phase": "selection", "manifest": "preflight", |
| 381 | "status": "failed", "reason": selection_error, |
| 382 | }] |
| 383 | else: |
| 384 | try: |
| 385 | if args.phase == "local" and selected != []: |
| 386 | prepare_local_tools(ROOT) |
| 387 | except (OSError, ValueError, subprocess.CalledProcessError) as error: |
| 388 | results = [{ |
| 389 | "phase": "tool-setup", "manifest": "preflight", |
| 390 | "status": "failed", "reason": str(error), |
| 391 | }] |
| 392 | else: |
| 393 | results = execute_phases(ROOT, phases, selected) |
| 394 | report = { |
| 395 | "head": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip(), |
| 396 | "platform": sys.platform, |
| 397 | "windows_cross_target": WINDOWS_TARGET if "cross-build" in phases else None, |
| 398 | "windows_runtime_tested": checks.returncode == 0 and sys.platform == "win32" and "test" in phases, |
| 399 | "changed_only": args.changed, |
| 400 | "selected_manifests": [ |
| 401 | path.relative_to(ROOT).as_posix() for path in selected |
| 402 | ] if selected is not None else None, |
| 403 | "results": results, |
| 404 | } |
| 405 | (work / f"{args.phase}-results.json").write_text( |
| 406 | json.dumps(report, ensure_ascii=False, indent=4) + "\n", encoding="utf-8" |
| 407 | ) |
| 408 | lines = [] |
| 409 | for phase in phases: |
| 410 | selected = [row for row in results if row["phase"] == phase] |
| 411 | counts = {status: sum(row["status"] == status for row in selected) |
| 412 | for status in ("passed", "failed", "not-applicable")} |
| 413 | lines.append(f"{phase}: " + ", ".join(f"{key}={value}" for key, value in counts.items())) |
| 414 | for row in results: |
| 415 | if row["status"] == "failed": |
| 416 | lines.append(f"FAIL {row['phase']} {row['manifest']}: {row.get('reason', row.get('exit_code'))}") |
| 417 | if "cross-build" in phases: |
| 418 | lines.append("Windows: cross-build only; runtime tests not executed") |
| 419 | print("\n".join(lines), flush=True) |
| 420 | summary = os.environ.get("GITHUB_STEP_SUMMARY") |
| 421 | if summary: |
| 422 | with open(summary, "a", encoding="utf-8") as output: |
| 423 | output.write("\n" + "\n\n".join(lines) + "\n") |
| 424 | return checks.returncode or int(any(result["status"] == "failed" for result in results)) |
| 425 | |
| 426 | |
| 427 | if __name__ == "__main__": |
| 428 | raise SystemExit(main()) |