diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 19:33:14 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 19:33:14 +0000 |
commit | 36d22d82aa202bb199967e9512281e9a53db42c9 (patch) | |
tree | 105e8c98ddea1c1e4784a60a5a6410fa416be2de /third_party/rust/zip/examples | |
parent | Initial commit. (diff) | |
download | firefox-esr-upstream.tar.xz firefox-esr-upstream.zip |
Adding upstream version 115.7.0esr.upstream/115.7.0esrupstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'third_party/rust/zip/examples')
-rw-r--r-- | third_party/rust/zip/examples/extract.rs | 64 | ||||
-rw-r--r-- | third_party/rust/zip/examples/extract_lorem.rs | 31 | ||||
-rw-r--r-- | third_party/rust/zip/examples/file_info.rs | 54 | ||||
-rw-r--r-- | third_party/rust/zip/examples/stdin_info.rs | 35 | ||||
-rw-r--r-- | third_party/rust/zip/examples/write_dir.rs | 125 | ||||
-rw-r--r-- | third_party/rust/zip/examples/write_sample.rs | 71 |
6 files changed, 380 insertions, 0 deletions
diff --git a/third_party/rust/zip/examples/extract.rs b/third_party/rust/zip/examples/extract.rs new file mode 100644 index 0000000000..3080716266 --- /dev/null +++ b/third_party/rust/zip/examples/extract.rs @@ -0,0 +1,64 @@ +use std::fs; +use std::io; + +fn main() { + std::process::exit(real_main()); +} + +fn real_main() -> i32 { + let args: Vec<_> = std::env::args().collect(); + if args.len() < 2 { + println!("Usage: {} <filename>", args[0]); + return 1; + } + let fname = std::path::Path::new(&*args[1]); + let file = fs::File::open(fname).unwrap(); + + let mut archive = zip::ZipArchive::new(file).unwrap(); + + for i in 0..archive.len() { + let mut file = archive.by_index(i).unwrap(); + let outpath = match file.enclosed_name() { + Some(path) => path.to_owned(), + None => continue, + }; + + { + let comment = file.comment(); + if !comment.is_empty() { + println!("File {i} comment: {comment}"); + } + } + + if (*file.name()).ends_with('/') { + println!("File {} extracted to \"{}\"", i, outpath.display()); + fs::create_dir_all(&outpath).unwrap(); + } else { + println!( + "File {} extracted to \"{}\" ({} bytes)", + i, + outpath.display(), + file.size() + ); + if let Some(p) = outpath.parent() { + if !p.exists() { + fs::create_dir_all(p).unwrap(); + } + } + let mut outfile = fs::File::create(&outpath).unwrap(); + io::copy(&mut file, &mut outfile).unwrap(); + } + + // Get and Set permissions + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + + if let Some(mode) = file.unix_mode() { + fs::set_permissions(&outpath, fs::Permissions::from_mode(mode)).unwrap(); + } + } + } + + 0 +} diff --git a/third_party/rust/zip/examples/extract_lorem.rs b/third_party/rust/zip/examples/extract_lorem.rs new file mode 100644 index 0000000000..bc50abe164 --- /dev/null +++ b/third_party/rust/zip/examples/extract_lorem.rs @@ -0,0 +1,31 @@ +use std::io::prelude::*; + +fn main() { + std::process::exit(real_main()); +} + +fn real_main() -> i32 { + let args: Vec<_> = std::env::args().collect(); + if args.len() < 2 { + println!("Usage: {} <filename>", args[0]); + return 1; + } + let fname = std::path::Path::new(&*args[1]); + let zipfile = std::fs::File::open(fname).unwrap(); + + let mut archive = zip::ZipArchive::new(zipfile).unwrap(); + + let mut file = match archive.by_name("test/lorem_ipsum.txt") { + Ok(file) => file, + Err(..) => { + println!("File test/lorem_ipsum.txt not found"); + return 2; + } + }; + + let mut contents = String::new(); + file.read_to_string(&mut contents).unwrap(); + println!("{contents}"); + + 0 +} diff --git a/third_party/rust/zip/examples/file_info.rs b/third_party/rust/zip/examples/file_info.rs new file mode 100644 index 0000000000..6a2adc58ed --- /dev/null +++ b/third_party/rust/zip/examples/file_info.rs @@ -0,0 +1,54 @@ +use std::fs; +use std::io::BufReader; + +fn main() { + std::process::exit(real_main()); +} + +fn real_main() -> i32 { + let args: Vec<_> = std::env::args().collect(); + if args.len() < 2 { + println!("Usage: {} <filename>", args[0]); + return 1; + } + let fname = std::path::Path::new(&*args[1]); + let file = fs::File::open(fname).unwrap(); + let reader = BufReader::new(file); + + let mut archive = zip::ZipArchive::new(reader).unwrap(); + + for i in 0..archive.len() { + let file = archive.by_index(i).unwrap(); + let outpath = match file.enclosed_name() { + Some(path) => path, + None => { + println!("Entry {} has a suspicious path", file.name()); + continue; + } + }; + + { + let comment = file.comment(); + if !comment.is_empty() { + println!("Entry {i} comment: {comment}"); + } + } + + if (*file.name()).ends_with('/') { + println!( + "Entry {} is a directory with name \"{}\"", + i, + outpath.display() + ); + } else { + println!( + "Entry {} is a file with name \"{}\" ({} bytes)", + i, + outpath.display(), + file.size() + ); + } + } + + 0 +} diff --git a/third_party/rust/zip/examples/stdin_info.rs b/third_party/rust/zip/examples/stdin_info.rs new file mode 100644 index 0000000000..a609916a09 --- /dev/null +++ b/third_party/rust/zip/examples/stdin_info.rs @@ -0,0 +1,35 @@ +use std::io::{self, Read}; + +fn main() { + std::process::exit(real_main()); +} + +fn real_main() -> i32 { + let stdin = io::stdin(); + let mut stdin_handle = stdin.lock(); + let mut buf = [0u8; 16]; + + loop { + match zip::read::read_zipfile_from_stream(&mut stdin_handle) { + Ok(Some(mut file)) => { + println!( + "{}: {} bytes ({} bytes packed)", + file.name(), + file.size(), + file.compressed_size() + ); + match file.read(&mut buf) { + Ok(n) => println!("The first {} bytes are: {:?}", n, &buf[0..n]), + Err(e) => println!("Could not read the file: {e:?}"), + }; + } + Ok(None) => break, + Err(e) => { + println!("Error encountered while reading zip: {e:?}"); + return 1; + } + } + } + + 0 +} diff --git a/third_party/rust/zip/examples/write_dir.rs b/third_party/rust/zip/examples/write_dir.rs new file mode 100644 index 0000000000..3b043528f4 --- /dev/null +++ b/third_party/rust/zip/examples/write_dir.rs @@ -0,0 +1,125 @@ +use std::io::prelude::*; +use std::io::{Seek, Write}; +use std::iter::Iterator; +use zip::result::ZipError; +use zip::write::FileOptions; + +use std::fs::File; +use std::path::Path; +use walkdir::{DirEntry, WalkDir}; + +fn main() { + std::process::exit(real_main()); +} + +const METHOD_STORED: Option<zip::CompressionMethod> = Some(zip::CompressionMethod::Stored); + +#[cfg(any( + feature = "deflate", + feature = "deflate-miniz", + feature = "deflate-zlib" +))] +const METHOD_DEFLATED: Option<zip::CompressionMethod> = Some(zip::CompressionMethod::Deflated); +#[cfg(not(any( + feature = "deflate", + feature = "deflate-miniz", + feature = "deflate-zlib" +)))] +const METHOD_DEFLATED: Option<zip::CompressionMethod> = None; + +#[cfg(feature = "bzip2")] +const METHOD_BZIP2: Option<zip::CompressionMethod> = Some(zip::CompressionMethod::Bzip2); +#[cfg(not(feature = "bzip2"))] +const METHOD_BZIP2: Option<zip::CompressionMethod> = None; + +#[cfg(feature = "zstd")] +const METHOD_ZSTD: Option<zip::CompressionMethod> = Some(zip::CompressionMethod::Zstd); +#[cfg(not(feature = "zstd"))] +const METHOD_ZSTD: Option<zip::CompressionMethod> = None; + +fn real_main() -> i32 { + let args: Vec<_> = std::env::args().collect(); + if args.len() < 3 { + println!( + "Usage: {} <source_directory> <destination_zipfile>", + args[0] + ); + return 1; + } + + let src_dir = &*args[1]; + let dst_file = &*args[2]; + for &method in [METHOD_STORED, METHOD_DEFLATED, METHOD_BZIP2, METHOD_ZSTD].iter() { + if method.is_none() { + continue; + } + match doit(src_dir, dst_file, method.unwrap()) { + Ok(_) => println!("done: {src_dir} written to {dst_file}"), + Err(e) => println!("Error: {e:?}"), + } + } + + 0 +} + +fn zip_dir<T>( + it: &mut dyn Iterator<Item = DirEntry>, + prefix: &str, + writer: T, + method: zip::CompressionMethod, +) -> zip::result::ZipResult<()> +where + T: Write + Seek, +{ + let mut zip = zip::ZipWriter::new(writer); + let options = FileOptions::default() + .compression_method(method) + .unix_permissions(0o755); + + let mut buffer = Vec::new(); + for entry in it { + let path = entry.path(); + let name = path.strip_prefix(Path::new(prefix)).unwrap(); + + // Write file or directory explicitly + // Some unzip tools unzip files with directory paths correctly, some do not! + if path.is_file() { + println!("adding file {path:?} as {name:?} ..."); + #[allow(deprecated)] + zip.start_file_from_path(name, options)?; + let mut f = File::open(path)?; + + f.read_to_end(&mut buffer)?; + zip.write_all(&buffer)?; + buffer.clear(); + } else if !name.as_os_str().is_empty() { + // Only if not root! Avoids path spec / warning + // and mapname conversion failed error on unzip + println!("adding dir {path:?} as {name:?} ..."); + #[allow(deprecated)] + zip.add_directory_from_path(name, options)?; + } + } + zip.finish()?; + Result::Ok(()) +} + +fn doit( + src_dir: &str, + dst_file: &str, + method: zip::CompressionMethod, +) -> zip::result::ZipResult<()> { + if !Path::new(src_dir).is_dir() { + return Err(ZipError::FileNotFound); + } + + let path = Path::new(dst_file); + let file = File::create(path).unwrap(); + + let walkdir = WalkDir::new(src_dir); + let it = walkdir.into_iter(); + + zip_dir(&mut it.filter_map(|e| e.ok()), src_dir, file, method)?; + + Ok(()) +} diff --git a/third_party/rust/zip/examples/write_sample.rs b/third_party/rust/zip/examples/write_sample.rs new file mode 100644 index 0000000000..2e45cb1eac --- /dev/null +++ b/third_party/rust/zip/examples/write_sample.rs @@ -0,0 +1,71 @@ +use std::io::prelude::*; +use zip::write::FileOptions; + +fn main() { + std::process::exit(real_main()); +} + +fn real_main() -> i32 { + let args: Vec<_> = std::env::args().collect(); + if args.len() < 2 { + println!("Usage: {} <filename>", args[0]); + return 1; + } + + let filename = &*args[1]; + match doit(filename) { + Ok(_) => println!("File written to {filename}"), + Err(e) => println!("Error: {e:?}"), + } + + 0 +} + +fn doit(filename: &str) -> zip::result::ZipResult<()> { + let path = std::path::Path::new(filename); + let file = std::fs::File::create(path).unwrap(); + + let mut zip = zip::ZipWriter::new(file); + + zip.add_directory("test/", Default::default())?; + + let options = FileOptions::default() + .compression_method(zip::CompressionMethod::Stored) + .unix_permissions(0o755); + zip.start_file("test/☃.txt", options)?; + zip.write_all(b"Hello, World!\n")?; + + zip.start_file("test/lorem_ipsum.txt", Default::default())?; + zip.write_all(LOREM_IPSUM)?; + + zip.finish()?; + Ok(()) +} + +const LOREM_IPSUM : &[u8] = b"Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tellus elit, tristique vitae mattis egestas, ultricies vitae risus. Quisque sit amet quam ut urna aliquet +molestie. Proin blandit ornare dui, a tempor nisl accumsan in. Praesent a consequat felis. Morbi metus diam, auctor in auctor vel, feugiat id odio. Curabitur ex ex, +dictum quis auctor quis, suscipit id lorem. Aliquam vestibulum dolor nec enim vehicula, porta tristique augue tincidunt. Vivamus ut gravida est. Sed pellentesque, dolor +vitae tristique consectetur, neque lectus pulvinar dui, sed feugiat purus diam id lectus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per +inceptos himenaeos. Maecenas feugiat velit in ex ultrices scelerisque id id neque. + +Phasellus sed nisi in augue sodales pulvinar ut et leo. Pellentesque eget leo vitae massa bibendum sollicitudin. Curabitur erat lectus, congue quis auctor sed, aliquet +bibendum est. Ut porta ultricies turpis at maximus. Cras non lobortis justo. Duis rutrum magna sed velit facilisis, et sagittis metus laoreet. Pellentesque quam ligula, +dapibus vitae mauris quis, dapibus cursus leo. Sed sit amet condimentum eros. Nulla vestibulum enim sit amet lorem pharetra, eu fringilla nisl posuere. Sed tristique non +nibh at viverra. Vivamus sed accumsan lacus, nec pretium eros. Mauris elementum arcu eu risus fermentum, tempor ullamcorper neque aliquam. Sed tempor in erat eu +suscipit. In euismod in libero in facilisis. Donec sagittis, odio et fermentum dignissim, risus justo pretium nibh, eget vestibulum lectus metus vel lacus. + +Quisque feugiat, magna ac feugiat ullamcorper, augue justo consequat felis, ut fermentum arcu lorem vitae ligula. Quisque iaculis tempor maximus. In quis eros ac tellus +aliquam placerat quis id tellus. Donec non gravida nulla. Morbi faucibus neque sed faucibus aliquam. Sed accumsan mattis nunc, non interdum justo. Cras vitae facilisis +leo. Fusce sollicitudin ultrices sagittis. Maecenas eget massa id lorem dignissim ultrices non et ligula. Pellentesque aliquam mi ac neque tempus ornare. Morbi non enim +vulputate quam ullamcorper finibus id non neque. Quisque malesuada commodo lorem, ut ornare velit iaculis rhoncus. Mauris vel maximus ex. + +Morbi eleifend blandit diam, non vulputate ante iaculis in. Donec pellentesque augue id enim suscipit, eget suscipit lacus commodo. Ut vel ex vitae elit imperdiet +vulputate. Nunc eu mattis orci, ut pretium sem. Nam vitae purus mollis ante tempus malesuada a at magna. Integer mattis lectus non luctus lobortis. In a cursus quam, +eget faucibus sem. + +Donec vitae condimentum nisi, non efficitur massa. Praesent sed mi in massa sollicitudin iaculis. Pellentesque a libero ultrices, sodales lacus eu, ornare dui. In +laoreet est nec dolor aliquam consectetur. Integer iaculis felis venenatis libero pulvinar, ut pretium odio interdum. Donec in nisi eu dolor varius vestibulum eget vel +nunc. Morbi a venenatis quam, in vehicula justo. Nam risus dui, auctor eu accumsan at, sagittis ac lectus. Mauris iaculis dignissim interdum. Cras cursus dapibus auctor. +Donec sagittis massa vitae tortor viverra vehicula. Mauris fringilla nunc eu lorem ultrices placerat. Maecenas posuere porta quam at semper. Praesent eu bibendum eros. +Nunc congue sollicitudin ante, sollicitudin lacinia magna cursus vitae. +"; |