๐Ÿ“ฆ sharkdp / lscolors

๐Ÿ“„ lib.rs ยท 1001 lines
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//! A library for colorizing paths according to the `LS_COLORS` environment variable.
//!
//! # Example
//! ```
//! use lscolors::{LsColors, Style};
//!
//! let lscolors = LsColors::from_env().unwrap_or_default();
//!
//! let path = "some/folder/archive.zip";
//! let style = lscolors.style_for_path(path);
//!
//! // If you want to use `nu_ansi_term`:
//! # #[cfg(features = "nu-ansi-term")]
//! # {
//! let ansi_style = style.map(Style::to_nu_ansi_term_style).unwrap_or_default();
//! println!("{}", ansi_style.paint(path));
//! # }
//!
//! // If you want to use `ansi_term`:
//! # #[cfg(features = "ansi_term")]
//! # {
//! let ansi_style = style.map(Style::to_ansi_term_style).unwrap_or_default();
//! println!("{}", ansi_style.paint(path));
//! # }
//! ```

mod fs;
pub mod style;

use std::collections::HashMap;
use std::env;
use std::ffi::OsString;
use std::fs::{DirEntry, FileType, Metadata};
use std::path::{Component, Path, PathBuf, MAIN_SEPARATOR};

pub use crate::style::{Color, FontStyle, Style};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Indicator {
    /// `no`: Normal (non-filename) text
    Normal,

    /// `fi`: Regular file
    RegularFile,

    /// `di`: Directory
    Directory,

    /// `ln`: Symbolic link
    SymbolicLink,

    /// `pi`: Named pipe or FIFO
    FIFO,

    /// `so`: Socket
    Socket,

    /// `do`: Door (IPC connection to another program)
    Door,

    /// `bd`: Block-oriented device
    BlockDevice,

    /// `cd`: Character-oriented device
    CharacterDevice,

    /// `or`: A broken symbolic link
    OrphanedSymbolicLink,

    /// `su`: A file that is setuid (`u+s`)
    Setuid,

    /// `sg`: A file that is setgid (`g+s`)
    Setgid,

    /// `st`: A directory that is sticky and other-writable (`+t`, `o+w`)
    Sticky,

    /// `ow`: A directory that is not sticky and other-writeable (`o+w`)
    OtherWritable,

    /// `tw`: A directory that is sticky and other-writable (`+t`, `o+w`)
    StickyAndOtherWritable,

    /// `ex`: Executable file
    ExecutableFile,

    /// `mi`: Missing file
    MissingFile,

    /// `ca`: File with capabilities set
    Capabilities,

    /// `mh`: File with multiple hard links
    MultipleHardLinks,

    /// `lc`: Code that is printed before the color sequence
    LeftCode,

    /// `rc`: Code that is printed after the color sequence
    RightCode,

    /// `ec`: End code
    EndCode,

    /// `rs`: Code to reset to ordinary colors
    Reset,

    /// `cl`: Code to clear to the end of the line
    ClearLine,
}

impl Indicator {
    pub fn from(indicator: &str) -> Option<Indicator> {
        match indicator {
            "no" => Some(Indicator::Normal),
            "fi" => Some(Indicator::RegularFile),
            "di" => Some(Indicator::Directory),
            "ln" => Some(Indicator::SymbolicLink),
            "pi" => Some(Indicator::FIFO),
            "so" => Some(Indicator::Socket),
            "do" => Some(Indicator::Door),
            "bd" => Some(Indicator::BlockDevice),
            "cd" => Some(Indicator::CharacterDevice),
            "or" => Some(Indicator::OrphanedSymbolicLink),
            "su" => Some(Indicator::Setuid),
            "sg" => Some(Indicator::Setgid),
            "st" => Some(Indicator::Sticky),
            "ow" => Some(Indicator::OtherWritable),
            "tw" => Some(Indicator::StickyAndOtherWritable),
            "ex" => Some(Indicator::ExecutableFile),
            "mi" => Some(Indicator::MissingFile),
            "ca" => Some(Indicator::Capabilities),
            "mh" => Some(Indicator::MultipleHardLinks),
            "lc" => Some(Indicator::LeftCode),
            "rc" => Some(Indicator::RightCode),
            "ec" => Some(Indicator::EndCode),
            "rs" => Some(Indicator::Reset),
            "cl" => Some(Indicator::ClearLine),
            _ => None,
        }
    }
}

type FileNameSuffix = String;
type Priority = usize;

/// Iterator over the path components with their respective style.
pub struct StyledComponents<'a> {
    /// Reference to the underlying LsColors object
    lscolors: &'a LsColors,

    /// Full path to the current component
    component_path: PathBuf,

    /// Underlying iterator over the path components
    components: std::iter::Peekable<std::path::Components<'a>>,
}

