gitai/remote/cache/
fetcher.rs

1use crate::remote::models::repo_config::RepositoryConfiguration;
2
3use super::super::common::{ErrorType, Method};
4use cause::{Cause, cause};
5use git2::Repository;
6use std::process::Command;
7
8#[derive(Clone)]
9pub struct RepositoryFetcher;
10
11impl RepositoryFetcher {
12    /// Fetch a repository to a temporary directory
13    /// This is a wrapper around the existing fetch functionality with caching logic
14    pub async fn fetch_repository(
15        &self,
16        config: &RepositoryConfiguration,
17        cache_path: &str,
18    ) -> Result<(), Cause<ErrorType>> {
19        let config = config.clone();
20        let cache_path = cache_path.to_string();
21
22        // Check if the repository is already cached and up-to-date
23        if Self::is_cache_valid(&config, &cache_path) {
24            println!("Using cached repository: {}", config.url);
25            return Ok(());
26        }
27
28        println!("Fetching repository: {} to cache", config.url);
29
30        // Wrap blocking operations in spawn_blocking
31        let cache_path_clone = cache_path.clone();
32        tokio::task::spawn_blocking(move || {
33            Self::execute_git_clone(&config, &cache_path_clone)?;
34            if !matches!(config.mtd, Some(Method::ShallowNoSparse)) {
35                Self::execute_git_checkout(&cache_path_clone, &config.branch)?;
36            }
37            Ok(())
38        })
39        .await
40        .map_err(|e| cause!(ErrorType::GitCloneCommand).msg(format!("Task join error: {e:?}")))??;
41
42        println!("Repository fetched and cached at: {cache_path}");
43        Ok(())
44    }
45
46    /// Execute the git clone command with error handling
47    fn execute_git_clone(
48        config: &RepositoryConfiguration,
49        cache_path: &str,
50    ) -> Result<(), Cause<ErrorType>> {
51        // Remove the cache directory if it exists
52        if std::path::Path::new(cache_path).exists() {
53            std::fs::remove_dir_all(cache_path)
54                .map_err(|e| cause!(ErrorType::GitCloneCommand).src(e))?;
55        }
56
57        if matches!(config.mtd, Some(Method::ShallowNoSparse)) {
58            // Use git command for shallow clone with branch
59            let output = Command::new("git")
60                .args([
61                    "clone",
62                    "--depth",
63                    "1",
64                    "--branch",
65                    &config.branch,
66                    &config.url,
67                    cache_path,
68                ])
69                .output()
70                .map_err(|e| cause!(ErrorType::GitCloneCommand).src(e))?;
71            if !output.status.success() {
72                return Err(
73                    cause!(ErrorType::GitCloneCommand).msg(String::from_utf8_lossy(&output.stderr))
74                );
75            }
76        } else {
77            Repository::clone(&config.url, cache_path)
78                .map_err(|e| cause!(ErrorType::GitCloneCommand).src(e))?;
79        }
80
81        Ok(())
82    }
83
84    /// Execute the git checkout command with error handling
85    fn execute_git_checkout(cache_path: &str, rev: &str) -> Result<(), Cause<ErrorType>> {
86        let repo = Repository::open(cache_path)
87            .map_err(|e| cause!(ErrorType::GitCheckoutCommand).src(e))?;
88
89        let obj = repo
90            .revparse_single(rev)
91            .map_err(|e| cause!(ErrorType::GitCheckoutCommand).src(e))?
92            .peel(git2::ObjectType::Commit)
93            .map_err(|e| cause!(ErrorType::GitCheckoutCommand).src(e))?;
94
95        repo.checkout_tree(&obj, None)
96            .map_err(|e| cause!(ErrorType::GitCheckoutCommand).src(e))?;
97
98        repo.set_head_detached(obj.id())
99            .map_err(|e| cause!(ErrorType::GitCheckoutCommand).src(e))?;
100
101        Ok(())
102    }
103
104    /// Check if the cached repository is still valid (up-to-date)
105    fn is_cache_valid(_config: &RepositoryConfiguration, cache_path: &str) -> bool {
106        // Check if the directory exists
107        std::path::Path::new(cache_path).exists()
108    }
109}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114
115    #[test]
116    fn test_fetcher_creation() {
117        let _ = RepositoryFetcher;
118        // Just checking the struct can be instantiated
119    }
120
121    #[test]
122    fn test_is_cache_valid_with_nonexistent_path() {
123        let config = RepositoryConfiguration::new(
124            "https://github.com/example/repo.git".to_string(),
125            "main".to_string(),
126            "./src/module1".to_string(),
127            vec!["src/".to_string()],
128            None,
129            None,
130        );
131
132        // Test with a path that doesn't exist
133        let result = RepositoryFetcher::is_cache_valid(&config, "/definitely/does/not/exist");
134        // It should return false since the path doesn't exist
135        assert!(!result);
136    }
137}