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, target: Option<&str>) -> Step<Run> {
215 match platform {
216 Platform::Windows => named::pwsh("./script/clippy.ps1"),
217 _ => match target {
218 Some(target) => named::bash(format!("./script/clippy --target {target}")),
219 None => named::bash("./script/clippy"),
220 },
221 }
222}
223
224pub fn install_rustup_target(target: &str) -> Step<Run> {
225 named::bash(format!("rustup target add {target}"))
226}
227
228pub fn cache_rust_dependencies_namespace() -> Step<Use> {
229 named::uses("namespacelabs", "nscloud-cache-action", "v1")
230 .add_with(("cache", "rust"))
231 .add_with(("path", "~/.rustup"))
232}
233
234pub fn setup_sccache(platform: Platform) -> Step<Run> {
235 let step = match platform {
236 Platform::Windows => named::pwsh("./script/setup-sccache.ps1"),
237 Platform::Linux | Platform::Mac => named::bash("./script/setup-sccache"),
238 };
239 step.add_env(("R2_ACCOUNT_ID", vars::R2_ACCOUNT_ID))
240 .add_env(("R2_ACCESS_KEY_ID", vars::R2_ACCESS_KEY_ID))
241 .add_env(("R2_SECRET_ACCESS_KEY", vars::R2_SECRET_ACCESS_KEY))
242 .add_env(("SCCACHE_BUCKET", SCCACHE_R2_BUCKET))
243}
244
245pub fn show_sccache_stats(platform: Platform) -> Step<Run> {
246 match platform {
247 // Use $env:RUSTC_WRAPPER (absolute path) because GITHUB_PATH changes
248 // don't take effect until the next step in PowerShell.
249 // Check if RUSTC_WRAPPER is set first (it won't be for fork PRs without secrets).
250 Platform::Windows => {
251 named::pwsh("if ($env:RUSTC_WRAPPER) { & $env:RUSTC_WRAPPER --show-stats }; exit 0")
252 }
253 Platform::Linux | Platform::Mac => named::bash("sccache --show-stats || true"),
254 }
255}
256
257pub fn cache_nix_dependencies_namespace() -> Step<Use> {
258 named::uses("namespacelabs", "nscloud-cache-action", "v1").add_with(("cache", "nix"))
259}
260
261pub fn cache_nix_store_macos() -> Step<Use> {
262 // On macOS, `/nix` is on a read-only root filesystem so nscloud's `cache: nix`
263 // cannot mount or symlink there. Instead we cache a user-writable directory and
264 // use nix-store --import/--export in separate steps to transfer store paths.
265 named::uses("namespacelabs", "nscloud-cache-action", "v1").add_with(("path", "~/nix-cache"))
266}
267
268pub fn setup_linux() -> Step<Run> {
269 named::bash("./script/linux")
270}
271
272fn download_wasi_sdk() -> Step<Run> {
273 named::bash("./script/download-wasi-sdk")
274}
275
276pub(crate) fn install_linux_dependencies(job: Job) -> Job {
277 job.add_step(setup_linux()).add_step(download_wasi_sdk())
278}
279
280pub fn script(name: &str) -> Step<Run> {
281 if name.ends_with(".ps1") {
282 Step::new(name).run(name).shell(PWSH_SHELL)
283 } else {
284 Step::new(name).run(name)
285 }
286}
287
288pub struct NamedJob<J: JobType = RunJob> {
289 pub name: String,
290 pub job: Job<J>,
291}
292
293// impl NamedJob {
294// pub fn map(self, f: impl FnOnce(Job) -> Job) -> Self {
295// NamedJob {
296// name: self.name,
297// job: f(self.job),
298// }
299// }
300// }
301
302pub(crate) const DEFAULT_REPOSITORY_OWNER_GUARD: &str =
303 "(github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions')";
304
305pub fn repository_owner_guard_expression(trigger_always: bool) -> Expression {
306 Expression::new(format!(
307 "{}{}",
308 DEFAULT_REPOSITORY_OWNER_GUARD,
309 trigger_always.then_some(" && always()").unwrap_or_default()
310 ))
311}
312
313pub trait CommonJobConditions: Sized {
314 fn with_repository_owner_guard(self) -> Self;
315}
316
317impl CommonJobConditions for Job {
318 fn with_repository_owner_guard(self) -> Self {
319 self.cond(repository_owner_guard_expression(false))
320 }
321}
322
323pub(crate) fn release_job(deps: &[&NamedJob]) -> Job {
324 dependant_job(deps)
325 .with_repository_owner_guard()
326 .timeout_minutes(60u32)
327}
328
329pub(crate) fn dependant_job(deps: &[&NamedJob]) -> Job {
330 let job = Job::default();
331 if deps.len() > 0 {
332 job.needs(deps.iter().map(|j| j.name.clone()).collect::<Vec<_>>())
333 } else {
334 job
335 }
336}
337
338impl FluentBuilder for Job {}
339impl FluentBuilder for Workflow {}
340impl FluentBuilder for Input {}
341impl<T> FluentBuilder for Step<T> {}
342
343/// A helper trait for building complex objects with imperative conditionals in a fluent style.
344/// Copied from GPUI to avoid adding GPUI as dependency
345/// todo(ci) just put this in gh-workflow
346#[allow(unused)]
347pub trait FluentBuilder {
348 /// Imperatively modify self with the given closure.
349 fn map<U>(self, f: impl FnOnce(Self) -> U) -> U
350 where
351 Self: Sized,
352 {
353 f(self)
354 }
355
356 /// Conditionally modify self with the given closure.
357 fn when(self, condition: bool, then: impl FnOnce(Self) -> Self) -> Self
358 where
359 Self: Sized,
360 {
361 self.map(|this| if condition { then(this) } else { this })
362 }
363
364 /// Conditionally modify self with the given closure.
365 fn when_else(
366 self,
367 condition: bool,
368 then: impl FnOnce(Self) -> Self,
369 else_fn: impl FnOnce(Self) -> Self,
370 ) -> Self
371 where
372 Self: Sized,
373 {
374 self.map(|this| if condition { then(this) } else { else_fn(this) })
375 }
376
377 /// Conditionally unwrap and modify self with the given closure, if the given option is Some.
378 fn when_some<T>(self, option: Option<T>, then: impl FnOnce(Self, T) -> Self) -> Self
379 where
380 Self: Sized,
381 {
382 self.map(|this| {
383 if let Some(value) = option {
384 then(this, value)
385 } else {
386 this
387 }
388 })
389 }
390 /// Conditionally unwrap and modify self with the given closure, if the given option is None.
391 fn when_none<T>(self, option: &Option<T>, then: impl FnOnce(Self) -> Self) -> Self
392 where
393 Self: Sized,
394 {
395 self.map(|this| if option.is_some() { this } else { then(this) })
396 }
397}
398
399// (janky) helper to generate steps with a name that corresponds
400// to the name of the calling function.
401pub mod named {
402 use super::*;
403
404 /// Returns a uses 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 uses(owner: &str, repo: &str, ref_: &str) -> Step<Use> {
408 Step::new(function_name(1)).uses(owner, repo, ref_)
409 }
410
411 /// Returns a bash-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 bash(script: impl AsRef<str>) -> Step<Run> {
415 Step::new(function_name(1)).run(script.as_ref())
416 }
417
418 /// Returns a pwsh-script step with the same name as the enclosing function.
419 /// (You shouldn't inline this function into the workflow definition, you must
420 /// wrap it in a new function.)
421 pub fn pwsh(script: &str) -> Step<Run> {
422 Step::new(function_name(1)).run(script).shell(PWSH_SHELL)
423 }
424
425 /// Runs the command in either powershell or bash, depending on platform.
426 /// (You shouldn't inline this function into the workflow definition, you must
427 /// wrap it in a new function.)
428 pub fn run(platform: Platform, script: &str) -> Step<Run> {
429 match platform {
430 Platform::Windows => Step::new(function_name(1)).run(script).shell(PWSH_SHELL),
431 Platform::Linux | Platform::Mac => Step::new(function_name(1)).run(script),
432 }
433 }
434
435 /// Returns a Workflow with the same name as the enclosing module with default
436 /// set for the running shell.
437 pub fn workflow() -> Workflow {
438 Workflow::default()
439 .name(
440 named::function_name(1)
441 .split("::")
442 .collect::<Vec<_>>()
443 .into_iter()
444 .rev()
445 .skip(1)
446 .rev()
447 .collect::<Vec<_>>()
448 .join("::"),
449 )
450 .defaults(Defaults::default().run(RunDefaults::default().shell(BASH_SHELL)))
451 }
452
453 /// Returns a Job with the same name as the enclosing function.
454 /// (note job names may not contain `::`)
455 pub fn job<J: JobType>(job: Job<J>) -> NamedJob<J> {
456 NamedJob {
457 name: function_name(1).split("::").last().unwrap().to_owned(),
458 job,
459 }
460 }
461
462 /// Returns the function name N callers above in the stack
463 /// (typically 1).
464 /// This only works because xtask always runs debug builds.
465 pub fn function_name(i: usize) -> String {
466 let mut name = "<unknown>".to_string();
467 let mut count = 0;
468 backtrace::trace(|frame| {
469 if count < i + 3 {
470 count += 1;
471 return true;
472 }
473 backtrace::resolve_frame(frame, |cb| {
474 if let Some(s) = cb.name() {
475 name = s.to_string()
476 }
477 });
478 false
479 });
480
481 name.split("::")
482 .skip_while(|s| s != &"workflows")
483 .skip(1)
484 .collect::<Vec<_>>()
485 .join("::")
486 }
487}
488
489pub fn git_checkout(ref_name: &dyn std::fmt::Display) -> Step<Run> {
490 named::bash(r#"git fetch origin "$REF_NAME" && git checkout "$REF_NAME""#)
491 .add_env(("REF_NAME", ref_name.to_string()))
492}
493
494pub fn authenticate_as_zippy() -> (Step<Use>, StepOutput) {
495 let step = named::uses(
496 "actions",
497 "create-github-app-token",
498 "bef1eaf1c0ac2b148ee2a0a74c65fbe6db0631f1",
499 )
500 .add_with(("app-id", vars::ZED_ZIPPY_APP_ID))
501 .add_with(("private-key", vars::ZED_ZIPPY_APP_PRIVATE_KEY))
502 .id("get-app-token");
503 let output = StepOutput::new(&step, "token");
504 (step, output)
505}