notox 1.6.1

no toxic names anymore
Documentation
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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
//! notox is a tool to clean file names.
//!
//! ## Usage as a binary
//!
//! ```shell
//! # install notox
//! cargo install notox --locked
//! # then use it (dry-run by default)
//! notox .
//! # to rename the file
//! notox -d .
//! ```
//!
//! ## Usage as a library
//!
//! ```rust
//! use std::collections::HashSet;
//! use std::path::PathBuf;
//! use notox::{Notox, NotoxArgs, NotoxOutput};
//!
//! let paths: HashSet<PathBuf> = HashSet::from(["README.md".into(), "Cargo.toml".into()]);
//! let notox_args = NotoxArgs {
//!     dry_run: true, // change here
//!     // if using serde
//!     // output: NotoxOutput::JsonOutput {
//!     //    json: JsonOutput::JsonDefault,
//!     //    pretty: false,
//!     // },
//!     output: NotoxOutput::Quiet
//! };
//! let res = Notox::new(notox_args).run(&paths);
//! ```
//!
//! ## Usage as a library and printing the output
//!
//! ```rust
//! use std::collections::HashSet;
//! use std::path::PathBuf;
//! use notox::{Notox, NotoxArgs, NotoxOutput};
//!
//! let paths: HashSet<PathBuf> = HashSet::from(["README.md".into(), "Cargo.toml".into()]);
//! let notox_args = NotoxArgs {
//!     dry_run: true, // change here
//!     // if using serde
//!     // output: NotoxOutput::JsonOutput {
//!     //    json: JsonOutput::JsonDefault,
//!     //    pretty: false,
//!     // },
//!     output: NotoxOutput::Quiet
//! };
//! let notox_inst = Notox::new(notox_args);
//! let res = notox_inst.run(&paths);
//! notox_inst.print_output(res);
//! ```
//!
//! ## Coverage
//!
//! Coverage is available at [https://n4n5.dev/notox/coverage/](https://n4n5.dev/notox/coverage/)
//!

#![warn(clippy::all, rust_2018_idioms)]
#![deny(
    missing_docs,
    clippy::all,
    clippy::missing_docs_in_private_items,
    clippy::missing_errors_doc,
    clippy::missing_panics_doc,
    clippy::cargo,
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::pedantic
)]

use core::fmt;
use std::{
    collections::HashSet,
    ffi::{OsStr, OsString},
    path::{Path, PathBuf},
};

#[cfg(feature = "rayon")]
use rayon::{iter::Either, prelude::*};

/// Type of JSON output
#[cfg(feature = "serde")]
#[derive(Debug, Clone, PartialEq)]
pub enum JsonOutput {
    /// full json output
    JsonDefault,

    /// only errors in json output
    JsonOnlyError,
}

/// Type of output
#[derive(Debug, Clone, PartialEq)]
pub enum NotoxOutput {
    /// default verbose output
    Default,

    /// quiet output
    Quiet,

    /// json output type and pretty print flag
    #[cfg(feature = "serde")]
    JsonOutput {
        /// which kind of json output to use
        json: JsonOutput,
        /// whether to pretty print the json output
        pretty: bool,
    },
}

impl NotoxOutput {
    /// Check if the output is verbose
    #[must_use]
    pub fn is_verbose(&self) -> bool {
        matches!(self, NotoxOutput::Default)
    }
}

#[derive(Debug, Clone, PartialEq)]
/// Options for the program
pub struct NotoxArgs {
    /// if true, the program will not rename files
    pub dry_run: bool,

    /// which kind of json output to use
    pub output: NotoxOutput,
}

impl NotoxArgs {
    /// Create a new [`NotoxArgs`] instance with default values
    #[must_use]
    pub fn is_verbose(&self) -> bool {
        self.output.is_verbose()
    }
}

impl fmt::Display for NotoxArgs {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // We don't need to print output when
        // - it's Output::Quiet because it's quiet
        // - it's Output::JsonOutput because it's json
        // so, only one case is default
        write!(f, "NotoxArgs {{ dry_run: {} }}", self.dry_run)
    }
}

/// Contains information about a result of a single file
#[derive(Debug, PartialEq, Eq, Hash)]
pub enum PathChange {
    /// The path has not been changed
    Unchanged {
        /// The original path
        path: PathBuf,
    },
    /// The path has been changed
    Changed {
        /// The original path
        path: PathBuf,
        /// The modified path
        modified: PathBuf,
    },
    /// The path could not be changed
    ErrorRename {
        /// The original path
        path: PathBuf,
        /// The modified path
        modified: PathBuf,
        /// The error message
        error: String,
    },
    /// There was an error while processing the path
    Error {
        /// The original path
        path: PathBuf,
        /// The error message
        error: String,
    },
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for PathChange {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(serde::Deserialize)]
        struct Helper {
            /// Path string
            path: String,
            /// Modified string
            modified: Option<String>,
            /// Error string
            error: Option<String>,
        }