impl<'a> Iterator for StyledComponents<'a> {
    type Item = (OsString, Option<&'a Style>);

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(component) = self.components.next() {
            let mut component_str = component.as_os_str().to_os_string();

            self.component_path.push(&component_str);
            let style = self.lscolors.style_for_path(&self.component_path);

            if self.components.peek().is_some() {
                match component {
                    // Prefix needs no separator, as it is always followed by RootDir.
                    // RootDir is already a separator.
                    Component::Prefix(_) | Component::RootDir => {}
                    // Everything else uses a separator that is painted the same way as the component.
                    Component::CurDir | Component::ParentDir | Component::Normal(_) => {
                        component_str.push(MAIN_SEPARATOR.to_string());
                    }
                }
            }

            Some((component_str, style))
        } else {
            None
        }
    }
}

/// A colorable file path.
pub trait Colorable {
    /// Get the full path to this file.
    fn path(&self) -> PathBuf;

    /// Get the name of this file.
    fn file_name(&self) -> OsString;

    /// Try to get the type of this file.
    fn file_type(&self) -> Option<FileType>;

    /// Try to get the metadata for this file.
    fn metadata(&self) -> Option<Metadata>;
}

impl Colorable for DirEntry {
    fn path(&self) -> PathBuf {
        self.path()
    }

    fn file_name(&self) -> OsString {
        self.file_name()
    }

    fn file_type(&self) -> Option<FileType> {
        self.file_type().ok()
    }

    fn metadata(&self) -> Option<Metadata> {
        self.metadata().ok()
    }
}

const LS_COLORS_DEFAULT: &str = "rs=0:lc=\x1b[:rc=m:cl=\x1b[K:ex=01;32:sg=30;43:su=37;41:di=01;34:st=37;44:ow=34;42:tw=30;42:ln=01;36:bd=01;33:cd=01;33:do=01;35:pi=33:so=01;35:";

#[derive(Default, Debug, Clone)]
struct SuffixMappingEntry {
    /// Keys are non-normalized suffixes(variants of the suffix), and values are
    /// tuples containing an style and their priority.
    /// We need to store the priority (the index of the entry in the env) here
    /// because ls has an overriding mechanism. For example,
    /// *.gz=01;33:*.tar.gz=01;31: and *.tar.gz=01;31:*.gz=01;33: are not the
    /// same.
    variants: HashMap<FileNameSuffix, (Option<Style>, Priority)>,
    // whether the variants are case sensitive or not
    case_sensitive: bool,
}

impl SuffixMappingEntry {
    fn init_case_sensitivity(&mut self) {
        // we treat an entry as case-insensitive when all the styles are equal
        let mut iter = self.variants.values();
        // it's okay to unwrap here because there must be atleast element present
        let (ref_style, _) = iter.next().unwrap();
        self.case_sensitive = iter.any(|(style, _)| style != ref_style);
    }
}

/// Holds information about how different file system entries should be colorized / styled.
#[derive(Debug, Clone)]
pub struct LsColors {
    indicator_mapping: HashMap<Indicator, Style>,

    /// Whether Indicator::RegularFile falls back to Indicator::Normal
    /// (see <https://github.com/sharkdp/lscolors/issues/48#issuecomment-1582830387>)
    file_normal_fallback: bool,
    suffix_mapping: HashMap<FileNameSuffix, SuffixMappingEntry>,
}

impl Default for LsColors {
    /// Constructs a default `LsColors` instance with some default styles. See `man dircolors` for
    /// information about the default styles and colors.
    fn default() -> Self {
        let mut lscolors = LsColors::empty();
        lscolors.add_from_string(LS_COLORS_DEFAULT);
        lscolors
    }
}

impl LsColors {
    /// Construct an empty [`LsColors`](struct.LsColors.html) instance with no pre-defined styles.
    pub fn empty() -> Self {
        LsColors {
            indicator_mapping: HashMap::new(),
            file_normal_fallback: true,
            suffix_mapping: HashMap::new(),
        }
    }

    /// Creates a new [`LsColors`](struct.LsColors.html) instance from the `LS_COLORS` environment
    /// variable. The basis for this is a default style as constructed via the `Default`
    /// implementation.
    pub fn from_env() -> Option<Self> {
        env::var("LS_COLORS")
            .ok()
            .as_ref()
            .map(|s| Self::from_string(s))
    }

    /// Creates a new [`LsColors`](struct.LsColors.html) instance from the given string.
    pub fn from_string(input: &str) -> Self {
        let mut lscolors = LsColors::default();
        lscolors.add_from_string(input);
        lscolors
    }

