exarch-core 0.2.9

Memory-safe archive extraction library with security validation
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
845
846
847
848
849
850
851
852
853
854
//! High-level public API for archive extraction, creation, and inspection.

use std::path::Path;

use crate::ExtractionError;
use crate::ExtractionReport;
use crate::NoopProgress;
use crate::ProgressCallback;
use crate::Result;
use crate::SecurityConfig;
use crate::config::ExtractionOptions;
use crate::creation::CreationConfig;
use crate::creation::CreationReport;
use crate::formats::detect::ArchiveType;
use crate::formats::detect::detect_format;
use crate::inspection::ArchiveManifest;
use crate::inspection::VerificationReport;

/// Extracts an archive to the specified output directory.
///
/// This is the main high-level API for extracting archives with security
/// validation. The archive format is automatically detected.
///
/// # Arguments
///
/// * `archive_path` - Path to the archive file
/// * `output_dir` - Directory where files will be extracted
/// * `config` - Security configuration for the extraction
///
/// # Errors
///
/// Returns an error if:
/// - Archive file cannot be opened
/// - Archive format is unsupported
/// - Security validation fails
/// - I/O operations fail
///
/// # Examples
///
/// ```no_run
/// use exarch_core::SecurityConfig;
/// use exarch_core::extract_archive;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let config = SecurityConfig::default();
/// let report = extract_archive("archive.tar.gz", "/tmp/output", &config)?;
/// println!("Extracted {} files", report.files_extracted);
/// # Ok(())
/// # }
/// ```
pub fn extract_archive<P: AsRef<Path>, Q: AsRef<Path>>(
    archive_path: P,
    output_dir: Q,
    config: &SecurityConfig,
) -> Result<ExtractionReport> {
    let mut noop = NoopProgress;
    extract_archive_with_progress(archive_path, output_dir, config, &mut noop)
}

/// Extracts an archive with progress reporting.
///
/// Same as `extract_archive` but accepts a `ProgressCallback` for
/// real-time progress updates during extraction.
///
/// # Arguments
///
/// * `archive_path` - Path to the archive file
/// * `output_dir` - Directory where files will be extracted
/// * `config` - Security configuration for the extraction
/// * `progress` - Callback for progress updates
///
/// # Errors
///
/// Returns an error if:
/// - Archive file cannot be opened
/// - Archive format is unsupported
/// - Security validation fails
/// - I/O operations fail
///
/// # Examples
///
/// ```no_run
/// use exarch_core::NoopProgress;
/// use exarch_core::SecurityConfig;
/// use exarch_core::extract_archive_with_progress;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let config = SecurityConfig::default();
/// let mut progress = NoopProgress;
/// let report =
///     extract_archive_with_progress("archive.tar.gz", "/tmp/output", &config, &mut progress)?;
/// println!("Extracted {} files", report.files_extracted);
/// # Ok(())
/// # }
/// ```
pub fn extract_archive_with_progress<P: AsRef<Path>, Q: AsRef<Path>>(
    archive_path: P,
    output_dir: Q,
    config: &SecurityConfig,
    progress: &mut dyn ProgressCallback,
) -> Result<ExtractionReport> {
    let options = ExtractionOptions::default();
    extract_archive_with_progress_and_options(archive_path, output_dir, config, &options, progress)
}

fn extract_archive_with_progress_and_options<P: AsRef<Path>, Q: AsRef<Path>>(
    archive_path: P,
    output_dir: Q,
    config: &SecurityConfig,
    options: &ExtractionOptions,
    _progress: &mut dyn ProgressCallback,
) -> Result<ExtractionReport> {
    let archive_path = archive_path.as_ref();
    let output_dir = output_dir.as_ref();

    // Detect archive format from file extension
    let format = detect_format(archive_path)?;

    // Dispatch to format-specific extraction
    match format {
        ArchiveType::Tar => extract_tar(archive_path, output_dir, config, options),
        ArchiveType::TarGz => extract_tar_gz(archive_path, output_dir, config, options),
        ArchiveType::TarBz2 => extract_tar_bz2(archive_path, output_dir, config, options),
        ArchiveType::TarXz => extract_tar_xz(archive_path, output_dir, config, options),
        ArchiveType::TarZst => extract_tar_zst(archive_path, output_dir, config, options),
        ArchiveType::Zip => extract_zip(archive_path, output_dir, config, options),
        ArchiveType::SevenZ => extract_7z(archive_path, output_dir, config, options),
    }
}

