Skip to main content

hyprstream_p2p/git/
remote.rs

1//! Git remote operations for GitTorrent
2
3use crate::{
4    types::{GitHash, GitRef},
5    Result,
6};
7use git2::Repository;
8use std::collections::HashMap;
9use tokio::process::Command;
10
11/// List references from a remote Git repository
12/// This is equivalent to `git ls-remote <url>`
13pub async fn ls_remote(url: &str) -> Result<Vec<GitRef>> {
14    let output = Command::new("git")
15        .args(["ls-remote", url])
16        .output()
17        .await?;
18
19    if !output.status.success() {
20        let stderr = String::from_utf8_lossy(&output.stderr);
21        return Err(crate::Error::other(format!(
22            "git ls-remote failed: {stderr}"
23        )));
24    }
25
26    let stdout = String::from_utf8(output.stdout)?;
27    parse_ls_remote_output(&stdout)
28}
29
30/// Parse the output of `git ls-remote`
31fn parse_ls_remote_output(output: &str) -> Result<Vec<GitRef>> {
32    let mut refs = Vec::new();
33
34    for line in output.lines() {
35        if line.trim().is_empty() {
36            continue;
37        }
38
39        let parts: Vec<&str> = line.split_whitespace().collect();
40        if parts.len() >= 2 {
41            let hash = GitHash::from_hex(parts[0])?;
42            let name = parts[1].to_owned();
43
44            refs.push(GitRef { name, hash });
45        }
46    }
47
48    Ok(refs)
49}
50
51/// List references from a local repository
52pub fn list_local_refs(repo_path: &str) -> Result<Vec<GitRef>> {
53    let repo = Repository::open(repo_path)?;
54    let mut refs = Vec::new();
55
56    for reference in repo.references()? {
57        let reference = reference?;
58
59        if let Some(name) = reference.name() {
60            if let Some(target) = reference.target() {
61                let hash = GitHash::from_hex(&target.to_string())?;
62                refs.push(GitRef {
63                    name: name.to_owned(),
64                    hash,
65                });
66            }
67        }
68    }
69
70    Ok(refs)
71}
72
73/// Convert references to a map for easier lookup
74pub fn refs_to_map(refs: Vec<GitRef>) -> HashMap<String, GitHash> {
75    refs.into_iter()
76        .map(|git_ref| (git_ref.name, git_ref.hash))
77        .collect()
78}
79
80#[cfg(test)]
81mod tests {
82    use super::*;
83
84    #[test]
85    fn test_parse_ls_remote_output() -> crate::error::Result<()> {
86        // Test with SHA1 hashes (40 hex chars) - current git format
87        let output = r#"
880123456789abcdef0123456789abcdef01234567	HEAD
890123456789abcdef0123456789abcdef01234567	refs/heads/main
901123456789abcdef0123456789abcdef01234567	refs/heads/develop
912123456789abcdef0123456789abcdef01234567	refs/tags/v1.0.0
92"#;
93
94        let refs = parse_ls_remote_output(output.trim())?;
95        assert_eq!(refs.len(), 4);
96
97        assert_eq!(refs[0].name, "HEAD");
98        assert_eq!(
99            refs[0].hash.to_hex(),
100            "0123456789abcdef0123456789abcdef01234567"
101        );
102        assert!(refs[0].hash.is_sha1());
103
104        assert_eq!(refs[1].name, "refs/heads/main");
105        assert_eq!(
106            refs[1].hash.to_hex(),
107            "0123456789abcdef0123456789abcdef01234567"
108        );
109
110        assert_eq!(refs[2].name, "refs/heads/develop");
111        assert_eq!(
112            refs[2].hash.to_hex(),
113            "1123456789abcdef0123456789abcdef01234567"
114        );
115
116        assert_eq!(refs[3].name, "refs/tags/v1.0.0");
117        assert_eq!(
118            refs[3].hash.to_hex(),
119            "2123456789abcdef0123456789abcdef01234567"
120        );
121        Ok(())
122    }
123
124    #[test]
125    fn test_refs_to_map() -> crate::error::Result<()> {
126        let refs = vec![
127            GitRef {
128                name: "refs/heads/main".to_owned(),
129                hash: GitHash::from_hex("0123456789abcdef0123456789abcdef01234567")?,
130            },
131            GitRef {
132                name: "refs/heads/develop".to_owned(),
133                hash: GitHash::from_hex("1123456789abcdef0123456789abcdef01234567")?,
134            },
135        ];
136
137        let map = refs_to_map(refs);
138        assert_eq!(map.len(), 2);
139        assert!(map.contains_key("refs/heads/main"));
140        assert!(map.contains_key("refs/heads/develop"));
141        Ok(())
142    }
143}