rattler_build_source_cache 0.1.5

Source cache management for rattler-build
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
//! Main source cache implementation

use flate2::read::GzDecoder;
use std::path::{Path, PathBuf};
use tokio::io::AsyncWriteExt;

use crate::{
    builder::ProgressHandler,
    error::CacheError,
    index::{CacheEntry, CacheIndex, SourceType},
    lock::LockManager,
    source::{AttestationVerification, Checksum, GitSource, Source, UrlSource},
};
use rattler_build_networking::BaseClient;
use rattler_git::CheckoutOptions;
use rattler_git::resolver::GitResolver;

/// Result of fetching a source from the cache
#[derive(Debug, Clone)]
pub struct SourceResult {
    /// Path to the fetched source
    pub path: PathBuf,
    /// For git sources, the resolved commit SHA
    pub git_commit: Option<String>,
}

/// The main source cache that handles Git, URL, and Path sources
pub struct SourceCache {
    cache_dir: PathBuf,
    index: CacheIndex,
    lock_manager: LockManager,
    client: BaseClient,
    git_resolver: GitResolver,
    progress_handler: Option<Box<dyn ProgressHandler>>,
}

impl SourceCache {
    /// Create a new source cache
    pub async fn new(
        cache_dir: PathBuf,
        client: BaseClient,
        progress_handler: Option<Box<dyn ProgressHandler>>,
    ) -> Result<Self, CacheError> {
        let index = CacheIndex::new(cache_dir.clone()).await?;
        let lock_manager = LockManager::new(&cache_dir).await?;

        let cache = Self {
            cache_dir,
            index,
            lock_manager,
            client,
            git_resolver: GitResolver::default(),
            progress_handler,
        };

        Ok(cache)
    }

    /// Get a source from the cache or fetch it if not present
    pub async fn get_source(&self, source: &Source) -> Result<SourceResult, CacheError> {
        match source {
            Source::Git(git_source) => self.get_git_source(git_source).await,
            Source::Url(url_source) => self.get_url_source(url_source).await,
            Source::Path(path) => {
                // Path sources are not cached, just return the path
                Ok(SourceResult {
                    path: path.clone(),
                    git_commit: None,
                })
            }
        }
    }

    /// Get a Git source from the cache or clone it if not present
    async fn get_git_source(&self, source: &GitSource) -> Result<SourceResult, CacheError> {
        let git_url = source.to_git_url();
        let key =
            CacheIndex::generate_git_cache_key(source.url.as_ref(), &source.reference.to_string());

        // Acquire lock for this cache entry
        let _lock = self.lock_manager.acquire(&key).await?;

        // Check if we have it in cache
        if let Some(entry) = self.index.get(&key).await {
            let cache_path = self.index.get_cache_path(&entry);
            if cache_path.exists() {
                // Update access time
                self.index.touch(&key).await?;
                tracing::info!("Found git source in cache: {}", cache_path.display());
                return Ok(SourceResult {
                    path: cache_path,
                    git_commit: entry.git_commit.clone(),
                });
            }
        }

        // Use rattler_git to fetch the repository
        tracing::info!("Fetching git repository: {}", git_url);
        let git_cache = self.cache_dir.join("git");
        fs_err::tokio::create_dir_all(&git_cache).await?;

        let checkout_options = CheckoutOptions {
            update_submodules: source.submodules,
        };

        let fetch_result = self
            .git_resolver
            .fetch(
                git_url.clone(),
                self.client.get_client().clone(),
                git_cache,
                None,
                checkout_options,
            )
            .await
            .map_err(|e| CacheError::Git(format!("Git fetch failed: {}", e)))?;

        let repo_path = fetch_result.path().to_path_buf();
        let commit_hash = fetch_result.commit().to_string();

        // Verify expected commit if specified
        if let Some(expected) = &source.expected_commit {
            if commit_hash != *expected {
                return Err(CacheError::GitCommitMismatch {
                    expected: expected.clone(),
                    actual: commit_hash,
                    rev: source.reference.to_string(),
                });
            }
            tracing::info!("Verified expected commit: {}", expected);
        }

        // Handle LFS if needed
        if source.lfs {
            self.git_lfs_pull(&repo_path, &source.url).await?;
        }

        // Create cache entry
        let entry = CacheEntry {
            source_type: SourceType::Git,
            url: source.url.to_string(),
            checksum: None,
            checksum_type: None,
            actual_filename: None,
            git_commit: Some(commit_hash.clone()),
            git_rev: Some(source.reference.to_string()),
            cache_path: repo_path
                .strip_prefix(&self.cache_dir)
                .unwrap_or(&repo_path)
                .to_path_buf(),
            extracted_path: None,
            last_accessed: chrono::Utc::now(),
            created: chrono::Utc::now(),
            lock_file: Some(_lock.path().to_path_buf()),
            attestation_verified: false,
        };

        self.index.insert(key, entry).await?;

        Ok(SourceResult {
            path: repo_path,
            git_commit: Some(commit_hash),
        })
    }

