prek 0.5.5

A fast Git hook manager written in Rust, designed as a drop-in alternative to pre-commit, reimagined.
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
use std::borrow::Cow;
use std::fmt::Display;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

use crate::config::validate_group_name;
use crate::hook::Hook;
use crate::warn_user;

use anyhow::anyhow;
use itertools::Itertools;
use owo_colors::OwoColorize;
use prek_consts::env_vars::{EnvVars, EnvVarsRead};
use rustc_hash::FxHashSet;
use tracing::trace;

use crate::fs::PathClean;

#[derive(Debug, Clone, Copy)]
pub(crate) struct ConfiguredHook<'a> {
    project_relative_path: &'a Path,
    id: &'a str,
    alias: Option<&'a str>,
    groups: Option<&'a [String]>,
}

impl<'a> ConfiguredHook<'a> {
    pub(crate) fn new(
        project_relative_path: &'a Path,
        id: &'a str,
        alias: Option<&'a str>,
        groups: Option<&'a [String]>,
    ) -> Self {
        Self {
            project_relative_path,
            id,
            alias,
            groups,
        }
    }
}

#[derive(Debug, thiserror::Error)]
pub(crate) enum Error {
    #[error("Invalid selector: `{selector}`")]
    InvalidSelector {
        selector: String,
        #[source]
        source: anyhow::Error,
    },

    #[error("Invalid project path: `{path}`")]
    InvalidPath {
        path: String,
        #[source]
        source: anyhow::Error,
    },

    #[error("Invalid group selector: `{selector}`")]
    GroupSelector {
        selector: String,
        #[source]
        source: anyhow::Error,
    },
}

#[derive(Debug, Clone, Copy)]
pub(crate) enum SelectorSource {
    CliArg,
    CliFlag(&'static str),
    EnvVar(&'static str),
}

#[derive(Debug, Clone)]
pub(crate) enum SelectorExpr {
    HookId(String),
    ProjectPrefix(PathBuf),
    ProjectHook {
        project_path: PathBuf,
        hook_id: String,
    },
}

#[derive(Debug, Clone)]
pub(crate) struct Selector {
    source: SelectorSource,
    original: String,
    expr: SelectorExpr,
}

impl Display for Selector {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.expr {
            SelectorExpr::HookId(hook_id) => write!(f, "{hook_id}"),
            SelectorExpr::ProjectPrefix(project_path) => {
                if project_path.as_os_str().is_empty() {
                    write!(f, "./")
                } else {
                    write!(f, "{}/", project_path.display())
                }
            }
            SelectorExpr::ProjectHook {
                project_path,
                hook_id,
            } => {
                if project_path.as_os_str().is_empty() {
                    write!(f, ".:{hook_id}")
                } else {
                    write!(f, "{}:{hook_id}", project_path.display())
                }
            }
        }
    }
}

impl Selector {
    pub(crate) fn as_flag(&self) -> Cow<'_, str> {
        match &self.source {
            SelectorSource::CliArg => Cow::Borrowed(&self.original),
            SelectorSource::CliFlag(flag) => Cow::Owned(format!("{}={}", flag, self.original)),
            SelectorSource::EnvVar(var) => Cow::Owned(format!("{}={}", var, self.original)),
        }
    }

    pub(crate) fn as_normalized_flag(&self) -> String {
        match &self.source {
            SelectorSource::CliArg => self.to_string(),
            SelectorSource::CliFlag(flag) => format!("{flag}={self}"),
            SelectorSource::EnvVar(var) => format!("{var}={self}"),
        }
    }

    pub(crate) fn source(&self) -> &SelectorSource {
        &self.source
    }

    pub(crate) fn kind_str(&self) -> &'static str {
        match &self.expr {
            SelectorExpr::HookId(_) | SelectorExpr::ProjectHook { .. } => "hooks",
            SelectorExpr::ProjectPrefix(_) => "projects",
        }
    }
}

impl Selector {
    pub(crate) fn matches_hook(&self, hook: &Hook) -> bool {
        match &self.expr {
            SelectorExpr::HookId(hook_id) => {
                // For bare hook IDs, check if it matches the hook
                &hook.id == hook_id || &hook.alias == hook_id
            }
            SelectorExpr::ProjectPrefix(project_path) => {
                // For project paths, check if the hook belongs to that project.
                hook.project().relative_path().starts_with(project_path)
            }
            SelectorExpr::ProjectHook {
                project_path,
                hook_id,
            } => {
                // For project:hook syntax, check both
                (&hook.id == hook_id || &hook.alias == hook_id)
                    && project_path == hook.project().relative_path()
            }
        }
    }

