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