run_tests.rs

  1use gh_workflow::{
  2    Concurrency, Event, Expression, Job, PullRequest, Push, Run, Step, Use, Workflow,
  3};
  4use indexmap::IndexMap;
  5
  6use crate::tasks::workflows::{
  7    nix_build::build_nix, runners::Arch, steps::BASH_SHELL, vars::PathCondition,
  8};
  9
 10use super::{
 11    runners::{self, Platform},
 12    steps::{self, FluentBuilder, NamedJob, named, release_job},
 13};
 14
 15pub(crate) fn run_tests() -> Workflow {
 16    // Specify anything which should potentially skip full test suite in this regex:
 17    // - docs/
 18    // - script/update_top_ranking_issues/
 19    // - .github/ISSUE_TEMPLATE/
 20    // - .github/workflows/  (except .github/workflows/ci.yml)
 21    let should_run_tests = PathCondition::inverted(
 22        "run_tests",
 23        r"^(docs/|script/update_top_ranking_issues/|\.github/(ISSUE_TEMPLATE|workflows/(?!run_tests)))",
 24    );
 25    let should_check_docs = PathCondition::new("run_docs", r"^docs/");
 26    let should_check_scripts = PathCondition::new(
 27        "run_action_checks",
 28        r"^\.github/(workflows/|actions/|actionlint.yml)|tooling/xtask|script/",
 29    );
 30    let should_check_licences =
 31        PathCondition::new("run_licenses", r"^(Cargo.lock|script/.*licenses)");
 32    let should_build_nix = PathCondition::new(
 33        "run_nix",
 34        r"^(nix/|flake\.|Cargo\.|rust-toolchain.toml|\.cargo/config.toml)",
 35    );
 36
 37    let orchestrate = orchestrate(&[
 38        &should_check_scripts,
 39        &should_check_docs,
 40        &should_check_licences,
 41        &should_build_nix,
 42        &should_run_tests,
 43    ]);
 44
 45    let mut jobs = vec![
 46        orchestrate,
 47        check_style(),
 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        should_build_nix.guard(build_nix(
 58            Platform::Linux,
 59            Arch::X86_64,
 60            "debug",
 61            // *don't* cache the built output
 62            Some("-zed-editor-[0-9.]*-nightly"),
 63            &[],
 64        )),
 65        should_build_nix.guard(build_nix(
 66            Platform::Mac,
 67            Arch::AARCH64,
 68            "debug",
 69            // *don't* cache the built output
 70            Some("-zed-editor-[0-9.]*-nightly"),
 71            &[],
 72        )),
 73    ];
 74    let tests_pass = tests_pass(&jobs);
 75
 76    jobs.push(should_run_tests.guard(check_postgres_and_protobuf_migrations())); // could be more specific here?
 77
 78    named::workflow()
 79        .add_event(
 80            Event::default()
 81                .push(
 82                    Push::default()
 83                        .add_branch("main")
 84                        .add_branch("v[0-9]+.[0-9]+.x"),
 85                )
 86                .pull_request(PullRequest::default().add_branch("**")),
 87        )
 88        .concurrency(
 89            Concurrency::default()
 90                .group(concat!(
 91                    "${{ github.workflow }}-${{ github.ref_name }}-",
 92                    "${{ github.ref_name == 'main' && github.sha || 'anysha' }}"
 93                ))
 94                .cancel_in_progress(true),
 95        )
 96        .add_env(("CARGO_TERM_COLOR", "always"))
 97        .add_env(("RUST_BACKTRACE", 1))
 98        .add_env(("CARGO_INCREMENTAL", 0))
 99        .map(|mut workflow| {
100            for job in jobs {
101                workflow = workflow.add_job(job.name, job.job)
102            }
103            workflow
104        })
105        .add_job(tests_pass.name, tests_pass.job)
106}
107
108// Generates a bash script that checks changed files against regex patterns
109// and sets GitHub output variables accordingly
110fn orchestrate(rules: &[&PathCondition]) -> NamedJob {
111    let name = "orchestrate".to_owned();
112    let step_name = "filter".to_owned();
113    let mut script = String::new();
114
115    script.push_str(indoc::indoc! {r#"
116        if [ -z "$GITHUB_BASE_REF" ]; then
117          echo "Not in a PR context (i.e., push to main/stable/preview)"
118          COMPARE_REV="$(git rev-parse HEAD~1)"
119        else
120          echo "In a PR context comparing to pull_request.base.ref"
121          git fetch origin "$GITHUB_BASE_REF" --depth=350
122          COMPARE_REV="$(git merge-base "origin/${GITHUB_BASE_REF}" HEAD)"
123        fi
124        CHANGED_FILES="$(git diff --name-only "$COMPARE_REV" ${{ github.sha }})"
125
126        check_pattern() {
127          local output_name="$1"
128          local pattern="$2"
129          local grep_arg="$3"
130
131          echo "$CHANGED_FILES" | grep "$grep_arg" "$pattern" && \
132            echo "${output_name}=true" >> "$GITHUB_OUTPUT" || \
133            echo "${output_name}=false" >> "$GITHUB_OUTPUT"
134        }
135
136    "#});
137
138    let mut outputs = IndexMap::new();
139
140    for rule in rules {
141        assert!(
142            rule.set_by_step
143                .borrow_mut()
144                .replace(name.clone())
145                .is_none()
146        );
147        assert!(
148            outputs
149                .insert(
150                    rule.name.to_owned(),
151                    format!("${{{{ steps.{}.outputs.{} }}}}", step_name, rule.name)
152                )
153                .is_none()
154        );
155
156        let grep_arg = if rule.invert { "-qvP" } else { "-qP" };
157        script.push_str(&format!(
158            "check_pattern \"{}\" '{}' {}\n",
159            rule.name, rule.pattern, grep_arg
160        ));
161    }
162
163    let job = Job::default()
164        .runs_on(runners::LINUX_SMALL)
165        .cond(Expression::new(
166            "github.repository_owner == 'zed-industries'",
167        ))
168        .outputs(outputs)
169        .add_step(steps::checkout_repo().add_with((
170            "fetch-depth",
171            "${{ github.ref == 'refs/heads/main' && 2 || 350 }}",
172        )))
173        .add_step(
174            Step::new(step_name.clone())
175                .run(script)
176                .id(step_name)
177                .shell(BASH_SHELL),
178        );
179
180    NamedJob { name, job }
181}
182
183pub(crate) 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(Expression::new(
218            "github.repository_owner == 'zed-industries' && always()",
219        ))
220        .add_step(named::bash(&script));
221
222    named::job(job)
223}
224
225fn check_style() -> NamedJob {
226    fn check_for_typos() -> Step<Use> {
227        named::uses(
228            "crate-ci",
229            "typos",
230            "80c8a4945eec0f6d464eaf9e65ed98ef085283d1",
231        ) // v1.38.1
232        .with(("config", "./typos.toml"))
233    }
234    named::job(
235        release_job(&[])
236            .runs_on(runners::LINUX_MEDIUM)
237            .add_step(steps::checkout_repo())
238            .add_step(steps::cache_rust_dependencies_namespace())
239            .add_step(steps::setup_pnpm())
240            .add_step(steps::script("./script/prettier"))
241            .add_step(steps::script("./script/check-todos"))
242            .add_step(steps::script("./script/check-keymaps"))
243            .add_step(check_for_typos())
244            .add_step(steps::cargo_fmt()),
245    )
246}
247
248fn check_dependencies() -> NamedJob {
249    fn install_cargo_machete() -> Step<Use> {
250        named::uses(
251            "clechasseur",
252            "rs-cargo",
253            "8435b10f6e71c2e3d4d3b7573003a8ce4bfc6386", // v2
254        )
255        .add_with(("command", "install"))
256        .add_with(("args", "cargo-machete@0.7.0"))
257    }
258
259    fn run_cargo_machete() -> Step<Use> {
260        named::uses(
261            "clechasseur",
262            "rs-cargo",
263            "8435b10f6e71c2e3d4d3b7573003a8ce4bfc6386", // v2
264        )
265        .add_with(("command", "machete"))
266    }
267
268    fn check_cargo_lock() -> Step<Run> {
269        named::bash("cargo update --locked --workspace")
270    }
271
272    fn check_vulnerable_dependencies() -> Step<Use> {
273        named::uses(
274            "actions",
275            "dependency-review-action",
276            "67d4f4bd7a9b17a0db54d2a7519187c65e339de8", // v4
277        )
278        .if_condition(Expression::new("github.event_name == 'pull_request'"))
279        .with(("license-check", false))
280    }
281
282    named::job(
283        release_job(&[])
284            .runs_on(runners::LINUX_SMALL)
285            .add_step(steps::checkout_repo())
286            .add_step(steps::cache_rust_dependencies_namespace())
287            .add_step(install_cargo_machete())
288            .add_step(run_cargo_machete())
289            .add_step(check_cargo_lock())
290            .add_step(check_vulnerable_dependencies()),
291    )
292}
293
294fn check_workspace_binaries() -> NamedJob {
295    named::job(
296        release_job(&[])
297            .runs_on(runners::LINUX_LARGE)
298            .add_step(steps::checkout_repo())
299            .add_step(steps::setup_cargo_config(Platform::Linux))
300            .add_step(steps::cache_rust_dependencies_namespace())
301            .map(steps::install_linux_dependencies)
302            .add_step(steps::script("cargo build -p collab"))
303            .add_step(steps::script("cargo build --workspace --bins --examples"))
304            .add_step(steps::cleanup_cargo_config(Platform::Linux)),
305    )
306}
307
308pub(crate) fn run_platform_tests(platform: Platform) -> NamedJob {
309    let runner = match platform {
310        Platform::Windows => runners::WINDOWS_DEFAULT,
311        Platform::Linux => runners::LINUX_DEFAULT,
312        Platform::Mac => runners::MAC_DEFAULT,
313    };
314    NamedJob {
315        name: format!("run_tests_{platform}"),
316        job: release_job(&[])
317            .runs_on(runner)
318            .add_step(steps::checkout_repo())
319            .add_step(steps::setup_cargo_config(platform))
320            .when(platform == Platform::Linux, |this| {
321                this.add_step(steps::cache_rust_dependencies_namespace())
322            })
323            .when(
324                platform == Platform::Linux,
325                steps::install_linux_dependencies,
326            )
327            .add_step(steps::setup_node())
328            .add_step(steps::clippy(platform))
329            .when(platform == Platform::Linux, |job| {
330                job.add_step(steps::cargo_install_nextest())
331            })
332            .add_step(steps::clear_target_dir_if_large(platform))
333            .add_step(steps::cargo_nextest(platform))
334            .add_step(steps::cleanup_cargo_config(platform)),
335    }
336}
337
338pub(crate) fn check_postgres_and_protobuf_migrations() -> NamedJob {
339    fn remove_untracked_files() -> Step<Run> {
340        named::bash("git clean -df")
341    }
342
343    fn ensure_fresh_merge() -> Step<Run> {
344        named::bash(indoc::indoc! {r#"
345            if [ -z "$GITHUB_BASE_REF" ];
346            then
347              echo "BUF_BASE_BRANCH=$(git merge-base origin/main HEAD)" >> "$GITHUB_ENV"
348            else
349              git checkout -B temp
350              git merge -q "origin/$GITHUB_BASE_REF" -m "merge main into temp"
351              echo "BUF_BASE_BRANCH=$GITHUB_BASE_REF" >> "$GITHUB_ENV"
352            fi
353        "#})
354    }
355
356    fn bufbuild_setup_action() -> Step<Use> {
357        named::uses("bufbuild", "buf-setup-action", "v1").add_with(("version", "v1.29.0"))
358    }
359
360    fn bufbuild_breaking_action() -> Step<Use> {
361        named::uses("bufbuild", "buf-breaking-action", "v1").add_with(("input", "crates/proto/proto/"))
362            .add_with(("against", "https://github.com/${GITHUB_REPOSITORY}.git#branch=${BUF_BASE_BRANCH},subdir=crates/proto/proto/"))
363    }
364
365    named::job(
366        release_job(&[])
367            .runs_on(runners::MAC_DEFAULT)
368            .add_step(steps::checkout_repo().with(("fetch-depth", 0))) // fetch full history
369            .add_step(remove_untracked_files())
370            .add_step(ensure_fresh_merge())
371            .add_step(bufbuild_setup_action())
372            .add_step(bufbuild_breaking_action()),
373    )
374}
375
376fn doctests() -> NamedJob {
377    fn run_doctests() -> Step<Run> {
378        named::bash(indoc::indoc! {r#"
379            cargo test --workspace --doc --no-fail-fast
380        "#})
381        .id("run_doctests")
382    }
383
384    named::job(
385        release_job(&[])
386            .runs_on(runners::LINUX_DEFAULT)
387            .add_step(steps::checkout_repo())
388            .add_step(steps::cache_rust_dependencies_namespace())
389            .map(steps::install_linux_dependencies)
390            .add_step(steps::setup_cargo_config(Platform::Linux))
391            .add_step(run_doctests())
392            .add_step(steps::cleanup_cargo_config(Platform::Linux)),
393    )
394}
395
396fn check_licenses() -> NamedJob {
397    named::job(
398        Job::default()
399            .runs_on(runners::LINUX_SMALL)
400            .add_step(steps::checkout_repo())
401            .add_step(steps::cache_rust_dependencies_namespace())
402            .add_step(steps::script("./script/check-licenses"))
403            .add_step(steps::script("./script/generate-licenses")),
404    )
405}
406
407fn check_docs() -> NamedJob {
408    fn lychee_link_check(dir: &str) -> Step<Use> {
409        named::uses(
410            "lycheeverse",
411            "lychee-action",
412            "82202e5e9c2f4ef1a55a3d02563e1cb6041e5332",
413        ) // v2.4.1
414        .add_with(("args", format!("--no-progress --exclude '^http' '{dir}'")))
415        .add_with(("fail", true))
416        .add_with(("jobSummary", false))
417    }
418
419    fn install_mdbook() -> Step<Use> {
420        named::uses(
421            "peaceiris",
422            "actions-mdbook",
423            "ee69d230fe19748b7abf22df32acaa93833fad08", // v2
424        )
425        .with(("mdbook-version", "0.4.37"))
426    }
427
428    fn build_docs() -> Step<Run> {
429        named::bash(indoc::indoc! {r#"
430            mkdir -p target/deploy
431            mdbook build ./docs --dest-dir=../target/deploy/docs/
432        "#})
433    }
434
435    named::job(
436        release_job(&[])
437            .runs_on(runners::LINUX_LARGE)
438            .add_step(steps::checkout_repo())
439            .add_step(steps::setup_cargo_config(Platform::Linux))
440            // todo(ci): un-inline build_docs/action.yml here
441            .add_step(steps::cache_rust_dependencies_namespace())
442            .add_step(
443                lychee_link_check("./docs/src/**/*"), // check markdown links
444            )
445            .map(steps::install_linux_dependencies)
446            .add_step(install_mdbook())
447            .add_step(build_docs())
448            .add_step(
449                lychee_link_check("target/deploy/docs"), // check links in generated html
450            ),
451    )
452}
453
454pub(crate) fn check_scripts() -> NamedJob {
455    fn download_actionlint() -> Step<Run> {
456        named::bash(
457            "bash <(curl https://raw.githubusercontent.com/rhysd/actionlint/main/scripts/download-actionlint.bash)",
458        )
459    }
460
461    fn run_actionlint() -> Step<Run> {
462        named::bash(indoc::indoc! {r#"
463            ${{ steps.get_actionlint.outputs.executable }} -color
464        "#})
465    }
466
467    fn run_shellcheck() -> Step<Run> {
468        named::bash("./script/shellcheck-scripts error")
469    }
470
471    fn check_xtask_workflows() -> Step<Run> {
472        named::bash(indoc::indoc! {r#"
473            cargo xtask workflows
474            if ! git diff --exit-code .github; then
475              echo "Error: .github directory has uncommitted changes after running 'cargo xtask workflows'"
476              echo "Please run 'cargo xtask workflows' locally and commit the changes"
477              exit 1
478            fi
479        "#})
480    }
481
482    named::job(
483        release_job(&[])
484            .runs_on(runners::LINUX_SMALL)
485            .add_step(steps::checkout_repo())
486            .add_step(run_shellcheck())
487            .add_step(download_actionlint().id("get_actionlint"))
488            .add_step(run_actionlint())
489            .add_step(check_xtask_workflows()),
490    )
491}