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