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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
use clap::ArgMatches;
use colored::*;
use dialoguer::Input;
use regex::Regex;
use std::{
    cmp::Ordering,
    fs,
    path::{Path, PathBuf},
    process,
};

// Logging conventions:
//      Level:
//          Error = red
//          Info = green
//          Verbose = bright_black
//      Text:
//          Error = bright_red
//          Info = white
//          Verbose = blue
//      Data (paths, numbers, etc):
//          yellow

pub struct Arguments {
    pub path: PathBuf,
    pub logfile: bool,
    pub yes: bool,
    pub nro: usize,
    pub zeroes: usize,
    pub prefix: String,
    pub mode: String,
    pub ordering: String,
    pub ignore: Vec<usize>,
    pub file_extension: Regex,
    pub file_numbers_test: Regex,
    pub file_numbers: Regex,
}

impl From<ArgMatches> for Arguments {
    fn from(a: ArgMatches) -> Self {
        let path: PathBuf = {
            let folder: String = a.value_of_t_or_exit("folder");
            Path::new(&folder).to_owned()
        };
        let logfile = a.is_present("logfile");
        let yes = a.is_present("yes");

        let nro: usize = if a.is_present("nro") {
            a.value_of_t_or_exit("nro")
        } else {
            1
        };
        let zeroes: usize = if a.is_present("zeroes") {
            a.value_of_t_or_exit("zeroes")
        } else {
            7
        };
        let prefix: String = if a.is_present("prefix") {
            a.value_of_t_or_exit("prefix")
        } else {
            "".to_string()
        };
        let mode: String = if a.is_present("mode") {
            a.value_of_t_or_exit("mode")
        } else {
            "n".to_string()
        };
        let ordering: String = if a.is_present("ordering") {
            a.value_of_t_or_exit("ordering")
        } else {
            "a".to_string()
        };

        let ignore: Vec<usize> = if a.is_present("ignore") {
            a.values_of_t_or_exit("ignore")
        } else {
            vec![]
        };

        let file_extension =
            Regex::new(r"(?i)\.[0-9A-Z]+$").expect("Unable to create 'file_extension' regex");
        let file_numbers_test = Regex::new(format!(r"(?i)(^{}\d+)\.[0-9A-Z]+$", prefix).as_str())
            .expect("Unable to create 'file_numbers_test' regex");
        let file_numbers = Regex::new(&format!(r"(?i)(\d{{{}}})\.[0-9A-Z]+$", zeroes))
            .expect("Unable to create 'file_numbers' regex");

        Self {
            path,
            logfile,
            yes,
            nro,
            zeroes,
            prefix,
            mode,
            ordering,
            ignore,
            file_extension,
            file_numbers_test,
            file_numbers,
        }
    }
}

#[derive(Debug, PartialEq, PartialOrd, Clone, Copy)]
pub enum LogLevel {
    Verbose,
    Standard,
    Quiet,
}

impl LogLevel {
    pub fn is_verbose(&self) -> bool {
        matches!(self, LogLevel::Verbose)
    }

    pub fn is_standard(&self) -> bool {
        matches!(self, LogLevel::Standard)
    }

    pub fn is_quiet(&self) -> bool {
        matches!(self, LogLevel::Quiet)
    }
}

pub fn rename(args: Arguments, log_level: LogLevel) {
    if !args.path.exists() || !args.path.is_dir() {
        eprintln!(
            "{} {}",
            "[Error]:".red(),
            "Folder doesn't exists or is not a folder".bright_red()
        );
        process::exit(1);
    }

    // Get files
    if log_level.is_verbose() {
        println!("{} {}", "[Verbose]".bright_black(), "Checking files".blue());
    }
    let files: Vec<String> = {
        let mut ready: Vec<String> = Vec::new();
        let mut i: Vec<(String, u128)> = Vec::new();
        for file in args
            .path
            .read_dir()
            .expect("Unable to read path contents")
            .map(|x| x.unwrap())
        {
            if file.file_type().unwrap().is_dir() {
                continue;
            }
            let file_name = file
                .file_name()
                .into_string()
                .expect("Unable to read file name");
            let file_date: u128 =
                fs::metadata(format!("{:?}/{}", args.path, file_name).replace("\"", ""))
                    .unwrap()
                    .modified()
                    .unwrap()
                    .elapsed()
                    .unwrap()
                    .as_micros();
            i.push((file_name, file_date));
        }
        if args.ordering == "n" {
            // newest to oldest
            ready = order_by_date(i);
        } else if args.ordering == "o" {
            // oldest to newest
            ready = order_by_date(i).into_iter().rev().collect();
        } else if args.ordering == "z" {
            // Z-A
            for item in i {
                ready.push(item.0);
            }
            ready.sort();
            ready.reverse();
        } else {
            // A-Z
            for item in i {
                ready.push(item.0);
            }
            ready.sort();
        }
        ready
    };

    let total_nro: usize = files.len();

    // Get files to rename
    if log_level.is_verbose() {
        println!(
            "{} {}",
            "[Verbose]".bright_black(),
            "Generating file names".blue()
        );
    }
    let files_to_rename: Vec<(String, String)> = match args.mode.as_str() {
        "n" => normal_rename(files, total_nro, &args),
        "f" => number_fixing(files, &args, log_level),
        _ => panic!("Mode not found"),
    };

    if !files_to_rename.is_empty() {
        rename_files(files_to_rename, total_nro, &args, log_level);
    } else if !log_level.is_quiet() {
        println!(
            "{} {}",
            "[Info]:".green(),
            "Nothing to rename. Exiting...".white()
        )
    }
}

