1mod pr;
11mod push;
12
13use crate::cmd::CommandErrorContext;
14use crate::github::token;
15use std::ffi::OsStr;
16use std::io;
17use std::path::Path;
18use std::process::Output;
19use std::time::Duration;
20
21pub use pr::create_pr_if_needed;
22pub(crate) use pr::{
23 is_invalid_base_error, is_transient_github_api_error, is_transient_github_error,
24};
25pub(crate) use push::{
26 clear_push_lease, force_push_leased, record_push_lease, sanitize_git_output,
27 sanitize_push_error,
28};
29pub use push::{is_missing_remote_ref_error, is_transient_network_error, push_branch};
30use tokio::process::Command;
31use tokio::time;
32
33pub(crate) fn format_task_ref(task_id: &str) -> String {
39 if task_id.starts_with("internal:") {
40 task_id.replace(':', "-")
41 } else {
42 format!("#{task_id}")
43 }
44}
45
46#[derive(Debug, thiserror::Error)]
48pub enum PrCreateError {
49 #[error("GitHub API error: {0}")]
50 ApiError(#[from] anyhow::Error),
51}
52
53pub type PrCreateResult<T> = Result<T, PrCreateError>;
55
56pub async fn has_commits_ahead(dir: &Path, default_branch: &str) -> bool {
58 let output = Command::new("git")
59 .args([
60 "rev-list",
61 "--count",
62 &format!("origin/{default_branch}..HEAD"),
63 ])
64 .current_dir(dir)
65 .output()
66 .await;
67 match output {
68 Ok(o) if o.status.success() => {
69 let count: u32 = String::from_utf8_lossy(&o.stdout)
70 .trim()
71 .parse()
72 .unwrap_or(0);
73 count > 0
74 }
75 _ => {
76 tracing::debug!(
77 default_branch,
78 "git rev-list failed for compare ref, assuming commits ahead"
79 );
80 true
84 }
85 }
86}
87
88pub async fn has_changes(dir: &Path) -> bool {
90 let diff = Command::new("git")
92 .args(["diff", "--quiet"])
93 .current_dir(dir)
94 .status()
95 .await;
96
97 let cached = Command::new("git")
98 .args(["diff", "--cached", "--quiet"])
99 .current_dir(dir)
100 .status()
101 .await;
102
103 let untracked = Command::new("git")
104 .args(["ls-files", "--others", "--exclude-standard"])
105 .current_dir(dir)
106 .output_with_context()
107 .await;
108
109 let has_diff = diff.is_ok_and(|s| !s.success());
110 let has_cached = cached.is_ok_and(|s| !s.success());
111 let has_untracked =
112 untracked.is_ok_and(|o| !String::from_utf8_lossy(&o.stdout).trim().is_empty());
113
114 has_diff || has_cached || has_untracked
115}
116
117pub(crate) fn find_stash_ref_by_hash(stash_list: &str, stash_hash: &str) -> Option<String> {
118 stash_list.lines().find_map(|line| {
119 let mut parts = line.split_whitespace();
120 match (parts.next(), parts.next()) {
121 (Some(hash), Some(reference)) if hash == stash_hash => Some(reference.to_string()),
122 _ => None,
123 }
124 })
125}
126
127pub(crate) struct StashRebaseOpts {
129 pub abort_on_failure: bool,
133}
134
135impl Default for StashRebaseOpts {
136 fn default() -> Self {
137 Self {
138 abort_on_failure: true,
139 }
140 }
141}
142
143#[derive(Debug)]
145pub(crate) enum RebaseOutcome {
146 Succeeded,
148 Failed(String),
152 Skipped(String),
155}
156
157pub(crate) async fn stash_rebase_restore(
174 dir: &Path,
175 target_ref: &str,
176 opts: StashRebaseOpts,
177) -> anyhow::Result<RebaseOutcome> {
178 let stash_ref: Option<String> = if has_changes(dir).await {
179 let stash_out = Command::new("git")
180 .args(["stash", "push", "--include-untracked", "-m", "orch-rebase"])
181 .current_dir(dir)
182 .output_with_context()
183 .await;
184
185 match stash_out {
186 Ok(o) if o.status.success() => {
187 let stdout_preview = String::from_utf8_lossy(&o.stdout)
188 .lines()
189 .next()
190 .unwrap_or("")
191 .to_string();
192 tracing::debug!(
193 dir = %dir.display(),
194 stdout = %stdout_preview,
195 "git stash push succeeded before rebase"
196 );
197
198 let ref_out = Command::new("git")
202 .args(["rev-parse", "refs/stash@{0}"])
203 .current_dir(dir)
204 .output_with_context()
205 .await;
206 let stash_hash = ref_out
207 .ok()
208 .filter(|o| o.status.success())
209 .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
210 .filter(|s| !s.is_empty());
211
212 if stash_hash.is_none() {
213 tracing::warn!(
216 dir = %dir.display(),
217 "git stash succeeded but rev-parse failed — popping stash and skipping rebase"
218 );
219 let _ = Command::new("git")
220 .args(["stash", "pop"])
221 .current_dir(dir)
222 .output_with_context()
223 .await;
224 return Ok(RebaseOutcome::Skipped(
225 "stash OID capture failed".to_string(),
226 ));
227 }
228 stash_hash
229 }
230 Ok(o) => {
231 let stderr = String::from_utf8_lossy(&o.stderr).trim().to_string();
232 tracing::warn!(
233 dir = %dir.display(),
234 code = ?o.status.code(),
235 stderr = %stderr,
236 "git stash push failed — skipping rebase to preserve dirty state"
237 );
238 return Ok(RebaseOutcome::Skipped(format!(
239 "stash push failed: {stderr}"
240 )));
241 }
242 Err(e) => {
243 tracing::warn!(
244 dir = %dir.display(),
245 error = %e,
246 "failed to run git stash push — skipping rebase to preserve dirty state"
247 );
248 return Ok(RebaseOutcome::Skipped(format!("stash push error: {e}")));
249 }
250 }
251 } else {
252 None
253 };
254
255 let output = git()
256 .await
257 .args(["rebase", target_ref])
258 .current_dir(dir)
259 .output_with_context()
260 .await;
261
262 match output {
263 Ok(o) if o.status.success() => {
264 tracing::debug!(dir = %dir.display(), target_ref, "rebase succeeded");
265 restore_stash_by_hash(dir, stash_ref.as_deref()).await;
266 Ok(RebaseOutcome::Succeeded)
267 }
268 Ok(o) => {
269 let stderr = sanitize_push_error(&String::from_utf8_lossy(&o.stderr));
270 tracing::warn!(dir = %dir.display(), target_ref, err = %stderr, "rebase failed");
271 if opts.abort_on_failure {
272 let abort = Command::new("git")
273 .args(["rebase", "--abort"])
274 .current_dir(dir)
275 .output_with_context()
276 .await;
277 match abort {
278 Err(e) => {
279 tracing::warn!(dir = %dir.display(), error = %e, "git rebase --abort failed — worktree may be in inconsistent state");
280 }
281 Ok(o) if !o.status.success() => {
282 let stderr = String::from_utf8_lossy(&o.stderr);
283 tracing::warn!(dir = %dir.display(), stderr = %stderr, "git rebase --abort returned non-zero — worktree may be in inconsistent state");
284 }
285 _ => {}
286 }
287 }
288 restore_stash_by_hash(dir, stash_ref.as_deref()).await;
289 Ok(RebaseOutcome::Failed(stderr))
290 }
291 Err(e) => {
292 if opts.abort_on_failure {
293 let abort = Command::new("git")
294 .args(["rebase", "--abort"])
295 .current_dir(dir)
296 .output_with_context()
297 .await;
298 match abort {
299 Err(e) => {
300 tracing::warn!(dir = %dir.display(), error = %e, "git rebase --abort failed — worktree may be in inconsistent state");
301 }
302 Ok(o) if !o.status.success() => {
303 let stderr = String::from_utf8_lossy(&o.stderr);
304 tracing::warn!(dir = %dir.display(), stderr = %stderr, "git rebase --abort returned non-zero — worktree may be in inconsistent state");
305 }
306 _ => {}
307 }
308 }
309 restore_stash_by_hash(dir, stash_ref.as_deref()).await;
310 Err(e)
311 }
312 }
313}
314
315async fn restore_stash_by_hash(dir: &Path, stash_hash: Option<&str>) {
319 let Some(stash_hash) = stash_hash else {
320 return;
321 };
322
323 let apply = Command::new("git")
324 .args(["stash", "apply", stash_hash])
325 .current_dir(dir)
326 .output_with_context()
327 .await;
328 if apply.is_ok_and(|o| o.status.success()) {
329 let list = Command::new("git")
330 .args(["stash", "list", "--format=%H %gd"])
331 .current_dir(dir)
332 .output_with_context()
333 .await;
334 if let Ok(list_out) = list
335 && list_out.status.success()
336 {
337 let list_str = String::from_utf8_lossy(&list_out.stdout);
338 if let Some(stash_ref) = find_stash_ref_by_hash(&list_str, stash_hash) {
339 match Command::new("git")
340 .args(["stash", "drop", &stash_ref])
341 .current_dir(dir)
342 .output_with_context()
343 .await
344 {
345 Ok(drop_out) if !drop_out.status.success() => {
346 let stderr = String::from_utf8_lossy(&drop_out.stderr);
347 tracing::warn!(
348 dir = %dir.display(),
349 stash_ref = %stash_ref,
350 err = %stderr,
351 "stash drop failed after apply — entry may remain on stack"
352 );
353 }
354 Err(e) => {
355 tracing::warn!(
356 dir = %dir.display(),
357 stash_ref = %stash_ref,
358 error = %e,
359 "stash drop command failed after apply — entry may remain on stack"
360 );
361 }
362 _ => {}
363 }
364 } else {
365 tracing::warn!(
366 dir = %dir.display(),
367 stash = %stash_hash,
368 "stash applied but could not find ref by hash — stash entry may be orphaned on stack"
369 );
370 }
371 }
372 } else {
373 tracing::warn!(
374 dir = %dir.display(),
375 stash = %stash_hash,
376 "stash apply failed after rebase — stash preserved for manual recovery"
377 );
378 }
379}
380
381pub async fn auto_commit(
383 dir: &Path,
384 task_id: &str,
385 title: &str,
386 agent: &str,
387 attempt: u32,
388 when: super::commit::When,
389) -> anyhow::Result<bool> {
390 if !has_changes(dir).await {
391 return Ok(false);
392 }
393
394 tracing::info!(task_id, "auto-committing uncommitted changes");
395 let task_ref = format_task_ref(task_id);
396 let message = format!("{title}\n\nTask {task_ref}\nAgent: {agent}\nAttempt: {attempt}");
397 match super::commit::commit_all(dir, &message, agent, when).await? {
398 super::commit::Outcome::Committed => {
399 tracing::info!(task_id, "auto-commit succeeded");
400 Ok(true)
401 }
402 super::commit::Outcome::Nothing => Ok(false),
403 super::commit::Outcome::Refused {
404 by: super::commit::Tool::Git,
405 reason,
406 } => {
407 tracing::warn!(task_id, err = %reason, "git commit failed");
408 Ok(false)
409 }
410 super::commit::Outcome::Refused { reason, .. } => anyhow::bail!(reason),
411 }
412}
413
414const MAX_REBASE_COMMITS: usize = 50;
422
423pub async fn rebase_on_branch(dir: &Path, branch: &str) -> anyhow::Result<bool> {
433 let origin_branch = format!("origin/{branch}");
434
435 let fetch = time::timeout(
438 Duration::from_secs(120),
439 git()
440 .await
441 .args(["fetch", "origin", branch])
442 .kill_on_drop(true)
443 .current_dir(dir)
444 .output(),
445 )
446 .await
447 .map_err(|_| anyhow::anyhow!("git fetch timed out after 120s"))
448 .and_then(|r| r.map_err(Into::into));
449
450 match fetch {
451 Ok(o) if o.status.success() => {}
452 Ok(o) => {
453 let stderr = sanitize_push_error(&String::from_utf8_lossy(&o.stderr));
454 anyhow::bail!("failed to fetch origin/{branch}: {stderr}");
455 }
456 Err(e) => anyhow::bail!("failed to fetch origin/{branch}: {e}"),
457 }
458
459 let count_output = Command::new("git")
461 .args(["rev-list", "--count", &format!("{origin_branch}..HEAD")])
462 .current_dir(dir)
463 .output_with_context()
464 .await;
465
466 let commit_count: usize = match count_output {
467 Ok(o) if o.status.success() => {
468 let raw = String::from_utf8_lossy(&o.stdout);
469 raw.trim().parse().map_err(|e| {
470 anyhow::anyhow!(
471 "failed to parse commit count from git rev-list output {:?}: {e}",
472 raw.trim()
473 )
474 })?
475 }
476 Ok(o) => {
477 let stderr = String::from_utf8_lossy(&o.stderr);
478 anyhow::bail!("git rev-list --count failed: {stderr}");
479 }
480 Err(e) => anyhow::bail!("failed to run git rev-list --count: {e}"),
481 };
482
483 if commit_count == 0 {
484 return Ok(false);
486 }
487
488 if commit_count > MAX_REBASE_COMMITS {
489 anyhow::bail!(
490 "refusing to rebase {commit_count} commits on origin/{branch} (max {MAX_REBASE_COMMITS})"
491 );
492 }
493
494 tracing::info!(
495 branch = branch,
496 commit_count,
497 "rebasing local commits on origin/{branch}"
498 );
499
500 match stash_rebase_restore(dir, &origin_branch, StashRebaseOpts::default()).await? {
501 RebaseOutcome::Succeeded => Ok(true),
502 RebaseOutcome::Failed(e) => anyhow::bail!("rebase failed: {e}"),
503 RebaseOutcome::Skipped(reason) => anyhow::bail!("rebase skipped: {reason}"),
504 }
505}
506
507pub async fn rebase_on_default(dir: &Path, default_branch: &str) {
515 if rebase_in_progress(dir).await {
517 tracing::info!("rebase already in progress, skipping pre-dispatch rebase");
518 return;
519 }
520
521 let branch = get_current_branch(dir).await;
523 record_push_lease(dir, &branch, default_branch).await;
524
525 let _ = git()
528 .await
529 .args(["fetch", "origin"])
530 .current_dir(dir)
531 .output_with_context()
532 .await;
533
534 let commit_count = Command::new("git")
539 .args([
540 "rev-list",
541 "--count",
542 &format!("origin/{default_branch}..HEAD"),
543 ])
544 .current_dir(dir)
545 .output_with_context()
546 .await
547 .ok()
548 .and_then(|o| {
549 String::from_utf8_lossy(&o.stdout)
550 .trim()
551 .parse::<usize>()
552 .ok()
553 })
554 .unwrap_or(0);
555
556 if commit_count > MAX_REBASE_COMMITS {
557 tracing::warn!(
558 default_branch,
559 commit_count,
560 max = MAX_REBASE_COMMITS,
561 "skipping rebase: branch has too many commits to replay safely"
562 );
563 return;
564 }
565
566 match stash_rebase_restore(
567 dir,
568 &format!("origin/{default_branch}"),
569 StashRebaseOpts::default(),
570 )
571 .await
572 {
573 Ok(RebaseOutcome::Succeeded) => {
574 tracing::debug!(default_branch, "rebased worktree on default branch");
575 }
576 Ok(RebaseOutcome::Failed(e)) => {
577 tracing::warn!(default_branch, err = %e, "rebase failed, continuing with current state");
578 }
579 Ok(RebaseOutcome::Skipped(reason)) => {
580 tracing::warn!(default_branch, %reason, "stash failed before rebase, continuing with current state");
581 }
582 Err(e) => tracing::warn!(err = %e, "rebase error"),
583 }
584}
585
586pub(crate) async fn rebase_in_progress(dir: &Path) -> bool {
587 for name in ["rebase-merge", "rebase-apply"] {
588 let out = Command::new("git")
589 .args(["rev-parse", "--git-path", name])
590 .current_dir(dir)
591 .output_with_context()
592 .await;
593 if let Ok(o) = out {
594 let p = String::from_utf8_lossy(&o.stdout).trim().to_string();
595 if !p.is_empty() && dir.join(p).exists() {
596 return true;
597 }
598 }
599 }
600 false
601}
602
603pub(crate) fn remote_change_tools() -> Vec<String> {
606 [
607 "Bash(git remote set-url*)",
608 "Bash(git remote add*)",
609 "Bash(git remote remove*)",
610 "Bash(git remote rm*)",
611 "Bash(git remote rename*)",
612 "Bash(git config*remote.*)",
613 "Bash(git config*url.*)",
614 ]
615 .map(String::from)
616 .to_vec()
617}
618
619pub(crate) struct GitCommand {
621 inner: Command,
622}
623
624impl GitCommand {
625 pub(crate) fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Self {
626 self.inner.arg(arg);
627 self
628 }
629
630 pub(crate) fn args<I, S>(&mut self, args: I) -> &mut Self
631 where
632 I: IntoIterator<Item = S>,
633 S: AsRef<OsStr>,
634 {
635 self.inner.args(args);
636 self
637 }
638
639 pub(crate) fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Self {
640 self.inner.current_dir(dir);
641 self
642 }
643
644 pub(crate) fn env<K, V>(&mut self, key: K, val: V) -> &mut Self
645 where
646 K: AsRef<OsStr>,
647 V: AsRef<OsStr>,
648 {
649 self.inner.env(key, val);
650 self
651 }
652
653 pub(crate) fn kill_on_drop(&mut self, kill: bool) -> &mut Self {
654 self.inner.kill_on_drop(kill);
655 self
656 }
657
658 pub(crate) async fn output(&mut self) -> io::Result<Output> {
659 self.inner.output().await.map(sanitize_git_output)
660 }
661
662 pub(crate) async fn output_with_context(&mut self) -> anyhow::Result<Output> {
663 self.inner
664 .output_with_context()
665 .await
666 .map(sanitize_git_output)
667 }
668}
669
670pub(crate) async fn git() -> GitCommand {
673 let mut cmd = Command::new("git");
674 cmd.envs(build_git_auth_env().await).kill_on_drop(true);
675 GitCommand { inner: cmd }
676}
677
678pub(crate) async fn build_git_auth_env() -> Vec<(String, String)> {
699 let token = token::shared().get_token().await.ok().flatten();
700 build_git_auth_env_for_token(token)
701}
702
703fn build_git_auth_env_for_token(token: Option<String>) -> Vec<(String, String)> {
704 let mut config: Vec<(String, String)> = match token {
705 Some(t) if !t.is_empty() => {
706 let authed = format!("url.https://x-access-token:{t}@github.com/.insteadOf");
707 vec![
708 (authed.clone(), "https://github.com/".into()),
709 (authed, "git@github.com:".into()),
710 ]
711 }
712 _ => vec![(
713 "url.https://github.com/.insteadOf".into(),
714 "git@github.com:".into(),
715 )],
716 };
717 config.push(("commit.gpgsign".into(), "false".into()));
719 config.push(("tag.gpgsign".into(), "false".into()));
720
721 let mut env = vec![("GIT_CONFIG_COUNT".to_string(), config.len().to_string())];
722 for (n, (key, value)) in config.into_iter().enumerate() {
723 env.push((format!("GIT_CONFIG_KEY_{n}"), key));
724 env.push((format!("GIT_CONFIG_VALUE_{n}"), value));
725 }
726 env
727}
728
729pub(crate) fn is_workflow_scope_error(stderr: &str) -> bool {
736 stderr.contains("without `workflow` scope")
737 || stderr.contains("without 'workflow' scope")
738 || (stderr.contains("refusing to allow")
739 && stderr.contains("workflow")
740 && stderr.contains("scope"))
741}
742
743async fn strip_workflow_files(dir: &Path, default_branch: &str) -> anyhow::Result<bool> {
754 let output = Command::new("git")
756 .args([
757 "diff",
758 "--name-only",
759 &format!("origin/{default_branch}...HEAD"),
760 "--",
761 ".github/workflows/",
762 ])
763 .current_dir(dir)
764 .output_with_context()
765 .await?;
766
767 let workflow_files: Vec<String> = String::from_utf8_lossy(&output.stdout)
768 .lines()
769 .filter(|l| !l.is_empty())
770 .map(ToString::to_string)
771 .collect();
772
773 if workflow_files.is_empty() {
774 return Ok(false);
775 }
776
777 tracing::info!(
778 files = ?workflow_files,
779 "stripping workflow files from commits to bypass missing workflow scope"
780 );
781
782 let count_output = Command::new("git")
787 .args([
788 "rev-list",
789 "--count",
790 &format!("origin/{default_branch}..HEAD"),
791 ])
792 .current_dir(dir)
793 .output_with_context()
794 .await?;
795
796 let commit_count: usize = String::from_utf8_lossy(&count_output.stdout)
797 .trim()
798 .parse()
799 .unwrap_or(0);
800
801 if commit_count == 0 {
802 return Ok(false);
803 }
804
805 let log_output = Command::new("git")
810 .args([
811 "log",
812 "--format=%x00%H%n%B",
813 &format!("origin/{default_branch}..HEAD"),
814 ])
815 .current_dir(dir)
816 .output_with_context()
817 .await?;
818 let log_text = String::from_utf8_lossy(&log_output.stdout).to_string();
819
820 let commits: Vec<(String, String)> = log_text
824 .split('\0')
825 .filter(|s| !s.trim().is_empty())
826 .map(|block| {
827 let block = block.trim();
828 let first_nl = block.find('\n').unwrap_or(block.len());
829 let hash = block[..first_nl].to_string();
830 let msg = block[first_nl..].trim().to_string();
831 (hash, msg)
832 })
833 .collect::<Vec<_>>()
834 .into_iter()
835 .rev()
836 .collect();
837
838 if commits.is_empty() {
839 return Ok(false);
840 }
841
842 let reset = Command::new("git")
844 .args(["reset", "--soft", &format!("origin/{default_branch}")])
845 .current_dir(dir)
846 .output_with_context()
847 .await?;
848
849 if !reset.status.success() {
850 let stderr = String::from_utf8_lossy(&reset.stderr);
851 anyhow::bail!("git reset --soft failed during workflow file stripping: {stderr}");
852 }
853
854 let mut rm_args = vec!["rm", "--cached", "--ignore-unmatch", "--"];
856 let file_refs: Vec<&str> = workflow_files.iter().map(String::as_str).collect();
857 rm_args.extend(file_refs);
858
859 let rm = Command::new("git")
860 .args(&rm_args)
861 .current_dir(dir)
862 .output_with_context()
863 .await?;
864
865 if !rm.status.success() {
866 let stderr = String::from_utf8_lossy(&rm.stderr);
867 tracing::warn!("git rm --cached for workflow files failed (non-fatal): {stderr}");
868 }
869
870 let has_staged = Command::new("git")
873 .args(["diff", "--cached", "--quiet"])
874 .current_dir(dir)
875 .status()
876 .await
877 .is_ok_and(|s| !s.success());
878
879 if !has_staged {
880 tracing::warn!(
881 "after removing workflow files, no staged changes remain — \
882 the only changes were workflow files"
883 );
884 if let Some((hash, _)) = commits.last() {
887 let _ = Command::new("git")
888 .args(["reset", "--soft", hash])
889 .current_dir(dir)
890 .output_with_context()
891 .await;
892 }
893 return Ok(false);
894 }
895
896 let commit_msg = if commits.len() == 1 {
898 commits[0].1.clone()
899 } else {
900 let mut combined = String::new();
902 for (i, (_, msg)) in commits.iter().enumerate() {
903 if i > 0 {
904 combined.push_str("\n\n");
905 }
906 combined.push_str(msg);
907 }
908 combined.push_str("\n\n[workflow files stripped: token lacks `workflow` scope]");
909 combined
910 };
911
912 let commit = super::commit::git_commit(dir, &commit_msg, "orchestrator").await?;
914
915 if !commit.status.success() {
916 let stderr = String::from_utf8_lossy(&commit.stderr);
917 if let Some((original_head, _)) = commits.last() {
919 let _ = Command::new("git")
920 .args(["reset", "--hard", original_head])
921 .current_dir(dir)
922 .output_with_context()
923 .await;
924 }
925 anyhow::bail!("git commit failed during workflow file stripping: {stderr}");
926 }
927
928 tracing::info!(
929 stripped_files = ?workflow_files,
930 original_commits = commit_count,
931 "successfully stripped workflow files from commits"
932 );
933
934 Ok(true)
935}
936
937pub(crate) async fn get_current_branch(dir: &Path) -> String {
939 let output = Command::new("git")
940 .args(["branch", "--show-current"])
941 .current_dir(dir)
942 .output_with_context()
943 .await;
944
945 match output {
946 Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
947 _ => String::new(),
948 }
949}
950
951pub async fn count_changed_files(dir: &Path) -> anyhow::Result<usize> {
953 let output = Command::new("git")
955 .args(["status", "--porcelain"])
956 .current_dir(dir)
957 .output_with_context()
958 .await?;
959
960 let status_output = String::from_utf8_lossy(&output.stdout);
961 let count = status_output
962 .lines()
963 .filter(|line| {
964 let prefix = line.get(0..2).unwrap_or("");
965 prefix.starts_with('M')
967 || prefix.starts_with('A')
968 || prefix.starts_with('R')
969 || prefix.starts_with('C')
970 || prefix.starts_with('?')
971 })
972 .count();
973
974 Ok(count)
975}
976
977async fn check_push_needed(dir: &Path, branch: &str, default_branch: &str) -> (bool, bool) {
985 let remote_exists = Command::new("git")
987 .args(["rev-parse", &format!("origin/{branch}")])
988 .current_dir(dir)
989 .output_with_context()
990 .await
991 .is_ok_and(|o| o.status.success());
992
993 let compare_ref = if remote_exists {
994 format!("origin/{branch}..{branch}")
995 } else {
996 format!("origin/{default_branch}..{branch}")
998 };
999
1000 tracing::debug!(
1001 branch,
1002 compare_ref,
1003 remote_exists,
1004 "checking unpushed commits"
1005 );
1006
1007 let output = Command::new("git")
1008 .args(["log", &compare_ref, "--oneline"])
1009 .current_dir(dir)
1010 .output_with_context()
1011 .await;
1012
1013 let has_unpushed = match output {
1014 Ok(o) if o.status.success() => {
1015 let out = String::from_utf8_lossy(&o.stdout);
1016 let has = !out.trim().is_empty();
1017 tracing::debug!(branch, has_unpushed = has, "unpushed commits check result");
1018 has
1019 }
1020 _ => {
1021 tracing::debug!(branch, "git log failed for compare ref, assuming unpushed");
1022 true
1025 }
1026 };
1027
1028 (remote_exists, has_unpushed)
1029}
1030
1031#[cfg(test)]
1032mod tests;