omegasort 0.2.0

The last text sorting tool you'll ever need
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
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
use crate::gitignore::GitignorePattern;
use anyhow::Result;
use chrono::{DateTime, Utc};
use dateparser::DateTimeUtc;
use icu_collator::Collator;
use ipnet::IpNet;
use lazy_regex::regex;
use log::debug;
use std::cmp::Ordering;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use typed_path::{
    Utf8Component, Utf8Encoding, Utf8Path, Utf8UnixPath, Utf8WindowsComponent, Utf8WindowsPath,
};

pub(crate) trait Comparer {
    fn is_ordered(&self, str1: &str, str2: &str, reverse: bool) -> Result<bool> {
        let ord = self.cmp(str1, str2)?;
        Ok(if reverse { ord.is_ge() } else { ord.is_le() })
    }

    fn cmp(&self, str1: &str, str2: &str) -> Result<Ordering>;
}

pub(crate) struct TextComparer {
    collator: Option<Collator>,
    case_insensitive: bool,
}

impl Comparer for TextComparer {
    fn cmp(&self, str1: &str, str2: &str) -> Result<Ordering> {
        Ok(compare_two_strings(
            self.collator.as_ref(),
            self.case_insensitive,
            str1,
            str2,
        ))
    }
}

impl TextComparer {
    pub(crate) fn new(collator: Option<Collator>, case_insensitive: bool) -> Self {
        Self {
            collator,
            case_insensitive,
        }
    }
}

pub(crate) struct NumberedTextComparer {
    collator: Option<Collator>,
    case_insensitive: bool,
}

impl Comparer for NumberedTextComparer {
    fn cmp(&self, str1: &str, str2: &str) -> Result<Ordering> {
        debug!("NumberedTextComparer comparing `{str1}` <=> `{str2}`");
        let numbered_text_re = regex!(
            r#"(?x)
            \A
            (?P<number>
                [0-9]+
                (?:\.[0-9]+)?
            )?
            (?P<rest>.*)
            \z
        "#
        );

        // This regex will always match since it matches even an empty string.
        let caps1 = numbered_text_re.captures(str1).unwrap();
        let caps2 = numbered_text_re.captures(str2).unwrap();

        // This always has to be at least an empty string.
        let rest1 = caps1.name("rest").unwrap();
        let rest2 = caps2.name("rest").unwrap();

        match (caps1.name("number"), caps2.name("number")) {
            (Some(num1), Some(num2)) => {
                let num1 = num1.as_str();
                let num2 = num2.as_str();

                debug!("  Both strings match the number regex: `{num1}` <=> `{num2}`");
                if num1 == num2 {
                    debug!("  The numbers are equal so the comparison will look at the rest of each string");
                    return Ok(compare_two_strings(
                        self.collator.as_ref(),
                        self.case_insensitive,
                        rest1.as_str(),
                        rest2.as_str(),
                    ));
                }

                let f1 = num1.parse::<f64>();
                let f2 = num2.parse::<f64>();
                debug!(
                    "  Parsed numbers as: `{}` <=> `{}`",
                    f1.as_ref().map_or_else(
                        std::string::ToString::to_string,
                        std::string::ToString::to_string
                    ),
                    f2.as_ref().map_or_else(
                        std::string::ToString::to_string,
                        std::string::ToString::to_string
                    ),
                );

                match (f1, f2) {
                    (Ok(f1), Ok(f2)) => {
                        debug!("  Both strings start with valid numbers");
                        Ok(f1.total_cmp(&f2))
                    }
                    (Ok(_), Err(_)) => {
                        debug!("  Only the left side has a valid number ");
                        Ok(Ordering::Less)
                    }
                    (Err(_), Ok(_)) => {
                        debug!("  Only the right side has a valid number");
                        Ok(Ordering::Greater)
                    }
                    (Err(_), Err(_)) => {
                        debug!(
                            "  Neither side has a valid number, comparing the values as strings"
                        );
                        Ok(compare_two_strings(
                            self.collator.as_ref(),
                            self.case_insensitive,
                            str1,
                            str2,
                        ))
                    }
                }
            }
            (Some(_), None) => {
                debug!("  Only the left side matches the number regex ");
                Ok(Ordering::Less)
            }
            (None, Some(_)) => {
                debug!("  Only the right side matches the number regex ");
                Ok(Ordering::Greater)
            }
            (None, None) => {
                debug!("  Neither side matches the number regex, comparing the values as strings");
                Ok(compare_two_strings(
                    self.collator.as_ref(),
                    self.case_insensitive,
                    str1,
                    str2,
                ))
            }
        }
    }
}

