1use anyhow::Context;
10use std::fs::{self, File};
11use std::io::{self, BufReader, BufWriter, Write};
12use std::path::{Path, PathBuf};
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum ArchiveFormat {
17 Tar,
18 TarGz,
19 TarZst,
20 TarBz2,
21 TarXz,
22 Zip,
23}
24
25impl ArchiveFormat {
26 pub fn from_output_path(path: &Path) -> Option<Self> {
29 let name = path.file_name()?.to_str()?.to_ascii_lowercase();
30 let f = if name.ends_with(".tar.gz") || name.ends_with(".tgz") {
31 Self::TarGz
32 } else if name.ends_with(".tar.zst") || name.ends_with(".tzst") {
33 Self::TarZst
34 } else if name.ends_with(".tar.bz2") || name.ends_with(".tbz2") {
35 Self::TarBz2
36 } else if name.ends_with(".tar.xz") || name.ends_with(".txz") {
37 Self::TarXz
38 } else if name.ends_with(".tar") {
39 Self::Tar
40 } else if name.ends_with(".zip") {
41 Self::Zip
42 } else {
43 return None;
44 };
45 Some(f)
46 }
47
48 pub fn label(&self) -> &'static str {
49 match self {
50 Self::Tar => "tar",
51 Self::TarGz => "tar.gz",
52 Self::TarZst => "tar.zst",
53 Self::TarBz2 => "tar.bz2",
54 Self::TarXz => "tar.xz",
55 Self::Zip => "zip",
56 }
57 }
58}
59
60pub fn pack_directory(
63 src_dir: &Path,
64 out_path: &Path,
65 format: ArchiveFormat,
66) -> anyhow::Result<()> {
67 let mut entries: Vec<(PathBuf, String)> = Vec::new();
68 for de in fs::read_dir(src_dir).with_context(|| format!("read spool dir {src_dir:?}"))? {
69 let path = de?.path();
70 if path.is_file() {
71 if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
72 entries.push((path.clone(), name.to_string()));
73 }
74 }
75 }
76 entries.sort_by(|a, b| a.1.cmp(&b.1));
77
78 let file = File::create(out_path).with_context(|| format!("create archive {out_path:?}"))?;
79
80 match format {
81 ArchiveFormat::Zip => write_zip(file, &entries),
82 _ => write_tar(file, &entries, format),
83 }
84}
85
86fn append_tar<W: Write>(inner: W, entries: &[(PathBuf, String)]) -> anyhow::Result<W> {
89 let mut builder = tar::Builder::new(inner);
90 for (path, name) in entries {
91 builder
92 .append_path_with_name(path, name)
93 .with_context(|| format!("add {name} to archive"))?;
94 }
95 Ok(builder.into_inner()?)
96}
97
98fn write_tar(
99 file: File,
100 entries: &[(PathBuf, String)],
101 format: ArchiveFormat,
102) -> anyhow::Result<()> {
103 let buf = BufWriter::new(file);
104 match format {
107 ArchiveFormat::Tar => {
108 let mut w = append_tar(buf, entries)?;
109 w.flush()?;
110 }
111 ArchiveFormat::TarGz => {
112 let enc = flate2::write::GzEncoder::new(buf, flate2::Compression::default());
113 append_tar(enc, entries)?.finish()?.flush()?;
114 }
115 ArchiveFormat::TarZst => {
116 let enc = zstd::stream::write::Encoder::new(buf, 3)?;
117 append_tar(enc, entries)?.finish()?.flush()?;
118 }
119 ArchiveFormat::TarBz2 => {
120 let enc = bzip2::write::BzEncoder::new(buf, bzip2::Compression::default());
121 append_tar(enc, entries)?.finish()?.flush()?;
122 }
123 ArchiveFormat::TarXz => {
124 let enc = xz2::write::XzEncoder::new(buf, 6);
125 append_tar(enc, entries)?.finish()?.flush()?;
126 }
127 ArchiveFormat::Zip => unreachable!("zip handled separately"),
128 }
129 Ok(())
130}
131
132fn write_zip(file: File, entries: &[(PathBuf, String)]) -> anyhow::Result<()> {
133 let mut zip = zip::ZipWriter::new(BufWriter::new(file));
135 let opts = zip::write::SimpleFileOptions::default()
136 .compression_method(zip::CompressionMethod::Deflated);
137 for (path, name) in entries {
138 zip.start_file(name.as_str(), opts)
139 .with_context(|| format!("add {name} to zip"))?;
140 let mut src = BufReader::new(File::open(path)?);
141 io::copy(&mut src, &mut zip)?;
142 }
143 zip.finish()?.flush()?;
144 Ok(())
145}
146
147#[cfg(test)]
148mod tests {
149 use super::*;
150 use std::io::Read;
151
152 fn spool_with(users: &[u8], orders: &[u8]) -> tempfile::TempDir {
153 let d = tempfile::TempDir::new().unwrap();
154 fs::write(d.path().join("users.sql"), users).unwrap();
155 fs::write(d.path().join("orders.sql"), orders).unwrap();
156 d
157 }
158
159 #[test]
160 fn test_format_detection() {
161 let cases = [
162 ("x.tar.gz", Some(ArchiveFormat::TarGz)),
163 ("x.tgz", Some(ArchiveFormat::TarGz)),
164 ("x.tar.zst", Some(ArchiveFormat::TarZst)),
165 ("x.tar.bz2", Some(ArchiveFormat::TarBz2)),
166 ("x.tar.xz", Some(ArchiveFormat::TarXz)),
167 ("x.tar", Some(ArchiveFormat::Tar)),
168 ("x.zip", Some(ArchiveFormat::Zip)),
169 ("output", None),
170 ("tables.d", None),
171 ];
172 for (name, want) in cases {
173 assert_eq!(
174 ArchiveFormat::from_output_path(Path::new(name)),
175 want,
176 "{name}"
177 );
178 }
179 }
180
181 #[test]
182 fn test_pack_tar_gz_roundtrip() {
183 let spool = spool_with(b"CREATE TABLE users;\n", b"CREATE TABLE orders;\n");
184 let out_dir = tempfile::TempDir::new().unwrap();
185 let out = out_dir.path().join("a.tar.gz");
186 pack_directory(spool.path(), &out, ArchiveFormat::TarGz).unwrap();
187
188 let dec = flate2::read::GzDecoder::new(File::open(&out).unwrap());
189 let mut ar = tar::Archive::new(dec);
190 let mut found = std::collections::BTreeMap::new();
191 for e in ar.entries().unwrap() {
192 let mut e = e.unwrap();
193 let name = e.path().unwrap().to_string_lossy().into_owned();
194 let mut s = String::new();
195 e.read_to_string(&mut s).unwrap();
196 found.insert(name, s);
197 }
198 assert_eq!(found.get("users.sql").unwrap(), "CREATE TABLE users;\n");
199 assert_eq!(found.get("orders.sql").unwrap(), "CREATE TABLE orders;\n");
200 }
201
202 #[test]
203 fn test_pack_zip_roundtrip() {
204 let spool = spool_with(b"CREATE TABLE users;\n", b"CREATE TABLE orders;\n");
205 let out_dir = tempfile::TempDir::new().unwrap();
206 let out = out_dir.path().join("a.zip");
207 pack_directory(spool.path(), &out, ArchiveFormat::Zip).unwrap();
208
209 let mut zip = zip::ZipArchive::new(File::open(&out).unwrap()).unwrap();
210 let mut names: Vec<String> = (0..zip.len())
211 .map(|i| zip.by_index(i).unwrap().name().to_string())
212 .collect();
213 names.sort();
214 assert_eq!(
215 names,
216 vec!["orders.sql".to_string(), "users.sql".to_string()]
217 );
218
219 let mut s = String::new();
220 zip.by_name("users.sql")
221 .unwrap()
222 .read_to_string(&mut s)
223 .unwrap();
224 assert_eq!(s, "CREATE TABLE users;\n");
225 }
226}