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