impl NumberedTextComparer {
    pub(crate) fn new(collator: Option<Collator>, case_insensitive: bool) -> Self {
        Self {
            collator,
            case_insensitive,
        }
    }
}

pub(crate) struct DatetimeTextComparer {
    collator: Option<Collator>,
    case_insensitive: bool,
}

impl Comparer for DatetimeTextComparer {
    fn cmp(&self, str1: &str, str2: &str) -> Result<Ordering> {
        debug!("DatetimeTextComparer comparing `{str1}` <=> `{str2}`");

        let dt1 = Self::datetime_from_str(str1);
        let dt2 = Self::datetime_from_str(str2);

        match (dt1, dt2) {
            (Some(dt1), Some(dt2)) => {
                debug!("Both strings match the datetime regex: `{dt1}` <=> `{dt2}`");
                Ok(dt1.cmp(&dt2))
            }
            (Some(_), None) => {
                debug!("  Only the left side has a valid datetime ");
                Ok(Ordering::Less)
            }
            (None, Some(_)) => {
                debug!("  Only the right side has a valid datetime ");
                Ok(Ordering::Greater)
            }
            (None, None) => {
                debug!("  Neither side has a valid datetime, comparing the values as strings");
                Ok(compare_two_strings(
                    self.collator.as_ref(),
                    self.case_insensitive,
                    str1,
                    str2,
                ))
            }
        }
    }
}

impl DatetimeTextComparer {
    pub(crate) fn new(collator: Option<Collator>, case_insensitive: bool) -> Self {
        Self {
            collator,
            case_insensitive,
        }
    }

    fn datetime_from_str(str: &str) -> Option<DateTime<Utc>> {
        let datetime_text_re = regex!(
            r#"(?x)
            \A
            (?P<datetime>\d\S+)
            (?:\s*|\z)
            \z
        "#
        );
        if let Some(caps) = datetime_text_re.captures(str) {
            if let Some(dt_text) = caps.name("datetime") {
                if let Ok(dt) = dt_text.as_str().parse::<DateTimeUtc>() {
                    return Some(dt.0);
                }
            }
        }

        None
    }
}

#[derive(PartialEq)]
pub(crate) enum PathType {
    Unix,
    Windows,
}

pub(crate) struct PathComparer {
    collator: Option<Collator>,
    case_insensitive: bool,
    path_type: PathType,
}

impl Comparer for PathComparer {
    fn cmp(&self, str1: &str, str2: &str) -> Result<Ordering> {
        Ok(match self.path_type {
            PathType::Unix => self.cmp_unix(str1, str2),
            PathType::Windows => self.cmp_windows(str1, str2),
        })
    }
}

impl PathComparer {
    pub(crate) fn new(
        collator: Option<Collator>,
        case_insensitive: bool,
        path_type: PathType,
    ) -> Self {
        Self {
            collator,
            case_insensitive,
            path_type,
        }
    }

    fn cmp_unix(&self, str1: &str, str2: &str) -> Ordering {
        debug!("PathComparer comparing paths as Unix paths: `{str1}` <=> `{str2}`");

        let path1 = Utf8UnixPath::new(str1);
        let path2 = Utf8UnixPath::new(str2);

        if let Some(o) = Self::cmp_absolute(path1, path2) {
            return o;
        }

        self.cmp_components(path1, path2)
    }

