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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
extern crate crossbeam;
extern crate walkdir;
pub mod single_threaded;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::fs;
use self::crossbeam::sync::chase_lev;
use self::walkdir::WalkDir;
use regex::{RegexSet, Regex};
use std::path::PathBuf;
use colored::*;
use std::process::exit;
use utils::size;
use std::thread;
use error::*;
use types::FileSize;
use std::path::Path;
pub use walk_parallel::single_threaded::*;
pub enum Status<T> {
Done,
Data(T),
}
#[derive(Debug)]
pub struct Walk {
pub path: PathBuf,
gitignore: Option<RegexSet>,
hgignore: Option<RegexSet>,
darcs_boring: Option<RegexSet>,
excludes: Option<Regex>,
max_depth: Option<u8>,
threshold: Option<u64>,
start_depth: usize,
nproc: usize,
show_files: bool,
get_blocks: bool,
follow_symlinks: bool,
artifacts_only: bool,
}
impl Walk {
pub fn print_dir(w: Walk, total: Arc<AtomicU64>) -> () {
let excludes = match w.excludes {
Some(ref x) => Some(x),
_ => None,
};
let v = if excludes.is_some() || w.artifacts_only {
read_all(
&w.path,
(w.start_depth as u8),
w.max_depth,
excludes,
&w.gitignore,
false,
w.artifacts_only,
)
} else {
read_all_fast(&w.path, (w.start_depth as u8), w.max_depth)
};
let subdir_size = v.file_size.get();
total.fetch_add(subdir_size, Ordering::Relaxed);
let mut to_print = if let Some(m) = w.threshold {
subdir_size > m
} else {
true
};
if let Some(0) = w.max_depth {
to_print = false;
}
if to_print {
let mut v_filtered = v.filtered(w.threshold, !w.show_files, w.max_depth);
v_filtered.display_tree(w.path);
}
}
pub fn set_depth(&mut self, d: u8) -> () {
self.max_depth = Some(d);
}
pub fn set_regex(&mut self, r: Regex) -> () {
self.excludes = Some(r);
}
pub fn set_threshold(&mut self, n: u64) -> () {
self.threshold = Some(n);
}
pub fn with_files(&mut self) -> () {
self.show_files = true;
}
pub fn blocks(&mut self) -> () {
self.get_blocks = true;
}
pub fn artifacts_only(&mut self) -> () {
self.artifacts_only = true;
}
fn get_proc(&self) -> usize {
self.nproc
}
pub fn new(p: PathBuf, n: usize) -> Walk {
Walk {
path: p,
gitignore: None,
hgignore: None,
darcs_boring: None,
excludes: None,
max_depth: None,
threshold: None,
start_depth: 0,
nproc: n,
show_files: false,
get_blocks: false,
follow_symlinks: false,
artifacts_only: false,
}
}
fn bump_depth(&mut self) -> () {
self.start_depth += 1;
}
pub fn push_subdir(
w: &Walk,
worker: &mut chase_lev::Worker<Status<Walk>>,
total: Arc<AtomicU64>,
) {
let in_paths = &w.path;
if let Ok(paths) = fs::read_dir(in_paths) {
for p in paths {
let val = match p {
Ok(x) => x,
_ => {
eprintln!("{}: path error at {:?}.", "Error".red(), p);
exit(0x0001)
}
};
let exclude_check = if let Some(ref x) = w.excludes {
if let Some(r) = val.path().into_os_string().to_str() {
!x.is_match(r)
} else {
eprintln!(
"{}: ignoring invalid unicode at: {:?}",
"Warning".yellow(),
val.path().display()
);
true
}
} else {
true
};
if exclude_check {
match val.file_type() {
Ok(t) => {
if t.is_dir() {
let mut new_path = w.path.to_owned();
new_path.push(val.file_name());
let mut new_walk = Walk::new(new_path, w.get_proc());
if w.excludes.is_some() {
new_walk.set_regex(w.excludes.clone().unwrap());
}
if w.show_files {
new_walk.with_files();
}
new_walk.bump_depth();
if let Some(d) = w.max_depth {
new_walk.set_depth(d);
}
if let Some(b) = w.threshold {
new_walk.set_threshold(b);
}
worker.push(Status::Data(new_walk));
} else if t.is_file() {
if let Ok(l) = val.metadata() {
let size = size(&l, w.get_blocks);
total.fetch_add(size, Ordering::Relaxed);
if w.show_files && size != 0 {
let to_formatted = format!("{}", FileSize::new(size));
println!(
"{}\t {}",
&to_formatted.green(),
val.path().display()
);
}
} else {
eprintln!(
"{}: could not find filesize for file at {}.",
"Warning".yellow(),
val.path().display()
);
}
}
}
_ => {
eprintln!(
"{}: could not determine file type for: {}",
"Warning".yellow(),
val.path().display()
)
}
}
}
}
let iter = 0..(w.get_proc());
iter.map(|_| worker.push(Status::Done)).count();
}
else if !in_paths.exists() {
eprintln!(
"{}: path '{}' does not exist, or you do not have permission to enter.",
"Error".red(),
&in_paths.display()
);
}
else if !in_paths.is_dir() {
if w.artifacts_only {
eprintln!(
"{}: {} is not a directory; not searching for artifacts",
"Warning".yellow(),
&in_paths.display()
);
}
if let Ok(l) = in_paths.metadata() {
let size = size(&l, w.get_blocks);
let to_formatted = format!("{}", FileSize::new(size));
println!("{}\t {}", &to_formatted.green(), in_paths.display());
} else {
panic!("{}", Internal::IoError);
}
}
else {
eprintln!(
"{}: permission denied for directory: {}",
"Warning".yellow(),
&in_paths.display()
);
}
}
}
fn latex_log<P: AsRef<Path>>(p: P) -> bool {
lazy_static! {
static ref LOG: Regex =
Regex::new(r"\.log$")
.unwrap();
}
if LOG.is_match(&p.as_ref().to_string_lossy().to_string()) {
let mut parent = (&p.as_ref())
.parent()
.unwrap()
.to_string_lossy()
.to_string();
parent.push_str("/*.tex");
glob_exists(&parent)
} else {
false
}
}
pub fn clean_project_dirs<P: AsRef<Path>>(p: P, exclude: Option<Regex>, vimtags: bool) -> () {
lazy_static! {
static ref REGEX: Regex =
Regex::new(r"(\.(a|la|lo|o|ll|keter|bc|dyn_o|d|rlib|crate|hi|hc|dyn_hi|S|jsexe|webapp|js\.externs|ibc|toc|aux|fdb_latexmk|fls|egg-info|whl|js_a|js_hi|jld|ji|js_o|so.*|dump-.*|vmb|crx|orig|elmo|elmi|hspec-failures|pyc|mod|go\.(v|teak|xmldef)|p_hi|p_o|prof|hide-cache|ghc\.environment\..*-\d.\d.\d|tix|synctex\.gz)|tags)$")
.unwrap();
}
for dir in WalkDir::new(p)
.into_iter()
.filter_map(|e| e.ok())
.filter(|p| {
exclude.clone().map(|e| {
e.is_match(&p.path().to_string_lossy().to_string())
}) != Some(false)
})
.filter(|p| {
REGEX.is_match(&p.path().to_string_lossy().to_string()) ||
is_project_dir(
&p.path().to_string_lossy().to_string(),
&p.path()
.file_name()
.map(|x| x.to_string_lossy().to_string())
.unwrap_or("".to_string()),
) || latex_log(&p.path()) ||
((&p.path().to_string_lossy().to_string() == "tags") && vimtags)
})
{
if dir.file_type().is_file() {
fs::remove_file(dir.path()).unwrap_or(());
} else if dir.file_type().is_dir() {
fs::remove_dir_all(dir.path()).unwrap_or(());
}
}
}
pub fn print_parallel(w: Walk) -> () {
let val = AtomicU64::new(0);
let arc = Arc::new(val);
let arc_producer = arc.clone();
let arc_child = arc.clone();
let path_display = w.path.clone();
let (mut worker, stealer): (chase_lev::Worker<Status<Walk>>,
chase_lev::Stealer<Status<Walk>>) = chase_lev::deque();
let iter = 0..(&w.get_proc() - 1);
let spawn_workers = (&w.path).is_file();
let child_producer = thread::spawn(move || {
let arc_local = arc_producer.clone();
Walk::push_subdir(&w, &mut worker, arc_local.clone());
loop {
if let Some(p) = worker.try_pop() {
match p {
Status::Data(d) => Walk::print_dir(d, arc_local.clone()),
_ => break,
};
}
}
});
let mut threads = Vec::new();
for _ in iter {
let stealer_clone = stealer.clone();
let arc_local = arc_child.clone();
let child_consumer = thread::spawn(move || loop {
if let chase_lev::Steal::Data(p) = stealer_clone.steal() {
match p {
Status::Data(d) => Walk::print_dir(d, arc_local.clone()),
_ => break,
};
}
});
threads.push(child_consumer);
}
let _ = child_producer.join();
let _ = threads
.into_iter()
.map(|v| {
let result = v.join();
if let Ok(exit) = result {
exit
} else if let Err(e) = result {
panic!("{:?}", e)
}
})
.count();
let m = arc.load(Ordering::SeqCst);
let size = FileSize::new(m);
if size != FileSize::new(0) {
let to_formatted = format!("{}", size);
println!("{}\t {}", &to_formatted.green(), path_display.display());
}
}