grit-lib 0.5.18

Core library for the grit Git implementation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
//! Remote configuration and transport operations scoped to a [`Repository`](crate::repo::Repository).

use std::collections::{BTreeSet, HashSet};

use crate::check_ref_format::{check_refname_format, RefNameOptions};
use crate::config::{ConfigFile, ConfigScope, ConfigSet};
use crate::error::Result;
use crate::fetch::Progress;
use crate::refs::store::{Expected, RefUpdate, RefUpdateFlags};
use crate::refs::{commit_ref_updates_on_store, list_refs_for_repository};
use crate::refspec::{fetch_specs_bind_local_ref, parse_fetch_refspec, RefspecItem};
use crate::remote::{
    inspect_remote, HttpClientFactory, InspectOptions, ListRefsOptions, Remote, RemoteError,
    RemoteRef, RemoteSummary, DEFAULT_REMOTE,
};
use crate::repo::Repository;
use crate::transfer::{FetchOptions, FetchOutcome, PushOptions, PushOutcome, PushRefSpec};
use crate::url_rewrite;

/// Remote names and network operations for one open repository.
#[derive(Debug, Copy, Clone)]
pub struct RepositoryRemotes<'repo> {
    repo: &'repo Repository,
}

impl<'repo> RepositoryRemotes<'repo> {
    pub(crate) fn new(repo: &'repo Repository) -> Self {
        Self { repo }
    }