    /// Pull LFS files for a git repository
    async fn git_lfs_pull(
        &self,
        repo_path: &Path,
        source_url: &url::Url,
    ) -> Result<(), CacheError> {
        let output = tokio::process::Command::new("git")
            .current_dir(repo_path)
            .arg("lfs")
            .arg("version")
            .output()
            .await
            .map_err(|e| CacheError::Git(format!("git-lfs not installed: {}", e)))?;

        if !output.status.success() {
            return Err(CacheError::Git("git-lfs not installed".to_string()));
        }

        // Point git-lfs at the original source via `lfs.url` config.
        // The checkout's origin remote points to the local bare database
        // (set by `git clone --local`), which doesn't have LFS objects.
        // We use lfs.url rather than modifying origin so only LFS is affected.
        // For file:// URLs, convert to a plain local path because git-lfs does
        // not handle the file:// protocol correctly (especially on Windows).
        let lfs_url = if source_url.scheme() == "file" {
            source_url
                .to_file_path()
                .map(|p| p.display().to_string())
                .unwrap_or_else(|_| source_url.as_str().to_string())
        } else {
            source_url.as_str().to_string()
        };

        let output = tokio::process::Command::new("git")
            .current_dir(repo_path)
            .arg("config")
            .arg("lfs.url")
            .arg(&lfs_url)
            .output()
            .await
            .map_err(|e| CacheError::Git(format!("Failed to configure lfs.url: {}", e)))?;

        if !output.status.success() {
            return Err(CacheError::Git(format!(
                "Failed to configure lfs.url: {}",
                String::from_utf8_lossy(&output.stderr)
            )));
        }

        // Fetch LFS files from the configured lfs.url.
        let output = tokio::process::Command::new("git")
            .current_dir(repo_path)
            .arg("lfs")
            .arg("fetch")
            .output()
            .await
            .map_err(|e| CacheError::Git(format!("Failed to fetch LFS files: {}", e)))?;

        if !output.status.success() {
            return Err(CacheError::Git(format!(
                "LFS fetch failed: {}",
                String::from_utf8_lossy(&output.stderr)
            )));
        }

        // Checkout LFS files
        let output = tokio::process::Command::new("git")
            .current_dir(repo_path)
            .arg("lfs")
            .arg("checkout")
            .output()
            .await
            .map_err(|e| CacheError::Git(format!("Failed to checkout LFS files: {}", e)))?;

        if !output.status.success() {
            return Err(CacheError::Git(format!(
                "LFS checkout failed: {}",
                String::from_utf8_lossy(&output.stderr)
            )));
        }

        Ok(())
    }

    /// Get a URL source from the cache or download it if not present
    async fn get_url_source(&self, source: &UrlSource) -> Result<SourceResult, CacheError> {
        // Try each URL until one succeeds
        let mut last_error = None;

        for url in &source.urls {
            match self
                .try_url(
                    url,
                    &source.checksums,
                    source.file_name.as_deref(),
                    source.attestation.as_ref(),
                )
                .await
            {
                Ok(path) => {
                    return Ok(SourceResult {
                        path,
                        git_commit: None,
                    });
                }
                Err(e) => {
                    tracing::warn!("Failed to fetch from {}: {}", url, e);
                    last_error = Some(e);
                }
            }
        }

        Err(last_error.unwrap_or_else(|| CacheError::Other("No URLs provided".to_string())))
    }

