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