        let helper = Helper::deserialize(deserializer)?;

        let path = PathBuf::from(helper.path);
        match (helper.modified, helper.error) {
            (None, None) => Ok(PathChange::Unchanged { path }),
            (Some(modified), None) => Ok(PathChange::Changed {
                path,
                modified: PathBuf::from(modified),
            }),
            (Some(modified), Some(error)) => Ok(PathChange::ErrorRename {
                path,
                modified: PathBuf::from(modified),
                error,
            }),
            (None, Some(error)) => Ok(PathChange::Error { path, error }),
        }
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for PathChange {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeStruct;

        let mut state = serializer.serialize_struct("PathChange", 3)?;
        match self {
            PathChange::Unchanged { path } => {
                state.serialize_field("path", path)?;
                state.serialize_field("modified", &Option::<PathBuf>::None)?;
                state.serialize_field("error", &Option::<String>::None)?;
            }
            PathChange::Changed { path, modified } => {
                state.serialize_field("path", path)?;
                state.serialize_field("modified", &Some(modified))?;
                state.serialize_field("error", &Option::<String>::None)?;
            }
            PathChange::ErrorRename {
                path,
                modified,
                error,
            } => {
                state.serialize_field("path", path)?;
                state.serialize_field("modified", &Some(modified))?;
                state.serialize_field("error", &Some(error))?;
            }
            PathChange::Error { path, error } => {
                state.serialize_field("path", path)?;
                state.serialize_field("modified", &Option::<PathBuf>::None)?;
                state.serialize_field("error", &Some(error))?;
            }
        }
        state.end()
    }
}

