| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
use std::{ |
| 14 |
env::current_dir, |
| 15 |
path::{Path, PathBuf}, |
| 16 |
}; |
| 17 |
|
| 18 |
use async_zip::base::read::seek::ZipFileReader; |
| 19 |
use tokio::{ |
| 20 |
fs::{create_dir_all, File, OpenOptions}, |
| 21 |
io::BufReader, |
| 22 |
}; |
| 23 |
use tokio_util::compat::{TokioAsyncReadCompatExt, TokioAsyncWriteCompatExt}; |
| 24 |
|
| 25 |
#[tokio::main] |
| 26 |
async fn main() { |
| 27 |
let archive = File::open("example.zip").await.expect("Failed to open zip file"); |
| 28 |
let out_dir = current_dir().expect("Failed to get current working directory"); |
| 29 |
unzip_file(archive, &out_dir).await; |
| 30 |
} |
| 31 |
|
| 32 |
|
| 33 |
fn sanitize_file_path(path: &str) -> PathBuf { |
| 34 |
|
| 35 |
path.replace('\\', "/") |
| 36 |
|
| 37 |
.split('/') |
| 38 |
.map(sanitize_filename::sanitize) |
| 39 |
.collect() |
| 40 |
} |
| 41 |
|
| 42 |
|
| 43 |
async fn unzip_file(archive: File, out_dir: &Path) { |
| 44 |
let archive = BufReader::new(archive).compat(); |
| 45 |
let mut reader = ZipFileReader::new(archive).await.expect("Failed to read zip file"); |
| 46 |
for index in 0..reader.file().entries().len() { |
| 47 |
let entry = reader.file().entries().get(index).unwrap(); |
| 48 |
let path = out_dir.join(sanitize_file_path(entry.filename().as_str().unwrap())); |
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
let entry_is_dir = entry.dir().unwrap(); |
| 54 |
|
| 55 |
let mut entry_reader = reader.reader_without_entry(index).await.expect("Failed to read ZipEntry"); |
| 56 |
|
| 57 |
if entry_is_dir { |
| 58 |
|
| 59 |
if !path.exists() { |
| 60 |
create_dir_all(&path).await.expect("Failed to create extracted directory"); |
| 61 |
} |
| 62 |
} else { |
| 63 |
|
| 64 |
|
| 65 |
let parent = path.parent().expect("A file entry should have parent directories"); |
| 66 |
if !parent.is_dir() { |
| 67 |
create_dir_all(parent).await.expect("Failed to create parent directories"); |
| 68 |
} |
| 69 |
let writer = OpenOptions::new() |
| 70 |
.write(true) |
| 71 |
.create_new(true) |
| 72 |
.open(&path) |
| 73 |
.await |
| 74 |
.expect("Failed to create extracted file"); |
| 75 |
futures_lite::io::copy(&mut entry_reader, &mut writer.compat_write()) |
| 76 |
.await |
| 77 |
.expect("Failed to copy to extracted file"); |
| 78 |
|
| 79 |
|
| 80 |
} |
| 81 |
} |
| 82 |
} |