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