    /// Try to get a single URL from cache or download it
    async fn try_url(
        &self,
        url: &url::Url,
        checksums: &[Checksum],
        file_name: Option<&str>,
        attestation: Option<&AttestationVerification>,
    ) -> Result<PathBuf, CacheError> {
        let key = CacheIndex::generate_cache_key(url, checksums);

        // Acquire lock for this cache entry
        let _lock = self.lock_manager.acquire(&key).await?;

        // Check if we have it in cache
        if let Some(entry) = self.index.get(&key).await {
            let cache_path = self.index.get_cache_path(&entry);

            // If extraction was done, return extracted path
            if let Some(extracted_path) = self.index.get_extracted_path(&entry)
                && extracted_path.exists()
            {
                // Re-verify attestation if configured but not yet verified for this entry
                if let Some(attestation_config) = attestation
                    && !entry.attestation_verified
                {
                    let archive_path = self.index.get_cache_path(&entry);
                    self.verify_attestation(&archive_path, url, attestation_config)
                        .await?;
                    self.index.set_attestation_verified(&key).await?;
                }
                self.index.touch(&key).await?;
                tracing::info!(
                    "Found extracted source in cache: {}",
                    extracted_path.display()
                );
                return Ok(extracted_path);
            }

            // Otherwise return the archive file
            if cache_path.exists() {
                // Validate all checksums if provided
                if !checksums.is_empty() {
                    let mismatch = checksums
                        .iter()
                        .find_map(|cs| cs.validate(&cache_path).err());
                    if mismatch.is_some() {
                        tracing::warn!("Checksum validation failed, re-downloading");
                        fs_err::tokio::remove_file(&cache_path).await?;
                    } else {
                        // Re-verify attestation if configured but not yet verified for this entry
                        if let Some(attestation_config) = attestation
                            && !entry.attestation_verified
                        {
                            self.verify_attestation(&cache_path, url, attestation_config)
                                .await?;
                            self.index.set_attestation_verified(&key).await?;
                        }
                        self.index.touch(&key).await?;
                        tracing::info!("Found source in cache: {}", cache_path.display());
                        return Ok(cache_path);
                    }
                } else {
                    // Re-verify attestation if configured but not yet verified for this entry
                    if let Some(attestation_config) = attestation
                        && !entry.attestation_verified
                    {
                        self.verify_attestation(&cache_path, url, attestation_config)
                            .await?;
                        self.index.set_attestation_verified(&key).await?;
                    }
                    self.index.touch(&key).await?;
                    tracing::info!("Found source in cache: {}", cache_path.display());
                    return Ok(cache_path);
                }
            }
        }

        // Download the file
        tracing::info!("Downloading from: {}", url);
        let (cache_path, actual_filename) = self.download_url(url, &key).await?;

        // Validate all checksums
        for cs in checksums {
            if let Err(mismatch) = cs.validate(&cache_path) {
                fs_err::tokio::remove_file(&cache_path).await?;
                return Err(CacheError::ValidationFailed {
                    path: cache_path,
                    expected: mismatch.expected,
                    actual: mismatch.actual,
                    kind: mismatch.kind.to_string(),
                });
            }
        }

        // Perform attestation verification if configured
        if let Some(attestation_config) = attestation {
            self.verify_attestation(&cache_path, url, attestation_config)
                .await?;
        }

        // Extract if needed and no explicit filename was provided
        let final_path = if file_name.is_none() && self.should_extract(&cache_path) {
            let extracted_dir = self.cache_dir.join(format!("{}_extracted", key));
            self.extract_archive(&cache_path, &extracted_dir).await?;
            Some(extracted_dir)
        } else {
            None
        };

        // Use the first checksum for the cache entry metadata
        let primary_checksum = checksums.first();

        // Create cache entry
        let entry = CacheEntry {
            source_type: SourceType::Url,
            url: url.to_string(),
            checksum: primary_checksum.map(|c| c.to_hex()),
            checksum_type: primary_checksum
                .map(|c| match c {
                    Checksum::Sha256(_) => "sha256",
                    Checksum::Md5(_) => "md5",
                })
                .map(String::from),
            actual_filename,
            git_commit: None,
            git_rev: None,
            cache_path: cache_path
                .strip_prefix(&self.cache_dir)
                .unwrap_or(&cache_path)
                .to_path_buf(),
            extracted_path: final_path
                .as_ref()
                .map(|p| p.strip_prefix(&self.cache_dir).unwrap_or(p).to_path_buf()),
            last_accessed: chrono::Utc::now(),
            created: chrono::Utc::now(),
            lock_file: Some(_lock.path().to_path_buf()),
            attestation_verified: attestation.is_some(),
        };

        self.index.insert(key, entry).await?;

        Ok(final_path.unwrap_or(cache_path))
    }