/// Extracts an archive with extraction options and optional progress reporting.
///
/// This is the most flexible extraction API. Use this when you need both
/// `ExtractionOptions` (e.g., atomic mode) and progress reporting.
///
/// # Arguments
///
/// * `archive_path` - Path to the archive file
/// * `output_dir` - Directory where files will be extracted
/// * `config` - Security configuration for the extraction
/// * `options` - Extraction behavior options (e.g., atomic mode)
/// * `progress` - Callback for progress updates
///
/// # Errors
///
/// Returns an error if:
/// - Archive file cannot be opened
/// - Archive format is unsupported
/// - Security validation fails
/// - I/O operations fail
/// - Atomic temp dir creation or rename fails
pub fn extract_archive_full<P: AsRef<Path>, Q: AsRef<Path>>(
    archive_path: P,
    output_dir: Q,
    config: &SecurityConfig,
    options: &ExtractionOptions,
    progress: &mut dyn ProgressCallback,
) -> Result<ExtractionReport> {
    if options.atomic {
        extract_atomic(archive_path, output_dir, config, options, progress)
    } else {
        extract_archive_with_progress_and_options(
            archive_path,
            output_dir,
            config,
            options,
            progress,
        )
    }
}

/// Extracts an archive with extraction options (no progress reporting).
///
/// Same as `extract_archive_full` but uses a no-op progress callback.
///
/// # Errors
///
/// Returns an error if:
/// - Archive file cannot be opened
/// - Archive format is unsupported
/// - Security validation fails
/// - I/O operations fail
/// - Atomic temp dir creation or rename fails
pub fn extract_archive_with_options<P: AsRef<Path>, Q: AsRef<Path>>(
    archive_path: P,
    output_dir: Q,
    config: &SecurityConfig,
    options: &ExtractionOptions,
) -> Result<ExtractionReport> {
    let mut noop = NoopProgress;
    extract_archive_full(archive_path, output_dir, config, options, &mut noop)
}

fn extract_atomic<P: AsRef<Path>, Q: AsRef<Path>>(
    archive_path: P,
    output_dir: Q,
    config: &SecurityConfig,
    options: &ExtractionOptions,
    progress: &mut dyn ProgressCallback,
) -> Result<ExtractionReport> {
    let output_dir = output_dir.as_ref();

    // Canonicalize output_dir to resolve any symlinks in the path before
    // computing the parent, so temp dir lands on the same filesystem.
    // If output_dir doesn't exist yet, use its lexical parent.
    let canonical_output = if output_dir.exists() {
        output_dir.canonicalize().map_err(ExtractionError::Io)?
    } else {
        output_dir.to_path_buf()
    };

    let parent =
        canonical_output
            .parent()
            .ok_or_else(|| ExtractionError::InvalidConfiguration {
                reason: "output directory has no parent".into(),
            })?;

    std::fs::create_dir_all(parent).map_err(ExtractionError::Io)?;

    let temp_dir = tempfile::tempdir_in(parent).map_err(|e| {
        ExtractionError::Io(std::io::Error::new(
            e.kind(),
            format!(
                "failed to create temp directory in {}: {e}",
                parent.display()
            ),
        ))
    })?;

    let result = extract_archive_with_progress_and_options(
        archive_path,
        temp_dir.path(),
        config,
        options,
        progress,
    );

    match result {
        Ok(report) => {
            // Consume TempDir to prevent Drop cleanup, then rename.
            let temp_path = temp_dir.keep();
            std::fs::rename(&temp_path, output_dir).map_err(|e| {
                // Rename failed: clean up temp dir
                let _ = std::fs::remove_dir_all(&temp_path);
                // Map AlreadyExists to OutputExists for caller clarity
                if e.kind() == std::io::ErrorKind::AlreadyExists {
                    ExtractionError::OutputExists {
                        path: output_dir.to_path_buf(),
                    }
                } else {
                    ExtractionError::Io(std::io::Error::new(
                        e.kind(),
                        format!("failed to rename temp dir to {}: {e}", output_dir.display()),
                    ))
                }
            })?;

            Ok(report)
        }
        Err(e) => {
            // TempDir Drop runs here: cleans up temp dir automatically.
            Err(e)
        }
    }
}