    /// Borrow the underlying repository.
    #[must_use]
    pub fn repository(&self) -> &'repo Repository {
        self.repo
    }

    /// Names of remotes with a configured `remote.<name>.url` in the merged config cascade.
    ///
    /// # Errors
    ///
    /// Propagates [`Repository::config`] failures.
    ///
    /// # Examples
    ///
    /// ```
    /// # use grit_lib::repo::Repository;
    /// # use std::path::Path;
    /// # fn demo() -> grit_lib::error::Result<()> {
    /// let repo = Repository::discover(Some(Path::new(".")), &grit_lib::config::environment::RepositoryOptions::empty())?;
    /// let names = repo.remotes().list()?;
    /// let _ = names;
    /// # Ok(())
    /// # }
    /// ```
    pub fn list(&self) -> Result<Vec<String>> {
        let config = self.repo.config()?;
        Ok(configured_remote_names(config.as_ref()))
    }

    /// Every remote with a `remote.<name>.*` section, sorted by name, with its URL.
    ///
    /// Unlike [`Self::list`], this includes remotes that have config but no
    /// `remote.<name>.url` (their [`ConfiguredRemote::url`] is `None`).
    ///
    /// # Errors
    ///
    /// Propagates [`Repository::config`] failures.
    pub fn configured(&self) -> Result<Vec<ConfiguredRemote>> {
        let config = self.repo.config()?;
        Ok(configured_remotes(config.as_ref()))
    }

    /// Replace the fetch or push URL for an existing remote.
    ///
    /// Fetch updates `remote.<name>.url`. Push removes every `remote.<name>.pushurl` entry and
    /// writes a single new one, matching `git remote set-url --push`. Writes the shared
    /// repository config (same rules as [`Self::add`]), then reloads config unless `dry_run`.
    ///
    /// # Errors
    ///
    /// - [`RemoteError::UnknownRemote`] when no `remote.<name>.*` section exists.
    /// - [`RemoteError::Library`] when config cannot be read or written.
    pub fn set_url(
        &self,
        name: &str,
        url: &str,
        kind: RemoteUrlKind,
        dry_run: bool,
    ) -> std::result::Result<UrlChange, RemoteError> {
        let config = self.repo.config().map_err(RemoteError::Library)?;
        if !has_remote_section(config.as_ref(), name) {
            return Err(RemoteError::UnknownRemote(name.to_owned()));
        }
        let old = match kind {
            RemoteUrlKind::Fetch => config.get(&format!("remote.{name}.url")),
            RemoteUrlKind::Push => config
                .get(&format!("remote.{name}.pushurl"))
                .filter(|u| !u.trim().is_empty()),
        };
        let change = UrlChange {
            old,
            new: url.to_owned(),
        };
        if dry_run {
            return Ok(change);
        }
        let path = crate::repo::common_git_dir_for_config(self.repo.git_dir()).join("config");
        let mut file = match ConfigFile::from_path(&path, ConfigScope::Local)? {
            Some(file) => file,
            None => ConfigFile::parse(&path, "", ConfigScope::Local)?,
        };
        match kind {
            RemoteUrlKind::Fetch => {
                let key = format!("remote.{name}.url");
                if file.count(&key)? > 1 {
                    file.unset(&key)?;
                }
                file.set(&key, url)?;
            }
            RemoteUrlKind::Push => {
                file.unset(&format!("remote.{name}.pushurl"))?;
                file.set(&format!("remote.{name}.pushurl"), url)?;
            }
        }
        file.write()?;
        self.repo.reload_config()?;
        Ok(change)
    }

    /// Add remote `name` at `url` to the repository's local config.
    ///
    /// Writes `remote.<name>.url` and the default fetch refspec
    /// `+refs/heads/*:refs/remotes/<name>/*` to the shared repository config (the common
    /// directory's `config`, also from a linked worktree that has its own admin `config`),
    /// then reloads [`Repository::config`]. The URL is stored as given and
    /// not validated, like Git.
    ///
    /// # Errors
    ///
    /// - [`RemoteError::InvalidRemoteName`] when `refs/remotes/<name>/…` would not be a valid ref.
    /// - [`RemoteError::RemoteExists`] when any `remote.<name>.*` key is already configured.
    /// - [`RemoteError::Library`] when the config cannot be read, parsed, or written.
    pub fn add(&self, name: &str, url: &str) -> std::result::Result<(), RemoteError> {
        if !is_valid_remote_name(name) {
            return Err(RemoteError::InvalidRemoteName(name.to_owned()));
        }
        if has_remote_section(self.repo.config()?.as_ref(), name) {
            return Err(RemoteError::RemoteExists(name.to_owned()));
        }
        // Git keeps remotes in the common config even when a worktree admin dir has its own.
        let path = crate::repo::common_git_dir_for_config(self.repo.git_dir()).join("config");
        let mut file = match ConfigFile::from_path(&path, ConfigScope::Local)? {
            Some(file) => file,
            None => ConfigFile::parse(&path, "", ConfigScope::Local)?,
        };
        file.set(&format!("remote.{name}.url"), url)?;
        file.set(
            &format!("remote.{name}.fetch"),
            &format!("+refs/heads/*:refs/remotes/{name}/*"),
        )?;
        file.write()?;
        self.repo.reload_config()?;
        Ok(())
    }

    /// Load `remote.<name>` URL(s) and fetch refspecs from config.
    ///
    /// # Errors
    ///
    /// Returns [`RemoteError::NoUrl`] when the remote is missing or has no URL.
    ///
    /// # Examples
    ///
    /// ```
    /// # use grit_lib::repo::Repository;
    /// # use std::path::Path;
    /// # fn demo() -> Result<(), Box<dyn std::error::Error>> {
    /// let repo = Repository::discover(Some(Path::new(".")), &grit_lib::config::environment::RepositoryOptions::empty())?;
    /// if let Ok(origin) = repo.remotes().get("origin") {
    ///     let _url = origin.fetch_url();
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn get(&self, name: &str) -> std::result::Result<Remote, RemoteError> {
        let config = self.repo.config().map_err(RemoteError::Library)?;
        Remote::from_config(config.as_ref(), name)
    }

    /// Resolve a remote by name, falling back to [`DEFAULT_REMOTE`] when `name` is empty.
    ///
    /// # Errors
    ///
    /// Same as [`Self::get`].
    pub fn get_or_default(&self, name: &str) -> std::result::Result<Remote, RemoteError> {
        let trimmed = name.trim();
        if trimmed.is_empty() {
            self.get(DEFAULT_REMOTE)
        } else {
            self.get(trimmed)
        }
    }

    /// List references on `remote` ([`Remote::list_refs`] with this repository as context).
    ///
    /// # Errors
    ///
    /// Propagates [`RemoteError`] from the wire or local transport.
    ///
    /// # Examples
    ///
    /// ```
    /// # use grit_lib::remote::{ListRefsOptions, Remote};
    /// # use grit_lib::repo::Repository;
    /// # use std::path::Path;
    /// # fn demo() -> Result<(), Box<dyn std::error::Error>> {
    /// let repo = Repository::discover(Some(Path::new(".")), &grit_lib::config::environment::RepositoryOptions::empty())?;
    /// let remote = Remote::from_url("/path/to/other.git")?;
    /// let refs = repo.remotes().ls_remote(&remote, &ListRefsOptions::default(), None)?;
    /// let _ = refs.len();
    /// # Ok(())
    /// # }
    /// ```
    pub fn ls_remote(
        &self,
        remote: &Remote,
        options: &ListRefsOptions,
        http_factory: Option<&dyn HttpClientFactory>,
    ) -> std::result::Result<Vec<RemoteRef>, RemoteError> {
        remote.list_refs(Some(self.repo), options, http_factory)
    }

    /// Fetch from `remote` into this repository.
    ///
    /// # Errors
    ///
    /// Propagates transport and ref-update failures as [`RemoteError`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use grit_lib::remote::fetch::NoProgress;
    /// # use grit_lib::remote::Remote;
    /// # use grit_lib::repo::Repository;
    /// # use grit_lib::remote::transfer::FetchOptions;
    /// # use std::path::Path;
    /// # fn demo() -> Result<(), Box<dyn std::error::Error>> {
    /// let repo = Repository::discover(Some(Path::new(".")), &grit_lib::config::environment::RepositoryOptions::empty())?;
    /// let remote = Remote::from_url("/path/to/upstream.git")?;
    /// let mut progress = NoProgress;
    /// let _out = repo
    ///     .remotes()
    ///     .fetch(&remote, FetchOptions::default(), &mut progress, None)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn fetch(
        &self,
        remote: &Remote,
        options: FetchOptions,
        progress: &mut dyn Progress,
        http_factory: Option<&dyn HttpClientFactory>,
    ) -> std::result::Result<FetchOutcome, RemoteError> {
        remote.fetch(self.repo, options, progress, http_factory)
    }

    /// Fetch from every configured remote in config load order, skipping
    /// `remote.<name>.skipFetchAll=true` entries.
    ///
    /// Each remote uses [`resolve_fetch_prune`](crate::remote::transfer::resolve_fetch_prune)
    /// and [`resolve_fetch_tags`](crate::remote::transfer::resolve_fetch_tags) with
    /// `cli_prune` / `cli_tags` when set; otherwise that remote's own config.
    /// Failures are recorded per remote and fetching continues.
    ///
    /// # Errors
    ///
    /// Returns [`crate::error::Error::Config`] when prune config is invalid for
    /// a remote (same as
    /// [`resolve_fetch_prune`](crate::remote::transfer::resolve_fetch_prune)).
    pub fn fetch_all(
        &self,
        config: &ConfigSet,
        base: &FetchOptions,
        cli_prune: Option<bool>,
        cli_tags: Option<bool>,
        progress: &mut dyn Progress,
        http_factory: Option<&dyn HttpClientFactory>,
    ) -> Result<Vec<(String, std::result::Result<FetchOutcome, RemoteError>)>> {
        use crate::remote::transfer::{resolve_fetch_prune, resolve_fetch_tags};

        let mut results = Vec::new();
        for name in configured_remote_names_in_config_order(config) {
            if remote_skip_fetch_all(config, &name) {
                continue;
            }
            let prune = resolve_fetch_prune(config, &name, cli_prune)?;
            let tags = resolve_fetch_tags(config, &name, cli_tags);
            let opts = FetchOptions {
                tags,
                prune,
                dry_run: base.dry_run,
                fetch_depth: base.fetch_depth,
                deepen_since: base.deepen_since.clone(),
                deepen_not: base.deepen_not.clone(),
                index_pack_threads: base.index_pack_threads,
                thread_policy: self.repo.thread_policy(),
                environment: base.environment.clone(),
                pack_spool_only: base.pack_spool_only,
                http_protocol_version: base.http_protocol_version,
                remote_progress: base.remote_progress,
                ..Default::default()
            };
            let outcome = self
                .get(&name)
                .and_then(|remote| self.fetch(&remote, opts, progress, http_factory));
            results.push((name, outcome));
        }
        Ok(results)
    }

    /// Push `refs` to `remote` from this repository.
    ///
    /// # Errors
    ///
    /// Propagates transport and ref-update failures as [`RemoteError`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use grit_lib::remote::fetch::NoProgress;
    /// # use grit_lib::remote::Remote;
    /// # use grit_lib::repo::Repository;
    /// # use grit_lib::remote::transfer::{PushOptions, PushRefSpec};
    /// # use std::path::Path;
    /// # fn demo() -> Result<(), Box<dyn std::error::Error>> {
    /// let repo = Repository::discover(Some(Path::new(".")), &grit_lib::config::environment::RepositoryOptions::empty())?;
    /// let remote = Remote::from_url("/path/to/upstream.git")?;
    /// let mut progress = NoProgress;
    /// let refs: Vec<PushRefSpec> = Vec::new();
    /// let _out = repo
    ///     .remotes()
    ///     .push(&remote, &refs, PushOptions::default(), &mut progress, None)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn push(
        &self,
        remote: &Remote,
        refs: &[PushRefSpec],
        options: PushOptions,
        progress: &mut dyn Progress,
        http_factory: Option<&dyn HttpClientFactory>,
    ) -> std::result::Result<PushOutcome, RemoteError> {
        remote.push(self.repo, refs, options, progress, http_factory)
    }

    /// Summarize a configured remote: URLs, default branch, tracking branch states, pull config.
    ///
    /// With [`InspectOptions::query`], contacts the remote (like `git remote show`) to classify
    /// branches as tracked, new, or stale. Without a query, branch states come from local
    /// remote-tracking refs only (every branch is reported as tracked).
    ///
    /// # Errors
    ///
    /// - [`RemoteError::UnknownRemote`] when `name` is not configured.
    /// - [`RemoteError::NoUrl`] when the remote has no URL.
    /// - Propagates transport and ref errors as [`RemoteError::Library`].
    pub fn inspect(
        &self,
        name: &str,
        options: &InspectOptions,
        http_factory: Option<&dyn HttpClientFactory>,
    ) -> std::result::Result<RemoteSummary, RemoteError> {
        inspect_remote(self.repo, name, options, http_factory)
    }

    /// Remove remote `name`: drop its config section, remote-tracking refs, and branch upstream keys.
    ///
    /// Tracking refs another remote's fetch refspec also maps to are kept, matching `git remote remove`.
    ///
    /// # Errors
    ///
    /// - [`RemoteError::UnknownRemote`] when no `remote.<name>.*` section exists.
    /// - [`RemoteError::Library`] when config or ref updates fail.
    pub fn remove(
        &self,
        name: &str,
        options: RemoveOptions,
    ) -> std::result::Result<RemoteRemoval, RemoteError> {
        let config = self.repo.config().map_err(RemoteError::Library)?;
        if !has_remote_section(config.as_ref(), name) {
            return Err(RemoteError::UnknownRemote(name.to_owned()));
        }

        let refs_to_delete = refs_to_delete_for_remote(self.repo, config.as_ref(), name)?;
        let branches_untracked = branches_to_untrack(config.as_ref(), name);
        let mut config_keys_removed = branch_untrack_config_keys(&branches_untracked);
        for branch in branches_with_push_remote(config.as_ref(), name) {
            if !branches_untracked.contains(&branch) {
                config_keys_removed.push(format!("branch.{branch}.pushRemote"));
            }
        }
        if config.get("remote.pushDefault").as_deref() == Some(name) {
            config_keys_removed.push("remote.pushDefault".to_owned());
        }
        for entry in config.entries() {
            if entry.key.starts_with(&format!("remote.{name}.")) {
                config_keys_removed.push(entry.key.clone());
            }
        }
        config_keys_removed.sort_unstable();
        config_keys_removed.dedup();

        if options.dry_run {
            return Ok(RemoteRemoval {
                name: name.to_owned(),
                refs_deleted: refs_to_delete,
                config_keys_removed,
                branches_untracked,
                dry_run: true,
            });
        }

        let path = crate::repo::common_git_dir_for_config(self.repo.git_dir()).join("config");
        let mut file = match ConfigFile::from_path(&path, ConfigScope::Local)? {
            Some(file) => file,
            None => ConfigFile::parse(&path, "", ConfigScope::Local)?,
        };

        for branch in &branches_untracked {
            for suffix in ["remote", "merge"] {
                let key = format!("branch.{branch}.{suffix}");
                file.unset(&key)?;
            }
        }
        for branch in branches_with_push_remote(config.as_ref(), name) {
            file.unset(&format!("branch.{branch}.pushRemote"))?;
        }
        if config.get("remote.pushDefault").as_deref() == Some(name) {
            file.unset("remote.pushDefault")?;
        }

        let delete_flags = RefUpdateFlags {
            no_deref: true,
            ..RefUpdateFlags::default()
        };
        let updates: Vec<RefUpdate> = refs_to_delete
            .iter()
            .map(|refname| RefUpdate {
                name: refname.clone(),
                new_value: None,
                expected: Expected::Any,
                reflog: None,
                flags: delete_flags,
            })
            .collect();
        if !updates.is_empty() {
            commit_ref_updates_on_store(self.repo.refs(), &updates, &[])?;
        }

        if !file.remove_section(&format!("remote.{name}"))? {
            return Err(RemoteError::Library(crate::error::Error::Message(format!(
                "could not remove config section remote.{name}"
            ))));
        }
        file.write()?;
        self.repo.reload_config()?;

        Ok(RemoteRemoval {
            name: name.to_owned(),
            refs_deleted: refs_to_delete,
            config_keys_removed,
            branches_untracked,
            dry_run: false,
        })
    }
}