fn order_by_date(list: Vec<(String, u128)>) -> Vec<String> {
    let mut i: Vec<String> = Vec::new();
    let mut numbers: Vec<u128> = Vec::new();
    for item in &list {
        numbers.push(item.1);
    }
    numbers.sort_unstable();
    for number in numbers {
        i.push(
            list[list.iter().position(|x| x.1 == number).unwrap()]
                .0
                .to_owned(),
        );
    }
    i
}

fn normal_rename(files: Vec<String>, total_nro: usize, args: &Arguments) -> Vec<(String, String)> {
    // Aka mode 0
    // Rename only new files not following correct naming

    let mut files_to_rename: Vec<(String, String)> = Vec::new();
    let mut nro_to_skip: Vec<usize> = Vec::new();

    // Set numbers to skip by nro variable
    if args.nro != 1 {
        for nro in 1..args.nro {
            nro_to_skip.push(nro);
        }
    }

    // Ignore specific numbers
    if !args.ignore.is_empty() {
        nro_to_skip.extend(args.ignore.iter());
    }

    // Find what numbers to skip
    let mut sorted_files = files.clone();
    sorted_files.sort();
    for file in &sorted_files {
        match args.file_numbers.captures(file) {
            Some(i) => {
                let i_str = i.get(1).unwrap().as_str();
                let i_nro: usize = i_str.parse().unwrap();

                if (!i_nro > total_nro + (args.nro - 1)
                    && i_nro >= args.nro
                    && i_str.len() == args.zeroes)
                    && (i_nro == 1 || !nro_to_skip.is_empty() && nro_to_skip.contains(&(i_nro - 1)))
                {
                    nro_to_skip.push(i_nro);
                }
            }
            None => {
                continue;
            }
        };
    }
    // Find what to rename to what
    for (index, file) in files.iter().enumerate() {
        let mut index = index + args.nro;
        while nro_to_skip.contains(&index) {
            index += 1;
        }
        let ext = match args.file_extension.find(file) {
            Some(i) => i.as_str().to_string(),
            None => {
                eprintln!(
                    "{} {}{}{}",
                    "[Error]:".red(),
                    "Unable to get file extension of \"".bright_red(),
                    &file.yellow(),
                    "\" with regex".bright_red()
                );
                process::exit(1);
            }
        };
        if !args.file_numbers_test.is_match(file) {
            nro_to_skip.push(index);
            files_to_rename.push((
                file.to_owned(),
                format!("{}{}", generate_name(index, args.zeroes, &args.prefix), ext),
            ));
            continue;
        }

        let ii = match args.file_numbers.captures(file) {
            Some(i) => i.get(1).unwrap().as_str(),
            None => {
                nro_to_skip.push(index);
                files_to_rename.push((
                    file.to_owned(),
                    format!("{}{}", generate_name(index, args.zeroes, &args.prefix), ext),
                ));
                continue;
            }
        };

        if ii
            .parse::<usize>()
            .expect("Unable to turn regex string into usize")
            > total_nro + (args.nro - 1)
            || ii
                .parse::<usize>()
                .expect("Unable to turn regex string into usize")
                < args.nro
            || !ii.len() == args.zeroes
        {
            // the range needs to be the range of numbers to use in renaming
            nro_to_skip.push(index);
            files_to_rename.push((
                file.to_owned(),
                format!("{}{}", generate_name(index, args.zeroes, &args.prefix), ext),
            ));
        } else if !nro_to_skip.contains(
            &ii.parse::<usize>()
                .expect("Unable to turn regex string into usize"),
        ) {
            // it's named correclty, but it is not correct number
            nro_to_skip.push(index);
            files_to_rename.push((
                file.to_owned(),
                format!("{}{}", generate_name(index, args.zeroes, &args.prefix), ext),
            ));
            continue;
        } else {
            continue;
        }
    }

    files_to_rename
}