    fn add_from_string(&mut self, input: &str) {
        for (idx, entry) in input.split(':').enumerate() {
            let parts: Vec<_> = entry.split('=').collect();
            if let Some([entry, ansi_style]) = parts.get(0..2) {
                let style = Style::from_ansi_sequence(ansi_style);
                if let Some(suffix) = entry.strip_prefix('*') {
                    self.add_suffix_entry(suffix.to_string(), style, idx);
                } else if let Some(indicator) = Indicator::from(entry) {
                    if let Some(style) = style {
                        self.indicator_mapping.insert(indicator, style);
                    } else {
                        self.indicator_mapping.remove(&indicator);
                        if indicator == Indicator::RegularFile {
                            self.file_normal_fallback = false;
                        }
                    }
                }
            }
        }
        self.suffix_mapping
            .values_mut()
            .for_each(|entry| entry.init_case_sensitivity());
    }

    fn add_suffix_entry(
        &mut self,
        suffix: FileNameSuffix,
        style: Option<Style>,
        priority: Priority,
    ) {
        // We use `to_ascii_lowercase` here to normalize suffix to use as keys.
        let suffix_normalized = suffix.to_ascii_lowercase();
        let suffix_mapping_entry = self.suffix_mapping.entry(suffix_normalized).or_default();
        suffix_mapping_entry
            .variants
            .insert(suffix, (style, priority));
    }

    /// Get the ANSI style for a given path.
    ///
    /// *Note:* this function calls `Path::symlink_metadata` internally. If you already happen to
    /// have the `Metadata` available, use [`style_for_path_with_metadata`](#method.style_for_path_with_metadata).
    pub fn style_for_path<P: AsRef<Path>>(&self, path: P) -> Option<&Style> {
        let metadata = path.as_ref().symlink_metadata().ok();
        self.style_for_path_with_metadata(path, metadata.as_ref())
    }

    /// Check if an indicator has an associated color.
    fn has_color_for(&self, indicator: Indicator) -> bool {
        self.indicator_mapping.contains_key(&indicator)
    }

    /// Check if we need metadata to color a regular file.
    fn needs_file_metadata(&self) -> bool {
        self.has_color_for(Indicator::Setuid)
            || self.has_color_for(Indicator::Setgid)
            || self.has_color_for(Indicator::ExecutableFile)
            || self.has_color_for(Indicator::MultipleHardLinks)
    }

    /// Check if we need metadata to color a directory.
    fn needs_dir_metadata(&self) -> bool {
        self.has_color_for(Indicator::StickyAndOtherWritable)
            || self.has_color_for(Indicator::OtherWritable)
            || self.has_color_for(Indicator::Sticky)
    }

    /// Get the indicator type for a path with corresponding metadata.
    fn indicator_for<F: Colorable>(&self, file: &F) -> Indicator {
        let file_type = file.file_type();

        if let Some(file_type) = file_type {
            if file_type.is_file() {
                if self.needs_file_metadata() {
                    if let Some(metadata) = file.metadata() {
                        let mode = crate::fs::mode(&metadata);
                        let nlink = crate::fs::nlink(&metadata);

                        if self.has_color_for(Indicator::Setuid) && mode & 0o4000 != 0 {
                            return Indicator::Setuid;
                        } else if self.has_color_for(Indicator::Setgid) && mode & 0o2000 != 0 {
                            return Indicator::Setgid;
                        } else if self.has_color_for(Indicator::ExecutableFile)
                            && mode & 0o0111 != 0
                        {
                            return Indicator::ExecutableFile;
                        } else if self.has_color_for(Indicator::MultipleHardLinks) && nlink > 1 {
                            return Indicator::MultipleHardLinks;
                        }
                    }
                }

                Indicator::RegularFile
            } else if file_type.is_dir() {
                if self.needs_dir_metadata() {
                    if let Some(metadata) = file.metadata() {
                        let mode = crate::fs::mode(&metadata);

                        if self.has_color_for(Indicator::StickyAndOtherWritable)
                            && mode & 0o1002 == 0o1002
                        {
                            return Indicator::StickyAndOtherWritable;
                        } else if self.has_color_for(Indicator::OtherWritable) && mode & 0o0002 != 0
                        {
                            return Indicator::OtherWritable;
                        } else if self.has_color_for(Indicator::Sticky) && mode & 0o1000 != 0 {
                            return Indicator::Sticky;
                        }
                    }
                }

                Indicator::Directory
            } else if file_type.is_symlink() {
                // This works because `Path::exists` traverses symlinks.
                if self.has_color_for(Indicator::OrphanedSymbolicLink) && !file.path().exists() {
                    return Indicator::OrphanedSymbolicLink;
                }

                Indicator::SymbolicLink
            } else {
                #[cfg(unix)]
                {
                    use std::os::unix::fs::FileTypeExt;

                    if file_type.is_fifo() {
                        return Indicator::FIFO;
                    }
                    if file_type.is_socket() {
                        return Indicator::Socket;
                    }
                    if file_type.is_block_device() {
                        return Indicator::BlockDevice;
                    }
                    if file_type.is_char_device() {
                        return Indicator::CharacterDevice;
                    }
                }

                // Treat files of unknown type as errors
                Indicator::MissingFile
            }
        } else {
            // Default to a regular file, so we still try the suffix map when no metadata is available
            Indicator::RegularFile
        }
    }