/// Options for [`RepositoryRemotes::remove`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct RemoveOptions {
    /// When true, report what would change without writing config or refs.
    pub dry_run: bool,
}

/// Outcome of removing a remote.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoteRemoval {
    /// Removed remote name.
    pub name: String,
    /// Deleted remote-tracking ref names (including `refs/remotes/<name>/HEAD` when removed).
    pub refs_deleted: Vec<String>,
    /// Config keys removed or unset (includes `remote.<name>.*` entries).
    pub config_keys_removed: Vec<String>,
    /// Local branch short names whose upstream keys were cleared.
    pub branches_untracked: Vec<String>,
    /// Whether this was a dry run.
    pub dry_run: bool,
}

/// Branch short names with `branch.<name>.remote` equal to `remote`.
#[must_use]
pub(crate) fn branches_tracking(config: &ConfigSet, remote: &str) -> Vec<String> {
    let mut branches = BTreeSet::new();
    for entry in config.entries() {
        let Some(rest) = entry.key.strip_prefix("branch.") else {
            continue;
        };
        let Some((branch, key)) = rest.rsplit_once('.') else {
            continue;
        };
        if key == "remote" && entry.value.as_deref() == Some(remote) {
            branches.insert(branch.to_owned());
        }
    }
    branches.into_iter().collect()
}

