1use super::{
4 check_push_needed, get_current_branch, git, is_workflow_scope_error, rebase_on_branch,
5 strip_workflow_files,
6};
7use crate::github::http;
8use crate::security;
9use crate::sys::cmd::CommandErrorContext;
10use regex::Regex;
11use std::path::Path;
12use std::process::Output;
13use std::sync::LazyLock;
14use std::sync::atomic::{AtomicU64, Ordering};
15use std::time::Duration;
16use tokio::process::Command;
17use tokio::time;
18
19pub(super) const LEASE_ABSENT: &str = "absent";
20
21pub(super) static LEASE_FALLBACKS: AtomicU64 = AtomicU64::new(0);
23
24async fn git_stdout(dir: &Path, args: &[&str]) -> Option<String> {
25 let out = Command::new("git")
26 .args(args)
27 .current_dir(dir)
28 .output_with_context()
29 .await
30 .ok()?;
31 if !out.status.success() {
32 return None;
33 }
34
35 Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
36}
37
38fn lease_key(branch: &str) -> String {
39 format!("branch.{branch}.orchPushLease")
40}
41
42pub(super) async fn read_push_lease(dir: &Path, branch: &str) -> Option<String> {
43 git_stdout(dir, &["config", "--get", &lease_key(branch)]).await
44}
45
46async fn write_push_lease(dir: &Path, branch: &str, value: &str) {
47 if git_stdout(dir, &["config", &lease_key(branch), value])
48 .await
49 .is_none()
50 {
51 tracing::warn!(branch, "failed to record push lease");
52 }
53}
54
55async fn remote_tracking_sha(dir: &Path, branch: &str) -> Option<String> {
56 let rev = format!("refs/remotes/origin/{branch}");
57 git_stdout(dir, &["rev-parse", "--verify", "--quiet", &rev])
58 .await
59 .filter(|sha| http::is_full_commit_sha(sha))
60}
61
62async fn is_ancestor(dir: &Path, ancestor: &str, descendant: &str) -> bool {
63 git_stdout(dir, &["merge-base", "--is-ancestor", ancestor, descendant])
64 .await
65 .is_some()
66}
67
68pub(crate) async fn record_push_lease(dir: &Path, branch: &str, default_branch: &str) {
71 if branch.is_empty() || branch == default_branch {
72 return;
73 }
74
75 let tip = remote_tracking_sha(dir, branch).await;
76 match (read_push_lease(dir, branch).await, tip) {
77 (Some(lease), Some(tip)) if lease != tip && is_ancestor(dir, &tip, "HEAD").await => {
78 write_push_lease(dir, branch, &tip).await;
79 }
80 (Some(_), _) => {}
81 (None, tip) => {
82 let expect = tip.unwrap_or_else(|| LEASE_ABSENT.to_string());
83 write_push_lease(dir, branch, &expect).await;
84 }
85 }
86}
87
88pub(crate) async fn clear_push_lease(dir: &Path, branch: &str) {
90 let _ = git_stdout(dir, &["config", "--unset", &lease_key(branch)]).await;
91}
92
93async fn note_pushed_head(dir: &Path, branch: &str) {
94 let spec = format!("refs/heads/{branch}");
95 if let Some(sha) = git_stdout(dir, &["rev-parse", "--verify", &spec]).await {
96 write_push_lease(dir, branch, &sha).await;
97 }
98}
99
100pub(super) async fn is_github_branch_update(
103 dir: &Path,
104 tip: &str,
105 lease: &str,
106 default_branch: &str,
107) -> bool {
108 let base = format!("origin/{default_branch}");
109 let Some(line) = git_stdout(dir, &["rev-list", "--parents", "-n", "1", tip]).await else {
110 return false;
111 };
112 let parents: Vec<&str> = line.split_whitespace().skip(1).collect();
113 if let [first, second] = parents[..] {
114 return first == lease && is_ancestor(dir, second, &base).await;
115 }
116
117 let Some(cherry) = git_stdout(dir, &["cherry", lease, tip, &base]).await else {
119 return false;
120 };
121 is_ancestor(dir, &base, tip).await
122 && !cherry.is_empty()
123 && cherry.lines().all(|l| l.starts_with('-'))
124}
125
126pub(super) async fn expected_force_sha(
127 dir: &Path,
128 branch: &str,
129 default_branch: &str,
130) -> anyhow::Result<String> {
131 let tip = remote_tracking_sha(dir, branch).await;
132 let base = format!("origin/{default_branch}");
133 if let Some(tip) = &tip {
134 if is_ancestor(dir, tip, &base).await {
136 tracing::info!(branch, %tip, "remote tip is contained in the default branch, leasing it");
137 return Ok(tip.clone());
138 }
139 }
140
141 match read_push_lease(dir, branch).await {
142 Some(lease) if lease == LEASE_ABSENT => anyhow::bail!(
143 "force push rejected: remote branch {branch} was absent when the lease was recorded"
144 ),
145 Some(lease) => match tip {
146 Some(tip)
147 if tip != lease
148 && is_github_branch_update(dir, &tip, &lease, default_branch).await =>
149 {
150 tracing::info!(branch, %lease, %tip, "remote tip is GitHub's update of the leased branch, leasing it");
151 Ok(tip)
152 }
153 _ => Ok(lease),
154 },
155 None => {
156 let Some(tip) = tip else {
157 anyhow::bail!("force push rejected: no remote sha recorded for {branch}");
158 };
159 let fallbacks = LEASE_FALLBACKS.fetch_add(1, Ordering::Relaxed) + 1;
160 tracing::warn!(
161 branch,
162 fallbacks,
163 "no push lease recorded, using the fetched origin tip"
164 );
165 Ok(tip)
166 }
167 }
168}
169
170pub(crate) async fn force_push_leased(
172 dir: &Path,
173 branch: &str,
174 default_branch: &str,
175) -> anyhow::Result<()> {
176 let expected = expected_force_sha(dir, branch, default_branch).await?;
177 let lease = format!("--force-with-lease={branch}:{expected}");
178 tracing::info!(branch, expected_sha = %expected, "force-pushing with an expected remote sha");
179 let output = git()
180 .await
181 .args([
182 "-c",
183 "lfs.locksverify=false",
184 "push",
185 &lease,
186 "-u",
187 "origin",
188 branch,
189 ])
190 .current_dir(dir)
191 .kill_on_drop(true)
192 .output_with_context()
193 .await?;
194 if output.status.success() {
195 note_pushed_head(dir, branch).await;
196 return Ok(());
197 }
198
199 let stderr = sanitize_push_error(String::from_utf8_lossy(&output.stderr).trim());
200 anyhow::bail!("{stderr}")
201}
202
203fn is_protected_push_branch(name: &str, default_branch: &str) -> bool {
205 !name.is_empty() && (name == default_branch || name == "main" || name == "master")
206}
207
208pub(super) fn resolve_push_branch<'a>(
210 current: &'a str,
211 branch: &'a str,
212 default_branch: &str,
213) -> anyhow::Result<&'a str> {
214 let chosen = if !current.is_empty() && !is_protected_push_branch(current, default_branch) {
215 current
216 } else if !branch.is_empty() && !is_protected_push_branch(branch, default_branch) {
217 branch
218 } else {
219 let name = if current.is_empty() { branch } else { current };
220 if name.is_empty() {
221 anyhow::bail!("cannot push: branch name is empty");
222 }
223 anyhow::bail!("push refused: '{name}' is a default branch");
224 };
225 Ok(chosen)
226}
227
228pub async fn push_branch(dir: &Path, branch: &str, default_branch: &str) -> anyhow::Result<bool> {
233 let current = get_current_branch(dir).await;
234 let branch_to_push = resolve_push_branch(¤t, branch, default_branch)?;
235
236 let (remote_exists, has_unpushed) =
238 check_push_needed(dir, branch_to_push, default_branch).await;
239 if remote_exists && !has_unpushed {
240 tracing::debug!(
244 branch = branch_to_push,
245 "remote branch exists and is up to date, skipping push"
246 );
247 note_pushed_head(dir, branch_to_push).await;
248 return Ok(true);
249 }
250 if !remote_exists && !has_unpushed {
251 tracing::debug!(
257 branch = branch_to_push,
258 "remote branch missing with no new commits — pushing to create it on remote"
259 );
260 }
261
262 tracing::info!(branch = branch_to_push, "pushing branch");
263
264 let output = time::timeout(
271 Duration::from_secs(120),
272 git()
273 .await
274 .args([
275 "-c",
276 "lfs.locksverify=false",
277 "push",
278 "-u",
279 "origin",
280 branch_to_push,
281 ])
282 .kill_on_drop(true)
283 .current_dir(dir)
284 .output(),
285 )
286 .await
287 .map_err(|_| anyhow::anyhow!("git push timed out after 120s"))??;
288
289 if output.status.success() {
290 tracing::info!(branch = branch_to_push, "push succeeded");
291 note_pushed_head(dir, branch_to_push).await;
292 return Ok(true);
293 }
294
295 let stderr = sanitize_push_error(String::from_utf8_lossy(&output.stderr).trim());
296
297 if is_large_file_error(&stderr) {
298 return push_without_oversized_tip(dir, branch_to_push, &stderr).await;
299 }
300
301 if is_transient_network_error(&stderr) {
304 tracing::warn!(
305 branch = branch_to_push,
306 stderr = %stderr,
307 "push failed with transient network error — retrying once"
308 );
309 let retry_output = time::timeout(
310 Duration::from_secs(120),
311 git()
312 .await
313 .args([
314 "-c",
315 "lfs.locksverify=false",
316 "push",
317 "-u",
318 "origin",
319 branch_to_push,
320 ])
321 .kill_on_drop(true)
322 .current_dir(dir)
323 .output(),
324 )
325 .await
326 .map_err(|_| anyhow::anyhow!("git push (network retry) timed out after 120s"))??;
327
328 if retry_output.status.success() {
329 tracing::info!(branch = branch_to_push, "push succeeded on network retry");
330 note_pushed_head(dir, branch_to_push).await;
331 return Ok(true);
332 }
333
334 let retry_stderr =
335 sanitize_push_error(String::from_utf8_lossy(&retry_output.stderr).trim());
336 tracing::warn!(
337 branch = branch_to_push,
338 stderr = %retry_stderr,
339 "push retry also failed"
340 );
341 anyhow::bail!("push failed: {retry_stderr}");
342 }
343
344 if is_workflow_scope_error(&stderr) {
348 tracing::warn!(
349 branch = branch_to_push,
350 "push rejected: token lacks `workflow` scope — stripping workflow files and retrying"
351 );
352
353 match strip_workflow_files(dir, default_branch).await {
354 Ok(true) => {
355 let retry_output = time::timeout(
357 Duration::from_secs(120),
358 git()
359 .await
360 .args([
361 "-c",
362 "lfs.locksverify=false",
363 "push",
364 "-u",
365 "origin",
366 branch_to_push,
367 ])
368 .kill_on_drop(true)
369 .current_dir(dir)
370 .output(),
371 )
372 .await
373 .map_err(|_| anyhow::anyhow!("git push (retry) timed out after 120s"))??;
374
375 if retry_output.status.success() {
376 tracing::info!(
377 branch = branch_to_push,
378 "push succeeded after stripping workflow files"
379 );
380 note_pushed_head(dir, branch_to_push).await;
381 return Ok(true);
382 }
383
384 let retry_stderr =
385 sanitize_push_error(String::from_utf8_lossy(&retry_output.stderr).trim());
386
387 if is_workflow_scope_error(&retry_stderr) {
389 anyhow::bail!(
390 "push failed: token lacks `workflow` OAuth scope and workflow files \
391 could not be fully stripped — add `workflow` scope to your GitHub \
392 token or use a GitHub App for authentication"
393 );
394 }
395
396 anyhow::bail!("push failed after stripping workflow files: {retry_stderr}");
397 }
398 Ok(false) => {
399 anyhow::bail!(
401 "push failed: token lacks `workflow` OAuth scope — add `workflow` scope \
402 to your GitHub token or use a GitHub App for authentication. \
403 Error: {stderr}"
404 );
405 }
406 Err(e) => {
407 tracing::error!(error = %e, "failed to strip workflow files from commits");
408 anyhow::bail!(
409 "push failed: token lacks `workflow` OAuth scope and automatic \
410 recovery failed ({e}) — add `workflow` scope to your GitHub token \
411 or use a GitHub App for authentication"
412 );
413 }
414 }
415 }
416
417 if push_needs_rebase(&stderr) && remote_exists {
420 tracing::info!(
421 branch = branch_to_push,
422 "push rejected (non-fast-forward), force-pushing with lease"
423 );
424 let stderr = match force_push_leased(dir, branch_to_push, default_branch).await {
425 Ok(()) => {
426 tracing::info!(branch = branch_to_push, "force push succeeded");
427 return Ok(true);
428 }
429 Err(e) => e.to_string(),
430 };
431
432 if is_workflow_scope_error(&stderr) {
434 tracing::warn!(
435 branch = branch_to_push,
436 "force push also rejected due to workflow scope — stripping and retrying"
437 );
438 match strip_workflow_files(dir, default_branch).await {
439 Ok(true) => {
440 if let Err(e) = force_push_leased(dir, branch_to_push, default_branch).await {
441 anyhow::bail!("force push failed after stripping workflow files: {e}");
442 }
443
444 tracing::info!(
445 branch = branch_to_push,
446 "force push succeeded after stripping workflow files"
447 );
448 return Ok(true);
449 }
450 Ok(false) => {
451 anyhow::bail!(
452 "force push failed: token lacks `workflow` OAuth scope — \
453 add `workflow` scope to your GitHub token or use a GitHub App. \
454 Error: {stderr}"
455 );
456 }
457 Err(e) => {
458 anyhow::bail!(
459 "force push failed: token lacks `workflow` scope and recovery \
460 failed ({e})"
461 );
462 }
463 }
464 }
465
466 if is_stale_lease_error(&stderr) && rebase_on_branch(dir, branch_to_push).await? {
469 let output = git()
470 .await
471 .args([
472 "-c",
473 "lfs.locksverify=false",
474 "push",
475 "-u",
476 "origin",
477 branch_to_push,
478 ])
479 .current_dir(dir)
480 .output_with_context()
481 .await?;
482 if output.status.success() {
483 tracing::info!(
484 branch = branch_to_push,
485 "push succeeded after rebasing on the moved remote branch"
486 );
487 note_pushed_head(dir, branch_to_push).await;
488 return Ok(true);
489 }
490
491 let stderr = sanitize_push_error(String::from_utf8_lossy(&output.stderr).trim());
492 anyhow::bail!("push failed after rebasing on the moved remote branch: {stderr}");
493 }
494
495 if is_stale_lease_error(&stderr) {
496 tracing::info!(
497 branch = branch_to_push,
498 "remote branch already holds every local commit, nothing to push"
499 );
500 return Ok(true);
501 }
502
503 anyhow::bail!("force push failed: {stderr}");
504 }
505
506 anyhow::bail!("push failed: {stderr}")
507}
508
509async fn push_without_oversized_tip(
512 dir: &Path,
513 branch: &str,
514 stderr: &str,
515) -> anyhow::Result<bool> {
516 let paths = oversized_paths(stderr);
517 match drop_from_tip(dir, &paths).await {
518 Ok(true) => {}
519 Ok(false) => anyhow::bail!("push failed: {stderr}"),
520 Err(e) => {
521 tracing::warn!(branch, err = %e, "failed to drop oversized files from the tip commit");
522 anyhow::bail!("push failed: {stderr}");
523 }
524 }
525
526 tracing::warn!(branch, files = ?paths, "dropped files over GitHub's size limit from the tip commit, pushing again");
527 let output = time::timeout(
528 Duration::from_secs(120),
529 git()
530 .await
531 .args([
532 "-c",
533 "lfs.locksverify=false",
534 "push",
535 "-u",
536 "origin",
537 branch,
538 ])
539 .kill_on_drop(true)
540 .current_dir(dir)
541 .output(),
542 )
543 .await
544 .map_err(|_| anyhow::anyhow!("git push timed out after 120s"))??;
545 if output.status.success() {
546 note_pushed_head(dir, branch).await;
547 return Ok(true);
548 }
549
550 let retry_stderr = sanitize_push_error(String::from_utf8_lossy(&output.stderr).trim());
551 anyhow::bail!("push failed: {retry_stderr}")
552}
553
554pub(super) async fn drop_from_tip(dir: &Path, paths: &[String]) -> anyhow::Result<bool> {
557 if paths.is_empty() {
558 return Ok(false);
559 }
560
561 let Some(head) = git_stdout(dir, &["rev-parse", "HEAD"]).await else {
562 return Ok(false);
563 };
564 let parents = git_stdout(dir, &["rev-list", "--parents", "-n", "1", "HEAD"])
565 .await
566 .unwrap_or_default();
567 if parents.split_whitespace().count() != 2 {
568 return Ok(false);
569 }
570
571 for path in paths {
572 let touching = git_stdout(
573 dir,
574 &[
575 "--literal-pathspecs",
576 "rev-list",
577 "--full-history",
578 "HEAD",
579 "--not",
580 "--remotes=origin",
581 "--",
582 path,
583 ],
584 )
585 .await
586 .unwrap_or_default();
587 if touching != head {
588 return Ok(false);
589 }
590 }
591
592 let committer = git_stdout(dir, &["log", "-1", "--format=%cn%x00%ce", "HEAD"])
593 .await
594 .unwrap_or_default();
595 let (name, email) = committer.split_once('\0').unwrap_or(("", ""));
596
597 git_stdout(dir, &["reset", "-q", "--soft", "HEAD^"])
598 .await
599 .ok_or_else(|| anyhow::anyhow!("git reset --soft HEAD^ failed"))?;
600 let rewritten = recommit_without(dir, paths, &head, name, email).await;
601 if rewritten.is_err() {
602 let _ = git_stdout(dir, &["reset", "-q", "--soft", &head]).await;
603 }
604
605 rewritten.map(|()| true)
606}
607
608async fn recommit_without(
609 dir: &Path,
610 paths: &[String],
611 head: &str,
612 name: &str,
613 email: &str,
614) -> anyhow::Result<()> {
615 let restore = Command::new("git")
616 .args(["--literal-pathspecs", "restore", "--staged", "--"])
617 .args(paths)
618 .current_dir(dir)
619 .output_with_context()
620 .await?;
621 if !restore.status.success() {
622 anyhow::bail!(
623 "git restore --staged failed: {}",
624 String::from_utf8_lossy(&restore.stderr).trim()
625 );
626 }
627
628 if git_stdout(dir, &["diff", "--cached", "--quiet"])
630 .await
631 .is_some()
632 {
633 return Ok(());
634 }
635
636 let mut commit = Command::new("git");
637 commit.args(["-c", "commit.gpgsign=false", "commit", "-q", "-C", head]);
638 if !name.is_empty() {
639 commit
640 .env("GIT_COMMITTER_NAME", name)
641 .env("GIT_COMMITTER_EMAIL", email);
642 }
643
644 let out = commit.current_dir(dir).output_with_context().await?;
645 if !out.status.success() {
646 anyhow::bail!(
647 "git commit failed: {}",
648 String::from_utf8_lossy(&out.stderr).trim()
649 );
650 }
651
652 Ok(())
653}
654
655pub fn is_large_file_error(stderr: &str) -> bool {
658 stderr
659 .to_ascii_lowercase()
660 .contains("exceeds github's file size limit")
661}
662
663pub fn large_file_lines(stderr: &str) -> Vec<String> {
665 stderr
666 .lines()
667 .filter(|l| is_large_file_error(l))
668 .map(|l| l.find("File ").map_or(l, |i| &l[i..]).trim().to_string())
669 .collect()
670}
671
672pub(super) fn oversized_paths(stderr: &str) -> Vec<String> {
674 static FILE_LINE: LazyLock<Regex> = LazyLock::new(|| {
675 Regex::new(r"File (.+?) is [0-9.]+ MB; this exceeds GitHub's file size limit")
676 .expect("valid large file regex")
677 });
678 stderr
679 .lines()
680 .filter_map(|l| FILE_LINE.captures(l))
681 .map(|c| c[1].to_string())
682 .collect()
683}
684
685pub fn is_missing_remote_ref_error(err: &anyhow::Error) -> bool {
686 err.to_string().contains("couldn't find remote ref")
687}
688
689pub(super) fn push_needs_rebase(stderr: &str) -> bool {
690 let lower = stderr.to_ascii_lowercase();
691 lower.contains("non-fast-forward")
692 || lower.contains("rejected")
693 || lower.contains("fetch first")
694 || lower.contains("behind")
695}
696
697pub(super) fn is_stale_lease_error(stderr: &str) -> bool {
699 let lower = stderr.to_ascii_lowercase();
700 lower.contains("stale info") || lower.contains("remote ref updated since checkout")
701}
702
703pub fn is_transient_network_error(stderr: &str) -> bool {
708 let lower = stderr.to_ascii_lowercase();
709 if is_large_file_error(&lower) {
710 return false;
711 }
712
713 lower.contains("i/o timeout")
714 || lower.contains("dial tcp")
715 || lower.contains("connection reset")
716 || lower.contains("connection refused")
717 || lower.contains("no route to host")
718 || lower.contains("temporary failure in name resolution")
719 || lower.contains("eof")
720 || lower.contains("fatal error in commit_refs")
721 || (lower.contains("[remote rejected]") && lower.contains("(failure)"))
722}
723
724pub(crate) fn sanitize_push_error(stderr: &str) -> String {
727 static URL_USERINFO: LazyLock<Regex> =
728 LazyLock::new(|| Regex::new(r"://[^/@\s]+@").expect("valid url userinfo regex"));
729 let no_userinfo = URL_USERINFO.replace_all(stderr, "://***@");
730 security::redact(&no_userinfo)
731}
732
733pub(crate) fn sanitize_git_output(mut output: Output) -> Output {
735 output.stdout = sanitize_push_error(&String::from_utf8_lossy(&output.stdout)).into_bytes();
736 output.stderr = sanitize_push_error(&String::from_utf8_lossy(&output.stderr)).into_bytes();
737 output
738}