    /// Download a URL to the cache
    async fn download_url(
        &self,
        url: &url::Url,
        key: &str,
    ) -> Result<(PathBuf, Option<String>), CacheError> {
        // Determine filename
        let filename = url
            .path_segments()
            .and_then(|mut segments| segments.next_back())
            .unwrap_or("download");

        let cache_path = self.cache_dir.join(format!("{}_{}", key, filename));

        // Handle file:// URLs
        if url.scheme() == "file" {
            let source_path = url
                .to_file_path()
                .map_err(|_| CacheError::Other("Invalid file URL".to_string()))?;

            if !source_path.exists() {
                return Err(CacheError::FileNotFound(source_path));
            }

            fs_err::tokio::copy(&source_path, &cache_path).await?;
            return Ok((cache_path, Some(filename.to_string())));
        }

        // Download from HTTP/HTTPS - use the appropriate client based on SSL settings
        let response = self.client.for_host(url).get(url.clone()).send().await?;

        if !response.status().is_success() {
            return Err(CacheError::Download(
                response.error_for_status().unwrap_err(),
            ));
        }

        // Get actual filename from Content-Disposition header if present
        let actual_filename = response
            .headers()
            .get("content-disposition")
            .and_then(|v| v.to_str().ok())
            .and_then(extract_filename_from_header);

        // Get content length for progress reporting
        let total_size = response
            .headers()
            .get("content-length")
            .and_then(|v| v.to_str().ok())
            .and_then(|s| s.parse::<u64>().ok());

        // Notify progress handler
        if let Some(handler) = &self.progress_handler {
            handler.on_download_start(url.as_str(), total_size);
        }

        // Stream download to file
        let mut file = fs_err::tokio::File::create(&cache_path).await?;
        let mut stream = response.bytes_stream();
        let mut downloaded = 0u64;

        use futures::StreamExt;
        while let Some(chunk) = stream.next().await {
            let chunk = chunk?;
            downloaded += chunk.len() as u64;
            file.write_all(&chunk).await?;

            // Update progress
            if let Some(handler) = &self.progress_handler {
                handler.on_download_progress(url.as_str(), downloaded, total_size);
            }
        }

        file.flush().await?;

        // Notify completion
        if let Some(handler) = &self.progress_handler {
            handler.on_download_complete(url.as_str());
        }

        // If Content-Disposition provided a filename that differs from the URL's,
        // rename the cached file so downstream code can detect the archive format
        // from the file extension alone.
        let final_path = if let Some(ref actual) = actual_filename {
            let new_path = self.cache_dir.join(format!("{}_{}", key, actual));
            if new_path != cache_path {
                fs_err::tokio::rename(&cache_path, &new_path).await?;
                new_path
            } else {
                cache_path
            }
        } else {
            cache_path
        };

        Ok((final_path, actual_filename))
    }

    /// Check if a file should be extracted based on its filename extension
    pub(crate) fn should_extract(&self, path: &Path) -> bool {
        let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
        is_archive(name)
    }

    /// Extract an archive to a directory
    async fn extract_archive(
        &self,
        archive_path: &Path,
        target_dir: &Path,
    ) -> Result<(), CacheError> {
        // Notify progress handler
        if let Some(handler) = &self.progress_handler {
            handler.on_extraction_start(archive_path);
        }

        // Create a temporary directory for extraction
        let temp_dir = tempfile::tempdir_in(&self.cache_dir)
            .map_err(|e| CacheError::Other(format!("Failed to create temp dir: {}", e)))?;

        let name = archive_path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("");

        // Extract based on file type to temp directory
        if is_tarball(name) {
            extract_tar(archive_path, temp_dir.path())?;
        } else if name.ends_with(".zip") {
            extract_zip(archive_path, temp_dir.path())?;
        } else if name.ends_with(".7z") {
            extract_7z(archive_path, temp_dir.path())?;
        } else {
            return Err(CacheError::ExtractionError(format!(
                "Unsupported archive format: {}",
                name
            )));
        }

        // Strip root directory if needed and move to final location
        strip_and_move_extracted_dir(temp_dir.path(), target_dir).await?;

        // Notify completion
        if let Some(handler) = &self.progress_handler {
            handler.on_extraction_complete(archive_path);
        }

        Ok(())
    }