fn branches_to_untrack(config: &ConfigSet, remote: &str) -> Vec<String> {
    branches_tracking(config, remote)
}

fn branches_with_push_remote(config: &ConfigSet, remote: &str) -> Vec<String> {
    let mut branches = BTreeSet::new();
    for entry in config.entries() {
        let Some(rest) = entry.key.strip_prefix("branch.") else {
            continue;
        };
        let Some((branch, key)) = rest.rsplit_once('.') else {
            continue;
        };
        if key.eq_ignore_ascii_case("pushremote") && entry.value.as_deref() == Some(remote) {
            branches.insert(branch.to_owned());
        }
    }
    branches.into_iter().collect()
}

fn branch_untrack_config_keys(branches: &[String]) -> Vec<String> {
    let mut keys = Vec::with_capacity(branches.len() * 2);
    for branch in branches {
        keys.push(format!("branch.{branch}.remote"));
        keys.push(format!("branch.{branch}.merge"));
    }
    keys
}

fn remote_has_fetch_keys(config: &ConfigSet, remote: &str) -> bool {
    let prefix = format!("remote.{remote}.fetch");
    config
        .entries()
        .iter()
        .any(|entry| entry.key.starts_with(&prefix))
}

fn load_remote_fetch_specs(
    config: &ConfigSet,
    remote: &str,
) -> std::result::Result<Vec<RefspecItem>, RemoteError> {
    let had_fetch_keys = remote_has_fetch_keys(config, remote);
    let mut raw = config.get_all(&format!("remote.{remote}.fetch"));
    raw.retain(|s| !s.trim().is_empty());
    let mut specs = Vec::new();
    for line in raw {
        specs.push(
            parse_fetch_refspec(&line)
                .map_err(|e| RemoteError::Library(crate::error::Error::Message(e.to_string())))?,
        );
    }
    if !had_fetch_keys && specs.is_empty() {
        specs.push(
            parse_fetch_refspec(&format!("+refs/heads/*:refs/remotes/{remote}/*"))
                .map_err(|e| RemoteError::Library(crate::error::Error::Message(e.to_string())))?,
        );
    }
    Ok(specs)
}

