list: highlight directories (either coloring them or adding a /)

This commit is contained in:
Anton Hermann 2021-11-01 12:10:48 +01:00
parent 5421a5db77
commit e8f24b7178
4 changed files with 39 additions and 9 deletions

View File

@ -50,7 +50,10 @@ pub fn list_archive(reader: Box<dyn Read>) -> crate::Result<Vec<FileInArchive>>
for file in archive.entries()? {
let file = file?;
files.push(FileInArchive { path: file.path()?.into_owned() });
let path = file.path()?.into_owned();
let is_dir = file.header().entry_type().is_dir();
files.push(FileInArchive { path, is_dir });
}
Ok(files)

View File

@ -81,11 +81,14 @@ where
let mut files = vec![];
for idx in 0..archive.len() {
let file = archive.by_index(idx)?;
let path = match file.enclosed_name() {
Some(path) => path.to_owned(),
None => continue,
};
files.push(FileInArchive { path });
let is_dir = file.is_dir();
files.push(FileInArchive { path, is_dir });
}
Ok(files)
}

View File

@ -15,6 +15,9 @@ pub struct ListOptions {
pub struct FileInArchive {
/// The file path
pub path: PathBuf,
/// Whether this file is a directory
pub is_dir: bool,
}
/// Actually print the files
@ -24,12 +27,28 @@ pub fn list_files(archive: &Path, files: Vec<FileInArchive>, list_options: ListO
let tree: Tree = files.into_iter().collect();
tree.print();
} else {
for file in files {
println!("{}", file.path.display());
for FileInArchive { path, is_dir } in files {
print_entry(path.display(), is_dir);
}
}
}
fn print_entry(name: impl std::fmt::Display, is_dir: bool) {
use crate::utils::colors::*;
if is_dir {
// if colors are deactivated, print final / to mark directories
if BLUE.is_empty() {
println!("{}/", name);
} else {
println!("{}{}{}{}", *BLUE, *STYLE_BOLD, name, *ALL_RESET);
}
} else {
// not a dir -> just print the file name
println!("{}", name);
}
}
mod tree {
use super::FileInArchive;
use linked_hash_map::LinkedHashMap;
@ -99,11 +118,13 @@ mod tree {
false => TREE_FINAL_BRANCH,
};
if let Some(_file) = &self.file {
println!("{}{}{}", prefix, final_part, name);
} else {
println!("{}{}[{}]", prefix, final_part, name);
}
print!("{}{}", prefix, final_part);
let is_dir = match self.file {
Some(FileInArchive { is_dir, .. }) => is_dir,
None => true,
};
super::print_file(name, is_dir);
// Construct prefix for children, adding either a line if this isn't
// the last entry in the parent dir or empty space if it is.
prefix.push_str(match last {

View File

@ -102,6 +102,9 @@ pub mod colors {
color!(RED = "\u{1b}[38;5;9m");
color!(WHITE = "\u{1b}[38;5;15m");
color!(YELLOW = "\u{1b}[38;5;11m");
color!(STYLE_BOLD = "\u{1b}[1m");
color!(STYLE_RESET = "\u{1b}[0m");
color!(ALL_RESET = "\u{1b}[0;39m");
}
impl Bytes {