Skip to main content

hyprstream_p2p/git/
repository.rs

1//! Repository abstraction layer using libgit2
2//!
3//! This module provides the core Git operations using libgit2 instead of shell commands.
4//! Uses the Repository pattern to encapsulate Git operations with clean separation.
5
6use crate::{
7    types::{GitHash, Sha256Hash},
8    Result,
9};
10use git2::{Oid, Repository as Git2Repository};
11use std::path::Path;
12
13/// Wrapper around git2::Repository providing essential GitTorrent operations
14/// This follows the Newtype pattern for zero-cost abstraction
15pub struct Repository {
16    inner: Git2Repository,
17}
18
19impl Repository {
20    /// Open an existing repository
21    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
22        let inner = Git2Repository::open(path)?;
23        Ok(Repository { inner })
24    }
25
26    /// Check if repository is bare
27    pub fn is_bare(&self) -> bool {
28        self.inner.is_bare()
29    }
30
31    /// Get the repository path
32    pub fn path(&self) -> &Path {
33        self.inner.path()
34    }
35
36    /// Check if object exists in repository
37    pub fn has_object(&self, hash: &GitHash) -> Result<bool> {
38        let oid = Oid::from_str(&hash.to_hex())?;
39        Ok(self.inner.odb()?.exists(oid))
40    }
41
42    /// Get references for the repository
43    pub fn references(&self) -> Result<Vec<crate::types::GitRef>> {
44        let mut refs = Vec::new();
45
46        for reference in self.inner.references()? {
47            let reference = reference?;
48            if let Some(name) = reference.name() {
49                if let Some(target) = reference.target() {
50                    refs.push(crate::types::GitRef {
51                        name: name.to_owned(),
52                        hash: GitHash::from_hex(&target.to_string())?,
53                    });
54                }
55            }
56        }
57
58        Ok(refs)
59    }
60
61    /// Create a pack file for objects between 'have' and 'want' commits
62    /// This is the core operation for BitTorrent sharing
63    pub fn create_pack(&self, want: &Sha256Hash, have: Option<&Sha256Hash>) -> Result<Vec<u8>> {
64        let want_oid = Oid::from_str(want.as_str())?;
65
66        // Create object database pack builder
67        let mut builder = self.inner.packbuilder()?;
68
69        // Walk from want to have (or root)
70        let mut revwalk = self.inner.revwalk()?;
71        revwalk.push(want_oid)?;
72
73        if let Some(have_sha256) = have {
74            let have_oid = Oid::from_str(have_sha256.as_str())?;
75            revwalk.hide(have_oid)?;
76        }
77
78        // Collect all objects to pack
79        for oid in revwalk {
80            let oid = oid?;
81            builder.insert_object(oid, None)?;
82
83            // Also include tree and blob objects
84            if let Ok(commit) = self.inner.find_commit(oid) {
85                builder.insert_tree(commit.tree_id())?;
86            }
87        }
88
89        // Write pack to memory
90        let mut pack_data = Vec::new();
91        builder.foreach(|chunk| {
92            pack_data.extend_from_slice(chunk);
93            true
94        })?;
95
96        Ok(pack_data)
97    }
98
99    /// Unpack received pack data into the repository
100    pub fn unpack(&self, pack_data: &[u8]) -> Result<()> {
101        // Write pack data to a temporary file
102        let temp_dir = tempfile::tempdir()?;
103        let pack_path = temp_dir.path().join("pack.pack");
104        std::fs::write(&pack_path, pack_data)?;
105
106        // Use git2 to unpack the file directly into the repository
107        // This is the simplest approach that works with git2 0.18
108        let pack_dir = self.inner.path().join("objects/pack");
109        std::fs::create_dir_all(&pack_dir)?;
110
111        // Create a unique pack name based on content hash
112        let hash = crate::crypto::hash::sha256(pack_data);
113        let pack_name = format!("pack-{}.pack", hex::encode(&hash[..20]));
114
115        // Move the pack file to the repository
116        let final_pack_path = pack_dir.join(&pack_name);
117        std::fs::copy(&pack_path, &final_pack_path)?;
118
119        // Let git2 handle the indexing when the pack is accessed
120        // The repository will automatically index the pack when needed
121
122        Ok(())
123    }
124
125    /// Get commit information
126    pub fn find_commit(&self, sha256: &Sha256Hash) -> Result<CommitInfo> {
127        let oid = Oid::from_str(sha256.as_str())?;
128        let commit = self.inner.find_commit(oid)?;
129
130        Ok(CommitInfo {
131            sha256: sha256.clone(),
132            tree_sha256: Sha256Hash::new(commit.tree_id().to_string())?,
133            parent_sha256s: commit
134                .parent_ids()
135                .map(|oid| Sha256Hash::new(oid.to_string()))
136                .collect::<Result<Vec<_>>>()?,
137            message: commit.message().unwrap_or("").to_owned(),
138        })
139    }
140}
141
142/// Commit information
143#[derive(Debug, Clone)]
144pub struct CommitInfo {
145    pub sha256: Sha256Hash,
146    pub tree_sha256: Sha256Hash,
147    pub parent_sha256s: Vec<Sha256Hash>,
148    pub message: String,
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154    use tempfile::TempDir;
155
156    #[test]
157    fn test_repository_operations() -> Result<()> {
158        let temp_dir = TempDir::new()?;
159        let repo_path = temp_dir.path();
160
161        // Initialize a new repository
162        let git_repo = Git2Repository::init(repo_path)?;
163
164        // Create initial commit
165        let sig = git2::Signature::now("Test", "test@example.com")?;
166        let tree_id = {
167            let mut index = git_repo.index()?;
168            index.write_tree()?
169        };
170        let tree = git_repo.find_tree(tree_id)?;
171
172        let commit_id = git_repo.commit(Some("HEAD"), &sig, &sig, "Initial commit", &tree, &[])?;
173
174        // Test our Repository wrapper
175        let repo = Repository::open(repo_path)?;
176
177        // Use GitHash which supports SHA1 (40-char) from git2
178        let hash = GitHash::from_hex(&commit_id.to_string())?;
179        assert!(repo.has_object(&hash)?);
180
181        let refs = repo.references()?;
182        assert!(!refs.is_empty());
183
184        Ok(())
185    }
186}