fn ref_tracked_by_fetch(specs: &[RefspecItem], refname: &str) -> bool {
    fetch_specs_bind_local_ref(specs, refname).is_some()
}

fn refs_to_delete_for_remote(
    repo: &Repository,
    config: &ConfigSet,
    remote: &str,
) -> std::result::Result<Vec<String>, RemoteError> {
    let specs = load_remote_fetch_specs(config, remote)?;
    let other_specs: Vec<Vec<RefspecItem>> = configured_remotes(config)
        .into_iter()
        .map(|r| r.name)
        .filter(|n| n != remote)
        .filter_map(|name| load_remote_fetch_specs(config, &name).ok())
        .collect();

    let all_refs = list_refs_for_repository(repo, "refs/").map_err(RemoteError::Library)?;
    let mut refs_to_delete = BTreeSet::new();
    for (refname, _) in all_refs {
        if !refname.starts_with("refs/remotes/") {
            continue;
        }
        if !ref_tracked_by_fetch(&specs, &refname) {
            continue;
        }
        if other_specs
            .iter()
            .any(|other| ref_tracked_by_fetch(other, &refname))
        {
            continue;
        }
        refs_to_delete.insert(refname);
    }
    Ok(refs_to_delete.into_iter().collect())
}

/// Whether `remote.<name>.skipFetchAll` disables [`RepositoryRemotes::fetch_all`].
#[must_use]
pub fn remote_skip_fetch_all(config: &ConfigSet, remote: &str) -> bool {
    match config.get_bool(&format!("remote.{remote}.skipFetchAll")) {
        None | Some(Ok(false)) => false,
        Some(Ok(true)) => true,
        Some(Err(_)) => false,
    }
}

