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(platform: Platform) -> Step<Run> {
 52    named::run(platform, "cargo install cargo-nextest --locked")
 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 upload_artifact(name: &str, path: &str) -> Step<Use> {
 90    Step::new(format!("@actions/upload-artifact {}", name))
 91        .uses(
 92            "actions",
 93            "upload-artifact",
 94            "330a01c490aca151604b8cf639adc76d48f6c5d4", // v5
 95        )
 96        .add_with(("name", name))
 97        .add_with(("path", path))
 98}
 99
100pub fn clear_target_dir_if_large(platform: Platform) -> Step<Run> {
101    match platform {
102        Platform::Windows => named::pwsh("./script/clear-target-dir-if-larger-than.ps1 250"),
103        Platform::Linux => named::bash("./script/clear-target-dir-if-larger-than 100"),
104        Platform::Mac => named::bash("./script/clear-target-dir-if-larger-than 300"),
105    }
106}
107
108pub(crate) fn clippy(platform: Platform) -> Step<Run> {
109    match platform {
110        Platform::Windows => named::pwsh("./script/clippy.ps1"),
111        _ => named::bash("./script/clippy"),
112    }
113}
114
115pub(crate) fn cache_rust_dependencies_namespace() -> Step<Use> {
116    let allowlisted_binaries: &str = &[
117        "/home/runner/.cargo/bin/cargo-nextest",
118        "/home/runner/.cargo/bin/cargo-about",
119    ]
120    .join("\n");
121    named::uses(
122        "namespacelabs",
123        "rust-cache",
124        "nscloud-cache-action", // v2
125    )
126    .add_with(("save-if", "${{ github.ref == 'refs/heads/main' }}"))
127    .add_with(("cache", "rust"))
128    .add_with(("path", allowlisted_binaries))
129}
130
131fn setup_linux() -> Step<Run> {
132    named::bash("./script/linux")
133}
134
135fn install_mold() -> Step<Run> {
136    named::bash("./script/install-mold")
137}
138
139pub(crate) fn install_linux_dependencies(job: Job) -> Job {
140    job.add_step(setup_linux()).add_step(install_mold())
141}
142
143pub fn script(name: &str) -> Step<Run> {
144    if name.ends_with(".ps1") {
145        Step::new(name).run(name).shell(PWSH_SHELL)
146    } else {
147        Step::new(name).run(name).shell(BASH_SHELL)
148    }
149}
150
151pub(crate) struct NamedJob {
152    pub name: String,
153    pub job: Job,
154}
155
156// impl NamedJob {
157//     pub fn map(self, f: impl FnOnce(Job) -> Job) -> Self {
158//         NamedJob {
159//             name: self.name,
160//             job: f(self.job),
161//         }
162//     }
163// }
164
165pub(crate) fn release_job(deps: &[&NamedJob]) -> Job {
166    let job = Job::default()
167        .cond(Expression::new(
168            "github.repository_owner == 'zed-industries'",
169        ))
170        .timeout_minutes(60u32);
171    if deps.len() > 0 {
172        job.needs(deps.iter().map(|j| j.name.clone()).collect::<Vec<_>>())
173    } else {
174        job
175    }
176}
177
178impl FluentBuilder for Job {}
179impl FluentBuilder for Workflow {}
180
181/// A helper trait for building complex objects with imperative conditionals in a fluent style.
182/// Copied from GPUI to avoid adding GPUI as dependency
183/// todo(ci) just put this in gh-workflow
184#[allow(unused)]
185pub(crate) trait FluentBuilder {
186    /// Imperatively modify self with the given closure.
187    fn map<U>(self, f: impl FnOnce(Self) -> U) -> U
188    where
189        Self: Sized,
190    {
191        f(self)
192    }
193
194    /// Conditionally modify self with the given closure.
195    fn when(self, condition: bool, then: impl FnOnce(Self) -> Self) -> Self
196    where
197        Self: Sized,
198    {
199        self.map(|this| if condition { then(this) } else { this })
200    }
201
202    /// Conditionally modify self with the given closure.
203    fn when_else(
204        self,
205        condition: bool,
206        then: impl FnOnce(Self) -> Self,
207        else_fn: impl FnOnce(Self) -> Self,
208    ) -> Self
209    where
210        Self: Sized,
211    {
212        self.map(|this| if condition { then(this) } else { else_fn(this) })
213    }
214
215    /// Conditionally unwrap and modify self with the given closure, if the given option is Some.
216    fn when_some<T>(self, option: Option<T>, then: impl FnOnce(Self, T) -> Self) -> Self
217    where
218        Self: Sized,
219    {
220        self.map(|this| {
221            if let Some(value) = option {
222                then(this, value)
223            } else {
224                this
225            }
226        })
227    }
228    /// Conditionally unwrap and modify self with the given closure, if the given option is None.
229    fn when_none<T>(self, option: &Option<T>, then: impl FnOnce(Self) -> Self) -> Self
230    where
231        Self: Sized,
232    {
233        self.map(|this| if option.is_some() { this } else { then(this) })
234    }
235}
236
237// (janky) helper to generate steps with a name that corresponds
238// to the name of the calling function.
239pub(crate) mod named {
240    use super::*;
241
242    /// Returns a uses step with the same name as the enclosing function.
243    /// (You shouldn't inline this function into the workflow definition, you must
244    /// wrap it in a new function.)
245    pub(crate) fn uses(owner: &str, repo: &str, ref_: &str) -> Step<Use> {
246        Step::new(function_name(1)).uses(owner, repo, ref_)
247    }
248
249    /// Returns a bash-script step with the same name as the enclosing function.
250    /// (You shouldn't inline this function into the workflow definition, you must
251    /// wrap it in a new function.)
252    pub(crate) fn bash(script: &str) -> Step<Run> {
253        Step::new(function_name(1)).run(script).shell(BASH_SHELL)
254    }
255
256    /// Returns a pwsh-script step with the same name as the enclosing function.
257    /// (You shouldn't inline this function into the workflow definition, you must
258    /// wrap it in a new function.)
259    pub(crate) fn pwsh(script: &str) -> Step<Run> {
260        Step::new(function_name(1)).run(script).shell(PWSH_SHELL)
261    }
262
263    /// Runs the command in either powershell or bash, depending on platform.
264    /// (You shouldn't inline this function into the workflow definition, you must
265    /// wrap it in a new function.)
266    pub(crate) fn run(platform: Platform, script: &str) -> Step<Run> {
267        match platform {
268            Platform::Windows => Step::new(function_name(1)).run(script).shell(PWSH_SHELL),
269            Platform::Linux | Platform::Mac => {
270                Step::new(function_name(1)).run(script).shell(BASH_SHELL)
271            }
272        }
273    }
274
275    /// Returns a Workflow with the same name as the enclosing module.
276    pub(crate) fn workflow() -> Workflow {
277        Workflow::default().name(
278            named::function_name(1)
279                .split("::")
280                .next()
281                .unwrap()
282                .to_owned(),
283        )
284    }
285
286    /// Returns a Job with the same name as the enclosing function.
287    /// (note job names may not contain `::`)
288    pub(crate) fn job(job: Job) -> NamedJob {
289        NamedJob {
290            name: function_name(1).split("::").last().unwrap().to_owned(),
291            job,
292        }
293    }
294
295    /// Returns the function name N callers above in the stack
296    /// (typically 1).
297    /// This only works because xtask always runs debug builds.
298    pub(crate) fn function_name(i: usize) -> String {
299        let mut name = "<unknown>".to_string();
300        let mut count = 0;
301        backtrace::trace(|frame| {
302            if count < i + 3 {
303                count += 1;
304                return true;
305            }
306            backtrace::resolve_frame(frame, |cb| {
307                if let Some(s) = cb.name() {
308                    name = s.to_string()
309                }
310            });
311            false
312        });
313        name.split("::")
314            .skip_while(|s| s != &"workflows")
315            .skip(1)
316            .collect::<Vec<_>>()
317            .join("::")
318    }
319}