1use gh_workflow::{
2 Concurrency, Container, Event, Expression, Job, Port, PullRequest, Push, Run, Step, Use,
3 Workflow,
4};
5use indexmap::IndexMap;
6
7use crate::tasks::workflows::{
8 nix_build::build_nix,
9 runners::Arch,
10 steps::{CommonJobConditions, repository_owner_guard_expression},
11 vars::{self, PathCondition},
12};
13
14use super::{
15 runners::{self, Platform},
16 steps::{self, FluentBuilder, NamedJob, named, release_job},
17};
18
19pub(crate) fn run_tests() -> Workflow {
20 // Specify anything which should potentially skip full test suite in this regex:
21 // - docs/
22 // - script/update_top_ranking_issues/
23 // - .github/ISSUE_TEMPLATE/
24 // - .github/workflows/ (except .github/workflows/ci.yml)
25 let should_run_tests = PathCondition::inverted(
26 "run_tests",
27 r"^(docs/|script/update_top_ranking_issues/|\.github/(ISSUE_TEMPLATE|workflows/(?!run_tests)))",
28 );
29 let should_check_docs = PathCondition::new("run_docs", r"^(docs/|crates/.*\.rs)");
30 let should_check_scripts = PathCondition::new(
31 "run_action_checks",
32 r"^\.github/(workflows/|actions/|actionlint.yml)|tooling/xtask|script/",
33 );
34 let should_check_licences =
35 PathCondition::new("run_licenses", r"^(Cargo.lock|script/.*licenses)");
36 let should_build_nix = PathCondition::new(
37 "run_nix",
38 r"^(nix/|flake\.|Cargo\.|rust-toolchain.toml|\.cargo/config.toml)",
39 );
40
41 let orchestrate = orchestrate(&[
42 &should_check_scripts,
43 &should_check_docs,
44 &should_check_licences,
45 &should_build_nix,
46 &should_run_tests,
47 ]);
48
49 let mut jobs = vec![
50 orchestrate,
51 check_style(),
52 should_run_tests.guard(clippy(Platform::Windows)),
53 should_run_tests.guard(clippy(Platform::Linux)),
54 should_run_tests.guard(clippy(Platform::Mac)),
55 should_run_tests.guard(run_platform_tests(Platform::Windows)),
56 should_run_tests.guard(run_platform_tests(Platform::Linux)),
57 should_run_tests.guard(run_platform_tests(Platform::Mac)),
58 should_run_tests.guard(doctests()),
59 should_run_tests.guard(check_workspace_binaries()),
60 should_run_tests.guard(check_dependencies()), // could be more specific here?
61 should_check_docs.guard(check_docs()),
62 should_check_licences.guard(check_licenses()),
63 should_check_scripts.guard(check_scripts()),
64 should_build_nix.guard(build_nix(
65 Platform::Linux,
66 Arch::X86_64,
67 "debug",
68 // *don't* cache the built output
69 Some("-zed-editor-[0-9.]*-nightly"),
70 &[],
71 )),
72 should_build_nix.guard(build_nix(
73 Platform::Mac,
74 Arch::AARCH64,
75 "debug",
76 // *don't* cache the built output
77 Some("-zed-editor-[0-9.]*-nightly"),
78 &[],
79 )),
80 ];
81 let tests_pass = tests_pass(&jobs);
82
83 jobs.push(should_run_tests.guard(check_postgres_and_protobuf_migrations())); // could be more specific here?
84
85 named::workflow()
86 .add_event(
87 Event::default()
88 .push(
89 Push::default()
90 .add_branch("main")
91 .add_branch("v[0-9]+.[0-9]+.x"),
92 )
93 .pull_request(PullRequest::default().add_branch("**")),
94 )
95 .concurrency(
96 Concurrency::default()
97 .group(concat!(
98 "${{ github.workflow }}-${{ github.ref_name }}-",
99 "${{ github.ref_name == 'main' && github.sha || 'anysha' }}"
100 ))
101 .cancel_in_progress(true),
102 )
103 .add_env(("CARGO_TERM_COLOR", "always"))
104 .add_env(("RUST_BACKTRACE", 1))
105 .add_env(("CARGO_INCREMENTAL", 0))
106 .map(|mut workflow| {
107 for job in jobs {
108 workflow = workflow.add_job(job.name, job.job)
109 }
110 workflow
111 })
112 .add_job(tests_pass.name, tests_pass.job)
113}
114
115// Generates a bash script that checks changed files against regex patterns
116// and sets GitHub output variables accordingly
117pub fn orchestrate(rules: &[&PathCondition]) -> NamedJob {
118 orchestrate_impl(rules, true)
119}
120
121pub fn orchestrate_without_package_filter(rules: &[&PathCondition]) -> NamedJob {
122 orchestrate_impl(rules, false)
123}
124
125fn orchestrate_impl(rules: &[&PathCondition], include_package_filter: bool) -> NamedJob {
126 let name = "orchestrate".to_owned();
127 let step_name = "filter".to_owned();
128 let mut script = String::new();
129
130 script.push_str(indoc::indoc! {r#"
131 if [ -z "$GITHUB_BASE_REF" ]; then
132 echo "Not in a PR context (i.e., push to main/stable/preview)"
133 COMPARE_REV="$(git rev-parse HEAD~1)"
134 else
135 echo "In a PR context comparing to pull_request.base.ref"
136 git fetch origin "$GITHUB_BASE_REF" --depth=350
137 COMPARE_REV="$(git merge-base "origin/${GITHUB_BASE_REF}" HEAD)"
138 fi
139 CHANGED_FILES="$(git diff --name-only "$COMPARE_REV" ${{ github.sha }})"
140
141 check_pattern() {
142 local output_name="$1"
143 local pattern="$2"
144 local grep_arg="$3"
145
146 echo "$CHANGED_FILES" | grep "$grep_arg" "$pattern" && \
147 echo "${output_name}=true" >> "$GITHUB_OUTPUT" || \
148 echo "${output_name}=false" >> "$GITHUB_OUTPUT"
149 }
150
151 "#});
152
153 let mut outputs = IndexMap::new();
154
155 if include_package_filter {
156 script.push_str(indoc::indoc! {r#"
157 # Check for changes that require full rebuild (no filter)
158 # Direct pushes to main/stable/preview always run full suite
159 if [ -z "$GITHUB_BASE_REF" ]; then
160 echo "Not a PR, running full test suite"
161 echo "changed_packages=" >> "$GITHUB_OUTPUT"
162 elif echo "$CHANGED_FILES" | grep -qP '^(rust-toolchain\.toml|\.cargo/|\.github/|Cargo\.(toml|lock)$)'; then
163 echo "Toolchain, cargo config, or root Cargo files changed, will run all tests"
164 echo "changed_packages=" >> "$GITHUB_OUTPUT"
165 else
166 # Extract changed packages from file paths
167 FILE_CHANGED_PKGS=$(echo "$CHANGED_FILES" | \
168 grep -oP '^(crates|tooling)/\K[^/]+' | \
169 sort -u || true)
170
171 # If assets/ changed, add crates that depend on those assets
172 if echo "$CHANGED_FILES" | grep -qP '^assets/'; then
173 FILE_CHANGED_PKGS=$(printf '%s\n%s\n%s\n%s' "$FILE_CHANGED_PKGS" "settings" "storybook" "assets" | sort -u)
174 fi
175
176 # Combine all changed packages
177 ALL_CHANGED_PKGS=$(echo "$FILE_CHANGED_PKGS" | grep -v '^$' || true)
178
179 if [ -z "$ALL_CHANGED_PKGS" ]; then
180 echo "No package changes detected, will run all tests"
181 echo "changed_packages=" >> "$GITHUB_OUTPUT"
182 else
183 # Build nextest filterset with rdeps for each package
184 FILTERSET=$(echo "$ALL_CHANGED_PKGS" | \
185 sed 's/.*/rdeps(&)/' | \
186 tr '\n' '|' | \
187 sed 's/|$//')
188 echo "Changed packages filterset: $FILTERSET"
189 echo "changed_packages=$FILTERSET" >> "$GITHUB_OUTPUT"
190 fi
191 fi
192
193 "#});
194
195 outputs.insert(
196 "changed_packages".to_owned(),
197 format!("${{{{ steps.{}.outputs.changed_packages }}}}", step_name),
198 );
199 }
200
201 for rule in rules {
202 assert!(
203 rule.set_by_step
204 .borrow_mut()
205 .replace(name.clone())
206 .is_none()
207 );
208 assert!(
209 outputs
210 .insert(
211 rule.name.to_owned(),
212 format!("${{{{ steps.{}.outputs.{} }}}}", step_name, rule.name)
213 )
214 .is_none()
215 );
216
217 let grep_arg = if rule.invert { "-qvP" } else { "-qP" };
218 script.push_str(&format!(
219 "check_pattern \"{}\" '{}' {}\n",
220 rule.name, rule.pattern, grep_arg
221 ));
222 }
223
224 let job = Job::default()
225 .runs_on(runners::LINUX_SMALL)
226 .with_repository_owner_guard()
227 .outputs(outputs)
228 .add_step(steps::checkout_repo().add_with((
229 "fetch-depth",
230 "${{ github.ref == 'refs/heads/main' && 2 || 350 }}",
231 )))
232 .add_step(Step::new(step_name.clone()).run(script).id(step_name));
233
234 NamedJob { name, job }
235}
236
237pub fn tests_pass(jobs: &[NamedJob]) -> NamedJob {
238 let mut script = String::from(indoc::indoc! {r#"
239 set +x
240 EXIT_CODE=0
241
242 check_result() {
243 echo "* $1: $2"
244 if [[ "$2" != "skipped" && "$2" != "success" ]]; then EXIT_CODE=1; fi
245 }
246
247 "#});
248
249 script.push_str(
250 &jobs
251 .iter()
252 .map(|job| {
253 format!(
254 "check_result \"{}\" \"${{{{ needs.{}.result }}}}\"",
255 job.name, job.name
256 )
257 })
258 .collect::<Vec<_>>()
259 .join("\n"),
260 );
261
262 script.push_str("\n\nexit $EXIT_CODE\n");
263
264 let job = Job::default()
265 .runs_on(runners::LINUX_SMALL)
266 .needs(
267 jobs.iter()
268 .map(|j| j.name.to_string())
269 .collect::<Vec<String>>(),
270 )
271 .cond(repository_owner_guard_expression(true))
272 .add_step(named::bash(&script));
273
274 named::job(job)
275}
276
277fn check_style() -> NamedJob {
278 fn check_for_typos() -> Step<Use> {
279 named::uses(
280 "crate-ci",
281 "typos",
282 "2d0ce569feab1f8752f1dde43cc2f2aa53236e06",
283 ) // v1.40.0
284 .with(("config", "./typos.toml"))
285 }
286 named::job(
287 release_job(&[])
288 .runs_on(runners::LINUX_MEDIUM)
289 .add_step(steps::checkout_repo())
290 .add_step(steps::cache_rust_dependencies_namespace())
291 .add_step(steps::setup_pnpm())
292 .add_step(steps::prettier())
293 .add_step(steps::cargo_fmt())
294 .add_step(steps::script("./script/check-todos"))
295 .add_step(steps::script("./script/check-keymaps"))
296 .add_step(check_for_typos()),
297 )
298}
299
300fn check_dependencies() -> NamedJob {
301 fn install_cargo_machete() -> Step<Use> {
302 named::uses(
303 "clechasseur",
304 "rs-cargo",
305 "8435b10f6e71c2e3d4d3b7573003a8ce4bfc6386", // v2
306 )
307 .add_with(("command", "install"))
308 .add_with(("args", "cargo-machete@0.7.0"))
309 }
310
311 fn run_cargo_machete() -> Step<Use> {
312 named::uses(
313 "clechasseur",
314 "rs-cargo",
315 "8435b10f6e71c2e3d4d3b7573003a8ce4bfc6386", // v2
316 )
317 .add_with(("command", "machete"))
318 }
319
320 fn check_cargo_lock() -> Step<Run> {
321 named::bash("cargo update --locked --workspace")
322 }
323
324 fn check_vulnerable_dependencies() -> Step<Use> {
325 named::uses(
326 "actions",
327 "dependency-review-action",
328 "67d4f4bd7a9b17a0db54d2a7519187c65e339de8", // v4
329 )
330 .if_condition(Expression::new("github.event_name == 'pull_request'"))
331 .with(("license-check", false))
332 }
333
334 named::job(
335 release_job(&[])
336 .runs_on(runners::LINUX_SMALL)
337 .add_step(steps::checkout_repo())
338 .add_step(steps::cache_rust_dependencies_namespace())
339 .add_step(install_cargo_machete())
340 .add_step(run_cargo_machete())
341 .add_step(check_cargo_lock())
342 .add_step(check_vulnerable_dependencies()),
343 )
344}
345
346fn check_workspace_binaries() -> NamedJob {
347 named::job(
348 release_job(&[])
349 .runs_on(runners::LINUX_LARGE)
350 .add_step(steps::checkout_repo())
351 .add_step(steps::setup_cargo_config(Platform::Linux))
352 .add_step(steps::cache_rust_dependencies_namespace())
353 .map(steps::install_linux_dependencies)
354 .add_step(steps::script("cargo build -p collab"))
355 .add_step(steps::script("cargo build --workspace --bins --examples"))
356 .add_step(steps::cleanup_cargo_config(Platform::Linux)),
357 )
358}
359
360pub(crate) fn clippy(platform: Platform) -> NamedJob {
361 let runner = match platform {
362 Platform::Windows => runners::WINDOWS_DEFAULT,
363 Platform::Linux => runners::LINUX_DEFAULT,
364 Platform::Mac => runners::MAC_DEFAULT,
365 };
366 NamedJob {
367 name: format!("clippy_{platform}"),
368 job: release_job(&[])
369 .runs_on(runner)
370 .add_step(steps::checkout_repo())
371 .add_step(steps::setup_cargo_config(platform))
372 .when(
373 platform == Platform::Linux || platform == Platform::Mac,
374 |this| this.add_step(steps::cache_rust_dependencies_namespace()),
375 )
376 .when(
377 platform == Platform::Linux,
378 steps::install_linux_dependencies,
379 )
380 .add_step(steps::clippy(platform)),
381 }
382}
383
384pub(crate) fn run_platform_tests(platform: Platform) -> NamedJob {
385 run_platform_tests_impl(platform, true)
386}
387
388pub(crate) fn run_platform_tests_no_filter(platform: Platform) -> NamedJob {
389 run_platform_tests_impl(platform, false)
390}
391
392fn run_platform_tests_impl(platform: Platform, filter_packages: bool) -> NamedJob {
393 let runner = match platform {
394 Platform::Windows => runners::WINDOWS_DEFAULT,
395 Platform::Linux => runners::LINUX_DEFAULT,
396 Platform::Mac => runners::MAC_DEFAULT,
397 };
398 NamedJob {
399 name: format!("run_tests_{platform}"),
400 job: release_job(&[])
401 .runs_on(runner)
402 .when(platform == Platform::Linux, |job| {
403 job.add_service(
404 "postgres",
405 Container::new("postgres:15")
406 .add_env(("POSTGRES_HOST_AUTH_METHOD", "trust"))
407 .ports(vec![Port::Name("5432:5432".into())])
408 .options(
409 "--health-cmd pg_isready \
410 --health-interval 500ms \
411 --health-timeout 5s \
412 --health-retries 10",
413 ),
414 )
415 })
416 .add_step(steps::checkout_repo())
417 .add_step(steps::setup_cargo_config(platform))
418 .when(
419 platform == Platform::Linux || platform == Platform::Mac,
420 |this| this.add_step(steps::cache_rust_dependencies_namespace()),
421 )
422 .when(
423 platform == Platform::Linux,
424 steps::install_linux_dependencies,
425 )
426 .add_step(steps::setup_node())
427 .when(
428 platform == Platform::Linux || platform == Platform::Mac,
429 |job| job.add_step(steps::cargo_install_nextest()),
430 )
431 .add_step(steps::clear_target_dir_if_large(platform))
432 .when(filter_packages, |job| {
433 job.add_step(
434 steps::cargo_nextest(platform).with_changed_packages_filter("orchestrate"),
435 )
436 })
437 .when(!filter_packages, |job| {
438 job.add_step(steps::cargo_nextest(platform))
439 })
440 .add_step(steps::cleanup_cargo_config(platform)),
441 }
442}
443
444pub(crate) fn check_postgres_and_protobuf_migrations() -> NamedJob {
445 fn remove_untracked_files() -> Step<Run> {
446 named::bash("git clean -df")
447 }
448
449 fn ensure_fresh_merge() -> Step<Run> {
450 named::bash(indoc::indoc! {r#"
451 if [ -z "$GITHUB_BASE_REF" ];
452 then
453 echo "BUF_BASE_BRANCH=$(git merge-base origin/main HEAD)" >> "$GITHUB_ENV"
454 else
455 git checkout -B temp
456 git merge -q "origin/$GITHUB_BASE_REF" -m "merge main into temp"
457 echo "BUF_BASE_BRANCH=$GITHUB_BASE_REF" >> "$GITHUB_ENV"
458 fi
459 "#})
460 }
461
462 fn bufbuild_setup_action() -> Step<Use> {
463 named::uses("bufbuild", "buf-setup-action", "v1")
464 .add_with(("version", "v1.29.0"))
465 .add_with(("github_token", vars::GITHUB_TOKEN))
466 }
467
468 fn bufbuild_breaking_action() -> Step<Use> {
469 named::uses("bufbuild", "buf-breaking-action", "v1").add_with(("input", "crates/proto/proto/"))
470 .add_with(("against", "https://github.com/${GITHUB_REPOSITORY}.git#branch=${BUF_BASE_BRANCH},subdir=crates/proto/proto/"))
471 }
472
473 named::job(
474 release_job(&[])
475 .runs_on(runners::LINUX_DEFAULT)
476 .add_env(("GIT_AUTHOR_NAME", "Protobuf Action"))
477 .add_env(("GIT_AUTHOR_EMAIL", "ci@zed.dev"))
478 .add_env(("GIT_COMMITTER_NAME", "Protobuf Action"))
479 .add_env(("GIT_COMMITTER_EMAIL", "ci@zed.dev"))
480 .add_step(steps::checkout_repo().with(("fetch-depth", 0))) // fetch full history
481 .add_step(remove_untracked_files())
482 .add_step(ensure_fresh_merge())
483 .add_step(bufbuild_setup_action())
484 .add_step(bufbuild_breaking_action()),
485 )
486}
487
488fn doctests() -> NamedJob {
489 fn run_doctests() -> Step<Run> {
490 named::bash(indoc::indoc! {r#"
491 cargo test --workspace --doc --no-fail-fast
492 "#})
493 .id("run_doctests")
494 }
495
496 named::job(
497 release_job(&[])
498 .runs_on(runners::LINUX_DEFAULT)
499 .add_step(steps::checkout_repo())
500 .add_step(steps::cache_rust_dependencies_namespace())
501 .map(steps::install_linux_dependencies)
502 .add_step(steps::setup_cargo_config(Platform::Linux))
503 .add_step(run_doctests())
504 .add_step(steps::cleanup_cargo_config(Platform::Linux)),
505 )
506}
507
508fn check_licenses() -> NamedJob {
509 named::job(
510 Job::default()
511 .runs_on(runners::LINUX_SMALL)
512 .add_step(steps::checkout_repo())
513 .add_step(steps::cache_rust_dependencies_namespace())
514 .add_step(steps::script("./script/check-licenses"))
515 .add_step(steps::script("./script/generate-licenses")),
516 )
517}
518
519fn check_docs() -> NamedJob {
520 fn lychee_link_check(dir: &str) -> Step<Use> {
521 named::uses(
522 "lycheeverse",
523 "lychee-action",
524 "82202e5e9c2f4ef1a55a3d02563e1cb6041e5332",
525 ) // v2.4.1
526 .add_with(("args", format!("--no-progress --exclude '^http' '{dir}'")))
527 .add_with(("fail", true))
528 .add_with(("jobSummary", false))
529 }
530
531 fn install_mdbook() -> Step<Use> {
532 named::uses(
533 "peaceiris",
534 "actions-mdbook",
535 "ee69d230fe19748b7abf22df32acaa93833fad08", // v2
536 )
537 .with(("mdbook-version", "0.4.37"))
538 }
539
540 fn build_docs() -> Step<Run> {
541 named::bash(indoc::indoc! {r#"
542 mkdir -p target/deploy
543 mdbook build ./docs --dest-dir=../target/deploy/docs/
544 "#})
545 }
546
547 named::job(
548 release_job(&[])
549 .runs_on(runners::LINUX_LARGE)
550 .add_step(steps::checkout_repo())
551 .add_step(steps::setup_cargo_config(Platform::Linux))
552 // todo(ci): un-inline build_docs/action.yml here
553 .add_step(steps::cache_rust_dependencies_namespace())
554 .add_step(
555 lychee_link_check("./docs/src/**/*"), // check markdown links
556 )
557 .map(steps::install_linux_dependencies)
558 .add_step(steps::script("./script/generate-action-metadata"))
559 .add_step(install_mdbook())
560 .add_step(build_docs())
561 .add_step(
562 lychee_link_check("target/deploy/docs"), // check links in generated html
563 ),
564 )
565}
566
567pub(crate) fn check_scripts() -> NamedJob {
568 fn download_actionlint() -> Step<Run> {
569 named::bash(
570 "bash <(curl https://raw.githubusercontent.com/rhysd/actionlint/main/scripts/download-actionlint.bash)",
571 )
572 }
573
574 fn run_actionlint() -> Step<Run> {
575 named::bash(indoc::indoc! {r#"
576 ${{ steps.get_actionlint.outputs.executable }} -color
577 "#})
578 }
579
580 fn run_shellcheck() -> Step<Run> {
581 named::bash("./script/shellcheck-scripts error")
582 }
583
584 fn check_xtask_workflows() -> Step<Run> {
585 named::bash(indoc::indoc! {r#"
586 cargo xtask workflows
587 if ! git diff --exit-code .github; then
588 echo "Error: .github directory has uncommitted changes after running 'cargo xtask workflows'"
589 echo "Please run 'cargo xtask workflows' locally and commit the changes"
590 exit 1
591 fi
592 "#})
593 }
594
595 named::job(
596 release_job(&[])
597 .runs_on(runners::LINUX_SMALL)
598 .add_step(steps::checkout_repo())
599 .add_step(run_shellcheck())
600 .add_step(download_actionlint().id("get_actionlint"))
601 .add_step(run_actionlint())
602 .add_step(check_xtask_workflows()),
603 )
604}