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_transient_network_error(&stderr) {
300 tracing::warn!(
301 branch = branch_to_push,
302 stderr = %stderr,
303 "push failed with transient network error — retrying once"
304 );
305 let retry_output = time::timeout(
306 Duration::from_secs(120),
307 git()
308 .await
309 .args([
310 "-c",
311 "lfs.locksverify=false",
312 "push",
313 "-u",
314 "origin",
315 branch_to_push,
316 ])
317 .kill_on_drop(true)
318 .current_dir(dir)
319 .output(),
320 )
321 .await
322 .map_err(|_| anyhow::anyhow!("git push (network retry) timed out after 120s"))??;
323
324 if retry_output.status.success() {
325 tracing::info!(branch = branch_to_push, "push succeeded on network retry");
326 note_pushed_head(dir, branch_to_push).await;
327 return Ok(true);
328 }
329
330 let retry_stderr =
331 sanitize_push_error(String::from_utf8_lossy(&retry_output.stderr).trim());
332 tracing::warn!(
333 branch = branch_to_push,
334 stderr = %retry_stderr,
335 "push retry also failed"
336 );
337 anyhow::bail!("push failed: {retry_stderr}");
338 }
339
340 if is_workflow_scope_error(&stderr) {
344 tracing::warn!(
345 branch = branch_to_push,
346 "push rejected: token lacks `workflow` scope — stripping workflow files and retrying"
347 );
348
349 match strip_workflow_files(dir, default_branch).await {
350 Ok(true) => {
351 let retry_output = time::timeout(
353 Duration::from_secs(120),
354 git()
355 .await
356 .args([
357 "-c",
358 "lfs.locksverify=false",
359 "push",
360 "-u",
361 "origin",
362 branch_to_push,
363 ])
364 .kill_on_drop(true)
365 .current_dir(dir)
366 .output(),
367 )
368 .await
369 .map_err(|_| anyhow::anyhow!("git push (retry) timed out after 120s"))??;
370
371 if retry_output.status.success() {
372 tracing::info!(
373 branch = branch_to_push,
374 "push succeeded after stripping workflow files"
375 );
376 note_pushed_head(dir, branch_to_push).await;
377 return Ok(true);
378 }
379
380 let retry_stderr =
381 sanitize_push_error(String::from_utf8_lossy(&retry_output.stderr).trim());
382
383 if is_workflow_scope_error(&retry_stderr) {
385 anyhow::bail!(
386 "push failed: token lacks `workflow` OAuth scope and workflow files \
387 could not be fully stripped — add `workflow` scope to your GitHub \
388 token or use a GitHub App for authentication"
389 );
390 }
391
392 anyhow::bail!("push failed after stripping workflow files: {retry_stderr}");
393 }
394 Ok(false) => {
395 anyhow::bail!(
397 "push failed: token lacks `workflow` OAuth scope — add `workflow` scope \
398 to your GitHub token or use a GitHub App for authentication. \
399 Error: {stderr}"
400 );
401 }
402 Err(e) => {
403 tracing::error!(error = %e, "failed to strip workflow files from commits");
404 anyhow::bail!(
405 "push failed: token lacks `workflow` OAuth scope and automatic \
406 recovery failed ({e}) — add `workflow` scope to your GitHub token \
407 or use a GitHub App for authentication"
408 );
409 }
410 }
411 }
412
413 if push_needs_rebase(&stderr) && remote_exists {
416 tracing::info!(
417 branch = branch_to_push,
418 "push rejected (non-fast-forward), force-pushing with lease"
419 );
420 let stderr = match force_push_leased(dir, branch_to_push, default_branch).await {
421 Ok(()) => {
422 tracing::info!(branch = branch_to_push, "force push succeeded");
423 return Ok(true);
424 }
425 Err(e) => e.to_string(),
426 };
427
428 if is_workflow_scope_error(&stderr) {
430 tracing::warn!(
431 branch = branch_to_push,
432 "force push also rejected due to workflow scope — stripping and retrying"
433 );
434 match strip_workflow_files(dir, default_branch).await {
435 Ok(true) => {
436 if let Err(e) = force_push_leased(dir, branch_to_push, default_branch).await {
437 anyhow::bail!("force push failed after stripping workflow files: {e}");
438 }
439
440 tracing::info!(
441 branch = branch_to_push,
442 "force push succeeded after stripping workflow files"
443 );
444 return Ok(true);
445 }
446 Ok(false) => {
447 anyhow::bail!(
448 "force push failed: token lacks `workflow` OAuth scope — \
449 add `workflow` scope to your GitHub token or use a GitHub App. \
450 Error: {stderr}"
451 );
452 }
453 Err(e) => {
454 anyhow::bail!(
455 "force push failed: token lacks `workflow` scope and recovery \
456 failed ({e})"
457 );
458 }
459 }
460 }
461
462 if is_stale_lease_error(&stderr) && rebase_on_branch(dir, branch_to_push).await? {
465 let output = git()
466 .await
467 .args([
468 "-c",
469 "lfs.locksverify=false",
470 "push",
471 "-u",
472 "origin",
473 branch_to_push,
474 ])
475 .current_dir(dir)
476 .output_with_context()
477 .await?;
478 if output.status.success() {
479 tracing::info!(
480 branch = branch_to_push,
481 "push succeeded after rebasing on the moved remote branch"
482 );
483 note_pushed_head(dir, branch_to_push).await;
484 return Ok(true);
485 }
486
487 let stderr = sanitize_push_error(String::from_utf8_lossy(&output.stderr).trim());
488 anyhow::bail!("push failed after rebasing on the moved remote branch: {stderr}");
489 }
490
491 if is_stale_lease_error(&stderr) {
492 tracing::info!(
493 branch = branch_to_push,
494 "remote branch already holds every local commit, nothing to push"
495 );
496 return Ok(true);
497 }
498
499 anyhow::bail!("force push failed: {stderr}");
500 }
501
502 anyhow::bail!("push failed: {stderr}")
503}
504
505pub fn is_missing_remote_ref_error(err: &anyhow::Error) -> bool {
506 err.to_string().contains("couldn't find remote ref")
507}
508
509pub(super) fn push_needs_rebase(stderr: &str) -> bool {
510 let lower = stderr.to_ascii_lowercase();
511 lower.contains("non-fast-forward")
512 || lower.contains("rejected")
513 || lower.contains("fetch first")
514 || lower.contains("behind")
515}
516
517pub(super) fn is_stale_lease_error(stderr: &str) -> bool {
519 let lower = stderr.to_ascii_lowercase();
520 lower.contains("stale info") || lower.contains("remote ref updated since checkout")
521}
522
523pub fn is_transient_network_error(stderr: &str) -> bool {
528 let lower = stderr.to_ascii_lowercase();
529 lower.contains("i/o timeout")
530 || lower.contains("dial tcp")
531 || lower.contains("connection reset")
532 || lower.contains("connection refused")
533 || lower.contains("no route to host")
534 || lower.contains("temporary failure in name resolution")
535 || lower.contains("eof")
536 || lower.contains("fatal error in commit_refs")
537 || (lower.contains("[remote rejected]") && lower.contains("(failure)"))
538}
539
540pub(crate) fn sanitize_push_error(stderr: &str) -> String {
543 static URL_USERINFO: LazyLock<Regex> =
544 LazyLock::new(|| Regex::new(r"://[^/@\s]+@").expect("valid url userinfo regex"));
545 let no_userinfo = URL_USERINFO.replace_all(stderr, "://***@");
546 security::redact(&no_userinfo)
547}
548
549pub(crate) fn sanitize_git_output(mut output: Output) -> Output {
551 output.stdout = sanitize_push_error(&String::from_utf8_lossy(&output.stdout)).into_bytes();
552 output.stderr = sanitize_push_error(&String::from_utf8_lossy(&output.stderr)).into_bytes();
553 output
554}