    fn matches_configured_hook(&self, hook: &ConfiguredHook<'_>) -> bool {
        let matches_hook_id = |selector: &str| {
            hook.id == selector || hook.alias.is_some_and(|alias| alias == selector)
        };

        match &self.expr {
            SelectorExpr::HookId(selector) => matches_hook_id(selector),
            SelectorExpr::ProjectPrefix(project_path) => {
                hook.project_relative_path.starts_with(project_path)
            }
            SelectorExpr::ProjectHook {
                project_path,
                hook_id: selector_hook_id,
            } => {
                project_path.as_path() == hook.project_relative_path
                    && matches_hook_id(selector_hook_id)
            }
        }
    }
}

#[derive(Debug, Clone, Default)]
pub(crate) struct Selectors {
    includes: Vec<Selector>,
    skips: Vec<Selector>,
    usage: Arc<Mutex<FilterUsage>>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum HookSelection {
    Selected,
    Skipped,
    NotSelected,
}

impl Selectors {
    /// Create selectors for one explicit include without applying skip environment variables.
    pub(crate) fn from_include(include: &str, workspace_root: &Path) -> Result<Self, Error> {
        let include = parse_single_selector(
            include,
            workspace_root,
            SelectorSource::CliArg,
            RealFileSystem,
        )?;
        trace!("Include selector: `{include}`");

        Ok(Self {
            includes: vec![include],
            skips: Vec::new(),
            usage: Arc::default(),
        })
    }

    /// Load include and skip selectors from CLI args and environment variables.
    pub(crate) fn load(
        includes: &[String],
        skips: &[String],
        workspace_root: &Path,
    ) -> Result<Selectors, Error> {
        let includes = includes
            .iter()
            .unique()
            .map(|selector| {
                parse_single_selector(
                    selector,
                    workspace_root,
                    SelectorSource::CliArg,
                    RealFileSystem,
                )
            })
            .collect::<Result<Vec<_>, _>>()?;

        trace!(
            "Include selectors: `{}`",
            includes
                .iter()
                .map(ToString::to_string)
                .collect::<Vec<_>>()
                .join(", ")
        );

        let skips = load_skips(skips, workspace_root, RealFileSystem)?;

        trace!(
            "Skip selectors: `{}`",
            skips
                .iter()
                .map(ToString::to_string)
                .collect::<Vec<_>>()
                .join(", ")
        );

        Ok(Self {
            includes,
            skips,
            usage: Arc::default(),
        })
    }

    pub(crate) fn includes(&self) -> &[Selector] {
        &self.includes
    }

    pub(crate) fn skips(&self) -> &[Selector] {
        &self.skips
    }

    pub(crate) fn has_project_selectors(&self) -> bool {
        self.includes.iter().any(|include| {
            matches!(
                include.expr,
                SelectorExpr::ProjectPrefix(_) | SelectorExpr::ProjectHook { .. }
            )
        })
    }

    pub(crate) fn includes_only_hook_targets(&self) -> bool {
        !self.includes.is_empty()
            && self.includes.iter().all(|s| {
                matches!(
                    s.expr,
                    SelectorExpr::HookId(_) | SelectorExpr::ProjectHook { .. }
                )
            })
    }

    /// Select a hook and retain whether an explicit skip caused its exclusion.
    pub(super) fn select_hook(&self, hook: &Hook) -> HookSelection {
        let mut usage = self.usage.lock().unwrap();

        // Always check every selector to track usage
        let mut skipped = false;
        for (idx, skip) in self.skips.iter().enumerate() {
            if skip.matches_hook(hook) {
                usage.use_exclude(idx);
                skipped = true;
            }
        }
        let included = if self.includes.is_empty() {
            true
        } else {
            let mut included = false;
            for (idx, include) in self.includes.iter().enumerate() {
                if include.matches_hook(hook) {
                    usage.use_include(idx);
                    included = true;
                }
            }
            included
        };

        if !included {
            HookSelection::NotSelected
        } else if skipped {
            HookSelection::Skipped
        } else {
            HookSelection::Selected
        }
    }