/// Check if a vector of bytes is similar to a char
#[inline]
#[allow(clippy::too_many_lines)]
pub fn check_similar(curr_char: Option<char>, name_acc: &mut String, last_was_ascii: bool) -> bool {
    if let Some(one_char) = curr_char {
        match one_char {
            'A' | '' | '' | 'À' | 'Á' | 'Â' | '' | '' | '' | '' | 'Ã' | 'Ā' | 'Ă' | ''
            | '' | '' | '' | 'Ȧ' | 'Ǡ' | 'Ä' | 'Ǟ' | '' | 'Å' | 'Ǻ' | 'Ǎ' | 'Ȁ' | 'Ȃ' | ''
            | '' | '' | '' | 'Ą' | 'Ⱥ' | '' => name_acc.push('A'),
            '' => name_acc.push_str("AA"),
            'Æ' | 'Ǽ' | 'Ǣ' => {
                name_acc.push_str("AE");
            }
            '' => name_acc.push_str("AO"),
            '' => name_acc.push_str("AU"),
            '' | '' => name_acc.push_str("AV"),
            '' => name_acc.push_str("AY"),
            'B' | '' | '' | '' | '' | '' | 'Ƀ' | 'Ƃ' | 'Ɓ' => name_acc.push('B'),
            'C' | '' | '' | 'Ć' | 'Ĉ' | 'Ċ' | 'Č' | 'Ç' | '' | 'Ƈ' | 'Ȼ' | '' => {
                name_acc.push('C');
            }
            'D' | '' | '' | '' | 'Ď' | '' | '' | '' | '' | 'Đ' | 'Ƌ' | 'Ɗ' | 'Ɖ' | '' =>
            {
                name_acc.push('D');
            }
            'DZ' | 'DŽ' => name_acc.push_str("DZ"),
            'Dz' | 'Dž' => name_acc.push_str("Dz"),
            'E' | '' | '' | 'È' | 'É' | 'Ê' | '' | '' | '' | '' | '' | 'Ē' | '' | ''
            | 'Ĕ' | 'Ė' | 'Ë' | '' | 'Ě' | 'Ȅ' | 'Ȇ' | '' | '' | 'Ȩ' | '' | 'Ę' | '' | ''
            | 'Ɛ' | 'Ǝ' => name_acc.push('E'),
            'F' | '' | '' | '' | 'Ƒ' | '' => name_acc.push('F'),
            'G' | '' | '' | 'Ǵ' | 'Ĝ' | '' | 'Ğ' | 'Ġ' | 'Ǧ' | 'Ģ' | 'Ǥ' | 'Ɠ' | '' | ''
            | '' => name_acc.push('G'),
            'H' | '' | '' | 'Ĥ' | '' | '' | 'Ȟ' | '' | '' | '' | 'Ħ' | '' | '' | '' =>
            {
                name_acc.push('H');
            }
            'I' | '' | '' | 'Ì' | 'Í' | 'Î' | 'Ĩ' | 'Ī' | 'Ĭ' | 'İ' | 'Ï' | '' | '' | 'Ǐ'
            | 'Ȉ' | 'Ȋ' | '' | 'Į' | '' | 'Ɨ' => name_acc.push('I'),
            'J' | '' | '' | 'Ĵ' | 'Ɉ' => name_acc.push('J'),
            'K' | '' | '' | '' | 'Ǩ' | '' | 'Ķ' | '' | 'Ƙ' | '' | '' | '' | '' | '' =>
            {
                name_acc.push('K');
            }
            'L' | '' | '' | 'Ŀ' | 'Ĺ' | 'Ľ' | '' | '' | 'Ļ' | '' | '' | 'Ł' | 'Ƚ' | ''
            | '' | '' | '' | '' => name_acc.push('L'),
            'LJ' => name_acc.push_str("LJ"),
            'Lj' => name_acc.push_str("Lj"),
            'M' | '' | '' | '' | '' | '' | '' | 'Ɯ' => name_acc.push('M'),
            'N' | '' | '' | 'Ǹ' | 'Ń' | 'Ñ' | '' | 'Ň' | '' | 'Ņ' | '' | '' | 'Ƞ' | 'Ɲ'
            | '' | '' => name_acc.push('N'),
            'NJ' => name_acc.push_str("NJ"),
            'Nj' => name_acc.push_str("Nj"),
            'O' | '' | '' | 'Ò' | 'Ó' | 'Ô' | '' | '' | '' | '' | 'Õ' | '' | 'Ȭ' | ''
            | 'Ō' | '' | '' | 'Ŏ' | 'Ȯ' | 'Ȱ' | 'Ö' | 'Ȫ' | '' | 'Ő' | 'Ǒ' | 'Ȍ' | 'Ȏ' | 'Ơ'
            | '' | '' | '' | '' | '' | '' | '' | 'Ǫ' | 'Ǭ' | 'Ø' | 'Ǿ' | 'Ɔ' | 'Ɵ' | ''
            | '' => name_acc.push('O'),
            'Ƣ' => name_acc.push_str("OI"),
            '' => name_acc.push_str("OO"),
            'Ȣ' => name_acc.push_str("OU"),
            '\u{008C}' | 'Œ' => name_acc.push_str("OE"),
            '\u{009C}' | 'œ' => name_acc.push_str("oe"),
            'P' | '' | '' | '' | '' | 'Ƥ' | '' | '' | '' | '' => {
                name_acc.push('P');
            }
            'Q' | '' | '' | '' | '' | 'Ɋ' => name_acc.push('Q'),
            'R' | '' | '' | 'Ŕ' | '' | 'Ř' | 'Ȑ' | 'Ȓ' | '' | '' | 'Ŗ' | '' | 'Ɍ' | ''
            | '' | '' | '' => name_acc.push('R'),
            'S' | '' | '' | '' | 'Ś' | '' | 'Ŝ' | '' | 'Š' | '' | '' | '' | 'Ș' | 'Ş'
            | '' | '' | '' => name_acc.push('S'),
            'T' | '' | '' | '' | 'Ť' | '' | 'Ț' | 'Ţ' | '' | '' | 'Ŧ' | 'Ƭ' | 'Ʈ' | 'Ⱦ'
            | '' => name_acc.push('T'),
            '' => name_acc.push_str("TZ"),
            'U' | '' | '' | 'Ù' | 'Ú' | 'Û' | 'Ũ' | '' | 'Ū' | '' | 'Ŭ' | 'Ü' | 'Ǜ' | 'Ǘ'
            | 'Ǖ' | 'Ǚ' | '' | 'Ů' | 'Ű' | 'Ǔ' | 'Ȕ' | 'Ȗ' | 'Ư' | '' | '' | '' | '' | ''
            | '' | '' | 'Ų' | '' | '' | 'Ʉ' => name_acc.push('U'),
            'V' | '' | '' | '' | '' | 'Ʋ' | '' | 'Ʌ' => name_acc.push('V'),
            '' => name_acc.push_str("VY"),
            'W' | '' | '' | '' | '' | 'Ŵ' | '' | '' | '' | '' => {
                name_acc.push('W');
            }
            'X' | '' | '' | '' | '' => name_acc.push('X'),
            'Y' | '' | '' | '' | 'Ý' | 'Ŷ' | '' | 'Ȳ' | '' | 'Ÿ' | '' | '' | 'Ƴ' | 'Ɏ'
            | '' => name_acc.push('Y'),
            'Z' | '' | '' | 'Ź' | '' | 'Ż' | 'Ž' | '' | '' | 'Ƶ' | 'Ȥ' | 'Ɀ' | '' | '' =>
            {
                name_acc.push('Z');
            }
            'a' | '' | '' | '' | 'à' | 'á' | 'â' | '' | '' | '' | '' | 'ã' | 'ā' | 'ă'
            | '' | '' | '' | '' | 'ȧ' | 'ǡ' | 'ä' | 'ǟ' | '' | 'å' | 'ǻ' | 'ǎ' | 'ȁ' | 'ȃ'
            | '' | '' | '' | '' | 'ą' | '' | 'ɐ' => name_acc.push('a'),
            '' => name_acc.push_str("aa"),
            'æ' | 'ǽ' | 'ǣ' => name_acc.push_str("ae"),
            '' => name_acc.push_str("ao"),
            '' => name_acc.push_str("au"),
            '' | '' => name_acc.push_str("av"),
            '' => name_acc.push_str("ay"),
            'b' | '' | '' | '' | '' | '' | 'ƀ' | 'ƃ' | 'ɓ' | 'þ' => {
                name_acc.push('b');
            }
            'c' | '' | '' | 'ć' | 'ĉ' | 'ċ' | 'č' | 'ç' | '' | 'ƈ' | 'ȼ' | '' | '' =>
            {
                name_acc.push('c');
            }
            'd' | '' | '' | '' | 'ď' | '' | '' | '' | '' | 'đ' | 'ƌ' | 'ɖ' | 'ɗ' | '' =>
            {
                name_acc.push('d');
            }
            'dz' | 'dž' => name_acc.push_str("dz"),
            'e' | '' | '' | 'è' | 'é' | 'ê' | '' | 'ế' | '' | '' | '' | 'ē' | '' | ''
            | 'ĕ' | 'ė' | 'ë' | '' | 'ě' | 'ȅ' | 'ȇ' | '' | '' | 'ȩ' | '' | 'ę' | '' | ''
            | 'ɇ' | 'ɛ' | 'ǝ' => name_acc.push('e'),
            'f' | '' | '' | '' | 'ƒ' | '' => name_acc.push('f'),
            'g' | '' | '' | 'ǵ' | 'ĝ' | '' | 'ğ' | 'ġ' | 'ǧ' | 'ģ' | 'ǥ' | 'ɠ' | '' | ''
            | '' => name_acc.push('g'),
            'h' | '' | '' | 'ĥ' | '' | '' | 'ȟ' | '' | '' | '' | '' | 'ħ' | '' | ''
            | 'ɥ' => name_acc.push('h'),
            'ƕ' => name_acc.push_str("hv"),
            'i' | '' | '' | 'ì' | 'í' | 'î' | 'ĩ' | 'ī' | 'ĭ' | 'ï' | '' | '' | 'ǐ' | 'ȉ'
            | 'ȋ' | '' | 'į' | '' | 'ɨ' | 'ı' => name_acc.push('i'),
            'j' | '' | '' | 'ĵ' | 'ǰ' | 'ɉ' => name_acc.push('j'),
            'k' | '' | '' | '' | 'ǩ' | '' | 'ķ' | '' | 'ƙ' | '' | '' | '' | '' | '' =>
            {
                name_acc.push('k');
            }
            'l' | '' | '' | 'ŀ' | 'ĺ' | 'ľ' | '' | '' | 'ļ' | '' | '' | 'ſ' | 'ł' | 'ƚ'
            | 'ɫ' | '' | '' | '' | '' => name_acc.push('l'),
            'lj' => name_acc.push_str("lj"),
            'm' | '' | '' | 'ḿ' | '' | '' | 'ɱ' | 'ɯ' => name_acc.push('m'),
            'n' | '' | '' | 'ǹ' | 'ń' | 'ñ' | '' | 'ň' | '' | 'ņ' | '' | '' | 'ƞ' | 'ɲ'
            | 'ʼn' | '' | '' => name_acc.push('n'),
            'nj' => name_acc.push_str("nj"),
            'o' | '' | '' | 'ò' | 'ó' | 'ô' | '' | '' | '' | '' | 'õ' | '' | 'ȭ' | ''
            | 'ō' | '' | '' | 'ŏ' | 'ȯ' | 'ȱ' | 'ö' | 'ȫ' | '' | 'ő' | 'ǒ' | 'ȍ' | 'ȏ' | 'ơ'
            | '' | '' | '' | '' | '' | '' | '' | 'ǫ' | 'ǭ' | 'ø' | 'ǿ' | 'ɔ' | '' | ''
            | 'ɵ' => name_acc.push('o'),
            'ƣ' => name_acc.push_str("oi"),
            'ȣ' => name_acc.push_str("ou"),
            '' => name_acc.push_str("oo"),
            'p' | '' | '' | '' | '' | 'ƥ' | '' | '' | '' | '' => {
                name_acc.push('p');
            }
            'q' | '' | '' | 'ɋ' | '' | '' => name_acc.push('q'),
            'r' | '' | '' | 'ŕ' | '' | 'ř' | 'ȑ' | 'ȓ' | '' | '' | 'ŗ' | '' | 'ɍ' | 'ɽ'
            | '' | '' | '' => name_acc.push('r'),
            's' | '' | '' | 'ß' | 'ś' | '' | 'ŝ' | '' | 'š' | '' | '' | '' | 'ș' | 'ş'
            | 'ȿ' | '' | '' | '' => name_acc.push('s'),
            't' | '' | '' | '' | '' | 'ť' | '' | 'ț' | 'ţ' | '' | '' | 'ŧ' | 'ƭ' | 'ʈ'
            | '' | '' => name_acc.push('t'),
            '' => name_acc.push_str("tz"),
            'u' | '' | '' | 'ù' | 'ú' | 'û' | 'ũ' | '' | 'ū' | '' | 'ŭ' | 'ü' | 'ǜ' | 'ǘ'
            | 'ǖ' | 'ǚ' | '' | 'ů' | 'ű' | 'ǔ' | 'ȕ' | 'ȗ' | 'ư' | '' | '' | '' | '' | ''
            | '' | '' | 'ų' | '' | '' | 'ʉ' => name_acc.push('u'),
            'v' | '' | '' | '' | 'ṿ' | 'ʋ' | '' | 'ʌ' => name_acc.push('v'),
            '' => name_acc.push_str("vy"),
            'w' | '' | '' | '' | '' | 'ŵ' | '' | '' | '' | '' | '' => {
                name_acc.push('w');
            }
            'x' | '' | '' | '' | '' => name_acc.push('x'),
            'y' | '' | '' | '' | 'ý' | 'ŷ' | '' | 'ȳ' | '' | 'ÿ' | '' | '' | '' | 'ƴ'
            | 'ɏ' | 'ỿ' => name_acc.push('y'),
            'z' | '' | '' | 'ź' | '' | 'ż' | 'ž' | '' | '' | 'ƶ' | 'ȥ' | 'ɀ' | '' | '' =>
            {
                name_acc.push('z');
            }
            '' => {
                name_acc.push('-');
                return false;
            }
            '\u{0300}'..='\u{036F}' | '\u{1AB0}'..='\u{1AFF}' | '\u{1DC0}'..='\u{1DFF}' => {}
            _ => {
                if last_was_ascii {
                    name_acc.push('_');
                }
                return false;
            }
        }
        return true;
    }
    last_was_ascii
}