    fn cmp_windows(&self, str1: &str, str2: &str) -> Ordering {
        debug!("PathComparer comparing paths as Windows paths: `{str1}` <=> `{str2}`");

        let path1 = Utf8WindowsPath::new(str1);
        let path2 = Utf8WindowsPath::new(str2);

        if let Some(o) = Self::cmp_absolute(path1, path2) {
            return o;
        }

        // We end up calling `components()` again in `cmp_components` but when
        // trying to avoid this by passing the components to `cmp_components`
        // instead of the paths I walked into generic type hell and gave up.
        let path1_first = path1.components().next();
        let path2_first = path2.components().next();

        match (path1_first, path2_first) {
            (
                Some(Utf8WindowsComponent::Prefix(pre1)),
                Some(Utf8WindowsComponent::Prefix(pre2)),
            ) => {
                debug!(
                    "  both sides start with a Windows prefix, comparing `{}` <=> `{}`",
                    pre1.as_str(),
                    pre2.as_str(),
                );
                if pre1 != pre2 {
                    return pre1.cmp(&pre2);
                }
            }
            (Some(Utf8WindowsComponent::Prefix(_)), _) => {
                debug!("  only the left side starts with a Windows prefix");
                return Ordering::Less;
            }
            (_, Some(Utf8WindowsComponent::Prefix(_))) => {
                debug!("  only the right side starts with a Windows prefix");
                return Ordering::Greater;
            }
            _ => {
                debug!("  neither side starts with a Windows prefix");
            }
        }

        self.cmp_components(path1, path2)
    }

    fn cmp_absolute<T>(path1: &Utf8Path<T>, path2: &Utf8Path<T>) -> Option<Ordering>
    where
        T: Utf8Encoding,
    {
        let path1_is_abs = path1.is_absolute();
        let path2_is_abs = path2.is_absolute();

        debug!("  left side is absolute? {path1_is_abs}");
        debug!("  right side is absolute? {path2_is_abs}");

        match (path1_is_abs, path2_is_abs) {
            (true, false) => Some(Ordering::Less),
            (false, true) => Some(Ordering::Greater),
            _ => None,
        }
    }

    fn cmp_components<T>(&self, path1: &Utf8Path<T>, path2: &Utf8Path<T>) -> Ordering
    where
        T: Utf8Encoding,
    {
        let elems1 = path1.components().collect::<Vec<_>>();
        let elems2 = path2.components().collect::<Vec<_>>();

        debug!("  left side has {} components", elems1.len());
        debug!("  right side has {} components", elems2.len());

        match (elems1.is_empty(), elems2.is_empty()) {
            (true, true) => {
                debug!("  neither side has components");
                return Ordering::Equal;
            }
            (true, false) => {
                debug!("  only the left side has components");
                return Ordering::Less;
            }
            (false, true) => {
                debug!("  only the right side has components");
                return Ordering::Greater;
            }
            _ => (),
        }

        if elems1.len() != elems2.len() {
            debug!(
                "  the sides differ in numbers of elements: {} <=> {}",
                elems1.len(),
                elems2.len(),
            );
            return elems1.len().cmp(&elems2.len());
        }

        debug!("  comparing each component in turn");
        for i in 0..elems1.len() {
            let elem1_str = elems1[i].as_str();
            let elem2_str = elems2[i].as_str();
            let ord = compare_two_strings(
                self.collator.as_ref(),
                self.case_insensitive,
                elem1_str,
                elem2_str,
            );
            debug!("  {i}: `{elem1_str}` <=> `{elem2_str}`: {ord:?}");
            if ord != Ordering::Equal {
                return ord;
            }
        }

        debug!("  no differences in path found");
        Ordering::Equal
    }
}

