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    let name = "orchestrate".to_owned();
119    let step_name = "filter".to_owned();
120    let mut script = String::new();
121
122    script.push_str(indoc::indoc! {r#"
123        if [ -z "$GITHUB_BASE_REF" ]; then
124          echo "Not in a PR context (i.e., push to main/stable/preview)"
125          COMPARE_REV="$(git rev-parse HEAD~1)"
126        else
127          echo "In a PR context comparing to pull_request.base.ref"
128          git fetch origin "$GITHUB_BASE_REF" --depth=350
129          COMPARE_REV="$(git merge-base "origin/${GITHUB_BASE_REF}" HEAD)"
130        fi
131        CHANGED_FILES="$(git diff --name-only "$COMPARE_REV" ${{ github.sha }})"
132
133        check_pattern() {
134          local output_name="$1"
135          local pattern="$2"
136          local grep_arg="$3"
137
138          echo "$CHANGED_FILES" | grep "$grep_arg" "$pattern" && \
139            echo "${output_name}=true" >> "$GITHUB_OUTPUT" || \
140            echo "${output_name}=false" >> "$GITHUB_OUTPUT"
141        }
142
143    "#});
144
145    let mut outputs = IndexMap::new();
146
147    for rule in rules {
148        assert!(
149            rule.set_by_step
150                .borrow_mut()
151                .replace(name.clone())
152                .is_none()
153        );
154        assert!(
155            outputs
156                .insert(
157                    rule.name.to_owned(),
158                    format!("${{{{ steps.{}.outputs.{} }}}}", step_name, rule.name)
159                )
160                .is_none()
161        );
162
163        let grep_arg = if rule.invert { "-qvP" } else { "-qP" };
164        script.push_str(&format!(
165            "check_pattern \"{}\" '{}' {}\n",
166            rule.name, rule.pattern, grep_arg
167        ));
168    }
169
170    let job = Job::default()
171        .runs_on(runners::LINUX_SMALL)
172        .with_repository_owner_guard()
173        .outputs(outputs)
174        .add_step(steps::checkout_repo().add_with((
175            "fetch-depth",
176            "${{ github.ref == 'refs/heads/main' && 2 || 350 }}",
177        )))
178        .add_step(Step::new(step_name.clone()).run(script).id(step_name));
179
180    NamedJob { name, job }
181}
182
183pub fn tests_pass(jobs: &[NamedJob]) -> NamedJob {
184    let mut script = String::from(indoc::indoc! {r#"
185        set +x
186        EXIT_CODE=0
187
188        check_result() {
189          echo "* $1: $2"
190          if [[ "$2" != "skipped" && "$2" != "success" ]]; then EXIT_CODE=1; fi
191        }
192
193    "#});
194
195    script.push_str(
196        &jobs
197            .iter()
198            .map(|job| {
199                format!(
200                    "check_result \"{}\" \"${{{{ needs.{}.result }}}}\"",
201                    job.name, job.name
202                )
203            })
204            .collect::<Vec<_>>()
205            .join("\n"),
206    );
207
208    script.push_str("\n\nexit $EXIT_CODE\n");
209
210    let job = Job::default()
211        .runs_on(runners::LINUX_SMALL)
212        .needs(
213            jobs.iter()
214                .map(|j| j.name.to_string())
215                .collect::<Vec<String>>(),
216        )
217        .cond(repository_owner_guard_expression(true))
218        .add_step(named::bash(&script));
219
220    named::job(job)
221}
222
223fn check_style() -> NamedJob {
224    fn check_for_typos() -> Step<Use> {
225        named::uses(
226            "crate-ci",
227            "typos",
228            "2d0ce569feab1f8752f1dde43cc2f2aa53236e06",
229        ) // v1.40.0
230        .with(("config", "./typos.toml"))
231    }
232    named::job(
233        release_job(&[])
234            .runs_on(runners::LINUX_MEDIUM)
235            .add_step(steps::checkout_repo())
236            .add_step(steps::cache_rust_dependencies_namespace())
237            .add_step(steps::setup_pnpm())
238            .add_step(steps::prettier())
239            .add_step(steps::cargo_fmt())
240            .add_step(steps::script("./script/check-todos"))
241            .add_step(steps::script("./script/check-keymaps"))
242            .add_step(check_for_typos()),
243    )
244}
245
246fn check_dependencies() -> NamedJob {
247    fn install_cargo_machete() -> Step<Use> {
248        named::uses(
249            "clechasseur",
250            "rs-cargo",
251            "8435b10f6e71c2e3d4d3b7573003a8ce4bfc6386", // v2
252        )
253        .add_with(("command", "install"))
254        .add_with(("args", "cargo-machete@0.7.0"))
255    }
256
257    fn run_cargo_machete() -> Step<Use> {
258        named::uses(
259            "clechasseur",
260            "rs-cargo",
261            "8435b10f6e71c2e3d4d3b7573003a8ce4bfc6386", // v2
262        )
263        .add_with(("command", "machete"))
264    }
265
266    fn check_cargo_lock() -> Step<Run> {
267        named::bash("cargo update --locked --workspace")
268    }
269
270    fn check_vulnerable_dependencies() -> Step<Use> {
271        named::uses(
272            "actions",
273            "dependency-review-action",
274            "67d4f4bd7a9b17a0db54d2a7519187c65e339de8", // v4
275        )
276        .if_condition(Expression::new("github.event_name == 'pull_request'"))
277        .with(("license-check", false))
278    }
279
280    named::job(
281        release_job(&[])
282            .runs_on(runners::LINUX_SMALL)
283            .add_step(steps::checkout_repo())
284            .add_step(steps::cache_rust_dependencies_namespace())
285            .add_step(install_cargo_machete())
286            .add_step(run_cargo_machete())
287            .add_step(check_cargo_lock())
288            .add_step(check_vulnerable_dependencies()),
289    )
290}
291
292fn check_workspace_binaries() -> NamedJob {
293    named::job(
294        release_job(&[])
295            .runs_on(runners::LINUX_LARGE)
296            .add_step(steps::checkout_repo())
297            .add_step(steps::setup_cargo_config(Platform::Linux))
298            .add_step(steps::cache_rust_dependencies_namespace())
299            .map(steps::install_linux_dependencies)
300            .add_step(steps::script("cargo build -p collab"))
301            .add_step(steps::script("cargo build --workspace --bins --examples"))
302            .add_step(steps::cleanup_cargo_config(Platform::Linux)),
303    )
304}
305
306pub(crate) fn clippy(platform: Platform) -> NamedJob {
307    let runner = match platform {
308        Platform::Windows => runners::WINDOWS_DEFAULT,
309        Platform::Linux => runners::LINUX_DEFAULT,
310        Platform::Mac => runners::MAC_DEFAULT,
311    };
312    NamedJob {
313        name: format!("clippy_{platform}"),
314        job: release_job(&[])
315            .runs_on(runner)
316            .add_step(steps::checkout_repo())
317            .add_step(steps::setup_cargo_config(platform))
318            .when(
319                platform == Platform::Linux || platform == Platform::Mac,
320                |this| this.add_step(steps::cache_rust_dependencies_namespace()),
321            )
322            .when(
323                platform == Platform::Linux,
324                steps::install_linux_dependencies,
325            )
326            .add_step(steps::clippy(platform)),
327    }
328}
329
330pub(crate) fn run_platform_tests(platform: Platform) -> NamedJob {
331    let runner = match platform {
332        Platform::Windows => runners::WINDOWS_DEFAULT,
333        Platform::Linux => runners::LINUX_DEFAULT,
334        Platform::Mac => runners::MAC_DEFAULT,
335    };
336    NamedJob {
337        name: format!("run_tests_{platform}"),
338        job: release_job(&[])
339            .runs_on(runner)
340            .when(platform == Platform::Linux, |job| {
341                job.add_service(
342                    "postgres",
343                    Container::new("postgres:15")
344                        .add_env(("POSTGRES_HOST_AUTH_METHOD", "trust"))
345                        .ports(vec![Port::Name("5432:5432".into())])
346                        .options(
347                            "--health-cmd pg_isready \
348                             --health-interval 500ms \
349                             --health-timeout 5s \
350                             --health-retries 10",
351                        ),
352                )
353            })
354            .add_step(steps::checkout_repo())
355            .add_step(steps::setup_cargo_config(platform))
356            .when(
357                platform == Platform::Linux || platform == Platform::Mac,
358                |this| this.add_step(steps::cache_rust_dependencies_namespace()),
359            )
360            .when(
361                platform == Platform::Linux,
362                steps::install_linux_dependencies,
363            )
364            .add_step(steps::setup_node())
365            .when(
366                platform == Platform::Linux || platform == Platform::Mac,
367                |job| job.add_step(steps::cargo_install_nextest()),
368            )
369            .add_step(steps::clear_target_dir_if_large(platform))
370            .add_step(steps::cargo_nextest(platform))
371            .add_step(steps::cleanup_cargo_config(platform)),
372    }
373}
374
375pub(crate) fn check_postgres_and_protobuf_migrations() -> NamedJob {
376    fn remove_untracked_files() -> Step<Run> {
377        named::bash("git clean -df")
378    }
379
380    fn ensure_fresh_merge() -> Step<Run> {
381        named::bash(indoc::indoc! {r#"
382            if [ -z "$GITHUB_BASE_REF" ];
383            then
384              echo "BUF_BASE_BRANCH=$(git merge-base origin/main HEAD)" >> "$GITHUB_ENV"
385            else
386              git checkout -B temp
387              git merge -q "origin/$GITHUB_BASE_REF" -m "merge main into temp"
388              echo "BUF_BASE_BRANCH=$GITHUB_BASE_REF" >> "$GITHUB_ENV"
389            fi
390        "#})
391    }
392
393    fn bufbuild_setup_action() -> Step<Use> {
394        named::uses("bufbuild", "buf-setup-action", "v1")
395            .add_with(("version", "v1.29.0"))
396            .add_with(("github_token", vars::GITHUB_TOKEN))
397    }
398
399    fn bufbuild_breaking_action() -> Step<Use> {
400        named::uses("bufbuild", "buf-breaking-action", "v1").add_with(("input", "crates/proto/proto/"))
401            .add_with(("against", "https://github.com/${GITHUB_REPOSITORY}.git#branch=${BUF_BASE_BRANCH},subdir=crates/proto/proto/"))
402    }
403
404    named::job(
405        release_job(&[])
406            .runs_on(runners::LINUX_DEFAULT)
407            .add_env(("GIT_AUTHOR_NAME", "Protobuf Action"))
408            .add_env(("GIT_AUTHOR_EMAIL", "ci@zed.dev"))
409            .add_env(("GIT_COMMITTER_NAME", "Protobuf Action"))
410            .add_env(("GIT_COMMITTER_EMAIL", "ci@zed.dev"))
411            .add_step(steps::checkout_repo().with(("fetch-depth", 0))) // fetch full history
412            .add_step(remove_untracked_files())
413            .add_step(ensure_fresh_merge())
414            .add_step(bufbuild_setup_action())
415            .add_step(bufbuild_breaking_action()),
416    )
417}
418
419fn doctests() -> NamedJob {
420    fn run_doctests() -> Step<Run> {
421        named::bash(indoc::indoc! {r#"
422            cargo test --workspace --doc --no-fail-fast
423        "#})
424        .id("run_doctests")
425    }
426
427    named::job(
428        release_job(&[])
429            .runs_on(runners::LINUX_DEFAULT)
430            .add_step(steps::checkout_repo())
431            .add_step(steps::cache_rust_dependencies_namespace())
432            .map(steps::install_linux_dependencies)
433            .add_step(steps::setup_cargo_config(Platform::Linux))
434            .add_step(run_doctests())
435            .add_step(steps::cleanup_cargo_config(Platform::Linux)),
436    )
437}
438
439fn check_licenses() -> NamedJob {
440    named::job(
441        Job::default()
442            .runs_on(runners::LINUX_SMALL)
443            .add_step(steps::checkout_repo())
444            .add_step(steps::cache_rust_dependencies_namespace())
445            .add_step(steps::script("./script/check-licenses"))
446            .add_step(steps::script("./script/generate-licenses")),
447    )
448}
449
450fn check_docs() -> NamedJob {
451    fn lychee_link_check(dir: &str) -> Step<Use> {
452        named::uses(
453            "lycheeverse",
454            "lychee-action",
455            "82202e5e9c2f4ef1a55a3d02563e1cb6041e5332",
456        ) // v2.4.1
457        .add_with(("args", format!("--no-progress --exclude '^http' '{dir}'")))
458        .add_with(("fail", true))
459        .add_with(("jobSummary", false))
460    }
461
462    fn install_mdbook() -> Step<Use> {
463        named::uses(
464            "peaceiris",
465            "actions-mdbook",
466            "ee69d230fe19748b7abf22df32acaa93833fad08", // v2
467        )
468        .with(("mdbook-version", "0.4.37"))
469    }
470
471    fn build_docs() -> Step<Run> {
472        named::bash(indoc::indoc! {r#"
473            mkdir -p target/deploy
474            mdbook build ./docs --dest-dir=../target/deploy/docs/
475        "#})
476    }
477
478    named::job(
479        release_job(&[])
480            .runs_on(runners::LINUX_LARGE)
481            .add_step(steps::checkout_repo())
482            .add_step(steps::setup_cargo_config(Platform::Linux))
483            // todo(ci): un-inline build_docs/action.yml here
484            .add_step(steps::cache_rust_dependencies_namespace())
485            .add_step(
486                lychee_link_check("./docs/src/**/*"), // check markdown links
487            )
488            .map(steps::install_linux_dependencies)
489            .add_step(steps::script("./script/generate-action-metadata"))
490            .add_step(install_mdbook())
491            .add_step(build_docs())
492            .add_step(
493                lychee_link_check("target/deploy/docs"), // check links in generated html
494            ),
495    )
496}
497
498pub(crate) fn check_scripts() -> NamedJob {
499    fn download_actionlint() -> Step<Run> {
500        named::bash(
501            "bash <(curl https://raw.githubusercontent.com/rhysd/actionlint/main/scripts/download-actionlint.bash)",
502        )
503    }
504
505    fn run_actionlint() -> Step<Run> {
506        named::bash(indoc::indoc! {r#"
507            ${{ steps.get_actionlint.outputs.executable }} -color
508        "#})
509    }
510
511    fn run_shellcheck() -> Step<Run> {
512        named::bash("./script/shellcheck-scripts error")
513    }
514
515    fn check_xtask_workflows() -> Step<Run> {
516        named::bash(indoc::indoc! {r#"
517            cargo xtask workflows
518            if ! git diff --exit-code .github; then
519              echo "Error: .github directory has uncommitted changes after running 'cargo xtask workflows'"
520              echo "Please run 'cargo xtask workflows' locally and commit the changes"
521              exit 1
522            fi
523        "#})
524    }
525
526    named::job(
527        release_job(&[])
528            .runs_on(runners::LINUX_SMALL)
529            .add_step(steps::checkout_repo())
530            .add_step(run_shellcheck())
531            .add_step(download_actionlint().id("get_actionlint"))
532            .add_step(run_actionlint())
533            .add_step(check_xtask_workflows()),
534    )
535}