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