    /// Get the ANSI style for a colorable path.
    pub fn style_for<F: Colorable>(&self, file: &F) -> Option<&Style> {
        let indicator = self.indicator_for(file);

        if indicator == Indicator::RegularFile {
            // Note: using '.to_str()' here means that filename
            // matching will not work with invalid-UTF-8 paths.
            let filename = file.file_name();
            if let Some(style) = self.style_for_str(filename.to_str()?) {
                return Some(style);
            }
        }

        self.style_for_indicator(indicator)
    }

    /// Get the ANSI style for a string. This does not have to be a valid filepath.
    pub fn style_for_str(&self, file_str: &str) -> Option<&Style> {
        let file_str_len = file_str.len();
        let file_str_normalized = file_str.to_ascii_lowercase();
        let mut last_matched_style: Option<&Style> = None;
        let mut last_matched_priority = 0;
        for (suffix_normalized, suffix_mapping_entry) in self.suffix_mapping.iter() {
            // check if there is an entry for the suffix
            if file_str_normalized.ends_with(suffix_normalized) {
                // check whether the entry is marked as case sensitive or not
                if suffix_mapping_entry.case_sensitive {
                    // then we need to check whether there is a suffix that exactly
                    // matches in different variants.
                    // we could do that by finding the suffix variant that appears in the filename,
                    let file_str_suffix = &file_str[file_str_len - suffix_normalized.len()..];
                    // and use that to find the corresponding style.
                    if let Some((style, priority)) =
                        suffix_mapping_entry.variants.get(file_str_suffix)
                    {
                        if *priority >= last_matched_priority {
                            last_matched_style = style.as_ref();
                            last_matched_priority = *priority;
                        }
                    }
                } else {
                    // case doesn't matter, but we need select the one with the biggest priority.
                    let (style, priority) = suffix_mapping_entry
                        .variants
                        .values()
                        .max_by(|x, y| x.1.cmp(&y.1))
                        // it okay to unwrap here, because there should exist atleast one variant.
                        .unwrap();
                    if *priority >= last_matched_priority {
                        last_matched_style = style.as_ref();
                        last_matched_priority = *priority;
                    }
                }
            }
        }
        last_matched_style
    }

    /// Get the ANSI style for a path, given the corresponding `Metadata` struct.
    ///
    /// *Note:* The `Metadata` struct must have been acquired via `Path::symlink_metadata` in
    /// order to colorize symbolic links correctly.
    pub fn style_for_path_with_metadata<P: AsRef<Path>>(
        &self,
        path: P,
        metadata: Option<&std::fs::Metadata>,
    ) -> Option<&Style> {
        struct PathWithMetadata<'a> {
            path: &'a Path,
            metadata: Option<&'a Metadata>,
        }

        impl Colorable for PathWithMetadata<'_> {
            fn path(&self) -> PathBuf {
                self.path.to_owned()
            }

            fn file_name(&self) -> OsString {
                // Path::file_name() only works if the last component is Normal, but
                // we want it for all component types, so we open code it

                self.path
                    .components()
                    .last()
                    .map(|c| c.as_os_str())
                    .unwrap_or_else(|| self.path.as_os_str())
                    .to_owned()
            }

            fn file_type(&self) -> Option<FileType> {
                self.metadata.map(|m| m.file_type())
            }

