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
use std::fmt::Display;
use std::io::prelude::*;
use std::io::Write;

use crate::fm_error::FmResult;
use crate::impl_selectable_content;
use flate2::write::{DeflateEncoder, GzEncoder, ZlibEncoder};
use flate2::Compression;
use lzma::LzmaWriter;
use zip::write::FileOptions;

/// Different kind of compression methods
#[derive(Debug)]
pub enum CompressionMethod {
    ZIP,
    DEFLATE,
    GZ,
    ZLIB,
    LZMA,
}

impl Display for CompressionMethod {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::ZIP => write!(f, "ZIP:     archive.zip"),
            Self::DEFLATE => write!(f, "DEFLATE: archive.tar.gz"),
            Self::LZMA => write!(f, "LZMA:    archive.tar.xz"),
            Self::GZ => write!(f, "GZ:      archive.tar.gz"),
            Self::ZLIB => write!(f, "ZLIB:    archive.tar.xz"),
        }
    }
}
/// Holds a vector of CompressionMethod and a few methods to compress some files.
#[derive(Debug)]
pub struct Compresser {
    content: Vec<CompressionMethod>,
    pub index: usize,
}

impl Default for Compresser {
    fn default() -> Self {
        Self {
            content: vec![
                CompressionMethod::ZIP,
                CompressionMethod::LZMA,
                CompressionMethod::ZLIB,
                CompressionMethod::GZ,
                CompressionMethod::DEFLATE,
            ],
            index: 0,
        }
    }
}

impl Compresser {
    /// Archive the files with tar and compress them with the selected method.
    /// The compression method is chosen by the user.
    pub fn compress(&self, files: Vec<std::path::PathBuf>) -> FmResult<()> {
        let Some(selected) = self.selected() else { return Ok(()) };
        match selected {
            CompressionMethod::DEFLATE => Self::compress_deflate("archive.tar.gz", files),
            CompressionMethod::GZ => Self::compress_gzip("archive.tar.gz", files),
            CompressionMethod::ZLIB => Self::compress_zlib("archive.tar.xz", files),
            CompressionMethod::ZIP => Self::compress_zip("archive.zip", files),
            CompressionMethod::LZMA => Self::compress_lzma("archive.tar.xz", files),
        }
    }

    fn make_tar<W>(files: Vec<std::path::PathBuf>, mut archive: tar::Builder<W>) -> FmResult<()>
    where
        W: Write,
    {
        for file in files.iter() {
            if file.is_dir() {
                archive.append_dir_all(file, file)?;
            } else {
                archive.append_path(file)?;
            }
        }
        Ok(())
    }

    fn compress_gzip(archive_name: &str, files: Vec<std::path::PathBuf>) -> FmResult<()> {
        let compressed_file = std::fs::File::create(archive_name)?;
        let mut encoder = GzEncoder::new(compressed_file, Compression::default());

        // Create tar archive and compress files
        Self::make_tar(files, tar::Builder::new(&mut encoder))?;

        // Finish Gzip file
        encoder.finish()?;

        Ok(())
    }

    fn compress_deflate(archive_name: &str, files: Vec<std::path::PathBuf>) -> FmResult<()> {
        let compressed_file = std::fs::File::create(archive_name)?;
        let mut encoder = DeflateEncoder::new(compressed_file, Compression::default());

        // Create tar archive and compress files
        Self::make_tar(files, tar::Builder::new(&mut encoder))?;

        // Finish deflate file
        encoder.finish()?;

        Ok(())
    }

    fn compress_zlib(archive_name: &str, files: Vec<std::path::PathBuf>) -> FmResult<()> {
        let compressed_file = std::fs::File::create(archive_name)?;
        let mut encoder = ZlibEncoder::new(compressed_file, Compression::default());

        // Create tar archive and compress files
        Self::make_tar(files, tar::Builder::new(&mut encoder))?;

        // Finish zlib file
        encoder.finish()?;

        Ok(())
    }

    fn compress_lzma(archive_name: &str, files: Vec<std::path::PathBuf>) -> FmResult<()> {
        let compressed_file = std::fs::File::create(archive_name)?;
        let mut encoder = LzmaWriter::new_compressor(compressed_file, 6)?;

        // Create tar archive and compress files
        Self::make_tar(files, tar::Builder::new(&mut encoder))?;

        // Finish lzma file
        encoder.finish()?;

        Ok(())
    }

    fn compress_zip(archive_name: &str, files: Vec<std::path::PathBuf>) -> FmResult<()> {
        let archive = std::fs::File::create(archive_name).unwrap();
        let mut zip = zip::ZipWriter::new(archive);
        for file in files.iter() {
            zip.start_file(
                file.to_str().unwrap(),
                FileOptions::default().compression_method(zip::CompressionMethod::Bzip2),
            )?;
            let mut buffer = Vec::new();
            let mut content = std::fs::File::open(file)?;
            content.read_to_end(&mut buffer)?;
            zip.write_all(&buffer)?;
        }

        // Finish zip file
        zip.finish()?;
        Ok(())
    }
}

impl_selectable_content!(CompressionMethod, Compresser);