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