fn extract_tar(
    archive_path: &Path,
    output_dir: &Path,
    config: &SecurityConfig,
    options: &ExtractionOptions,
) -> Result<ExtractionReport> {
    use crate::formats::TarArchive;
    use crate::formats::traits::ArchiveFormat;
    use std::fs::File;
    use std::io::BufReader;

    let file = File::open(archive_path)?;
    let reader = BufReader::new(file);
    let mut archive = TarArchive::new(reader);
    archive.extract(output_dir, config, options)
}

fn extract_tar_gz(
    archive_path: &Path,
    output_dir: &Path,
    config: &SecurityConfig,
    options: &ExtractionOptions,
) -> Result<ExtractionReport> {
    use crate::formats::TarArchive;
    use crate::formats::traits::ArchiveFormat;
    use flate2::read::GzDecoder;
    use std::fs::File;
    use std::io::BufReader;

    let file = File::open(archive_path)?;
    let reader = BufReader::new(file);
    let decoder = GzDecoder::new(reader);
    let mut archive = TarArchive::new(decoder);
    archive.extract(output_dir, config, options)
}

fn extract_tar_bz2(
    archive_path: &Path,
    output_dir: &Path,
    config: &SecurityConfig,
    options: &ExtractionOptions,
) -> Result<ExtractionReport> {
    use crate::formats::TarArchive;
    use crate::formats::traits::ArchiveFormat;
    use bzip2::read::BzDecoder;
    use std::fs::File;
    use std::io::BufReader;

    let file = File::open(archive_path)?;
    let reader = BufReader::new(file);
    let decoder = BzDecoder::new(reader);
    let mut archive = TarArchive::new(decoder);
    archive.extract(output_dir, config, options)
}

fn extract_tar_xz(
    archive_path: &Path,
    output_dir: &Path,
    config: &SecurityConfig,
    options: &ExtractionOptions,
) -> Result<ExtractionReport> {
    use crate::formats::TarArchive;
    use crate::formats::traits::ArchiveFormat;
    use std::fs::File;
    use std::io::BufReader;
    use xz2::read::XzDecoder;

    let file = File::open(archive_path)?;
    let reader = BufReader::new(file);
    let decoder = XzDecoder::new(reader);
    let mut archive = TarArchive::new(decoder);
    archive.extract(output_dir, config, options)
}

fn extract_tar_zst(
    archive_path: &Path,
    output_dir: &Path,
    config: &SecurityConfig,
    options: &ExtractionOptions,
) -> Result<ExtractionReport> {
    use crate::formats::TarArchive;
    use crate::formats::traits::ArchiveFormat;
    use std::fs::File;
    use std::io::BufReader;
    use zstd::stream::read::Decoder as ZstdDecoder;

    let file = File::open(archive_path)?;
    let reader = BufReader::new(file);
    let decoder = ZstdDecoder::new(reader)?;
    let mut archive = TarArchive::new(decoder);
    archive.extract(output_dir, config, options)
}

fn extract_zip(
    archive_path: &Path,
    output_dir: &Path,
    config: &SecurityConfig,
    options: &ExtractionOptions,
) -> Result<ExtractionReport> {
    use crate::formats::ZipArchive;
    use crate::formats::traits::ArchiveFormat;
    use std::fs::File;

    let file = File::open(archive_path)?;
    let mut archive = ZipArchive::new(file)?;
    archive.extract(output_dir, config, options)
}

fn extract_7z(
    archive_path: &Path,
    output_dir: &Path,
    config: &SecurityConfig,
    options: &ExtractionOptions,
) -> Result<ExtractionReport> {
    use crate::formats::SevenZArchive;
    use crate::formats::traits::ArchiveFormat;
    use std::fs::File;

    let file = File::open(archive_path)?;
    let mut archive = SevenZArchive::new(file)?;
    archive.extract(output_dir, config, options)
}

/// Creates an archive from source files and directories.
///
/// Format is auto-detected from output file extension, or can be
/// explicitly set via `config.format`.
///
/// # Arguments
///
/// * `output_path` - Path to the output archive file
/// * `sources` - Source files and directories to include
/// * `config` - Creation configuration
///
/// # Errors
///
/// Returns an error if:
/// - Cannot determine archive format
/// - Source files don't exist
/// - I/O operations fail
/// - Configuration is invalid
///
/// # Examples
///
/// ```no_run
/// use exarch_core::create_archive;
/// use exarch_core::creation::CreationConfig;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let config = CreationConfig::default();
/// let report = create_archive("output.tar.gz", &["src/", "Cargo.toml"], &config)?;
/// println!("Created archive with {} files", report.files_added);
/// # Ok(())
/// # }
/// ```
pub fn create_archive<P: AsRef<Path>, Q: AsRef<Path>>(
    output_path: P,
    sources: &[Q],
    config: &CreationConfig,
) -> Result<CreationReport> {
    let mut noop = NoopProgress;
    create_archive_with_progress(output_path, sources, config, &mut noop)
}