pub(crate) struct GitignoreComparer {
    text_comparer: TextComparer,
}

impl Comparer for GitignoreComparer {
    fn cmp(&self, str1: &str, str2: &str) -> Result<Ordering> {
        debug!("GitignoreComparer comparing patterns: `{str1}` <=> `{str2}`");

        let pat1 = GitignorePattern::new(str1);
        let pat2 = GitignorePattern::new(str2);

        let ord = self.text_comparer.cmp(pat1.path, pat2.path)?;
        debug!("  `{}` <=> `{}`: {ord:?}", pat1.path, pat2.path);
        if ord != Ordering::Equal {
            return Ok(ord);
        }

        // Anchored patterns sort before unanchored ones.
        if pat1.anchored != pat2.anchored {
            debug!("  only one side is anchored, so it sorts first");
            return Ok(pat2.anchored.cmp(&pat1.anchored));
        }

        // Directory-only patterns sort before ones that match any entry.
        if pat1.dir_only != pat2.dir_only {
            debug!("  only one side is directory-only, so it sorts first");
            return Ok(pat2.dir_only.cmp(&pat1.dir_only));
        }

        // `foo` and `**/foo` are the same pattern, so they sort together with the shorter spelling
        // first.
        if pat1.double_star != pat2.double_star {
            debug!("  only one side is spelled with a `**/` prefix, so it sorts last");
            return Ok(pat1.double_star.cmp(&pat2.double_star));
        }

        // Two lines of different polarity are never in the same group, so this never decides
        // anything real. It is here so that the ordering is total.
        if pat1.negated != pat2.negated {
            debug!("  the patterns differ only in whether they are negated");
            return Ok(pat1.negated.cmp(&pat2.negated));
        }

        // Falling back to the bytes means the comparer alone decides the order, rather than leaving
        // it to whether the sort is stable.
        debug!("  falling back to comparing the lines as written");
        Ok(str1.cmp(str2))
    }
}

impl GitignoreComparer {
    pub(crate) fn new(collator: Option<Collator>, case_insensitive: bool) -> Self {
        Self {
            // Gitignore patterns are a flat list of match rules rather than a directory listing, so
            // they are compared as plain text. Sorting them by depth the way `PathComparer` does
            // would put `zzz` above `a/a`, which reads as an error in a file like this.
            text_comparer: TextComparer::new(collator, case_insensitive),
        }
    }
}

pub(crate) struct IpComparer;

impl Comparer for IpComparer {
    fn cmp(&self, str1: &str, str2: &str) -> Result<Ordering> {
        let ip1 = Self::parse_ip_address(str1)?;
        let ip2 = Self::parse_ip_address(str2)?;
        Ok(compare_two_ip_addresses(ip1, ip2))
    }
}

impl IpComparer {
    pub(crate) fn new() -> Self {
        Self
    }

    fn parse_ip_address(addr: &str) -> Result<IpAddr> {
        if addr.contains('.') {
            Ok(IpAddr::V4(addr.parse::<Ipv4Addr>()?))
        } else {
            Ok(IpAddr::V6(addr.parse::<Ipv6Addr>()?))
        }
    }
}

pub(crate) struct NetworkComparer;

impl Comparer for NetworkComparer {
    fn cmp(&self, str1: &str, str2: &str) -> Result<Ordering> {
        let net1 = Self::parse_network(str1)?;
        let net2 = Self::parse_network(str2)?;

        let cmp = compare_two_ip_addresses(net1.addr(), net2.addr());
        if cmp != Ordering::Equal {
            return Ok(cmp);
        }

        Ok(net1.prefix_len().cmp(&net2.prefix_len()))
    }
}

impl NetworkComparer {
    pub(crate) fn new() -> Self {
        Self
    }
    fn parse_network(addr: &str) -> Result<IpNet> {
        Ok(addr.parse::<IpNet>()?)
    }
}

