Skip to main content

grit_lib/remote/
push_plan.rs

1//! Resolve remotes and refspecs for [`Remote::push`](crate::remote::Remote::push).
2//!
3//! [`resolve_push`] turns a [`PushRequest`] (CLI flags and positional refspecs)
4//! into a [`ResolvedPush`] of concrete [`PushRefSpec`] entries, matching Git's
5//! push refspec and remote-selection rules.
6//!
7//! A typical push classifies its positionals with [`resolve_push_invocation`], loads the remote's
8//! advertisement with [`load_push_plan_context`], plans with [`resolve_push`], and sends the
9//! result through the [`Remote`] returned by [`open_push_destination`].
10
11use std::collections::{HashMap, HashSet};
12use std::path::Path;
13
14use thiserror::Error;
15
16use crate::branch_tracking::{apply_push_set_upstream, remote_tracking_ref_for_remote_ref};
17use crate::config::gitmodules::gitdir::is_git_directory;
18use crate::config::{parse_git_config_maybe_bool, ConfigSet};
19use crate::merge_base::is_ancestor;
20use crate::objects::{ObjectId, ObjectKind};
21use crate::push_report::PushRefResult;
22use crate::refs;
23use crate::refspec::{parse_push_refspec, RefspecItem};
24use crate::remote::{HttpClientFactory, PreflightHttpClientFactory, Remote, RemoteRef};
25use crate::repo::Repository;
26use crate::repo_handles::has_remote_section;
27use crate::repo_handles::RepositoryRemotes;
28use crate::rev_parse::{resolve_push_full_ref_for_branch, resolve_revision_for_verify};
29use crate::state::{resolve_head, HeadState};
30use crate::transfer::{resolve_push_delete_ref, PushRefSpec};
31
32pub use crate::remote::DEFAULT_REMOTE;
33
34/// How non-fast-forward updates are allowed during a push.
35#[derive(Debug, Clone, Default, PartialEq, Eq)]
36pub enum ForceMode {
37    /// Reject non-fast-forward updates (default).
38    #[default]
39    None,
40    /// Unconditional force (`--force`).
41    Force,
42    /// Guarded force (`--force-with-lease`).
43    Lease(LeaseExpectation),
44}
45
46/// What a force-with-lease push compares the remote ref against.
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub enum LeaseExpectation {
49    /// Use the local remote-tracking ref mapped from the push destination.
50    Tracking,
51    /// Use an explicit object id (`--force-with-lease=<rev>`); only valid for a single ref.
52    Value(ObjectId),
53}
54
55/// What the caller wants to push (remote override, refspecs, tags, deletions).
56#[derive(Debug, Clone, Default, PartialEq, Eq)]
57pub struct PushRequest {
58    /// Explicit remote name from `--remote` or the first positional argument.
59    pub remote: Option<String>,
60    /// Positional refspec strings (`src`, `src:dst`, `:dst`, `+src:dst`, …).
61    pub refspecs: Vec<String>,
62    /// Push all local tags (`--tags`).
63    pub tags: bool,
64    /// Delete the remote refs named in [`Self::refspecs`] instead of pushing them (`--delete`).
65    ///
66    /// Every refspec must then be a plain ref name (no `:`); see
67    /// [`PushPlanError::DeleteNotPlainName`].
68    pub delete_refs: bool,
69    /// Additional remote refs to delete, planned together with [`Self::refspecs`] as when
70    /// [`Self::delete_refs`] is set.
71    pub delete: Vec<String>,
72    /// Force or force-with-lease mode from CLI flags.
73    pub force: ForceMode,
74    /// Push annotated tags reachable from the commits being pushed (`--follow-tags`).
75    pub follow_tags: bool,
76    /// After a successful branch push, write `branch.<name>.remote` / `.merge` (`-u`).
77    pub set_upstream: bool,
78    /// Push every local branch (`refs/heads/*:refs/heads/*`), including names the remote
79    /// does not advertise yet (unlike `push.default = matching` or a `:` refspec).
80    pub all: bool,
81    /// Mirror the repository: push all refs under `refs/*`, force updates, and delete remote
82    /// refs under `refs/` with no local counterpart (implies [`Self::prune`] and force).
83    pub mirror: bool,
84    /// Delete remote refs in the destination namespace of a wildcard or matching refspec when
85    /// there is no matching update in this push (for example `grit push --all --prune` or
86    /// `refs/heads/*:refs/heads/* --prune`). A single-branch push does not prune siblings.
87    pub prune: bool,
88}
89
90/// A fully resolved push target.
91#[derive(Debug, Clone)]
92pub struct ResolvedPush {
93    /// Remote name to push to.
94    pub remote: String,
95    /// Concrete ref updates to send.
96    pub specs: Vec<PushRefSpec>,
97    /// Short branch label when the push maps to one local branch (for display).
98    pub branch_label: Option<String>,
99    /// High-level kind for JSON (`branch`, `tags`, `delete`, `refspecs`).
100    pub kind: PushPlanKind,
101}
102
103/// JSON / CLI classification of what was pushed.
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub enum PushPlanKind {
106    /// Default push of the current branch (or a single mapped branch).
107    Branch,
108    /// Push all local tags (`--tags`).
109    Tags,
110    /// Delete one or more remote refs (`--delete`).
111    Delete,
112    /// Explicit refspecs from the command line or remote `push` config.
113    Refspecs,
114}
115
116/// Extra inputs needed to DWIM delete targets and short push destinations.
117#[derive(Debug, Clone, Default)]
118pub struct PushPlanContext {
119    /// Advertised ref names on the remote (for delete mapping and dst guessing).
120    pub remote_ref_names: HashSet<String>,
121    /// Tips of `refs/heads/*` on the remote (reserved for push planning; follow-tags
122    /// uses commit-graph ancestor queries instead of materializing reachable sets).
123    pub remote_branch_tips: HashSet<ObjectId>,
124    /// Tip of every advertised ref, or `None` when the advertisement was not read.
125    ///
126    /// Pass it on as [`PushOptions::remote_ref_tips`](crate::transfer::PushOptions) so a local
127    /// push does not scan the remote's refs a second time. Only pass it to a push to the same
128    /// remote: [`RepositoryRemotes::push_plan_context`] and [`RepositoryRemotes::resolve_push`]
129    /// select the same remote when given the same override.
130    pub remote_tips: Option<Vec<ObjectId>>,
131}
132
133/// Errors while planning a push (typed; no stringly matching in callers).
134#[derive(Debug, Error)]
135#[non_exhaustive]
136pub enum PushPlanError {
137    /// Detached `HEAD` with no refspec on the command line.
138    #[error("HEAD is detached; specify a refspec (for example HEAD:refs/heads/<name>)")]
139    DetachedHeadNoRefspec,
140    /// Current branch exists but has no commits.
141    #[error("no commits yet to push")]
142    NoCommits,
143    /// `--tags` was given but there are no local tags.
144    #[error("no tags to push")]
145    NoTags,
146    /// `push.default = nothing` blocks an empty refspec push.
147    #[error("push.default is nothing; no push destination")]
148    PushDefaultNothing,
149    /// No remote was named and none is configured: the branch has no push remote or remote,
150    /// `remote.pushDefault` is unset and there is no `origin` with a URL.
151    #[error("no remote to push to")]
152    NoRemote,
153    /// Named remote is missing from config.
154    #[error("unknown remote '{name}'")]
155    UnknownRemote {
156        /// The remote name or URL as given.
157        name: String,
158    },
159    /// Malformed refspec string.
160    #[error("invalid refspec '{spec}': {reason}")]
161    InvalidRefspec {
162        /// Original refspec text.
163        spec: String,
164        /// Parse or validation detail.
165        reason: String,
166    },
167    /// Source side did not match any local ref or object.
168    #[error("src refspec {spec} does not match any ref")]
169    SrcRefspecNoMatch {
170        /// Source pattern or name.
171        spec: String,
172    },
173    /// Source side matched more than one local ref.
174    #[error("src refspec {spec} matches more than one ref")]
175    SrcRefspecAmbiguous {
176        /// Source pattern or name.
177        spec: String,
178    },
179    /// Short destination matched multiple remote refs.
180    #[error("dst refspec {spec} matches more than one remote ref")]
181    DstRefspecAmbiguous {
182        /// Destination pattern or name.
183        spec: String,
184    },
185    /// Revision text could not be resolved to an object.
186    #[error("could not resolve revision '{spec}'")]
187    UnknownRevision {
188        /// Revision expression.
189        spec: String,
190    },
191    /// `--force-with-lease=<rev>` with more than one ref update.
192    #[error("--force-with-lease=<rev> requires pushing exactly one ref")]
193    LeaseValueRequiresSingleRef,
194    /// A delete push was given a refspec (`src:dst`) instead of a plain remote ref name.
195    #[error("cannot delete '{spec}': --delete takes ref names, not src:dst refspecs")]
196    DeleteNotPlainName {
197        /// The offending refspec.
198        spec: String,
199    },
200    /// A delete push named no ref to delete.
201    #[error("--delete needs at least one ref to delete")]
202    DeleteWithoutRefs,
203    /// `HEAD` could not be interpreted for push planning.
204    #[error("HEAD is in an unknown state")]
205    InvalidHead,
206    /// `push.default = upstream` but the branch has no `branch.<name>.merge`.
207    #[error("branch '{branch}' has no upstream for push.default upstream")]
208    NoUpstreamForPushDefault {
209        /// Local branch short name.
210        branch: String,
211    },
212}
213
214type PlanResult<T> = crate::error::Result<T>;
215
216/// Parse `--force` / `--force-with-lease[=<rev>]` into [`ForceMode`].
217pub(crate) fn parse_force_mode(
218    repo: &Repository,
219    force: bool,
220    force_with_lease: Option<Option<String>>,
221) -> PlanResult<ForceMode> {
222    if force {
223        return Ok(ForceMode::Force);
224    }
225    let Some(flag) = force_with_lease else {
226        return Ok(ForceMode::None);
227    };
228    match flag {
229        None => Ok(ForceMode::Lease(LeaseExpectation::Tracking)),
230        Some(rev) => {
231            let oid = crate::rev_parse::resolve_revision_for_verify(repo, &rev)
232                .map_err(|_| PushPlanError::UnknownRevision { spec: rev.clone() })?;
233            Ok(ForceMode::Lease(LeaseExpectation::Value(oid)))
234        }
235    }
236}
237
238/// Resolve `request` into a remote name and [`PushRefSpec`] list.
239///
240/// When `ctx.remote_ref_names` is empty, delete/ref DWIM still uses local refs
241/// and falls back to Git's default `refs/heads/<name>` for deletes.
242///
243/// A delete push ([`PushRequest::delete_refs`] or a non-empty [`PushRequest::delete`]) plans one
244/// deletion per name in `delete` and `refspecs`, and nothing else.
245///
246/// # Errors
247///
248/// Besides remote and refspec resolution failures: [`PushPlanError::DeleteNotPlainName`] when a
249/// delete push is given a `src:dst` refspec, and [`PushPlanError::DeleteWithoutRefs`] when it
250/// names no ref. Both are reported before the remote is contacted.
251pub(crate) fn resolve_push(
252    repo: &Repository,
253    request: &PushRequest,
254    ctx: &PushPlanContext,
255) -> PlanResult<ResolvedPush> {
256    let config = repo.config().snapshot()?;
257    if request.delete_refs || !request.delete.is_empty() {
258        return resolve_delete_push(repo, config.as_ref(), request, ctx);
259    }
260    if request.tags {
261        return resolve_tags_push(repo, config.as_ref(), request);
262    }
263
264    let remote = configured_remote_for_push(repo, config.as_ref(), request.remote.as_deref())?;
265    validate_remote(config.as_ref(), &remote)?;
266
267    let follow_tags = request.follow_tags || push_follow_tags_config(config.as_ref());
268
269    let force_mode = if request.mirror {
270        ForceMode::Force
271    } else {
272        request.force.clone()
273    };
274
275    let mut resolved = if request.mirror {
276        resolve_mirror_push(repo, &remote, ctx)?
277    } else if request.all && request.refspecs.is_empty() {
278        resolve_all_branches_push(repo, &remote, ctx)?
279    } else if request.refspecs.is_empty() {
280        resolve_default_push(repo, config.as_ref(), &remote, ctx)?
281    } else {
282        resolve_cli_refspecs_push(repo, config.as_ref(), &remote, &request.refspecs, ctx)?
283    };
284
285    if request.prune && !request.mirror {
286        let scopes = collect_prune_scopes(config.as_ref(), &remote, request);
287        let negatives = collect_prune_negative_refspecs(config.as_ref(), &remote, request);
288        apply_prune_scopes(&mut resolved.specs, ctx, &scopes, &negatives);
289    }
290
291    if follow_tags {
292        let extra = follow_tag_push_specs(repo, &resolved.specs, ctx)?;
293        if !extra.is_empty() {
294            resolved.specs.extend(extra);
295            resolved.kind = PushPlanKind::Refspecs;
296            resolved.branch_label = None;
297        }
298    }
299
300    apply_force_mode(repo, &resolved.remote, &mut resolved.specs, &force_mode)?;
301    Ok(resolved)
302}
303
304fn resolve_all_branches_push(
305    repo: &Repository,
306    remote: &str,
307    ctx: &PushPlanContext,
308) -> PlanResult<ResolvedPush> {
309    let local = LocalPushRefs::load(repo)?;
310    let item = parse_push_refspec("refs/heads/*:refs/heads/*").map_err(|e| {
311        PushPlanError::InvalidRefspec {
312            spec: "refs/heads/*:refs/heads/*".into(),
313            reason: e.to_string(),
314        }
315    })?;
316    let specs = expand_wildcard_push_item(repo, &item, ctx, &local)?;
317    if specs.is_empty() {
318        return Err(PushPlanError::SrcRefspecNoMatch {
319            spec: "refs/heads/*".into(),
320        }
321        .into());
322    }
323    let branch_label = branch_label_from_specs(repo, &specs);
324    let kind = if specs.len() == 1 {
325        PushPlanKind::Branch
326    } else {
327        PushPlanKind::Refspecs
328    };
329    Ok(ResolvedPush {
330        remote: remote.to_owned(),
331        specs,
332        branch_label,
333        kind,
334    })
335}
336
337fn resolve_mirror_push(
338    repo: &Repository,
339    remote: &str,
340    ctx: &PushPlanContext,
341) -> PlanResult<ResolvedPush> {
342    let local = LocalPushRefs::load(repo)?;
343    let item = parse_push_refspec("refs/*:refs/*").map_err(|e| PushPlanError::InvalidRefspec {
344        spec: "refs/*:refs/*".into(),
345        reason: e.to_string(),
346    })?;
347    let mut specs = expand_wildcard_push_item(repo, &item, ctx, &local)?;
348    if specs.is_empty() {
349        return Err(PushPlanError::SrcRefspecNoMatch {
350            spec: "refs/*".into(),
351        }
352        .into());
353    }
354    let local_dst: HashSet<String> = specs.iter().map(|s| s.dst.clone()).collect();
355    append_mirror_prune_deletes(&mut specs, ctx, &local_dst);
356    Ok(ResolvedPush {
357        remote: remote.to_owned(),
358        specs,
359        branch_label: None,
360        kind: PushPlanKind::Refspecs,
361    })
362}
363
364fn resolve_cli_refspecs_push(
365    repo: &Repository,
366    config: &ConfigSet,
367    remote: &str,
368    refspecs: &[String],
369    ctx: &PushPlanContext,
370) -> PlanResult<ResolvedPush> {
371    let local = LocalPushRefs::load(repo)?;
372    let mut positive = Vec::new();
373    let mut negative = Vec::new();
374    for spec in refspecs {
375        let item = parse_push_refspec(spec).map_err(|e| PushPlanError::InvalidRefspec {
376            spec: spec.clone(),
377            reason: e.to_string(),
378        })?;
379        if item.negative {
380            negative.push(item);
381        } else {
382            positive.push(spec.as_str());
383        }
384    }
385    let mut specs = Vec::new();
386    for spec in positive {
387        specs.extend(resolve_cli_refspec(
388            repo, config, remote, spec, ctx, &local,
389        )?);
390    }
391    for item in negative {
392        specs.retain(|s| !push_spec_excluded_by_negative(&item, s));
393    }
394    let branch_label = branch_label_from_specs(repo, &specs);
395    Ok(ResolvedPush {
396        remote: remote.to_owned(),
397        specs,
398        branch_label,
399        kind: PushPlanKind::Refspecs,
400    })
401}
402
403fn positive_prune_scopes_from_refspec_strings(specs: &[String]) -> Vec<RefspecItem> {
404    specs
405        .iter()
406        .filter_map(|spec| {
407            let item = parse_push_refspec(spec).ok()?;
408            if item.negative || (!item.pattern && !item.matching) {
409                return None;
410            }
411            Some(item)
412        })
413        .collect()
414}
415
416/// Wildcard or matching refspecs that define `--prune` destination namespaces.
417fn collect_prune_scopes(
418    config: &ConfigSet,
419    remote: &str,
420    request: &PushRequest,
421) -> Vec<RefspecItem> {
422    if request.all {
423        return parse_push_refspec("refs/heads/*:refs/heads/*")
424            .ok()
425            .into_iter()
426            .collect();
427    }
428    if !request.refspecs.is_empty() {
429        return positive_prune_scopes_from_refspec_strings(&request.refspecs);
430    }
431    let configured = remote_push_refspec_strings(config, remote);
432    let mut scopes = positive_prune_scopes_from_refspec_strings(&configured);
433    if scopes.is_empty() {
434        let push_default = config
435            .value("push.default")
436            .unwrap_or_else(|| "simple".to_owned());
437        if push_default == "matching" {
438            if let Ok(item) = parse_push_refspec(":") {
439                scopes.push(item);
440            }
441        }
442    }
443    scopes
444}
445
446fn negative_refspecs_from_strings(specs: &[String]) -> Vec<RefspecItem> {
447    specs
448        .iter()
449        .filter_map(|spec| {
450            let item = parse_push_refspec(spec).ok()?;
451            item.negative.then_some(item)
452        })
453        .collect()
454}
455
456fn collect_prune_negative_refspecs(
457    config: &ConfigSet,
458    remote: &str,
459    request: &PushRequest,
460) -> Vec<RefspecItem> {
461    if !request.refspecs.is_empty() {
462        return negative_refspecs_from_strings(&request.refspecs);
463    }
464    negative_refspecs_from_strings(&remote_push_refspec_strings(config, remote))
465}
466
467fn apply_prune_scopes(
468    specs: &mut Vec<PushRefSpec>,
469    ctx: &PushPlanContext,
470    scopes: &[RefspecItem],
471    negatives: &[RefspecItem],
472) {
473    for scope in scopes {
474        append_prune_deletes_for_scope(specs, ctx, scope, negatives);
475    }
476}
477
478fn prune_destination_patterns(scope: &RefspecItem) -> Vec<String> {
479    if scope.matching {
480        return vec!["refs/heads/*".to_owned()];
481    }
482    if scope.pattern {
483        if let Some(dst) = scope.dst.as_deref().filter(|d| d.contains('*')) {
484            return vec![dst.to_owned()];
485        }
486        if let Some(src) = scope.src.as_deref().filter(|s| s.contains('*')) {
487            return vec![src.to_owned()];
488        }
489    }
490    Vec::new()
491}
492
493fn remote_ref_in_prune_destination_namespace(remote_ref: &str, dst_pattern: &str) -> bool {
494    if !dst_pattern.contains('*') {
495        return remote_ref == dst_pattern;
496    }
497    match_refname_with_pattern(dst_pattern, remote_ref, dst_pattern).is_some()
498}
499
500fn prune_scope_local_ref_for_remote_dst(remote_ref: &str, scope: &RefspecItem) -> Option<String> {
501    if scope.matching {
502        return remote_ref
503            .starts_with("refs/heads/")
504            .then(|| remote_ref.to_owned());
505    }
506    if scope.pattern {
507        let src_pat = scope.src.as_deref()?;
508        let dst_pat = scope.dst.as_deref()?;
509        return match_refname_with_pattern(dst_pat, remote_ref, src_pat);
510    }
511    None
512}
513
514fn negative_excludes_local_ref(negative: &RefspecItem, local_ref: &str) -> bool {
515    let Some(pat) = negative.src.as_deref() else {
516        return false;
517    };
518    if negative.pattern {
519        return match_refname_with_pattern(pat, local_ref, pat).is_some();
520    }
521    pat == local_ref || refname_match_one(pat, local_ref)
522}
523
524fn prune_dst_excluded_by_negative(
525    negative: &RefspecItem,
526    remote_ref: &str,
527    scope: &RefspecItem,
528) -> bool {
529    let Some(local) = prune_scope_local_ref_for_remote_dst(remote_ref, scope) else {
530        return false;
531    };
532    negative_excludes_local_ref(negative, &local)
533}
534
535fn append_prune_deletes_for_scope(
536    specs: &mut Vec<PushRefSpec>,
537    ctx: &PushPlanContext,
538    scope: &RefspecItem,
539    negatives: &[RefspecItem],
540) {
541    let patterns = prune_destination_patterns(scope);
542    if patterns.is_empty() {
543        return;
544    }
545    let pushed_dst: HashSet<&str> = specs
546        .iter()
547        .filter(|s| !s.delete)
548        .map(|s| s.dst.as_str())
549        .collect();
550    let mut to_delete = Vec::new();
551    for remote_ref in &ctx.remote_ref_names {
552        if remote_ref == "HEAD" {
553            continue;
554        }
555        if !patterns
556            .iter()
557            .any(|pat| remote_ref_in_prune_destination_namespace(remote_ref, pat))
558        {
559            continue;
560        }
561        if pushed_dst.contains(remote_ref.as_str()) {
562            continue;
563        }
564        if specs.iter().any(|s| s.dst == *remote_ref) {
565            continue;
566        }
567        if negatives
568            .iter()
569            .any(|n| prune_dst_excluded_by_negative(n, remote_ref, scope))
570        {
571            continue;
572        }
573        to_delete.push(remote_ref.clone());
574    }
575    for remote_ref in to_delete {
576        specs.push(push_spec(None, None, remote_ref, false, true));
577    }
578}
579
580fn append_mirror_prune_deletes(
581    specs: &mut Vec<PushRefSpec>,
582    ctx: &PushPlanContext,
583    local_dst: &HashSet<String>,
584) {
585    let mut to_delete = Vec::new();
586    for remote_ref in &ctx.remote_ref_names {
587        if remote_ref == "HEAD" || !remote_ref.starts_with("refs/") {
588            continue;
589        }
590        if local_dst.contains(remote_ref) {
591            continue;
592        }
593        if specs.iter().any(|s| s.dst == *remote_ref) {
594            continue;
595        }
596        to_delete.push(remote_ref.clone());
597    }
598    for remote_ref in to_delete {
599        specs.push(push_spec(None, None, remote_ref, false, true));
600    }
601}
602
603/// Whether `push.followTags` is enabled in config (default false).
604#[must_use]
605pub fn push_follow_tags_config(config: &ConfigSet) -> bool {
606    config
607        .value("push.followTags")
608        .and_then(|v| parse_git_config_maybe_bool(&v))
609        .unwrap_or(false)
610}
611
612/// Append annotated tag refspecs reachable from the updates in `specs`.
613///
614/// Matches `git push --follow-tags`: lightweight tags are skipped, tags already on the remote
615/// are skipped, and reachability uses commit-graph ancestor checks from pushed tips (any ref
616/// namespace). Tag refspecs and specs whose source is a tag object do not seed the walk.
617pub(crate) fn follow_tag_push_specs(
618    repo: &Repository,
619    specs: &[PushRefSpec],
620    ctx: &PushPlanContext,
621) -> PlanResult<Vec<PushRefSpec>> {
622    let tips = push_follow_tip_commits(repo, specs)?;
623    if tips.is_empty() {
624        return Ok(Vec::new());
625    }
626
627    let existing: HashSet<&str> = specs.iter().map(|s| s.dst.as_str()).collect();
628    let odb = repo.odb();
629    let mut out = Vec::new();
630    for (tag_name, tag_oid) in list_local_refs(repo.git_dir(), "refs/tags/")? {
631        if ctx.remote_ref_names.contains(&tag_name) || existing.contains(tag_name.as_str()) {
632            continue;
633        }
634        let Ok(obj) = odb.read(&tag_oid) else {
635            continue;
636        };
637        if obj.kind != ObjectKind::Tag {
638            continue;
639        }
640        let Ok((peeled, _)) = odb.peel_tags(tag_oid) else {
641            continue;
642        };
643        if !tag_reachable_from_push_tips(repo, peeled, &tips)? {
644            continue;
645        }
646        out.push(push_spec(
647            Some(tag_oid),
648            Some(tag_name.clone()),
649            tag_name,
650            false,
651            false,
652        ));
653    }
654    Ok(out)
655}
656
657fn push_follow_tip_commits(repo: &Repository, specs: &[PushRefSpec]) -> PlanResult<Vec<ObjectId>> {
658    let mut tips = Vec::new();
659    for spec in specs {
660        if spec.delete || is_tag_push_spec(repo, spec) {
661            continue;
662        }
663        if let Some(commit) = peel_push_src_to_commit(repo, spec) {
664            tips.push(commit);
665        }
666    }
667    Ok(tips)
668}
669
670fn is_tag_push_spec(repo: &Repository, spec: &PushRefSpec) -> bool {
671    if spec.dst.starts_with("refs/tags/") {
672        return true;
673    }
674    let Some(src) = spec.src else {
675        return false;
676    };
677    let Ok(obj) = repo.odb().read(&src) else {
678        return false;
679    };
680    obj.kind == ObjectKind::Tag
681}
682
683fn peel_push_src_to_commit(repo: &Repository, spec: &PushRefSpec) -> Option<ObjectId> {
684    let src = spec.src?;
685    let odb = repo.odb();
686    let Ok(obj) = odb.read(&src) else {
687        return None;
688    };
689    match obj.kind {
690        ObjectKind::Commit => Some(src),
691        ObjectKind::Tag => odb.peel_tags(src).ok().map(|(commit, _)| commit),
692        _ => None,
693    }
694}
695
696fn tag_reachable_from_push_tips(
697    repo: &Repository,
698    peeled: ObjectId,
699    tips: &[ObjectId],
700) -> PlanResult<bool> {
701    for &tip in tips {
702        if peeled == tip {
703            return Ok(true);
704        }
705        if is_ancestor(repo, peeled, tip)? {
706            return Ok(true);
707        }
708    }
709    Ok(false)
710}
711
712fn resolve_delete_push(
713    repo: &Repository,
714    config: &ConfigSet,
715    request: &PushRequest,
716    ctx: &PushPlanContext,
717) -> PlanResult<ResolvedPush> {
718    let names: Vec<&String> = request.delete.iter().chain(&request.refspecs).collect();
719    if let Some(spec) = names.iter().find(|name| name.contains(':')) {
720        return Err(PushPlanError::DeleteNotPlainName {
721            spec: (*spec).clone(),
722        }
723        .into());
724    }
725    if names.is_empty() {
726        return Err(PushPlanError::DeleteWithoutRefs.into());
727    }
728    let remote = configured_remote_for_push(repo, config, request.remote.as_deref())?;
729    validate_remote(config, &remote)?;
730    let specs = names
731        .into_iter()
732        .map(|name| {
733            let dst = resolve_push_delete_ref(repo.git_dir(), &ctx.remote_ref_names, name);
734            push_spec(None, None, dst, false, true)
735        })
736        .collect::<Vec<_>>();
737    let branch_label = delete_branch_label(&specs);
738    let mut resolved = ResolvedPush {
739        remote,
740        specs,
741        branch_label,
742        kind: PushPlanKind::Delete,
743    };
744    apply_force_mode(repo, &resolved.remote, &mut resolved.specs, &request.force)?;
745    Ok(resolved)
746}
747
748fn resolve_tags_push(
749    repo: &Repository,
750    config: &ConfigSet,
751    request: &PushRequest,
752) -> PlanResult<ResolvedPush> {
753    let remote = configured_remote_for_push(repo, config, request.remote.as_deref())?;
754    validate_remote(config, &remote)?;
755    let entries = refs::list_refs(repo.git_dir(), "refs/tags/")?;
756    if entries.is_empty() {
757        return Err(PushPlanError::NoTags.into());
758    }
759    let specs = entries
760        .into_iter()
761        .map(|(refname, oid)| push_spec(Some(oid), Some(refname.clone()), refname, false, false))
762        .collect();
763    let mut resolved = ResolvedPush {
764        remote,
765        specs,
766        branch_label: None,
767        kind: PushPlanKind::Tags,
768    };
769    apply_force_mode(repo, &resolved.remote, &mut resolved.specs, &request.force)?;
770    Ok(resolved)
771}
772
773fn resolve_default_push(
774    repo: &Repository,
775    config: &ConfigSet,
776    remote: &str,
777    ctx: &PushPlanContext,
778) -> PlanResult<ResolvedPush> {
779    let push_specs = remote_push_refspec_strings(config, remote);
780    if !push_specs.is_empty() {
781        let mut positive_specs = Vec::new();
782        let mut negative_items = Vec::new();
783        for spec in push_specs {
784            let item = parse_push_refspec(&spec).map_err(|e| PushPlanError::InvalidRefspec {
785                spec: spec.clone(),
786                reason: e.to_string(),
787            })?;
788            if item.negative {
789                negative_items.push(item);
790            } else {
791                positive_specs.push(spec);
792            }
793        }
794        let local = LocalPushRefs::load(repo)?;
795        let mut specs = Vec::new();
796        for spec in positive_specs {
797            specs.extend(expand_configured_push_refspec(repo, spec, ctx, &local)?);
798        }
799        for item in negative_items {
800            specs.retain(|s| !push_spec_excluded_by_negative(&item, s));
801        }
802        let branch_label = branch_label_from_specs(repo, &specs);
803        let kind = if specs.len() == 1 {
804            PushPlanKind::Branch
805        } else {
806            PushPlanKind::Refspecs
807        };
808        return Ok(ResolvedPush {
809            remote: remote.to_owned(),
810            specs,
811            branch_label,
812            kind,
813        });
814    }
815
816    let push_default = config
817        .value("push.default")
818        .unwrap_or_else(|| "simple".to_owned());
819    if push_default == "matching" {
820        return resolve_matching_default_push(repo, remote, ctx);
821    }
822
823    let (short_name, oid) = current_branch_oid(repo)?;
824    let src_ref = format!("refs/heads/{short_name}");
825    let dst = default_push_destination(repo, config, remote, &short_name, &src_ref)?;
826    let spec = push_spec(Some(oid), Some(src_ref.clone()), dst, false, false);
827    Ok(ResolvedPush {
828        remote: remote.to_owned(),
829        specs: vec![spec],
830        branch_label: Some(short_name),
831        kind: PushPlanKind::Branch,
832    })
833}
834
835/// `push.default = matching`: push every local branch whose name exists on the remote.
836fn resolve_matching_default_push(
837    repo: &Repository,
838    remote: &str,
839    ctx: &PushPlanContext,
840) -> PlanResult<ResolvedPush> {
841    let heads = list_local_refs(repo.git_dir(), "refs/heads/")?;
842    let mut specs = Vec::new();
843    for (name, oid) in heads {
844        if ctx.remote_ref_names.contains(&name) {
845            specs.push(push_spec(
846                Some(oid),
847                Some(name.clone()),
848                name.clone(),
849                false,
850                false,
851            ));
852        }
853    }
854    let branch_label = branch_label_from_specs(repo, &specs);
855    let kind = if specs.len() == 1 {
856        PushPlanKind::Branch
857    } else {
858        PushPlanKind::Refspecs
859    };
860    Ok(ResolvedPush {
861        remote: remote.to_owned(),
862        specs,
863        branch_label,
864        kind,
865    })
866}
867
868fn current_branch_oid(repo: &Repository) -> PlanResult<(String, ObjectId)> {
869    match resolve_head(repo.git_dir())? {
870        HeadState::Branch {
871            short_name,
872            oid: Some(oid),
873            ..
874        } => Ok((short_name, oid)),
875        HeadState::Branch { .. } => Err(PushPlanError::NoCommits.into()),
876        HeadState::Detached { .. } => Err(PushPlanError::DetachedHeadNoRefspec.into()),
877        HeadState::Invalid => Err(PushPlanError::InvalidHead.into()),
878    }
879}
880
881/// Remote selection for push: explicit, `branch.*.pushRemote`, `remote.pushDefault`,
882/// `branch.*.remote`, then `origin`.
883///
884/// # Errors
885///
886/// [`PushPlanError::NoRemote`] when nothing selects a remote and no `remote.origin.*` section
887/// is configured.
888pub(crate) fn configured_remote_for_push(
889    repo: &Repository,
890    config: &ConfigSet,
891    remote_override: Option<&str>,
892) -> PlanResult<String> {
893    if let Some(remote) = remote_override.filter(|r| !r.trim().is_empty()) {
894        return Ok(remote.to_owned());
895    }
896    if let Ok(HeadState::Branch { short_name, .. }) = resolve_head(repo.git_dir()) {
897        if let Some(remote) = config
898            .value(&format!("branch.{short_name}.pushremote"))
899            .or_else(|| config.value(&format!("branch.{short_name}.pushRemote")))
900            .filter(|r| !r.trim().is_empty())
901        {
902            return Ok(remote);
903        }
904    }
905    if let Some(remote) = config
906        .value("remote.pushDefault")
907        .filter(|r| !r.trim().is_empty())
908    {
909        return Ok(remote);
910    }
911    if let Ok(HeadState::Branch { short_name, .. }) = resolve_head(repo.git_dir()) {
912        if let Some(remote) = config
913            .value(&format!("branch.{short_name}.remote"))
914            .filter(|r| !r.trim().is_empty() && r != ".")
915        {
916            return Ok(remote);
917        }
918    }
919    if !has_remote_section(config, DEFAULT_REMOTE) {
920        return Err(PushPlanError::NoRemote.into());
921    }
922    Ok(DEFAULT_REMOTE.to_owned())
923}
924
925/// Remote and refspec strings after classifying `grit push [<remote>] [<refspec>...]`.
926#[derive(Debug, Clone, Default, PartialEq, Eq)]
927pub struct PushInvocation {
928    /// Remote name, URL or path; `None` selects the remote with [`configured_remote_for_push`].
929    pub remote: Option<String>,
930    /// Refspec strings for [`PushRequest::refspecs`].
931    pub refspecs: Vec<String>,
932}
933
934/// Classify push positionals into a remote and refspecs.
935///
936/// With `remote_flag` set, every positional is a refspec. Otherwise the first positional is the
937/// remote when it has a configured `remote.<name>.url` or looks like a literal URL or path
938/// (`scheme://`, `*.git`, `/abs/path`, `.` / `..`, `./…` / `../…`, or an existing relative git
939/// directory). A single other positional is a refspec pushed to the default remote; with more
940/// positionals the first one must name a remote.
941///
942/// # Errors
943///
944/// [`PushPlanError::UnknownRemote`] when several positionals are given and the first is neither a
945/// configured remote nor a literal URL or path.
946pub fn resolve_push_invocation(
947    config: &ConfigSet,
948    remote_flag: Option<&str>,
949    positionals: &[String],
950) -> PlanResult<PushInvocation> {
951    if let Some(remote) = remote_flag {
952        return Ok(PushInvocation {
953            remote: Some(remote.to_owned()),
954            refspecs: positionals.to_vec(),
955        });
956    }
957    let Some((first, rest)) = positionals.split_first() else {
958        return Ok(PushInvocation::default());
959    };
960    if has_remote_url(config, first) || looks_like_literal_remote(first) {
961        return Ok(PushInvocation {
962            remote: Some(first.clone()),
963            refspecs: rest.to_vec(),
964        });
965    }
966    if !rest.is_empty() {
967        return Err(PushPlanError::UnknownRemote {
968            name: first.clone(),
969        }
970        .into());
971    }
972    Ok(PushInvocation {
973        remote: None,
974        refspecs: positionals.to_vec(),
975    })
976}
977
978/// The URL `<host>/<owner>/<project>.git` when `grit push <owner>/<project> <refspec>...` names
979/// a repository on a grit host rather than a remote.
980///
981/// Only a first positional followed by refspecs is a remote, so a lone `topic/x` stays a
982/// refspec (`None`). A configured remote of the same name wins, and literal URLs and paths
983/// (`a/b/c`, `./a/b`, `x/y.git`) are left alone. Owner and project are letters, digits, `-`,
984/// `_` and `.`, not starting with `.`.
985#[must_use]
986pub fn expand_repository_shorthand(
987    config: &ConfigSet,
988    positionals: &[String],
989    host: &str,
990) -> Option<String> {
991    let [first, _, ..] = positionals else {
992        return None;
993    };
994    if has_remote_url(config, first) || looks_like_literal_remote(first) {
995        return None;
996    }
997    let is_segment = |s: &str| {
998        !s.is_empty()
999            && !s.starts_with('.')
1000            && s.chars()
1001                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
1002    };
1003    let (owner, project) = first.split_once('/')?;
1004    (is_segment(owner) && is_segment(project))
1005        .then(|| format!("{}/{owner}/{project}.git", host.trim_end_matches('/')))
1006}
1007
1008/// Open the [`Remote`] a resolved push sends to ([`ResolvedPush::remote`]).
1009///
1010/// Literal URLs and paths (see [`resolve_push_invocation`]) become anonymous remotes; any other
1011/// name is read from `remote.<name>.*` config.
1012///
1013/// # Errors
1014///
1015/// [`RemoteError::NoUrl`](crate::remote::RemoteError::NoUrl) when `name` has no configured URL, or a URL parse error.
1016pub fn open_push_destination(config: &ConfigSet, name: &str) -> crate::error::Result<Remote> {
1017    if looks_like_literal_remote(name) {
1018        Remote::from_url(name)
1019    } else {
1020        Remote::from_config(config, name)
1021    }
1022}
1023
1024impl PushPlanContext {
1025    /// Build a context from a remote's ref advertisement (peeled `^{}` entries are skipped).
1026    #[must_use]
1027    pub fn from_advertised_refs(refs: impl IntoIterator<Item = RemoteRef>) -> Self {
1028        let mut ctx = Self::default();
1029        let mut tips = Vec::new();
1030        for remote_ref in refs {
1031            if remote_ref.peeled_tag().is_some() {
1032                continue;
1033            }
1034            if remote_ref.name.starts_with("refs/heads/") {
1035                ctx.remote_branch_tips.insert(remote_ref.oid);
1036            }
1037            tips.push(remote_ref.oid);
1038            ctx.remote_ref_names.insert(remote_ref.name);
1039        }
1040        ctx.remote_tips = Some(tips);
1041        ctx
1042    }
1043}
1044
1045/// Load the [`PushPlanContext`] for the remote a push would select.
1046///
1047/// The remote is chosen with [`configured_remote_for_push`], opened with
1048/// [`open_push_destination`] (so literal URLs and paths are listed like configured remotes) and
1049/// listed with [`Remote::list_push_refs`]. The context is best-effort: a remote without a URL, or one whose refs cannot be listed,
1050/// yields an empty context, and the push itself reports any connection failure.
1051///
1052/// The listing uses a [preflight client](HttpClientFactory::create_for_preflight), so credentials the
1053/// server refuses stay stored and the push reports them as rejected
1054/// ([`AuthFailure::Rejected`](crate::error::AuthFailure::Rejected)).
1055///
1056/// # Errors
1057///
1058/// Only errors from [`configured_remote_for_push`].
1059pub(crate) fn load_push_plan_context(
1060    repo: &Repository,
1061    remote_override: Option<&str>,
1062    http_factory: Option<&dyn HttpClientFactory>,
1063) -> PlanResult<PushPlanContext> {
1064    let config = repo.config().snapshot()?;
1065    let remote = configured_remote_for_push(repo, config.as_ref(), remote_override)?;
1066    let Ok(handle) = open_push_destination(config.as_ref(), &remote) else {
1067        return Ok(PushPlanContext::default());
1068    };
1069    let probe = PreflightHttpClientFactory::new(http_factory, repo);
1070    let Ok(advertised) = handle.list_push_refs(repo, Some(&probe)) else {
1071        return Ok(PushPlanContext::default());
1072    };
1073    Ok(PushPlanContext::from_advertised_refs(advertised))
1074}
1075
1076fn looks_like_literal_remote(name: &str) -> bool {
1077    if name.contains("://") || name.ends_with(".git") || name.starts_with('/') {
1078        return true;
1079    }
1080    if name == "." || name == ".." || name.starts_with("./") || name.starts_with("../") {
1081        return true;
1082    }
1083    is_git_directory(Path::new(name))
1084}
1085
1086fn has_remote_url(config: &ConfigSet, name: &str) -> bool {
1087    config
1088        .value(&format!("remote.{name}.url"))
1089        .is_some_and(|u| !u.trim().is_empty())
1090}
1091
1092fn validate_remote(config: &ConfigSet, name: &str) -> PlanResult<()> {
1093    if has_remote_url(config, name) {
1094        Ok(())
1095    } else if name == DEFAULT_REMOTE || looks_like_literal_remote(name) {
1096        // Literal URL / path remotes are resolved by the transport layer.
1097        Ok(())
1098    } else {
1099        Err(PushPlanError::UnknownRemote {
1100            name: name.to_owned(),
1101        }
1102        .into())
1103    }
1104}
1105
1106fn remote_push_refspec_strings(config: &ConfigSet, remote: &str) -> Vec<String> {
1107    config
1108        .values_all(&format!("remote.{remote}.push"))
1109        .into_iter()
1110        .filter(|s| !s.trim().is_empty())
1111        .collect()
1112}
1113
1114fn default_push_destination(
1115    repo: &Repository,
1116    config: &ConfigSet,
1117    remote: &str,
1118    branch_short: &str,
1119    _src_ref: &str,
1120) -> PlanResult<String> {
1121    let push_default = config
1122        .value("push.default")
1123        .unwrap_or_else(|| "simple".to_owned());
1124
1125    if push_default == "nothing" {
1126        return Err(PushPlanError::PushDefaultNothing.into());
1127    }
1128
1129    if push_default.as_str() == "upstream" {
1130        let merge = config
1131            .value(&format!("branch.{branch_short}.merge"))
1132            .filter(|m| m.starts_with("refs/"));
1133        return merge.ok_or(crate::error::Error::from(
1134            PushPlanError::NoUpstreamForPushDefault {
1135                branch: branch_short.to_owned(),
1136            },
1137        ));
1138    }
1139
1140    // `simple`, `current`, and unspecified: grit keeps the historical default of
1141    // `branch.<name>.merge` when set, else same branch name on the remote.
1142    if push_default.as_str() == "simple" {
1143        let branch_remote = config.value(&format!("branch.{branch_short}.remote"));
1144        if branch_remote.as_deref() == Some(remote) {
1145            if let Some(merge) = config
1146                .value(&format!("branch.{branch_short}.merge"))
1147                .filter(|m| m.starts_with("refs/"))
1148            {
1149                let _merge_branch = merge.strip_prefix("refs/heads/").unwrap_or(merge.as_str());
1150                let same_name_dst = format!("refs/heads/{branch_short}");
1151                if merge != same_name_dst {
1152                    // Git `simple` dies when upstream name differs; grit uses merge ref when same remote.
1153                    return Ok(merge);
1154                }
1155                return Ok(same_name_dst);
1156            }
1157        }
1158    }
1159
1160    let _ = resolve_push_full_ref_for_branch(repo, branch_short);
1161    Ok(format!("refs/heads/{branch_short}"))
1162}
1163
1164fn resolve_cli_refspec(
1165    repo: &Repository,
1166    config: &ConfigSet,
1167    remote: &str,
1168    spec: &str,
1169    ctx: &PushPlanContext,
1170    local: &LocalPushRefs,
1171) -> PlanResult<Vec<PushRefSpec>> {
1172    if !spec.contains(':') {
1173        return resolve_shorthand_refspec(repo, config, remote, spec, ctx, local);
1174    }
1175    let item = parse_push_refspec(spec).map_err(|e| PushPlanError::InvalidRefspec {
1176        spec: spec.to_owned(),
1177        reason: e.to_string(),
1178    })?;
1179    resolve_parsed_refspec(repo, &item, ctx, local)
1180}
1181
1182fn resolve_shorthand_refspec(
1183    repo: &Repository,
1184    config: &ConfigSet,
1185    remote: &str,
1186    spec: &str,
1187    ctx: &PushPlanContext,
1188    local: &LocalPushRefs,
1189) -> PlanResult<Vec<PushRefSpec>> {
1190    let count = local.count_refname_match(spec);
1191    if count == 1 {
1192        let Some(matched) = local.refname_match(spec) else {
1193            return Err(PushPlanError::SrcRefspecNoMatch {
1194                spec: spec.to_owned(),
1195            }
1196            .into());
1197        };
1198        if let Some(mapped) = map_through_remote_push_refspec(config, remote, &matched.0) {
1199            let item = parse_push_refspec(&mapped).map_err(|e| PushPlanError::InvalidRefspec {
1200                spec: mapped.clone(),
1201                reason: e.to_string(),
1202            })?;
1203            return resolve_parsed_refspec(repo, &item, ctx, local);
1204        }
1205        let item = RefspecItem {
1206            force: false,
1207            src: Some(matched.0.clone()),
1208            dst: Some(matched.0.clone()),
1209            ..Default::default()
1210        };
1211        return push_spec_from_parsed_item(repo, &item, ctx, matched);
1212    }
1213    if count == 0 {
1214        // Treat as explicit refspec string (Git refspec_append).
1215        let item = parse_push_refspec(spec).map_err(|e| PushPlanError::InvalidRefspec {
1216            spec: spec.to_owned(),
1217            reason: e.to_string(),
1218        })?;
1219        return resolve_parsed_refspec(repo, &item, ctx, local);
1220    }
1221    Err(PushPlanError::SrcRefspecAmbiguous {
1222        spec: spec.to_owned(),
1223    }
1224    .into())
1225}
1226
1227fn map_through_remote_push_refspec(
1228    config: &ConfigSet,
1229    remote: &str,
1230    local_full_ref: &str,
1231) -> Option<String> {
1232    for spec in remote_push_refspec_strings(config, remote) {
1233        let Ok(item) = parse_push_refspec(&spec) else {
1234            continue;
1235        };
1236        if item.negative || item.matching {
1237            continue;
1238        }
1239        if let Some(dst) = refspec_map_src(&item, local_full_ref) {
1240            let force = if item.force { "+" } else { "" };
1241            return Some(format!("{force}{local_full_ref}:{dst}"));
1242        }
1243    }
1244    None
1245}
1246
1247fn expand_configured_push_refspec(
1248    repo: &Repository,
1249    spec: String,
1250    ctx: &PushPlanContext,
1251    local: &LocalPushRefs,
1252) -> PlanResult<Vec<PushRefSpec>> {
1253    let item = parse_push_refspec(&spec).map_err(|e| PushPlanError::InvalidRefspec {
1254        spec: spec.clone(),
1255        reason: e.to_string(),
1256    })?;
1257    if item.matching {
1258        let mut out = Vec::new();
1259        for (name, oid) in local.heads() {
1260            if !ctx.remote_ref_names.contains(name) {
1261                continue;
1262            }
1263            out.push(push_spec(
1264                Some(*oid),
1265                Some(name.clone()),
1266                name.clone(),
1267                item.force,
1268                false,
1269            ));
1270        }
1271        return Ok(out);
1272    }
1273    if item.pattern {
1274        return expand_wildcard_push_item(repo, &item, ctx, local);
1275    }
1276    resolve_parsed_refspec(repo, &item, ctx, local)
1277}
1278
1279fn expand_wildcard_push_item(
1280    repo: &Repository,
1281    item: &RefspecItem,
1282    _ctx: &PushPlanContext,
1283    local: &LocalPushRefs,
1284) -> PlanResult<Vec<PushRefSpec>> {
1285    let refs = pattern_source_refs(repo, local, item.src.as_deref().unwrap_or(""))?;
1286    let mut out = Vec::new();
1287    for (name, oid) in refs {
1288        if let Some(dst) = refspec_map_src(item, &name) {
1289            out.push(push_spec(
1290                Some(oid),
1291                Some(name.clone()),
1292                dst,
1293                item.force,
1294                false,
1295            ));
1296        }
1297    }
1298    Ok(out)
1299}
1300
1301fn pattern_source_refs(
1302    repo: &Repository,
1303    local: &LocalPushRefs,
1304    prefix: &str,
1305) -> PlanResult<Vec<(String, ObjectId)>> {
1306    Ok(if prefix.starts_with("refs/tags/") {
1307        local.tags().to_vec()
1308    } else if prefix.starts_with("refs/heads/") {
1309        local.heads().to_vec()
1310    } else {
1311        list_local_refs(repo.git_dir(), "refs/")?
1312            .into_iter()
1313            .filter(|(name, _)| name != "HEAD")
1314            .collect()
1315    })
1316}
1317
1318fn resolve_parsed_refspec(
1319    repo: &Repository,
1320    item: &RefspecItem,
1321    ctx: &PushPlanContext,
1322    local: &LocalPushRefs,
1323) -> PlanResult<Vec<PushRefSpec>> {
1324    if item.negative {
1325        return Ok(Vec::new());
1326    }
1327    if item.pattern {
1328        let specs = expand_wildcard_push_item(repo, item, ctx, local)?;
1329        if specs.is_empty() {
1330            return Err(PushPlanError::SrcRefspecNoMatch {
1331                spec: item.src.clone().unwrap_or_default(),
1332            }
1333            .into());
1334        }
1335        return Ok(specs);
1336    }
1337    if item.matching {
1338        return expand_configured_push_refspec(
1339            repo,
1340            if item.force {
1341                "+:".to_owned()
1342            } else {
1343                ":".to_owned()
1344            },
1345            ctx,
1346            local,
1347        );
1348    }
1349
1350    let src_empty = item.src.as_deref().is_some_and(|s| s.is_empty());
1351    let src_name = item.src.as_deref().unwrap_or("");
1352
1353    if src_empty || (src_name.is_empty() && item.dst.is_some()) {
1354        let dst = item
1355            .dst
1356            .as_ref()
1357            .ok_or_else(|| PushPlanError::InvalidRefspec {
1358                spec: String::new(),
1359                reason: "delete refspec missing destination".into(),
1360            })?;
1361        let resolved_dst = resolve_dst_name(repo, dst, None, ctx)?;
1362        return Ok(vec![push_spec(None, None, resolved_dst, item.force, true)]);
1363    }
1364
1365    let src_oid = if item.exact_sha1 {
1366        ObjectId::from_hex(src_name).map_err(|_| PushPlanError::UnknownRevision {
1367            spec: src_name.to_owned(),
1368        })?
1369    } else if src_name.is_empty() {
1370        resolve_src_ref(repo, "HEAD")?
1371    } else {
1372        match resolve_src_ref(repo, src_name) {
1373            Ok(oid) => oid,
1374            Err(_) => match local.count_refname_match(src_name) {
1375                0 => {
1376                    return Err(PushPlanError::SrcRefspecNoMatch {
1377                        spec: src_name.to_owned(),
1378                    }
1379                    .into());
1380                }
1381                1 => {
1382                    let Some((name, oid)) = local.refname_match(src_name) else {
1383                        return Err(PushPlanError::SrcRefspecNoMatch {
1384                            spec: src_name.to_owned(),
1385                        }
1386                        .into());
1387                    };
1388                    let dst = resolve_dst_for_src(repo, item, &name, ctx)?;
1389                    return Ok(vec![push_spec(
1390                        Some(oid),
1391                        Some(name.clone()),
1392                        dst,
1393                        item.force,
1394                        false,
1395                    )]);
1396                }
1397                _ => {
1398                    return Err(PushPlanError::SrcRefspecAmbiguous {
1399                        spec: src_name.to_owned(),
1400                    }
1401                    .into());
1402                }
1403            },
1404        }
1405    };
1406
1407    let known_src = if item.exact_sha1
1408        || src_name.is_empty()
1409        || src_name.eq_ignore_ascii_case("HEAD")
1410        || src_name == "@"
1411    {
1412        None
1413    } else {
1414        local.refname_match(src_name)
1415    };
1416    let src_full = if item.exact_sha1 {
1417        None
1418    } else if let Some((name, _)) = &known_src {
1419        Some(name.clone())
1420    } else {
1421        Some(full_src_ref_name(repo, src_name, local)?)
1422    };
1423    let src_label = src_full.clone();
1424    let dst = resolve_dst_for_src(repo, item, src_label.as_deref().unwrap_or(src_name), ctx)?;
1425    let mut spec = push_spec(Some(src_oid), src_label, dst, item.force, false);
1426    if matches!(src_name, "HEAD" | "@") {
1427        spec.hook_src_ref = Some("HEAD".to_owned());
1428    }
1429    Ok(vec![spec])
1430}
1431
1432fn push_spec_from_parsed_item(
1433    repo: &Repository,
1434    item: &RefspecItem,
1435    ctx: &PushPlanContext,
1436    known_src: (String, ObjectId),
1437) -> PlanResult<Vec<PushRefSpec>> {
1438    let src_name = item.src.as_deref().unwrap_or("");
1439    let src_oid = known_src.1;
1440
1441    let src_full = if item.exact_sha1 {
1442        None
1443    } else {
1444        Some(known_src.0.clone())
1445    };
1446    let src_label = src_full.clone();
1447    let dst = resolve_dst_for_src(repo, item, src_label.as_deref().unwrap_or(src_name), ctx)?;
1448    let mut spec = push_spec(Some(src_oid), src_label, dst, item.force, false);
1449    if matches!(src_name, "HEAD" | "@") {
1450        spec.hook_src_ref = Some("HEAD".to_owned());
1451    }
1452    Ok(vec![spec])
1453}
1454
1455fn resolve_dst_for_src(
1456    repo: &Repository,
1457    item: &RefspecItem,
1458    src_full: &str,
1459    ctx: &PushPlanContext,
1460) -> PlanResult<String> {
1461    if let Some(dst) = &item.dst {
1462        if dst.is_empty() {
1463            return Err(PushPlanError::InvalidRefspec {
1464                spec: String::new(),
1465                reason: "empty destination".into(),
1466            }
1467            .into());
1468        }
1469        return resolve_dst_name(repo, dst, Some(src_full), ctx);
1470    }
1471    // Missing dst: use same ref name on remote (symref target for branches).
1472    if src_full.starts_with("refs/heads/") {
1473        return Ok(src_full.to_owned());
1474    }
1475    if src_full.starts_with("refs/tags/") {
1476        return Ok(src_full.to_owned());
1477    }
1478    Ok(src_full.to_owned())
1479}
1480
1481fn resolve_dst_name(
1482    _repo: &Repository,
1483    dst: &str,
1484    src_full: Option<&str>,
1485    ctx: &PushPlanContext,
1486) -> PlanResult<String> {
1487    if dst.starts_with("refs/") {
1488        return Ok(dst.to_owned());
1489    }
1490    let remote_list = remote_ref_list(ctx);
1491    match count_refname_match(dst, &remote_list) {
1492        0 => {}
1493        1 => {
1494            let Some((name, _)) = refname_match(dst, &remote_list) else {
1495                return Err(PushPlanError::InvalidRefspec {
1496                    spec: dst.to_owned(),
1497                    reason: "remote ref match failed".into(),
1498                }
1499                .into());
1500            };
1501            return Ok(name);
1502        }
1503        _ => {
1504            return Err(PushPlanError::DstRefspecAmbiguous {
1505                spec: dst.to_owned(),
1506            }
1507            .into());
1508        }
1509    }
1510    if let Some(src) = src_full {
1511        if let Some(guessed) = guess_qualified_dst(src, dst) {
1512            return Ok(guessed);
1513        }
1514    }
1515    Ok(format!("refs/heads/{dst}"))
1516}
1517
1518fn remote_ref_list(ctx: &PushPlanContext) -> Vec<(String, ObjectId)> {
1519    ctx.remote_ref_names
1520        .iter()
1521        .filter_map(|n| {
1522            // oid unused for matching; use zero placeholder.
1523            ObjectId::from_hex("0".repeat(40).as_str())
1524                .ok()
1525                .map(|z| (n.clone(), z))
1526        })
1527        .collect()
1528}
1529
1530fn guess_qualified_dst(src_full: &str, short_dst: &str) -> Option<String> {
1531    if src_full.starts_with("refs/heads/") {
1532        Some(format!("refs/heads/{short_dst}"))
1533    } else if src_full.starts_with("refs/tags/") {
1534        Some(format!("refs/tags/{short_dst}"))
1535    } else {
1536        None
1537    }
1538}
1539
1540/// Fill `force`, `expected_old`, and `expect_absent` on planned specs from [`ForceMode`].
1541fn apply_force_mode(
1542    repo: &Repository,
1543    remote: &str,
1544    specs: &mut [PushRefSpec],
1545    mode: &ForceMode,
1546) -> PlanResult<()> {
1547    match mode {
1548        ForceMode::None => {}
1549        ForceMode::Force => {
1550            for spec in specs.iter_mut() {
1551                spec.force = true;
1552                spec.expected_old = None;
1553                spec.expect_absent = false;
1554            }
1555        }
1556        ForceMode::Lease(LeaseExpectation::Tracking) => {
1557            for spec in specs.iter_mut() {
1558                apply_tracking_lease(repo, remote, spec);
1559            }
1560        }
1561        ForceMode::Lease(LeaseExpectation::Value(expected)) => {
1562            if specs.len() != 1 {
1563                return Err(PushPlanError::LeaseValueRequiresSingleRef.into());
1564            }
1565            for spec in specs.iter_mut() {
1566                spec.force = true;
1567                spec.expected_old = Some(*expected);
1568                spec.expect_absent = false;
1569            }
1570        }
1571    }
1572    Ok(())
1573}
1574
1575/// Let `spec` replace the remote ref when it still holds what this clone's
1576/// remote-tracking ref for it says (`--force-with-lease` for one ref), or
1577/// is absent when there is none.
1578pub(crate) fn apply_tracking_lease(repo: &Repository, remote: &str, spec: &mut PushRefSpec) {
1579    spec.force = true;
1580    spec.expected_old = None;
1581    spec.expect_absent = false;
1582    let Ok(config) = repo.config().snapshot() else {
1583        return;
1584    };
1585    if let Some(tracking) = remote_tracking_ref_for_remote_ref(config.as_ref(), remote, &spec.dst) {
1586        match refs::resolve_ref(repo.git_dir(), &tracking) {
1587            Ok(oid) => spec.expected_old = Some(oid),
1588            Err(_) => spec.expect_absent = true,
1589        }
1590    } else {
1591        spec.expect_absent = true;
1592    }
1593}
1594
1595fn push_spec(
1596    src: Option<ObjectId>,
1597    src_ref: Option<String>,
1598    dst: String,
1599    force: bool,
1600    delete: bool,
1601) -> PushRefSpec {
1602    PushRefSpec {
1603        src,
1604        src_ref,
1605        dst,
1606        force,
1607        delete,
1608        ..Default::default()
1609    }
1610}
1611
1612fn resolve_src_ref(repo: &Repository, spec: &str) -> PlanResult<ObjectId> {
1613    Ok(
1614        resolve_revision_for_verify(repo, spec).map_err(|_| PushPlanError::UnknownRevision {
1615            spec: spec.to_owned(),
1616        })?,
1617    )
1618}
1619
1620fn full_src_ref_name(repo: &Repository, spec: &str, local: &LocalPushRefs) -> PlanResult<String> {
1621    if spec.eq_ignore_ascii_case("HEAD") {
1622        if let Ok(HeadState::Branch { short_name, .. }) = resolve_head(repo.git_dir()) {
1623            return Ok(format!("refs/heads/{short_name}"));
1624        }
1625    }
1626    if spec.starts_with("refs/") {
1627        return Ok(spec.to_owned());
1628    }
1629    if let Some((name, _)) = local.refname_match(spec) {
1630        return Ok(name);
1631    }
1632    Ok(spec.to_owned())
1633}
1634
1635/// Local heads and tags loaded once for refspec planning.
1636struct LocalPushRefs {
1637    all: Vec<(String, ObjectId)>,
1638    by_full: HashMap<String, ObjectId>,
1639    by_short: HashMap<String, Vec<(String, ObjectId)>>,
1640    heads: Vec<(String, ObjectId)>,
1641    tags: Vec<(String, ObjectId)>,
1642}
1643
1644impl LocalPushRefs {
1645    fn load(repo: &Repository) -> PlanResult<Self> {
1646        let heads = list_local_refs(repo.git_dir(), "refs/heads/")?;
1647        let tags = list_local_refs(repo.git_dir(), "refs/tags/")?;
1648        let mut all = Vec::with_capacity(heads.len() + tags.len());
1649        let mut by_full = HashMap::with_capacity(heads.len() + tags.len());
1650        let mut by_short: HashMap<String, Vec<(String, ObjectId)>> = HashMap::new();
1651        for entry in heads.iter().chain(tags.iter()) {
1652            all.push(entry.clone());
1653            by_full.insert(entry.0.clone(), entry.1);
1654            if let Some(short) = entry
1655                .0
1656                .strip_prefix("refs/heads/")
1657                .or_else(|| entry.0.strip_prefix("refs/tags/"))
1658            {
1659                by_short
1660                    .entry(short.to_owned())
1661                    .or_default()
1662                    .push(entry.clone());
1663            }
1664        }
1665        Ok(Self {
1666            all,
1667            by_full,
1668            by_short,
1669            heads,
1670            tags,
1671        })
1672    }
1673
1674    fn heads(&self) -> &[(String, ObjectId)] {
1675        &self.heads
1676    }
1677
1678    fn tags(&self) -> &[(String, ObjectId)] {
1679        &self.tags
1680    }
1681
1682    fn count_refname_match(&self, pattern: &str) -> usize {
1683        if (pattern.starts_with("refs/heads/") || pattern.starts_with("refs/tags/"))
1684            && self.by_full.contains_key(pattern)
1685        {
1686            return 1;
1687        }
1688        if let Some(entries) = self.by_short.get(pattern) {
1689            return count_refname_match(pattern, entries);
1690        }
1691        count_refname_match(pattern, &self.all)
1692    }
1693
1694    fn refname_match(&self, pattern: &str) -> Option<(String, ObjectId)> {
1695        if pattern.starts_with("refs/heads/") || pattern.starts_with("refs/tags/") {
1696            if let Some(oid) = self.by_full.get(pattern) {
1697                return Some((pattern.to_owned(), *oid));
1698            }
1699        }
1700        if let Some(entries) = self.by_short.get(pattern) {
1701            return refname_match(pattern, entries);
1702        }
1703        refname_match(pattern, &self.all)
1704    }
1705}
1706
1707fn list_local_refs(git_dir: &Path, prefix: &str) -> PlanResult<Vec<(String, ObjectId)>> {
1708    refs::list_refs(git_dir, prefix)
1709}
1710
1711/// Port of Git `count_refspec_match` / `refname_match` for local refs.
1712fn count_refname_match(pattern: &str, refs: &[(String, ObjectId)]) -> usize {
1713    let mut strong = 0usize;
1714    let mut weak = 0usize;
1715    let patlen = pattern.len();
1716    for (name, _) in refs {
1717        if !refname_match_one(pattern, name) {
1718            continue;
1719        }
1720        let namelen = name.len();
1721        if namelen != patlen
1722            && patlen != namelen.saturating_sub(5)
1723            && !name.starts_with("refs/heads/")
1724            && !name.starts_with("refs/tags/")
1725        {
1726            weak += 1;
1727        } else {
1728            strong += 1;
1729        }
1730    }
1731    if strong == 0 {
1732        weak
1733    } else {
1734        strong
1735    }
1736}
1737
1738fn refname_match(pattern: &str, refs: &[(String, ObjectId)]) -> Option<(String, ObjectId)> {
1739    let mut strong: Option<(String, ObjectId)> = None;
1740    let mut weak: Option<(String, ObjectId)> = None;
1741    let patlen = pattern.len();
1742    for (name, oid) in refs {
1743        if !refname_match_one(pattern, name) {
1744            continue;
1745        }
1746        let namelen = name.len();
1747        if namelen != patlen
1748            && patlen != namelen.saturating_sub(5)
1749            && !name.starts_with("refs/heads/")
1750            && !name.starts_with("refs/tags/")
1751        {
1752            weak = Some((name.clone(), *oid));
1753        } else {
1754            strong = Some((name.clone(), *oid));
1755        }
1756    }
1757    strong.or(weak)
1758}
1759
1760fn refname_match_one(pattern: &str, refname: &str) -> bool {
1761    if pattern == refname {
1762        return true;
1763    }
1764    if refname.ends_with(pattern) {
1765        // `main` matches `refs/heads/main`
1766        if refname == format!("refs/heads/{pattern}") || refname == format!("refs/tags/{pattern}") {
1767            return true;
1768        }
1769        if pattern.len() + 5 == refname.len() && refname.starts_with("refs/heads/") {
1770            return refname.strip_prefix("refs/heads/") == Some(pattern);
1771        }
1772        if pattern.len() + 5 == refname.len() && refname.starts_with("refs/tags/") {
1773            return refname.strip_prefix("refs/tags/") == Some(pattern);
1774        }
1775    }
1776    false
1777}
1778
1779fn refspec_map_src(item: &RefspecItem, src_ref: &str) -> Option<String> {
1780    let src_pat = item.src.as_deref()?;
1781    let dst_pat = item.dst.as_deref()?;
1782    match_refname_with_pattern(src_pat, src_ref, dst_pat)
1783}
1784
1785/// Whether a planned push ref should be dropped by a configured `^` refspec.
1786fn push_spec_excluded_by_negative(item: &RefspecItem, spec: &PushRefSpec) -> bool {
1787    if !item.negative {
1788        return false;
1789    }
1790    let local = spec.src_ref.as_deref().or_else(|| {
1791        spec.dst
1792            .starts_with("refs/heads/")
1793            .then_some(spec.dst.as_str())
1794    });
1795    let Some(local) = local else {
1796        return false;
1797    };
1798    negative_excludes_local_ref(item, local)
1799}
1800
1801fn match_refname_with_pattern(pattern: &str, refname: &str, replacement: &str) -> Option<String> {
1802    match (pattern.find('*'), replacement.find('*')) {
1803        (Some(pstar), Some(vstar)) => {
1804            let kprefix = &pattern[..pstar];
1805            let ksuffix = &pattern[pstar + 1..];
1806            if !refname.starts_with(kprefix) || !refname.ends_with(ksuffix) {
1807                return None;
1808            }
1809            if refname.len() < kprefix.len() + ksuffix.len() {
1810                return None;
1811            }
1812            let middle = &refname[kprefix.len()..refname.len() - ksuffix.len()];
1813            Some(format!(
1814                "{}{}{}",
1815                &replacement[..vstar],
1816                middle,
1817                &replacement[vstar + 1..]
1818            ))
1819        }
1820        (None, None) if pattern == refname => Some(replacement.to_owned()),
1821        _ => None,
1822    }
1823}
1824
1825fn delete_branch_label(specs: &[PushRefSpec]) -> Option<String> {
1826    if specs.len() != 1 {
1827        return None;
1828    }
1829    specs[0].dst.strip_prefix("refs/heads/").map(str::to_owned)
1830}
1831
1832fn branch_label_from_specs(_repo: &Repository, specs: &[PushRefSpec]) -> Option<String> {
1833    if specs.len() != 1 || specs[0].delete {
1834        return None;
1835    }
1836    let dst = &specs[0].dst;
1837    dst.strip_prefix("refs/heads/")
1838        .or_else(|| dst.strip_prefix("refs/tags/"))
1839        .map(str::to_owned)
1840}
1841
1842#[cfg(test)]
1843mod tests {
1844    use super::*;
1845    use crate::config::environment::Environment;
1846    use crate::remote::RemoteError;
1847    use crate::repo::{InitOptions, Repository};
1848
1849    fn init_repo() -> (tempfile::TempDir, Repository) {
1850        let tmp = tempfile::tempdir().expect("tempdir");
1851        let (repo, _) = Repository::init(tmp.path(), &InitOptions::default()).expect("init");
1852        (tmp, repo)
1853    }
1854
1855    #[test]
1856    fn push_remote_precedence_pushremote_over_remote() {
1857        let (_tmp, repo) = init_repo();
1858        let git_dir = repo.git_dir();
1859        std::fs::write(
1860            git_dir.join("config"),
1861            r#"[remote "origin"]
1862	url = /tmp/o.git
1863[remote "upstream"]
1864	url = /tmp/u.git
1865[branch "main"]
1866	remote = origin
1867	pushRemote = upstream
1868"#,
1869        )
1870        .expect("write config");
1871        std::fs::write(git_dir.join("HEAD"), "ref: refs/heads/main\n").expect("write HEAD");
1872        let config = ConfigSet::load(
1873            &Environment::empty(),
1874            Some(git_dir),
1875            &crate::config::LoadConfigOptions::standard(&Environment::empty(), Some(git_dir)),
1876        )
1877        .expect("config");
1878        let remote = configured_remote_for_push(&repo, &config, None).expect("remote");
1879        assert_eq!(remote, "upstream");
1880    }
1881
1882    #[test]
1883    fn map_through_skips_malformed_remote_push_refspec() {
1884        let (_tmp, repo) = init_repo();
1885        let git_dir = repo.git_dir();
1886        std::fs::write(
1887            git_dir.join("config"),
1888            r#"[remote "origin"]
1889	url = /tmp/o.git
1890	push = not a valid refspec at all
1891	push = refs/heads/*:refs/remotes/origin/*
1892"#,
1893        )
1894        .expect("write config");
1895        std::fs::write(git_dir.join("HEAD"), "ref: refs/heads/main\n").expect("write HEAD");
1896        let config = ConfigSet::load(
1897            &Environment::empty(),
1898            Some(git_dir),
1899            &crate::config::LoadConfigOptions::standard(&Environment::empty(), Some(git_dir)),
1900        )
1901        .expect("config");
1902        let mapped = map_through_remote_push_refspec(&config, "origin", "refs/heads/main");
1903        assert_eq!(
1904            mapped.as_deref(),
1905            Some("refs/heads/main:refs/remotes/origin/main")
1906        );
1907    }
1908
1909    #[test]
1910    fn force_with_lease_tracking_sets_expected_old() {
1911        let (_tmp, repo) = init_repo();
1912        let git_dir = repo.git_dir();
1913        std::fs::write(
1914            git_dir.join("config"),
1915            r#"[remote "origin"]
1916	url = /tmp/o.git
1917	fetch = +refs/heads/*:refs/remotes/origin/*
1918[branch "main"]
1919	remote = origin
1920	merge = refs/heads/main
1921"#,
1922        )
1923        .expect("config");
1924        std::fs::write(git_dir.join("HEAD"), "ref: refs/heads/main\n").expect("HEAD");
1925        let oid = ObjectId::from_hex("a".repeat(40).as_str()).expect("oid");
1926        std::fs::create_dir_all(git_dir.join("refs/heads")).expect("heads dir");
1927        std::fs::write(
1928            git_dir.join("refs/heads/main"),
1929            format!("{}\n", oid.to_hex()),
1930        )
1931        .expect("main");
1932        std::fs::create_dir_all(git_dir.join("refs/remotes/origin")).expect("rt dir");
1933        std::fs::write(
1934            git_dir.join("refs/remotes/origin/main"),
1935            format!("{}\n", oid.to_hex()),
1936        )
1937        .expect("tracking");
1938        let config = ConfigSet::load(
1939            &Environment::empty(),
1940            Some(git_dir),
1941            &crate::config::LoadConfigOptions::standard(&Environment::empty(), Some(git_dir)),
1942        )
1943        .expect("config");
1944        let ctx = PushPlanContext::default();
1945        let resolved = resolve_push(
1946            &repo,
1947            &PushRequest {
1948                force: ForceMode::Lease(LeaseExpectation::Tracking),
1949                ..Default::default()
1950            },
1951            &ctx,
1952        )
1953        .expect("resolve");
1954        assert_eq!(resolved.specs.len(), 1);
1955        assert_eq!(resolved.specs[0].expected_old, Some(oid));
1956        assert!(resolved.specs[0].force);
1957    }
1958
1959    #[test]
1960    fn negative_push_refspec_filters_planned_spec() {
1961        let item = parse_push_refspec("^refs/heads/private").expect("parse");
1962        let kept = push_spec(
1963            Some(ObjectId::from_hex("0".repeat(40).as_str()).expect("oid")),
1964            Some("refs/heads/main".into()),
1965            "refs/heads/main".into(),
1966            false,
1967            false,
1968        );
1969        let dropped = push_spec(
1970            Some(ObjectId::from_hex("1".repeat(40).as_str()).expect("oid")),
1971            Some("refs/heads/private".into()),
1972            "refs/heads/private".into(),
1973            false,
1974            false,
1975        );
1976        assert!(!push_spec_excluded_by_negative(&item, &kept));
1977        assert!(push_spec_excluded_by_negative(&item, &dropped));
1978    }
1979
1980    fn config_from(text: &str) -> ConfigSet {
1981        let file = crate::config::ConfigFile::parse(
1982            Path::new("config"),
1983            text,
1984            crate::config::ConfigScope::Local,
1985        )
1986        .expect("parse config");
1987        let mut config = ConfigSet::new();
1988        config.merge(&file);
1989        config
1990    }
1991
1992    fn strings(items: &[&str]) -> Vec<String> {
1993        items.iter().map(|s| (*s).to_owned()).collect()
1994    }
1995
1996    #[test]
1997    fn push_invocation_remote_flag_keeps_every_positional_as_refspec() {
1998        let config = ConfigSet::new();
1999        let invocation =
2000            resolve_push_invocation(&config, Some("upstream"), &strings(&["origin", "main"]))
2001                .expect("invocation");
2002        assert_eq!(
2003            invocation,
2004            PushInvocation {
2005                remote: Some("upstream".into()),
2006                refspecs: strings(&["origin", "main"]),
2007            }
2008        );
2009    }
2010
2011    #[test]
2012    fn push_invocation_without_positionals_uses_default_remote() {
2013        let invocation = resolve_push_invocation(&ConfigSet::new(), None, &[]).expect("invocation");
2014        assert_eq!(invocation, PushInvocation::default());
2015    }
2016
2017    #[test]
2018    fn push_invocation_first_positional_is_configured_remote() {
2019        let config = config_from("[remote \"upstream\"]\n\turl = /tmp/u.git\n");
2020        for positionals in [strings(&["upstream"]), strings(&["upstream", "a", "b:c"])] {
2021            let invocation =
2022                resolve_push_invocation(&config, None, &positionals).expect("invocation");
2023            assert_eq!(invocation.remote.as_deref(), Some("upstream"));
2024            assert_eq!(invocation.refspecs, positionals[1..]);
2025        }
2026    }
2027
2028    #[test]
2029    fn push_invocation_first_positional_is_literal_url_or_path() {
2030        let config = ConfigSet::new();
2031        for remote in [
2032            "https://example.com/r",
2033            "../sibling.git",
2034            "/srv/repo",
2035            "../srv",
2036            "./srv",
2037            "./../srv",
2038            "../deep/nb3",
2039            ".",
2040            "..",
2041        ] {
2042            let invocation = resolve_push_invocation(&config, None, &strings(&[remote, "main"]))
2043                .expect("invocation");
2044            assert_eq!(invocation.remote.as_deref(), Some(remote));
2045            assert_eq!(invocation.refspecs, strings(&["main"]));
2046        }
2047    }
2048
2049    #[test]
2050    fn push_invocation_single_unknown_positional_is_a_refspec() {
2051        let config = config_from("[remote \"blank\"]\n\turl =   \n");
2052        for token in ["main", "HEAD:refs/heads/x", "blank"] {
2053            let invocation =
2054                resolve_push_invocation(&config, None, &strings(&[token])).expect("invocation");
2055            assert_eq!(invocation.remote, None, "{token}");
2056            assert_eq!(invocation.refspecs, strings(&[token]));
2057        }
2058    }
2059
2060    #[test]
2061    fn push_without_any_remote_is_no_remote() {
2062        let (_tmp, repo) = init_repo();
2063        assert!(matches!(
2064            configured_remote_for_push(&repo, &ConfigSet::new(), None),
2065            Err(crate::error::Error::Remote(
2066                crate::remote::RemoteError::PushPlan(PushPlanError::NoRemote)
2067            ))
2068        ));
2069        assert_eq!(PushPlanError::NoRemote.to_string(), "no remote to push to");
2070        assert!(matches!(
2071            load_push_plan_context(&repo, None, None).map(|_| ()),
2072            Err(crate::error::Error::Remote(
2073                crate::remote::RemoteError::PushPlan(PushPlanError::NoRemote)
2074            ))
2075        ));
2076        let named = configured_remote_for_push(&repo, &ConfigSet::new(), Some("upstream"));
2077        assert_eq!(named.as_deref().unwrap(), "upstream");
2078        let url_less_origin = config_from("[remote \"origin\"]\n\tpushurl = /tmp/o.git\n");
2079        assert_eq!(
2080            configured_remote_for_push(&repo, &url_less_origin, None)
2081                .as_deref()
2082                .unwrap(),
2083            "origin"
2084        );
2085    }
2086
2087    #[test]
2088    fn push_invocation_unknown_remote_before_refspecs_is_rejected() {
2089        let err = resolve_push_invocation(&ConfigSet::new(), None, &strings(&["nosuch", "main"]))
2090            .expect_err("unknown remote");
2091        assert!(
2092            matches!(err, crate::error::Error::Remote(crate::remote::RemoteError::PushPlan(PushPlanError::UnknownRemote { name })) if name == "nosuch")
2093        );
2094    }
2095
2096    #[test]
2097    fn owner_project_shorthand_expands_to_host_url() {
2098        let config = config_from("[remote \"team/app\"]\n\turl = /srv/app.git\n");
2099        let expand = |args: &[&str]| {
2100            let args: Vec<String> = args.iter().map(|s| (*s).to_owned()).collect();
2101            expand_repository_shorthand(&config, &args, "https://grithub.dev/")
2102        };
2103        assert_eq!(
2104            expand(&["me/proj", "main"]).as_deref(),
2105            Some("https://grithub.dev/me/proj.git")
2106        );
2107        // A lone positional is a refspec, not a repository.
2108        assert_eq!(expand(&["topic/x"]), None);
2109        // Configured remotes, URLs and paths are left alone.
2110        for literal in [
2111            "team/app",
2112            "origin",
2113            "./a/b",
2114            "a/b/c",
2115            "x/y.git",
2116            "https://h/a/b",
2117        ] {
2118            assert_eq!(expand(&[literal, "main"]), None, "{literal}");
2119        }
2120    }
2121
2122    #[test]
2123    fn open_push_destination_reads_config_or_treats_literal_as_url() {
2124        let config = config_from(
2125            "[remote \"origin\"]\n\turl = /tmp/o.git\n[remote \"nourl\"]\n\tfetch = +refs/heads/*:refs/remotes/nourl/*\n",
2126        );
2127        let origin = open_push_destination(&config, "origin").expect("origin");
2128        assert_eq!(origin.name.as_deref(), Some("origin"));
2129        for path in ["/srv/other.git", "../srv", "./srv"] {
2130            let literal = open_push_destination(&config, path).expect("literal");
2131            assert_eq!(literal.name, None, "{path}");
2132        }
2133        assert!(matches!(
2134            open_push_destination(&config, "nourl"),
2135            Err(crate::error::Error::Remote(RemoteError::NoUrl { remote: Some(name) })) if name == "nourl"
2136        ));
2137    }
2138
2139    #[test]
2140    fn plan_context_from_advertisement_skips_peeled_entries() {
2141        let oid = |c: &str| ObjectId::from_hex(&c.repeat(40)).expect("oid");
2142        let remote_ref = |name: &str, hex: &str| RemoteRef {
2143            name: name.to_owned(),
2144            oid: oid(hex),
2145            symref_target: None,
2146        };
2147        let ctx = PushPlanContext::from_advertised_refs([
2148            remote_ref("HEAD", "1"),
2149            remote_ref("refs/heads/main", "1"),
2150            remote_ref("refs/heads/topic", "2"),
2151            remote_ref("refs/tags/v1", "3"),
2152            remote_ref("refs/tags/v1^{}", "4"),
2153        ]);
2154        let mut names: Vec<_> = ctx.remote_ref_names.iter().map(String::as_str).collect();
2155        names.sort_unstable();
2156        assert_eq!(
2157            names,
2158            [
2159                "HEAD",
2160                "refs/heads/main",
2161                "refs/heads/topic",
2162                "refs/tags/v1"
2163            ]
2164        );
2165        assert_eq!(ctx.remote_branch_tips, HashSet::from([oid("1"), oid("2")]));
2166        assert_eq!(
2167            ctx.remote_tips,
2168            Some(vec![oid("1"), oid("1"), oid("2"), oid("3")])
2169        );
2170    }
2171
2172    #[test]
2173    fn plan_context_from_empty_advertisement_knows_remote_has_no_tips() {
2174        let ctx = PushPlanContext::from_advertised_refs([]);
2175        assert_eq!(ctx.remote_tips, Some(Vec::new()));
2176    }
2177
2178    #[test]
2179    fn plan_context_is_empty_for_unconfigured_remote() {
2180        let (_tmp, repo) = init_repo();
2181        let ctx = load_push_plan_context(&repo, Some("nosuch"), None).expect("context");
2182        assert!(ctx.remote_ref_names.is_empty());
2183        assert!(ctx.remote_branch_tips.is_empty());
2184        assert_eq!(ctx.remote_tips, None);
2185    }
2186
2187    #[test]
2188    fn plan_context_for_missing_path_assumes_no_remote_objects() {
2189        let (tmp, repo) = init_repo();
2190        let missing = tmp.path().join("missing.git");
2191        let missing = missing.to_str().expect("utf-8 path");
2192        let ctx = load_push_plan_context(&repo, Some(missing), None).expect("context");
2193        assert!(ctx.remote_ref_names.is_empty());
2194        assert!(ctx.remote_tips.as_ref().is_none_or(Vec::is_empty));
2195    }
2196
2197    #[test]
2198    fn tag_push_branch_label_is_tag_name_not_current_branch() {
2199        let (_tmp, repo) = init_repo();
2200        let git_dir = repo.git_dir();
2201        std::fs::write(
2202            git_dir.join("config"),
2203            r#"[remote "origin"]
2204	url = /tmp/o.git
2205"#,
2206        )
2207        .expect("config");
2208        std::fs::write(git_dir.join("HEAD"), "ref: refs/heads/main\n").expect("HEAD");
2209        let oid = ObjectId::from_hex("a".repeat(40).as_str()).expect("oid");
2210        std::fs::create_dir_all(git_dir.join("refs/heads")).expect("heads");
2211        std::fs::write(
2212            git_dir.join("refs/heads/main"),
2213            format!("{}\n", oid.to_hex()),
2214        )
2215        .expect("main");
2216        std::fs::create_dir_all(git_dir.join("refs/tags")).expect("tags");
2217        std::fs::write(git_dir.join("refs/tags/v1"), format!("{}\n", oid.to_hex())).expect("tag");
2218        let config = ConfigSet::load(
2219            &Environment::empty(),
2220            Some(git_dir),
2221            &crate::config::LoadConfigOptions::standard(&Environment::empty(), Some(git_dir)),
2222        )
2223        .expect("config");
2224        let ctx = PushPlanContext::default();
2225        let resolved = resolve_push(
2226            &repo,
2227            &PushRequest {
2228                remote: Some("origin".to_owned()),
2229                refspecs: vec!["v1".to_owned()],
2230                ..Default::default()
2231            },
2232            &ctx,
2233        )
2234        .expect("resolve tag push");
2235        assert_eq!(resolved.branch_label.as_deref(), Some("v1"));
2236        assert_eq!(resolved.kind, PushPlanKind::Refspecs);
2237        assert_eq!(resolved.specs[0].dst, "refs/tags/v1");
2238    }
2239
2240    fn delete_request(refspecs: &[&str]) -> PushRequest {
2241        PushRequest {
2242            remote: Some("origin".to_owned()),
2243            refspecs: strings(refspecs),
2244            delete_refs: true,
2245            ..Default::default()
2246        }
2247    }
2248
2249    #[test]
2250    fn delete_push_plans_every_plain_name() {
2251        let (_tmp, repo) = init_repo();
2252        let config = config_from("[remote \"origin\"]\n\turl = /tmp/o.git\n");
2253        let ctx = PushPlanContext {
2254            remote_ref_names: HashSet::from(["refs/tags/v1".to_owned()]),
2255            ..Default::default()
2256        };
2257        let resolved = resolve_push(
2258            &repo,
2259            &delete_request(&["a", "refs/heads/b", "v1", "+c", "HEAD"]),
2260            &ctx,
2261        )
2262        .expect("resolve delete push");
2263        assert_eq!(resolved.kind, PushPlanKind::Delete);
2264        assert_eq!(resolved.branch_label, None);
2265        let dsts: Vec<_> = resolved.specs.iter().map(|s| s.dst.as_str()).collect();
2266        assert_eq!(
2267            dsts,
2268            [
2269                "refs/heads/a",
2270                "refs/heads/b",
2271                "refs/tags/v1",
2272                "refs/heads/+c",
2273                "refs/heads/HEAD"
2274            ]
2275        );
2276        assert!(resolved
2277            .specs
2278            .iter()
2279            .all(|s| s.delete && !s.force && s.src.is_none()));
2280    }
2281
2282    #[test]
2283    fn delete_push_unions_delete_list_with_refspecs() {
2284        let (_tmp, repo) = init_repo();
2285        let config = config_from("[remote \"origin\"]\n\turl = /tmp/o.git\n");
2286        let request = PushRequest {
2287            delete: strings(&["a"]),
2288            ..delete_request(&["b"])
2289        };
2290        let resolved = resolve_push(&repo, &request, &PushPlanContext::default())
2291            .expect("resolve delete push");
2292        let dsts: Vec<_> = resolved.specs.iter().map(|s| s.dst.as_str()).collect();
2293        assert_eq!(dsts, ["refs/heads/a", "refs/heads/b"]);
2294        assert_eq!(
2295            resolve_push(
2296                &repo,
2297                &PushRequest {
2298                    delete_refs: false,
2299                    ..request
2300                },
2301                &PushPlanContext::default(),
2302            )
2303            .unwrap()
2304            .specs
2305            .len(),
2306            2
2307        );
2308    }
2309
2310    #[test]
2311    fn delete_push_rejects_colon_refspec() {
2312        let (_tmp, repo) = init_repo();
2313        let config = config_from("[remote \"origin\"]\n\turl = /tmp/o.git\n");
2314        for spec in ["HEAD:refs/heads/release", ":b", "a:"] {
2315            let err = resolve_push(
2316                &repo,
2317                &delete_request(&["ok", spec]),
2318                &PushPlanContext::default(),
2319            )
2320            .expect_err("colon refspec with --delete");
2321            assert!(
2322                matches!(
2323                    &err,
2324                    crate::error::Error::Remote(crate::remote::RemoteError::PushPlan(PushPlanError::DeleteNotPlainName { spec: s })) if s == spec
2325                ),
2326                "{err}"
2327            );
2328            assert!(err.to_string().contains(spec), "{err}");
2329        }
2330    }
2331
2332    #[test]
2333    fn delete_push_without_refs_is_an_error() {
2334        let (_tmp, repo) = init_repo();
2335        let err = resolve_push(&repo, &delete_request(&[]), &PushPlanContext::default())
2336            .expect_err("empty delete");
2337        assert!(matches!(
2338            err,
2339            crate::error::Error::Remote(crate::remote::RemoteError::PushPlan(
2340                PushPlanError::DeleteWithoutRefs
2341            ))
2342        ));
2343    }
2344
2345    #[test]
2346    fn many_shorthand_refspecs_resolve_local_heads() {
2347        let (_tmp, repo) = init_repo();
2348        let git_dir = repo.git_dir();
2349        std::fs::write(
2350            git_dir.join("config"),
2351            r#"[remote "origin"]
2352	url = /tmp/o.git
2353"#,
2354        )
2355        .expect("config");
2356        std::fs::write(git_dir.join("HEAD"), "ref: refs/heads/main\n").expect("HEAD");
2357        let oid = ObjectId::from_hex("a".repeat(40).as_str()).expect("oid");
2358        std::fs::create_dir_all(git_dir.join("refs/heads")).expect("heads");
2359        std::fs::write(
2360            git_dir.join("refs/heads/main"),
2361            format!("{}\n", oid.to_hex()),
2362        )
2363        .expect("main");
2364        for i in 1..=500 {
2365            std::fs::write(
2366                git_dir.join(format!("refs/heads/b{i}")),
2367                format!("{}\n", oid.to_hex()),
2368            )
2369            .expect("branch");
2370        }
2371        let config = ConfigSet::load(
2372            &Environment::empty(),
2373            Some(git_dir),
2374            &crate::config::LoadConfigOptions::standard(&Environment::empty(), Some(git_dir)),
2375        )
2376        .expect("config");
2377        let refspecs: Vec<String> = (1..=500).map(|i| format!("b{i}")).collect();
2378        let resolved = resolve_push(
2379            &repo,
2380            &PushRequest {
2381                remote: Some("origin".to_owned()),
2382                refspecs,
2383                ..Default::default()
2384            },
2385            &PushPlanContext::default(),
2386        )
2387        .expect("resolve many shorthands");
2388        assert_eq!(resolved.specs.len(), 500);
2389        for (i, spec) in resolved.specs.iter().enumerate() {
2390            let n = i + 1;
2391            assert_eq!(spec.dst, format!("refs/heads/b{n}"));
2392            assert_eq!(spec.src, Some(oid));
2393            assert_eq!(
2394                spec.src_ref.as_deref(),
2395                Some(format!("refs/heads/b{n}").as_str())
2396            );
2397        }
2398    }
2399
2400    #[test]
2401    fn shorthand_ambiguous_head_and_tag_same_name() {
2402        let (_tmp, repo) = init_repo();
2403        let git_dir = repo.git_dir();
2404        std::fs::write(
2405            git_dir.join("config"),
2406            r#"[remote "origin"]
2407	url = /tmp/o.git
2408"#,
2409        )
2410        .expect("config");
2411        let oid = ObjectId::from_hex("b".repeat(40).as_str()).expect("oid");
2412        std::fs::create_dir_all(git_dir.join("refs/heads")).expect("heads");
2413        std::fs::create_dir_all(git_dir.join("refs/tags")).expect("tags");
2414        std::fs::write(
2415            git_dir.join("refs/heads/release"),
2416            format!("{}\n", oid.to_hex()),
2417        )
2418        .expect("head");
2419        std::fs::write(
2420            git_dir.join("refs/tags/release"),
2421            format!("{}\n", oid.to_hex()),
2422        )
2423        .expect("tag");
2424        let config = ConfigSet::load(
2425            &Environment::empty(),
2426            Some(git_dir),
2427            &crate::config::LoadConfigOptions::standard(&Environment::empty(), Some(git_dir)),
2428        )
2429        .expect("config");
2430        let err = resolve_push(
2431            &repo,
2432            &PushRequest {
2433                remote: Some("origin".to_owned()),
2434                refspecs: vec!["release".to_owned()],
2435                ..Default::default()
2436            },
2437            &PushPlanContext::default(),
2438        )
2439        .expect_err("ambiguous");
2440        assert!(matches!(
2441            err,
2442            crate::error::Error::Remote(crate::remote::RemoteError::PushPlan(PushPlanError::SrcRefspecAmbiguous { spec })) if spec == "release"
2443        ));
2444    }
2445
2446    #[test]
2447    fn shorthand_honors_remote_push_mapping() {
2448        let (_tmp, repo) = init_repo();
2449        let git_dir = repo.git_dir();
2450        std::fs::write(
2451            git_dir.join("config"),
2452            r#"[remote "origin"]
2453	url = /tmp/o.git
2454	push = refs/heads/main:refs/remotes/origin/main
2455"#,
2456        )
2457        .expect("config");
2458        let oid = ObjectId::from_hex("c".repeat(40).as_str()).expect("oid");
2459        std::fs::create_dir_all(git_dir.join("refs/heads")).expect("heads");
2460        std::fs::write(
2461            git_dir.join("refs/heads/main"),
2462            format!("{}\n", oid.to_hex()),
2463        )
2464        .expect("main");
2465        let config = ConfigSet::load(
2466            &Environment::empty(),
2467            Some(git_dir),
2468            &crate::config::LoadConfigOptions::standard(&Environment::empty(), Some(git_dir)),
2469        )
2470        .expect("config");
2471        let resolved = resolve_push(
2472            &repo,
2473            &PushRequest {
2474                remote: Some("origin".to_owned()),
2475                refspecs: vec!["main".to_owned()],
2476                ..Default::default()
2477            },
2478            &PushPlanContext::default(),
2479        )
2480        .expect("mapped shorthand");
2481        assert_eq!(resolved.specs.len(), 1);
2482        assert_eq!(resolved.specs[0].dst, "refs/remotes/origin/main");
2483        assert_eq!(resolved.specs[0].src, Some(oid));
2484    }
2485}
2486
2487impl RepositoryRemotes<'_> {
2488    /// Turn `--force` / `--force-with-lease[=<rev>]` into a [`ForceMode`]. `force` wins; an
2489    /// explicit lease revision is resolved in this repository.
2490    ///
2491    /// # Errors
2492    ///
2493    /// [`PushPlanError::UnknownRevision`] when the lease revision does not resolve.
2494    pub fn force_mode(
2495        &self,
2496        force: bool,
2497        force_with_lease: Option<Option<String>>,
2498    ) -> PlanResult<ForceMode> {
2499        parse_force_mode(self.repository(), force, force_with_lease)
2500    }
2501
2502    /// Load the [`PushPlanContext`] for the remote a push would select (`remote`, or the
2503    /// configured push remote when `None`).
2504    ///
2505    /// The remote is chosen like [`Self::resolve_push`] chooses it, opened with
2506    /// [`open_push_destination`] (so literal URLs and paths are listed like configured
2507    /// remotes) and listed with [`Remote::list_push_refs`]. The context is best-effort: a
2508    /// remote without a URL, or one whose refs cannot be listed, yields an empty context, and
2509    /// the push itself reports any connection failure.
2510    ///
2511    /// The listing uses a [preflight client](HttpClientFactory::create_for_preflight), so
2512    /// credentials the server refuses stay stored and the push reports them as rejected
2513    /// ([`AuthFailure::Rejected`](crate::error::AuthFailure::Rejected)).
2514    ///
2515    /// # Errors
2516    ///
2517    /// Only errors selecting the remote (for example [`PushPlanError::NoRemote`]).
2518    pub fn push_plan_context(
2519        &self,
2520        remote: Option<&str>,
2521        http_factory: Option<&dyn HttpClientFactory>,
2522    ) -> PlanResult<PushPlanContext> {
2523        load_push_plan_context(self.repository(), remote, http_factory)
2524    }
2525
2526    /// Resolve `request` into a remote name and [`PushRefSpec`] list, using `ctx` (from
2527    /// [`Self::push_plan_context`]) for delete and destination DWIM.
2528    ///
2529    /// When `ctx.remote_ref_names` is empty, delete/ref DWIM still uses local refs and falls
2530    /// back to Git's default `refs/heads/<name>` for deletes. A delete push
2531    /// ([`PushRequest::delete_refs`] or a non-empty [`PushRequest::delete`]) plans one deletion
2532    /// per name in `delete` and `refspecs`, and nothing else.
2533    ///
2534    /// # Errors
2535    ///
2536    /// Besides remote and refspec resolution failures: [`PushPlanError::DeleteNotPlainName`]
2537    /// when a delete push is given a `src:dst` refspec, and [`PushPlanError::DeleteWithoutRefs`]
2538    /// when it names no ref. Both are reported before the remote is contacted.
2539    pub fn resolve_push(
2540        &self,
2541        request: &PushRequest,
2542        ctx: &PushPlanContext,
2543    ) -> PlanResult<ResolvedPush> {
2544        resolve_push(self.repository(), request, ctx)
2545    }
2546
2547    /// The annotated tag refspecs `git push --follow-tags` adds to `specs`.
2548    ///
2549    /// Lightweight tags are skipped, tags already on the remote (per `ctx`) are skipped, and
2550    /// reachability uses commit-graph ancestor checks from the pushed tips (any ref
2551    /// namespace). Tag refspecs and specs whose source is a tag object do not seed the walk.
2552    ///
2553    /// # Errors
2554    ///
2555    /// Repository failures while reading tags or walking history.
2556    pub fn follow_tag_push_specs(
2557        &self,
2558        specs: &[PushRefSpec],
2559        ctx: &PushPlanContext,
2560    ) -> PlanResult<Vec<PushRefSpec>> {
2561        follow_tag_push_specs(self.repository(), specs, ctx)
2562    }
2563
2564    /// Let `spec` replace the remote ref when it still holds what this clone's
2565    /// remote-tracking ref for it says (`--force-with-lease` for one ref), or is absent when
2566    /// there is none. `remote` names the remote whose tracking refs are consulted.
2567    pub fn apply_tracking_lease(&self, remote: &str, spec: &mut PushRefSpec) {
2568        apply_tracking_lease(self.repository(), remote, spec);
2569    }
2570
2571    /// After a successful push to `remote`, write `branch.<name>.remote` and
2572    /// `branch.<name>.merge` for every branch update in `specs` that `results` reports as
2573    /// pushed (`push -u` / [`PushRequest::set_upstream`]). Call it only for a push that was
2574    /// not a dry run.
2575    ///
2576    /// Returns the short names of the branches whose upstream config was written.
2577    ///
2578    /// # Errors
2579    ///
2580    /// Config read or write failures.
2581    pub fn set_upstream_after_push(
2582        &self,
2583        remote: &str,
2584        specs: &[PushRefSpec],
2585        results: &[PushRefResult],
2586    ) -> Result<Vec<String>, crate::error::Error> {
2587        apply_push_set_upstream(self.repository(), remote, specs, results)
2588    }
2589}