run_tests.rs

  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/)'; then
163          echo "Toolchain, .github or cargo config 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          # Parse Cargo.lock diff for added/changed crates
177          LOCK_CHANGED_PKGS=""
178          if echo "$CHANGED_FILES" | grep -qP '^Cargo\.lock$'; then
179            echo "Cargo.lock changed, analyzing diff..."
180            LOCK_CHANGED_PKGS=$(git diff "$COMPARE_REV" "${{ github.sha }}" -- Cargo.lock | \
181              grep -oP '^[+-]name = "\K[^"]+' | \
182              sort -u || true)
183          fi
184
185          # Combine all changed packages
186          ALL_CHANGED_PKGS=$(printf '%s\n%s' "$FILE_CHANGED_PKGS" "$LOCK_CHANGED_PKGS" | sort -u | grep -v '^$' || true)
187
188          if [ -z "$ALL_CHANGED_PKGS" ]; then
189            echo "No package changes detected, will run all tests"
190            echo "changed_packages=" >> "$GITHUB_OUTPUT"
191          else
192            # Build nextest filterset with rdeps for each package
193            FILTERSET=$(echo "$ALL_CHANGED_PKGS" | \
194              sed 's/.*/rdeps(&)/' | \
195              tr '\n' '|' | \
196              sed 's/|$//')
197            echo "Changed packages filterset: $FILTERSET"
198            echo "changed_packages=$FILTERSET" >> "$GITHUB_OUTPUT"
199          fi
200        fi
201
202    "#});
203
204        outputs.insert(
205            "changed_packages".to_owned(),
206            format!("${{{{ steps.{}.outputs.changed_packages }}}}", step_name),
207        );
208    }
209
210    for rule in rules {
211        assert!(
212            rule.set_by_step
213                .borrow_mut()
214                .replace(name.clone())
215                .is_none()
216        );
217        assert!(
218            outputs
219                .insert(
220                    rule.name.to_owned(),
221                    format!("${{{{ steps.{}.outputs.{} }}}}", step_name, rule.name)
222                )
223                .is_none()
224        );
225
226        let grep_arg = if rule.invert { "-qvP" } else { "-qP" };
227        script.push_str(&format!(
228            "check_pattern \"{}\" '{}' {}\n",
229            rule.name, rule.pattern, grep_arg
230        ));
231    }
232
233    let job = Job::default()
234        .runs_on(runners::LINUX_SMALL)
235        .with_repository_owner_guard()
236        .outputs(outputs)
237        .add_step(steps::checkout_repo().add_with((
238            "fetch-depth",
239            "${{ github.ref == 'refs/heads/main' && 2 || 350 }}",
240        )))
241        .add_step(Step::new(step_name.clone()).run(script).id(step_name));
242
243    NamedJob { name, job }
244}
245
246pub fn tests_pass(jobs: &[NamedJob]) -> NamedJob {
247    let mut script = String::from(indoc::indoc! {r#"
248        set +x
249        EXIT_CODE=0
250
251        check_result() {
252          echo "* $1: $2"
253          if [[ "$2" != "skipped" && "$2" != "success" ]]; then EXIT_CODE=1; fi
254        }
255
256    "#});
257
258    script.push_str(
259        &jobs
260            .iter()
261            .map(|job| {
262                format!(
263                    "check_result \"{}\" \"${{{{ needs.{}.result }}}}\"",
264                    job.name, job.name
265                )
266            })
267            .collect::<Vec<_>>()
268            .join("\n"),
269    );
270
271    script.push_str("\n\nexit $EXIT_CODE\n");
272
273    let job = Job::default()
274        .runs_on(runners::LINUX_SMALL)
275        .needs(
276            jobs.iter()
277                .map(|j| j.name.to_string())
278                .collect::<Vec<String>>(),
279        )
280        .cond(repository_owner_guard_expression(true))
281        .add_step(named::bash(&script));
282
283    named::job(job)
284}
285
286fn check_style() -> NamedJob {
287    fn check_for_typos() -> Step<Use> {
288        named::uses(
289            "crate-ci",
290            "typos",
291            "2d0ce569feab1f8752f1dde43cc2f2aa53236e06",
292        ) // v1.40.0
293        .with(("config", "./typos.toml"))
294    }
295    named::job(
296        release_job(&[])
297            .runs_on(runners::LINUX_MEDIUM)
298            .add_step(steps::checkout_repo())
299            .add_step(steps::cache_rust_dependencies_namespace())
300            .add_step(steps::setup_pnpm())
301            .add_step(steps::prettier())
302            .add_step(steps::cargo_fmt())
303            .add_step(steps::script("./script/check-todos"))
304            .add_step(steps::script("./script/check-keymaps"))
305            .add_step(check_for_typos()),
306    )
307}
308
309fn check_dependencies() -> NamedJob {
310    fn install_cargo_machete() -> Step<Use> {
311        named::uses(
312            "clechasseur",
313            "rs-cargo",
314            "8435b10f6e71c2e3d4d3b7573003a8ce4bfc6386", // v2
315        )
316        .add_with(("command", "install"))
317        .add_with(("args", "cargo-machete@0.7.0"))
318    }
319
320    fn run_cargo_machete() -> Step<Use> {
321        named::uses(
322            "clechasseur",
323            "rs-cargo",
324            "8435b10f6e71c2e3d4d3b7573003a8ce4bfc6386", // v2
325        )
326        .add_with(("command", "machete"))
327    }
328
329    fn check_cargo_lock() -> Step<Run> {
330        named::bash("cargo update --locked --workspace")
331    }
332
333    fn check_vulnerable_dependencies() -> Step<Use> {
334        named::uses(
335            "actions",
336            "dependency-review-action",
337            "67d4f4bd7a9b17a0db54d2a7519187c65e339de8", // v4
338        )
339        .if_condition(Expression::new("github.event_name == 'pull_request'"))
340        .with(("license-check", false))
341    }
342
343    named::job(
344        release_job(&[])
345            .runs_on(runners::LINUX_SMALL)
346            .add_step(steps::checkout_repo())
347            .add_step(steps::cache_rust_dependencies_namespace())
348            .add_step(install_cargo_machete())
349            .add_step(run_cargo_machete())
350            .add_step(check_cargo_lock())
351            .add_step(check_vulnerable_dependencies()),
352    )
353}
354
355fn check_workspace_binaries() -> NamedJob {
356    named::job(
357        release_job(&[])
358            .runs_on(runners::LINUX_LARGE)
359            .add_step(steps::checkout_repo())
360            .add_step(steps::setup_cargo_config(Platform::Linux))
361            .add_step(steps::cache_rust_dependencies_namespace())
362            .map(steps::install_linux_dependencies)
363            .add_step(steps::script("cargo build -p collab"))
364            .add_step(steps::script("cargo build --workspace --bins --examples"))
365            .add_step(steps::cleanup_cargo_config(Platform::Linux)),
366    )
367}
368
369pub(crate) fn clippy(platform: Platform) -> NamedJob {
370    let runner = match platform {
371        Platform::Windows => runners::WINDOWS_DEFAULT,
372        Platform::Linux => runners::LINUX_DEFAULT,
373        Platform::Mac => runners::MAC_DEFAULT,
374    };
375    NamedJob {
376        name: format!("clippy_{platform}"),
377        job: release_job(&[])
378            .runs_on(runner)
379            .add_step(steps::checkout_repo())
380            .add_step(steps::setup_cargo_config(platform))
381            .when(
382                platform == Platform::Linux || platform == Platform::Mac,
383                |this| this.add_step(steps::cache_rust_dependencies_namespace()),
384            )
385            .when(
386                platform == Platform::Linux,
387                steps::install_linux_dependencies,
388            )
389            .add_step(steps::clippy(platform)),
390    }
391}
392
393pub(crate) fn run_platform_tests(platform: Platform) -> NamedJob {
394    run_platform_tests_impl(platform, true)
395}
396
397pub(crate) fn run_platform_tests_no_filter(platform: Platform) -> NamedJob {
398    run_platform_tests_impl(platform, false)
399}
400
401fn run_platform_tests_impl(platform: Platform, filter_packages: bool) -> NamedJob {
402    let runner = match platform {
403        Platform::Windows => runners::WINDOWS_DEFAULT,
404        Platform::Linux => runners::LINUX_DEFAULT,
405        Platform::Mac => runners::MAC_DEFAULT,
406    };
407    NamedJob {
408        name: format!("run_tests_{platform}"),
409        job: release_job(&[])
410            .runs_on(runner)
411            .when(platform == Platform::Linux, |job| {
412                job.add_service(
413                    "postgres",
414                    Container::new("postgres:15")
415                        .add_env(("POSTGRES_HOST_AUTH_METHOD", "trust"))
416                        .ports(vec![Port::Name("5432:5432".into())])
417                        .options(
418                            "--health-cmd pg_isready \
419                             --health-interval 500ms \
420                             --health-timeout 5s \
421                             --health-retries 10",
422                        ),
423                )
424            })
425            .add_step(steps::checkout_repo())
426            .add_step(steps::setup_cargo_config(platform))
427            .when(
428                platform == Platform::Linux || platform == Platform::Mac,
429                |this| this.add_step(steps::cache_rust_dependencies_namespace()),
430            )
431            .when(
432                platform == Platform::Linux,
433                steps::install_linux_dependencies,
434            )
435            .add_step(steps::setup_node())
436            .when(
437                platform == Platform::Linux || platform == Platform::Mac,
438                |job| job.add_step(steps::cargo_install_nextest()),
439            )
440            .add_step(steps::clear_target_dir_if_large(platform))
441            .when(filter_packages, |job| {
442                job.add_step(
443                    steps::cargo_nextest(platform).with_changed_packages_filter("orchestrate"),
444                )
445            })
446            .when(!filter_packages, |job| {
447                job.add_step(steps::cargo_nextest(platform))
448            })
449            .add_step(steps::cleanup_cargo_config(platform)),
450    }
451}
452
453pub(crate) fn check_postgres_and_protobuf_migrations() -> NamedJob {
454    fn remove_untracked_files() -> Step<Run> {
455        named::bash("git clean -df")
456    }
457
458    fn ensure_fresh_merge() -> Step<Run> {
459        named::bash(indoc::indoc! {r#"
460            if [ -z "$GITHUB_BASE_REF" ];
461            then
462              echo "BUF_BASE_BRANCH=$(git merge-base origin/main HEAD)" >> "$GITHUB_ENV"
463            else
464              git checkout -B temp
465              git merge -q "origin/$GITHUB_BASE_REF" -m "merge main into temp"
466              echo "BUF_BASE_BRANCH=$GITHUB_BASE_REF" >> "$GITHUB_ENV"
467            fi
468        "#})
469    }
470
471    fn bufbuild_setup_action() -> Step<Use> {
472        named::uses("bufbuild", "buf-setup-action", "v1")
473            .add_with(("version", "v1.29.0"))
474            .add_with(("github_token", vars::GITHUB_TOKEN))
475    }
476
477    fn bufbuild_breaking_action() -> Step<Use> {
478        named::uses("bufbuild", "buf-breaking-action", "v1").add_with(("input", "crates/proto/proto/"))
479            .add_with(("against", "https://github.com/${GITHUB_REPOSITORY}.git#branch=${BUF_BASE_BRANCH},subdir=crates/proto/proto/"))
480    }
481
482    named::job(
483        release_job(&[])
484            .runs_on(runners::LINUX_DEFAULT)
485            .add_env(("GIT_AUTHOR_NAME", "Protobuf Action"))
486            .add_env(("GIT_AUTHOR_EMAIL", "ci@zed.dev"))
487            .add_env(("GIT_COMMITTER_NAME", "Protobuf Action"))
488            .add_env(("GIT_COMMITTER_EMAIL", "ci@zed.dev"))
489            .add_step(steps::checkout_repo().with(("fetch-depth", 0))) // fetch full history
490            .add_step(remove_untracked_files())
491            .add_step(ensure_fresh_merge())
492            .add_step(bufbuild_setup_action())
493            .add_step(bufbuild_breaking_action()),
494    )
495}
496
497fn doctests() -> NamedJob {
498    fn run_doctests() -> Step<Run> {
499        named::bash(indoc::indoc! {r#"
500            cargo test --workspace --doc --no-fail-fast
501        "#})
502        .id("run_doctests")
503    }
504
505    named::job(
506        release_job(&[])
507            .runs_on(runners::LINUX_DEFAULT)
508            .add_step(steps::checkout_repo())
509            .add_step(steps::cache_rust_dependencies_namespace())
510            .map(steps::install_linux_dependencies)
511            .add_step(steps::setup_cargo_config(Platform::Linux))
512            .add_step(run_doctests())
513            .add_step(steps::cleanup_cargo_config(Platform::Linux)),
514    )
515}
516
517fn check_licenses() -> NamedJob {
518    named::job(
519        Job::default()
520            .runs_on(runners::LINUX_SMALL)
521            .add_step(steps::checkout_repo())
522            .add_step(steps::cache_rust_dependencies_namespace())
523            .add_step(steps::script("./script/check-licenses"))
524            .add_step(steps::script("./script/generate-licenses")),
525    )
526}
527
528fn check_docs() -> NamedJob {
529    fn lychee_link_check(dir: &str) -> Step<Use> {
530        named::uses(
531            "lycheeverse",
532            "lychee-action",
533            "82202e5e9c2f4ef1a55a3d02563e1cb6041e5332",
534        ) // v2.4.1
535        .add_with(("args", format!("--no-progress --exclude '^http' '{dir}'")))
536        .add_with(("fail", true))
537        .add_with(("jobSummary", false))
538    }
539
540    fn install_mdbook() -> Step<Use> {
541        named::uses(
542            "peaceiris",
543            "actions-mdbook",
544            "ee69d230fe19748b7abf22df32acaa93833fad08", // v2
545        )
546        .with(("mdbook-version", "0.4.37"))
547    }
548
549    fn build_docs() -> Step<Run> {
550        named::bash(indoc::indoc! {r#"
551            mkdir -p target/deploy
552            mdbook build ./docs --dest-dir=../target/deploy/docs/
553        "#})
554    }
555
556    named::job(
557        release_job(&[])
558            .runs_on(runners::LINUX_LARGE)
559            .add_step(steps::checkout_repo())
560            .add_step(steps::setup_cargo_config(Platform::Linux))
561            // todo(ci): un-inline build_docs/action.yml here
562            .add_step(steps::cache_rust_dependencies_namespace())
563            .add_step(
564                lychee_link_check("./docs/src/**/*"), // check markdown links
565            )
566            .map(steps::install_linux_dependencies)
567            .add_step(steps::script("./script/generate-action-metadata"))
568            .add_step(install_mdbook())
569            .add_step(build_docs())
570            .add_step(
571                lychee_link_check("target/deploy/docs"), // check links in generated html
572            ),
573    )
574}
575
576pub(crate) fn check_scripts() -> NamedJob {
577    fn download_actionlint() -> Step<Run> {
578        named::bash(
579            "bash <(curl https://raw.githubusercontent.com/rhysd/actionlint/main/scripts/download-actionlint.bash)",
580        )
581    }
582
583    fn run_actionlint() -> Step<Run> {
584        named::bash(indoc::indoc! {r#"
585            ${{ steps.get_actionlint.outputs.executable }} -color
586        "#})
587    }
588
589    fn run_shellcheck() -> Step<Run> {
590        named::bash("./script/shellcheck-scripts error")
591    }
592
593    fn check_xtask_workflows() -> Step<Run> {
594        named::bash(indoc::indoc! {r#"
595            cargo xtask workflows
596            if ! git diff --exit-code .github; then
597              echo "Error: .github directory has uncommitted changes after running 'cargo xtask workflows'"
598              echo "Please run 'cargo xtask workflows' locally and commit the changes"
599              exit 1
600            fi
601        "#})
602    }
603
604    named::job(
605        release_job(&[])
606            .runs_on(runners::LINUX_SMALL)
607            .add_step(steps::checkout_repo())
608            .add_step(run_shellcheck())
609            .add_step(download_actionlint().id("get_actionlint"))
610            .add_step(run_actionlint())
611            .add_step(check_xtask_workflows()),
612    )
613}