/// Creates an archive with progress reporting.
///
/// Same as `create_archive` but accepts a `ProgressCallback` for
/// real-time progress updates during creation.
///
/// # Arguments
///
/// * `output_path` - Path to the output archive file
/// * `sources` - Source files and directories to include
/// * `config` - Creation configuration
/// * `progress` - Callback for progress updates
///
/// # Errors
///
/// Returns an error if:
/// - Cannot determine archive format
/// - Source files don't exist
/// - I/O operations fail
/// - Configuration is invalid
///
/// # Examples
///
/// ```no_run
/// use exarch_core::NoopProgress;
/// use exarch_core::create_archive_with_progress;
/// use exarch_core::creation::CreationConfig;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let config = CreationConfig::default();
/// let mut progress = NoopProgress;
/// let report = create_archive_with_progress(
///     "output.tar.gz",
///     &["src/", "Cargo.toml"],
///     &config,
///     &mut progress,
/// )?;
/// println!("Created archive with {} files", report.files_added);
/// # Ok(())
/// # }
/// ```
pub fn create_archive_with_progress<P: AsRef<Path>, Q: AsRef<Path>>(
    output_path: P,
    sources: &[Q],
    config: &CreationConfig,
    progress: &mut dyn ProgressCallback,
) -> Result<CreationReport> {
    let output = output_path.as_ref();

    // Determine format from extension or config
    let format = determine_creation_format(output, config)?;

    // Dispatch to format-specific creator with progress
    match format {
        ArchiveType::Tar => {
            crate::creation::tar::create_tar_with_progress(output, sources, config, progress)
        }
        ArchiveType::TarGz => {
            crate::creation::tar::create_tar_gz_with_progress(output, sources, config, progress)
        }
        ArchiveType::TarBz2 => {
            crate::creation::tar::create_tar_bz2_with_progress(output, sources, config, progress)
        }
        ArchiveType::TarXz => {
            crate::creation::tar::create_tar_xz_with_progress(output, sources, config, progress)
        }
        ArchiveType::TarZst => {
            crate::creation::tar::create_tar_zst_with_progress(output, sources, config, progress)
        }
        ArchiveType::Zip => {
            crate::creation::zip::create_zip_with_progress(output, sources, config, progress)
        }
        ArchiveType::SevenZ => Err(ExtractionError::InvalidArchive(
            "7z archive creation not yet supported".into(),
        )),
    }
}

/// Lists archive contents without extracting.
///
/// Returns a manifest containing metadata for all entries in the archive.
/// No files are written to disk during this operation.
///
/// # Arguments
///
/// * `archive_path` - Path to archive file
/// * `config` - Security configuration (quota limits apply)
///
/// # Errors
///
/// Returns error if:
/// - Archive file cannot be opened
/// - Archive format is unsupported or corrupted
/// - Quota limits exceeded (file count, total size)
///
/// # Examples
///
/// ```no_run
/// use exarch_core::SecurityConfig;
/// use exarch_core::list_archive;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let config = SecurityConfig::default();
/// let manifest = list_archive("archive.tar.gz", &config)?;
///
/// println!("Archive contains {} files", manifest.total_entries);
/// for entry in manifest.entries {
///     println!("{}: {} bytes", entry.path.display(), entry.size);
/// }
/// # Ok(())
/// # }
/// ```
pub fn list_archive<P: AsRef<Path>>(
    archive_path: P,
    config: &SecurityConfig,
) -> Result<ArchiveManifest> {
    crate::inspection::list_archive(archive_path, config)
}

