1mod pr;
11mod push;
12
13use super::commit;
14use crate::cmd::CommandErrorContext;
15use crate::github::token;
16use std::ffi::OsStr;
17use std::io;
18use std::path::Path;
19use std::process::Output;
20use std::time::Duration;
21
22pub use pr::create_pr_if_needed;
23pub(crate) use pr::{
24 is_invalid_base_error, is_transient_github_api_error, is_transient_github_error,
25};
26pub(crate) use push::{
27 clear_push_lease, force_push_leased, record_push_lease, sanitize_git_output,
28 sanitize_push_error,
29};
30pub use push::{is_missing_remote_ref_error, is_transient_network_error, push_branch};
31use tokio::process::Command;
32use tokio::time;
33
34pub(crate) fn format_task_ref(task_id: &str) -> String {
40 if task_id.starts_with("internal:") {
41 task_id.replace(':', "-")
42 } else {
43 format!("#{task_id}")
44 }
45}
46
47#[derive(Debug, thiserror::Error)]
49pub enum PrCreateError {
50 #[error("GitHub API error: {0}")]
51 ApiError(#[from] anyhow::Error),
52}
53
54pub type PrCreateResult<T> = Result<T, PrCreateError>;
56
57pub async fn has_commits_ahead(dir: &Path, default_branch: &str) -> bool {
59 let output = Command::new("git")
60 .args([
61 "rev-list",
62 "--count",
63 &format!("origin/{default_branch}..HEAD"),
64 ])
65 .current_dir(dir)
66 .output()
67 .await;
68 match output {
69 Ok(o) if o.status.success() => {
70 let count: u32 = String::from_utf8_lossy(&o.stdout)
71 .trim()
72 .parse()
73 .unwrap_or(0);
74 count > 0
75 }
76 _ => {
77 tracing::debug!(
78 default_branch,
79 "git rev-list failed for compare ref, assuming commits ahead"
80 );
81 true
85 }
86 }
87}
88
89pub(crate) fn find_stash_ref_by_hash(stash_list: &str, stash_hash: &str) -> Option<String> {
90 stash_list.lines().find_map(|line| {
91 let mut parts = line.split_whitespace();
92 match (parts.next(), parts.next()) {
93 (Some(hash), Some(reference)) if hash == stash_hash => Some(reference.to_string()),
94 _ => None,
95 }
96 })
97}
98
99pub(crate) struct StashRebaseOpts {
101 pub abort_on_failure: bool,
105}
106
107impl Default for StashRebaseOpts {
108 fn default() -> Self {
109 Self {
110 abort_on_failure: true,
111 }
112 }
113}
114
115#[derive(Debug)]
117pub(crate) enum RebaseOutcome {
118 Succeeded,
120 Failed(String),
124 Skipped(String),
127}
128
129pub(crate) async fn stash_rebase_restore(
146 dir: &Path,
147 target_ref: &str,
148 opts: StashRebaseOpts,
149) -> anyhow::Result<RebaseOutcome> {
150 let stash_ref: Option<String> = if commit::has_changes(dir).await {
151 let stash_out = Command::new("git")
152 .args(["stash", "push", "--include-untracked", "-m", "orch-rebase"])
153 .current_dir(dir)
154 .output_with_context()
155 .await;
156
157 match stash_out {
158 Ok(o) if o.status.success() => {
159 let stdout_preview = String::from_utf8_lossy(&o.stdout)
160 .lines()
161 .next()
162 .unwrap_or("")
163 .to_string();
164 tracing::debug!(
165 dir = %dir.display(),
166 stdout = %stdout_preview,
167 "git stash push succeeded before rebase"
168 );
169
170 let ref_out = Command::new("git")
174 .args(["rev-parse", "refs/stash@{0}"])
175 .current_dir(dir)
176 .output_with_context()
177 .await;
178 let stash_hash = ref_out
179 .ok()
180 .filter(|o| o.status.success())
181 .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
182 .filter(|s| !s.is_empty());
183
184 if stash_hash.is_none() {
185 tracing::warn!(
188 dir = %dir.display(),
189 "git stash succeeded but rev-parse failed — popping stash and skipping rebase"
190 );
191 let _ = Command::new("git")
192 .args(["stash", "pop"])
193 .current_dir(dir)
194 .output_with_context()
195 .await;
196 return Ok(RebaseOutcome::Skipped(
197 "stash OID capture failed".to_string(),
198 ));
199 }
200 stash_hash
201 }
202 Ok(o) => {
203 let stderr = String::from_utf8_lossy(&o.stderr).trim().to_string();
204 tracing::warn!(
205 dir = %dir.display(),
206 code = ?o.status.code(),
207 stderr = %stderr,
208 "git stash push failed — skipping rebase to preserve dirty state"
209 );
210 return Ok(RebaseOutcome::Skipped(format!(
211 "stash push failed: {stderr}"
212 )));
213 }
214 Err(e) => {
215 tracing::warn!(
216 dir = %dir.display(),
217 error = %e,
218 "failed to run git stash push — skipping rebase to preserve dirty state"
219 );
220 return Ok(RebaseOutcome::Skipped(format!("stash push error: {e}")));
221 }
222 }
223 } else {
224 None
225 };
226
227 let output = git()
228 .await
229 .args(["rebase", target_ref])
230 .current_dir(dir)
231 .output_with_context()
232 .await;
233
234 match output {
235 Ok(o) if o.status.success() => {
236 tracing::debug!(dir = %dir.display(), target_ref, "rebase succeeded");
237 restore_stash_by_hash(dir, stash_ref.as_deref()).await;
238 Ok(RebaseOutcome::Succeeded)
239 }
240 Ok(o) => {
241 let stderr = sanitize_push_error(&String::from_utf8_lossy(&o.stderr));
242 tracing::warn!(dir = %dir.display(), target_ref, err = %stderr, "rebase failed");
243 if opts.abort_on_failure {
244 let abort = Command::new("git")
245 .args(["rebase", "--abort"])
246 .current_dir(dir)
247 .output_with_context()
248 .await;
249 match abort {
250 Err(e) => {
251 tracing::warn!(dir = %dir.display(), error = %e, "git rebase --abort failed — worktree may be in inconsistent state");
252 }
253 Ok(o) if !o.status.success() => {
254 let stderr = String::from_utf8_lossy(&o.stderr);
255 tracing::warn!(dir = %dir.display(), stderr = %stderr, "git rebase --abort returned non-zero — worktree may be in inconsistent state");
256 }
257 _ => {}
258 }
259 }
260 restore_stash_by_hash(dir, stash_ref.as_deref()).await;
261 Ok(RebaseOutcome::Failed(stderr))
262 }
263 Err(e) => {
264 if opts.abort_on_failure {
265 let abort = Command::new("git")
266 .args(["rebase", "--abort"])
267 .current_dir(dir)
268 .output_with_context()
269 .await;
270 match abort {
271 Err(e) => {
272 tracing::warn!(dir = %dir.display(), error = %e, "git rebase --abort failed — worktree may be in inconsistent state");
273 }
274 Ok(o) if !o.status.success() => {
275 let stderr = String::from_utf8_lossy(&o.stderr);
276 tracing::warn!(dir = %dir.display(), stderr = %stderr, "git rebase --abort returned non-zero — worktree may be in inconsistent state");
277 }
278 _ => {}
279 }
280 }
281 restore_stash_by_hash(dir, stash_ref.as_deref()).await;
282 Err(e)
283 }
284 }
285}
286
287async fn restore_stash_by_hash(dir: &Path, stash_hash: Option<&str>) {
291 let Some(stash_hash) = stash_hash else {
292 return;
293 };
294
295 let apply = Command::new("git")
296 .args(["stash", "apply", stash_hash])
297 .current_dir(dir)
298 .output_with_context()
299 .await;
300 if apply.is_ok_and(|o| o.status.success()) {
301 let list = Command::new("git")
302 .args(["stash", "list", "--format=%H %gd"])
303 .current_dir(dir)
304 .output_with_context()
305 .await;
306 if let Ok(list_out) = list
307 && list_out.status.success()
308 {
309 let list_str = String::from_utf8_lossy(&list_out.stdout);
310 if let Some(stash_ref) = find_stash_ref_by_hash(&list_str, stash_hash) {
311 match Command::new("git")
312 .args(["stash", "drop", &stash_ref])
313 .current_dir(dir)
314 .output_with_context()
315 .await
316 {
317 Ok(drop_out) if !drop_out.status.success() => {
318 let stderr = String::from_utf8_lossy(&drop_out.stderr);
319 tracing::warn!(
320 dir = %dir.display(),
321 stash_ref = %stash_ref,
322 err = %stderr,
323 "stash drop failed after apply — entry may remain on stack"
324 );
325 }
326 Err(e) => {
327 tracing::warn!(
328 dir = %dir.display(),
329 stash_ref = %stash_ref,
330 error = %e,
331 "stash drop command failed after apply — entry may remain on stack"
332 );
333 }
334 _ => {}
335 }
336 } else {
337 tracing::warn!(
338 dir = %dir.display(),
339 stash = %stash_hash,
340 "stash applied but could not find ref by hash — stash entry may be orphaned on stack"
341 );
342 }
343 }
344 } else {
345 tracing::warn!(
346 dir = %dir.display(),
347 stash = %stash_hash,
348 "stash apply failed after rebase — stash preserved for manual recovery"
349 );
350 }
351}
352
353pub async fn auto_commit(
355 dir: &Path,
356 task_id: &str,
357 title: &str,
358 agent: &str,
359 attempt: u32,
360 when: commit::When,
361) -> anyhow::Result<bool> {
362 if !commit::has_changes(dir).await {
363 return Ok(false);
364 }
365
366 tracing::info!(task_id, "auto-committing uncommitted changes");
367 let task_ref = format_task_ref(task_id);
368 let message = format!("{title}\n\nTask {task_ref}\nAgent: {agent}\nAttempt: {attempt}");
369 match commit::commit_all(dir, &message, agent, when).await? {
370 commit::Outcome::Committed => {
371 tracing::info!(task_id, "auto-commit succeeded");
372 Ok(true)
373 }
374 commit::Outcome::Nothing => Ok(false),
375 commit::Outcome::Refused {
376 by: commit::Tool::Git,
377 reason,
378 } => {
379 tracing::warn!(task_id, err = %reason, "git commit failed");
380 Ok(false)
381 }
382 commit::Outcome::Refused { reason, .. } => anyhow::bail!(reason),
383 }
384}
385
386const MAX_REBASE_COMMITS: usize = 50;
394
395pub async fn rebase_on_branch(dir: &Path, branch: &str) -> anyhow::Result<bool> {
405 let origin_branch = format!("origin/{branch}");
406
407 let fetch = time::timeout(
410 Duration::from_secs(120),
411 git()
412 .await
413 .args(["fetch", "origin", branch])
414 .kill_on_drop(true)
415 .current_dir(dir)
416 .output(),
417 )
418 .await
419 .map_err(|_| anyhow::anyhow!("git fetch timed out after 120s"))
420 .and_then(|r| r.map_err(Into::into));
421
422 match fetch {
423 Ok(o) if o.status.success() => {}
424 Ok(o) => {
425 let stderr = sanitize_push_error(&String::from_utf8_lossy(&o.stderr));
426 anyhow::bail!("failed to fetch origin/{branch}: {stderr}");
427 }
428 Err(e) => anyhow::bail!("failed to fetch origin/{branch}: {e}"),
429 }
430
431 let count_output = Command::new("git")
433 .args(["rev-list", "--count", &format!("{origin_branch}..HEAD")])
434 .current_dir(dir)
435 .output_with_context()
436 .await;
437
438 let commit_count: usize = match count_output {
439 Ok(o) if o.status.success() => {
440 let raw = String::from_utf8_lossy(&o.stdout);
441 raw.trim().parse().map_err(|e| {
442 anyhow::anyhow!(
443 "failed to parse commit count from git rev-list output {:?}: {e}",
444 raw.trim()
445 )
446 })?
447 }
448 Ok(o) => {
449 let stderr = String::from_utf8_lossy(&o.stderr);
450 anyhow::bail!("git rev-list --count failed: {stderr}");
451 }
452 Err(e) => anyhow::bail!("failed to run git rev-list --count: {e}"),
453 };
454
455 if commit_count == 0 {
456 return Ok(false);
458 }
459
460 if commit_count > MAX_REBASE_COMMITS {
461 anyhow::bail!(
462 "refusing to rebase {commit_count} commits on origin/{branch} (max {MAX_REBASE_COMMITS})"
463 );
464 }
465
466 tracing::info!(
467 branch = branch,
468 commit_count,
469 "rebasing local commits on origin/{branch}"
470 );
471
472 match stash_rebase_restore(dir, &origin_branch, StashRebaseOpts::default()).await? {
473 RebaseOutcome::Succeeded => Ok(true),
474 RebaseOutcome::Failed(e) => anyhow::bail!("rebase failed: {e}"),
475 RebaseOutcome::Skipped(reason) => anyhow::bail!("rebase skipped: {reason}"),
476 }
477}
478
479pub async fn rebase_on_default(dir: &Path, default_branch: &str) {
487 if rebase_in_progress(dir).await {
489 tracing::info!("rebase already in progress, skipping pre-dispatch rebase");
490 return;
491 }
492
493 let branch = get_current_branch(dir).await;
495 record_push_lease(dir, &branch, default_branch).await;
496
497 let _ = git()
500 .await
501 .args(["fetch", "origin"])
502 .current_dir(dir)
503 .output_with_context()
504 .await;
505
506 let commit_count = Command::new("git")
511 .args([
512 "rev-list",
513 "--count",
514 &format!("origin/{default_branch}..HEAD"),
515 ])
516 .current_dir(dir)
517 .output_with_context()
518 .await
519 .ok()
520 .and_then(|o| {
521 String::from_utf8_lossy(&o.stdout)
522 .trim()
523 .parse::<usize>()
524 .ok()
525 })
526 .unwrap_or(0);
527
528 if commit_count > MAX_REBASE_COMMITS {
529 tracing::warn!(
530 default_branch,
531 commit_count,
532 max = MAX_REBASE_COMMITS,
533 "skipping rebase: branch has too many commits to replay safely"
534 );
535 return;
536 }
537
538 match stash_rebase_restore(
539 dir,
540 &format!("origin/{default_branch}"),
541 StashRebaseOpts::default(),
542 )
543 .await
544 {
545 Ok(RebaseOutcome::Succeeded) => {
546 tracing::debug!(default_branch, "rebased worktree on default branch");
547 }
548 Ok(RebaseOutcome::Failed(e)) => {
549 tracing::warn!(default_branch, err = %e, "rebase failed, continuing with current state");
550 }
551 Ok(RebaseOutcome::Skipped(reason)) => {
552 tracing::warn!(default_branch, %reason, "stash failed before rebase, continuing with current state");
553 }
554 Err(e) => tracing::warn!(err = %e, "rebase error"),
555 }
556}
557
558pub(crate) async fn rebase_in_progress(dir: &Path) -> bool {
559 for name in ["rebase-merge", "rebase-apply"] {
560 let out = Command::new("git")
561 .args(["rev-parse", "--git-path", name])
562 .current_dir(dir)
563 .output_with_context()
564 .await;
565 if let Ok(o) = out {
566 let p = String::from_utf8_lossy(&o.stdout).trim().to_string();
567 if !p.is_empty() && dir.join(p).exists() {
568 return true;
569 }
570 }
571 }
572 false
573}
574
575pub(crate) fn remote_change_tools() -> Vec<String> {
578 [
579 "Bash(git remote set-url*)",
580 "Bash(git remote add*)",
581 "Bash(git remote remove*)",
582 "Bash(git remote rm*)",
583 "Bash(git remote rename*)",
584 "Bash(git config*remote.*)",
585 "Bash(git config*url.*)",
586 ]
587 .map(String::from)
588 .to_vec()
589}
590
591pub(crate) struct GitCommand {
593 inner: Command,
594}
595
596impl GitCommand {
597 pub(crate) fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Self {
598 self.inner.arg(arg);
599 self
600 }
601
602 pub(crate) fn args<I, S>(&mut self, args: I) -> &mut Self
603 where
604 I: IntoIterator<Item = S>,
605 S: AsRef<OsStr>,
606 {
607 self.inner.args(args);
608 self
609 }
610
611 pub(crate) fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Self {
612 self.inner.current_dir(dir);
613 self
614 }
615
616 pub(crate) fn env<K, V>(&mut self, key: K, val: V) -> &mut Self
617 where
618 K: AsRef<OsStr>,
619 V: AsRef<OsStr>,
620 {
621 self.inner.env(key, val);
622 self
623 }
624
625 pub(crate) fn kill_on_drop(&mut self, kill: bool) -> &mut Self {
626 self.inner.kill_on_drop(kill);
627 self
628 }
629
630 pub(crate) async fn output(&mut self) -> io::Result<Output> {
631 self.inner.output().await.map(sanitize_git_output)
632 }
633
634 pub(crate) async fn output_with_context(&mut self) -> anyhow::Result<Output> {
635 self.inner
636 .output_with_context()
637 .await
638 .map(sanitize_git_output)
639 }
640}
641
642pub(crate) async fn git() -> GitCommand {
645 let mut cmd = Command::new("git");
646 cmd.envs(build_git_auth_env().await).kill_on_drop(true);
647 GitCommand { inner: cmd }
648}
649
650pub(crate) async fn build_git_auth_env() -> Vec<(String, String)> {
671 let token = token::shared().get_token().await.ok().flatten();
672 build_git_auth_env_for_token(token)
673}
674
675fn build_git_auth_env_for_token(token: Option<String>) -> Vec<(String, String)> {
676 let mut config: Vec<(String, String)> = match token {
677 Some(t) if !t.is_empty() => {
678 let authed = format!("url.https://x-access-token:{t}@github.com/.insteadOf");
679 vec![
680 (authed.clone(), "https://github.com/".into()),
681 (authed, "git@github.com:".into()),
682 ]
683 }
684 _ => vec![(
685 "url.https://github.com/.insteadOf".into(),
686 "git@github.com:".into(),
687 )],
688 };
689 config.push(("commit.gpgsign".into(), "false".into()));
691 config.push(("tag.gpgsign".into(), "false".into()));
692
693 let mut env = vec![("GIT_CONFIG_COUNT".to_string(), config.len().to_string())];
694 for (n, (key, value)) in config.into_iter().enumerate() {
695 env.push((format!("GIT_CONFIG_KEY_{n}"), key));
696 env.push((format!("GIT_CONFIG_VALUE_{n}"), value));
697 }
698 env
699}
700
701pub(crate) fn is_workflow_scope_error(stderr: &str) -> bool {
708 stderr.contains("without `workflow` scope")
709 || stderr.contains("without 'workflow' scope")
710 || (stderr.contains("refusing to allow")
711 && stderr.contains("workflow")
712 && stderr.contains("scope"))
713}
714
715async fn strip_workflow_files(dir: &Path, default_branch: &str) -> anyhow::Result<bool> {
726 let output = Command::new("git")
728 .args([
729 "diff",
730 "--name-only",
731 &format!("origin/{default_branch}...HEAD"),
732 "--",
733 ".github/workflows/",
734 ])
735 .current_dir(dir)
736 .output_with_context()
737 .await?;
738
739 let workflow_files: Vec<String> = String::from_utf8_lossy(&output.stdout)
740 .lines()
741 .filter(|l| !l.is_empty())
742 .map(ToString::to_string)
743 .collect();
744
745 if workflow_files.is_empty() {
746 return Ok(false);
747 }
748
749 tracing::info!(
750 files = ?workflow_files,
751 "stripping workflow files from commits to bypass missing workflow scope"
752 );
753
754 let count_output = Command::new("git")
759 .args([
760 "rev-list",
761 "--count",
762 &format!("origin/{default_branch}..HEAD"),
763 ])
764 .current_dir(dir)
765 .output_with_context()
766 .await?;
767
768 let commit_count: usize = String::from_utf8_lossy(&count_output.stdout)
769 .trim()
770 .parse()
771 .unwrap_or(0);
772
773 if commit_count == 0 {
774 return Ok(false);
775 }
776
777 let log_output = Command::new("git")
782 .args([
783 "log",
784 "--format=%x00%H%n%B",
785 &format!("origin/{default_branch}..HEAD"),
786 ])
787 .current_dir(dir)
788 .output_with_context()
789 .await?;
790 let log_text = String::from_utf8_lossy(&log_output.stdout).to_string();
791
792 let commits: Vec<(String, String)> = log_text
796 .split('\0')
797 .filter(|s| !s.trim().is_empty())
798 .map(|block| {
799 let block = block.trim();
800 let first_nl = block.find('\n').unwrap_or(block.len());
801 let hash = block[..first_nl].to_string();
802 let msg = block[first_nl..].trim().to_string();
803 (hash, msg)
804 })
805 .collect::<Vec<_>>()
806 .into_iter()
807 .rev()
808 .collect();
809
810 if commits.is_empty() {
811 return Ok(false);
812 }
813
814 let reset = Command::new("git")
816 .args(["reset", "--soft", &format!("origin/{default_branch}")])
817 .current_dir(dir)
818 .output_with_context()
819 .await?;
820
821 if !reset.status.success() {
822 let stderr = String::from_utf8_lossy(&reset.stderr);
823 anyhow::bail!("git reset --soft failed during workflow file stripping: {stderr}");
824 }
825
826 let mut rm_args = vec!["rm", "--cached", "--ignore-unmatch", "--"];
828 let file_refs: Vec<&str> = workflow_files.iter().map(String::as_str).collect();
829 rm_args.extend(file_refs);
830
831 let rm = Command::new("git")
832 .args(&rm_args)
833 .current_dir(dir)
834 .output_with_context()
835 .await?;
836
837 if !rm.status.success() {
838 let stderr = String::from_utf8_lossy(&rm.stderr);
839 tracing::warn!("git rm --cached for workflow files failed (non-fatal): {stderr}");
840 }
841
842 let has_staged = Command::new("git")
845 .args(["diff", "--cached", "--quiet"])
846 .current_dir(dir)
847 .status()
848 .await
849 .is_ok_and(|s| !s.success());
850
851 if !has_staged {
852 tracing::warn!(
853 "after removing workflow files, no staged changes remain — \
854 the only changes were workflow files"
855 );
856 if let Some((hash, _)) = commits.last() {
859 let _ = Command::new("git")
860 .args(["reset", "--soft", hash])
861 .current_dir(dir)
862 .output_with_context()
863 .await;
864 }
865 return Ok(false);
866 }
867
868 let commit_msg = if commits.len() == 1 {
870 commits[0].1.clone()
871 } else {
872 let mut combined = String::new();
874 for (i, (_, msg)) in commits.iter().enumerate() {
875 if i > 0 {
876 combined.push_str("\n\n");
877 }
878 combined.push_str(msg);
879 }
880 combined.push_str("\n\n[workflow files stripped: token lacks `workflow` scope]");
881 combined
882 };
883
884 let commit = commit::git_commit(dir, &commit_msg, "orchestrator").await?;
886
887 if !commit.status.success() {
888 let stderr = String::from_utf8_lossy(&commit.stderr);
889 if let Some((original_head, _)) = commits.last() {
891 let _ = Command::new("git")
892 .args(["reset", "--hard", original_head])
893 .current_dir(dir)
894 .output_with_context()
895 .await;
896 }
897 anyhow::bail!("git commit failed during workflow file stripping: {stderr}");
898 }
899
900 tracing::info!(
901 stripped_files = ?workflow_files,
902 original_commits = commit_count,
903 "successfully stripped workflow files from commits"
904 );
905
906 Ok(true)
907}
908
909pub(crate) async fn get_current_branch(dir: &Path) -> String {
911 let output = Command::new("git")
912 .args(["branch", "--show-current"])
913 .current_dir(dir)
914 .output_with_context()
915 .await;
916
917 match output {
918 Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
919 _ => String::new(),
920 }
921}
922
923pub async fn count_changed_files(dir: &Path) -> anyhow::Result<usize> {
925 let output = Command::new("git")
927 .args(["status", "--porcelain"])
928 .current_dir(dir)
929 .output_with_context()
930 .await?;
931
932 let status_output = String::from_utf8_lossy(&output.stdout);
933 let count = status_output
934 .lines()
935 .filter(|line| {
936 let prefix = line.get(0..2).unwrap_or("");
937 prefix.starts_with('M')
939 || prefix.starts_with('A')
940 || prefix.starts_with('R')
941 || prefix.starts_with('C')
942 || prefix.starts_with('?')
943 })
944 .count();
945
946 Ok(count)
947}
948
949async fn check_push_needed(dir: &Path, branch: &str, default_branch: &str) -> (bool, bool) {
957 let remote_exists = Command::new("git")
959 .args(["rev-parse", &format!("origin/{branch}")])
960 .current_dir(dir)
961 .output_with_context()
962 .await
963 .is_ok_and(|o| o.status.success());
964
965 let compare_ref = if remote_exists {
966 format!("origin/{branch}..{branch}")
967 } else {
968 format!("origin/{default_branch}..{branch}")
970 };
971
972 tracing::debug!(
973 branch,
974 compare_ref,
975 remote_exists,
976 "checking unpushed commits"
977 );
978
979 let output = Command::new("git")
980 .args(["log", &compare_ref, "--oneline"])
981 .current_dir(dir)
982 .output_with_context()
983 .await;
984
985 let has_unpushed = match output {
986 Ok(o) if o.status.success() => {
987 let out = String::from_utf8_lossy(&o.stdout);
988 let has = !out.trim().is_empty();
989 tracing::debug!(branch, has_unpushed = has, "unpushed commits check result");
990 has
991 }
992 _ => {
993 tracing::debug!(branch, "git log failed for compare ref, assuming unpushed");
994 true
997 }
998 };
999
1000 (remote_exists, has_unpushed)
1001}
1002
1003#[cfg(test)]
1004mod tests;