    /// Verify a downloaded file using attestation (sigstore-based).
    ///
    /// When the `sigstore` feature is enabled, delegates to the full verification
    /// implementation. When disabled, logs a warning and skips verification.
    async fn verify_attestation(
        &self,
        file_path: &Path,
        source_url: &url::Url,
        attestation_config: &AttestationVerification,
    ) -> Result<(), CacheError> {
        #[cfg(feature = "sigstore")]
        {
            crate::sigstore::verify_attestation(
                &self.client,
                file_path,
                source_url,
                attestation_config,
            )
            .await?;
        }
        #[cfg(not(feature = "sigstore"))]
        {
            let _ = (file_path, attestation_config);
            tracing::warn!(
                url = %source_url,
                "sigstore verification is disabled at compile time — \
                 attestation will NOT be verified"
            );
        }
        Ok(())
    }

    /// Clean up stale locks (manual cleanup only, cache entries are kept indefinitely)
    pub async fn cleanup_stale_locks(&self) -> Result<(), CacheError> {
        self.lock_manager.cleanup_stale_locks().await?;
        Ok(())
    }

    /// Get cache statistics
    pub async fn stats(&self) -> Result<CacheStats, CacheError> {
        let entries = self.index.list_entries().await;
        let total_entries = entries.len();
        let mut total_size = 0u64;
        let mut git_entries = 0;
        let mut url_entries = 0;

        for (_, entry) in entries {
            match entry.source_type {
                SourceType::Git => git_entries += 1,
                SourceType::Url => url_entries += 1,
            }

            let path = self.index.get_cache_path(&entry);
            if let Ok(metadata) = fs_err::tokio::metadata(&path).await {
                if metadata.is_file() {
                    total_size += metadata.len();
                } else if metadata.is_dir() {
                    // Calculate directory size
                    total_size += calculate_dir_size(&path).await?;
                }
            }
        }

        Ok(CacheStats {
            total_entries,
            total_size,
            git_entries,
            url_entries,
        })
    }
}

/// Cache statistics
#[derive(Debug, Clone)]
pub struct CacheStats {
    pub total_entries: usize,
    pub total_size: u64,
    pub git_entries: usize,
    pub url_entries: usize,
}

// Helper functions

pub(crate) fn extract_filename_from_header(header_value: &str) -> Option<String> {
    for part in header_value.split(';') {
        let part = part.trim();
        if part.starts_with("filename=") {
            let filename = part.strip_prefix("filename=")?;
            let filename = filename.trim_matches('"').trim_matches('\'');
            if !filename.is_empty() {
                // Strip any path components — only keep the base filename
                let filename = Path::new(filename)
                    .file_name()
                    .and_then(|n| n.to_str())
                    .unwrap_or(filename);
                return Some(filename.to_string());
            }
        }
    }
    None
}

pub(crate) fn is_archive(name: &str) -> bool {
    is_tarball(name) || name.ends_with(".zip") || name.ends_with(".7z")
}

/// Checks whether file has known tarball extension
pub fn is_tarball(file_name: &str) -> bool {
    [
        // Gzip
        ".tar.gz",
        ".tgz",
        ".taz",
        // Bzip2
        ".tar.bz2",
        ".tbz",
        ".tbz2",
        ".tz2",
        // Xz2
        ".tar.lzma",
        ".tlz",
        ".tar.xz",
        ".txz",
        // Zstd
        ".tar.zst",
        ".tzst",
        // Compress
        ".tar.Z",
        ".taZ",
        // Lzip
        ".tar.lz",
        // Lzop
        ".tar.lzo",
        // PlainTar
        ".tar",
    ]
    .iter()
    .any(|ext| file_name.ends_with(ext))
}

