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