    /// Check if a hook matches any of the selection criteria.
    pub(crate) fn matches_hook(&self, hook: &Hook) -> bool {
        self.select_hook(hook) == HookSelection::Selected
    }

    /// Return whether skip selectors rule out a hook from config alone.
    ///
    /// Include selectors are intentionally not applied here. Remote hook aliases
    /// can select hooks, but those aliases are only known after cloning the repo.
    /// A non-matching include selector is therefore not enough to rule out a clone
    /// in this generic helper.
    pub(crate) fn excludes_configured_hook(&self, hook: &ConfiguredHook<'_>) -> bool {
        let mut usage = self.usage.lock().unwrap();

        let mut skipped = false;
        for (idx, skip) in self.skips.iter().enumerate() {
            if skip.matches_configured_hook(hook) {
                usage.use_exclude(idx);
                skipped = true;
            }
        }
        skipped
    }

    pub(crate) fn matches_hook_id(&self, hook_id: &str) -> bool {
        let mut usage = self.usage.lock().unwrap();

        // Always check every selector to track usage
        let mut skipped = false;
        for (idx, skip) in self.skips.iter().enumerate() {
            if let SelectorExpr::HookId(id) = &skip.expr {
                if id == hook_id {
                    usage.use_exclude(idx);
                    skipped = true;
                }
            }
        }
        if skipped {
            return false;
        }

        if self.includes.is_empty() {
            return true; // No `includes` mean all hooks are included
        }

        let mut included = false;
        for (idx, include) in self.includes.iter().enumerate() {
            if let SelectorExpr::HookId(id) = &include.expr {
                if id == hook_id {
                    usage.use_include(idx);
                    included = true;
                }
            }
        }
        included
    }

    pub(crate) fn matches_path(&self, path: &Path) -> bool {
        let mut usage = self.usage.lock().unwrap();

        let mut skipped = false;
        for (idx, skip) in self.skips.iter().enumerate() {
            if let SelectorExpr::ProjectPrefix(project_path) = &skip.expr {
                if path.starts_with(project_path) {
                    usage.use_exclude(idx);
                    skipped = true;
                }
            }
        }
        if skipped {
            return false;
        }

        if self.includes.is_empty() {
            return true;
        }

        let mut included = false;
        // This is a project-discovery prefilter, not final hook selection.
        // Keep scanning after a match so project-prefix selectors still get
        // usage recorded for accurate unused-selector warnings.
        for (idx, include) in self.includes.iter().enumerate() {
            match &include.expr {
                SelectorExpr::HookId(_) => {
                    // A bare hook id can match any project, but we cannot mark
                    // it used until final hook filtering proves a hook exists.
                    included = true;
                }
                SelectorExpr::ProjectPrefix(project_path) => {
                    // Project-prefix selectors select projects directly, so a
                    // matching discovered project is enough to mark them used.
                    if path.starts_with(project_path) {
                        usage.use_include(idx);
                        included = true;
                    }
                }
                SelectorExpr::ProjectHook { project_path, .. } => {
                    // `project:hook` only needs this exact project initialized;
                    // usage is still decided by the final hook-id match.
                    if path == project_path {
                        included = true;
                    }
                }
            }
        }
        included
    }

    pub(crate) fn report_unused(&self) {
        let usage = self.usage.lock().unwrap();
        usage.report_unused(self);
    }
}

#[derive(Debug, Clone, Default)]
pub(crate) struct GroupFilters {
    include_any: Vec<GroupSelector>,
    require_all: Vec<GroupSelector>,
    exclude_any: Vec<GroupSelector>,
    usage: Arc<Mutex<FilterUsage>>,
}

#[derive(Debug, Clone)]
enum GroupSelector {
    Named(String),
    Ungrouped,
}

const UNGROUPED_GROUP: &str = "@ungrouped";

impl GroupSelector {
    fn parse(group: &str) -> Result<Self, &'static str> {
        if group == UNGROUPED_GROUP {
            Ok(Self::Ungrouped)
        } else {
            validate_group_name(group)?;
            Ok(Self::Named(group.to_owned()))
        }
    }
}

impl Display for GroupSelector {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Named(group) => f.write_str(group),
            Self::Ungrouped => f.write_str(UNGROUPED_GROUP),
        }
    }
}