/// Convert four bytes to a u32
#[inline]
#[must_use]
pub fn convert_four_to_u32(
    first_byte: u8,
    second_byte: u8,
    third_byte: u8,
    fourth_byte: u8,
) -> u32 {
    ((u32::from(first_byte) & 0b0000_0111) << 18)
        | ((u32::from(second_byte) & 0b0011_1111) << 12)
        | ((u32::from(third_byte) & 0b0011_1111) << 6)
        | (u32::from(fourth_byte) & 0b0011_1111)
}

/// Convert three bytes to a u32
#[inline]
#[must_use]
pub fn convert_three_to_u32(first_byte: u8, second_byte: u8, third_byte: u8) -> u32 {
    ((u32::from(first_byte) & 0b0001_1111) << 12)
        | ((u32::from(second_byte) & 0b0011_1111) << 6)
        | (u32::from(third_byte) & 0b0011_1111)
}

/// Convert two bytes to a u32
#[inline]
#[must_use]
pub fn convert_two_to_u32(first_byte: u8, second_byte: u8) -> u32 {
    ((u32::from(first_byte) & 0b0001_1111) << 6) | (u32::from(second_byte) & 0b0011_1111)
}

/// Clean a name
#[inline]
fn clean_name(path: &OsStr, _options: &NotoxArgs) -> OsString {
    const MINUS: char = '-'; // 45
    const DOT: char = '.'; // 46

    // for each byte of the path if it's not ascii, replace it with _
    let mut new_name = String::new();
    let mut vec_grapheme: [u8; 4] = [0; 4];
    let mut last_was_ascii = false;
    let mut idx_grapheme = 0;
    for byte in path.as_encoded_bytes() {
        // eprintln!("{} {} {}", byte, *byte as char, last_was_ascii);
        if idx_grapheme == 0 && *byte < 128 {
            match byte {
                45 => {
                    // - Hyphen-minus
                    if last_was_ascii {
                        new_name.push(MINUS);
                        last_was_ascii = false;
                    } else {
                        match new_name.pop() {
                            Some(MINUS | '_' | DOT) | None => {
                                // add or re-add the minus
                                new_name.push(MINUS);
                            }
                            Some(last_char) => {
                                new_name.push(last_char);
                                new_name.push(MINUS);
                            }
                        }
                    }
                }
                46 => {
                    // . (dot)
                    if last_was_ascii {
                        new_name.push(DOT);
                        last_was_ascii = false;
                    } else {
                        match new_name.pop() {
                            Some(DOT | '_' | MINUS) | None => {
                                // add or re-add the dot
                                new_name.push(DOT);
                            }
                            Some(last_char) => {
                                new_name.push(last_char);
                                new_name.push(DOT);
                            }
                        }
                    }
                }
                0..=44 | 47 | 58..=64 | 91..=96 | 123..=127 => {
                    // 47 is a slash
                    if last_was_ascii {
                        new_name.push('_');
                        last_was_ascii = false;
                    }
                }
                _ => {
                    new_name.push(*byte as char);
                    last_was_ascii = true;
                }
            }
            idx_grapheme = 0;
        } else {
            vec_grapheme[idx_grapheme] = *byte;
            idx_grapheme += 1;
            let first_byte = vec_grapheme[0];
            if first_byte >= 240 && idx_grapheme == 4 {
                // four bytes grapheme
                let curr_char = std::char::from_u32(convert_four_to_u32(
                    vec_grapheme[0],
                    vec_grapheme[1],
                    vec_grapheme[2],
                    vec_grapheme[3],
                ));
                last_was_ascii = check_similar(curr_char, &mut new_name, last_was_ascii);
                vec_grapheme = [0; 4];
                idx_grapheme = 0;
            } else if (224..240).contains(&first_byte) && idx_grapheme == 3 {
                // three bytes grapheme
                let curr_char = std::char::from_u32(convert_three_to_u32(
                    vec_grapheme[0],
                    vec_grapheme[1],
                    vec_grapheme[2],
                ));
                last_was_ascii = check_similar(curr_char, &mut new_name, last_was_ascii);
                vec_grapheme = [0; 4];
                idx_grapheme = 0;
            } else if (128..224).contains(&first_byte) && idx_grapheme == 2 {
                // two bytes grapheme
                let curr_char =
                    std::char::from_u32(convert_two_to_u32(vec_grapheme[0], vec_grapheme[1]));
                last_was_ascii = check_similar(curr_char, &mut new_name, last_was_ascii);
                vec_grapheme = [0; 4];
                idx_grapheme = 0;
            }
        }
    }
    OsString::from(new_name)
}

