steps.rs

  1use gh_workflow::*;
  2
  3use crate::tasks::workflows::{runners::Platform, vars, vars::StepOutput};
  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 checkout_repo_with_token(token: &StepOutput) -> Step<Use> {
 21    named::uses(
 22        "actions",
 23        "checkout",
 24        "11bd71901bbe5b1630ceea73d27597364c9af683", // v4
 25    )
 26    .add_with(("clean", false))
 27    .add_with(("token", token.to_string()))
 28}
 29
 30pub fn setup_pnpm() -> Step<Use> {
 31    named::uses(
 32        "pnpm",
 33        "action-setup",
 34        "fe02b34f77f8bc703788d5817da081398fad5dd2", // v4.0.0
 35    )
 36    .add_with(("version", "9"))
 37}
 38
 39pub fn setup_node() -> Step<Use> {
 40    named::uses(
 41        "actions",
 42        "setup-node",
 43        "49933ea5288caeca8642d1e84afbd3f7d6820020", // v4
 44    )
 45    .add_with(("node-version", "20"))
 46}
 47
 48pub fn setup_sentry() -> Step<Use> {
 49    named::uses(
 50        "matbour",
 51        "setup-sentry-cli",
 52        "3e938c54b3018bdd019973689ef984e033b0454b",
 53    )
 54    .add_with(("token", vars::SENTRY_AUTH_TOKEN))
 55}
 56
 57pub fn prettier() -> Step<Run> {
 58    named::bash("./script/prettier")
 59}
 60
 61pub fn cargo_fmt() -> Step<Run> {
 62    named::bash("cargo fmt --all -- --check")
 63}
 64
 65pub fn cargo_install_nextest() -> Step<Use> {
 66    named::uses("taiki-e", "install-action", "nextest")
 67}
 68
 69pub fn cargo_nextest(platform: Platform) -> Step<Run> {
 70    named::run(platform, "cargo nextest run --workspace --no-fail-fast")
 71}
 72
 73pub fn setup_cargo_config(platform: Platform) -> Step<Run> {
 74    match platform {
 75        Platform::Windows => named::pwsh(indoc::indoc! {r#"
 76            New-Item -ItemType Directory -Path "./../.cargo" -Force
 77            Copy-Item -Path "./.cargo/ci-config.toml" -Destination "./../.cargo/config.toml"
 78        "#}),
 79
 80        Platform::Linux | Platform::Mac => named::bash(indoc::indoc! {r#"
 81            mkdir -p ./../.cargo
 82            cp ./.cargo/ci-config.toml ./../.cargo/config.toml
 83        "#}),
 84    }
 85}
 86
 87pub fn cleanup_cargo_config(platform: Platform) -> Step<Run> {
 88    let step = match platform {
 89        Platform::Windows => named::pwsh(indoc::indoc! {r#"
 90            Remove-Item -Recurse -Path "./../.cargo" -Force -ErrorAction SilentlyContinue
 91        "#}),
 92        Platform::Linux | Platform::Mac => named::bash(indoc::indoc! {r#"
 93            rm -rf ./../.cargo
 94        "#}),
 95    };
 96
 97    step.if_condition(Expression::new("always()"))
 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 250"),
104        Platform::Mac => named::bash("./script/clear-target-dir-if-larger-than 300"),
105    }
106}
107
108pub 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 fn cache_rust_dependencies_namespace() -> Step<Use> {
116    named::uses("namespacelabs", "nscloud-cache-action", "v1")
117        .add_with(("cache", "rust"))
118        .add_with(("path", "~/.rustup"))
119}
120
121pub fn setup_linux() -> Step<Run> {
122    named::bash("./script/linux")
123}
124
125fn install_mold() -> Step<Run> {
126    named::bash("./script/install-mold")
127}
128
129fn download_wasi_sdk() -> Step<Run> {
130    named::bash("./script/download-wasi-sdk")
131}
132
133pub(crate) fn install_linux_dependencies(job: Job) -> Job {
134    job.add_step(setup_linux())
135        .add_step(install_mold())
136        .add_step(download_wasi_sdk())
137}
138
139pub fn script(name: &str) -> Step<Run> {
140    if name.ends_with(".ps1") {
141        Step::new(name).run(name).shell(PWSH_SHELL)
142    } else {
143        Step::new(name).run(name).shell(BASH_SHELL)
144    }
145}
146
147pub struct NamedJob<J: JobType = RunJob> {
148    pub name: String,
149    pub job: Job<J>,
150}
151
152// impl NamedJob {
153//     pub fn map(self, f: impl FnOnce(Job) -> Job) -> Self {
154//         NamedJob {
155//             name: self.name,
156//             job: f(self.job),
157//         }
158//     }
159// }
160
161pub(crate) const DEFAULT_REPOSITORY_OWNER_GUARD: &str =
162    "(github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions')";
163
164pub fn repository_owner_guard_expression(trigger_always: bool) -> Expression {
165    Expression::new(format!(
166        "{}{}",
167        DEFAULT_REPOSITORY_OWNER_GUARD,
168        trigger_always.then_some(" && always()").unwrap_or_default()
169    ))
170}
171
172pub trait CommonJobConditions: Sized {
173    fn with_repository_owner_guard(self) -> Self;
174}
175
176impl CommonJobConditions for Job {
177    fn with_repository_owner_guard(self) -> Self {
178        self.cond(repository_owner_guard_expression(false))
179    }
180}
181
182pub(crate) fn release_job(deps: &[&NamedJob]) -> Job {
183    dependant_job(deps)
184        .with_repository_owner_guard()
185        .timeout_minutes(60u32)
186}
187
188pub(crate) fn dependant_job(deps: &[&NamedJob]) -> Job {
189    let job = Job::default();
190    if deps.len() > 0 {
191        job.needs(deps.iter().map(|j| j.name.clone()).collect::<Vec<_>>())
192    } else {
193        job
194    }
195}
196
197impl FluentBuilder for Job {}
198impl FluentBuilder for Workflow {}
199impl FluentBuilder for Input {}
200
201/// A helper trait for building complex objects with imperative conditionals in a fluent style.
202/// Copied from GPUI to avoid adding GPUI as dependency
203/// todo(ci) just put this in gh-workflow
204#[allow(unused)]
205pub trait FluentBuilder {
206    /// Imperatively modify self with the given closure.
207    fn map<U>(self, f: impl FnOnce(Self) -> U) -> U
208    where
209        Self: Sized,
210    {
211        f(self)
212    }
213
214    /// Conditionally modify self with the given closure.
215    fn when(self, condition: bool, then: impl FnOnce(Self) -> Self) -> Self
216    where
217        Self: Sized,
218    {
219        self.map(|this| if condition { then(this) } else { this })
220    }
221
222    /// Conditionally modify self with the given closure.
223    fn when_else(
224        self,
225        condition: bool,
226        then: impl FnOnce(Self) -> Self,
227        else_fn: impl FnOnce(Self) -> Self,
228    ) -> Self
229    where
230        Self: Sized,
231    {
232        self.map(|this| if condition { then(this) } else { else_fn(this) })
233    }
234
235    /// Conditionally unwrap and modify self with the given closure, if the given option is Some.
236    fn when_some<T>(self, option: Option<T>, then: impl FnOnce(Self, T) -> Self) -> Self
237    where
238        Self: Sized,
239    {
240        self.map(|this| {
241            if let Some(value) = option {
242                then(this, value)
243            } else {
244                this
245            }
246        })
247    }
248    /// Conditionally unwrap and modify self with the given closure, if the given option is None.
249    fn when_none<T>(self, option: &Option<T>, then: impl FnOnce(Self) -> Self) -> Self
250    where
251        Self: Sized,
252    {
253        self.map(|this| if option.is_some() { this } else { then(this) })
254    }
255}
256
257// (janky) helper to generate steps with a name that corresponds
258// to the name of the calling function.
259pub mod named {
260    use super::*;
261
262    /// Returns a uses step with the same name as the enclosing function.
263    /// (You shouldn't inline this function into the workflow definition, you must
264    /// wrap it in a new function.)
265    pub fn uses(owner: &str, repo: &str, ref_: &str) -> Step<Use> {
266        Step::new(function_name(1)).uses(owner, repo, ref_)
267    }
268
269    /// Returns a bash-script step with the same name as the enclosing function.
270    /// (You shouldn't inline this function into the workflow definition, you must
271    /// wrap it in a new function.)
272    pub fn bash(script: impl AsRef<str>) -> Step<Run> {
273        Step::new(function_name(1))
274            .run(script.as_ref())
275            .shell(BASH_SHELL)
276    }
277
278    /// Returns a pwsh-script step with the same name as the enclosing function.
279    /// (You shouldn't inline this function into the workflow definition, you must
280    /// wrap it in a new function.)
281    pub fn pwsh(script: &str) -> Step<Run> {
282        Step::new(function_name(1)).run(script).shell(PWSH_SHELL)
283    }
284
285    /// Runs the command in either powershell or bash, depending on platform.
286    /// (You shouldn't inline this function into the workflow definition, you must
287    /// wrap it in a new function.)
288    pub fn run(platform: Platform, script: &str) -> Step<Run> {
289        match platform {
290            Platform::Windows => Step::new(function_name(1)).run(script).shell(PWSH_SHELL),
291            Platform::Linux | Platform::Mac => {
292                Step::new(function_name(1)).run(script).shell(BASH_SHELL)
293            }
294        }
295    }
296
297    /// Returns a Workflow with the same name as the enclosing module.
298    pub fn workflow() -> Workflow {
299        Workflow::default().name(
300            named::function_name(1)
301                .split("::")
302                .collect::<Vec<_>>()
303                .into_iter()
304                .rev()
305                .skip(1)
306                .rev()
307                .collect::<Vec<_>>()
308                .join("::"),
309        )
310    }
311
312    /// Returns a Job with the same name as the enclosing function.
313    /// (note job names may not contain `::`)
314    pub fn job<J: JobType>(job: Job<J>) -> NamedJob<J> {
315        NamedJob {
316            name: function_name(1).split("::").last().unwrap().to_owned(),
317            job,
318        }
319    }
320
321    /// Returns the function name N callers above in the stack
322    /// (typically 1).
323    /// This only works because xtask always runs debug builds.
324    pub fn function_name(i: usize) -> String {
325        let mut name = "<unknown>".to_string();
326        let mut count = 0;
327        backtrace::trace(|frame| {
328            if count < i + 3 {
329                count += 1;
330                return true;
331            }
332            backtrace::resolve_frame(frame, |cb| {
333                if let Some(s) = cb.name() {
334                    name = s.to_string()
335                }
336            });
337            false
338        });
339
340        name.split("::")
341            .skip_while(|s| s != &"workflows")
342            .skip(1)
343            .collect::<Vec<_>>()
344            .join("::")
345    }
346}
347
348pub fn git_checkout(ref_name: &dyn std::fmt::Display) -> Step<Run> {
349    named::bash(&format!(
350        "git fetch origin {ref_name} && git checkout {ref_name}"
351    ))
352}
353
354pub fn authenticate_as_zippy() -> (Step<Use>, StepOutput) {
355    let step = named::uses(
356        "actions",
357        "create-github-app-token",
358        "bef1eaf1c0ac2b148ee2a0a74c65fbe6db0631f1",
359    )
360    .add_with(("app-id", vars::ZED_ZIPPY_APP_ID))
361    .add_with(("private-key", vars::ZED_ZIPPY_APP_PRIVATE_KEY))
362    .id("get-app-token");
363    let output = StepOutput::new(&step, "token");
364    (step, output)
365}