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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
use crate::structs::File;
use super::messages::{error_messages, DryRunMessage, ProgressBar};
use std::fs;
pub mod sort {
use chrono::{DateTime, TimeZone, Utc, Local};
use crate::{error_messages, messages::{DryRunMessage, ProgressBar}, structs::{ConfigData, File}};
use std::{fs, path::Path, time::UNIX_EPOCH};
use walkdir::WalkDir;
#[cfg(test)]
mod tests {
use std::{env, path::Path};
use super::*;
#[test]
fn test_get_sequential_name() {
let parent_dir = File::from_pathbuf(&env::current_dir().expect("Failed to get current dir."));
let old_path = parent_dir.join(Path::new("testing/test.txt"));
let existing_path = parent_dir.join(Path::new("testing/test_1.txt"));
let new_path = parent_dir.join(Path::new("testing/test_2.txt"));
let mut vec = Vec::new();
vec.push(existing_path);
assert_eq!(new_path, get_sequential_name(&old_path, &vec));
}
#[test]
fn test_get_sorting_results() {
let source = File::from_pathbuf(&env::current_dir().expect("Failed to get current dir"));
let source = source.join(Path::new("testing"));
let target = source.join(Path::new("target"));
let date_format = "%Y";
let date_type = "m";
let preserve_name = true;
let exclude_type = ("txt", true);
let only_type = ("", false);
let results = get_sorting_results(
&source,
&target,
&date_format,
&date_type,
&preserve_name,
exclude_type,
only_type
);
let (old, new) = (&results.1, &results.2);
for i in 0..4 {
println!("Old: {:?}, New: {:?}", old[i].copy(), new[i].copy());
}
assert_eq!((old[0].copy(), new[0].copy()), (source.join(Path::new("test.jpg")), source.join(Path::new("target/2021/02/2021 test.jpg"))));
assert_eq!((old[1].copy(), new[1].copy()), (source.join(Path::new("test")), source.join(Path::new("target/2021/02/2021 test."))));
assert_eq!((old[2].copy(), new[2].copy()), (source.join(Path::new("files/test")), source.join(Path::new("target/2021/02/2021 test_2."))));
assert_eq!((old[3].copy(), new[3].copy()), (source.join(Path::new("test.png")), source.join(Path::new("target/2021/02/2021 test.png"))));
assert_eq!(results.0, 4);
assert_eq!(old.len(), 4);
assert_eq!(new.len(), 4);
}
#[test]
fn test_is_sortable() {
let path = File::new("file.txt");
assert!(is_sortable(&path, &(&"", false), &(&"txt", true)));
assert!(is_sortable(&path, &(&"txt", true), &(&"txt", true)));
assert!(is_sortable(&path, &(&"", false), &(&"", false)));
assert!(!is_sortable(&path, &(&"txt", true), &(&"", false)));
}
#[test]
fn test_is_type() {
let path = File::new("file.txt");
assert!(is_type(&path, &"txt"));
}
}
fn get_epoch_secs_access(path: &File) -> i64 {
let ctime_system = path.pathbuf.metadata().unwrap().accessed().expect("Failed to get atime");
let secs: i64 = ctime_system.duration_since(UNIX_EPOCH).unwrap().as_secs() as i64;
secs
}
fn get_epoch_secs_creation(path: &File) -> i64 {
let ctime_system = path.pathbuf.metadata().unwrap().created().expect("Failed to get ctime");
let secs: i64 = ctime_system.duration_since(UNIX_EPOCH).unwrap().as_secs() as i64;
secs
}
fn get_epoch_secs_modified(path: &File) -> i64 {
let ctime_system = path.pathbuf.metadata().unwrap().modified().expect("Failed to get mtime");
let secs: i64 = ctime_system.duration_since(UNIX_EPOCH).unwrap().as_secs() as i64;
secs
}
fn get_datetime(path: &File, date_type: &str) -> DateTime<Local> {
let secs: i64;
if date_type == "m" {
secs = get_epoch_secs_modified(path);
} else if date_type == "a" {
secs = get_epoch_secs_access(path);
} else {
secs = get_epoch_secs_creation(path);
}
let ctime = Utc.timestamp(secs, 0);
let mytime = Local.from_utc_datetime(&ctime.naive_utc());
mytime
}
fn get_new_date_path(
target: &File,
old_file: &File,
date_format: &str,
date_type: &str,
preserve_name: bool) -> File {
let ctime = get_datetime(old_file, &date_type);
let dir = target.join(Path::new(&ctime.format("%Y/%m/").to_string()));
let mut name_to_preserve = String::from("");
if preserve_name {
name_to_preserve = format!(
" {}",
old_file.file_stem()
);
}
let new_file = dir.join(Path::new(&format!(
"{}{}.{}",
&ctime.format(date_format).to_string(),
name_to_preserve,
old_file.extension()
)));
new_file
}
fn get_sequential_name(path: &File, vec: &Vec<File>) -> File {
let mut num = 2;
loop {
let mut new_pathbuf = path.to_path_buf();
new_pathbuf.set_file_name(&format!(
"{}_{}.{}",
path.pathbuf.file_stem().unwrap().to_str().unwrap(),
num,
path.pathbuf.extension().unwrap().to_str().unwrap()
));
let new_file = File::from_pathbuf(&new_pathbuf);
if !vec.contains(&new_file) {
return new_file;
}
num += 1;
}
}
fn get_sorting_results(
source: &File,
target: &File,
date_format: &str,
date_type: &str,
preserve_name: &bool,
exclude_type: (&str, bool),
only_type: (&str, bool)) -> (usize, Vec<File>, Vec<File>) {
let mut vec_old: Vec<File> = Vec::new();
let mut vec_new: Vec<File> = Vec::new();
let mut items_to_sort = 0;
for entry in WalkDir::new(source.to_string()) {
let entry = entry.unwrap();
if !entry.metadata().expect("Failed to get dir metadata").is_dir() {
if is_sortable(&File::from_path(entry.path()), &exclude_type, &only_type) {
items_to_sort += 1;
}
}
}
for entry in WalkDir::new(source.to_string()) {
let entry = entry.unwrap();
if !entry.metadata().expect("Failed to get dir metadata").is_dir() {
let path = File::from_path(entry.path());
if is_sortable(&File::from_path(entry.path()), &exclude_type, &only_type) {
let mut new_file = get_new_date_path(&target, &path, date_format, date_type, *preserve_name);
if vec_new.contains(&new_file) {
new_file = get_sequential_name(&new_file, &vec_new);
}
vec_old.push(path.copy());
vec_new.push(new_file);
}
}
}
(items_to_sort, vec_old, vec_new)
}
fn is_sortable(path: &File, exclude_type: &(&str, bool), only_type: &(&str, bool)) -> bool {
if is_type(path, only_type.0) && only_type.1 {
return true;
} else if !is_type(path, exclude_type.0) && !only_type.1 {
return true;
} else {
return false;
}
}
fn is_type(path: &File, types: &str) -> bool {
let mut to_return: bool = false;
for t in types.split("-") {
if path.extension() == t {
to_return = true;
}
}
to_return
}
pub fn sort_dry_run(
source: &File,
target: &File,
date_format: &str,
date_type: &str,
preserve_name: &bool,
exclude_type: (&str, bool),
only_type: (&str, bool)) {
let results = get_sorting_results(
source,
target,
date_format,
date_type,
preserve_name,
exclude_type,
only_type
);
for i in 0..results.0 {
println!("{}", DryRunMessage {
from_file: results.1[i].copy(),
to_file: results.2[i].copy(),
}.to_string());
}
}
pub fn sort(
source: &File,
target: &File,
date_format: &str,
date_type: &str,
preserve_name: &bool,
exclude_type: (&str, bool),
only_type: (&str, bool),
dry_run: bool) {
if dry_run {
sort_dry_run(
source,
target,
date_format,
date_type,
preserve_name,
exclude_type,
only_type
);
return;
}
let results = get_sorting_results(
source,
target,
date_format,
date_type,
preserve_name,
exclude_type,
only_type
);
let items_to_sort = results.0;
let mut items_sorted = 0;
let progress_bar = ProgressBar {
completed_message: String::from("Done."),
message: String::from("Sorting..."),
total: items_to_sort
};
for (old, new) in results.1.iter().zip(results.2.iter()) {
let old_file = old.pathbuf.as_path();
let new_file = new.pathbuf.as_path();
let dir = new_file.parent().expect("Failed to get parent dir.");
if !dir.exists() {
fs::create_dir_all(&dir).expect("Failed to create dirs.");
}
fs::rename(&old_file, &new_file).expect(
&error_messages::PathMoveFailedError {
source: &File::from_path(old_file),
target: &File::from_path(new_file),
}.to_string()
);
items_sorted += 1;
progress_bar.set_progress(items_sorted);
}
progress_bar.complete();
println!("Sucessfully sorted {} items by date into {}.", items_sorted, target.to_string());
}
pub fn sort_from_json(json: String, source: File, target: File, dry_run: bool) {
let data = ConfigData::from_json(&json);
let mut errors = false;
if !source.exists() {
println!("{}", error_messages::PathDoesNotExistError { path: &source }.to_string());
errors = true;
}
if !target.exists() {
println!("{}", error_messages::PathDoesNotExistError { path: &target }.to_string());
errors = true;
}
if errors { return }
let exclude_type: (&str, bool) = (&data.exclude_type.join("-"), data.exclude_type.len() > 0);
let only_type: (&str, bool) = (&data.only_type.join("-"), data.only_type.len() > 0);
if dry_run {
sort_dry_run(
&source,
&target,
data.date_format.as_str(),
data.date_type.as_str(),
&data.preserve_name,
exclude_type,
only_type
);
} else {
sort(
&source,
&target,
data.date_format.as_str(),
data.date_type.as_str(),
&data.preserve_name,
exclude_type,
only_type,
false
)
}
}
}
pub fn extract(source: &File, target: &File, dry_run: bool) {
let mut items_moved = 0;
if dry_run {
for entry in source.pathbuf.as_path().read_dir().expect("Failed to read dir.") {
let entry = entry.expect("Failed to get dir entry.");
let old_path = File::from_pathbuf(&entry.path());
let new_path = target.join_string(&old_path.file_name());
if &old_path == source || &old_path == target { continue }
println!("{}", DryRunMessage { from_file: old_path, to_file: new_path }.to_string());
}
return;
}
let mut items_to_move = 0;
for entry in source.pathbuf.as_path().read_dir().expect("Failed to read dir") {
let entry = entry.expect("Failed to get dir entry.");
let old_path = File::from_pathbuf(&entry.path());
if &old_path == source || &old_path == target { continue }
items_to_move += 1;
}
let progress_bar = ProgressBar {
completed_message: String::from("Completed."),
message: String::from("Extracting..."),
total: items_to_move,
};
for entry in source.pathbuf.as_path().read_dir().expect("Failed to read dir.") {
let entry = entry.expect("Failed to get dir entry.");
let old_path = File::from_pathbuf(&entry.path());
let new_path = target.join_string(&old_path.file_name());
if &old_path == source || &old_path == target { continue }
fs::rename(old_path.to_string(), new_path.to_string())
.expect(
&error_messages::PathMoveFailedError {
source: &old_path,
target: &new_path,
}.to_string()
);
items_moved += 1;
progress_bar.set_progress(items_moved);
}
progress_bar.complete();
println!("Successfully moved {} items to {}.", items_moved, target.to_string());
}