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