/// Clean a path
fn clean_path(file_path: &Path, options: &NotoxArgs) -> PathChange {
    let Some(file_name) = file_path.file_name() else {
        return PathChange::Unchanged {
            path: file_path.to_path_buf(),
        };
    };
    let cleaned_name = clean_name(file_name, options);
    if cleaned_name == file_name {
        return PathChange::Unchanged {
            path: file_path.to_path_buf(),
        };
    }
    let cleaned_path = file_path.with_file_name(cleaned_name);
    if options.dry_run {
        return PathChange::ErrorRename {
            path: file_path.to_path_buf(),
            modified: cleaned_path,
            error: "dry-run".to_string(),
        };
    }
    match std::fs::rename(file_path, &cleaned_path) {
        Ok(()) => PathChange::Changed {
            path: file_path.to_path_buf(),
            modified: cleaned_path,
        },
        Err(rename_error) => PathChange::ErrorRename {
            path: file_path.to_path_buf(),
            modified: cleaned_path,
            error: rename_error.to_string(),
        },
    }
}

/// Clean a directory
fn clean_directory(dir_path: &Path, options: &NotoxArgs) -> Vec<PathChange> {
    let mut dir_path = dir_path.to_path_buf();
    let mut result_vec = Vec::new();
    let res_dir = clean_path(&dir_path, options);
    if let PathChange::Changed { modified, .. } = &res_dir {
        dir_path.clone_from(modified);
    }
    result_vec.push(res_dir);
    if let Ok(entries) = std::fs::read_dir(&dir_path) {
        let ok_entries = {
            #[cfg(feature = "rayon")]
            {
                use std::fs::DirEntry;
                let (ok_entries, error_entries): (Vec<_>, Vec<_>) = entries
                    .collect::<Vec<Result<DirEntry, std::io::Error>>>()
                    .into_par_iter()
                    .partition_map(|x| match x {
                        Ok(entry) => Either::Left(entry),
                        Err(e) => Either::Right(e),
                    });
                for e in error_entries {
                    result_vec.push(PathChange::Error {
                        path: dir_path.clone(),
                        error: format!("Error reading dir entry of directory {e}"),
                    });
                }
                ok_entries
            }
            #[cfg(not(feature = "rayon"))]
            {
                let mut ok_entries = Vec::new();
                for entry in entries {
                    match entry {
                        Ok(e) => ok_entries.push(e),
                        Err(e) => result_vec.push(PathChange::Error {
                            path: dir_path.clone(),
                            error: format!("Error reading dir entry of directory {}", e),
                        }),
                    }
                }
                ok_entries
            }
        };
        #[cfg(feature = "rayon")]
        let iter = ok_entries.par_iter();
        #[cfg(not(feature = "rayon"))]
        let iter = ok_entries.iter();
        let mapped = iter
            .map(|entry| {
                let file_path = entry.path();
                let is_entry_directory = match entry.file_type() {
                    Ok(file_type) => file_type.is_dir(),
                    Err(_) => false,
                };
                if is_entry_directory {
                    clean_directory(&file_path, options)
                } else {
                    let res = clean_path(&file_path, options);
                    vec![res]
                }
            })
            .flatten()
            .collect::<Vec<PathChange>>();
        result_vec.extend(mapped);
    } else {
        result_vec.push(PathChange::Error {
            path: dir_path,
            error: "Error while reading directory".to_string(),
        });
    }
    result_vec
}

