1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#[macro_use]
extern crate clap;
use clap::{Arg, App};
use colored::Colorize;
use std::path::{Path, PathBuf};
pub struct Config {
search_dir: PathBuf,
dirs: u64,
files: u64,
entries: u64
}
impl Default for Config {
fn default() -> Self {
Self {
search_dir: PathBuf::new(),
dirs: 0,
files: 0,
entries: 0
}
}
}
impl Config {
fn parse_arguments<'a>() -> clap::ArgMatches<'a> {
App::new(crate_name!())
.version(crate_version!())
.author(crate_authors!())
.about(crate_description!())
.arg(Arg::with_name("PATH")
.help("Sets the directory")
.required(true)
.index(1)
)
.get_matches()
}
pub fn new() -> Result<Config, String> {
let matches = Self::parse_arguments();
let mut search_dir = PathBuf::new();
if let Some(path) = matches.value_of("PATH") {
search_dir.push(path);
}
if search_dir.is_file() {
return Err(format!("error: sets the directory"));
}
if !search_dir.exists() {
return Err(format!("error: {} cannot find", search_dir.display()));
}
Ok( Config { search_dir, ..Config::default() } )
}
pub fn run(&mut self) {
for dir_entry in self.search_dir.read_dir().expect("cannot read dir") {
self.entries += 1;
if let Ok(entry) = dir_entry {
let entry_type = if entry.path().is_file() {
self.files += 1;
"file".green()
} else {
self.dirs += 1;
"dir ".cyan()
};
println!("{}: {} - {}", self.entries , entry_type , get_name(&entry.path()));
}
}
let dir_name = self.search_dir.as_path().to_str().unwrap().magenta();
let entries = self.entries.to_string().magenta();
println!("\ndir: {}, file: {}", self.dirs.to_string().cyan(), self.files.to_string().green());
println!("{} directory has {} entries.", dir_name, entries);
}
}
fn get_name(path: &Path) -> &str {
path.file_name().unwrap().to_str().unwrap()
}