fn number_fixing(
    files: Vec<String>,
    args: &Arguments,
    log_level: LogLevel,
) -> Vec<(String, String)> {
    // Aka mode 1
    // Fix missing numbers, by moving numbers backwards.
    let mut files_to_rename: Vec<(String, String)> = Vec::new();
    let mut nros_missing: Vec<usize> = Vec::new();

    // Find all numbers
    let mut sorted_files = files.clone();
    sorted_files.sort();
    let nros: Vec<usize> = {
        let mut i: Vec<usize> = Vec::new();
        for file in &sorted_files {
            // Skip if no numbers found
            if !args.file_numbers_test.is_match(file) {
                continue;
            }
            match args.file_numbers.captures(file) {
                Some(j) => {
                    if j.get(1).unwrap().as_str().len() == args.zeroes {
                        i.push(j.get(1).unwrap().as_str().parse().unwrap());
                    }
                }
                None => {
                    continue;
                }
            };
        }
        // Ignore specific numbers
        if !args.ignore.is_empty() {
            i.extend(args.ignore.iter());
            i.sort_unstable();
        }
        i
    };

    // Findout what numbers are missing
    let mut offset: usize = 0;
    for (index, number) in nros.iter().enumerate() {
        let index = index + args.nro - offset;
        if *number < args.nro {
            offset += 1;
        } else if index != *number {
            nros_missing.push(index);
        }
    }
    // Create list what to rename to what
    if !nros_missing.is_empty() {
        // Add only already correclty named to the list
        let mut count = 0;
        for file in &files {
            if count >= nros_missing.len() {
                break;
            }
            if !args.file_numbers_test.is_match(file) {
                continue;
            }

            let ii = match args.file_numbers.captures(file) {
                Some(i) => i.get(1).unwrap().as_str().to_string(),
                None => {
                    eprintln!(
                        "{} {}{}{}",
                        "[Error]".red(),
                        "Unable to get numbers from \"".bright_red(),
                        &file.yellow(),
                        "\" with regex".bright_red()
                    );
                    process::exit(1);
                }
            };

            match ii.parse::<usize>().unwrap().cmp(&nros_missing[count]) {
                Ordering::Equal => {
                    count += 1;
                }
                Ordering::Less => {
                    continue;
                }
                _ => {
                    if ii.parse::<usize>().unwrap() < args.nro {
                        continue;
                    }
                    let ext = match args.file_extension.find(file) {
                        Some(i) => i.as_str().to_string(),
                        None => {
                            eprintln!(
                                "{} {}{}{}",
                                "[Error]:".red(),
                                "Unable to get file extension from \"".bright_red(),
                                &file.yellow(),
                                "\" with regex".bright_red()
                            );
                            process::exit(1);
                        }
                    };
                    files_to_rename.push((
                        file.to_owned(),
                        format!(
                            "{}{}",
                            generate_name(nros_missing[count], args.zeroes, &args.prefix),
                            ext
                        ),
                    ));
                    count += 1;
                }
            }
        }
        // Add missing files to the end
        // Get last file number
        let mut count: usize = match args
            .file_numbers
            .captures(&files_to_rename.last().unwrap().1)
        {
            Some(i) => {
                let i: usize = i.get(1).unwrap().as_str().parse().unwrap();
                i + 1
            }
            None => {
                eprintln!(
                    "{} {}{}{}",
                    "[Error]:".red(),
                    "Unable to get numbers from \"".bright_red(),
                    &files_to_rename.last().unwrap().1.yellow(),
                    "\" with regex".bright_red()
                );
                if !log_level.is_quiet() {
                    println!(
                        "{} {}",
                        "[Info]:".green(),
                        "Did you run normal mode first?".white()
                    );
                }
                process::exit(1);
            }
        };
        // Find files missing in files_to_rename list and add to end
        for file in &files {
            if !files_to_rename.iter().any(|i| &i.0 == file) {
                let nro: usize = match args.file_numbers.captures(file) {
                    Some(i) => i.get(1).unwrap().as_str().parse().unwrap(),
                    None => {
                        eprintln!(
                            "{} {}{}{}",
                            "[Error]:".red(),
                            "Unable to get numbers from \"".bright_red(),
                            &file.yellow(),
                            "\" with regex".bright_red()
                        );
                        if !log_level.is_quiet() {
                            println!(
                                "{} {}",
                                "[Info]:".green(),
                                "Did you run normal mode first?".white()
                            );
                        }
                        process::exit(1);
                    }
                };
                if nro >= count || nro >= args.nro {
                    continue;
                }
                let ext = match args.file_extension.find(file) {
                    Some(i) => i.as_str().to_string(),
                    None => {
                        eprintln!(
                            "{} {}{}{}",
                            "[Error]:".red(),
                            "Unable to get file extension from \"".bright_red(),
                            &file.yellow(),
                            "\" with regex".bright_red()
                        );
                        process::exit(1);
                    }
                };
                files_to_rename.push((
                    file.to_owned(),
                    format!("{}{}", generate_name(count, args.zeroes, &args.prefix), ext),
                ));
                count += 1;
            }
        }
    } else {
        if !log_level.is_quiet() {
            println!(
                "{} {}",
                "[Info]:".green(),
                "Nothing to rename. Exiting...".white()
            )
        }
        process::exit(0);
    }

    files_to_rename
}

