git_policy_cli/auto_push_reconcile.rs
1//! What:
2//! Publishing a landed commit when the remote branch advanced after the commit landed:
3//! the merge of the remote tip and the local tip is computed in the object store,
4//! committed without a worktree or an index, and pushed with a plain push.
5//! Why:
6//! A rejected `push` of a branch that the remote moved cannot succeed again, and an ordinary merge in the active
7//! worktree can be blocked, or made unsafe, by another consumer's uncommitted files.
8//! `git merge-tree --write-tree` and `git commit-tree` read and write only objects, so the active worktree,
9//! its index and its untracked files are never touched while merging, and both histories stay reachable from the
10//! published tip.
11//! Only after the push succeeds is the branch fast-forwarded, and only where nothing can be lost: a dirty worktree
12//! follows too when the move changes none of the files its uncommitted work touches.
13//! An amended or rebased branch is merged like any other: nothing already published is lost, and the replaced
14//! commits stay in the remote history beside the new ones.
15
16/// The coordinator's Git, its command builder, queries and error type.
17use super::auto_push_single_flight::{
18 PushAttempt, PushGit, SingleFlightError, git_command, git_output, run_query,
19};
20/// The deadline-bound runner of network commands and the limits it applies.
21use super::auto_push_dirty_paths::{diff_paths, listed, overlapping_paths, status_paths};
22use super::bounded_push::{STOP_GRACE, apply_low_speed_defaults, push_deadline, run_bounded_push};
23/// The auto-push's bounded `git push` with the Git LFS upload.
24use super::lfs_bounded_push::run_push;
25/// The diagnostic log of the wrapper.
26use super::diagnostic_log::{debug, warn};
27/// Owned OS strings for Git arguments.
28use std::ffi::OsString;
29
30/// Tag used for diagnostics from this module.
31const TAG: &str = "cli-git";
32
33/// Prefix of every line this module adds to a push's output, so the terminal filter can keep it.
34pub const RECONCILE_LINE_PREFIX: &str = "cli-git: auto-push: ";
35
36/// Start of the line that explains why a rejected push stays unpublished; the generic "run `git push`" note is then
37/// wrong advice and is not printed.
38pub const RECONCILE_FAILED_PREFIX: &str = "cli-git: auto-push: not published: ";
39
40/// How many times the remote tip is fetched, merged and pushed before the push is reported as failed.
41pub const MAX_RECONCILE_ATTEMPTS: u32 = 10;
42
43/// The marker Git prints for a push the remote refused as stale; the word is not translated.
44const REJECTED_MARKER: &str = "[rejected]";
45
46/// The marker Git prints for an update that the remote's own rules refused, such as GitHub's protected branch (GH006).
47/// A remote that is updated by two pushes at once refuses the slower one this way, with no word about staleness.
48const REMOTE_REJECTED_MARKER: &str = "[remote rejected]";
49
50/// Where the plain push goes: the branch's upstream remote and the ref it tracks there.
51///
52/// In TS you'd write (pseudocode):
53/// ```ts
54/// type Destination = { remote: string; mergeRef: string };
55/// ```
56#[derive(Clone, Debug, Eq, PartialEq)]
57pub struct Destination {
58 /// Remote name from `branch.<name>.remote`.
59 pub remote: String,
60 /// Full ref from `branch.<name>.merge`, for example `refs/heads/main`.
61 pub merge_ref: String,
62}
63
64/// What:
65/// Whether a push's output shows a refusal that a moved remote branch can explain: Git's stale `[rejected]`, or the
66/// remote's own `[remote rejected]`.
67/// Why:
68/// Only a refusal of an update that raced another push can be cured by merging; an authentication failure or an offline
69/// error must be reported as they are.
70/// The message cannot tell a race from a rule that refuses every push, so the caller compares the remote tip with the
71/// branch and returns the refusal unchanged when the remote has not moved.
72///
73/// In TS you'd write (pseudocode):
74/// ```ts
75/// const wasRejectedAsStale = (output: string) => output.includes('[rejected]') || output.includes('[remote rejected]');
76/// ```
77pub fn was_rejected_as_stale(output: &str) -> bool {
78 return output.contains(REJECTED_MARKER) || output.contains(REMOTE_REJECTED_MARKER);
79}
80
81/// A failed attempt that explains itself and keeps the push output that came before.
82///
83/// In TS you'd write (pseudocode):
84/// ```ts
85/// { exitCode: 1, output: `${previous}\n${RECONCILE_FAILED_PREFIX}${reason}` }
86/// ```
87fn unpublished(failed_prefix: &str, previous: &str, exit_code: i64, reason: &str) -> PushAttempt {
88 return PushAttempt {
89 exit_code: if exit_code == 0 { 1 } else { exit_code },
90 output: format!("{previous}\n{failed_prefix}{reason}"),
91 };
92}
93
94/// Argument list from string literals and owned text.
95///
96/// In TS you'd write (pseudocode):
97/// ```ts
98/// ['merge-tree', '--write-tree', ...]
99/// ```
100fn argv(parts: &[&str]) -> Vec<OsString> {
101 return parts.iter().map(OsString::from).collect();
102}
103
104/// What:
105/// Whether the first commit is the second or one of its ancestors, or nothing when Git cannot tell.
106/// Why:
107/// Exit `0` and `1` are the answers; any other exit means an object is missing, and that is not an answer.
108///
109/// In TS you'd write (pseudocode):
110/// ```ts
111/// async function isAncestor({ ancestor, descendant }): Promise<boolean | undefined>;
112/// ```
113fn is_ancestor(
114 git: &PushGit,
115 ancestor: &str,
116 descendant: &str,
117) -> Result<Option<bool>, SingleFlightError> {
118 let output = run_query(
119 git,
120 &argv(&["merge-base", "--is-ancestor", ancestor, descendant]),
121 )?;
122 return Ok(match output.code {
123 Some(0) => Some(true),
124 Some(1) => Some(false),
125 _ => None,
126 });
127}
128
129/// What:
130/// The trimmed value of a Git setting, empty when it is not set.
131/// Why:
132/// An unset key exits `1` and prints nothing; the callers treat "not set" and "set to nothing" alike.
133///
134/// In TS you'd write (pseudocode):
135/// ```ts
136/// async function configValue({ key }): Promise<string>;
137/// ```
138fn config_value(git: &PushGit, key: &str) -> Result<String, SingleFlightError> {
139 let value = run_query(git, &argv(&["config", "--get", key]))?;
140 return Ok(String::from_utf8_lossy(&value.stdout).trim().to_owned());
141}
142
143/// What:
144/// The remote and the branch ref that the plain `git push` of this branch updates, when they can be named.
145/// Why:
146/// The merge must be made with the tip of the branch the rejected push targeted: with a push remote, a triangular
147/// setup or `push.default=current` that is not the tracked branch.
148/// The push remote follows Git's order (`branch.<name>.pushRemote`, then `remote.pushDefault`, then
149/// `branch.<name>.remote`), and `push.default` picks the ref: `current` and a triangular `simple` push to the
150/// branch's own name, `upstream` and a non-triangular `simple` push to the tracked ref.
151/// `@{push}` is not used because Git refuses to resolve it for a push remote that differs from the tracked one,
152/// although the push itself works.
153/// The remote `.`, a `remote.<name>.push` refspec, `matching`, `nothing` and a target outside `refs/heads` are not
154/// reconciled, because the rejection then came from a destination this module cannot name.
155///
156/// In TS you'd write (pseudocode):
157/// ```ts
158/// async function readDestination({ branch }): Promise<Destination | undefined>;
159/// ```
160fn read_destination(
161 git: &PushGit,
162 branch_ref: &str,
163) -> Result<Option<Destination>, SingleFlightError> {
164 let Some(name) = branch_ref.strip_prefix("refs/heads/") else {
165 return Ok(None);
166 };
167 let tracked_remote = config_value(git, &format!("branch.{name}.remote"))?;
168 let mut push_remote = config_value(git, &format!("branch.{name}.pushRemote"))?;
169 if push_remote.is_empty() {
170 push_remote = config_value(git, "remote.pushDefault")?;
171 }
172 if push_remote.is_empty() {
173 push_remote.clone_from(&tracked_remote);
174 }
175 if push_remote.is_empty() || push_remote == "." {
176 return Ok(None);
177 }
178 let refspecs = run_query(
179 git,
180 &argv(&["config", "--get-all", &format!("remote.{push_remote}.push")]),
181 )?;
182 if !refspecs.stdout.is_empty() {
183 return Ok(None);
184 }
185 let triangular = push_remote != tracked_remote;
186 let mode = config_value(git, "push.default")?;
187 let merge_ref = config_value(git, &format!("branch.{name}.merge"))?;
188 let target = match (mode.as_str(), triangular) {
189 ("current", _) | ("" | "simple", true) => format!("refs/heads/{name}"),
190 ("" | "simple" | "upstream" | "tracking", false) => merge_ref,
191 _ => return Ok(None),
192 };
193 if !target.starts_with("refs/heads/") || target == "refs/heads/" {
194 return Ok(None);
195 }
196 return Ok(Some(Destination {
197 remote: push_remote,
198 merge_ref: target,
199 }));
200}
201
202/// What:
203/// The arguments of a push that names its destination, when the plain `git push` of this branch cannot.
204/// Why:
205/// Under `push.default=simple` Git refuses to push a branch whose upstream has another name (a linked worktree
206/// branch created from `origin/main` is the usual case) before it contacts the remote, so no reconcile can start.
207/// The destination `read_destination` resolves is exactly where the person tracked the branch, so the push names it.
208/// A branch whose destination has its own name needs no such push, and nothing is returned for it.
209///
210/// In TS you'd write (pseudocode):
211/// ```ts
212/// async function namedDestinationPush({ branchRef }): Promise<string[] | undefined>; // ['push', remote, `${branchRef}:${mergeRef}`]
213/// ```
214pub fn named_destination_push(
215 git: &PushGit,
216 branch_ref: &str,
217) -> Result<Option<Vec<String>>, SingleFlightError> {
218 let Some(destination) = read_destination(git, branch_ref)? else {
219 return Ok(None);
220 };
221 if destination.merge_ref == branch_ref {
222 return Ok(None);
223 }
224 return Ok(Some(vec![
225 String::from("push"),
226 destination.remote,
227 format!("{branch_ref}:{}", destination.merge_ref),
228 ]));
229}
230
231/// What:
232/// Fetch the remote branch into a private ref and return the commit it names.
233/// Why:
234/// `FETCH_HEAD` is shared by every fetch in the repository, so another process could replace it between the fetch
235/// and the read; a ref named for this process cannot be replaced, and it is deleted before this returns.
236///
237/// In TS you'd write (pseudocode):
238/// ```ts
239/// async function fetchRemoteTip({ destination }): Promise<string | PushAttempt>;
240/// ```
241fn fetch_remote_tip(
242 git: &PushGit,
243 destination: &Destination,
244) -> Result<Result<String, PushAttempt>, SingleFlightError> {
245 let private_ref = format!("refs/cli-git/auto-push/fetch-{}", std::process::id());
246 let refspec = format!("+{}:{private_ref}", destination.merge_ref);
247 let arguments = argv(&[
248 "fetch",
249 "--no-tags",
250 "--quiet",
251 &destination.remote,
252 &refspec,
253 ]);
254 let mut command = git_command(git, &arguments);
255 apply_low_speed_defaults(&mut command, &git.environment);
256 let fetched = run_bounded_push(command, push_deadline(&git.environment), STOP_GRACE, git.environment.as_slice())?;
257 if fetched.exit_code != 0 {
258 return Ok(Err(fetched));
259 }
260 let tip = git_output(
261 git,
262 &argv(&[
263 "rev-parse",
264 "--verify",
265 &format!("{private_ref}^{{commit}}"),
266 ]),
267 );
268 // The private ref is scaffolding; a failed deletion leaves one small ref that the next run overwrites.
269 let _deleted = run_query(git, &argv(&["update-ref", "-d", &private_ref]));
270 return Ok(Ok(tip?));
271}
272
273/// What:
274/// Commit the merge of two tips from objects alone and return its OID, or the paths that conflict.
275/// Why:
276/// `merge-tree --write-tree` exits `1` for a conflicted merge and lists the paths; nothing is written to a worktree.
277///
278/// In TS you'd write (pseudocode):
279/// ```ts
280/// async function commitMerge({ local, remote, message }): Promise<{ oid } | { conflicts }>;
281/// ```
282fn commit_merge(
283 git: &PushGit,
284 local: &str,
285 remote: &str,
286 message: &str,
287) -> Result<Result<String, Vec<String>>, SingleFlightError> {
288 let merged = run_query(
289 git,
290 &argv(&[
291 "merge-tree",
292 "--write-tree",
293 "--no-messages",
294 "--name-only",
295 "--allow-unrelated-histories",
296 local,
297 remote,
298 ]),
299 )?;
300 let text = String::from_utf8_lossy(&merged.stdout).into_owned();
301 let mut lines = text.lines();
302 let tree = lines.next().unwrap_or_default().trim().to_owned();
303 if merged.code == Some(1) {
304 let paths: Vec<String> = lines
305 .map(str::trim)
306 .filter(|line| {
307 return !line.is_empty();
308 })
309 .map(str::to_owned)
310 .collect();
311 return Ok(Err(paths));
312 }
313 if merged.code != Some(0) {
314 return Err(SingleFlightError::Git {
315 arguments: format!("merge-tree --write-tree {local} {remote}"),
316 code: merged.code,
317 stderr: String::from_utf8_lossy(&merged.stderr).into_owned(),
318 });
319 }
320 let mut commit_tree = vec!["commit-tree"];
321 if signs_commits(git)? {
322 commit_tree.push("-S");
323 }
324 commit_tree.extend(["-p", local, "-p", remote, "-m", message, &tree]);
325 let oid = git_output(git, &argv(&commit_tree))?;
326 return Ok(Ok(oid));
327}
328
329/// What:
330/// Whether `commit.gpgsign` asks for signed commits.
331/// Why:
332/// `git commit-tree` signs only when given `-S` and never reads `commit.gpgsign`, so the merge would be the one
333/// unsigned commit of a signed branch, which a remote that requires verified signatures rejects.
334/// An unset key is `git config` exit `1`; any other failure is reported like every failed command.
335///
336/// In TS you'd write (pseudocode):
337/// ```ts
338/// async function signsCommits(git): Promise<boolean>;
339/// ```
340fn signs_commits(git: &PushGit) -> Result<bool, SingleFlightError> {
341 let asked = run_query(
342 git,
343 &argv(&["config", "--type=bool", "--get", "commit.gpgsign"]),
344 )?;
345 if asked.code == Some(1) {
346 return Ok(false);
347 }
348 if asked.code != Some(0) {
349 return Err(SingleFlightError::Git {
350 arguments: String::from("config --type=bool --get commit.gpgsign"),
351 code: asked.code,
352 stderr: String::from_utf8_lossy(&asked.stderr).into_owned(),
353 });
354 }
355 return Ok(asked.stdout.trim_ascii() == b"true");
356}
357
358/// What:
359/// Whether the status read after a fast-forward differs from the one read before it.
360/// `&[u8]` borrows Git's output.
361/// Why:
362/// The uncommitted work must read exactly as it did; a difference is the only sign that the move touched it.
363///
364/// In TS you'd write (pseudocode):
365/// ```ts
366/// function statusDiffers(before: Uint8Array, after: Uint8Array): boolean;
367/// ```
368fn status_differs(before: &[u8], after: &[u8]) -> bool {
369 return before != after;
370}
371
372/// What:
373/// Fast-forward the pushed branch and this worktree to the published merge, or the reason that was not done.
374/// The success value says whether uncommitted work was left in place.
375/// Why:
376/// A branch left behind the remote makes the next commit rejected again, and the person at the keyboard would have
377/// to merge by hand; the merge contains the branch tip, so the move is a pure fast-forward.
378/// It is attempted only where nothing can be lost or surprised: the worktree has the branch checked out at the tip
379/// that was pushed, and no uncommitted change (tracked file, staged entry, or either name of a staged rename)
380/// lies in a file the move writes.
381/// Another session's work in progress therefore never holds the branch behind the remote, while a move that
382/// would write over such a file is left for the person.
383/// The status read takes no optional lock, and `git merge --ff-only` refuses, without changing anything, a move that
384/// would overwrite an untracked file or a change made after the status read.
385/// Every refusal is a reason for the report, never a failure: the merge is already published.
386///
387/// In TS you'd write (pseudocode):
388/// ```ts
389/// async function advanceLocalBranch({ git, branchRef, local, mergeOid }): Promise<{ reason?: string; keptChanges?: boolean }>;
390/// ```
391fn advance_local_branch(
392 git: &PushGit,
393 branch_ref: &str,
394 local: &str,
395 merge_oid: &str,
396) -> Result<Result<bool, String>, SingleFlightError> {
397 let checked_out = run_query(git, &argv(&["symbolic-ref", "--quiet", "HEAD"]))?;
398 if checked_out.code != Some(0) {
399 return Ok(Err(String::from("HEAD is detached")));
400 }
401 if String::from_utf8_lossy(&checked_out.stdout).trim() != branch_ref {
402 return Ok(Err(String::from(
403 "this worktree has another branch checked out",
404 )));
405 }
406 let head = run_query(git, &argv(&["rev-parse", "--verify", "HEAD^{commit}"]))?;
407 if String::from_utf8_lossy(&head.stdout).trim() != local {
408 return Ok(Err(String::from(
409 "the branch moved after the commit landed",
410 )));
411 }
412 let status_arguments = argv(&[
413 "--no-optional-locks",
414 "status",
415 "--porcelain=v1",
416 "-z",
417 "--untracked-files=no",
418 ]);
419 let status = run_query(git, &status_arguments)?;
420 if status.code != Some(0) {
421 return Ok(Err(String::from("the worktree status could not be read")));
422 }
423 let dirty = status_paths(&status.stdout);
424 let kept: bool = !dirty.is_empty();
425 if kept {
426 let incoming = run_query(
427 git,
428 &argv(&["diff", "--name-only", "-z", "--no-renames", local, merge_oid]),
429 )?;
430 if incoming.code != Some(0) {
431 return Ok(Err(String::from(
432 "the files the merge changes could not be read",
433 )));
434 }
435 let overlap = overlapping_paths(&dirty, &diff_paths(&incoming.stdout));
436 if !overlap.is_empty() {
437 return Ok(Err(format!(
438 "the worktree has uncommitted changes to files the merge changes: {}",
439 listed(&overlap)
440 )));
441 }
442 }
443 let moved = run_query(git, &argv(&["merge", "--ff-only", "--quiet", merge_oid]))?;
444 if moved.code != Some(0) {
445 let detail = String::from_utf8_lossy(&moved.stderr);
446 return Ok(Err(format!(
447 "Git refused the fast-forward: {}",
448 detail.lines().next().unwrap_or_default().trim()
449 )));
450 }
451 if kept {
452 // The uncommitted work must read exactly as it did; the move is already done, so a difference is reported.
453 let after = run_query(git, &status_arguments)?;
454 if status_differs(&status.stdout, &after.stdout) {
455 warn(
456 TAG,
457 "the worktree status differs after the fast-forward; compare it with the status before the commit",
458 );
459 }
460 }
461 return Ok(Ok(kept));
462}
463
464/// What:
465/// Merge the remote tip into the pushed branch's tip and publish the result, a bounded number of times.
466/// Why:
467/// Another worktree advancing the remote makes the plain push fail for good, while both histories are valid and
468/// must both be kept; the merge is published as a new commit above the local tip, so the landed commit stays
469/// reachable and nothing is forced.
470/// Once the merge is published, the branch and its worktree are fast-forwarded to it when that cannot lose or
471/// overwrite anything; otherwise they are left as they are and the report says why.
472/// A push destination Git cannot name, a conflict, an exhausted retry budget and every failure of a command are
473/// reported, and only the first leaves the original rejection unchanged.
474///
475/// In TS you'd write (pseudocode):
476/// ```ts
477/// async function reconcileDivergentPush({ git, branchRef, rejected }): Promise<PushAttempt>;
478/// ```
479pub fn reconcile_divergent_push(
480 git: &PushGit,
481 branch_ref: &str,
482 rejected: PushAttempt,
483) -> Result<PushAttempt, SingleFlightError> {
484 if !was_rejected_as_stale(&rejected.output) {
485 return Ok(rejected);
486 }
487 let Some(destination) = read_destination(git, branch_ref)? else {
488 debug(
489 TAG,
490 "the push destination cannot be resolved to a remote branch; no reconcile",
491 );
492 return Ok(rejected);
493 };
494 let local = git_output(
495 git,
496 &argv(&["rev-parse", "--verify", &format!("{branch_ref}^{{commit}}")]),
497 )?;
498 let plan = Reconcile {
499 destination,
500 local,
501 branch_ref: Some(branch_ref),
502 label: "auto-push",
503 explicit: false,
504 };
505 let mut push_merge = |target: &Destination, merge_oid: &str| -> Result<PushAttempt, SingleFlightError> {
506 let arguments = argv(&[
507 "push",
508 &target.remote,
509 &format!("{merge_oid}:{}", target.merge_ref),
510 ]);
511 return run_push(git, &arguments);
512 };
513 return Ok(match integrate_and_push(git, &plan, rejected, &mut push_merge)? {
514 Integrated::NotDivergent(attempt) | Integrated::Finished(attempt) => attempt,
515 });
516}
517
518/// What:
519/// What one reconcile run integrates, where, and how it words and limits itself.
520/// `Option<&str>` is "the branch, or nothing for a detached HEAD".
521/// Why:
522/// Auto-push and an explicit push share the loop; they differ in the line prefix they print, in whether the branch
523/// follows the published merge, and in how much of a failure they keep quiet about.
524/// An explicit push already printed Git's own refusal, so a remote that cannot be fetched, a remote that did not
525/// diverge, and a failure that is not a stale update are left exactly as the push reported them.
526///
527/// In TS you'd write (pseudocode):
528/// ```ts
529/// type Reconcile = { destination: Destination; local: string; branchRef?: string; label: string; explicit: boolean };
530/// ```
531pub struct Reconcile<'a> {
532 /// The remote and the ref the rejected push updated.
533 pub destination: Destination,
534 /// The commit the rejected push sent.
535 pub local: String,
536 /// The branch that follows the published merge when it can, or nothing for a detached HEAD.
537 pub branch_ref: Option<&'a str>,
538 /// The word after `cli-git:` in every line the run adds.
539 pub label: &'a str,
540 /// Whether the rejected push was typed by a person and has already shown its own output.
541 pub explicit: bool,
542}
543
544/// How a reconcile run ended.
545///
546/// In TS you'd write (pseudocode):
547/// ```ts
548/// type Integrated = { kind: 'not-divergent'; attempt } | { kind: 'finished'; attempt };
549/// ```
550pub enum Integrated {
551 /// The remote did not diverge, or the run could not tell; the rejected attempt stands as it was.
552 NotDivergent(PushAttempt),
553 /// The run published the merge, or says why it did not.
554 Finished(PushAttempt),
555}
556
557/// What:
558/// Merge the remote tip into the pushed commit and publish the result, a bounded number of times.
559/// Why:
560/// Another worktree advancing the remote makes the plain push fail for good, while both histories are valid and
561/// must both be kept; the merge is published as a new commit above the local tip, so the landed commit stays
562/// reachable and nothing is forced.
563/// `push_merge` publishes one merge, and is told the destination and the merge commit.
564///
565/// In TS you'd write (pseudocode):
566/// ```ts
567/// async function integrateAndPush({ git, plan, rejected, pushMerge }): Promise<Integrated>;
568/// ```
569pub fn integrate_and_push(
570 git: &PushGit,
571 plan: &Reconcile<'_>,
572 rejected: PushAttempt,
573 push_merge: &mut dyn FnMut(&Destination, &str) -> Result<PushAttempt, SingleFlightError>,
574) -> Result<Integrated, SingleFlightError> {
575 let destination = plan.destination.clone();
576 let local = plan.local.clone();
577 let label = plan.label;
578 let line_prefix = format!("cli-git: {label}: ");
579 let failed_prefix = format!("{line_prefix}not published: ");
580 let short = destination
581 .merge_ref
582 .strip_prefix("refs/heads/")
583 .unwrap_or(&destination.merge_ref)
584 .to_owned();
585 let message = format!(
586 "Merge {}/{short} into {short}\n\nCreated by cli-git {label} because {}/{short} advanced after the commit landed.",
587 destination.remote, destination.remote
588 );
589 let mut previous = rejected.output.clone();
590 // The remote tip a merge was pushed against, with the refusal it got: a remote that still shows that tip did not
591 // move, so the refusal was a rule and not a race.
592 let mut refused_against: Option<(String, PushAttempt)> = None;
593 for attempt in 1..=MAX_RECONCILE_ATTEMPTS {
594 let remote_tip = match fetch_remote_tip(git, &destination)? {
595 Ok(tip) => tip,
596 Err(failed) => {
597 if plan.explicit && refused_against.is_none() {
598 debug(
599 TAG,
600 "the remote could not be fetched after an explicit push failed; its own report stands",
601 );
602 return Ok(Integrated::NotDivergent(rejected));
603 }
604 return Ok(Integrated::Finished(unpublished(
605 &failed_prefix,
606 &format!("{previous}\n{}", failed.output),
607 failed.exit_code,
608 &format!(
609 "{}/{short} has commits this branch lacks, and fetching them failed; nothing was pushed and the worktree was not touched.",
610 destination.remote
611 ),
612 )));
613 }
614 };
615 if let Some((tip, refusal)) = refused_against.take()
616 && tip == remote_tip
617 {
618 debug(
619 TAG,
620 "the remote did not move after it refused the merge; the refusal is final",
621 );
622 return Ok(Integrated::Finished(refusal));
623 }
624 match (
625 is_ancestor(git, &remote_tip, &local)?,
626 is_ancestor(git, &local, &remote_tip)?,
627 ) {
628 (Some(true), _) => {
629 debug(
630 TAG,
631 "the remote tip is behind the branch; the rejection was not a divergence",
632 );
633 return Ok(Integrated::NotDivergent(rejected));
634 }
635 (_, Some(true)) if plan.explicit => {
636 debug(
637 TAG,
638 "the remote already contains the pushed commit; the explicit push failed for another reason",
639 );
640 return Ok(Integrated::NotDivergent(rejected));
641 }
642 (_, Some(true)) => {
643 return Ok(Integrated::Finished(PushAttempt {
644 exit_code: 0,
645 output: format!(
646 "{line_prefix}{}/{short} already contains {local}; nothing to push.",
647 destination.remote
648 ),
649 }));
650 }
651 (Some(false), Some(false)) => {}
652 _ => {
653 if plan.explicit {
654 return Ok(Integrated::NotDivergent(rejected));
655 }
656 return Ok(Integrated::Finished(unpublished(
657 &failed_prefix,
658 &previous,
659 rejected.exit_code,
660 "Git could not relate the branch to the remote tip; nothing was pushed and the worktree was not touched.",
661 )));
662 }
663 }
664 let merge_oid = match commit_merge(git, &local, &remote_tip, &message)? {
665 Ok(oid) => oid,
666 Err(paths) => {
667 return Ok(Integrated::Finished(unpublished(
668 &failed_prefix,
669 &previous,
670 rejected.exit_code,
671 &format!(
672 "merging {}/{short} into {short} conflicts in: {}. Nothing was pushed and the worktree was not touched; \
673 merge {}/{short} in a separate worktree, resolve the conflicts and push.",
674 destination.remote,
675 paths.join(", "),
676 destination.remote
677 ),
678 )));
679 }
680 };
681 debug(
682 TAG,
683 &format!(
684 "attempt {attempt}: pushing the merge {merge_oid} of {local} and {remote_tip}"
685 ),
686 );
687 let pushed = push_merge(&destination, &merge_oid)?;
688 if pushed.exit_code == 0 {
689 let branch = plan
690 .branch_ref
691 .map(|reference| {
692 return reference.strip_prefix("refs/heads/").unwrap_or(reference);
693 })
694 .unwrap_or("HEAD");
695 let advanced = match plan.branch_ref {
696 Some(branch_ref) => advance_local_branch(git, branch_ref, &local, &merge_oid)?,
697 None => Err(String::from("HEAD is detached")),
698 };
699 let followed = match advanced {
700 Ok(false) => format!("{branch} and the worktree were fast-forwarded to it."),
701 Ok(true) => format!(
702 "{branch} and the worktree were fast-forwarded to it; your uncommitted changes were left as they are."
703 ),
704 Err(reason) => {
705 debug(TAG, &format!("{branch} was not fast-forwarded: {reason}"));
706 format!(
707 "{branch} itself and the worktree are unchanged ({reason}); update {branch} with `git merge --ff-only {}/{short}` \
708 when the worktree allows.",
709 destination.remote
710 )
711 }
712 };
713 return Ok(Integrated::Finished(PushAttempt {
714 exit_code: 0,
715 output: format!(
716 "{}\n{line_prefix}{}/{short} had new commits, so the merge {merge_oid} of {branch} and {}/{short} \
717 was published. {followed}",
718 pushed.output, destination.remote, destination.remote
719 )
720 .trim_start_matches('\n')
721 .to_owned(),
722 }));
723 }
724 if !plan.explicit && !was_rejected_as_stale(&pushed.output) {
725 return Ok(Integrated::Finished(pushed));
726 }
727 previous = pushed.output.clone();
728 refused_against = Some((remote_tip, pushed));
729 }
730 return Ok(Integrated::Finished(unpublished(
731 &failed_prefix,
732 &previous,
733 rejected.exit_code,
734 &format!(
735 "{}/{short} advanced again during each of {MAX_RECONCILE_ATTEMPTS} attempts, so nothing was pushed and the worktree was not touched. \
736 Push again when the remote is quiet.",
737 destination.remote
738 ),
739 )));
740}
741
742/// Reconcile behavior is controlled in the test module.
743#[cfg(test)]
744#[path = "auto_push_reconcile_tests.rs"]
745mod tests;