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