1use gh_workflow::{ctx::Context, *};
2use serde_json::Value;
3
4use crate::tasks::workflows::{
5 runners::Platform,
6 steps::named::function_name,
7 vars::{self, StepOutput},
8};
9
10pub(crate) fn use_clang(job: Job) -> Job {
11 job.add_env(Env::new("CC", "clang"))
12 .add_env(Env::new("CXX", "clang++"))
13}
14
15const SCCACHE_R2_BUCKET: &str = "sccache-zed";
16
17pub(crate) const BASH_SHELL: &str = "bash -euxo pipefail {0}";
18// https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax#jobsjob_idstepsshell
19pub const PWSH_SHELL: &str = "pwsh";
20
21pub(crate) struct Nextest(Step<Run>);
22
23pub(crate) fn cargo_nextest(platform: Platform) -> Nextest {
24 Nextest(named::run(
25 platform,
26 "cargo nextest run --workspace --no-fail-fast --no-tests=warn",
27 ))
28}
29
30impl Nextest {
31 #[allow(dead_code)]
32 pub(crate) fn with_filter_expr(mut self, filter_expr: &str) -> Self {
33 if let Some(nextest_command) = self.0.value.run.as_mut() {
34 nextest_command.push_str(&format!(r#" -E "{filter_expr}""#));
35 }
36 self
37 }
38
39 pub(crate) fn with_changed_packages_filter(mut self, orchestrate_job: &str) -> Self {
40 if let Some(nextest_command) = self.0.value.run.as_mut() {
41 nextest_command.push_str(&format!(
42 r#"${{{{ needs.{orchestrate_job}.outputs.changed_packages && format(' -E "{{0}}"', needs.{orchestrate_job}.outputs.changed_packages) || '' }}}}"#
43 ));
44 }
45 self
46 }
47}
48
49impl From<Nextest> for Step<Run> {
50 fn from(value: Nextest) -> Self {
51 value.0
52 }
53}
54
55#[derive(Default)]
56enum FetchDepth {
57 #[default]
58 Shallow,
59 Full,
60 Custom(serde_json::Value),
61}
62
63#[derive(Default)]
64pub(crate) struct CheckoutStep {
65 fetch_depth: FetchDepth,
66 name: Option<String>,
67 token: Option<String>,
68 path: Option<String>,
69 repository: Option<String>,
70 ref_: Option<String>,
71}
72
73impl CheckoutStep {
74 pub fn with_full_history(mut self) -> Self {
75 self.fetch_depth = FetchDepth::Full;
76 self
77 }
78
79 pub fn with_custom_name(mut self, name: &str) -> Self {
80 self.name = Some(name.to_string());
81 self
82 }
83
84 pub fn with_custom_fetch_depth(mut self, fetch_depth: impl Into<Value>) -> Self {
85 self.fetch_depth = FetchDepth::Custom(fetch_depth.into());
86 self
87 }
88
89 /// Sets `fetch-depth` to `2` on the main branch and `350` on all other branches.
90 pub fn with_deep_history_on_non_main(self) -> Self {
91 self.with_custom_fetch_depth("${{ github.ref == 'refs/heads/main' && 2 || 350 }}")
92 }
93
94 pub fn with_token(mut self, token: &StepOutput) -> Self {
95 self.token = Some(token.to_string());
96 self
97 }
98
99 pub fn with_path(mut self, path: &str) -> Self {
100 self.path = Some(path.to_string());
101 self
102 }
103
104 pub fn with_repository(mut self, repository: &str) -> Self {
105 self.repository = Some(repository.to_string());
106 self
107 }
108
109 pub fn with_ref(mut self, ref_: impl ToString) -> Self {
110 self.ref_ = Some(ref_.to_string());
111 self
112 }
113}
114
115impl From<CheckoutStep> for Step<Use> {
116 fn from(value: CheckoutStep) -> Self {
117 Step::new(value.name.unwrap_or("steps::checkout_repo".to_string()))
118 .uses(
119 "actions",
120 "checkout",
121 "93cb6efe18208431cddfb8368fd83d5badbf9bfd", // v5.0.1
122 )
123 // prevent checkout action from running `git clean -ffdx` which
124 // would delete the target directory
125 .add_with(("clean", false))
126 .map(|step| match value.fetch_depth {
127 FetchDepth::Shallow => step,
128 FetchDepth::Full => step.add_with(("fetch-depth", 0)),
129 FetchDepth::Custom(depth) => step.add_with(("fetch-depth", depth)),
130 })
131 .when_some(value.path, |step, path| step.add_with(("path", path)))
132 .when_some(value.repository, |step, repository| {
133 step.add_with(("repository", repository))
134 })
135 .when_some(value.ref_, |step, ref_| step.add_with(("ref", ref_)))
136 .when_some(value.token, |step, token| step.add_with(("token", token)))
137 }
138}
139
140pub fn checkout_repo() -> CheckoutStep {
141 CheckoutStep::default()
142}
143
144pub fn setup_pnpm() -> Step<Use> {
145 named::uses(
146 "pnpm",
147 "action-setup",
148 "fe02b34f77f8bc703788d5817da081398fad5dd2", // v4.0.0
149 )
150 .add_with(("version", "9"))
151}
152
153pub fn setup_node() -> Step<Use> {
154 named::uses(
155 "actions",
156 "setup-node",
157 "49933ea5288caeca8642d1e84afbd3f7d6820020", // v4
158 )
159 .add_with(("node-version", "20"))
160}
161
162pub fn setup_sentry() -> Step<Use> {
163 named::uses(
164 "matbour",
165 "setup-sentry-cli",
166 "3e938c54b3018bdd019973689ef984e033b0454b",
167 )
168 .add_with(("token", vars::SENTRY_AUTH_TOKEN))
169}
170
171pub fn prettier() -> Step<Run> {
172 named::bash("./script/prettier")
173}
174
175pub fn cargo_fmt() -> Step<Run> {
176 named::bash("cargo fmt --all -- --check")
177}
178
179pub fn install_cargo_edit() -> Step<Use> {
180 taiki_install_action("cargo-edit")
181}
182
183pub fn taiki_install_action(tool: &str) -> Step<Use> {
184 Step::new(named::function_name(1))
185 .uses(
186 "taiki-e",
187 "install-action",
188 "02cc5f8ca9f2301050c0c099055816a41ee05507", // v2
189 )
190 .add_with(("tool", tool))
191}
192
193pub fn cargo_install_nextest() -> Step<Use> {
194 named::uses(
195 "taiki-e",
196 "install-action",
197 "921e2c9f7148d7ba14cd819f417db338f63e733c", // nextest
198 )
199}
200
201pub fn setup_cargo_config(platform: Platform) -> Step<Run> {
202 match platform {
203 Platform::Windows => named::pwsh(indoc::indoc! {r#"
204 New-Item -ItemType Directory -Path "./../.cargo" -Force
205 Copy-Item -Path "./.cargo/ci-config.toml" -Destination "./../.cargo/config.toml"
206 "#}),
207
208 Platform::Linux | Platform::Mac => named::bash(indoc::indoc! {r#"
209 mkdir -p ./../.cargo
210 cp ./.cargo/ci-config.toml ./../.cargo/config.toml
211 "#}),
212 }
213}
214
215pub fn cleanup_cargo_config(platform: Platform) -> Step<Run> {
216 let step = match platform {
217 Platform::Windows => named::pwsh(indoc::indoc! {r#"
218 Remove-Item -Recurse -Path "./../.cargo" -Force -ErrorAction SilentlyContinue
219 "#}),
220 Platform::Linux | Platform::Mac => named::bash(indoc::indoc! {r#"
221 rm -rf ./../.cargo
222 "#}),
223 };
224
225 step.if_condition(Expression::new("always()"))
226}
227
228pub fn clear_target_dir_if_large(platform: Platform) -> Step<Run> {
229 match platform {
230 Platform::Windows => named::pwsh("./script/clear-target-dir-if-larger-than.ps1 350 200"),
231 Platform::Linux => named::bash("./script/clear-target-dir-if-larger-than 350 200"),
232 Platform::Mac => named::bash("./script/clear-target-dir-if-larger-than 350 200"),
233 }
234}
235
236pub fn clippy(platform: Platform, target: Option<&str>) -> Step<Run> {
237 match platform {
238 Platform::Windows => named::pwsh("./script/clippy.ps1"),
239 _ => match target {
240 Some(target) => named::bash(format!("./script/clippy --target {target}")),
241 None => named::bash("./script/clippy"),
242 },
243 }
244}
245
246pub fn install_rustup_target(target: &str) -> Step<Run> {
247 named::bash(format!("rustup target add {target}"))
248}
249
250pub fn cache_rust_dependencies_namespace() -> Step<Use> {
251 named::uses(
252 "namespacelabs",
253 "nscloud-cache-action",
254 "a90bb5d4b27522ce881c6e98eebd7d7e6d1653f9", // v1
255 )
256 .add_with(("cache", "rust"))
257 .add_with(("path", "~/.rustup"))
258}
259
260pub fn setup_sccache(platform: Platform) -> Step<Run> {
261 let step = match platform {
262 Platform::Windows => named::pwsh("./script/setup-sccache.ps1"),
263 Platform::Linux | Platform::Mac => named::bash("./script/setup-sccache"),
264 };
265 step.add_env(("R2_ACCOUNT_ID", vars::R2_ACCOUNT_ID))
266 .add_env(("R2_ACCESS_KEY_ID", vars::R2_ACCESS_KEY_ID))
267 .add_env(("R2_SECRET_ACCESS_KEY", vars::R2_SECRET_ACCESS_KEY))
268 .add_env(("SCCACHE_BUCKET", SCCACHE_R2_BUCKET))
269}
270
271pub fn show_sccache_stats(platform: Platform) -> Step<Run> {
272 match platform {
273 // Use $env:RUSTC_WRAPPER (absolute path) because GITHUB_PATH changes
274 // don't take effect until the next step in PowerShell.
275 // Check if RUSTC_WRAPPER is set first (it won't be for fork PRs without secrets).
276 Platform::Windows => {
277 named::pwsh("if ($env:RUSTC_WRAPPER) { & $env:RUSTC_WRAPPER --show-stats }; exit 0")
278 }
279 Platform::Linux | Platform::Mac => named::bash("sccache --show-stats || true"),
280 }
281}
282
283pub fn cache_nix_dependencies_namespace() -> Step<Use> {
284 named::uses(
285 "namespacelabs",
286 "nscloud-cache-action",
287 "a90bb5d4b27522ce881c6e98eebd7d7e6d1653f9", // v1
288 )
289 .add_with(("cache", "nix"))
290}
291
292pub fn cache_nix_store_macos() -> Step<Use> {
293 // On macOS, `/nix` is on a read-only root filesystem so nscloud's `cache: nix`
294 // cannot mount or symlink there. Instead we cache a user-writable directory and
295 // use nix-store --import/--export in separate steps to transfer store paths.
296 named::uses(
297 "namespacelabs",
298 "nscloud-cache-action",
299 "a90bb5d4b27522ce881c6e98eebd7d7e6d1653f9", // v1
300 )
301 .add_with(("path", "~/nix-cache"))
302}
303
304pub fn setup_linux() -> Step<Run> {
305 named::bash("./script/linux")
306}
307
308fn download_wasi_sdk() -> Step<Run> {
309 named::bash("./script/download-wasi-sdk")
310}
311
312pub(crate) fn install_linux_dependencies(job: Job) -> Job {
313 job.add_step(setup_linux()).add_step(download_wasi_sdk())
314}
315
316pub fn script(name: &str) -> Step<Run> {
317 if name.ends_with(".ps1") {
318 Step::new(name).run(name).shell(PWSH_SHELL)
319 } else {
320 Step::new(name).run(name)
321 }
322}
323
324pub struct NamedJob<J: JobType = RunJob> {
325 pub name: String,
326 pub job: Job<J>,
327}
328
329// impl NamedJob {
330// pub fn map(self, f: impl FnOnce(Job) -> Job) -> Self {
331// NamedJob {
332// name: self.name,
333// job: f(self.job),
334// }
335// }
336// }
337
338pub(crate) const DEFAULT_REPOSITORY_OWNER_GUARD: &str =
339 "(github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions')";
340
341pub fn repository_owner_guard_expression(trigger_always: bool) -> Expression {
342 Expression::new(format!(
343 "{}{}",
344 DEFAULT_REPOSITORY_OWNER_GUARD,
345 trigger_always.then_some(" && always()").unwrap_or_default()
346 ))
347}
348
349pub trait CommonJobConditions: Sized {
350 fn with_repository_owner_guard(self) -> Self;
351}
352
353impl CommonJobConditions for Job {
354 fn with_repository_owner_guard(self) -> Self {
355 self.cond(repository_owner_guard_expression(false))
356 }
357}
358
359pub(crate) fn release_job(deps: &[&NamedJob]) -> Job {
360 dependant_job(deps)
361 .with_repository_owner_guard()
362 .timeout_minutes(60u32)
363}
364
365pub(crate) fn dependant_job(deps: &[&NamedJob]) -> Job {
366 let job = Job::default();
367 if deps.len() > 0 {
368 job.needs(deps.iter().map(|j| j.name.clone()).collect::<Vec<_>>())
369 } else {
370 job
371 }
372}
373
374impl FluentBuilder for Job {}
375impl FluentBuilder for Workflow {}
376impl FluentBuilder for Input {}
377impl<T> FluentBuilder for Step<T> {}
378
379/// A helper trait for building complex objects with imperative conditionals in a fluent style.
380/// Copied from GPUI to avoid adding GPUI as dependency
381/// todo(ci) just put this in gh-workflow
382#[allow(unused)]
383pub trait FluentBuilder {
384 /// Imperatively modify self with the given closure.
385 fn map<U>(self, f: impl FnOnce(Self) -> U) -> U
386 where
387 Self: Sized,
388 {
389 f(self)
390 }
391
392 /// Conditionally modify self with the given closure.
393 fn when(self, condition: bool, then: impl FnOnce(Self) -> Self) -> Self
394 where
395 Self: Sized,
396 {
397 self.map(|this| if condition { then(this) } else { this })
398 }
399
400 /// Conditionally modify self with the given closure.
401 fn when_else(
402 self,
403 condition: bool,
404 then: impl FnOnce(Self) -> Self,
405 else_fn: impl FnOnce(Self) -> Self,
406 ) -> Self
407 where
408 Self: Sized,
409 {
410 self.map(|this| if condition { then(this) } else { else_fn(this) })
411 }
412
413 /// Conditionally unwrap and modify self with the given closure, if the given option is Some.
414 fn when_some<T>(self, option: Option<T>, then: impl FnOnce(Self, T) -> Self) -> Self
415 where
416 Self: Sized,
417 {
418 self.map(|this| {
419 if let Some(value) = option {
420 then(this, value)
421 } else {
422 this
423 }
424 })
425 }
426 /// Conditionally unwrap and modify self with the given closure, if the given option is None.
427 fn when_none<T>(self, option: &Option<T>, then: impl FnOnce(Self) -> Self) -> Self
428 where
429 Self: Sized,
430 {
431 self.map(|this| if option.is_some() { this } else { then(this) })
432 }
433}
434
435// (janky) helper to generate steps with a name that corresponds
436// to the name of the calling function.
437pub mod named {
438 use super::*;
439
440 /// Returns a uses step with the same name as the enclosing function.
441 /// (You shouldn't inline this function into the workflow definition, you must
442 /// wrap it in a new function.)
443 pub fn uses(owner: &str, repo: &str, ref_: &str) -> Step<Use> {
444 Step::new(function_name(1)).uses(owner, repo, ref_)
445 }
446
447 /// Returns a bash-script step with the same name as the enclosing function.
448 /// (You shouldn't inline this function into the workflow definition, you must
449 /// wrap it in a new function.)
450 pub fn bash(script: impl AsRef<str>) -> Step<Run> {
451 Step::new(function_name(1)).run(script.as_ref())
452 }
453
454 /// Returns a pwsh-script step with the same name as the enclosing function.
455 /// (You shouldn't inline this function into the workflow definition, you must
456 /// wrap it in a new function.)
457 pub fn pwsh(script: &str) -> Step<Run> {
458 Step::new(function_name(1)).run(script).shell(PWSH_SHELL)
459 }
460
461 /// Runs the command in either powershell or bash, depending on platform.
462 /// (You shouldn't inline this function into the workflow definition, you must
463 /// wrap it in a new function.)
464 pub fn run(platform: Platform, script: &str) -> Step<Run> {
465 match platform {
466 Platform::Windows => Step::new(function_name(1)).run(script).shell(PWSH_SHELL),
467 Platform::Linux | Platform::Mac => Step::new(function_name(1)).run(script),
468 }
469 }
470
471 /// Returns a Workflow with the same name as the enclosing module with default
472 /// set for the running shell.
473 pub fn workflow() -> Workflow {
474 Workflow::default()
475 .name(
476 named::function_name(1)
477 .split("::")
478 .collect::<Vec<_>>()
479 .into_iter()
480 .rev()
481 .skip(1)
482 .rev()
483 .collect::<Vec<_>>()
484 .join("::"),
485 )
486 .defaults(Defaults::default().run(RunDefaults::default().shell(BASH_SHELL)))
487 }
488
489 /// Returns a Job with the same name as the enclosing function.
490 /// (note job names may not contain `::`)
491 pub fn job<J: JobType>(job: Job<J>) -> NamedJob<J> {
492 NamedJob {
493 name: function_name(1).split("::").last().unwrap().to_owned(),
494 job,
495 }
496 }
497
498 /// Returns the function name N callers above in the stack
499 /// (typically 1).
500 /// This only works because xtask always runs debug builds.
501 pub fn function_name(i: usize) -> String {
502 let mut name = "<unknown>".to_string();
503 let mut count = 0;
504 backtrace::trace(|frame| {
505 if count < i + 3 {
506 count += 1;
507 return true;
508 }
509 backtrace::resolve_frame(frame, |cb| {
510 if let Some(s) = cb.name() {
511 name = s.to_string()
512 }
513 });
514 false
515 });
516
517 name.split("::")
518 .skip_while(|s| s != &"workflows")
519 .skip(1)
520 .collect::<Vec<_>>()
521 .join("::")
522 }
523}
524
525pub fn git_checkout(ref_name: &dyn std::fmt::Display) -> Step<Run> {
526 named::bash(r#"git fetch origin "$REF_NAME" && git checkout "$REF_NAME""#)
527 .add_env(("REF_NAME", ref_name.to_string()))
528}
529
530/// Non-exhaustive list of the permissions to be set for a GitHub app token.
531///
532/// See https://github.com/actions/create-github-app-token?tab=readme-ov-file#permission-permission-name
533/// and beyond for a full list of available permissions.
534#[allow(unused)]
535pub(crate) enum TokenPermissions {
536 Contents,
537 Issues,
538 PullRequests,
539 Workflows,
540}
541
542impl TokenPermissions {
543 pub fn environment_name(&self) -> &'static str {
544 match self {
545 TokenPermissions::Contents => "permission-contents",
546 TokenPermissions::Issues => "permission-issues",
547 TokenPermissions::PullRequests => "permission-pull-requests",
548 TokenPermissions::Workflows => "permission-workflows",
549 }
550 }
551}
552
553pub(crate) struct GenerateAppToken<'a> {
554 job_name: String,
555 app_id: &'a str,
556 app_secret: &'a str,
557 repository_target: Option<RepositoryTarget>,
558 permissions: Option<Vec<(TokenPermissions, Level)>>,
559}
560
561impl<'a> GenerateAppToken<'a> {
562 pub fn for_repository(self, repository_target: RepositoryTarget) -> Self {
563 Self {
564 repository_target: Some(repository_target),
565 ..self
566 }
567 }
568
569 pub fn with_permissions(self, permissions: impl Into<Vec<(TokenPermissions, Level)>>) -> Self {
570 Self {
571 permissions: Some(permissions.into()),
572 ..self
573 }
574 }
575}
576
577impl<'a> From<GenerateAppToken<'a>> for (Step<Use>, StepOutput) {
578 fn from(token: GenerateAppToken<'a>) -> Self {
579 let step = Step::new(token.job_name)
580 .uses(
581 "actions",
582 "create-github-app-token",
583 "f8d387b68d61c58ab83c6c016672934102569859",
584 )
585 .id("generate-token")
586 .add_with(
587 Input::default()
588 .add("app-id", token.app_id)
589 .add("private-key", token.app_secret)
590 .when_some(
591 token.repository_target,
592 |input,
593 RepositoryTarget {
594 owner,
595 repositories,
596 }| {
597 input
598 .when_some(owner, |input, owner| input.add("owner", owner))
599 .when_some(repositories, |input, repositories| {
600 input.add("repositories", repositories)
601 })
602 },
603 )
604 .when_some(token.permissions, |input, permissions| {
605 permissions
606 .into_iter()
607 .fold(input, |input, (permission, level)| {
608 input.add(
609 permission.environment_name(),
610 serde_json::to_value(&level).unwrap_or_default(),
611 )
612 })
613 }),
614 );
615
616 let generated_token = StepOutput::new(&step, "token");
617 (step, generated_token)
618 }
619}
620
621pub(crate) struct RepositoryTarget {
622 owner: Option<String>,
623 repositories: Option<String>,
624}
625
626impl RepositoryTarget {
627 pub fn new<T: ToString>(owner: T, repositories: &[&str]) -> Self {
628 Self {
629 owner: Some(owner.to_string()),
630 repositories: Some(repositories.join("\n")),
631 }
632 }
633
634 pub fn current() -> Self {
635 Self {
636 owner: None,
637 repositories: None,
638 }
639 }
640}
641
642pub(crate) fn generate_token<'a>(
643 app_id_source: &'a str,
644 app_secret_source: &'a str,
645) -> GenerateAppToken<'a> {
646 generate_token_with_job_name(app_id_source, app_secret_source)
647}
648
649pub fn authenticate_as_zippy() -> GenerateAppToken<'static> {
650 generate_token_with_job_name(vars::ZED_ZIPPY_APP_ID, vars::ZED_ZIPPY_APP_PRIVATE_KEY)
651}
652
653fn generate_token_with_job_name<'a>(
654 app_id_source: &'a str,
655 app_secret_source: &'a str,
656) -> GenerateAppToken<'a> {
657 GenerateAppToken {
658 job_name: function_name(1),
659 app_id: app_id_source,
660 app_secret: app_secret_source,
661 repository_target: None,
662 permissions: None,
663 }
664}
665
666pub(crate) struct BotCommitStep {
667 message: String,
668 branch: String,
669 files: String,
670 token: String,
671}
672
673impl BotCommitStep {
674 pub fn new(message: impl ToString, branch: impl ToString, token: &StepOutput) -> Self {
675 Self {
676 message: message.to_string(),
677 branch: branch.to_string(),
678 files: "**".to_string(),
679 token: token.to_string(),
680 }
681 }
682
683 pub fn with_files(self, files: impl ToString) -> Self {
684 Self {
685 files: files.to_string(),
686 ..self
687 }
688 }
689}
690
691impl From<BotCommitStep> for Step<Use> {
692 fn from(step: BotCommitStep) -> Self {
693 Step::new("steps::bot_commit")
694 .uses(
695 "IAreKyleW00t",
696 "verified-bot-commit",
697 "126a6a11889ab05bcff72ec2403c326cd249b84c", // v2.3.0
698 )
699 .id("commit")
700 .add_with(("message", step.message))
701 .add_with(("ref", format!("refs/heads/{}", step.branch)))
702 .add_with(("files", step.files))
703 .add_with(("token", step.token))
704 }
705}
706
707pub(crate) enum GitRef {
708 Tag(String),
709 Branch(String),
710}
711
712impl GitRef {
713 pub fn tag(name: impl ToString) -> Self {
714 Self::Tag(name.to_string())
715 }
716
717 pub fn branch(name: impl ToString) -> Self {
718 Self::Branch(name.to_string())
719 }
720
721 fn create_ref_path(&self) -> String {
722 match self {
723 Self::Tag(name) => format!("refs/tags/{name}"),
724 Self::Branch(name) => format!("refs/heads/{name}"),
725 }
726 }
727
728 fn update_ref_path(&self) -> String {
729 match self {
730 Self::Tag(name) => format!("tags/{name}"),
731 Self::Branch(name) => format!("heads/{name}"),
732 }
733 }
734
735 fn kind(&self) -> &'static str {
736 match self {
737 Self::Tag(_) => "tag",
738 Self::Branch(_) => "branch",
739 }
740 }
741}
742
743#[allow(unused)]
744enum RefOperation {
745 Create,
746 Update { force: bool },
747}
748
749struct RefOp {
750 git_ref: GitRef,
751 operation: RefOperation,
752 sha: String,
753 token: String,
754}
755
756impl From<RefOp> for Step<Use> {
757 fn from(op: RefOp) -> Self {
758 let (api_method, ref_path, force_line) = match &op.operation {
759 RefOperation::Create => ("createRef", op.git_ref.create_ref_path(), String::new()),
760 RefOperation::Update { force } => (
761 "updateRef",
762 op.git_ref.update_ref_path(),
763 format!(",\n force: {force}"),
764 ),
765 };
766 let step_name = match &op.operation {
767 RefOperation::Create => format!("steps::create_{}", op.git_ref.kind()),
768 RefOperation::Update { .. } => format!("steps::update_{}", op.git_ref.kind()),
769 };
770 let sha = &op.sha;
771 let script = indoc::formatdoc! {r#"
772 github.rest.git.{api_method}({{
773 owner: context.repo.owner,
774 repo: context.repo.repo,
775 ref: '{ref_path}',
776 sha: '{sha}'{force_line}
777 }})
778 "#};
779 Step::new(step_name)
780 .uses(
781 "actions",
782 "github-script",
783 "f28e40c7f34bde8b3046d885e986cb6290c5673b", // v7
784 )
785 .with(
786 Input::default()
787 .add("script", script)
788 .add("github-token", op.token),
789 )
790 }
791}
792
793pub(crate) fn create_ref(
794 git_ref: GitRef,
795 sha: impl ToString,
796 token: &StepOutput,
797) -> impl Into<Step<Use>> {
798 RefOp {
799 git_ref,
800 operation: RefOperation::Create,
801 sha: sha.to_string(),
802 token: token.to_string(),
803 }
804}
805
806#[allow(unused)]
807pub(crate) fn update_ref(
808 git_ref: GitRef,
809 sha: impl ToString,
810 token: &StepOutput,
811 force: bool,
812) -> impl Into<Step<Use>> {
813 RefOp {
814 git_ref,
815 operation: RefOperation::Update { force },
816 sha: sha.to_string(),
817 token: token.to_string(),
818 }
819}
820
821const ZED_ZIPPY_COMMITTER: &str =
822 "zed-zippy[bot] <234243425+zed-zippy[bot]@users.noreply.github.com>";
823
824pub(crate) struct CreatePrStep {
825 title: String,
826 body: String,
827 branch: String,
828 base: String,
829 token: String,
830 assignees: Option<String>,
831 labels: Option<String>,
832 path: Option<String>,
833}
834
835impl CreatePrStep {
836 pub fn new(title: impl ToString, branch: impl ToString, token: &StepOutput) -> Self {
837 Self {
838 title: title.to_string(),
839 body: "Release Notes:\n\n- N/A".to_string(),
840 branch: branch.to_string(),
841 base: "main".to_string(),
842 token: token.to_string(),
843 assignees: Some(Context::github().actor().to_string()),
844 labels: None,
845 path: None,
846 }
847 }
848
849 pub fn with_body(self, body: impl ToString) -> Self {
850 Self {
851 body: body.to_string(),
852 ..self
853 }
854 }
855
856 pub fn with_assignee(self, assignee: impl ToString) -> Self {
857 Self {
858 assignees: Some(assignee.to_string()),
859 ..self
860 }
861 }
862
863 pub fn with_labels(self, labels: impl ToString) -> Self {
864 Self {
865 labels: Some(labels.to_string()),
866 ..self
867 }
868 }
869
870 pub fn with_path(self, path: impl ToString) -> Self {
871 Self {
872 path: Some(path.to_string()),
873 ..self
874 }
875 }
876}
877
878impl From<CreatePrStep> for Step<Use> {
879 fn from(step: CreatePrStep) -> Self {
880 Step::new("steps::create_pull_request")
881 .uses(
882 "peter-evans",
883 "create-pull-request",
884 "98357b18bf14b5342f975ff684046ec3b2a07725", // v7
885 )
886 .add_with(("title", step.title.clone()))
887 .add_with(("body", step.body))
888 .add_with(("commit-message", step.title))
889 .add_with(("branch", step.branch))
890 .add_with(("committer", ZED_ZIPPY_COMMITTER))
891 .add_with(("author", ZED_ZIPPY_COMMITTER))
892 .add_with(("base", step.base))
893 .add_with(("delete-branch", true))
894 .add_with(("token", step.token))
895 .add_with(("sign-commits", true))
896 .when_some(step.assignees, |s, v| s.add_with(("assignees", v)))
897 .when_some(step.labels, |s, v| s.add_with(("labels", v)))
898 .when_some(step.path, |s, v| s.add_with(("path", v)))
899 }
900}