team-ljyzipelo

공개

Merge pull request #61 from Team-LJY/features/ci-rust-build

로컬 Linux 시험과 Windows 교차 빌드 실행기 추가
작성자
LeeJunyoung
작성 시각
커밋
486fe9ae64a73f999cc5122c2eb9bbeb62fb2fb3
이 시점의 파일 보기

변경된 파일 6개

+424-0
추가.github/workflows/rust.yml+44-0
@@ -0,0 +1,44 @@
1추가: name: Manual Windows verification
2추가:
3추가: on:
4추가: workflow_dispatch:
5추가:
6추가: permissions:
7추가: contents: read
8추가:
9추가: concurrency:
10추가: group: rust-${{ github.workflow }}-${{ github.ref }}
11추가: cancel-in-progress: true
12추가:
13추가: jobs:
14추가: rust:
15추가: name: Windows build and tests
16추가: runs-on: windows-latest
17추가: timeout-minutes: 45
18추가: env:
19추가: CARGO_TERM_COLOR: always
20추가: CARGO_BUILD_JOBS: 1
21추가: CARGO_TARGET_DIR: ${{ github.workspace }}/tests/ci/target
22추가: RUST_BACKTRACE: 1
23추가: steps:
24추가: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
25추가: env:
26추가: GIT_CONFIG_COUNT: 1
27추가: GIT_CONFIG_KEY_0: core.autocrlf
28추가: GIT_CONFIG_VALUE_0: false
29추가: with:
30추가: persist-credentials: false
31추가: - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1
32추가: with:
33추가: python-version: '3.13'
34추가: - name: Install Rust
35추가: run: rustup toolchain install 1.99.1 --profile minimal --no-self-update
36추가: - name: Check CI runner
37추가: run: python -m unittest discover -s tests/ci -p 'test_*.py' -v
38추가: - name: Build every Rust crate and test harness
39추가: timeout-minutes: 20
40추가: run: python tests/ci/run_rust.py build
41추가: - name: Run Rust tests
42추가: if: ${{ !cancelled() }}
43추가: timeout-minutes: 20
44추가: run: python tests/ci/run_rust.py test
추가tests/ci/.gitignore+3-0
@@ -0,0 +1,3 @@
1추가: /target/
2추가: /*-results.json
3추가: /tools/
추가tests/ci/README.md+27-0
@@ -0,0 +1,27 @@
1추가: # 로컬 Rust 검증
2추가:
3추가: PR을 병합하기 전에 linux-desktop-2에서 아래 명령을 실행하고 검증한 커밋, 요약과 실패 또는 미실행 항목을 PR 본문에 남깁니다. 실패를 성공으로 처리하지 않습니다.
4추가:
5추가: ```sh
6추가: # 최초 1회, Ubuntu의 apt 저장소에서 프로젝트 내부로 교차 도구를 준비함.
7추가: bash tests/ci/setup_windows.sh
8추가: python3 tests/ci/run_rust.py local
9추가: ```
10추가:
11추가: `local`은 실행기 자체 검사 후 Linux 전체 빌드, Linux Rust 시험, Windows 교차 빌드를 순서대로 수행합니다. 단계별 통과/실패/비해당 개수를 출력하고 `tests/ci/local-results.json`에 검증한 HEAD와 결과를 기록합니다. 실패가 있으면 종료 코드는 1입니다.
12추가:
13추가: - Rust 1.99.1, 기존 Cargo.lock, `--locked --all-targets --all-features`를 사용합니다. `experiments/*/Cargo.toml`과 `tests/*/Cargo.toml`을 자동 발견합니다.
14추가: - Windows는 `x86_64-pc-windows-gnu` 대상의 링크까지 확인합니다. 시험 바이너리도 컴파일하지만 실행하지 않습니다. Windows MSVC 빌드 및 실제 실행 검증을 대신하지 않습니다.
15추가: - 빌드 기본 병렬 수는 2이며 `CARGO_BUILD_JOBS`로 조절합니다. 시험 스레드는 1개입니다. `CARGO_TARGET_DIR` 기본값은 `tests/ci/target`이므로 후속 실행에서 빌드 캐시를 재사용합니다.
16추가: - `setup_windows.sh`는 관리자 권한 없이 도구를 `tests/ci/tools`에 풉니다. apt-get, dpkg-deb, rustup 및 GCC 호스트 실행 라이브러리가 필요합니다. 공용 도구 경로를 재사용할 때는 프로젝트 안의 소유 경로를 `ZIPELO_CI_TOOLS`로 지정합니다. 기존 Rust target과 MinGW가 있으면 준비 스크립트 없이 PATH와 관련 Cargo/CC/CXX 환경 설정을 사용할 수 있습니다.
17추가: - Linux GUI 빌드에는 pkg-config, libxkbcommon-dev, libwayland-dev, libgl1-mesa-dev가 필요하며 글꼴 시험에는 fonts-noto-cjk가 필요합니다.
18추가: - 추적된 fixture를 Git blob과 대조합니다. Windows checkout 시 core.autocrlf=false를 사용해야 하며 기대값의 바이트를 바꾸지 않습니다.
19추가: - Unix 소켓 시험을 위해 짧은 checkout 경로를 사용합니다. 예: 프로젝트 아래 `tests/ci-k`. 기존 `runs` 디렉터리는 소유권, 0700, 빈 상태를 확인하고 새 디렉터리만 생성합니다. 실패한 fixture는 삭제하거나 권한을 바꾸지 않습니다.
20추가: - 개별 단계는 `build`, `test`, `cross-build`로 실행할 수 있습니다. 한 crate가 실패해도 다른 crate 결과를 수집합니다.
21추가: - GUI 앱과 GUI race harness는 컴파일하며 실제 화면 시나리오는 실행하지 않습니다. C# 시험과 역사적 hash 검사는 포함하지 않습니다.
22추가:
23추가: ## 출시 전 Windows 실기 확인
24추가:
25추가: `.github/workflows/rust.yml`에는 `workflow_dispatch`만 있습니다. push/PR 자동 실행과 Linux GitHub job은 없습니다. 수동 Windows 실행은 출시 전에 별도로 배정하며, 이 작업에서는 다시 실행하지 않습니다. workflow가 기본 브랜치에 반영된 후 Actions에서 해당 브랜치를 골라 실행할 수 있습니다.
26추가:
27추가: 수동 실행은 Windows에서 전체 빌드와 Rust 시험을 수행하고 Linux 전용 publication, snapshot, file-job, system-font 시험은 `not-applicable`로 표시합니다. 기존 GUI 화면 시나리오는 별도 확인해야 합니다.
추가tests/ci/run_rust.py+193-0
@@ -0,0 +1,193 @@
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추가:
22추가:
23추가: def manifests(root):
24추가: paths = sorted(root.glob("experiments/*/Cargo.toml"))
25추가: if not paths:
26추가: raise ValueError("experiments/ Rust crate를 찾지 못함")
27추가: paths += sorted(root.glob("tests/*/Cargo.toml"))
28추가: for path in paths:
29추가: if not path.with_name("Cargo.lock").is_file():
30추가: raise ValueError(f"고정 Cargo.lock이 없음: {path}")
31추가: return paths
32추가:
33추가:
34추가: def command(manifest, phase):
35추가: arguments = [
36추가: "cargo",
37추가: TOOLCHAIN,
38추가: "build" if phase == "cross-build" else phase,
39추가: "--manifest-path",
40추가: str(manifest),
41추가: "--locked",
42추가: "--all-targets",
43추가: "--all-features",
44추가: ]
45추가: if phase == "cross-build":
46추가: arguments += ["--target", WINDOWS_TARGET]
47추가: if phase == "test":
48추가: arguments += ["--", "--test-threads=1"]
49추가: return arguments
50추가:
51추가:
52추가: def prepare_fixtures(root):
53추가: socket = root / "tests/rust-file-publication/runs/case-2147483647-99/parent/output"
54추가: if len(os.fsencode(socket)) >= 108:
55추가: raise ValueError("Unix 소켓 시험을 위해 더 짧은 checkout 경로가 필요함")
56추가: for name in sorted(FILE_FIXTURES):
57추가: path = root / "tests" / name / "runs"
58추가: if not path.exists() and not path.is_symlink():
59추가: path.mkdir(mode=0o700)
60추가: info = path.lstat()
61추가: if (
62추가: not stat.S_ISDIR(info.st_mode)
63추가: or stat.S_IMODE(info.st_mode) != 0o700
64추가: or info.st_uid != os.geteuid()
65추가: or path.resolve() != path
66추가: or any(path.iterdir())
67추가: ):
68추가: raise ValueError(f"비어 있는 소유 시험 디렉터리가 필요함: {path}")
69추가:
70추가:
71추가: def run(root, phase):
72추가: paths = manifests(root)
73추가: if phase == "test" and sys.platform == "linux":
74추가: prepare_fixtures(root)
75추가: results = []
76추가: for manifest in paths:
77추가: relative = manifest.relative_to(root).as_posix()
78추가: if (
79추가: phase == "test"
80추가: and sys.platform != "linux"
81추가: and manifest.parent.parent.name == "tests"
82추가: and manifest.parent.name in LINUX_ONLY
83추가: ):
84추가: results.append({
85추가: "manifest": relative,
86추가: "status": "not-applicable",
87추가: "reason": "Linux-only cfg",
88추가: })
89추가: print(f"NOT APPLICABLE: {relative} (Linux-only cfg)", flush=True)
90추가: continue
91추가: print(f"::group::{phase}: {relative}", flush=True)
92추가: completed = subprocess.run(command(manifest, phase), cwd=root, check=False)
93추가: results.append({
94추가: "manifest": relative,
95추가: "status": "passed" if completed.returncode == 0 else "failed",
96추가: "exit_code": completed.returncode,
97추가: })
98추가: print("::endgroup::", flush=True)
99추가: return results
100추가:
101추가:
102추가: def prepare_cross_build():
103추가: for variable, names in (
104추가: ("CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER", [
105추가: "x86_64-w64-mingw32-gcc", "x86_64-w64-mingw32-gcc-posix",
106추가: ]),
107추가: ("CC_x86_64_pc_windows_gnu", [
108추가: "x86_64-w64-mingw32-gcc", "x86_64-w64-mingw32-gcc-posix",
109추가: ]),
110추가: ("CXX_x86_64_pc_windows_gnu", [
111추가: "x86_64-w64-mingw32-g++", "x86_64-w64-mingw32-g++-posix",
112추가: ]),
113추가: ):
114추가: candidate = os.environ.get(variable)
115추가: if not candidate:
116추가: candidate = next((shutil.which(name) for name in names if shutil.which(name)), None)
117추가: if not candidate or not shutil.which(candidate):
118추가: raise ValueError(f"Windows 교차 컴파일 도구가 없음: {variable}")
119추가: os.environ[variable] = candidate
120추가:
121추가:
122추가: def execute_phases(root, phases):
123추가: results = []
124추가: for phase in phases:
125추가: try:
126추가: if phase == "cross-build":
127추가: prepare_cross_build()
128추가: rows = run(root, phase)
129추가: except (OSError, ValueError) as error:
130추가: rows = [{"manifest": "preflight", "status": "failed", "reason": str(error)}]
131추가: for row in rows:
132추가: results.append({"phase": phase, **row})
133추가: return results
134추가:
135추가:
136추가: def main():
137추가: parser = argparse.ArgumentParser(description="로컬 Linux 시험과 Windows 교차 빌드")
138추가: parser.add_argument("phase", choices=["local", "build", "test", "cross-build"])
139추가: args = parser.parse_args()
140추가: if args.phase == "local" and sys.platform != "linux":
141추가: parser.error("local 모드는 Linux에서 실행해야 함")
142추가: tools = Path(os.environ.get("ZIPELO_CI_TOOLS", ROOT / "tests/ci/tools")).resolve()
143추가: if (tools / "rustup/toolchains/1.99.1-x86_64-unknown-linux-gnu").is_dir():
144추가: os.environ.setdefault("RUSTUP_HOME", str(tools / "rustup"))
145추가: if (tools / "mingw/usr/bin").is_dir():
146추가: os.environ["PATH"] = str(tools / "mingw/usr/bin") + os.pathsep + os.environ["PATH"]
147추가: os.environ.setdefault("CARGO_BUILD_JOBS", "2")
148추가: os.environ.setdefault("CARGO_TARGET_DIR", str(ROOT / "tests/ci/target"))
149추가: phases = ["build", "test", "cross-build"] if args.phase == "local" else [args.phase]
150추가: checks = subprocess.run(
151추가: [sys.executable, "-m", "unittest", "discover", "-s", "tests/ci", "-p", "test_*.py"],
152추가: cwd=ROOT, check=False,
153추가: )
154추가: if checks.returncode != 0:
155추가: results = [{
156추가: "phase": "self-check",
157추가: "manifest": "tests/ci",
158추가: "status": "failed",
159추가: "exit_code": checks.returncode,
160추가: }]
161추가: else:
162추가: results = execute_phases(ROOT, phases)
163추가: report = {
164추가: "head": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip(),
165추가: "platform": sys.platform,
166추가: "windows_cross_target": WINDOWS_TARGET if "cross-build" in phases else None,
167추가: "windows_runtime_tested": checks.returncode == 0 and sys.platform == "win32" and "test" in phases,
168추가: "results": results,
169추가: }
170추가: (ROOT / f"tests/ci/{args.phase}-results.json").write_text(
171추가: json.dumps(report, ensure_ascii=False, indent=4) + "\n", encoding="utf-8"
172추가: )
173추가: lines = []
174추가: for phase in phases:
175추가: selected = [row for row in results if row["phase"] == phase]
176추가: counts = {status: sum(row["status"] == status for row in selected)
177추가: for status in ("passed", "failed", "not-applicable")}
178추가: lines.append(f"{phase}: " + ", ".join(f"{key}={value}" for key, value in counts.items()))
179추가: for row in results:
180추가: if row["status"] == "failed":
181추가: lines.append(f"FAIL {row['phase']} {row['manifest']}: {row.get('reason', row.get('exit_code'))}")
182추가: if "cross-build" in phases:
183추가: lines.append("Windows: cross-build only; runtime tests not executed")
184추가: print("\n".join(lines), flush=True)
185추가: summary = os.environ.get("GITHUB_STEP_SUMMARY")
186추가: if summary:
187추가: with open(summary, "a", encoding="utf-8") as output:
188추가: output.write("\n" + "\n\n".join(lines) + "\n")
189추가: return checks.returncode or int(any(result["status"] == "failed" for result in results))
190추가:
191추가:
192추가: if __name__ == "__main__":
193추가: raise SystemExit(main())
추가tests/ci/setup_windows.sh+26-0
@@ -0,0 +1,26 @@
1추가: #!/usr/bin/env bash
2추가: set -euo pipefail
3추가:
4추가: repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
5추가: ci_tools="${ZIPELO_CI_TOOLS:-$repo_root/tests/ci/tools}"
6추가: mkdir -p "$ci_tools/downloads" "$ci_tools/mingw"
7추가: ci_tools="$(cd "$ci_tools" && pwd)"
8추가:
9추가: # 도구를 프로젝트 안에 풀며 시스템 패키지는 설치하지 않음.
10추가: (
11추가: cd "$ci_tools/downloads"
12추가: apt-get download \
13추가: gcc-mingw-w64-x86-64-posix \
14추가: g++-mingw-w64-x86-64-posix \
15추가: gcc-mingw-w64-x86-64-posix-runtime \
16추가: gcc-mingw-w64-base \
17추가: binutils-mingw-w64-x86-64 \
18추가: binutils-mingw-w64-base \
19추가: mingw-w64-x86-64-dev \
20추가: mingw-w64-common
21추가: for package in ./*.deb; do
22추가: dpkg-deb -x "$package" "$ci_tools/mingw"
23추가: done
24추가: )
25추가: RUSTUP_HOME="$ci_tools/rustup" rustup toolchain install 1.99.1 \
26추가: --profile minimal --no-self-update --target x86_64-pc-windows-gnu
추가tests/ci/test_runner.py+131-0
@@ -0,0 +1,131 @@
1추가: from contextlib import redirect_stdout
2추가: from io import StringIO
3추가: import json
4추가: from pathlib import Path
5추가: import tempfile
6추가: import subprocess
7추가: import unittest
8추가: from unittest.mock import patch
9추가:
10추가: import run_rust
11추가:
12추가:
13추가: class RunnerTests(unittest.TestCase):
14추가: def test_all_manifests_have_locks(self):
15추가: paths = run_rust.manifests(run_rust.ROOT)
16추가: expected = set(run_rust.ROOT.glob("experiments/*/Cargo.toml"))
17추가: expected |= set(run_rust.ROOT.glob("tests/*/Cargo.toml"))
18추가: self.assertEqual(set(paths), expected)
19추가:
20추가: def test_failure_does_not_hide_later_crates(self):
21추가: paths = [
22추가: Path("/repo/experiments/a/Cargo.toml"),
23추가: Path("/repo/experiments/b/Cargo.toml"),
24추가: ]
25추가: with (
26추가: patch.object(run_rust, "manifests", return_value=paths),
27추가: patch.object(run_rust.subprocess, "run", side_effect=[
28추가: subprocess.CompletedProcess([], 7),
29추가: subprocess.CompletedProcess([], 0),
30추가: ]),
31추가: ):
32추가: results = run_rust.run(Path("/repo"), "build")
33추가: self.assertEqual([row["status"] for row in results], ["failed", "passed"])
34추가: self.assertEqual(results[0]["exit_code"], 7)
35추가:
36추가: def test_windows_exclusion_is_explicit_and_only_for_linux_tests(self):
37추가: paths = [
38추가: Path("/repo/tests/rust-file-publication/Cargo.toml"),
39추가: Path("/repo/experiments/rust-file-publication/Cargo.toml"),
40추가: ]
41추가: with (
42추가: patch.object(run_rust, "manifests", return_value=paths),
43추가: patch.object(run_rust.sys, "platform", "win32"),
44추가: patch.object(
45추가: run_rust.subprocess, "run",
46추가: return_value=subprocess.CompletedProcess([], 0),
47추가: ) as execute,
48추가: ):
49추가: results = run_rust.run(Path("/repo"), "test")
50추가: self.assertEqual(
51추가: [row["status"] for row in results], ["not-applicable", "passed"]
52추가: )
53추가: self.assertEqual(execute.call_count, 1)
54추가:
55추가: def test_fixture_bytes_match_git_blobs(self):
56추가: names = subprocess.check_output(
57추가: ["git", "ls-files", "-z", "tests/**/fixtures/*"], cwd=run_rust.ROOT
58추가: ).decode("utf-8").split("\0")
59추가: names = [name for name in names if name]
60추가: self.assertTrue(names, "검증할 fixture가 없음")
61추가: for name in names:
62추가: with self.subTest(path=name):
63추가: expected = subprocess.check_output(
64추가: ["git", "show", f"HEAD:{name}"], cwd=run_rust.ROOT
65추가: )
66추가: self.assertEqual((run_rust.ROOT / name).read_bytes(), expected)
67추가:
68추가: def test_cross_build_never_executes_tests(self):
69추가: args = run_rust.command(Path("tests/example/Cargo.toml"), "cross-build")
70추가: self.assertEqual(args[2], "build")
71추가: self.assertIn(run_rust.WINDOWS_TARGET, args)
72추가: self.assertNotIn("--test-threads=1", args)
73추가:
74추가: def test_preflight_failure_is_reported_without_hiding_other_phase(self):
75추가: with (
76추가: patch.object(run_rust, "prepare_cross_build", side_effect=ValueError("missing linker")),
77추가: patch.object(run_rust, "run", return_value=[{"manifest": "sample", "status": "passed"}]),
78추가: ):
79추가: results = run_rust.execute_phases(Path("/repo"), ["build", "cross-build"])
80추가: self.assertEqual([row["status"] for row in results], ["passed", "failed"])
81추가: self.assertEqual(results[1]["reason"], "missing linker")
82추가:
83추가: def test_self_check_failure_replaces_previous_success_report(self):
84추가: for phase, platform in (("local", "linux"), ("test", "win32")):
85추가: with self.subTest(phase=phase), tempfile.TemporaryDirectory(
86추가: dir=run_rust.ROOT / "tests/ci"
87추가: ) as directory:
88추가: root = Path(directory)
89추가: (root / "tests/ci").mkdir(parents=True)
90추가: report_path = root / f"tests/ci/{phase}-results.json"
91추가: with (
92추가: patch.object(run_rust, "ROOT", root),
93추가: patch.object(run_rust.sys, "argv", ["run_rust.py", phase]),
94추가: patch.object(run_rust.sys, "platform", platform),
95추가: patch.dict(run_rust.os.environ, {"GITHUB_STEP_SUMMARY": ""}),
96추가: patch.object(run_rust.subprocess, "run", side_effect=[
97추가: subprocess.CompletedProcess([], 0),
98추가: subprocess.CompletedProcess([], 7),
99추가: ]),
100추가: patch.object(run_rust.subprocess, "check_output", side_effect=[
101추가: "successful-head\n", "failed-head\n",
102추가: ]),
103추가: patch.object(run_rust, "execute_phases", return_value=[
104추가: {"phase": "test", "manifest": "sample", "status": "passed"},
105추가: ]) as execute,
106추가: redirect_stdout(StringIO()),
107추가: ):
108추가: self.assertEqual(run_rust.main(), 0)
109추가: successful = json.loads(report_path.read_text(encoding="utf-8"))
110추가: self.assertEqual(successful["results"][0]["status"], "passed")
111추가: self.assertEqual(run_rust.main(), 7)
112추가: failed = json.loads(report_path.read_text(encoding="utf-8"))
113추가: self.assertEqual(failed["head"], "failed-head")
114추가: self.assertEqual(failed["results"], [{
115추가: "phase": "self-check",
116추가: "manifest": "tests/ci",
117추가: "status": "failed",
118추가: "exit_code": 7,
119추가: }])
120추가: self.assertFalse(failed["windows_runtime_tested"])
121추가: execute.assert_called_once()
122추가:
123추가: def test_cargo_contract(self):
124추가: args = run_rust.command(Path("tests/example/Cargo.toml"), "test")
125추가: self.assertIn("--locked", args)
126추가: self.assertIn("--all-features", args)
127추가: self.assertEqual(args[-2:], ["--", "--test-threads=1"])
128추가:
129추가:
130추가: if __name__ == "__main__":
131추가: unittest.main()