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