aboutsummaryrefslogtreecommitdiffstats
path: root/src/archive.rs
blob: ca22d280d975eb97f3322dc3a4dc8d7b49642542 (plain)
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
use actix_web::http::ContentEncoding;
use libflate::gzip::Encoder;
use serde::Deserialize;
use std::path::Path;
use strum_macros::{Display, EnumIter, EnumString};
use tar::Builder;

use crate::errors::ContextualError;

/// Available compression methods
#[derive(Deserialize, Clone, Copy, EnumIter, EnumString, Display)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum CompressionMethod {
    /// Gzipped tarball
    TarGz,

    /// Regular tarball
    Tar,
}

impl CompressionMethod {
    pub fn extension(self) -> String {
        match self {
            CompressionMethod::TarGz => "tar.gz",
            CompressionMethod::Tar => "tar",
        }
        .to_string()
    }

    pub fn content_type(self) -> String {
        match self {
            CompressionMethod::TarGz => "application/gzip",
            CompressionMethod::Tar => "application/tar",
        }
        .to_string()
    }

    pub fn content_encoding(self) -> ContentEncoding {
        match self {
            CompressionMethod::TarGz => ContentEncoding::Gzip,
            CompressionMethod::Tar => ContentEncoding::Identity,
        }
    }

    pub fn create_archive<T, W>(
        self,
        dir: T,
        skip_symlinks: bool,
        out: W,
    ) -> Result<(), ContextualError>
    where
        T: AsRef<Path>,
        W: std::io::Write,
    {
        let dir = dir.as_ref();
        match self {
            CompressionMethod::TarGz => tar_gz(dir, skip_symlinks, out),
            CompressionMethod::Tar => tar_dir(dir, skip_symlinks, out),
        }
    }
}

fn tar_gz<W>(dir: &Path, skip_symlinks: bool, out: W) -> Result<(), ContextualError>
where
    W: std::io::Write,
{
    let mut out = Encoder::new(out).map_err(|e| ContextualError::IOError("GZIP".to_string(), e))?;

    tar_dir(dir, skip_symlinks, &mut out)?;

    out.finish()
        .into_result()
        .map_err(|e| ContextualError::IOError("GZIP finish".to_string(), e))?;

    Ok(())
}

fn tar_dir<W>(dir: &Path, skip_symlinks: bool, out: W) -> Result<(), ContextualError>
where
    W: std::io::Write,
{
    if let Some(inner_folder) = dir.file_name() {
        if let Some(directory) = inner_folder.to_str() {
            tar(dir, directory.to_string(), skip_symlinks, out).map_err(|e| {
                ContextualError::ArchiveCreationError("tarball".to_string(), Box::new(e))
            })
        } else {
            // https://doc.rust-lang.org/std/ffi/struct.OsStr.html#method.to_str
            Err(ContextualError::InvalidPathError(
                "Directory name contains invalid UTF-8 characters".to_string(),
            ))
        }
    } else {
        // https://doc.rust-lang.org/std/path/struct.Path.html#method.file_name
        Err(ContextualError::InvalidPathError(
            "Directory name terminates in \"..\"".to_string(),
        ))
    }
}

fn tar<W>(
    src_dir: &Path,
    inner_folder: String,
    skip_symlinks: bool,
    out: W,
) -> Result<(), ContextualError>
where
    W: std::io::Write,
{
    let mut tar_builder = Builder::new(out);

    tar_builder.follow_symlinks(!skip_symlinks);

    // Recursively adds the content of src_dir into the archive stream
    tar_builder
        .append_dir_all(inner_folder, src_dir)
        .map_err(|e| {
            ContextualError::IOError(
                format!(
                    "Failed to append the content of {} to the TAR archive",
                    src_dir.to_str().unwrap_or("file")
                ),
                e,
            )
        })?;

    // Finish the archive
    tar_builder.into_inner().map_err(|e| {
        ContextualError::IOError("Failed to finish writing the TAR archive".to_string(), e)
    })?;

    Ok(())
}