/// Get the path of a directory
#[inline]
fn get_path_of_dir(dir_path: &str) -> HashSet<PathBuf> {
    match std::fs::read_dir(dir_path) {
        Ok(dir_entries) => dir_entries
            .into_iter()
            .filter_map(Result::ok)
            .map(|e| e.path().clone())
            .collect(),
        Err(_) => HashSet::new(),
    }
}

/// Show the version
#[inline]
fn show_version() {
    /// Version of the program
    const VERSION: &str = env!("CARGO_PKG_VERSION");
    /// Authors of the program
    const AUTHORS: &str = env!("CARGO_PKG_AUTHORS");
    println!("notox {VERSION} by {AUTHORS}");
}

/// Parse the arguments and return the options and the paths to check
/// # Errors
/// Return an error if the path is not found
#[allow(clippy::too_many_lines)]
pub fn parse_args(args: &[String]) -> Result<(NotoxArgs, HashSet<PathBuf>), i32> {
    let mut dry_run = true;
    let mut output = NotoxOutput::Default;
    let mut path_to_check: HashSet<PathBuf> = HashSet::new();
    let mut count_path_args = 0;
    for one_arg in &args[1..] {
        if one_arg == "-d" || one_arg == "--do" {
            dry_run = false;
        } else if one_arg == "-h" || one_arg == "--help" {
            println!("Usage: notox [options] [path]");
            show_version();
            println!("Options:");
            println!("  -d, --do          Do the renaming");
            println!("  -h, --help        Show this help message");
            println!("  -v, --version     Show the version");
            println!("  -p, --json-pretty Print the result in JSON format (pretty)");
            println!("  -e, --json-error  Print only the errors in JSON format");
            println!("  -j, --json        Print the result in JSON format");
            println!("  -q, --quiet       Do not print anything");
            return Err(1);
        } else if one_arg == "-v" || one_arg == "--version" {
            show_version();
            return Err(1);
        } else if one_arg == "-p" || one_arg == "--json-pretty" {
            #[cfg(feature = "serde")]
            {
                output = match output {
                    NotoxOutput::JsonOutput {
                        json: json_output,
                        pretty: _,
                    } => NotoxOutput::JsonOutput {
                        json: json_output,
                        pretty: true,
                    },
                    _ => NotoxOutput::JsonOutput {
                        json: JsonOutput::JsonDefault,
                        pretty: true,
                    },
                };
            }
            #[cfg(not(feature = "serde"))]
            {
                println!("JSON output is not available, please use a notox version with the 'serde' feature.");
                return Err(2);
            }
        } else if one_arg == "-e" || one_arg == "--json-error" {
            #[cfg(feature = "serde")]
            {
                output = match output {
                    NotoxOutput::JsonOutput { json: _, pretty } => NotoxOutput::JsonOutput {
                        json: JsonOutput::JsonOnlyError,
                        pretty,
                    },
                    _ => NotoxOutput::JsonOutput {
                        json: JsonOutput::JsonOnlyError,
                        pretty: false,
                    },
                };
            }
            #[cfg(not(feature = "serde"))]
            {
                println!("JSON output is not available, please use a notox version with the 'serde' feature.");
                return Err(2);
            }
        } else if one_arg == "-j" || one_arg == "--json" {
            #[cfg(feature = "serde")]
            {
                output = match output {
                    NotoxOutput::JsonOutput { json: _, pretty } => NotoxOutput::JsonOutput {
                        json: JsonOutput::JsonDefault,
                        pretty,
                    },
                    _ => NotoxOutput::JsonOutput {
                        json: JsonOutput::JsonDefault,
                        pretty: false,
                    },
                };
            }
            #[cfg(not(feature = "serde"))]
            {
                println!("JSON output is not available, please use a notox version with the 'serde' feature.");
                return Err(2);
            }
        } else if one_arg == "-q" || one_arg == "--quiet" {
            output = NotoxOutput::Quiet;
        } else if one_arg == "*" {
            // should not happen with most shells
            let paths = get_path_of_dir(".");
            path_to_check.extend(paths);
            count_path_args += 1;
        } else if std::fs::metadata(one_arg).is_ok() {
            path_to_check.insert(PathBuf::from(one_arg));
            count_path_args += 1;
        } else if output.is_verbose() {
            count_path_args += 1;
            println!("Cannot find path: {one_arg}");
        }
    }
    if count_path_args == 1 && path_to_check.is_empty() {
        return Err(1);
    }
    if path_to_check.is_empty() {
        let paths = get_path_of_dir(".");
        path_to_check.extend(paths);
    }
    Ok((NotoxArgs { dry_run, output }, path_to_check))
}