fn compare_two_strings(
    collator: Option<&Collator>,
    case_insensitive: bool,
    str1: &str,
    str2: &str,
) -> Ordering {
    if let Some(c) = collator {
        let ord = c.as_borrowed().compare(str1, str2);
        if ord != Ordering::Equal {
            return ord;
        }
        // If the strings are equal according to the collator they may still
        // be different, in which case we want to further sort them
        // somehow. Otherwise they end up sorted based on their original order
        // in the file, which is random and means two files containing the
        // same lines in different order could be sorted differently.
        str1.cmp(str2)
    } else if case_insensitive {
        str1.to_lowercase().cmp(&str2.to_lowercase())
    } else {
        str1.cmp(str2)
    }
}

fn compare_two_ip_addresses(ip1: IpAddr, ip2: IpAddr) -> Ordering {
    match (ip1, ip2) {
        (IpAddr::V4(_), IpAddr::V6(_)) => return Ordering::Less,
        (IpAddr::V6(_), IpAddr::V4(_)) => return Ordering::Greater,
        _ => (),
    }

    let octets1 = octets_for_ip_address(ip1);
    let octets2 = octets_for_ip_address(ip2);

    for i in 0..octets1.len() {
        if octets1[i] != octets2[i] {
            return octets1[i].cmp(&octets2[i]);
        }
    }

    Ordering::Equal
}

fn octets_for_ip_address(ip: IpAddr) -> [u8; 16] {
    match ip {
        IpAddr::V4(ip) => ip.to_ipv6_compatible().octets(),
        IpAddr::V6(ip) => ip.octets(),
    }
}

#[cfg(test)]
mod test {
    use super::{
        Comparer, DatetimeTextComparer, GitignoreComparer, IpComparer, NetworkComparer,
        NumberedTextComparer, PathComparer, PathType, TextComparer,
    };
    use crate::collation::collator_for_locale;
    use test_log::test;

    struct Case {
        name: &'static str,
        input: Vec<&'static str>,
        expect: Vec<&'static str>,
        #[allow(clippy::struct_field_names)]
        case_insensitive: bool,
        locale: Option<&'static str>,
    }

    #[test]
    fn text_comparer() {
        for mut c in cases_from(TEXT_TEST_CASES) {
            println!("# text - {}", c.name);
            let tc = TextComparer {
                collator: c
                    .locale
                    .map(|l| collator_for_locale(l, c.case_insensitive).unwrap()),
                case_insensitive: c.case_insensitive,
            };
            c.input.sort_by(|a, b| tc.cmp(a, b).unwrap());
            assert_eq!(c.input, c.expect);
        }
    }

    #[test]
    fn numbered_text_comparer() {
        for mut c in cases_from(TEXT_TEST_CASES)
            .into_iter()
            .chain(cases_from(NUMBERED_TEXT_TEST_CASES))
        {
            println!("# numbered text - {}", c.name);
            let ntc = NumberedTextComparer {
                collator: c
                    .locale
                    .map(|l| collator_for_locale(l, c.case_insensitive).unwrap()),
                case_insensitive: c.case_insensitive,
            };
            c.input.sort_by(|a, b| ntc.cmp(a, b).unwrap());
            assert_eq!(c.input, c.expect);
        }
    }

    #[test]
    fn datetime_text_comparer() {
        for mut c in cases_from(TEXT_TEST_CASES)
            .into_iter()
            .chain(cases_from(DATETIME_TEXT_TEST_CASES))
        {
            println!("# datetime text - {}", c.name);
            let dtc = DatetimeTextComparer {
                collator: c
                    .locale
                    .map(|l| collator_for_locale(l, c.case_insensitive).unwrap()),
                case_insensitive: c.case_insensitive,
            };
            c.input.sort_by(|a, b| dtc.cmp(a, b).unwrap());
            assert_eq!(c.input, c.expect);
        }
    }

