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