/// Remote names in merged config load order (first `remote.<name>.url` wins ordering).
#[must_use]
pub fn configured_remote_names_in_config_order(config: &ConfigSet) -> Vec<String> {
    let mut seen = HashSet::new();
    let mut names = Vec::new();
    for entry in config.entries() {
        let Some(rest) = entry.key.strip_prefix("remote.") else {
            continue;
        };
        let Some((name, key)) = rest.rsplit_once('.') else {
            continue;
        };
        if key == "url" && !name.is_empty() && seen.insert(name.to_owned()) {
            names.push(name.to_owned());
        }
    }
    names
}

/// Which URL field [`RepositoryRemotes::set_url`] updates.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RemoteUrlKind {
    /// `remote.<name>.url` (fetch).
    Fetch,
    /// `remote.<name>.pushurl` (replaces all push URLs with one).
    Push,
}

/// Result of [`RepositoryRemotes::set_url`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UrlChange {
    /// Previous URL for the selected kind, if any.
    pub old: Option<String>,
    /// New URL written (or that would be written when dry-run).
    pub new: String,
}

/// A remote that has a `remote.<name>.*` section in config.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfiguredRemote {
    /// Remote name (the config subsection).
    pub name: String,
    /// Last `remote.<name>.url` value, or `None` when the section has no URL.
    pub url: Option<String>,
    /// Raw `remote.<name>.pushurl` values from config (may be empty).
    pub push_urls: Vec<String>,
    /// Raw `remote.<name>.fetch` refspecs (empty when unset).
    pub fetch_refspecs: Vec<String>,
    /// Fetch URL after `url.*.insteadOf`, when [`Self::url`] is set.
    pub effective_fetch_url: Option<String>,
    /// Push URL after `pushInsteadOf` / `insteadOf`; equals [`Self::effective_fetch_url`] when no push URL is configured.
    pub effective_push_url: Option<String>,
    /// Each [`Self::push_urls`] entry after `pushInsteadOf` / `insteadOf` (empty when there are no push URLs).
    pub effective_push_urls: Vec<String>,
}

