@@ -10,43 +10,11 @@ pub fn is_system_compatible(system_info: &SystemInfo) -> bool {
1010 matches ! ( system_info. os, SupportedOs :: Linux ( ref distro) if distro. is_supported( ) )
1111}
1212
13- /// Installs packages with caching support .
13+ /// Skip installed tools; otherwise restore the cache and recheck before installing .
1414///
15- /// This function provides a common pattern for installing tools on Ubuntu/Debian systems
16- /// with automatic caching to speed up subsequent installations (e.g., in CI environments).
17- ///
18- /// # Arguments
19- ///
20- /// * `system_info` - System information to determine compatibility
21- /// * `setup_cache_dir` - Optional directory to restore from/save to cache
22- /// * `is_installed` - Function that checks if the tool is already installed
23- /// * `install_packages` - Async closure that:
24- /// 1. Performs the installation (e.g., downloads .deb files, calls `apt::install`)
25- /// 2. Returns a Vec of package names that should be cached via `dpkg -L`
26- ///
27- /// # Flow
28- ///
29- /// 1. Check if already installed - if yes, skip everything
30- /// 2. Try to restore from cache (if cache_dir provided)
31- /// 3. Check again if installed - if yes, we're done
32- /// 4. Run the install closure to install and get package names
33- /// 5. Save installed packages to cache (if cache_dir provided)
34- ///
35- /// # Example
36- ///
37- /// ```rust,ignore
38- /// apt::install_cached(
39- /// system_info,
40- /// setup_cache_dir,
41- /// || Command::new("which").arg("perf").status().is_ok(),
42- /// || async {
43- /// let packages = vec!["linux-tools-common".to_string()];
44- /// let refs: Vec<&str> = packages.iter().map(|s| s.as_str()).collect();
45- /// apt::install(system_info, &refs)?;
46- /// Ok(packages) // Return package names for caching
47- /// },
48- /// ).await?;
49- /// ```
15+ /// `install_packages` installs the tool and returns package names to cache via `dpkg -L`.
16+ /// Restore copies files without updating dpkg's database, so `is_installed` must probe
17+ /// the tool or its files. Separate calls can share a cache: files and metadata accumulate.
5018pub async fn install_cached < F , I , Fut > (
5119 system_info : & SystemInfo ,
5220 setup_cache_dir : Option < & Path > ,
6331 return Ok ( ( ) ) ;
6432 }
6533
66- // Try to restore from cache first
6734 if let Some ( cache_dir) = setup_cache_dir {
6835 restore_from_cache ( system_info, cache_dir) ?;
6936
@@ -73,12 +40,10 @@ where
7340 }
7441 }
7542
76- // Install and get the package names for caching
7743 let cache_packages = install_packages ( ) . await ?;
7844
7945 info ! ( "Installation completed successfully" ) ;
8046
81- // Save to cache after successful installation
8247 if let Some ( cache_dir) = setup_cache_dir {
8348 let cache_refs: Vec < & str > = cache_packages. iter ( ) . map ( |s| s. as_str ( ) ) . collect ( ) ;
8449 save_to_cache ( system_info, cache_dir, & cache_refs) ?;
@@ -117,7 +82,6 @@ fn restore_from_cache(system_info: &SystemInfo, cache_dir: &Path) -> Result<()>
11782 return Ok ( ( ) ) ;
11883 }
11984
120- // Check if the directory has any contents
12185 let has_contents = std:: fs:: read_dir ( cache_dir)
12286 . map ( |mut entries| entries. next ( ) . is_some ( ) )
12387 . unwrap_or ( false ) ;
@@ -132,7 +96,6 @@ fn restore_from_cache(system_info: &SystemInfo, cache_dir: &Path) -> Result<()>
13296 cache_dir. display( )
13397 ) ;
13498
135- // Read and log the metadata file if it exists
13699 let metadata_path = cache_dir. join ( METADATA_FILENAME ) ;
137100 if metadata_path. exists ( ) {
138101 match std:: fs:: read_to_string ( & metadata_path) {
@@ -150,12 +113,11 @@ fn restore_from_cache(system_info: &SystemInfo, cache_dir: &Path) -> Result<()>
150113 debug ! ( "No metadata file found in cache directory" ) ;
151114 }
152115
153- // Use bash to properly handle glob expansion
154116 let cache_dir_str = cache_dir
155117 . to_str ( )
156118 . ok_or_else ( || anyhow ! ( "Invalid cache directory path" ) ) ?;
157119
158- // IMPORTANT: We have to use 'bash' here to ensure that glob patterns are expanded correctly
120+ // A shell is needed to expand the cache directory glob.
159121 let copy_cmd = format ! ( "cp -r {cache_dir_str}/* /" ) ;
160122 run_with_sudo ( "bash" , [ "-c" , & copy_cmd] ) ?;
161123
@@ -175,15 +137,13 @@ fn save_to_cache(system_info: &SystemInfo, cache_dir: &Path, packages: &[&str])
175137 cache_dir. display( )
176138 ) ;
177139
178- // Create cache directory if it doesn't exist
179140 std:: fs:: create_dir_all ( cache_dir) . context ( "Failed to create cache directory" ) ?;
180141
181142 let cache_dir_str = cache_dir
182143 . to_str ( )
183144 . ok_or_else ( || anyhow ! ( "Invalid cache directory path" ) ) ?;
184145
185146 // Logic taken from https://stackoverflow.com/a/59277514
186- // This shell command lists all the files outputted by the given packages and copy them to the cache directory
187147 let packages_str = packages. join ( " " ) ;
188148 let shell_cmd = format ! (
189149 "dpkg -L {packages_str} | while IFS= read -r f; do if test -f \" $f\" ; then echo \" $f\" ; fi; done | xargs cp --parents --target-directory {cache_dir_str}" ,
@@ -203,9 +163,26 @@ fn save_to_cache(system_info: &SystemInfo, cache_dir: &Path, packages: &[&str])
203163 bail ! ( "Failed to save packages to cache" ) ;
204164 }
205165
206- // Create metadata file containing the installed packages
166+ // Separate installs share the cache, so retain previously cached package names.
207167 let metadata_path = cache_dir. join ( METADATA_FILENAME ) ;
208- let metadata_content = packages. join ( "\n " ) ; // TODO: add package versions as well, by using the output of the install command for example
168+ let existing_metadata = match std:: fs:: read_to_string ( & metadata_path) {
169+ Ok ( content) => content,
170+ Err ( error) if error. kind ( ) == std:: io:: ErrorKind :: NotFound => String :: new ( ) ,
171+ Err ( error) => {
172+ warn ! (
173+ "Failed to read cache metadata at {}: {error}" ,
174+ metadata_path. display( )
175+ ) ;
176+ return Ok ( ( ) ) ;
177+ }
178+ } ;
179+ let mut cached_packages: Vec < & str > = existing_metadata
180+ . lines ( )
181+ . chain ( packages. iter ( ) . copied ( ) )
182+ . collect ( ) ;
183+ cached_packages. sort_unstable ( ) ;
184+ cached_packages. dedup ( ) ;
185+ let metadata_content = cached_packages. join ( "\n " ) ;
209186 if let Ok ( ( ) ) = std:: fs:: create_dir_all ( metadata_path. parent ( ) . unwrap ( ) ) {
210187 if let Ok ( ( ) ) = std:: fs:: write ( & metadata_path, metadata_content)
211188 . context ( "Failed to write metadata file" )
0 commit comments