impl GroupFilters {
    pub(crate) fn parse(
        include_any: &[String],
        require_all: &[String],
        exclude_any: &[String],
    ) -> Result<Self, Error> {
        let parse_groups = |flag: &'static str, groups: &[String]| {
            let mut seen = FxHashSet::default();
            let mut selectors = Vec::new();

            for group in groups {
                let selector =
                    GroupSelector::parse(group).map_err(|reason| Error::GroupSelector {
                        selector: format!("{flag}={group}"),
                        source: anyhow!("group name {reason}"),
                    })?;
                if seen.insert(group.as_str()) {
                    selectors.push(selector);
                }
            }

            Ok(selectors)
        };

        Ok(Self {
            include_any: parse_groups("--group", include_any)?,
            require_all: parse_groups("--require-group", require_all)?,
            exclude_any: parse_groups("--no-group", exclude_any)?,
            usage: Arc::default(),
        })
    }

    pub(crate) fn has_filters(&self) -> bool {
        !self.include_any.is_empty() || !self.require_all.is_empty() || !self.exclude_any.is_empty()
    }

    fn matches_groups(&self, contains_group: impl Fn(&GroupSelector) -> bool) -> bool {
        let mut usage = self.usage.lock().unwrap();

        let mut matches_any_excluded = false;
        for (idx, exclude) in self.exclude_any.iter().enumerate() {
            if contains_group(exclude) {
                usage.use_exclude(idx);
                matches_any_excluded = true;
            }
        }

        let mut matches_any_included = self.include_any.is_empty();
        for (idx, include) in self.include_any.iter().enumerate() {
            if contains_group(include) {
                usage.use_include(idx);
                matches_any_included = true;
            }
        }

        let mut matches_all_required = true;
        for (idx, requirement) in self.require_all.iter().enumerate() {
            if contains_group(requirement) {
                usage.use_requirement(idx);
            } else {
                matches_all_required = false;
            }
        }

        matches_any_included && matches_all_required && !matches_any_excluded
    }

    pub(crate) fn matches_hook(&self, hook: &Hook) -> bool {
        self.matches_groups(|group| match group {
            GroupSelector::Named(group) => hook.groups.contains(group),
            GroupSelector::Ungrouped => hook.groups.is_empty(),
        })
    }

    pub(crate) fn matches_configured_hook(&self, hook: &ConfiguredHook<'_>) -> bool {
        self.matches_groups(|group| match group {
            GroupSelector::Named(group) => hook
                .groups
                .is_some_and(|groups| groups.iter().any(|hook_group| hook_group == group)),
            GroupSelector::Ungrouped => hook.groups.is_none_or(<[String]>::is_empty),
        })
    }

    pub(crate) fn report_unused(&self) {
        let usage = self.usage.lock().unwrap();
        let unused = usage
            .unused_includes(&self.include_any)
            .map(|(_, group)| format!("--group={group}"))
            .chain(
                usage
                    .unused_requirements(&self.require_all)
                    .map(|(_, group)| format!("--require-group={group}")),
            )
            .chain(
                usage
                    .unused_excludes(&self.exclude_any)
                    .map(|(_, group)| format!("--no-group={group}")),
            )
            .collect::<Vec<_>>();

        match unused.as_slice() {
            [] => {}
            [group] => {
                warn_user!("group selector `{group}` did not match any hooks");
            }
            _ => {
                let warning = unused
                    .iter()
                    .map(|group| format!("  - `{group}`"))
                    .collect::<Vec<_>>()
                    .join("\n");

                warn_user!("the following group selectors did not match any hooks:");
                anstream::eprintln!("{warning}");
            }
        }
    }
}

#[derive(Default, Debug)]
struct FilterUsage {
    includes: FxHashSet<usize>,
    requirements: FxHashSet<usize>,
    excludes: FxHashSet<usize>,
}

impl FilterUsage {
    fn use_include(&mut self, idx: usize) {
        self.includes.insert(idx);
    }

    fn use_requirement(&mut self, idx: usize) {
        self.requirements.insert(idx);
    }

    fn use_exclude(&mut self, idx: usize) {
        self.excludes.insert(idx);
    }