/// Notox struct
pub struct Notox {
    /// Options
    notox_args: NotoxArgs,
}

impl Notox {
    /// Create a new Notox instance
    #[must_use]
    pub fn new(notox_args: NotoxArgs) -> Notox {
        Notox { notox_args }
    }

    /// Run from args. Paths needs to exists
    /// # Errors
    /// Returns error if [`parse_args`] fails
    pub fn run_from_args(args: &[String]) -> Result<Vec<PathChange>, i32> {
        match parse_args(args) {
            Ok((notox_args, paths)) => Ok(Self::new(notox_args).run(&paths)),
            Err(code) => Err(code),
        }
    }

    /// Run main from args. Paths needs to exists
    #[must_use]
    pub fn run_main_from_args(args: &[String]) -> i32 {
        match parse_args(args) {
            Ok((notox_args, paths)) => {
                let notox_inst = Self::new(notox_args);
                let final_res = notox_inst.run(&paths);
                match notox_inst.print_output(final_res) {
                    Ok(()) => 0,
                    Err(code) => code,
                }
            }
            Err(code) => code,
        }
    }

    /// Run the Notox instance. Paths needs to exists
    #[must_use]
    pub fn run<S: ::std::hash::BuildHasher>(
        &self,
        paths_to_check: &HashSet<PathBuf, S>,
    ) -> Vec<PathChange> {
        if self.notox_args.is_verbose() {
            println!("Running with options: {}", &self.notox_args);
        }
        #[cfg(feature = "rayon")]
        let iter = paths_to_check.par_iter();
        #[cfg(not(feature = "rayon"))]
        let iter = paths_to_check.iter();

        let results = iter
            .map(|one_path| {
                if self.notox_args.is_verbose() {
                    println!("Checking: {}", one_path.display());
                }
                if one_path.is_dir() {
                    clean_directory(one_path, &self.notox_args)
                } else {
                    let one_cleaned = clean_path(one_path, &self.notox_args);
                    vec![one_cleaned]
                }
            })
            .flatten();
        results.collect::<Vec<PathChange>>()
    }

