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