lsd/src/core.rs

90 lines
2.3 KiB
Rust
Raw Normal View History

2018-12-02 14:05:27 +00:00
use batch::Batch;
2018-12-02 16:22:51 +00:00
use display::Display;
2018-12-02 14:05:27 +00:00
use meta::Meta;
2018-11-24 14:43:04 +00:00
use std::path::Path;
use Options;
pub struct Core<'a> {
options: &'a Options,
}
impl<'a> Core<'a> {
pub fn new(options: &'a Options) -> Core<'a> {
2018-12-01 17:59:53 +00:00
Core { options }
}
2018-11-24 16:42:39 +00:00
pub fn run(&self, inputs: Vec<&str>) {
2018-12-02 16:22:51 +00:00
let display = Display::new(self.options);
let mut dirs = Vec::new();
let mut files = Vec::new();
for input in inputs {
let path = Path::new(input);
if path.is_dir() {
dirs.push(path);
} else {
if let Some(meta) = Meta::from_path(path) {
files.push(meta);
}
}
}
2018-12-02 14:05:27 +00:00
let print_folder_name: bool = dirs.len() + files.len() > 1;
2018-12-02 16:22:51 +00:00
if !files.is_empty() {
let mut file_batch = Batch::from(files);
file_batch.sort();
display.print_outputs(self.get_batch_outputs(&file_batch));
}
2018-12-02 14:05:27 +00:00
dirs.sort_unstable();
for dir in dirs {
2018-12-02 14:05:27 +00:00
if let Some(folder_batch) = self.list_folder_content(dir) {
if print_folder_name {
println!("\n{}:", dir.display())
}
2018-11-24 11:02:39 +00:00
2018-12-02 16:22:51 +00:00
display.print_outputs(self.get_batch_outputs(&folder_batch));
}
2018-11-24 16:42:39 +00:00
}
}
2018-12-02 16:22:51 +00:00
pub fn get_batch_outputs<'b>(&self, batch: &'b Batch) -> Vec<String> {
2018-11-24 16:42:39 +00:00
if self.options.display_long {
2018-12-02 16:22:51 +00:00
batch.get_long_output()
2018-11-24 16:42:39 +00:00
} else {
2018-12-02 16:22:51 +00:00
batch.get_short_output()
2018-11-24 16:42:39 +00:00
}
}
2018-12-02 14:05:27 +00:00
pub fn list_folder_content(&self, folder: &Path) -> Option<Batch> {
let mut metas: Vec<Meta> = Vec::new();
2018-11-24 11:02:39 +00:00
let dir = match folder.read_dir() {
Ok(dir) => dir,
Err(err) => {
println!("cannot open directory'{}': {}", folder.display(), err);
2018-12-02 14:05:27 +00:00
return None;
2018-11-24 11:02:39 +00:00
}
};
for entry in dir {
if let Ok(entry) = entry {
if let Some(meta) = Meta::from_path(entry.path().as_path()) {
if !meta.name.is_hidden() || self.options.display_all {
metas.push(meta);
}
}
}
}
2018-12-02 14:05:27 +00:00
let mut batch = Batch::from(metas);
batch.sort();
2018-12-02 14:05:27 +00:00
Some(batch)
}
}