    fn unused_includes<'a, T>(
        &'a self,
        values: &'a [T],
    ) -> impl Iterator<Item = (usize, &'a T)> + 'a {
        values
            .iter()
            .enumerate()
            .filter(|(idx, _)| !self.includes.contains(idx))
    }

    fn unused_excludes<'a, T>(
        &'a self,
        values: &'a [T],
    ) -> impl Iterator<Item = (usize, &'a T)> + 'a {
        values
            .iter()
            .enumerate()
            .filter(|(idx, _)| !self.excludes.contains(idx))
    }

    fn unused_requirements<'a, T>(
        &'a self,
        values: &'a [T],
    ) -> impl Iterator<Item = (usize, &'a T)> + 'a {
        values
            .iter()
            .enumerate()
            .filter(|(idx, _)| !self.requirements.contains(idx))
    }

    fn report_unused(&self, selectors: &Selectors) {
        let unused = self
            .unused_includes(&selectors.includes)
            .chain(self.unused_excludes(&selectors.skips))
            .collect::<Vec<_>>();

        match unused.as_slice() {
            [] => {}
            [(_, selector)] => {
                let flag = selector.as_flag();
                let normalized = selector.as_normalized_flag();
                if flag == normalized {
                    warn_user!(
                        "selector `{flag}` did not match any {}",
                        selector.kind_str()
                    );
                } else {
                    warn_user!(
                        "selector `{flag}` ({}) did not match any {}",
                        format!("normalized to `{normalized}`").dimmed(),
                        selector.kind_str()
                    );
                }
            }
            _ => {
                let warning = unused
                    .iter()
                    .map(|(_, sel)| {
                        let flag = sel.as_flag();
                        let normalized = sel.as_normalized_flag();
                        if flag == normalized {
                            format!("  - `{flag}`")
                        } else {
                            format!(
                                "  - `{flag}` ({})",
                                format!("normalized to `{normalized}`").dimmed()
                            )
                        }
                    })
                    .collect::<Vec<_>>()
                    .join("\n");

                warn_user!("the following selectors did not match any hooks or projects:");
                anstream::eprintln!("{warning}");
            }
        }
    }
}

/// Parse a single selector string into a Selection enum.
fn parse_single_selector<FS: FileSystem>(
    input: &str,
    workspace_root: &Path,
    source: SelectorSource,
    fs: FS,
) -> Result<Selector, Error> {
    // Handle `project:hook` syntax
    if let Some((project_path, hook_id)) = input.split_once(':') {
        if hook_id.is_empty() {
            return Err(Error::InvalidSelector {
                selector: input.to_string(),
                source: anyhow!("hook ID part is empty"),
            });
        }
        if project_path.is_empty() {
            return Ok(Selector {
                source,
                original: input.to_string(),
                expr: SelectorExpr::HookId(hook_id.to_string()),
            });
        }

        let project_path = normalize_path(project_path, workspace_root, fs).map_err(|e| {
            Error::InvalidSelector {
                selector: input.to_string(),
                source: anyhow!(e),
            }
        })?;

        return Ok(Selector {
            source,
            original: input.to_string(),
            expr: SelectorExpr::ProjectHook {
                project_path,
                hook_id: hook_id.to_string(),
            },
        });
    }

    // Handle project paths
    if input == "." || input.contains('/') {
        let project_path =
            normalize_path(input, workspace_root, fs).map_err(|e| Error::InvalidSelector {
                selector: input.to_string(),
                source: anyhow!(e),
            })?;

        return Ok(Selector {
            source,
            original: input.to_string(),
            expr: SelectorExpr::ProjectPrefix(project_path),
        });
    }

    // Ambiguous case: treat as hook ID for backward compatibility
    if input.is_empty() {
        return Err(Error::InvalidSelector {
            selector: input.to_string(),
            source: anyhow!("cannot be empty"),
        });
    }
    Ok(Selector {
        source,
        original: input.to_string(),
        expr: SelectorExpr::HookId(input.to_string()),
    })
}

/// Trait to abstract filesystem operations for easier testing.
pub trait FileSystem: Copy {
    fn absolute<P: AsRef<Path>>(&self, path: P) -> std::io::Result<PathBuf>;
}

#[derive(Copy, Clone)]
pub struct RealFileSystem;

impl FileSystem for RealFileSystem {
    fn absolute<P: AsRef<Path>>(&self, path: P) -> std::io::Result<PathBuf> {
        Ok(std::path::absolute(path)?.clean())
    }
}

