Skip to main content

cli_shared/remote/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Remote configuration management.
3//!
4//! Remote aliases remain repository-scoped and live in `.heddle/remotes.toml`.
5
6mod target;
7
8use std::{
9    collections::HashMap,
10    fs,
11    path::{Path, PathBuf},
12};
13
14use objects::fs_atomic::write_file_atomic;
15use repo::Repository;
16use serde::{Deserialize, Serialize};
17pub use target::RemoteTarget;
18
19#[derive(Debug, thiserror::Error)]
20pub enum RemoteError {
21    #[error("io error: {0}")]
22    Io(#[from] std::io::Error),
23
24    #[error("toml error: {0}")]
25    Toml(#[from] toml::de::Error),
26
27    #[error("toml serialize error: {0}")]
28    TomlSerialize(#[from] toml::ser::Error),
29
30    #[error("remote not found: {0}")]
31    NotFound(String),
32
33    #[error("no default remote configured")]
34    NoDefaultRemote,
35
36    #[error("invalid remote url: {0}")]
37    InvalidUrl(String),
38}
39
40pub type Result<T> = std::result::Result<T, RemoteError>;
41
42#[derive(Debug, Clone, Serialize, Deserialize)]
43pub struct Remote {
44    pub url: String,
45    /// Explicitly allow cleartext (non-TLS) connections to non-loopback hosts
46    /// for this remote. Equivalent to CLI `--insecure` for push/pull/clone.
47    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
48    pub insecure: bool,
49}
50
51#[derive(Debug, Default, Serialize, Deserialize)]
52pub struct RemotesFile {
53    #[serde(default)]
54    pub default: Option<String>,
55    #[serde(default)]
56    pub remotes: HashMap<String, Remote>,
57}
58
59impl RemotesFile {
60    pub fn load(path: &Path) -> Result<Self> {
61        match fs::read_to_string(path) {
62            Ok(contents) => Ok(toml::from_str(&contents)?),
63            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
64            Err(err) => Err(err.into()),
65        }
66    }
67
68    pub fn save(&self, path: &Path) -> Result<()> {
69        if let Some(parent) = path.parent() {
70            fs::create_dir_all(parent)?;
71        }
72        let contents = toml::to_string_pretty(self)?;
73        write_file_atomic(path, contents.as_bytes())?;
74        Ok(())
75    }
76}
77
78pub struct RemoteConfig {
79    path: PathBuf,
80    file: RemotesFile,
81}
82
83impl RemoteConfig {
84    pub fn open(repo: &Repository) -> Result<Self> {
85        let path = repo.heddle_dir().join("remotes.toml");
86        let file = RemotesFile::load(&path)?;
87        Ok(Self { path, file })
88    }
89
90    pub fn list(&self) -> Vec<(String, Remote)> {
91        let mut items: Vec<_> = self
92            .file
93            .remotes
94            .iter()
95            .map(|(name, remote)| (name.clone(), remote.clone()))
96            .collect();
97        items.sort_by(|a, b| a.0.cmp(&b.0));
98        items
99    }
100
101    pub fn get(&self, name: &str) -> Result<Remote> {
102        self.file
103            .remotes
104            .get(name)
105            .cloned()
106            .ok_or_else(|| RemoteError::NotFound(name.to_string()))
107    }
108
109    pub fn add(&mut self, name: &str, remote: Remote) -> Result<()> {
110        if self.file.default.is_none() {
111            self.file.default = Some(name.to_string());
112        }
113        self.file.remotes.insert(name.to_string(), remote);
114        self.file.save(&self.path)?;
115        Ok(())
116    }
117
118    pub fn remove(&mut self, name: &str) -> Result<()> {
119        if self.file.remotes.remove(name).is_none() {
120            return Err(RemoteError::NotFound(name.to_string()));
121        }
122        if self.file.default.as_deref() == Some(name) {
123            self.file.default = None;
124        }
125        self.file.save(&self.path)?;
126        Ok(())
127    }
128
129    pub fn clear_default(&mut self) -> Result<()> {
130        self.file.default = None;
131        self.file.save(&self.path)?;
132        Ok(())
133    }
134
135    pub fn set_default(&mut self, name: &str) -> Result<()> {
136        if !self.file.remotes.contains_key(name) {
137            return Err(RemoteError::NotFound(name.to_string()));
138        }
139        self.file.default = Some(name.to_string());
140        self.file.save(&self.path)?;
141        Ok(())
142    }
143
144    pub fn default_name(&self) -> Option<&str> {
145        self.file.default.as_deref()
146    }
147}
148
149/// Resolve a remote argument (name or URL) into a concrete target.
150pub fn resolve_remote(repo: &Repository, remote_arg: Option<&str>) -> Result<RemoteTarget> {
151    Ok(resolve_remote_with_key(repo, remote_arg)?.0)
152}
153
154/// Resolve a remote argument (name or URL) into a concrete target, also
155/// returning the raw URL string that can be used as a credential store key.
156pub fn resolve_remote_with_key(
157    repo: &Repository,
158    remote_arg: Option<&str>,
159) -> Result<(RemoteTarget, Option<String>)> {
160    let (target, key, _insecure) = resolve_remote_with_key_and_insecure(repo, remote_arg)?;
161    Ok((target, key))
162}
163
164/// Resolve a remote argument into target, credential key, and the remote's
165/// configured `insecure` flag (false for ad-hoc URL specs).
166pub fn resolve_remote_with_key_and_insecure(
167    repo: &Repository,
168    remote_arg: Option<&str>,
169) -> Result<(RemoteTarget, Option<String>, bool)> {
170    let cfg = RemoteConfig::open(repo)?;
171
172    let spec = match remote_arg {
173        Some(spec) => spec.to_string(),
174        None => cfg
175            .default_name()
176            .ok_or(RemoteError::NoDefaultRemote)?
177            .to_string(),
178    };
179
180    // Named remote first so configured `insecure` applies even when the
181    // name also happens to parse as a bare host:port.
182    if let Ok(remote) = cfg.get(&spec)
183        && let Ok(target) = RemoteTarget::parse(&remote.url)
184    {
185        let key = credential_key_from_url(&remote.url);
186        return Ok((target, key, remote.insecure));
187    }
188
189    if let Ok(target) = RemoteTarget::parse(&spec) {
190        let key = credential_key_from_url(&spec);
191        return Ok((target, key, false));
192    }
193
194    let remote = cfg.get(&spec)?;
195    if let Ok(target) = RemoteTarget::parse(&remote.url) {
196        let key = credential_key_from_url(&remote.url);
197        return Ok((target, key, remote.insecure));
198    }
199
200    Err(RemoteError::InvalidUrl(remote.url))
201}
202
203/// Whether a named remote (or the default) has `insecure = true` in
204/// `.heddle/remotes.toml`. Returns false for URL specs / missing remotes.
205pub fn remote_allows_insecure(repo: &Repository, remote_arg: Option<&str>) -> bool {
206    resolve_remote_with_key_and_insecure(repo, remote_arg)
207        .map(|(_, _, insecure)| insecure)
208        .unwrap_or(false)
209}
210
211/// Extract the hostname (credential store key) from a remote URL string.
212///
213/// Returns `None` for local paths (file:// or bare paths).
214pub fn credential_key_from_remote_url(url: &str) -> Option<String> {
215    credential_key_from_url(url)
216}
217
218/// Internal implementation of credential key extraction.
219fn credential_key_from_url(url: &str) -> Option<String> {
220    // Strip known scheme prefixes.
221    let rest = url
222        .strip_prefix("heddle://")
223        .or_else(|| url.strip_prefix("https://"))
224        .or_else(|| url.strip_prefix("http://"))
225        .unwrap_or(url);
226
227    // Skip local paths.
228    if rest.starts_with('/') || url.starts_with("file://") {
229        return None;
230    }
231
232    // The credential key is the host part (before the first '/').
233    let host_part = rest.split('/').next().unwrap_or(rest);
234    if host_part.is_empty() {
235        return None;
236    }
237    Some(host_part.to_string())
238}
239
240#[cfg(test)]
241mod tests {
242    use std::{
243        fs,
244        path::PathBuf,
245        time::{SystemTime, UNIX_EPOCH},
246    };
247
248    use repo::Repository;
249
250    use super::*;
251
252    fn unique_temp_dir(prefix: &str) -> PathBuf {
253        let unique = SystemTime::now()
254            .duration_since(UNIX_EPOCH)
255            .expect("system time before unix epoch")
256            .as_nanos();
257        std::env::temp_dir().join(format!("{prefix}-{unique}-{}", std::process::id()))
258    }
259
260    #[test]
261    fn remote_config_save_uses_atomic_write_and_persists() {
262        // Mutex serializes env-var access across this crate's tests so
263        // parallel runs don't observe each other's writes.
264        static TEST_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
265        let _guard = TEST_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
266        let temp = unique_temp_dir("heddle-remote-test");
267        fs::create_dir_all(&temp).expect("create temp dir");
268        let repo = Repository::init_default(&temp).expect("init repo");
269
270        {
271            let mut cfg = RemoteConfig::open(&repo).expect("open config");
272            cfg.add(
273                "origin",
274                Remote {
275                    url: "http://heddle.example:8421/repo".to_string(),
276                    insecure: false,
277                },
278            )
279            .expect("add remote");
280        }
281
282        let path = repo.heddle_dir().join("remotes.toml");
283        assert!(path.exists(), "expected remotes file to exist");
284
285        let contents = fs::read_to_string(&path).expect("read remotes file");
286        assert!(contents.contains("origin"));
287        assert!(contents.contains("heddle.example:8421"));
288
289        let reopened = RemoteConfig::open(&repo).expect("reopen config");
290        let remote = reopened.get("origin").expect("load remote");
291        assert_eq!(remote.url, "http://heddle.example:8421/repo");
292
293        let _ = fs::remove_dir_all(temp);
294    }
295}