fn extract_tar(archive: &Path, target: &Path) -> Result<(), CacheError> {
    let file = fs_err::File::open(archive)
        .map_err(|e| CacheError::ExtractionError(format!("Failed to open archive: {}", e)))?;

    let name = archive.file_name().and_then(|n| n.to_str()).unwrap_or("");

    if name.ends_with(".tar.gz") || name.ends_with(".tgz") {
        let mut archive = tar::Archive::new(GzDecoder::new(file));
        archive
            .unpack(target)
            .map_err(|e| CacheError::ExtractionError(format!("Failed to extract tar.gz: {}", e)))?;
    } else if name.ends_with(".tar.bz2") || name.ends_with(".tbz2") {
        let mut archive = tar::Archive::new(bzip2::read::BzDecoder::new(file));
        archive.unpack(target).map_err(|e| {
            CacheError::ExtractionError(format!("Failed to extract tar.bz2: {}", e))
        })?;
    } else if name.ends_with(".tar.xz") || name.ends_with(".txz") {
        let mut archive = tar::Archive::new(lzma_rust2::XzReader::new(file, true));
        archive
            .unpack(target)
            .map_err(|e| CacheError::ExtractionError(format!("Failed to extract tar.xz: {}", e)))?;
    } else if name.ends_with(".tar.zst") {
        let decoder = zstd::stream::read::Decoder::new(file).map_err(|e| {
            CacheError::ExtractionError(format!("Failed to create zstd decoder: {}", e))
        })?;
        let mut archive = tar::Archive::new(decoder);
        archive.unpack(target).map_err(|e| {
            CacheError::ExtractionError(format!("Failed to extract tar.zst: {}", e))
        })?;
    } else {
        let mut archive = tar::Archive::new(file);
        archive
            .unpack(target)
            .map_err(|e| CacheError::ExtractionError(format!("Failed to extract tar: {}", e)))?;
    }

    Ok(())
}

fn extract_zip(archive: &Path, target: &Path) -> Result<(), CacheError> {
    let file = fs_err::File::open(archive)
        .map_err(|e| CacheError::ExtractionError(format!("Failed to open archive: {}", e)))?;

    let mut archive = zip::ZipArchive::new(file)
        .map_err(|e| CacheError::ExtractionError(format!("Failed to read zip: {}", e)))?;

    archive
        .extract(target)
        .map_err(|e| CacheError::ExtractionError(format!("Failed to extract zip: {}", e)))?;

    Ok(())
}

fn extract_7z(archive: &Path, target: &Path) -> Result<(), CacheError> {
    sevenz_rust2::decompress_file(archive, target)
        .map_err(|e| CacheError::ExtractionError(format!("Failed to extract 7z: {}", e)))?;

    Ok(())
}

async fn calculate_dir_size(dir: &Path) -> Result<u64, CacheError> {
    let mut total = 0u64;
    let mut entries = fs_err::tokio::read_dir(dir).await?;

    while let Some(entry) = entries.next_entry().await? {
        let metadata = entry.metadata().await?;
        if metadata.is_file() {
            total += metadata.len();
        } else if metadata.is_dir() {
            total += Box::pin(calculate_dir_size(&entry.path())).await?;
        }
    }

    Ok(total)
}

/// Strip root directory if the extracted archive contains only a single top-level directory
async fn strip_and_move_extracted_dir(src: &Path, dest: &Path) -> Result<(), CacheError> {
    use fs_err as fs;

    // Read entries from source directory
    let mut entries = fs::read_dir(src)?;

    // Check if there's only one entry and if it's a directory
    let first_entry = entries.next();
    let second_entry = entries.next();

    let src_dir = match (first_entry, second_entry) {
        (Some(Ok(entry)), None) if entry.file_type()?.is_dir() => {
            // Single directory - we'll extract from inside it
            entry.path()
        }
        _ => {
            // Multiple entries or not a directory - use the source as-is
            src.to_path_buf()
        }
    };

    // Create destination directory
    fs::create_dir_all(dest)?;

    // Move all files from source directory to destination
    for entry in fs::read_dir(&src_dir)? {
        let entry = entry?;
        let dest_path = dest.join(entry.file_name());
        fs::rename(entry.path(), dest_path)?;
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_extract_filename_from_header() {
        assert_eq!(
            extract_filename_from_header("attachment; filename=\"test.tar.gz\""),
            Some("test.tar.gz".to_string())
        );
    }

    #[test]
    fn test_is_archive() {
        assert!(is_archive("test.tar.gz"));
        assert!(is_archive("test.zip"));
        assert!(is_archive("test.7z"));
        assert!(!is_archive("test.txt"));
    }
}