    #[test]
    fn path_comparer() {
        for mut c in cases_from(PATH_TEST_CASES) {
            println!("# path - {}", c.name);
            let pc = PathComparer {
                collator: c
                    .locale
                    .map(|l| collator_for_locale(l, c.case_insensitive).unwrap()),
                case_insensitive: c.case_insensitive,
                path_type: if c.name.contains("Windows") {
                    PathType::Windows
                } else {
                    PathType::Unix
                },
            };
            c.input.sort_by(|a, b| pc.cmp(a, b).unwrap());
            assert_eq!(c.input, c.expect);
        }
    }

    #[test]
    fn is_ordered_only_flags_a_real_violation() {
        let tc = TextComparer {
            collator: None,
            case_insensitive: false,
        };

        for (first, second, reverse, expect, why) in [
            (
                "b",
                "a",
                false,
                false,
                "b before a is out of order going up",
            ),
            ("a", "b", false, true, "a before b is in order going up"),
            (
                "a",
                "b",
                true,
                false,
                "a before b is out of order going down",
            ),
            ("b", "a", true, true, "b before a is in order going down"),
            ("a", "a", false, true, "equal lines are in order going up"),
            (
                "a",
                "a",
                true,
                true,
                "equal lines are in order going down too",
            ),
        ] {
            assert_eq!(
                tc.is_ordered(first, second, reverse).unwrap(),
                expect,
                "{why}",
            );
        }
    }

    #[test]
    fn gitignore_comparer() {
        for mut c in cases_from(GITIGNORE_TEST_CASES) {
            println!("# gitignore - {}", c.name);
            let gc = GitignoreComparer::new(
                c.locale
                    .map(|l| collator_for_locale(l, c.case_insensitive).unwrap()),
                c.case_insensitive,
            );
            c.input.sort_by(|a, b| gc.cmp(a, b).unwrap());
            assert_eq!(c.input, c.expect);
        }
    }

    #[test]
    fn ip_comparer() {
        for mut c in cases_from(IP_TEST_CASES) {
            println!("# ip - {}", c.name);
            let ic = IpComparer;
            c.input.sort_by(|a, b| ic.cmp(a, b).unwrap());
            assert_eq!(c.input, c.expect);
        }
    }

    #[test]
    fn network_comparer() {
        for mut c in cases_from(NETWORK_TEST_CASES) {
            println!("# network - {}", c.name);
            let nc = NetworkComparer;
            c.input.sort_by(|a, b| nc.cmp(a, b).unwrap());
            assert_eq!(c.input, c.expect);
        }
    }

    fn cases_from(cases_text: &'static str) -> Vec<Case> {
        cases_text
            .split("====\n")
            .map(|case| {
                let mut elts = case.split("----\n");
                let name = elts.next().unwrap().trim();
                let input = elts.next().unwrap().lines().collect();
                let expect = elts.next().unwrap().lines().collect();
                let case_insensitive = match elts.next() {
                    Some("false\n") | None => false,
                    Some("true\n") => true,
                    Some(ci) => panic!("unknown case-insensitive value: {ci}"),
                };
                let locale = elts.next().map(str::trim);
                Case {
                    name,
                    input,
                    expect,
                    case_insensitive,
                    locale,
                }
            })
            .collect()
    }

    const TEXT_TEST_CASES: &str = r"
ASCII with no locale
----
go
bears
above
And
all
home
----
And
above
all
bears
go
home
----
false
====
ASCII with no locale, case-insensitive
----
go
bears
above
And
all
home
----
above
all
And
bears
go
home
----
true
====
ASCII with en-US locale
----
go
bears
above
And
all
home
----
above
all
And
bears
go
home
----
false
----
en-US
====
Unicode text with de-DE locale
----
zoo
foo
öoo
----
foo
öoo
zoo
----
false
----
de-DE
====
Unicode text with sv-SE locale
----
zoo
foo
öoo
----
foo
zoo
öoo
----
false
----
sv-SE
";