/// Verifies archive integrity and security without extracting.
///
/// Performs comprehensive validation:
/// - Integrity checks (structure, checksums)
/// - Security checks (path traversal, zip bombs, CVEs)
/// - Policy checks (file types, permissions)
///
/// # Arguments
///
/// * `archive_path` - Path to archive file
/// * `config` - Security configuration for validation
///
/// # Errors
///
/// Returns error if:
/// - Archive file cannot be opened
/// - Archive is severely corrupted (cannot read structure)
///
/// Security violations are reported in `VerificationReport.issues`,
/// not as errors.
///
/// # Examples
///
/// ```no_run
/// use exarch_core::SecurityConfig;
/// use exarch_core::VerificationStatus;
/// use exarch_core::verify_archive;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let config = SecurityConfig::default();
/// let report = verify_archive("archive.tar.gz", &config)?;
///
/// if report.status == VerificationStatus::Pass {
///     println!("Archive is safe to extract");
/// } else {
///     eprintln!("Security issues found:");
///     for issue in report.issues {
///         eprintln!("  [{}] {}", issue.severity, issue.message);
///     }
/// }
/// # Ok(())
/// # }
/// ```
pub fn verify_archive<P: AsRef<Path>>(
    archive_path: P,
    config: &SecurityConfig,
) -> Result<VerificationReport> {
    crate::inspection::verify_archive(archive_path, config)
}