/// Normalize a project path to the relative path from the workspace root.
/// In workspace root:
/// './project/' -> 'project'
/// 'project/sub/' -> 'project/sub'
/// '.' -> ''
/// './' -> ''
/// '..' -> Error
/// '../project/' -> Error
/// '/absolute/path/' -> if inside workspace, relative path; else Error
/// In subdirectory of workspace (e.g., 'workspace/subdir'):
/// './project/' -> 'subdir/project'
/// 'project/' -> 'subdir/project'
/// '../project/' -> 'project'
/// '..' -> ''
fn normalize_path<FS: FileSystem>(
    path: &str,
    workspace_root: &Path,
    fs: FS,
) -> Result<PathBuf, Error> {
    let absolute_path = fs.absolute(path).map_err(|e| Error::InvalidPath {
        path: path.to_string(),
        source: anyhow!(e),
    })?;
    let absolute_path = absolute_path.clean();

    let rel_path = absolute_path
        .strip_prefix(workspace_root)
        .map_err(|_| Error::InvalidPath {
            path: path.to_string(),
            source: anyhow!("path is outside the workspace root"),
        })?;

    Ok(rel_path.to_path_buf())
}

/// Parse skip selectors from CLI args and environment variables
pub(crate) fn load_skips<FS: FileSystem>(
    cli_skips: &[String],
    workspace_root: &Path,
    fs: FS,
) -> Result<Vec<Selector>, Error> {
    let prek_skip = EnvVars.var(EnvVars::PREK_SKIP);
    let skip = EnvVars.var(EnvVars::SKIP);

    let (skips, source) = if !cli_skips.is_empty() {
        (
            cli_skips.iter().map(String::as_str).collect::<Vec<_>>(),
            SelectorSource::CliFlag("--skip"),
        )
    } else if let Ok(s) = &prek_skip {
        (
            parse_comma_separated(s).collect(),
            SelectorSource::EnvVar(EnvVars::PREK_SKIP),
        )
    } else if let Ok(s) = &skip {
        (
            parse_comma_separated(s).collect(),
            SelectorSource::EnvVar(EnvVars::SKIP),
        )
    } else {
        return Ok(vec![]);
    };

    skips
        .into_iter()
        .unique()
        .map(|skip| parse_single_selector(skip, workspace_root, source, fs))
        .collect()
}

/// Parse comma-separated values, trimming whitespace and filtering empty strings
fn parse_comma_separated(input: &str) -> impl Iterator<Item = &str> {
    input.split(',').map(str::trim).filter(|s| !s.is_empty())
}

#[cfg(test)]
mod tests {
    use std::assert_matches;

    use super::*;
    use tempfile::TempDir;

    struct MockFileSystem {
        current_dir: TempDir,
    }

    impl FileSystem for &MockFileSystem {
        fn absolute<P: AsRef<Path>>(&self, path: P) -> std::io::Result<PathBuf> {
            let p = path.as_ref();
            if p.is_absolute() {
                Ok(p.to_path_buf())
            } else {
                Ok(self.current_dir.path().join(p))
            }
        }
    }

    impl MockFileSystem {
        fn root(&self) -> &Path {
            self.current_dir.path()
        }
    }

    fn create_test_workspace() -> anyhow::Result<MockFileSystem> {
        let temp_dir = TempDir::new()?;

        fs_err::create_dir_all(temp_dir.path().join("src"))?;
        fs_err::create_dir_all(temp_dir.path().join("src/backend"))?;

        Ok(MockFileSystem {
            current_dir: temp_dir,
        })
    }

    #[test]
    fn test_parse_single_selector_hook_id() -> anyhow::Result<()> {
        let fs = create_test_workspace()?;

        // Test explicit hook ID with colon prefix
        let selector = parse_single_selector(":black", fs.root(), SelectorSource::CliArg, &fs)?;
        assert_matches!(selector.expr, SelectorExpr::HookId(ref id) if id == "black");

        let selector = parse_single_selector(":lint:ruff", fs.root(), SelectorSource::CliArg, &fs)?;
        assert_matches!(selector.expr, SelectorExpr::HookId(ref id) if id == "lint:ruff");

        // Test bare hook ID (backward compatibility)
        let selector = parse_single_selector("black", fs.root(), SelectorSource::CliArg, &fs)?;
        assert_matches!(selector.expr, SelectorExpr::HookId(ref id) if id == "black");

        Ok(())
    }

