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("invalid remote url: {0}")]
34    InvalidUrl(String),
35}
36
37pub type Result<T> = std::result::Result<T, RemoteError>;
38
39#[derive(Debug, Clone, Serialize, Deserialize)]
40pub struct Remote {
41    pub url: String,
42}
43
44#[derive(Debug, Default, Serialize, Deserialize)]
45pub struct RemotesFile {
46    #[serde(default)]
47    pub default: Option<String>,
48    #[serde(default)]
49    pub remotes: HashMap<String, Remote>,
50}
51
52impl RemotesFile {
53    pub fn load(path: &Path) -> Result<Self> {
54        match fs::read_to_string(path) {
55            Ok(contents) => Ok(toml::from_str(&contents)?),
56            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
57            Err(err) => Err(err.into()),
58        }
59    }
60
61    pub fn save(&self, path: &Path) -> Result<()> {
62        if let Some(parent) = path.parent() {
63            fs::create_dir_all(parent)?;
64        }
65        let contents = toml::to_string_pretty(self)?;
66        write_file_atomic(path, contents.as_bytes())?;
67        Ok(())
68    }
69}
70
71pub struct RemoteConfig {
72    path: PathBuf,
73    file: RemotesFile,
74}
75
76impl RemoteConfig {
77    pub fn open(repo: &Repository) -> Result<Self> {
78        let path = repo.heddle_dir().join("remotes.toml");
79        let file = RemotesFile::load(&path)?;
80        Ok(Self { path, file })
81    }
82
83    pub fn list(&self) -> Vec<(String, Remote)> {
84        let mut items: Vec<_> = self
85            .file
86            .remotes
87            .iter()
88            .map(|(name, remote)| (name.clone(), remote.clone()))
89            .collect();
90        items.sort_by(|a, b| a.0.cmp(&b.0));
91        items
92    }
93
94    pub fn get(&self, name: &str) -> Result<Remote> {
95        self.file
96            .remotes
97            .get(name)
98            .cloned()
99            .ok_or_else(|| RemoteError::NotFound(name.to_string()))
100    }
101
102    pub fn add(&mut self, name: &str, remote: Remote) -> Result<()> {
103        if self.file.default.is_none() {
104            self.file.default = Some(name.to_string());
105        }
106        self.file.remotes.insert(name.to_string(), remote);
107        self.file.save(&self.path)?;
108        Ok(())
109    }
110
111    pub fn remove(&mut self, name: &str) -> Result<()> {
112        if self.file.remotes.remove(name).is_none() {
113            return Err(RemoteError::NotFound(name.to_string()));
114        }
115        if self.file.default.as_deref() == Some(name) {
116            self.file.default = None;
117        }
118        self.file.save(&self.path)?;
119        Ok(())
120    }
121
122    pub fn default_name(&self) -> Option<&str> {
123        self.file.default.as_deref()
124    }
125}
126
127/// Resolve a remote argument (name or URL) into a concrete target.
128pub fn resolve_remote(repo: &Repository, remote_arg: Option<&str>) -> Result<RemoteTarget> {
129    Ok(resolve_remote_with_key(repo, remote_arg)?.0)
130}
131
132/// Resolve a remote argument (name or URL) into a concrete target, also
133/// returning the raw URL string that can be used as a credential store key.
134pub fn resolve_remote_with_key(
135    repo: &Repository,
136    remote_arg: Option<&str>,
137) -> Result<(RemoteTarget, Option<String>)> {
138    let cfg = RemoteConfig::open(repo)?;
139
140    let spec = match remote_arg {
141        Some(spec) => spec.to_string(),
142        None => cfg
143            .default_name()
144            .ok_or_else(|| RemoteError::NotFound("(no default remote configured)".to_string()))?
145            .to_string(),
146    };
147
148    if let Ok(target) = RemoteTarget::parse(&spec) {
149        let key = credential_key_from_url(&spec);
150        return Ok((target, key));
151    }
152
153    let remote = cfg.get(&spec)?;
154    if let Ok(target) = RemoteTarget::parse(&remote.url) {
155        let key = credential_key_from_url(&remote.url);
156        return Ok((target, key));
157    }
158
159    Err(RemoteError::InvalidUrl(remote.url))
160}
161
162/// Extract the hostname (credential store key) from a remote URL string.
163///
164/// Returns `None` for local paths (file:// or bare paths).
165pub fn credential_key_from_remote_url(url: &str) -> Option<String> {
166    credential_key_from_url(url)
167}
168
169/// Internal implementation of credential key extraction.
170fn credential_key_from_url(url: &str) -> Option<String> {
171    // Strip known scheme prefixes.
172    let rest = url
173        .strip_prefix("heddle://")
174        .or_else(|| url.strip_prefix("https://"))
175        .or_else(|| url.strip_prefix("http://"))
176        .unwrap_or(url);
177
178    // Skip local paths.
179    if rest.starts_with('/') || url.starts_with("file://") {
180        return None;
181    }
182
183    // The credential key is the host part (before the first '/').
184    let host_part = rest.split('/').next().unwrap_or(rest);
185    if host_part.is_empty() {
186        return None;
187    }
188    Some(host_part.to_string())
189}
190
191#[cfg(test)]
192mod tests {
193    use std::{
194        fs,
195        path::PathBuf,
196        time::{SystemTime, UNIX_EPOCH},
197    };
198
199    use repo::Repository;
200
201    use super::*;
202
203    fn unique_temp_dir(prefix: &str) -> PathBuf {
204        let unique = SystemTime::now()
205            .duration_since(UNIX_EPOCH)
206            .expect("system time before unix epoch")
207            .as_nanos();
208        std::env::temp_dir().join(format!("{prefix}-{unique}-{}", std::process::id()))
209    }
210
211    #[test]
212    fn remote_config_save_uses_atomic_write_and_persists() {
213        // Mutex serializes env-var access across this crate's tests so
214        // parallel runs don't observe each other's writes.
215        static TEST_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
216        let _guard = TEST_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
217        let temp = unique_temp_dir("heddle-remote-test");
218        fs::create_dir_all(&temp).expect("create temp dir");
219        let repo = Repository::init_default(&temp).expect("init repo");
220
221        {
222            let mut cfg = RemoteConfig::open(&repo).expect("open config");
223            cfg.add(
224                "origin",
225                Remote {
226                    url: "http://heddle.example:8421/repo".to_string(),
227                },
228            )
229            .expect("add remote");
230        }
231
232        let path = repo.heddle_dir().join("remotes.toml");
233        assert!(path.exists(), "expected remotes file to exist");
234
235        let contents = fs::read_to_string(&path).expect("read remotes file");
236        assert!(contents.contains("origin"));
237        assert!(contents.contains("heddle.example:8421"));
238
239        let reopened = RemoteConfig::open(&repo).expect("reopen config");
240        let remote = reopened.get("origin").expect("load remote");
241        assert_eq!(remote.url, "http://heddle.example:8421/repo");
242
243        let _ = fs::remove_dir_all(temp);
244    }
245}