            fn metadata(&self) -> Option<Metadata> {
                self.metadata.cloned()
            }
        }

        let path = path.as_ref();
        self.style_for(&PathWithMetadata { path, metadata })
    }

    /// Get ANSI styles for each component of a given path. Components already include the path
    /// separator symbol, if required. For a path like `foo/bar/test.md`, this would return an
    /// iterator over three pairs for the three path components `foo/`, `bar/` and `test.md`
    /// together with their respective styles.
    pub fn style_for_path_components<'a>(&'a self, path: &'a Path) -> StyledComponents<'a> {
        StyledComponents {
            lscolors: self,
            component_path: PathBuf::new(),
            components: path.components().peekable(),
        }
    }

    /// Get the ANSI style for a certain `Indicator` (regular file, directory, symlink, ...). Note
    /// that this function implements a fallback logic for some of the indicators (just like `ls`).
    /// For example, the style for `mi` (missing file) falls back to `or` (orphaned symbolic link)
    /// if it has not been specified explicitly.
    pub fn style_for_indicator(&self, indicator: Indicator) -> Option<&Style> {
        self.indicator_mapping
            .get(&indicator)
            .or_else(|| {
                self.indicator_mapping.get(&match indicator {
                    Indicator::Setuid
                    | Indicator::Setgid
                    | Indicator::ExecutableFile
                    | Indicator::MultipleHardLinks => Indicator::RegularFile,

                    Indicator::StickyAndOtherWritable
                    | Indicator::OtherWritable
                    | Indicator::Sticky => Indicator::Directory,

                    Indicator::OrphanedSymbolicLink => Indicator::SymbolicLink,

                    Indicator::MissingFile => Indicator::OrphanedSymbolicLink,

                    _ => indicator,
                })
            })
            .or_else(|| {
                if indicator == Indicator::RegularFile && !self.file_normal_fallback {
                    None
                } else {
                    self.indicator_mapping.get(&Indicator::Normal)
                }
            })
    }
}

#[cfg(test)]
mod tests {
    use crate::style::{Color, FontStyle, Style};
    use crate::{Indicator, LsColors};

    use std::fs::{self, File};
    use std::path::{Path, PathBuf};

    #[test]
    fn basic_usage() {
        let lscolors = LsColors::from_string("*.wav=00;36:");

        let style_dir = lscolors.style_for_indicator(Indicator::Directory).unwrap();
        assert_eq!(FontStyle::bold(), style_dir.font_style);
        assert_eq!(Some(Color::Blue), style_dir.foreground);
        assert_eq!(None, style_dir.background);

        let style_symlink = lscolors
            .style_for_indicator(Indicator::SymbolicLink)
            .unwrap();
        assert_eq!(FontStyle::bold(), style_symlink.font_style);
        assert_eq!(Some(Color::Cyan), style_symlink.foreground);
        assert_eq!(None, style_symlink.background);

        let style_rs = lscolors.style_for_path("test.wav").unwrap();
        assert_eq!(FontStyle::default(), style_rs.font_style);
        assert_eq!(Some(Color::Cyan), style_rs.foreground);
        assert_eq!(None, style_rs.background);
    }

    #[test]
    fn style_for_path_uses_correct_ordering() {
        let lscolors = LsColors::from_string("*.foo=01;35:*README.foo=33;44");

        // dummy.foo matches to *.foo without getting overriden.
        let style_foo = lscolors.style_for_path("some/folder/dummy.foo").unwrap();
        assert_eq!(FontStyle::bold(), style_foo.font_style);
        assert_eq!(Some(Color::Magenta), style_foo.foreground);
        assert_eq!(None, style_foo.background);

        // README.foo matches to *README.foo by overriding *.foo
        let style_readme = lscolors
            .style_for_path("some/other/folder/README.foo")
            .unwrap();
        assert_eq!(FontStyle::default(), style_readme.font_style);
        assert_eq!(Some(Color::Yellow), style_readme.foreground);
        assert_eq!(Some(Color::Blue), style_readme.background);

        let lscolors = LsColors::from_string("*README.foo=33;44:*.foo=01;35");

        let style_foo = lscolors.style_for_path("some/folder/dummy.foo").unwrap();
        assert_eq!(FontStyle::bold(), style_foo.font_style);
        assert_eq!(Some(Color::Magenta), style_foo.foreground);
        assert_eq!(None, style_foo.background);

        // README.foo matches to *.foo because *.foo overrides *README.foo
        let style_readme = lscolors
            .style_for_path("some/other/folder/README.foo")
            .unwrap();
        assert_eq!(FontStyle::bold(), style_readme.font_style);
        assert_eq!(Some(Color::Magenta), style_readme.foreground);
        assert_eq!(None, style_readme.background);
    }

    #[test]
    fn style_for_path_uses_lowercase_matching() {
        let lscolors = LsColors::from_string("*.O=01;35");

        let style_artifact = lscolors.style_for_path("artifact.o").unwrap();
        assert_eq!(FontStyle::bold(), style_artifact.font_style);
        assert_eq!(Some(Color::Magenta), style_artifact.foreground);
        assert_eq!(None, style_artifact.background);
    }

    #[test]
    fn default_styles_should_be_preserved() {
        // Setting an unrelated style should not influence the default
        // style for "directory" (below)
        let lscolors = LsColors::from_string("ex=01:");

        let style_dir = lscolors.style_for_indicator(Indicator::Directory).unwrap();
        assert_eq!(FontStyle::bold(), style_dir.font_style);
        assert_eq!(Some(Color::Blue), style_dir.foreground);
        assert_eq!(None, style_dir.background);
    }