    #[test]
    fn test_parse_single_selector_project_prefix() -> anyhow::Result<()> {
        let fs = create_test_workspace()?;

        // Test project path with slash
        let selector = parse_single_selector("src/", fs.root(), SelectorSource::CliArg, &fs)?;
        assert_matches!(
            selector.expr,
            SelectorExpr::ProjectPrefix(ref path) if path == &PathBuf::from("src")
        );

        // Test current directory
        let selector = parse_single_selector(".", fs.root(), SelectorSource::CliArg, &fs)?;
        assert_matches!(
            selector.expr,
            SelectorExpr::ProjectPrefix(ref path) if path == &PathBuf::from("")
        );
        let selector = parse_single_selector("./", fs.root(), SelectorSource::CliArg, &fs)?;
        assert_matches!(
            selector.expr,
            SelectorExpr::ProjectPrefix(ref path) if path == &PathBuf::from("")
        );

        Ok(())
    }

    #[test]
    fn test_parse_single_selector_project_hook() -> anyhow::Result<()> {
        let fs = create_test_workspace()?;

        let selector = parse_single_selector("src:black", fs.root(), SelectorSource::CliArg, &fs)?;
        match selector.expr {
            SelectorExpr::ProjectHook {
                project_path,
                hook_id,
            } => {
                assert_eq!(project_path, PathBuf::from("src"));
                assert_eq!(hook_id, "black");
            }
            _ => panic!("Expected ProjectHook"),
        }

        let selector =
            parse_single_selector("src:lint:ruff", fs.root(), SelectorSource::CliArg, &fs)?;
        match selector.expr {
            SelectorExpr::ProjectHook {
                project_path,
                hook_id,
            } => {
                assert_eq!(project_path, PathBuf::from("src"));
                assert_eq!(hook_id, "lint:ruff");
            }
            _ => panic!("Expected ProjectHook"),
        }

        Ok(())
    }

    #[test]
    fn test_parse_single_selector_invalid() -> anyhow::Result<()> {
        let fs = create_test_workspace()?;

        // Test empty hook ID
        let result = parse_single_selector(":", fs.root(), SelectorSource::CliArg, &fs);
        assert!(result.is_err());

        // Test empty hook ID in project:hook
        let result = parse_single_selector("src:", fs.root(), SelectorSource::CliArg, &fs);
        assert!(result.is_err());

        // Test empty string
        let result = parse_single_selector("", fs.root(), SelectorSource::CliArg, &fs);
        assert!(result.is_err());

        Ok(())
    }

    #[test]
    fn test_normalize_path() -> anyhow::Result<()> {
        let fs = create_test_workspace()?;

        // Test relative path
        let result = normalize_path("src", fs.root(), &fs)?;
        assert_eq!(result, PathBuf::from("src"));

        // Test nested path
        let result = normalize_path("src/backend", fs.root(), &fs)?;
        assert_eq!(result, PathBuf::from("src/backend"));

        // Test current directory
        let result = normalize_path(".", fs.root(), &fs)?;
        assert_eq!(result, PathBuf::from(""));

        // Test path outside workspace - create a temp dir outside workspace
        let outside_dir = TempDir::new()?;
        let outside_path = outside_dir.path().to_string_lossy();
        let result = normalize_path(&outside_path, fs.root(), &fs);
        assert!(result.is_err());

        Ok(())
    }

