gitai/remote/
sync.rs

1use std::env;
2use std::fs;
3use std::path::Path;
4
5use cause::{Cause, cause};
6use fs_extra::{copy_items, dir::CopyOptions, remove_items};
7use futures::future::join_all;
8use log::{debug, info};
9
10use super::cache::{
11    fetcher::RepositoryFetcher, key_generator::CacheKeyGenerator, manager::CacheManager,
12};
13use super::common::{ErrorType, Target, parse};
14use super::models::repo_config::RepositoryConfiguration;
15
16fn get_repo_configs(
17    target: &Target,
18) -> Result<(String, Vec<RepositoryConfiguration>), Cause<ErrorType>> {
19    match target {
20        Target::Declared(opt_name) => {
21            let (root, mut parsed_items) = parse::parse_gitwire()?;
22            if let Some(name) = opt_name {
23                parsed_items.retain(|p| p.name.as_ref() == Some(name));
24                if parsed_items.is_empty() {
25                    return Err(cause!(
26                        ErrorType::NoItemToOperate,
27                        "No item with specified name"
28                    ));
29                }
30            }
31            let repo_configs = parsed_items
32                .into_iter()
33                .map(|parsed| {
34                    RepositoryConfiguration::new(
35                        parsed.url,
36                        parsed.rev,
37                        parsed.dst,
38                        vec![parsed.src],
39                        None,
40                        parsed.mtd,
41                    )
42                })
43                .collect();
44            Ok((root, repo_configs))
45        }
46        Target::Direct(parsed) => {
47            let root = env::current_dir()
48                .or(Err(cause!(ErrorType::CurrentDirRetrieve)))?
49                .to_string_lossy()
50                .to_string();
51            let repo_configs = vec![RepositoryConfiguration::new(
52                parsed.url.clone(),
53                parsed.rev.clone(),
54                parsed.dst.clone(),
55                vec![parsed.src.clone()],
56                None,
57                parsed.mtd.clone(),
58            )];
59            Ok((root, repo_configs))
60        }
61    }
62}
63
64// Enhanced sync functionality that integrates caching
65pub async fn sync_with_caching(
66    target: &Target,
67    _mode: super::common::sequence::Mode,
68) -> Result<bool, Cause<ErrorType>> {
69    info!("git-wire sync with caching started");
70
71    let (root_dir, repo_configs) = get_repo_configs(target)?;
72
73    info!("Found {} repository configurations", repo_configs.len());
74
75    // Create components needed for caching
76    let cache_manager = CacheManager::new();
77    let fetcher = RepositoryFetcher;
78
79    // Plan fetch operations to identify unique repositories
80    let (unique_configs, mut wire_operations) = cache_manager
81        .plan_fetch_operations(&repo_configs)
82        .map_err(|e| cause!(ErrorType::NoItemToOperate).msg(e))?;
83
84    info!(
85        "Identified {} unique repositories to fetch ({} redundant fetches avoided)",
86        unique_configs.len(),
87        repo_configs.len().saturating_sub(unique_configs.len())
88    );
89
90    // Fetch each unique repository to its cache location in parallel
91    let fetch_futures = unique_configs
92        .iter()
93        .map(|config| {
94            let config = config.clone();
95            let fetcher = fetcher.clone();
96            async move {
97                let cache_key = CacheKeyGenerator::generate_key(&config);
98                let cache_dir = env::temp_dir().join("git-wire-cache").join(cache_key);
99                fs::create_dir_all(&cache_dir)
100                    .map_err(|e| cause!(ErrorType::TempDirCreation).src(e))?;
101                let cache_path = cache_dir.to_string_lossy().to_string();
102
103                debug!(
104                    "Fetching repository {} to cache path {}",
105                    config.url, cache_path
106                );
107
108                fetcher.fetch_repository(&config, &cache_path).await?;
109                debug!("Repository {} successfully cached", config.url);
110                Ok((config, cache_path))
111            }
112        })
113        .collect::<Vec<_>>();
114
115    let fetch_results = join_all(fetch_futures).await;
116
117    // Collect successful fetches and update wire operations
118    for result in fetch_results {
119        let (config, cache_path) = result?;
120        for op in &mut wire_operations {
121            if op.source_config.url == config.url && op.source_config.branch == config.branch {
122                op.cached_repo_path.clone_from(&cache_path);
123            }
124        }
125    }
126
127    // Execute wire operations using cached repositories
128    for wire_op in &wire_operations {
129        if wire_op.source_config.filters.is_empty() {
130            debug!(
131                "Skipping wire operation with no filters: {}",
132                wire_op.operation_id
133            );
134            continue;
135        }
136
137        let source_subdir = &wire_op.source_config.filters[0];
138        let source_content = Path::new(&wire_op.cached_repo_path).join(source_subdir);
139        if !source_content.exists() {
140            info!(
141                "Source path {} does not exist in cached repo {}",
142                source_subdir, wire_op.source_config.url
143            );
144            continue;
145        }
146
147        let dest_dir = Path::new(&root_dir).join(&wire_op.source_config.target_path);
148
149        // Remove destination if it exists
150        if dest_dir.exists() {
151            remove_items(&[dest_dir.as_path()]).map_err(|e| {
152                cause!(ErrorType::MoveFromTempToDest)
153                    .src(e)
154                    .msg(format!("Could not remove {}", dest_dir.display()))
155            })?;
156        }
157
158        // Create destination directory
159        fs::create_dir_all(&dest_dir).map_err(|e| cause!(ErrorType::MoveFromTempToDest).src(e))?;
160
161        let mut opt = CopyOptions::new();
162        opt.overwrite = true;
163        opt.copy_inside = true;
164
165        copy_items(&[source_content.as_path()], &dest_dir, &opt).map_err(|e| {
166            cause!(ErrorType::MoveFromTempToDest).src(e).msg(format!(
167                "Could not copy {} to {}",
168                source_content.display(),
169                dest_dir.display()
170            ))
171        })?;
172
173        debug!(
174            "Copied contents of {source_subdir} to {}",
175            wire_op.source_config.target_path
176        );
177    }
178
179    info!("git-wire sync with caching completed");
180    Ok(true)
181}