1use gh_workflow::*;
2use serde_json::Value;
3
4use crate::tasks::workflows::{runners::Platform, vars, vars::StepOutput};
5
6pub(crate) fn use_clang(job: Job) -> Job {
7 job.add_env(Env::new("CC", "clang"))
8 .add_env(Env::new("CXX", "clang++"))
9}
10
11const SCCACHE_R2_BUCKET: &str = "sccache-zed";
12
13pub(crate) const BASH_SHELL: &str = "bash -euxo pipefail {0}";
14// https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax#jobsjob_idstepsshell
15pub const PWSH_SHELL: &str = "pwsh";
16
17pub(crate) struct Nextest(Step<Run>);
18
19pub(crate) fn cargo_nextest(platform: Platform) -> Nextest {
20 Nextest(named::run(
21 platform,
22 "cargo nextest run --workspace --no-fail-fast --no-tests=warn",
23 ))
24}
25
26impl Nextest {
27 #[allow(dead_code)]
28 pub(crate) fn with_filter_expr(mut self, filter_expr: &str) -> Self {
29 if let Some(nextest_command) = self.0.value.run.as_mut() {
30 nextest_command.push_str(&format!(r#" -E "{filter_expr}""#));
31 }
32 self
33 }
34
35 pub(crate) fn with_changed_packages_filter(mut self, orchestrate_job: &str) -> Self {
36 if let Some(nextest_command) = self.0.value.run.as_mut() {
37 nextest_command.push_str(&format!(
38 r#"${{{{ needs.{orchestrate_job}.outputs.changed_packages && format(' -E "{{0}}"', needs.{orchestrate_job}.outputs.changed_packages) || '' }}}}"#
39 ));
40 }
41 self
42 }
43}
44
45impl From<Nextest> for Step<Run> {
46 fn from(value: Nextest) -> Self {
47 value.0
48 }
49}
50
51#[derive(Default)]
52enum FetchDepth {
53 #[default]
54 Shallow,
55 Full,
56 Custom(serde_json::Value),
57}
58
59#[derive(Default)]
60pub(crate) struct CheckoutStep {
61 fetch_depth: FetchDepth,
62 name: Option<String>,
63 token: Option<String>,
64 path: Option<String>,
65 repository: Option<String>,
66 ref_: Option<String>,
67}
68
69impl CheckoutStep {
70 pub fn with_full_history(mut self) -> Self {
71 self.fetch_depth = FetchDepth::Full;
72 self
73 }
74
75 pub fn with_custom_name(mut self, name: &str) -> Self {
76 self.name = Some(name.to_string());
77 self
78 }
79
80 pub fn with_custom_fetch_depth(mut self, fetch_depth: impl Into<Value>) -> Self {
81 self.fetch_depth = FetchDepth::Custom(fetch_depth.into());
82 self
83 }
84
85 /// Sets `fetch-depth` to `2` on the main branch and `350` on all other branches.
86 pub fn with_deep_history_on_non_main(self) -> Self {
87 self.with_custom_fetch_depth("${{ github.ref == 'refs/heads/main' && 2 || 350 }}")
88 }
89
90 pub fn with_token(mut self, token: &StepOutput) -> Self {
91 self.token = Some(token.to_string());
92 self
93 }
94
95 pub fn with_path(mut self, path: &str) -> Self {
96 self.path = Some(path.to_string());
97 self
98 }
99
100 pub fn with_repository(mut self, repository: &str) -> Self {
101 self.repository = Some(repository.to_string());
102 self
103 }
104
105 pub fn with_ref(mut self, ref_: impl ToString) -> Self {
106 self.ref_ = Some(ref_.to_string());
107 self
108 }
109}
110
111impl From<CheckoutStep> for Step<Use> {
112 fn from(value: CheckoutStep) -> Self {
113 Step::new(value.name.unwrap_or("steps::checkout_repo".to_string()))
114 .uses(
115 "actions",
116 "checkout",
117 "11bd71901bbe5b1630ceea73d27597364c9af683", // v4
118 )
119 // prevent checkout action from running `git clean -ffdx` which
120 // would delete the target directory
121 .add_with(("clean", false))
122 .map(|step| match value.fetch_depth {
123 FetchDepth::Shallow => step,
124 FetchDepth::Full => step.add_with(("fetch-depth", 0)),
125 FetchDepth::Custom(depth) => step.add_with(("fetch-depth", depth)),
126 })
127 .when_some(value.path, |step, path| step.add_with(("path", path)))
128 .when_some(value.repository, |step, repository| {
129 step.add_with(("repository", repository))
130 })
131 .when_some(value.ref_, |step, ref_| step.add_with(("ref", ref_)))
132 .when_some(value.token, |step, token| step.add_with(("token", token)))
133 }
134}
135
136pub fn checkout_repo() -> CheckoutStep {
137 CheckoutStep::default()
138}
139
140pub fn setup_pnpm() -> Step<Use> {
141 named::uses(
142 "pnpm",
143 "action-setup",
144 "fe02b34f77f8bc703788d5817da081398fad5dd2", // v4.0.0
145 )
146 .add_with(("version", "9"))
147}
148
149pub fn setup_node() -> Step<Use> {
150 named::uses(
151 "actions",
152 "setup-node",
153 "49933ea5288caeca8642d1e84afbd3f7d6820020", // v4
154 )
155 .add_with(("node-version", "20"))
156}
157
158pub fn setup_sentry() -> Step<Use> {
159 named::uses(
160 "matbour",
161 "setup-sentry-cli",
162 "3e938c54b3018bdd019973689ef984e033b0454b",
163 )
164 .add_with(("token", vars::SENTRY_AUTH_TOKEN))
165}
166
167pub fn prettier() -> Step<Run> {
168 named::bash("./script/prettier")
169}
170
171pub fn cargo_fmt() -> Step<Run> {
172 named::bash("cargo fmt --all -- --check")
173}
174
175pub fn cargo_install_nextest() -> Step<Use> {
176 named::uses("taiki-e", "install-action", "nextest")
177}
178
179pub fn setup_cargo_config(platform: Platform) -> Step<Run> {
180 match platform {
181 Platform::Windows => named::pwsh(indoc::indoc! {r#"
182 New-Item -ItemType Directory -Path "./../.cargo" -Force
183 Copy-Item -Path "./.cargo/ci-config.toml" -Destination "./../.cargo/config.toml"
184 "#}),
185
186 Platform::Linux | Platform::Mac => named::bash(indoc::indoc! {r#"
187 mkdir -p ./../.cargo
188 cp ./.cargo/ci-config.toml ./../.cargo/config.toml
189 "#}),
190 }
191}
192
193pub fn cleanup_cargo_config(platform: Platform) -> Step<Run> {
194 let step = match platform {
195 Platform::Windows => named::pwsh(indoc::indoc! {r#"
196 Remove-Item -Recurse -Path "./../.cargo" -Force -ErrorAction SilentlyContinue
197 "#}),
198 Platform::Linux | Platform::Mac => named::bash(indoc::indoc! {r#"
199 rm -rf ./../.cargo
200 "#}),
201 };
202
203 step.if_condition(Expression::new("always()"))
204}
205
206pub fn clear_target_dir_if_large(platform: Platform) -> Step<Run> {
207 match platform {
208 Platform::Windows => named::pwsh("./script/clear-target-dir-if-larger-than.ps1 250"),
209 Platform::Linux => named::bash("./script/clear-target-dir-if-larger-than 250"),
210 Platform::Mac => named::bash("./script/clear-target-dir-if-larger-than 300"),
211 }
212}
213
214pub fn clippy(platform: Platform) -> Step<Run> {
215 match platform {
216 Platform::Windows => named::pwsh("./script/clippy.ps1"),
217 _ => named::bash("./script/clippy"),
218 }
219}
220
221pub fn cache_rust_dependencies_namespace() -> Step<Use> {
222 named::uses("namespacelabs", "nscloud-cache-action", "v1")
223 .add_with(("cache", "rust"))
224 .add_with(("path", "~/.rustup"))
225}
226
227pub fn setup_sccache(platform: Platform) -> Step<Run> {
228 let step = match platform {
229 Platform::Windows => named::pwsh("./script/setup-sccache.ps1"),
230 Platform::Linux | Platform::Mac => named::bash("./script/setup-sccache"),
231 };
232 step.add_env(("R2_ACCOUNT_ID", vars::R2_ACCOUNT_ID))
233 .add_env(("R2_ACCESS_KEY_ID", vars::R2_ACCESS_KEY_ID))
234 .add_env(("R2_SECRET_ACCESS_KEY", vars::R2_SECRET_ACCESS_KEY))
235 .add_env(("SCCACHE_BUCKET", SCCACHE_R2_BUCKET))
236}
237
238pub fn show_sccache_stats(platform: Platform) -> Step<Run> {
239 match platform {
240 // Use $env:RUSTC_WRAPPER (absolute path) because GITHUB_PATH changes
241 // don't take effect until the next step in PowerShell.
242 // Check if RUSTC_WRAPPER is set first (it won't be for fork PRs without secrets).
243 Platform::Windows => {
244 named::pwsh("if ($env:RUSTC_WRAPPER) { & $env:RUSTC_WRAPPER --show-stats }; exit 0")
245 }
246 Platform::Linux | Platform::Mac => named::bash("sccache --show-stats || true"),
247 }
248}
249
250pub fn cache_nix_dependencies_namespace() -> Step<Use> {
251 named::uses("namespacelabs", "nscloud-cache-action", "v1").add_with(("cache", "nix"))
252}
253
254pub fn cache_nix_store_macos() -> Step<Use> {
255 // On macOS, `/nix` is on a read-only root filesystem so nscloud's `cache: nix`
256 // cannot mount or symlink there. Instead we cache a user-writable directory and
257 // use nix-store --import/--export in separate steps to transfer store paths.
258 named::uses("namespacelabs", "nscloud-cache-action", "v1").add_with(("path", "~/nix-cache"))
259}
260
261pub fn setup_linux() -> Step<Run> {
262 named::bash("./script/linux")
263}
264
265fn download_wasi_sdk() -> Step<Run> {
266 named::bash("./script/download-wasi-sdk")
267}
268
269pub(crate) fn install_linux_dependencies(job: Job) -> Job {
270 job.add_step(setup_linux()).add_step(download_wasi_sdk())
271}
272
273pub fn script(name: &str) -> Step<Run> {
274 if name.ends_with(".ps1") {
275 Step::new(name).run(name).shell(PWSH_SHELL)
276 } else {
277 Step::new(name).run(name)
278 }
279}
280
281pub struct NamedJob<J: JobType = RunJob> {
282 pub name: String,
283 pub job: Job<J>,
284}
285
286// impl NamedJob {
287// pub fn map(self, f: impl FnOnce(Job) -> Job) -> Self {
288// NamedJob {
289// name: self.name,
290// job: f(self.job),
291// }
292// }
293// }
294
295pub(crate) const DEFAULT_REPOSITORY_OWNER_GUARD: &str =
296 "(github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions')";
297
298pub fn repository_owner_guard_expression(trigger_always: bool) -> Expression {
299 Expression::new(format!(
300 "{}{}",
301 DEFAULT_REPOSITORY_OWNER_GUARD,
302 trigger_always.then_some(" && always()").unwrap_or_default()
303 ))
304}
305
306pub trait CommonJobConditions: Sized {
307 fn with_repository_owner_guard(self) -> Self;
308}
309
310impl CommonJobConditions for Job {
311 fn with_repository_owner_guard(self) -> Self {
312 self.cond(repository_owner_guard_expression(false))
313 }
314}
315
316pub(crate) fn release_job(deps: &[&NamedJob]) -> Job {
317 dependant_job(deps)
318 .with_repository_owner_guard()
319 .timeout_minutes(60u32)
320}
321
322pub(crate) fn dependant_job(deps: &[&NamedJob]) -> Job {
323 let job = Job::default();
324 if deps.len() > 0 {
325 job.needs(deps.iter().map(|j| j.name.clone()).collect::<Vec<_>>())
326 } else {
327 job
328 }
329}
330
331impl FluentBuilder for Job {}
332impl FluentBuilder for Workflow {}
333impl FluentBuilder for Input {}
334impl<T> FluentBuilder for Step<T> {}
335
336/// A helper trait for building complex objects with imperative conditionals in a fluent style.
337/// Copied from GPUI to avoid adding GPUI as dependency
338/// todo(ci) just put this in gh-workflow
339#[allow(unused)]
340pub trait FluentBuilder {
341 /// Imperatively modify self with the given closure.
342 fn map<U>(self, f: impl FnOnce(Self) -> U) -> U
343 where
344 Self: Sized,
345 {
346 f(self)
347 }
348
349 /// Conditionally modify self with the given closure.
350 fn when(self, condition: bool, then: impl FnOnce(Self) -> Self) -> Self
351 where
352 Self: Sized,
353 {
354 self.map(|this| if condition { then(this) } else { this })
355 }
356
357 /// Conditionally modify self with the given closure.
358 fn when_else(
359 self,
360 condition: bool,
361 then: impl FnOnce(Self) -> Self,
362 else_fn: impl FnOnce(Self) -> Self,
363 ) -> Self
364 where
365 Self: Sized,
366 {
367 self.map(|this| if condition { then(this) } else { else_fn(this) })
368 }
369
370 /// Conditionally unwrap and modify self with the given closure, if the given option is Some.
371 fn when_some<T>(self, option: Option<T>, then: impl FnOnce(Self, T) -> Self) -> Self
372 where
373 Self: Sized,
374 {
375 self.map(|this| {
376 if let Some(value) = option {
377 then(this, value)
378 } else {
379 this
380 }
381 })
382 }
383 /// Conditionally unwrap and modify self with the given closure, if the given option is None.
384 fn when_none<T>(self, option: &Option<T>, then: impl FnOnce(Self) -> Self) -> Self
385 where
386 Self: Sized,
387 {
388 self.map(|this| if option.is_some() { this } else { then(this) })
389 }
390}
391
392// (janky) helper to generate steps with a name that corresponds
393// to the name of the calling function.
394pub mod named {
395 use super::*;
396
397 /// Returns a uses step with the same name as the enclosing function.
398 /// (You shouldn't inline this function into the workflow definition, you must
399 /// wrap it in a new function.)
400 pub fn uses(owner: &str, repo: &str, ref_: &str) -> Step<Use> {
401 Step::new(function_name(1)).uses(owner, repo, ref_)
402 }
403
404 /// Returns a bash-script step with the same name as the enclosing function.
405 /// (You shouldn't inline this function into the workflow definition, you must
406 /// wrap it in a new function.)
407 pub fn bash(script: impl AsRef<str>) -> Step<Run> {
408 Step::new(function_name(1)).run(script.as_ref())
409 }
410
411 /// Returns a pwsh-script step with the same name as the enclosing function.
412 /// (You shouldn't inline this function into the workflow definition, you must
413 /// wrap it in a new function.)
414 pub fn pwsh(script: &str) -> Step<Run> {
415 Step::new(function_name(1)).run(script).shell(PWSH_SHELL)
416 }
417
418 /// Runs the command in either powershell or bash, depending on platform.
419 /// (You shouldn't inline this function into the workflow definition, you must
420 /// wrap it in a new function.)
421 pub fn run(platform: Platform, script: &str) -> Step<Run> {
422 match platform {
423 Platform::Windows => Step::new(function_name(1)).run(script).shell(PWSH_SHELL),
424 Platform::Linux | Platform::Mac => Step::new(function_name(1)).run(script),
425 }
426 }
427
428 /// Returns a Workflow with the same name as the enclosing module with default
429 /// set for the running shell.
430 pub fn workflow() -> Workflow {
431 Workflow::default()
432 .name(
433 named::function_name(1)
434 .split("::")
435 .collect::<Vec<_>>()
436 .into_iter()
437 .rev()
438 .skip(1)
439 .rev()
440 .collect::<Vec<_>>()
441 .join("::"),
442 )
443 .defaults(Defaults::default().run(RunDefaults::default().shell(BASH_SHELL)))
444 }
445
446 /// Returns a Job with the same name as the enclosing function.
447 /// (note job names may not contain `::`)
448 pub fn job<J: JobType>(job: Job<J>) -> NamedJob<J> {
449 NamedJob {
450 name: function_name(1).split("::").last().unwrap().to_owned(),
451 job,
452 }
453 }
454
455 /// Returns the function name N callers above in the stack
456 /// (typically 1).
457 /// This only works because xtask always runs debug builds.
458 pub fn function_name(i: usize) -> String {
459 let mut name = "<unknown>".to_string();
460 let mut count = 0;
461 backtrace::trace(|frame| {
462 if count < i + 3 {
463 count += 1;
464 return true;
465 }
466 backtrace::resolve_frame(frame, |cb| {
467 if let Some(s) = cb.name() {
468 name = s.to_string()
469 }
470 });
471 false
472 });
473
474 name.split("::")
475 .skip_while(|s| s != &"workflows")
476 .skip(1)
477 .collect::<Vec<_>>()
478 .join("::")
479 }
480}
481
482pub fn git_checkout(ref_name: &dyn std::fmt::Display) -> Step<Run> {
483 named::bash(r#"git fetch origin "$REF_NAME" && git checkout "$REF_NAME""#)
484 .add_env(("REF_NAME", ref_name.to_string()))
485}
486
487pub fn authenticate_as_zippy() -> (Step<Use>, StepOutput) {
488 let step = named::uses(
489 "actions",
490 "create-github-app-token",
491 "bef1eaf1c0ac2b148ee2a0a74c65fbe6db0631f1",
492 )
493 .add_with(("app-id", vars::ZED_ZIPPY_APP_ID))
494 .add_with(("private-key", vars::ZED_ZIPPY_APP_PRIVATE_KEY))
495 .id("get-app-token");
496 let output = StepOutput::new(&step, "token");
497 (step, output)
498}