/// Determines archive format from output path or config.
fn determine_creation_format(output: &Path, config: &CreationConfig) -> Result<ArchiveType> {
    // If format explicitly set in config, use it
    if let Some(format) = config.format {
        return Ok(format);
    }

    // Auto-detect from extension
    detect_format(output)
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    #[test]
    fn test_extract_archive_nonexistent_file() {
        let config = SecurityConfig::default();
        let result = extract_archive(
            PathBuf::from("nonexistent_test.tar"),
            PathBuf::from("/tmp/test"),
            &config,
        );
        // Should fail because file doesn't exist
        assert!(result.is_err());
    }

    #[test]
    fn test_determine_creation_format_tar() {
        let config = CreationConfig::default();
        let path = PathBuf::from("archive.tar");
        let format = determine_creation_format(&path, &config).unwrap();
        assert_eq!(format, ArchiveType::Tar);
    }

    #[test]
    fn test_determine_creation_format_tar_gz() {
        let config = CreationConfig::default();
        let path = PathBuf::from("archive.tar.gz");
        let format = determine_creation_format(&path, &config).unwrap();
        assert_eq!(format, ArchiveType::TarGz);

        let path2 = PathBuf::from("archive.tgz");
        let format2 = determine_creation_format(&path2, &config).unwrap();
        assert_eq!(format2, ArchiveType::TarGz);
    }

    #[test]
    fn test_determine_creation_format_tar_bz2() {
        let config = CreationConfig::default();
        let path = PathBuf::from("archive.tar.bz2");
        let format = determine_creation_format(&path, &config).unwrap();
        assert_eq!(format, ArchiveType::TarBz2);
    }

    #[test]
    fn test_determine_creation_format_tar_xz() {
        let config = CreationConfig::default();
        let path = PathBuf::from("archive.tar.xz");
        let format = determine_creation_format(&path, &config).unwrap();
        assert_eq!(format, ArchiveType::TarXz);
    }

    #[test]
    fn test_determine_creation_format_tar_zst() {
        let config = CreationConfig::default();
        let path = PathBuf::from("archive.tar.zst");
        let format = determine_creation_format(&path, &config).unwrap();
        assert_eq!(format, ArchiveType::TarZst);
    }

    #[test]
    fn test_determine_creation_format_zip() {
        let config = CreationConfig::default();
        let path = PathBuf::from("archive.zip");
        let format = determine_creation_format(&path, &config).unwrap();
        assert_eq!(format, ArchiveType::Zip);
    }

    #[test]
    fn test_determine_creation_format_explicit() {
        let config = CreationConfig::default().with_format(Some(ArchiveType::TarGz));
        let path = PathBuf::from("archive.xyz");
        let format = determine_creation_format(&path, &config).unwrap();
        assert_eq!(format, ArchiveType::TarGz);
    }

    #[test]
    fn test_determine_creation_format_unknown() {
        let config = CreationConfig::default();
        let path = PathBuf::from("archive.rar");
        let result = determine_creation_format(&path, &config);
        assert!(result.is_err());
    }

    #[test]
    fn test_extract_archive_7z_not_implemented() {
        let dest = tempfile::TempDir::new().unwrap();
        let path = PathBuf::from("test.7z");

        let result = extract_archive(&path, dest.path(), &SecurityConfig::default());

        assert!(result.is_err());
    }

    #[test]
    fn test_create_archive_7z_not_supported() {
        let dest = tempfile::TempDir::new().unwrap();
        let archive_path = dest.path().join("output.7z");

        let result = create_archive(&archive_path, &[] as &[&str], &CreationConfig::default());

        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ExtractionError::InvalidArchive(_)
        ));
    }

    #[test]
    fn test_extract_archive_full_non_atomic_delegates_to_normal() {
        let dest = tempfile::TempDir::new().unwrap();
        let options = ExtractionOptions {
            atomic: false,
            skip_duplicates: true,
        };
        let result = extract_archive_full(
            PathBuf::from("nonexistent.tar.gz"),
            dest.path(),
            &SecurityConfig::default(),
            &options,
            &mut NoopProgress,
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_extract_archive_with_options_delegates() {
        let dest = tempfile::TempDir::new().unwrap();
        let options = ExtractionOptions {
            atomic: false,
            skip_duplicates: true,
        };
        let result = extract_archive_with_options(
            PathBuf::from("nonexistent.tar.gz"),
            dest.path(),
            &SecurityConfig::default(),
            &options,
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_extract_atomic_success() {
        use crate::create_archive;
        use crate::creation::CreationConfig;

        // Create a valid tar.gz to extract
        let archive_dir = tempfile::TempDir::new().unwrap();
        let archive_path = archive_dir.path().join("test.tar.gz");

        // Create a simple archive with one file
        let src_dir = tempfile::TempDir::new().unwrap();
        std::fs::write(src_dir.path().join("hello.txt"), b"hello world").unwrap();
        create_archive(&archive_path, &[src_dir.path()], &CreationConfig::default()).unwrap();

        let parent = tempfile::TempDir::new().unwrap();
        let output_dir = parent.path().join("extracted");

        let options = ExtractionOptions {
            atomic: true,
            skip_duplicates: true,
        };
        let result = extract_archive_with_options(
            &archive_path,
            &output_dir,
            &SecurityConfig::default(),
            &options,
        );

        assert!(result.is_ok());
        assert!(output_dir.exists());
        // No temp dir remnants
        let temp_entries: Vec<_> = std::fs::read_dir(parent.path()).unwrap().collect();
        assert_eq!(
            temp_entries.len(),
            1,
            "Expected only the output dir, found temp remnants"
        );
    }

    #[test]
    fn test_extract_atomic_failure_cleans_up() {
        let parent = tempfile::TempDir::new().unwrap();
        let output_dir = parent.path().join("extracted");

        let options = ExtractionOptions {
            atomic: true,
            skip_duplicates: true,
        };
        let result = extract_archive_with_options(
            PathBuf::from("nonexistent_archive.tar.gz"),
            &output_dir,
            &SecurityConfig::default(),
            &options,
        );

        assert!(result.is_err());
        // Output dir must not exist
        assert!(!output_dir.exists());
        // No temp dir remnants in parent
        let temp_entries: Vec<_> = std::fs::read_dir(parent.path()).unwrap().collect();
        assert!(
            temp_entries.is_empty(),
            "Temp dir not cleaned up after failure"
        );
    }

    #[test]
    fn test_extract_atomic_output_already_exists_fails() {
        use crate::create_archive;
        use crate::creation::CreationConfig;

        let parent = tempfile::TempDir::new().unwrap();
        let output_dir = parent.path().join("extracted");
        std::fs::create_dir_all(&output_dir).unwrap();
        // Create a file in output_dir so it's non-empty (rename over non-empty dir
        // fails on most OSes)
        std::fs::write(output_dir.join("existing.txt"), b"old content").unwrap();

        let archive_dir = tempfile::TempDir::new().unwrap();
        let archive_path = archive_dir.path().join("test.tar.gz");
        let src_dir = tempfile::TempDir::new().unwrap();
        std::fs::write(src_dir.path().join("new.txt"), b"new content").unwrap();
        create_archive(&archive_path, &[src_dir.path()], &CreationConfig::default()).unwrap();

        let options = ExtractionOptions {
            atomic: true,
            skip_duplicates: true,
        };
        let result = extract_archive_with_options(
            &archive_path,
            &output_dir,
            &SecurityConfig::default(),
            &options,
        );

        // Should fail with OutputExists or Io (platform dependent rename semantics)
        assert!(result.is_err());
        // Output dir must still have old content (not corrupted)
        assert!(output_dir.join("existing.txt").exists());
    }
}