steps.rs

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