    fn temp_dir() -> tempfile::TempDir {
        tempfile::tempdir().expect("temporary directory")
    }

    fn create_file<P: AsRef<Path>>(path: P) -> PathBuf {
        File::create(&path).expect("temporary file");
        path.as_ref().to_path_buf()
    }

    fn create_dir<P: AsRef<Path>>(path: P) -> PathBuf {
        fs::create_dir(&path).expect("temporary directory");
        path.as_ref().to_path_buf()
    }

    fn get_default_style<P: AsRef<Path>>(path: P) -> Option<Style> {
        let lscolors = LsColors::default();
        lscolors.style_for_path(path).cloned()
    }

    #[cfg(unix)]
    fn create_symlink<P: AsRef<Path>>(from: P, to: P) {
        std::os::unix::fs::symlink(from, to).expect("temporary symlink");
    }

    #[cfg(windows)]
    fn create_symlink<P: AsRef<Path>>(src: P, dst: P) {
        if src.as_ref().is_dir() {
            std::os::windows::fs::symlink_dir(src, dst).expect("temporary symlink");
        } else {
            std::os::windows::fs::symlink_file(src, dst).expect("temporary symlink");
        }
    }

    #[test]
    fn style_for_str() {
        let lscolors = LsColors::from_string("*.wav=00;36:*.rs=1;38;5;202:");

        assert_eq!(lscolors.style_for_str(""), None);
        assert_eq!(lscolors.style_for_str("test"), None);
        assert_eq!(
            lscolors.style_for_str("test.wav").unwrap().foreground,
            Some(Color::Cyan)
        );
        assert_eq!(
            lscolors.style_for_str("test.rs").unwrap().foreground,
            Some(Color::Fixed(202))
        );
    }

    #[test]
    fn style_for_directory() {
        let tmp_dir = temp_dir();
        let style = get_default_style(tmp_dir.path()).unwrap();
        assert_eq!(Some(Color::Blue), style.foreground);
    }

    #[test]
    fn style_for_file() {
        let tmp_dir = temp_dir();
        let tmp_file_path = create_file(tmp_dir.path().join("test-file"));
        let style = get_default_style(tmp_file_path);
        assert_eq!(None, style);
    }

    #[test]
    fn style_for_symlink() {
        let tmp_dir = temp_dir();
        let tmp_file_path = create_file(tmp_dir.path().join("test-file"));
        let tmp_symlink_path = tmp_dir.path().join("test-symlink");

        create_symlink(&tmp_file_path, &tmp_symlink_path);

        let style = get_default_style(tmp_symlink_path).unwrap();
        assert_eq!(Some(Color::Cyan), style.foreground);
    }

    #[test]
    fn style_for_broken_symlink() {
        let tmp_dir = temp_dir();
        let tmp_file_path = tmp_dir.path().join("non-existing-file");
        let tmp_symlink_path = tmp_dir.path().join("broken-symlink");

        create_symlink(&tmp_file_path, &tmp_symlink_path);

        let lscolors = LsColors::from_string("or=40;31;01:");
        let style = lscolors.style_for_path(tmp_symlink_path).unwrap();
        assert_eq!(Some(Color::Red), style.foreground);
    }

    #[test]
    fn style_for_missing_file() {
        let lscolors1 = LsColors::from_string("mi=01:or=33;44");

        let style_missing = lscolors1
            .style_for_indicator(Indicator::MissingFile)
            .unwrap();
        assert_eq!(FontStyle::bold(), style_missing.font_style);

        let lscolors2 = LsColors::from_string("or=33;44");

        let style_missing = lscolors2
            .style_for_indicator(Indicator::MissingFile)
            .unwrap();
        assert_eq!(Some(Color::Yellow), style_missing.foreground);

        let lscolors3 = LsColors::from_string("or=33;44:mi=00");

        let style_missing = lscolors3
            .style_for_indicator(Indicator::MissingFile)
            .unwrap();
        assert_eq!(Some(Color::Yellow), style_missing.foreground);
    }

    #[cfg(unix)]
    #[test]
    fn style_for_setid() {
        use std::fs::{set_permissions, Permissions};
        use std::os::unix::fs::PermissionsExt;

        let tmp_dir = temp_dir();
        let tmp_file = create_file(tmp_dir.path().join("setid"));
        let perms = Permissions::from_mode(0o6750);
        set_permissions(&tmp_file, perms).unwrap();

        let suid_style = get_default_style(&tmp_file).unwrap();
        assert_eq!(Some(Color::Red), suid_style.background);

        let lscolors = LsColors::from_string("su=0");
        let sgid_style = lscolors.style_for_path(&tmp_file).unwrap();
        assert_eq!(Some(Color::Yellow), sgid_style.background);
    }

