Skip to main content

git_editor/utils/
git_clone.rs

1use crate::utils::types::Result;
2use colored::Colorize;
3use git2::build::RepoBuilder;
4use git2::{Cred, CredentialType, FetchOptions, RemoteCallbacks, Repository};
5use tempfile::TempDir;
6use url::Url;
7
8/// Checks if a string is a valid Git URL
9pub fn is_git_url(input: &str) -> bool {
10    // An existing local path is never a URL, even if it contains '@' and ':'.
11    if std::path::Path::new(input).exists() {
12        return false;
13    }
14    if let Ok(url) = Url::parse(input) {
15        matches!(url.scheme(), "http" | "https" | "git" | "ssh")
16    } else {
17        // Check for SSH format like git@github.com:user/repo.git
18        input.contains('@') && input.contains(':') && !input.contains(' ')
19    }
20}
21
22/// Normalizes a Git URL by removing .git suffix if present
23pub fn normalize_git_url(url: &str) -> String {
24    if url.ends_with(".git") {
25        url.trim_end_matches(".git").to_string()
26    } else {
27        url.to_string()
28    }
29}
30
31/// Hide credentials embedded in a URL (`https://user:token@host` → `https://user:***@host`).
32pub fn redact_url(input: &str) -> String {
33    let Ok(mut url) = Url::parse(input) else {
34        return input.to_string();
35    };
36    if url.password().is_some() {
37        let _ = url.set_password(Some("***"));
38    } else if !url.username().is_empty() && matches!(url.scheme(), "http" | "https") {
39        // A bare username on HTTP(S) is usually a token.
40        let _ = url.set_username("***");
41    } else {
42        return input.to_string();
43    }
44    url.to_string()
45}
46
47/// Clones a Git repository to a temporary directory (deleted on drop) and returns it.
48pub fn clone_repository(git_url: &str) -> Result<TempDir> {
49    let temp_dir =
50        TempDir::new().map_err(|e| format!("Failed to create temporary directory: {e}"))?;
51    clone_repository_to(git_url, temp_dir.path())?;
52    Ok(temp_dir)
53}
54
55/// Clones a Git repository into `dest`, which must not exist or be empty.
56pub fn clone_repository_to(git_url: &str, dest: &std::path::Path) -> Result<()> {
57    let shown = redact_url(git_url);
58    if dest.exists() && dest.read_dir()?.next().is_some() {
59        return Err(format!("Clone directory is not empty: {}", dest.display()).into());
60    }
61    crate::say!("{}", "🔄 Cloning repository...".cyan());
62    crate::say!("{} {}", "Repository:".bold(), shown.yellow());
63
64    clone_with_credentials(git_url, dest).map_err(|e| {
65        let detail = e.to_string().replace(git_url, &shown);
66        format!("Failed to clone repository '{shown}': {detail}")
67    })?;
68
69    crate::say!(
70        "{} {}",
71        "✓ Successfully cloned to:".green(),
72        dest.display().to_string().cyan()
73    );
74    Ok(())
75}
76
77/// Clone using the same credential sources as `git`: ssh-agent for SSH URLs
78/// and configured credential helpers for HTTP(S). Each source is tried once.
79fn clone_with_credentials(
80    url: &str,
81    path: &std::path::Path,
82) -> std::result::Result<Repository, git2::Error> {
83    let config = git2::Config::open_default().ok();
84    let mut tried_agent = false;
85    let mut tried_helper = false;
86    let mut tried_default = false;
87
88    let mut callbacks = RemoteCallbacks::new();
89    callbacks.credentials(move |url, username, allowed| {
90        if allowed.contains(CredentialType::USERNAME) {
91            return Cred::username(username.unwrap_or("git"));
92        }
93        if allowed.contains(CredentialType::SSH_KEY) && !tried_agent {
94            tried_agent = true;
95            return Cred::ssh_key_from_agent(username.unwrap_or("git"));
96        }
97        if allowed.contains(CredentialType::USER_PASS_PLAINTEXT) && !tried_helper {
98            tried_helper = true;
99            if let Some(config) = &config {
100                return Cred::credential_helper(config, url, username);
101            }
102        }
103        if allowed.contains(CredentialType::DEFAULT) && !tried_default {
104            tried_default = true;
105            return Cred::default();
106        }
107        Err(git2::Error::from_str(
108            "authentication failed: no usable credentials from ssh-agent or git credential helpers",
109        ))
110    });
111
112    let mut fetch = FetchOptions::new();
113    fetch.remote_callbacks(callbacks);
114    RepoBuilder::new().fetch_options(fetch).clone(url, path)
115}
116
117/// Gets repository name from Git URL for display purposes
118pub fn get_repo_name_from_url(git_url: &str) -> String {
119    let normalized = normalize_git_url(git_url);
120
121    if let Ok(url) = Url::parse(&normalized) {
122        // Extract from path like /user/repo
123        if let Some(segments) = url.path_segments() {
124            let segments: Vec<&str> = segments.collect();
125            if segments.len() >= 2 {
126                return format!(
127                    "{}/{}",
128                    segments[segments.len() - 2],
129                    segments[segments.len() - 1]
130                );
131            } else if segments.len() == 1 {
132                return segments[0].to_string();
133            }
134        }
135        return url.path().trim_start_matches('/').to_string();
136    }
137
138    // Handle SSH format like git@github.com:user/repo
139    if let Some(colon_pos) = normalized.rfind(':') {
140        let path_part = &normalized[colon_pos + 1..];
141        return path_part.to_string();
142    }
143
144    // Fallback: use the last part of the URL
145    normalized
146        .split('/')
147        .next_back()
148        .unwrap_or("repository")
149        .to_string()
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155
156    #[test]
157    fn test_is_git_url() {
158        assert!(is_git_url("https://github.com/user/repo"));
159        assert!(is_git_url("https://github.com/user/repo.git"));
160        assert!(is_git_url("http://gitlab.com/user/repo"));
161        assert!(is_git_url("git://github.com/user/repo.git"));
162        assert!(is_git_url("git@github.com:user/repo.git"));
163
164        assert!(!is_git_url("./local/path"));
165        assert!(!is_git_url("/absolute/path"));
166        assert!(!is_git_url("not-a-url"));
167        assert!(!is_git_url("file:///local/path"));
168    }
169
170    #[test]
171    #[cfg(unix)] // ':' is not allowed in Windows file names
172    fn test_existing_path_with_at_and_colon_is_local() {
173        let dir = tempfile::TempDir::new().unwrap();
174        let odd = dir.path().join("we@ird:dir");
175        std::fs::create_dir(&odd).unwrap();
176        assert!(!is_git_url(odd.to_str().unwrap()));
177    }
178
179    #[test]
180    fn test_redact_url_hides_credentials() {
181        assert_eq!(
182            redact_url("https://user:ghp_secret@github.com/o/r.git"),
183            "https://user:***@github.com/o/r.git"
184        );
185        assert_eq!(
186            redact_url("https://ghp_secret@github.com/o/r.git"),
187            "https://***@github.com/o/r.git"
188        );
189        assert_eq!(
190            redact_url("https://github.com/o/r.git"),
191            "https://github.com/o/r.git"
192        );
193        assert_eq!(
194            redact_url("git@github.com:o/r.git"),
195            "git@github.com:o/r.git"
196        );
197        assert_eq!(redact_url("ssh://git@host/r.git"), "ssh://git@host/r.git");
198    }
199
200    #[test]
201    fn test_clone_error_does_not_leak_token() {
202        let err = clone_repository("https://u:ghp_TOPSECRET@127.0.0.1:9/o/r.git")
203            .unwrap_err()
204            .to_string();
205        assert!(!err.contains("TOPSECRET"), "{err}");
206    }
207
208    #[test]
209    fn test_normalize_git_url() {
210        assert_eq!(
211            normalize_git_url("https://github.com/user/repo.git"),
212            "https://github.com/user/repo"
213        );
214        assert_eq!(
215            normalize_git_url("https://github.com/user/repo"),
216            "https://github.com/user/repo"
217        );
218        assert_eq!(
219            normalize_git_url("git@github.com:user/repo.git"),
220            "git@github.com:user/repo"
221        );
222    }
223
224    #[test]
225    fn test_get_repo_name_from_url() {
226        assert_eq!(
227            get_repo_name_from_url("https://github.com/rohansen856/git-editor.git"),
228            "rohansen856/git-editor"
229        );
230        assert_eq!(
231            get_repo_name_from_url("https://github.com/user/repo"),
232            "user/repo"
233        );
234        assert_eq!(
235            get_repo_name_from_url("git@github.com:user/repo.git"),
236            "user/repo"
237        );
238        assert_eq!(
239            get_repo_name_from_url("https://gitlab.com/namespace/project"),
240            "namespace/project"
241        );
242    }
243}