Add the RFC §8.6 explicit fetch refspecs for `remote` to the repository config, idempotently. Returns how many refspecs were newly added. A missing remote is a typed error: refspecs are only meaningful for a configured remote, and guessing one would hide a typo from the operator.
(git: &GitRepository, remote: &str)
| 67 | /// A missing remote is a typed error: refspecs are only meaningful for a |
| 68 | /// configured remote, and guessing one would hide a typo from the operator. |
| 69 | pub fn configure_fetch_refspecs(git: &GitRepository, remote: &str) -> CliResult<usize> { |
| 70 | // Fail closed when the remote does not exist. |
| 71 | git.find_remote(remote) |
| 72 | .map_err(|error| { |
| 73 | CliError::GitError { |
| 74 | message: format!( |
| 75 | "cannot configure Atomic fetch refspecs: remote '{remote}' does not exist ({error})" |
| 76 | ), |
| 77 | } |
| 78 | })?; |
| 79 | let mut config = git.config().map_err(|error| CliError::GitError { |
| 80 | message: format!("cannot read Git config: {error}"), |
| 81 | })?; |
| 82 | let existing: Vec<String> = config |
| 83 | .entries(Some(&format!("remote.{remote}.fetch"))) |
| 84 | .and_then(|mut entries| { |
| 85 | let mut out = Vec::new(); |
| 86 | while let Some(entry) = entries.next() { |
| 87 | let entry = entry?; |
| 88 | if let Ok(value) = entry.value() { |
| 89 | out.push(value.to_string()); |
| 90 | } |
| 91 | } |
| 92 | Ok(out) |
| 93 | }) |
| 94 | .map_err(|error| CliError::GitError { |
| 95 | message: format!("cannot read remote refspecs: {error}"), |
| 96 | })?; |
| 97 | let mut added = 0; |
| 98 | for refspec in [BINDING_REFSPEC, VIEWS_REFSPEC] { |
| 99 | if existing.iter().any(|line| line == refspec) { |
| 100 | continue; |
| 101 | } |
| 102 | // git2 has no add-multivar; append via a dedicated entries set is |
| 103 | // unsupported, so use the git CLI's --add, which is exactly the RFC |
| 104 | // §8.6 command and never rewrites existing values. |
| 105 | let status = Command::new("git") |
| 106 | .args([ |
| 107 | "config", |
| 108 | "--add", |
| 109 | &format!("remote.{remote}.fetch"), |
| 110 | refspec, |
| 111 | ]) |
| 112 | .current_dir(git.workdir().ok_or_else(|| CliError::GitError { |
| 113 | message: "Git repository has no working directory".to_string(), |
| 114 | })?) |
| 115 | .status() |
| 116 | .map_err(|error| CliError::GitError { |
| 117 | message: format!("cannot run git config: {error}"), |
| 118 | })?; |
| 119 | if !status.success() { |
| 120 | return Err(CliError::GitError { |
| 121 | message: format!("git config --add remote.{remote}.fetch {refspec} failed"), |
| 122 | }); |
| 123 | } |
| 124 | added += 1; |
| 125 | } |
| 126 | Ok(added) |