fn configured_remote_from_config(config: &ConfigSet, name: String) -> ConfiguredRemote {
    let url = config.get(&format!("remote.{name}.url"));
    let mut fetch_refspecs = config.get_all(&format!("remote.{name}.fetch"));
    fetch_refspecs.retain(|s| !s.trim().is_empty());
    let push_urls: Vec<String> = config
        .get_all(&format!("remote.{name}.pushurl"))
        .into_iter()
        .filter(|s| !s.trim().is_empty())
        .collect();
    let effective_push_urls: Vec<String> = push_urls
        .iter()
        .map(|raw| url_rewrite::rewrite_push_url(config, raw.as_str()))
        .collect();
    let (effective_fetch_url, effective_push_url) = match url.as_deref().filter(|u| !u.is_empty()) {
        Some(raw) => {
            let effective_fetch_url = url_rewrite::rewrite_fetch_url(config, raw);
            let push_source = config
                .get(&format!("remote.{name}.pushurl"))
                .filter(|u| !u.trim().is_empty())
                .unwrap_or_else(|| raw.to_owned());
            let effective_push_url = url_rewrite::rewrite_push_url(config, push_source.as_str());
            (Some(effective_fetch_url), Some(effective_push_url))
        }
        None => {
            let effective_push_url = push_urls
                .first()
                .map(|raw| url_rewrite::rewrite_push_url(config, raw.as_str()));
            (None, effective_push_url)
        }
    };
    ConfiguredRemote {
        name,
        url,
        push_urls,
        fetch_refspecs,
        effective_fetch_url,
        effective_push_url,
        effective_push_urls,
    }
}

/// Every remote with at least one `remote.<name>.*` key, sorted by name.
///
/// This is the set Git treats as configured remotes (for listing and for refusing to
/// add a duplicate), which is wider than [`configured_remote_names`].
#[must_use]
pub fn configured_remotes(config: &ConfigSet) -> Vec<ConfiguredRemote> {
    let mut names = BTreeSet::new();
    for entry in config.entries() {
        let Some(rest) = entry.key.strip_prefix("remote.") else {
            continue;
        };
        if let Some((name, _key)) = rest.rsplit_once('.') {
            names.insert(name);
        }
    }
    names
        .into_iter()
        .map(|name| configured_remote_from_config(config, name.to_owned()))
        .collect()
}

/// Whether any `remote.<name>.*` key exists (membership in [`configured_remotes`]).
pub fn has_remote_section(config: &ConfigSet, name: &str) -> bool {
    config.entries().iter().any(|entry| {
        entry
            .key
            .strip_prefix("remote.")
            .and_then(|rest| rest.rsplit_once('.'))
            .is_some_and(|(section, _key)| section == name)
    })
}

/// Whether `name` can name a remote: its tracking refs `refs/remotes/<name>/…` must be valid.
fn is_valid_remote_name(name: &str) -> bool {
    !name.is_empty()
        && check_refname_format(
            &format!("refs/remotes/{name}/test"),
            &RefNameOptions::default(),
        )
        .is_ok()
}

/// Collect remote subsection names that declare a `url` key.
#[must_use]
pub fn configured_remote_names(config: &ConfigSet) -> Vec<String> {
    let mut names = BTreeSet::new();
    for entry in config.entries() {
        let Some(rest) = entry.key.strip_prefix("remote.") else {
            continue;
        };
        let Some((name, key)) = rest.rsplit_once('.') else {
            continue;
        };
        if key == "url" && !name.is_empty() {
            names.insert(name.to_owned());
        }
    }
    names.into_iter().collect()
}

#[cfg(test)]
mod tests {
    use super::{
        configured_remote_names, configured_remote_names_in_config_order, configured_remotes,
        has_remote_section, is_valid_remote_name, remote_skip_fetch_all, ConfiguredRemote,
    };
    use crate::config::{ConfigFile, ConfigScope, ConfigSet};
    use crate::remote::RemoteError;
    use crate::repo::{InitOptions, Repository};

    fn config_set(text: &str) -> ConfigSet {
        let file = ConfigFile::parse(std::path::Path::new("cfg"), text, ConfigScope::Local)
            .expect("parse");
        let mut set = ConfigSet::new();
        set.merge(&file);
        set
    }

    #[test]
    fn configured_remotes_include_sections_without_url() {
        let set = config_set(
            "[remote \"zeta\"]\n\turl = /tmp/z.git\n[remote \"team.prod\"]\n\tfetch = +refs/heads/*:refs/remotes/team.prod/*\n[remote \"zeta\"]\n\turl = /tmp/z2.git\n",
        );
        assert_eq!(
            configured_remotes(&set),
            vec![
                ConfiguredRemote {
                    name: "team.prod".to_owned(),
                    url: None,
                    push_urls: vec![],
                    fetch_refspecs: vec!["+refs/heads/*:refs/remotes/team.prod/*".to_owned()],
                    effective_fetch_url: None,
                    effective_push_url: None,
                    effective_push_urls: vec![],
                },
                ConfiguredRemote {
                    name: "zeta".to_owned(),
                    url: Some("/tmp/z2.git".to_owned()),
                    push_urls: vec![],
                    fetch_refspecs: vec![],
                    effective_fetch_url: Some("/tmp/z2.git".to_owned()),
                    effective_push_url: Some("/tmp/z2.git".to_owned()),
                    effective_push_urls: vec![],
                },
            ]
        );
        assert_eq!(configured_remote_names(&set), vec!["zeta".to_owned()]);
        assert!(has_remote_section(&set, "team.prod"));
        assert!(has_remote_section(&set, "zeta"));
        assert!(!has_remote_section(&set, "team"));
    }