    #[cfg(unix)]
    #[test]
    fn style_for_multi_hard_links() {
        let tmp_dir = temp_dir();
        let tmp_file = create_file(tmp_dir.path().join("file1"));
        std::fs::hard_link(&tmp_file, tmp_dir.path().join("file2")).unwrap();

        let lscolors = LsColors::from_string("mh=35");
        let style = lscolors.style_for_path(&tmp_file).unwrap();
        assert_eq!(Some(Color::Magenta), style.foreground);
    }

    #[cfg(unix)]
    #[test]
    fn style_for_sticky_other_writable() {
        use std::fs::{set_permissions, Permissions};
        use std::os::unix::fs::PermissionsExt;

        let tmp_root = temp_dir();
        let tmp_dir = create_dir(tmp_root.path().join("test-dir"));
        let perms = Permissions::from_mode(0o1777);
        set_permissions(&tmp_dir, perms).unwrap();

        let so_style = get_default_style(&tmp_dir).unwrap();
        assert_eq!(Some(Color::Black), so_style.foreground);
        assert_eq!(Some(Color::Green), so_style.background);

        let lscolors1 = LsColors::from_string("tw=0");
        let ow_style = lscolors1.style_for_path(&tmp_dir).unwrap();
        assert_eq!(Some(Color::Blue), ow_style.foreground);
        assert_eq!(Some(Color::Green), ow_style.background);

        let lscolors2 = LsColors::from_string("tw=0:ow=0");
        let st_style = lscolors2.style_for_path(&tmp_dir).unwrap();
        assert_eq!(Some(Color::White), st_style.foreground);
        assert_eq!(Some(Color::Blue), st_style.background);
    }

    #[test]
    fn style_for_path_components() {
        use std::ffi::OsString;

        let tmp_root = temp_dir();
        let tmp_dir = create_dir(tmp_root.path().join("test-dir"));
        create_file(tmp_root.path().join("test-file.png"));

        let tmp_symlink = tmp_root.path().join("test-symlink");
        create_symlink(&tmp_dir, &tmp_symlink);

        let path_via_symlink = tmp_symlink.join("test-file.png");

        let lscolors = LsColors::from_string("di=34:ln=35:*.png=36");

        let mut components: Vec<_> = lscolors
            .style_for_path_components(&path_via_symlink)
            .collect();

        let (c_file, style_file) = components.pop().unwrap();
        assert_eq!("test-file.png", c_file);
        assert_eq!(Some(Color::Cyan), style_file.unwrap().foreground);

        let (c_symlink, style_symlink) = components.pop().unwrap();
        let mut expected_symlink_name = OsString::from("test-symlink");
        expected_symlink_name.push(std::path::MAIN_SEPARATOR.to_string());
        assert_eq!(expected_symlink_name, c_symlink);
        assert_eq!(
            Some(Color::Magenta),
            style_symlink.cloned().and_then(|style| style.foreground)
        );

        let (_, style_dir) = components.pop().unwrap();
        assert_eq!(Some(Color::Blue), style_dir.unwrap().foreground);
    }

    #[test]
    fn style_for_dir_entry() {
        use std::fs::read_dir;

        let tmp_root = temp_dir();
        create_file(tmp_root.path().join("test-file.png"));

        let lscolors = LsColors::from_string("*.png=01;35");

        for entry in read_dir(tmp_root.path()).unwrap() {
            let style = lscolors.style_for(&entry.unwrap()).unwrap();
            assert_eq!(Some(Color::Magenta), style.foreground);
        }
    }

    #[test]
    fn override_disable_suffix() {
        let tmp_dir = temp_dir();
        let tmp_file = create_file(tmp_dir.path().join("test-file.png"));

        let lscolors = LsColors::from_string("*.png=01;35:*.png=0");
        let style = lscolors.style_for_path(&tmp_file);
        assert_eq!(None, style);
    }