    const NUMBERED_TEXT_TEST_CASES: &str = r"
numbered ASCII with no locale
----
120001 go
0. bears
15 - above
5. And
1. all
5. act
2. home
----
0. bears
1. all
2. home
5. And
5. act
15 - above
120001 go
----
false
====
numbered ASCII with no locale, case-insensitive
----
120001 go
0. bears
15 - above
5. And
1. all
5. act
2. home
----
0. bears
1. all
2. home
5. act
5. And
15 - above
120001 go
----
true
====
numbered Unicode with de-DE locale
----
3. zoo
1. foo
2. öoo
2. zoo
----
1. foo
2. öoo
2. zoo
3. zoo
----
false
----
de-DE
====
numbered Unicode with sv-Se locale
----
3. zoo
1. foo
2. öoo
2. zoo
----
1. foo
2. zoo
2. öoo
3. zoo
----
false
----
sv-SE
====
mixed numbered and unnumbered
----
10. x
aloe
27. bar
love
1. hello
----
1. hello
10. x
27. bar
aloe
love
----
false
====
numbered text with decimal numbers
----
10.1 - x
27.2314 - bar
1.00 - hello
----
1.00 - hello
10.1 - x
27.2314 - bar
----
false
";

    const DATETIME_TEXT_TEST_CASES: &str = r"
datetime ASCII text with no locale
----
2017-1-12 hello
2014-05-07 foo
2018-12-30 bar
2014-05-07 FUN
----
2014-05-07 FUN
2014-05-07 foo
2017-1-12 hello
2018-12-30 bar
----
false
====
datetime ASCII text with no locale, case-insensitive
----
2017-1-12 hello
2014-05-07 foo
2018-12-30 bar
2014-05-07 FUN
----
2014-05-07 foo
2014-05-07 FUN
2017-1-12 hello
2018-12-30 bar
----
true
====
datetime ASCII text with de-DE locale
----
2017-1-12 hello
2014-05-07 zoo
2018-12-30 bar
2014-05-07 öoo
----
2014-05-07 öoo
2014-05-07 zoo
2017-1-12 hello
2018-12-30 bar
----
false
----
de-DE
====
datetime ASCII text with sv-SE locale
----
2017-1-12 hello
2014-05-07 zoo
2018-12-30 bar
2014-05-07 öoo
----
2014-05-07 zoo
2014-05-07 öoo
2017-1-12 hello
2018-12-30 bar
----
false
----
sv-SE
====
mixed datetime and non-datetime
----
2017-1-12 hello
no dt
also none
1973-01-01 and
----
1973-01-01 and
2017-1-12 hello
also none
no dt
----
false
====
datetime and dates
----
2017-1-12T01:00:37
1991-01-02
2017-1-12T14:01:01
----
1991-01-02
2017-1-12T01:00:37
2017-1-12T14:01:01
----
false
";

    const PATH_TEST_CASES: &str = r"
path with ASCII text
----
/foo
/bar
baz/quux
a/q
C:\
/X
/A
----
/A
/X
/bar
/foo
C:\
a/q
baz/quux
----
false
====
path with ASCII text, case-insensitive
----
/foo
/bar
baz/quux
a/q
C:\
/X
/A
----
/A
/bar
/foo
/X
C:\
a/q
baz/quux
----
true
====
path with ASCII text, depth sorts before path content
----
/zzz
/bbb
/xxx/a
/aaaaaa/q/r
----
/bbb
/zzz
/xxx/a
/aaaaaa/q/r
----
false
====
Windows ASCII path
----
C:\foo
\a\b
\b
C:\bar
E:\a
B:\x
C:\a\b\c
C:\a\b
----
B:\x
C:\bar
C:\foo
C:\a\b
C:\a\b\c
E:\a
\b
\a\b
----
false
====
Unix Unicode path with de-DE locale
----
/foo
/bar
baz/quux
/zoo
a/q
/öoo
C:\\
/X
/A
----
/A
/bar
/foo
/öoo
/X
/zoo
C:\\
a/q
baz/quux
----
false
----
de-DE
====
Unix Unicode path with sv-SE locale
----
/foo
/bar
baz/quux
/zoo
a/q
/öoo
C:\\
/X
/A
----
/A
/bar
/foo
/X
/zoo
/öoo
C:\\
a/q
baz/quux
----
false
----
sv-SE
";