    #[test]
    fn remote_name_validation_follows_tracking_ref_rules() {
        for ok in ["origin", "team.prod", "a/b", "up-stream"] {
            assert!(is_valid_remote_name(ok), "{ok}");
        }
        for bad in [
            "",
            ".",
            "..",
            "a..b",
            "has space",
            "x:y",
            "star*",
            "end.lock",
        ] {
            assert!(!is_valid_remote_name(bad), "{bad}");
        }
    }

    #[test]
    fn add_writes_url_and_default_fetch_refspec() {
        let dir = tempfile::tempdir().expect("tempdir");
        let repo = Repository::init(dir.path(), &InitOptions::default()).expect("init");
        repo.remotes()
            .add("upstream", "https://example.com/r.git")
            .expect("add");
        let config = repo.config().expect("config");
        assert_eq!(
            config.get("remote.upstream.url").as_deref(),
            Some("https://example.com/r.git")
        );
        assert_eq!(
            config.get_all("remote.upstream.fetch"),
            vec!["+refs/heads/*:refs/remotes/upstream/*".to_owned()]
        );
        assert_eq!(repo.remotes().list().expect("list"), vec!["upstream"]);
    }

    #[test]
    fn add_rejects_existing_and_invalid_names() {
        let dir = tempfile::tempdir().expect("tempdir");
        let repo = Repository::init(dir.path(), &InitOptions::default()).expect("init");
        repo.remotes().add("origin", "/tmp/a.git").expect("add");
        assert!(matches!(
            repo.remotes().add("origin", "/tmp/b.git"),
            Err(RemoteError::RemoteExists(name)) if name == "origin"
        ));
        assert!(matches!(
            repo.remotes().add("bad name", "/tmp/b.git"),
            Err(RemoteError::InvalidRemoteName(name)) if name == "bad name"
        ));
        assert_eq!(
            repo.config()
                .expect("config")
                .get("remote.origin.url")
                .as_deref(),
            Some("/tmp/a.git")
        );
    }

    #[test]
    fn configured_remote_names_in_config_order_preserves_file_order() {
        let file = ConfigFile::parse(
            std::path::Path::new("cfg"),
            r#"[remote "second"]
	url = /tmp/second.git
[remote "first"]
	url = /tmp/first.git
"#,
            ConfigScope::Local,
        )
        .expect("parse");
        let mut set = ConfigSet::new();
        set.merge(&file);
        assert_eq!(
            configured_remote_names_in_config_order(&set),
            vec!["second".to_owned(), "first".to_owned()]
        );
    }

    #[test]
    fn remote_skip_fetch_all_reads_config() {
        let file = ConfigFile::parse(
            std::path::Path::new("cfg"),
            r#"[remote "skipme"]
	url = /tmp/x.git
	skipFetchAll = true
"#,
            ConfigScope::Local,
        )
        .expect("parse");
        let mut set = ConfigSet::new();
        set.merge(&file);
        assert!(remote_skip_fetch_all(&set, "skipme"));
        assert!(!remote_skip_fetch_all(&set, "other"));
    }

    #[test]
    fn configured_remote_names_parses_dotted_subsections() {
        let file = ConfigFile::parse(
            std::path::Path::new("cfg"),
            r#"[remote "team.prod"]
	url = /tmp/upstream.git
[remote "origin"]
	url = /tmp/origin.git
"#,
            ConfigScope::Local,
        )
        .expect("parse");
        let mut set = ConfigSet::new();
        set.merge(&file);
        let names = configured_remote_names(&set);
        assert!(names.contains(&"team.prod".to_owned()));
        assert!(names.contains(&"origin".to_owned()));
    }
}