    #[test]
    fn file_normal_fallback() {
        let tmp_dir = temp_dir();
        let tmp_file_path = create_file(tmp_dir.path().join("test-file"));

        let lscolors = LsColors::from_string("no=01;31");
        let style = lscolors.style_for_path(&tmp_file_path).unwrap();
        assert_eq!(Some(Color::Red), style.foreground);

        let lscolors = LsColors::from_string("no=01;31:fi=0");
        let style = lscolors.style_for_path(&tmp_file_path);
        assert_eq!(None, style);
    }
    #[test]
    fn file_suffix_case() {
        let assert_bold_fg_magenta = |style: Option<&Style>| {
            Some(Color::Magenta) == style.and_then(|v| v.foreground)
                && matches!(style,Some(sty) if sty.font_style.bold )
        };
        let assert_bold_fg_green = |style: Option<&Style>| {
            Some(Color::Green) == style.and_then(|v| v.foreground)
                && matches!(style,Some(sty) if sty.font_style.bold )
        };

        // *.jpg is specified only once so any suffix that has .jpg should match
        // without caring about the letter case
        let lscolors = LsColors::from_string("*.jpg=01;35:*.Z=01;31");
        let lowercase_suffix = lscolors.style_for_str("img1.jpg");
        assert!(assert_bold_fg_magenta(lowercase_suffix));
        let uppercase_suffix = lscolors.style_for_str("img1.JPG");
        assert!(assert_bold_fg_magenta(uppercase_suffix));
        let mixedcase_suffix = lscolors.style_for_str("img1.JpG");
        assert!(assert_bold_fg_magenta(mixedcase_suffix));

        // *.jpg is specified more than once with different cases and style, so
        // case should matter here
        let lscolors = LsColors::from_string("*.jpg=01;35:*.JPG=01;32");
        let lowercase_suffix = lscolors.style_for_str("img1.jpg");
        assert!(assert_bold_fg_magenta(lowercase_suffix));
        let uppercase_suffix = lscolors.style_for_str("img1.JPG");
        assert!(assert_bold_fg_green(uppercase_suffix));
        let mixedcase_suffix = lscolors.style_for_str("img1.JpG");
        assert!(mixedcase_suffix.is_none());

        // *.jpg is specified more than once with different cases but style is same, so
        // case can ignored
        let lscolors = LsColors::from_string("*.jpg=01;35:*.JPG=01;35");
        let lowercase_suffix = lscolors.style_for_str("img1.jpg");
        assert!(assert_bold_fg_magenta(lowercase_suffix));
        let uppercase_suffix = lscolors.style_for_str("img1.JPG");
        assert!(assert_bold_fg_magenta(uppercase_suffix));
        let mixedcase_suffix = lscolors.style_for_str("img1.JpG");
        assert!(assert_bold_fg_magenta(mixedcase_suffix));

        // last *.jpg gets more priority resulting in same style across
        // different cases specified, so case can ignored
        let lscolors = LsColors::from_string("*.jpg=01;32:*.jpg=01;35:*.JPG=01;35");
        let lowercase_suffix = lscolors.style_for_str("img1.jpg");
        assert!(assert_bold_fg_magenta(lowercase_suffix));
        let uppercase_suffix = lscolors.style_for_str("img1.JPG");
        assert!(assert_bold_fg_magenta(uppercase_suffix));
        let mixedcase_suffix = lscolors.style_for_str("img1.JpG");
        assert!(assert_bold_fg_magenta(mixedcase_suffix));

        // same as above with different combinations
        let lscolors = LsColors::from_string("*.jpg=01;32:*.jpg=01;35:*.JPG=01;32:*.jpg=01;32");
        let lowercase_suffix = lscolors.style_for_str("img1.jpg");
        assert!(assert_bold_fg_green(lowercase_suffix));
        let uppercase_suffix = lscolors.style_for_str("img1.JPG");
        assert!(assert_bold_fg_green(uppercase_suffix));
        let mixedcase_suffix = lscolors.style_for_str("img1.JpG");
        assert!(assert_bold_fg_green(mixedcase_suffix));

        // last *.jpg gets more priority resulting in different style across
        // different cases specified, so case matters
        let lscolors = LsColors::from_string("*.jpg=01;32:*.jpg=01;35:*.JPG=01;32");
        let lowercase_suffix = lscolors.style_for_str("img1.jpg");
        assert!(assert_bold_fg_magenta(lowercase_suffix));
        let uppercase_suffix = lscolors.style_for_str("img1.JPG");
        assert!(assert_bold_fg_green(uppercase_suffix));
        let mixedcase_suffix = lscolors.style_for_str("img1.JpG");
        assert!(mixedcase_suffix.is_none());

        // same as above with different combinations
        let lscolors = LsColors::from_string("*.jpg=01;32:*.jpg=01;35:*.JPG=01;35:*.jpg=01;32");
        let lowercase_suffix = lscolors.style_for_str("img1.jpg");
        assert!(assert_bold_fg_green(lowercase_suffix));
        let uppercase_suffix = lscolors.style_for_str("img1.JPG");
        assert!(assert_bold_fg_magenta(uppercase_suffix));
        let mixedcase_suffix = lscolors.style_for_str("img1.JpG");
        assert!(mixedcase_suffix.is_none());
    }
}