Decompress files in parallel
[ouch.git] / src / archive / tar.rs
blob54f144f95c09aad958e9eac1c642b803109831bb
1 //! Contains Tar-specific building and unpacking functions
3 use std::{
4     env,
5     io::prelude::*,
6     path::{Path, PathBuf},
7     sync::mpsc::{self, Receiver},
8     thread,
9 };
11 use fs_err as fs;
12 use same_file::Handle;
13 use ubyte::ToByteUnit;
15 use crate::{
16     error::FinalError,
17     info,
18     list::FileInArchive,
19     utils::{self, EscapedPathDisplay, FileVisibilityPolicy},
20     warning,
23 /// Unpacks the archive given by `archive` into the folder given by `into`.
24 /// Assumes that output_folder is empty
25 pub fn unpack_archive(reader: Box<dyn Read>, output_folder: &Path, quiet: bool) -> crate::Result<usize> {
26     assert!(output_folder.read_dir().expect("dir exists").count() == 0);
27     let mut archive = tar::Archive::new(reader);
29     let mut files_unpacked = 0;
30     for file in archive.entries()? {
31         let mut file = file?;
33         file.unpack_in(output_folder)?;
35         // This is printed for every file in the archive and has little
36         // importance for most users, but would generate lots of
37         // spoken text for users using screen readers, braille displays
38         // and so on
39         if !quiet {
40             info!(
41                 inaccessible,
42                 "{:?} extracted. ({})",
43                 utils::strip_cur_dir(&output_folder.join(file.path()?)),
44                 file.size().bytes(),
45             );
47             files_unpacked += 1;
48         }
49     }
51     Ok(files_unpacked)
54 /// List contents of `archive`, returning a vector of archive entries
55 pub fn list_archive(
56     mut archive: tar::Archive<impl Read + Send + 'static>,
57 ) -> impl Iterator<Item = crate::Result<FileInArchive>> {
58     struct Files(Receiver<crate::Result<FileInArchive>>);
59     impl Iterator for Files {
60         type Item = crate::Result<FileInArchive>;
62         fn next(&mut self) -> Option<Self::Item> {
63             self.0.recv().ok()
64         }
65     }
67     let (tx, rx) = mpsc::channel();
68     thread::spawn(move || {
69         for file in archive.entries().expect("entries is only used once") {
70             let file_in_archive = (|| {
71                 let file = file?;
72                 let path = file.path()?.into_owned();
73                 let is_dir = file.header().entry_type().is_dir();
74                 Ok(FileInArchive { path, is_dir })
75             })();
76             tx.send(file_in_archive).unwrap();
77         }
78     });
80     Files(rx)
83 /// Compresses the archives given by `input_filenames` into the file given previously to `writer`.
84 pub fn build_archive_from_paths<W>(
85     input_filenames: &[PathBuf],
86     output_path: &Path,
87     writer: W,
88     file_visibility_policy: FileVisibilityPolicy,
89     quiet: bool,
90 ) -> crate::Result<W>
91 where
92     W: Write,
94     let mut builder = tar::Builder::new(writer);
95     let output_handle = Handle::from_path(output_path);
97     for filename in input_filenames {
98         let previous_location = utils::cd_into_same_dir_as(filename)?;
100         // Safe unwrap, input shall be treated before
101         let filename = filename.file_name().unwrap();
103         for entry in file_visibility_policy.build_walker(filename) {
104             let entry = entry?;
105             let path = entry.path();
107             // If the output_path is the same as the input file, warn the user and skip the input (in order to avoid compression recursion)
108             if let Ok(ref handle) = output_handle {
109                 if matches!(Handle::from_path(path), Ok(x) if &x == handle) {
110                     warning!(
111                         "The output file and the input file are the same: `{}`, skipping...",
112                         output_path.display()
113                     );
114                     continue;
115                 }
116             }
118             // This is printed for every file in `input_filenames` and has
119             // little importance for most users, but would generate lots of
120             // spoken text for users using screen readers, braille displays
121             // and so on
122             if !quiet {
123                 info!(inaccessible, "Compressing '{}'.", EscapedPathDisplay::new(path));
124             }
126             if path.is_dir() {
127                 builder.append_dir(path, path)?;
128             } else {
129                 let mut file = match fs::File::open(path) {
130                     Ok(f) => f,
131                     Err(e) => {
132                         if e.kind() == std::io::ErrorKind::NotFound && utils::is_symlink(path) {
133                             // This path is for a broken symlink
134                             // We just ignore it
135                             continue;
136                         }
137                         return Err(e.into());
138                     }
139                 };
140                 builder.append_file(path, file.file_mut()).map_err(|err| {
141                     FinalError::with_title("Could not create archive")
142                         .detail("Unexpected error while trying to read file")
143                         .detail(format!("Error: {err}."))
144                 })?;
145             }
146         }
147         env::set_current_dir(previous_location)?;
148     }
150     Ok(builder.into_inner()?)