| 1 | import argparse |
| 2 | import json |
| 3 | import os |
| 4 | from pathlib import Path |
| 5 | import shutil |
| 6 | import stat |
| 7 | import subprocess |
| 8 | import sys |
| 9 | |
| 10 | |
| 11 | ROOT = Path(__file__).resolve().parents[2] |
| 12 | TOOLCHAIN = "+1.99.1" |
| 13 | WINDOWS_TARGET = "x86_64-pc-windows-gnu" |
| 14 | LINUX_ONLY = { |
| 15 | "rust-file-publication", |
| 16 | "rust-file-snapshot", |
| 17 | "rust-gzip-file-job", |
| 18 | "rust-ui-system-font-regressions", |
| 19 | } |
| 20 | FILE_FIXTURES = LINUX_ONLY - {"rust-ui-system-font-regressions"} |
| 21 | PUBLICATION_FIXTURES = {"rust-file-publication", "rust-gzip-file-job"} |
| 22 | |
| 23 | |
| 24 | def manifests(root): |
| 25 | paths = sorted(root.glob("experiments/*/Cargo.toml")) |
| 26 | if not paths: |
| 27 | raise ValueError("experiments/ Rust crate를 찾지 못함") |
| 28 | paths += sorted(root.glob("tests/*/Cargo.toml")) |
| 29 | for path in paths: |
| 30 | if not path.with_name("Cargo.lock").is_file(): |
| 31 | raise ValueError(f"고정 Cargo.lock이 없음: {path}") |
| 32 | return paths |
| 33 | |
| 34 | |
| 35 | def command(manifest, phase): |
| 36 | arguments = [ |
| 37 | "cargo", |
| 38 | TOOLCHAIN, |
| 39 | "build" if phase == "cross-build" else phase, |
| 40 | "--manifest-path", |
| 41 | str(manifest), |
| 42 | "--locked", |
| 43 | "--all-targets", |
| 44 | "--all-features", |
| 45 | ] |
| 46 | if phase == "cross-build": |
| 47 | arguments += ["--target", WINDOWS_TARGET] |
| 48 | if phase == "test": |
| 49 | arguments += ["--", "--test-threads=1"] |
| 50 | return arguments |
| 51 | |
| 52 | |
| 53 | def prepare_fixtures(root): |
| 54 | skipped = {} |
| 55 | for name in sorted(FILE_FIXTURES): |
| 56 | path = root / "tests" / name / "runs" |
| 57 | if not path.exists() and not path.is_symlink(): |
| 58 | path.mkdir(mode=0o700) |
| 59 | info = path.lstat() |
| 60 | if ( |
| 61 | not stat.S_ISDIR(info.st_mode) |
| 62 | or stat.S_IMODE(info.st_mode) != 0o700 |
| 63 | or info.st_uid != os.geteuid() |
| 64 | or path.resolve() != path |
| 65 | or any(path.iterdir()) |
| 66 | ): |
| 67 | raise ValueError(f"비어 있는 소유 시험 디렉터리가 필요함: {path}") |
| 68 | if name in PUBLICATION_FIXTURES: |
| 69 | filesystem = subprocess.check_output( |
| 70 | ["stat", "-f", "-c", "%t", "--", str(path)], text=True |
| 71 | ).strip().lower() |
| 72 | if filesystem not in {"ef53", "58465342"}: |
| 73 | skipped[name] = ( |
| 74 | f"파일 게시 시험은 ext4/XFS가 필요함: filesystem=0x{filesystem}" |
| 75 | " (tmpfs 포함 다른 파일시스템은 제품 코드에서 지원하지 않음)" |
| 76 | ) |
| 77 | continue |
| 78 | if name == "rust-file-publication": |
| 79 | socket = path / "case-2147483647-99/parent/output" |
| 80 | if len(os.fsencode(socket)) >= 108: |
| 81 | raise ValueError("Unix 소켓 시험을 위해 더 짧은 checkout 경로가 필요함") |
| 82 | return skipped |
| 83 | |
| 84 | |
| 85 | def run(root, phase): |
| 86 | paths = manifests(root) |
| 87 | skipped = {} |
| 88 | if phase == "test" and sys.platform == "linux": |
| 89 | skipped = prepare_fixtures(root) |
| 90 | results = [] |
| 91 | for manifest in paths: |
| 92 | relative = manifest.relative_to(root).as_posix() |
| 93 | if manifest.parent.parent.name == "tests" and manifest.parent.name in skipped: |
| 94 | reason = skipped[manifest.parent.name] |
| 95 | results.append({ |
| 96 | "manifest": relative, |
| 97 | "status": "not-applicable", |
| 98 | "reason": reason, |
| 99 | }) |
| 100 | print(f"NOT APPLICABLE: {relative} ({reason})", flush=True) |
| 101 | continue |
| 102 | if ( |
| 103 | phase == "test" |
| 104 | and sys.platform != "linux" |
| 105 | and manifest.parent.parent.name == "tests" |
| 106 | and manifest.parent.name in LINUX_ONLY |
| 107 | ): |
| 108 | results.append({ |
| 109 | "manifest": relative, |
| 110 | "status": "not-applicable", |
| 111 | "reason": "Linux-only cfg", |
| 112 | }) |
| 113 | print(f"NOT APPLICABLE: {relative} (Linux-only cfg)", flush=True) |
| 114 | continue |
| 115 | print(f"::group::{phase}: {relative}", flush=True) |
| 116 | completed = subprocess.run(command(manifest, phase), cwd=root, check=False) |
| 117 | results.append({ |
| 118 | "manifest": relative, |
| 119 | "status": "passed" if completed.returncode == 0 else "failed", |
| 120 | "exit_code": completed.returncode, |
| 121 | }) |
| 122 | print("::endgroup::", flush=True) |
| 123 | return results |
| 124 | |
| 125 | |
| 126 | def prepare_tools(root): |
| 127 | configured = os.environ.get("ZIPELO_CI_TOOLS") |
| 128 | if configured: |
| 129 | directories = [Path(configured).resolve()] |
| 130 | else: |
| 131 | directories = [root / "tests/ci/tools"] |
| 132 | common = Path(subprocess.check_output( |
| 133 | ["git", "rev-parse", "--path-format=absolute", "--git-common-dir"], |
| 134 | cwd=root, text=True, |
| 135 | ).strip()) |
| 136 | # 같은 저장소의 기본 worktree에 준비한 도구만 재사용함. |
| 137 | if common.name == ".git" and common.parent != root: |
| 138 | directories.append(common.parent / "tests/ci/tools") |
| 139 | for tools in directories: |
| 140 | if (tools / "rustup/toolchains/1.99.1-x86_64-unknown-linux-gnu").is_dir(): |
| 141 | os.environ.setdefault("RUSTUP_HOME", str(tools / "rustup")) |
| 142 | bins = [str(tools / "mingw/usr/bin") for tools in directories |
| 143 | if (tools / "mingw/usr/bin").is_dir()] |
| 144 | if bins: |
| 145 | os.environ["PATH"] = os.pathsep.join(bins + [os.environ.get("PATH", "")]) |
| 146 | |
| 147 | |
| 148 | def prepare_cross_build(): |
| 149 | for variable, names in ( |
| 150 | ("CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER", [ |
| 151 | "x86_64-w64-mingw32-gcc", "x86_64-w64-mingw32-gcc-posix", |
| 152 | ]), |
| 153 | ("CC_x86_64_pc_windows_gnu", [ |
| 154 | "x86_64-w64-mingw32-gcc", "x86_64-w64-mingw32-gcc-posix", |
| 155 | ]), |
| 156 | ("CXX_x86_64_pc_windows_gnu", [ |
| 157 | "x86_64-w64-mingw32-g++", "x86_64-w64-mingw32-g++-posix", |
| 158 | ]), |
| 159 | ): |
| 160 | candidate = os.environ.get(variable) |
| 161 | if not candidate: |
| 162 | candidate = next((shutil.which(name) for name in names if shutil.which(name)), None) |
| 163 | if not candidate or not shutil.which(candidate): |
| 164 | raise ValueError( |
| 165 | f"Windows 교차 컴파일 도구가 없음: {variable}. " |
| 166 | "bash tests/ci/setup_windows.sh 실행 또는 ZIPELO_CI_TOOLS 지정이 필요함" |
| 167 | ) |
| 168 | os.environ[variable] = candidate |
| 169 | |
| 170 | |
| 171 | def prepare_local_tools(root): |
| 172 | try: |
| 173 | prepare_cross_build() |
| 174 | except ValueError: |
| 175 | print("Windows 교차 도구를 프로젝트 내부에 준비함: tests/ci/setup_windows.sh", flush=True) |
| 176 | subprocess.run(["bash", str(root / "tests/ci/setup_windows.sh")], cwd=root, check=True) |
| 177 | prepare_tools(root) |
| 178 | prepare_cross_build() |
| 179 | |
| 180 | |
| 181 | def execute_phases(root, phases): |
| 182 | results = [] |
| 183 | for phase in phases: |
| 184 | try: |
| 185 | if phase == "cross-build": |
| 186 | prepare_cross_build() |
| 187 | rows = run(root, phase) |
| 188 | except (OSError, ValueError, subprocess.CalledProcessError) as error: |
| 189 | rows = [{"manifest": "preflight", "status": "failed", "reason": str(error)}] |
| 190 | for row in rows: |
| 191 | results.append({"phase": phase, **row}) |
| 192 | return results |
| 193 | |
| 194 | |
| 195 | def main(): |
| 196 | parser = argparse.ArgumentParser(description="로컬 Linux 시험과 Windows 교차 빌드") |
| 197 | parser.add_argument("phase", choices=["local", "build", "test", "cross-build"]) |
| 198 | args = parser.parse_args() |
| 199 | if args.phase == "local" and sys.platform != "linux": |
| 200 | parser.error("local 모드는 Linux에서 실행해야 함") |
| 201 | prepare_tools(ROOT) |
| 202 | os.environ.setdefault("CARGO_BUILD_JOBS", "2") |
| 203 | os.environ.setdefault("CARGO_TARGET_DIR", str(ROOT / "tests/ci/target")) |
| 204 | phases = ["build", "test", "cross-build"] if args.phase == "local" else [args.phase] |
| 205 | checks = subprocess.run( |
| 206 | [sys.executable, "-m", "unittest", "discover", "-s", "tests/ci", "-p", "test_*.py"], |
| 207 | cwd=ROOT, check=False, |
| 208 | ) |
| 209 | if checks.returncode != 0: |
| 210 | results = [{ |
| 211 | "phase": "self-check", |
| 212 | "manifest": "tests/ci", |
| 213 | "status": "failed", |
| 214 | "exit_code": checks.returncode, |
| 215 | }] |
| 216 | else: |
| 217 | try: |
| 218 | if args.phase == "local": |
| 219 | prepare_local_tools(ROOT) |
| 220 | except (OSError, ValueError, subprocess.CalledProcessError) as error: |
| 221 | results = [{ |
| 222 | "phase": "tool-setup", "manifest": "preflight", |
| 223 | "status": "failed", "reason": str(error), |
| 224 | }] |
| 225 | else: |
| 226 | results = execute_phases(ROOT, phases) |
| 227 | report = { |
| 228 | "head": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip(), |
| 229 | "platform": sys.platform, |
| 230 | "windows_cross_target": WINDOWS_TARGET if "cross-build" in phases else None, |
| 231 | "windows_runtime_tested": checks.returncode == 0 and sys.platform == "win32" and "test" in phases, |
| 232 | "results": results, |
| 233 | } |
| 234 | (ROOT / f"tests/ci/{args.phase}-results.json").write_text( |
| 235 | json.dumps(report, ensure_ascii=False, indent=4) + "\n", encoding="utf-8" |
| 236 | ) |
| 237 | lines = [] |
| 238 | for phase in phases: |
| 239 | selected = [row for row in results if row["phase"] == phase] |
| 240 | counts = {status: sum(row["status"] == status for row in selected) |
| 241 | for status in ("passed", "failed", "not-applicable")} |
| 242 | lines.append(f"{phase}: " + ", ".join(f"{key}={value}" for key, value in counts.items())) |
| 243 | for row in results: |
| 244 | if row["status"] == "failed": |
| 245 | lines.append(f"FAIL {row['phase']} {row['manifest']}: {row.get('reason', row.get('exit_code'))}") |
| 246 | if "cross-build" in phases: |
| 247 | lines.append("Windows: cross-build only; runtime tests not executed") |
| 248 | print("\n".join(lines), flush=True) |
| 249 | summary = os.environ.get("GITHUB_STEP_SUMMARY") |
| 250 | if summary: |
| 251 | with open(summary, "a", encoding="utf-8") as output: |
| 252 | output.write("\n" + "\n\n".join(lines) + "\n") |
| 253 | return checks.returncode or int(any(result["status"] == "failed" for result in results)) |
| 254 | |
| 255 | |
| 256 | if __name__ == "__main__": |
| 257 | raise SystemExit(main()) |