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 {
132    pub name: String,
133    pub job: Job,
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 {}
183
184/// A helper trait for building complex objects with imperative conditionals in a fluent style.
185/// Copied from GPUI to avoid adding GPUI as dependency
186/// todo(ci) just put this in gh-workflow
187#[allow(unused)]
188pub trait FluentBuilder {
189    /// Imperatively modify self with the given closure.
190    fn map<U>(self, f: impl FnOnce(Self) -> U) -> U
191    where
192        Self: Sized,
193    {
194        f(self)
195    }
196
197    /// Conditionally modify self with the given closure.
198    fn when(self, condition: bool, then: impl FnOnce(Self) -> Self) -> Self
199    where
200        Self: Sized,
201    {
202        self.map(|this| if condition { then(this) } else { this })
203    }
204
205    /// Conditionally modify self with the given closure.
206    fn when_else(
207        self,
208        condition: bool,
209        then: impl FnOnce(Self) -> Self,
210        else_fn: impl FnOnce(Self) -> Self,
211    ) -> Self
212    where
213        Self: Sized,
214    {
215        self.map(|this| if condition { then(this) } else { else_fn(this) })
216    }
217
218    /// Conditionally unwrap and modify self with the given closure, if the given option is Some.
219    fn when_some<T>(self, option: Option<T>, then: impl FnOnce(Self, T) -> Self) -> Self
220    where
221        Self: Sized,
222    {
223        self.map(|this| {
224            if let Some(value) = option {
225                then(this, value)
226            } else {
227                this
228            }
229        })
230    }
231    /// Conditionally unwrap and modify self with the given closure, if the given option is None.
232    fn when_none<T>(self, option: &Option<T>, then: impl FnOnce(Self) -> Self) -> Self
233    where
234        Self: Sized,
235    {
236        self.map(|this| if option.is_some() { this } else { then(this) })
237    }
238}
239
240// (janky) helper to generate steps with a name that corresponds
241// to the name of the calling function.
242pub mod named {
243    use super::*;
244
245    /// Returns a uses step with the same name as the enclosing function.
246    /// (You shouldn't inline this function into the workflow definition, you must
247    /// wrap it in a new function.)
248    pub fn uses(owner: &str, repo: &str, ref_: &str) -> Step<Use> {
249        Step::new(function_name(1)).uses(owner, repo, ref_)
250    }
251
252    /// Returns a bash-script step with the same name as the enclosing function.
253    /// (You shouldn't inline this function into the workflow definition, you must
254    /// wrap it in a new function.)
255    pub fn bash(script: impl AsRef<str>) -> Step<Run> {
256        Step::new(function_name(1))
257            .run(script.as_ref())
258            .shell(BASH_SHELL)
259    }
260
261    /// Returns a pwsh-script step with the same name as the enclosing function.
262    /// (You shouldn't inline this function into the workflow definition, you must
263    /// wrap it in a new function.)
264    pub fn pwsh(script: &str) -> Step<Run> {
265        Step::new(function_name(1)).run(script).shell(PWSH_SHELL)
266    }
267
268    /// Runs the command in either powershell or bash, depending on platform.
269    /// (You shouldn't inline this function into the workflow definition, you must
270    /// wrap it in a new function.)
271    pub fn run(platform: Platform, script: &str) -> Step<Run> {
272        match platform {
273            Platform::Windows => Step::new(function_name(1)).run(script).shell(PWSH_SHELL),
274            Platform::Linux | Platform::Mac => {
275                Step::new(function_name(1)).run(script).shell(BASH_SHELL)
276            }
277        }
278    }
279
280    /// Returns a Workflow with the same name as the enclosing module.
281    pub fn workflow() -> Workflow {
282        Workflow::default().name(
283            named::function_name(1)
284                .split("::")
285                .next()
286                .unwrap()
287                .to_owned(),
288        )
289    }
290
291    /// Returns a Job with the same name as the enclosing function.
292    /// (note job names may not contain `::`)
293    pub fn job(job: Job) -> NamedJob {
294        NamedJob {
295            name: function_name(1).split("::").last().unwrap().to_owned(),
296            job,
297        }
298    }
299
300    /// Returns the function name N callers above in the stack
301    /// (typically 1).
302    /// This only works because xtask always runs debug builds.
303    pub fn function_name(i: usize) -> String {
304        let mut name = "<unknown>".to_string();
305        let mut count = 0;
306        backtrace::trace(|frame| {
307            if count < i + 3 {
308                count += 1;
309                return true;
310            }
311            backtrace::resolve_frame(frame, |cb| {
312                if let Some(s) = cb.name() {
313                    name = s.to_string()
314                }
315            });
316            false
317        });
318
319        name.split("::")
320            .skip_while(|s| s != &"workflows")
321            .skip(1)
322            .collect::<Vec<_>>()
323            .join("::")
324    }
325}
326
327pub fn git_checkout(ref_name: &dyn std::fmt::Display) -> Step<Run> {
328    named::bash(&format!(
329        "git fetch origin {ref_name} && git checkout {ref_name}"
330    ))
331}