steps.rs

  1use gh_workflow::*;
  2
  3use crate::tasks::workflows::{runners::Platform, vars};
  4
  5pub const BASH_SHELL: &str = "bash -euxo pipefail {0}";
  6// https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax#jobsjob_idstepsshell
  7pub const PWSH_SHELL: &str = "pwsh";
  8
  9pub fn checkout_repo() -> Step<Use> {
 10    named::uses(
 11        "actions",
 12        "checkout",
 13        "11bd71901bbe5b1630ceea73d27597364c9af683", // v4
 14    )
 15    // prevent checkout action from running `git clean -ffdx` which
 16    // would delete the target directory
 17    .add_with(("clean", false))
 18}
 19
 20pub fn setup_pnpm() -> Step<Use> {
 21    named::uses(
 22        "pnpm",
 23        "action-setup",
 24        "fe02b34f77f8bc703788d5817da081398fad5dd2", // v4.0.0
 25    )
 26    .add_with(("version", "9"))
 27}
 28
 29pub fn setup_node() -> Step<Use> {
 30    named::uses(
 31        "actions",
 32        "setup-node",
 33        "49933ea5288caeca8642d1e84afbd3f7d6820020", // v4
 34    )
 35    .add_with(("node-version", "20"))
 36}
 37
 38pub fn setup_sentry() -> Step<Use> {
 39    named::uses(
 40        "matbour",
 41        "setup-sentry-cli",
 42        "3e938c54b3018bdd019973689ef984e033b0454b",
 43    )
 44    .add_with(("token", vars::SENTRY_AUTH_TOKEN))
 45}
 46
 47pub fn cargo_fmt() -> Step<Run> {
 48    named::bash("cargo fmt --all -- --check")
 49}
 50
 51pub fn cargo_install_nextest() -> Step<Use> {
 52    named::uses("taiki-e", "install-action", "nextest")
 53}
 54
 55pub fn cargo_nextest(platform: Platform) -> Step<Run> {
 56    named::run(
 57        platform,
 58        "cargo nextest run --workspace --no-fail-fast --failure-output immediate-final",
 59    )
 60}
 61
 62pub fn setup_cargo_config(platform: Platform) -> Step<Run> {
 63    match platform {
 64        Platform::Windows => named::pwsh(indoc::indoc! {r#"
 65            New-Item -ItemType Directory -Path "./../.cargo" -Force
 66            Copy-Item -Path "./.cargo/ci-config.toml" -Destination "./../.cargo/config.toml"
 67        "#}),
 68
 69        Platform::Linux | Platform::Mac => named::bash(indoc::indoc! {r#"
 70            mkdir -p ./../.cargo
 71            cp ./.cargo/ci-config.toml ./../.cargo/config.toml
 72        "#}),
 73    }
 74}
 75
 76pub fn cleanup_cargo_config(platform: Platform) -> Step<Run> {
 77    let step = match platform {
 78        Platform::Windows => named::pwsh(indoc::indoc! {r#"
 79            Remove-Item -Recurse -Path "./../.cargo" -Force -ErrorAction SilentlyContinue
 80        "#}),
 81        Platform::Linux | Platform::Mac => named::bash(indoc::indoc! {r#"
 82            rm -rf ./../.cargo
 83        "#}),
 84    };
 85
 86    step.if_condition(Expression::new("always()"))
 87}
 88
 89pub fn clear_target_dir_if_large(platform: Platform) -> Step<Run> {
 90    match platform {
 91        Platform::Windows => named::pwsh("./script/clear-target-dir-if-larger-than.ps1 250"),
 92        Platform::Linux => named::bash("./script/clear-target-dir-if-larger-than 250"),
 93        Platform::Mac => named::bash("./script/clear-target-dir-if-larger-than 300"),
 94    }
 95}
 96
 97pub fn clippy(platform: Platform) -> Step<Run> {
 98    match platform {
 99        Platform::Windows => named::pwsh("./script/clippy.ps1"),
100        _ => named::bash("./script/clippy"),
101    }
102}
103
104pub fn cache_rust_dependencies_namespace() -> Step<Use> {
105    named::uses("namespacelabs", "nscloud-cache-action", "v1").add_with(("cache", "rust"))
106}
107
108pub fn setup_linux() -> Step<Run> {
109    named::bash("./script/linux")
110}
111
112fn install_mold() -> Step<Run> {
113    named::bash("./script/install-mold")
114}
115
116fn download_wasi_sdk() -> Step<Run> {
117    named::bash("./script/download-wasi-sdk")
118}
119
120pub(crate) fn install_linux_dependencies(job: Job) -> Job {
121    job.add_step(setup_linux())
122        .add_step(install_mold())
123        .add_step(download_wasi_sdk())
124}
125
126pub fn script(name: &str) -> Step<Run> {
127    if name.ends_with(".ps1") {
128        Step::new(name).run(name).shell(PWSH_SHELL)
129    } else {
130        Step::new(name).run(name).shell(BASH_SHELL)
131    }
132}
133
134pub struct NamedJob {
135    pub name: String,
136    pub job: Job,
137}
138
139// impl NamedJob {
140//     pub fn map(self, f: impl FnOnce(Job) -> Job) -> Self {
141//         NamedJob {
142//             name: self.name,
143//             job: f(self.job),
144//         }
145//     }
146// }
147
148pub fn repository_owner_guard_expression(trigger_always: bool) -> Expression {
149    Expression::new(format!(
150        "(github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions'){}",
151        trigger_always.then_some(" && always()").unwrap_or_default()
152    ))
153}
154
155pub trait CommonJobConditions: Sized {
156    fn with_repository_owner_guard(self) -> Self;
157}
158
159impl CommonJobConditions for Job {
160    fn with_repository_owner_guard(self) -> Self {
161        self.cond(repository_owner_guard_expression(false))
162    }
163}
164
165pub(crate) fn release_job(deps: &[&NamedJob]) -> Job {
166    dependant_job(deps)
167        .with_repository_owner_guard()
168        .timeout_minutes(60u32)
169}
170
171pub(crate) fn dependant_job(deps: &[&NamedJob]) -> Job {
172    let job = Job::default();
173    if deps.len() > 0 {
174        job.needs(deps.iter().map(|j| j.name.clone()).collect::<Vec<_>>())
175    } else {
176        job
177    }
178}
179
180impl FluentBuilder for Job {}
181impl FluentBuilder for Workflow {}
182
183/// A helper trait for building complex objects with imperative conditionals in a fluent style.
184/// Copied from GPUI to avoid adding GPUI as dependency
185/// todo(ci) just put this in gh-workflow
186#[allow(unused)]
187pub trait FluentBuilder {
188    /// Imperatively modify self with the given closure.
189    fn map<U>(self, f: impl FnOnce(Self) -> U) -> U
190    where
191        Self: Sized,
192    {
193        f(self)
194    }
195
196    /// Conditionally modify self with the given closure.
197    fn when(self, condition: bool, then: impl FnOnce(Self) -> Self) -> Self
198    where
199        Self: Sized,
200    {
201        self.map(|this| if condition { then(this) } else { this })
202    }
203
204    /// Conditionally modify self with the given closure.
205    fn when_else(
206        self,
207        condition: bool,
208        then: impl FnOnce(Self) -> Self,
209        else_fn: impl FnOnce(Self) -> Self,
210    ) -> Self
211    where
212        Self: Sized,
213    {
214        self.map(|this| if condition { then(this) } else { else_fn(this) })
215    }
216
217    /// Conditionally unwrap and modify self with the given closure, if the given option is Some.
218    fn when_some<T>(self, option: Option<T>, then: impl FnOnce(Self, T) -> Self) -> Self
219    where
220        Self: Sized,
221    {
222        self.map(|this| {
223            if let Some(value) = option {
224                then(this, value)
225            } else {
226                this
227            }
228        })
229    }
230    /// Conditionally unwrap and modify self with the given closure, if the given option is None.
231    fn when_none<T>(self, option: &Option<T>, then: impl FnOnce(Self) -> Self) -> Self
232    where
233        Self: Sized,
234    {
235        self.map(|this| if option.is_some() { this } else { then(this) })
236    }
237}
238
239// (janky) helper to generate steps with a name that corresponds
240// to the name of the calling function.
241pub mod named {
242    use super::*;
243
244    /// Returns a uses step with the same name as the enclosing function.
245    /// (You shouldn't inline this function into the workflow definition, you must
246    /// wrap it in a new function.)
247    pub fn uses(owner: &str, repo: &str, ref_: &str) -> Step<Use> {
248        Step::new(function_name(1)).uses(owner, repo, ref_)
249    }
250
251    /// Returns a bash-script step with the same name as the enclosing function.
252    /// (You shouldn't inline this function into the workflow definition, you must
253    /// wrap it in a new function.)
254    pub fn bash(script: &str) -> Step<Run> {
255        Step::new(function_name(1)).run(script).shell(BASH_SHELL)
256    }
257
258    /// Returns a pwsh-script step with the same name as the enclosing function.
259    /// (You shouldn't inline this function into the workflow definition, you must
260    /// wrap it in a new function.)
261    pub fn pwsh(script: &str) -> Step<Run> {
262        Step::new(function_name(1)).run(script).shell(PWSH_SHELL)
263    }
264
265    /// Runs the command in either powershell or bash, depending on platform.
266    /// (You shouldn't inline this function into the workflow definition, you must
267    /// wrap it in a new function.)
268    pub fn run(platform: Platform, script: &str) -> Step<Run> {
269        match platform {
270            Platform::Windows => Step::new(function_name(1)).run(script).shell(PWSH_SHELL),
271            Platform::Linux | Platform::Mac => {
272                Step::new(function_name(1)).run(script).shell(BASH_SHELL)
273            }
274        }
275    }
276
277    /// Returns a Workflow with the same name as the enclosing module.
278    pub fn workflow() -> Workflow {
279        Workflow::default().name(
280            named::function_name(1)
281                .split("::")
282                .next()
283                .unwrap()
284                .to_owned(),
285        )
286    }
287
288    /// Returns a Job with the same name as the enclosing function.
289    /// (note job names may not contain `::`)
290    pub fn job(job: Job) -> NamedJob {
291        NamedJob {
292            name: function_name(1).split("::").last().unwrap().to_owned(),
293            job,
294        }
295    }
296
297    /// Returns the function name N callers above in the stack
298    /// (typically 1).
299    /// This only works because xtask always runs debug builds.
300    pub fn function_name(i: usize) -> String {
301        let mut name = "<unknown>".to_string();
302        let mut count = 0;
303        backtrace::trace(|frame| {
304            if count < i + 3 {
305                count += 1;
306                return true;
307            }
308            backtrace::resolve_frame(frame, |cb| {
309                if let Some(s) = cb.name() {
310                    name = s.to_string()
311                }
312            });
313            false
314        });
315
316        name.split("::")
317            .skip_while(|s| s != &"workflows")
318            .skip(1)
319            .collect::<Vec<_>>()
320            .join("::")
321    }
322}
323
324pub fn git_checkout(ref_name: &dyn std::fmt::Display) -> Step<Run> {
325    named::bash(&format!(
326        "git fetch origin {ref_name} && git checkout {ref_name}"
327    ))
328}