    #[test]
    fn test_selector_display() -> anyhow::Result<()> {
        let fs = create_test_workspace()?;

        let selector = parse_single_selector("black", fs.root(), SelectorSource::CliArg, &fs)?;
        assert_eq!(selector.to_string(), "black");

        let selector = parse_single_selector(":black", fs.root(), SelectorSource::CliArg, &fs)?;
        assert_eq!(selector.to_string(), "black");

        let selector = parse_single_selector(":lint:ruff", fs.root(), SelectorSource::CliArg, &fs)?;
        assert_eq!(selector.to_string(), "lint:ruff");

        let selector = parse_single_selector("src/", fs.root(), SelectorSource::CliArg, &fs)?;
        assert_eq!(selector.to_string(), "src/");

        let selector = parse_single_selector("./src/", fs.root(), SelectorSource::CliArg, &fs)?;
        assert_eq!(selector.to_string(), "src/");

        let selector = parse_single_selector("src/", fs.root(), SelectorSource::CliArg, &fs)?;
        assert_eq!(selector.to_string(), "src/");

        let selector = parse_single_selector(".", fs.root(), SelectorSource::CliArg, &fs)?;
        assert_eq!(selector.to_string(), "./");

        let selector = parse_single_selector("./", fs.root(), SelectorSource::CliArg, &fs)?;
        assert_eq!(selector.to_string(), "./");

        let selector = parse_single_selector("src:black", fs.root(), SelectorSource::CliArg, &fs)?;
        assert_eq!(selector.to_string(), "src:black");

        let selector =
            parse_single_selector("./src:black", fs.root(), SelectorSource::CliArg, &fs)?;
        assert_eq!(selector.to_string(), "src:black");

        let selector =
            parse_single_selector("./src/:black", fs.root(), SelectorSource::CliArg, &fs)?;
        assert_eq!(selector.to_string(), "src:black");

        let selector =
            parse_single_selector("src:lint:ruff", fs.root(), SelectorSource::CliArg, &fs)?;
        assert_eq!(selector.to_string(), "src:lint:ruff");

        Ok(())
    }

    fn test_selector(expr: SelectorExpr) -> Selector {
        Selector {
            source: SelectorSource::CliArg,
            original: "selector".to_string(),
            expr,
        }
    }

    fn configured_hook(
        project_relative_path: &'static str,
        id: &'static str,
        alias: Option<&'static str>,
    ) -> ConfiguredHook<'static> {
        ConfiguredHook::new(Path::new(project_relative_path), id, alias, None)
    }

    #[test]
    fn test_selector_matches_configured_hook() {
        let cases = [
            (
                "hook id matches id",
                test_selector(SelectorExpr::HookId("black".to_string())),
                configured_hook("src", "black", None),
                true,
            ),
            (
                "hook id matches config alias",
                test_selector(SelectorExpr::HookId("black".to_string())),
                configured_hook("src", "ruff", Some("black")),
                true,
            ),
            (
                "project prefix matches nested project",
                test_selector(SelectorExpr::ProjectPrefix(PathBuf::from("src"))),
                configured_hook("src/backend", "black", None),
                true,
            ),
            (
                "project prefix rejects other project",
                test_selector(SelectorExpr::ProjectPrefix(PathBuf::from("src"))),
                configured_hook("tests", "black", None),
                false,
            ),
            (
                "project hook matches exact project and id",
                test_selector(SelectorExpr::ProjectHook {
                    project_path: PathBuf::from("src"),
                    hook_id: "black".to_string(),
                }),
                configured_hook("src", "black", None),
                true,
            ),
            (
                "project hook matches exact project and config alias",
                test_selector(SelectorExpr::ProjectHook {
                    project_path: PathBuf::from("src"),
                    hook_id: "black".to_string(),
                }),
                configured_hook("src", "ruff", Some("black")),
                true,
            ),
            (
                "project hook rejects nested project prefix",
                test_selector(SelectorExpr::ProjectHook {
                    project_path: PathBuf::from("src"),
                    hook_id: "black".to_string(),
                }),
                configured_hook("src/backend", "black", None),
                false,
            ),
            (
                "project hook rejects other hook",
                test_selector(SelectorExpr::ProjectHook {
                    project_path: PathBuf::from("src"),
                    hook_id: "black".to_string(),
                }),
                configured_hook("src", "ruff", Some("format")),
                false,
            ),
        ];

        for (name, selector, hook, expected) in cases {
            assert_eq!(selector.matches_configured_hook(&hook), expected, "{name}");
        }
    }

    #[test]
    fn test_selector_as_flag() {
        let selector = Selector {
            source: SelectorSource::CliArg,
            original: "black".to_string(),
            expr: SelectorExpr::HookId("black".to_string()),
        };
        assert_eq!(selector.as_flag(), "black");

        let selector = Selector {
            source: SelectorSource::CliFlag("--skip"),
            original: "black".to_string(),
            expr: SelectorExpr::HookId("black".to_string()),
        };
        assert_eq!(selector.as_flag(), "--skip=black");

        let selector = Selector {
            source: SelectorSource::EnvVar("SKIP"),
            original: "black".to_string(),
            expr: SelectorExpr::HookId("black".to_string()),
        };
        assert_eq!(selector.as_flag(), "SKIP=black");
    }
}