fn rename_files(
    files_to_rename: Vec<(String, String)>,
    total_nro: usize,
    args: &Arguments,
    log_level: LogLevel,
) {
    // Check/Ask stuff
    if !args.yes {
        if !log_level.is_quiet() {
            println!("{} {}", "[Info]:".green(), "These will be renamed:".white());
            for file in &files_to_rename {
                println!("{}{}{}", file.0.yellow(), " -> ".white(), file.1.yellow());
            }
            println!("{:_<20}", "");
        }
        println!(
            "{}{}{}{}",
            "Renaming ".white(),
            format!("{}", files_to_rename.len()).yellow(),
            " of ".white(),
            format!("{}", total_nro).yellow(),
        );

        let y = Input::<String>::new()
            .with_prompt("Are you sure you want to rename [y/N]")
            .default("n".to_string())
            .show_default(false)
            .interact()
            .unwrap();

        if y.to_lowercase() != "y" {
            println!("{}", "Aborting".bright_red());
            process::exit(0);
        } else if !args.logfile {
            let y = Input::<String>::new()
                .with_prompt("Do you want to save a log file [y/N]")
                .default("n".to_string())
                .show_default(false)
                .interact()
                .unwrap();
            if y.to_lowercase() == "y" {
                create_log(&files_to_rename, &args.path);
            }
        } else {
            create_log(&files_to_rename, &args.path);
        }
    } else if args.logfile {
        create_log(&files_to_rename, &args.path);
    }

    if args.yes && log_level.is_verbose() {
        println!("{} {}", "[Verbose]:".bright_black(), "Renaming".blue());

        for file in &files_to_rename {
            println!("{}{}{}", file.0.yellow(), " -> ".blue(), file.1.yellow());
        }

        println!("{:_<20}", "");
        println!(
            "{}{}{}{}",
            "Renaming ".white(),
            format!("{}", files_to_rename.len()).yellow(),
            " of ".white(),
            format!("{}", total_nro).yellow(),
        );
    }

    // Rename files with prefix
    if log_level.is_verbose() {
        println!("{} {}", "[Verbose]".bright_black(), "Renaming files".blue());
    }
    for (index, file) in files_to_rename.iter().enumerate() {
        if let Err(e) = fs::rename(
            format!("{}/{}", args.path.display(), file.0),
            format!("{}/{}{}", args.path.display(), index, file.1),
        ) {
            eprintln!("{} {}", "[Error]:".red(), e.to_string().bright_red());
        }
    }
    // Rename files for real
    for (index, file) in files_to_rename.iter().enumerate() {
        if let Err(e) = fs::rename(
            format!("{}/{}{}", args.path.display(), index, file.1),
            format!("{}/{}", args.path.display(), file.1),
        ) {
            eprintln!("{} {}", "[Error]:".red(), e.to_string().bright_red());
        }
    }
}

fn generate_name(number: usize, zeroes: usize, prefix: &str) -> String {
    format!(
        "{pre}{:0<1$}{nu}",
        "",
        zeroes - number.to_string().len(),
        nu = number,
        pre = prefix
    )
}

fn create_log(files: &[(String, String)], path: &Path) {
    let text = {
        let mut i: String = String::new();
        for file in files {
            i += format!("{} -> {}\n", file.0, file.1).as_str();
        }
        i
    };

    let mut file_name: String = "rename.log".to_string();
    let mut count = 0;

    while Path::new(&format!("{}/{}", path.display(), file_name)).exists() {
        file_name = format!("rename.{}.log", count);
        count += 1;
    }
    let file_name = format!("{}/{}", path.display(), file_name);

    fs::write(file_name, text).expect("Unable to create a logfile");
}

#[cfg(test)]
mod tests;