    // These cases exercise the comparer on a flat list of lines. They do not test gitignore sorting
    // end to end. The comparer never sees the blocks that `gitignore::Grouper` cuts the file into,
    // so some of the orderings below cannot come out of the tool: a negation and a plain pattern
    // land in different blocks and are never compared against each other. See
    // `src/test-cases/gitignore.test` for the whole pipeline.
    const GITIGNORE_TEST_CASES: &str = r"
the leading bang is ignored when comparing
----
!important.log
*.log
!vendor/keep
/target
----
*.log
!important.log
/target
!vendor/keep
----
false
====
markers do not split up related patterns
----
node_modules
target
/node_modules
node_modules/
/target/
----
/node_modules
node_modules/
node_modules
/target/
target
----
false
====
patterns sort as plain text, not by depth
----
zzz
bbb
xxx/a
aaaaaa/q/r
----
aaaaaa/q/r
bbb
xxx/a
zzz
----
false
====
every spelling of one pattern sorts together
----
zzz
/**/foo
foo
**/a/b
**/foo
a/b
----
**/a/b
a/b
foo
**/foo
/**/foo
zzz
----
false
====
escaped bang is not a negation
----
!foo
\!foo
bar
----
\!foo
bar
!foo
----
false
====
case-insensitive
----
!Zed
Foo
bar
!alpha
----
!alpha
bar
Foo
!Zed
----
true
====
with sv-SE locale
----
zoo
foo
öoo
----
foo
zoo
öoo
----
false
----
sv-SE
====
with de-DE locale, where `ö` sorts with `o` instead of after `z`
----
zoo
!öoo
/öoo
foo
----
foo
/öoo
!öoo
zoo
----
false
----
de-DE
";

    const IP_TEST_CASES: &str = r"
ip with just IPv4
----
1.1.1.1
0.1.255.255
123.100.125.242
1.255.0.0
----
0.1.255.255
1.1.1.1
1.255.0.0
123.100.125.242
====
ip with just IPv6
----
::1
::0
9876::fe01:1234:457f
1234::
----
::0
::1
1234::
9876::fe01:1234:457f
====
ip with mixed IPv4 and IPv6
----
::1
::0
255.255.255.255
::1234
9876::fe01:1234:457f
1.2.3.4
1234::
----
1.2.3.4
255.255.255.255
::0
::1
::1234
1234::
9876::fe01:1234:457f
";

    const NETWORK_TEST_CASES: &str = r"
network with just IPv4
----
1.1.1.1/32
0.1.255.0/24
123.100.125.0/25
1.255.0.0/17
1.255.0.0/16
----
0.1.255.0/24
1.1.1.1/32
1.255.0.0/16
1.255.0.0/17
123.100.125.0/25
====
network with just IPv6
----
::1/128
::0/127
::0/42
9876::fe01:1234:0/24
1234::/90
----
::0/42
::0/127
::1/128
1234::/90
9876::fe01:1234:0/24
====
network with mixed IPv4 and IPv6
----
::1/128
::0/127
1.2.3.0/18
::0/42
1.2.3.0/16
9876::fe01:1234:0/24
255.255.255.0/25
1234::/90
----
1.2.3.0/16
1.2.3.0/18
255.255.255.0/25
::0/42
::0/127
::1/128
1234::/90
9876::fe01:1234:0/24
";
}