steps.rs

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