    /// Print the output of the program conforming to the options
    /// # Errors
    /// Return an error if the output cannot be serialized
    pub fn print_output(&self, final_res: Vec<PathChange>) -> Result<(), i32> {
        match &self.notox_args.output {
            NotoxOutput::Default => {
                let len = final_res.len();
                for one_change in final_res {
                    match one_change {
                        PathChange::Unchanged { .. } => {}
                        PathChange::Changed { path, modified } => {
                            println!("{} -> {}", path.display(), modified.display());
                        }
                        PathChange::Error { path, error } => {
                            println!("{} : {}", path.display(), error);
                        }
                        PathChange::ErrorRename {
                            path,
                            modified,
                            error,
                        } => {
                            println!("{} -> {} : {}", path.display(), modified.display(), error);
                        }
                    }
                }
                if len == 1 {
                    println!("{len} file checked");
                } else {
                    println!("{len} files checked");
                }
            }
            #[cfg(feature = "serde")]
            NotoxOutput::JsonOutput {
                json: json_output,
                pretty: json_pretty,
            } => {
                let vec_to_json = match json_output {
                    JsonOutput::JsonDefault => final_res,
                    JsonOutput::JsonOnlyError => {
                        let mut vec_to_json: Vec<PathChange> = Vec::new();
                        for one_change in final_res {
                            match one_change {
                                PathChange::Unchanged { .. } | PathChange::Changed { .. } => {}
                                one_res @ (PathChange::Error { .. }
                                | PathChange::ErrorRename { .. }) => {
                                    vec_to_json.push(one_res);
                                }
                            }
                        }
                        vec_to_json
                    }
                };
                let json_string = match json_pretty {
                    true => serde_json::to_string_pretty(&vec_to_json),
                    false => serde_json::to_string(&vec_to_json),
                };
                if let Ok(stringed) = json_string {
                    println!("{stringed}");
                } else {
                    println!(r#"{{"error": "Cannot serialize result"}}"#);
                    return Err(2);
                }
            }
            NotoxOutput::Quiet => {}
        }
        Ok(())
    }
}