cfgmatic-paths 2.1.0

Cross-platform configuration path discovery following XDG and platform conventions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
//! Builder for creating path finders and directory scanners.

use crate::core::{
    AppType, ConfigCandidate, ConfigDiscovery, ConfigFileRule, ConfigRuleSet, ConfigTier,
    DiscoveryOptions, FilePattern, FragmentRule, PathStatus, RuleBasedDiscovery, RuleMatchResult,
    SourceType,
};
use crate::env::StdEnv;
use crate::platform::{DirectoryFinder, DirectoryInfo};
use crate::{Fs, StdFs};
use std::path::{Path, PathBuf};
use std::sync::Arc;

/// Builder for creating platform-specific path finders.
///
/// # Examples
///
/// ```
/// use cfgmatic_paths::{PathsBuilder, AppType};
///
/// // CLI application with XDG directories
/// let finder = PathsBuilder::new("myapp")
///     .app_type(AppType::Cli)
///     .build();
///
/// let user_dirs = finder.user_dirs();
/// ```
#[derive(Debug, Clone)]
pub struct PathsBuilder {
    /// Application name used in paths.
    app_name: String,
    /// Type of application (CLI, GUI, Service).
    app_type: AppType,
    /// Windows-specific company name.
    #[cfg(windows)]
    company_name: Option<String>,
    /// macOS GUI-specific bundle ID.
    #[cfg(all(target_os = "macos", feature = "macos-gui"))]
    bundle_id: Option<String>,
    /// Whether to include legacy `~/.apprc` fallback.
    legacy_rc: bool,
}

impl PathsBuilder {
    /// Create a new builder.
    pub fn new(app_name: impl Into<String>) -> Self {
        Self {
            app_name: app_name.into(),
            app_type: AppType::default(),
            #[cfg(windows)]
            company_name: None,
            #[cfg(all(target_os = "macos", feature = "macos-gui"))]
            bundle_id: None,
            legacy_rc: true,
        }
    }

    /// Set the application type.
    #[must_use]
    pub const fn app_type(mut self, app_type: AppType) -> Self {
        self.app_type = app_type;
        self
    }

    /// Enable/disable legacy `~/.apprc` fallback (Unix only).
    #[must_use]
    pub const fn legacy_rc(mut self, enabled: bool) -> Self {
        self.legacy_rc = enabled;
        self
    }

    /// Windows: set the company name.
    #[cfg(windows)]
    pub fn company_name(mut self, name: impl Into<String>) -> Self {
        self.company_name = Some(name.into());
        self
    }

    /// macOS GUI: set the bundle ID.
    #[cfg(all(target_os = "macos", feature = "macos-gui"))]
    #[must_use]
    pub fn bundle_id(mut self, id: impl Into<String>) -> Self {
        self.bundle_id = Some(id.into());
        self
    }

    /// Build the platform-specific directory finder.
    #[must_use]
    pub fn build(self) -> PathFinder {
        let dir_finder = self.build_directory_finder();
        PathFinder {
            dir_finder,
            fs: Arc::new(StdFs),
        }
    }

    /// Build the directory finder (internal).
    fn build_directory_finder(self) -> Box<dyn DirectoryFinder> {
        cfg_if::cfg_if! {
            if #[cfg(all(target_os = "macos", feature = "macos-gui"))] {
                use crate::platform::MacOSGuiDirectoryFinder;
                use crate::platform::UnixDirectoryFinder;
                if self.app_type == AppType::Gui {
                    let bundle_id = self.bundle_id.unwrap_or_else(|| {
                        format!("com.example.{}", self.app_name)
                    });
                    Box::new(MacOSGuiDirectoryFinder::new(bundle_id))
                } else {
                    // CLI on macOS uses XDG
                    Box::new(UnixDirectoryFinder::new(self.app_name).legacy_rc(self.legacy_rc))
                }
            } else if #[cfg(windows)] {
                use crate::platform::WindowsDirectoryFinder;
                let company_name = self.company_name.unwrap_or_else(|| {
                    self.app_name.clone()
                });
                Box::new(WindowsDirectoryFinder::new(self.app_name, company_name))
            } else {
                use crate::platform::UnixDirectoryFinder;
                // Unix/Linux or macOS CLI
                Box::new(UnixDirectoryFinder::new(self.app_name).legacy_rc(self.legacy_rc))
            }
        }
    }
}

/// Path finder for discovering configuration directories.
///
/// Provides methods to find configuration directories following
/// platform conventions (XDG on Unix, Known Folders on Windows,
/// Application Support on macOS).
pub struct PathFinder {
    /// Platform-specific directory finder.
    dir_finder: Box<dyn DirectoryFinder>,
    /// Filesystem abstraction.
    fs: Arc<dyn Fs>,
}

impl PathFinder {
    /// Get all user directories.
    #[must_use]
    pub fn user_dirs(&self) -> Vec<PathBuf> {
        self.dir_finder.user_dirs(&StdEnv)
    }

    /// Get all local directories.
    #[must_use]
    pub fn local_dirs(&self) -> Vec<PathBuf> {
        self.dir_finder.local_dirs(&StdEnv)
    }

    /// Get all system directories.
    #[must_use]
    pub fn system_dirs(&self) -> Vec<PathBuf> {
        self.dir_finder.system_dirs(&StdEnv)
    }

    /// Get all directories with their tiers.
    #[must_use]
    pub fn all_dirs(&self) -> Vec<DirectoryInfo> {
        [
            self.dirs_with_tier(self.user_dirs(), ConfigTier::User),
            self.dirs_with_tier(self.local_dirs(), ConfigTier::Local),
            self.dirs_with_tier(self.system_dirs(), ConfigTier::System),
        ]
        .into_iter()
        .flatten()
        .collect()
    }

    /// Get the primary user config directory (first user directory).
    #[must_use]
    pub fn user_config_dir(&self) -> Option<PathBuf> {
        self.user_dirs().into_iter().next()
    }

    /// Ensure the user config directory exists, creating it if necessary.
    ///
    /// Returns the path to the directory, or an error if creation fails.
    ///
    /// # Errors
    ///
    /// Returns an error if no user config directory is found or if creation fails.
    pub fn ensure_user_config_dir(&self) -> std::io::Result<PathBuf> {
        let path = self.user_config_dir().ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::NotFound,
                "No user config directory found",
            )
        })?;
        self.fs.create_dir_all(&path)?;
        Ok(path)
    }

    /// Get the preferred user config path (without checking existence).
    ///
    /// Returns the first user config directory path, regardless of whether
    /// it exists. This is useful for determining where to create a new
    /// configuration file.
    ///
    /// # Examples
    ///
    /// ```
    /// use cfgmatic_paths::PathsBuilder;
    ///
    /// let finder = PathsBuilder::new("myapp").build();
    /// let path = finder.preferred_config_path();
    /// println!("Config would be at: {}", path.display());
    /// ```
    #[must_use]
    pub fn preferred_config_path(&self) -> PathBuf {
        self.user_dirs()
            .into_iter()
            .next()
            .unwrap_or_else(|| PathBuf::from(".config").join("myapp"))
    }

    /// Get the preferred config path with a filename appended.
    ///
    /// # Examples
    ///
    /// ```
    /// use cfgmatic_paths::PathsBuilder;
    ///
    /// let finder = PathsBuilder::new("myapp").build();
    /// let path = finder.preferred_config_file("config.toml");
    /// println!("Config file would be at: {}", path.display());
    /// ```
    #[must_use]
    pub fn preferred_config_file(&self, filename: impl AsRef<Path>) -> PathBuf {
        self.preferred_config_path().join(filename)
    }

    /// Discover configuration with full diagnostics.
    ///
    /// Searches all configuration locations and returns comprehensive
    /// information about what was found, including the preferred path
    /// for creating new configurations.
    ///
    /// # Examples
    ///
    /// ```
    /// use cfgmatic_paths::PathsBuilder;
    ///
    /// let finder = PathsBuilder::new("myapp").build();
    /// let discovery = finder.discover_config();
    ///
    /// println!("Preferred path: {}", discovery.preferred_path.display());
    /// if let Some(found) = &discovery.found_path {
    ///     println!("Found config at: {}", found.display());
    /// }
    ///
    /// for candidate in discovery.candidates {
    ///     println!("  - {:?}: {} ({:?})",
    ///         candidate.tier,
    ///         candidate.path.display(),
    ///         candidate.status
    ///     );
    /// }
    /// ```
    #[must_use]
    pub fn discover_config(&self) -> ConfigDiscovery {
        self.discover_config_with_options(&DiscoveryOptions::default())
    }

    /// Discover configuration with custom options.
    ///
    /// Allows customization of the discovery process including
    /// file patterns, fragment discovery, and legacy path inclusion.
    ///
    /// # Examples
    ///
    /// ```
    /// use cfgmatic_paths::{PathsBuilder, FilePattern, DiscoveryOptions};
    ///
    /// let finder = PathsBuilder::new("myapp").build();
    ///
    /// let options = DiscoveryOptions::new()
    ///     .with_pattern(FilePattern::extensions("config", &["toml", "yaml"]))
    ///     .with_fragments(true)
    ///     .with_fragment_dir("conf.d");
    ///
    /// let discovery = finder.discover_config_with_options(&options);
    /// ```
    #[must_use]
    pub fn discover_config_with_options(&self, options: &DiscoveryOptions) -> ConfigDiscovery {
        let mut candidates = Vec::new();
        let mut fragments = Vec::new();
        let mut found_path: Option<PathBuf> = None;

        // Collect directories with their tiers
        let tiers = [
            (self.dir_finder.user_dirs(&StdEnv), ConfigTier::User),
            (self.dir_finder.local_dirs(&StdEnv), ConfigTier::Local),
            (self.dir_finder.system_dirs(&StdEnv), ConfigTier::System),
        ];

        // Build candidates for each tier
        for (dirs, tier) in tiers {
            self.build_candidates_for_tier(
                &dirs,
                tier,
                options,
                &mut candidates,
                &mut fragments,
                &mut found_path,
            );
        }

        // Sort candidates by tier priority (highest first)
        candidates.sort_by(|a, b| b.tier.cmp(&a.tier));

        ConfigDiscovery {
            preferred_path: self.preferred_config_path(),
            found_path,
            candidates,
            fragments,
        }
    }

    /// Find all configuration files matching a pattern.
    ///
    /// Searches all configuration directories for files matching the
    /// given pattern and returns them as candidates with status information.
    ///
    /// # Examples
    ///
    /// ```
    /// use cfgmatic_paths::{PathsBuilder, FilePattern};
    ///
    /// let finder = PathsBuilder::new("myapp").build();
    /// let pattern = FilePattern::extensions("config", &["toml", "yaml", "json"]);
    ///
    /// let configs = finder.find_config_files(&pattern);
    /// for config in configs {
    ///     if config.exists() {
    ///         println!("Found: {}", config.path.display());
    ///     }
    /// }
    /// ```
    #[must_use]
    pub fn find_config_files(&self, pattern: &FilePattern) -> Vec<ConfigCandidate> {
        let mut candidates = Vec::new();

        let tiers = [
            (self.dir_finder.user_dirs(&StdEnv), ConfigTier::User),
            (self.dir_finder.local_dirs(&StdEnv), ConfigTier::Local),
            (self.dir_finder.system_dirs(&StdEnv), ConfigTier::System),
        ];

        for (dirs, tier) in tiers {
            self.find_files_in_dirs(&dirs, tier, pattern, &mut candidates);
        }

        candidates.sort_by(|a, b| b.tier.cmp(&a.tier));
        candidates
    }

    /// Find configuration fragments from conf.d-style directories.
    ///
    /// Searches for fragment directories (like `/etc/myapp/conf.d/`) and
    /// returns all matching configuration files within them.
    ///
    /// # Examples
    ///
    /// ```
    /// use cfgmatic_paths::{PathsBuilder, FilePattern};
    ///
    /// let finder = PathsBuilder::new("myapp").build();
    /// let pattern = FilePattern::glob("*.conf");
    ///
    /// let fragments = finder.find_fragments(&pattern, "conf.d");
    /// for frag in &fragments {
    ///     println!("Fragment: {}", frag.display());
    /// }
    /// ```
    #[must_use]
    pub fn find_fragments(&self, pattern: &FilePattern, fragment_dir_name: &str) -> Vec<PathBuf> {
        let mut fragments = Vec::new();

        // Search for conf.d directories in each tier
        let dirs_by_tier: [(Vec<PathBuf>, ConfigTier); 3] = [
            (self.dir_finder.user_dirs(&StdEnv), ConfigTier::User),
            (self.dir_finder.local_dirs(&StdEnv), ConfigTier::Local),
            (self.dir_finder.system_dirs(&StdEnv), ConfigTier::System),
        ];

        for (dirs, _tier) in dirs_by_tier {
            for base_dir in dirs {
                let conf_d = base_dir.join(fragment_dir_name);
                if self.fs.is_dir(&conf_d) {
                    // Find matching files in this directory
                    for entry in self.fs.read_dir(&conf_d) {
                        if pattern.matches(&entry) && self.fs.is_file(&entry) {
                            fragments.push(entry);
                        }
                    }
                }
            }
        }

        fragments.sort();
        fragments
    }

    /// Get all config directories where a file could be placed.
    ///
    /// Returns all directories in priority order where configuration
    /// files could be located, regardless of whether they exist.
    ///
    /// # Examples
    ///
    /// ```
    /// use cfgmatic_paths::PathsBuilder;
    ///
    /// let finder = PathsBuilder::new("myapp").build();
    /// let dirs = finder.config_directories();
    ///
    /// for dir in dirs {
    ///     println!("Config directory: {}", dir.display());
    /// }
    /// ```
    #[must_use]
    pub fn config_directories(&self) -> Vec<PathBuf> {
        [
            self.dir_finder.user_dirs(&StdEnv),
            self.dir_finder.local_dirs(&StdEnv),
            self.dir_finder.system_dirs(&StdEnv),
        ]
        .into_iter()
        .flatten()
        .collect()
    }

    /// Get the path status of a specific configuration path.
    ///
    /// # Examples
    ///
    /// ```
    /// use cfgmatic_paths::PathsBuilder;
    ///
    /// let finder = PathsBuilder::new("myapp").build();
    /// let path = finder.preferred_config_file("config.toml");
    ///
    /// let status = finder.path_status(&path);
    /// println!("Path status: {:?}", status);
    /// ```
    #[must_use]
    pub fn path_status(&self, path: &Path) -> PathStatus {
        if !self.fs.exists(path) {
            PathStatus::NotFound
        } else if self.fs.is_file(path) {
            PathStatus::File
        } else {
            PathStatus::Directory
        }
    }

    /// Build candidates for a specific tier.
    fn build_candidates_for_tier(
        &self,
        dirs: &[PathBuf],
        tier: ConfigTier,
        options: &DiscoveryOptions,
        candidates: &mut Vec<ConfigCandidate>,
        fragments: &mut Vec<PathBuf>,
        found_path: &mut Option<PathBuf>,
    ) {
        for dir in dirs {
            // Check the directory itself
            let status = if self.fs.exists(dir) {
                if self.fs.is_dir(dir) {
                    PathStatus::Directory
                } else {
                    PathStatus::File
                }
            } else {
                PathStatus::NotFound
            };

            // Determine source type (first is main, others might be legacy)
            let source_type = if candidates.is_empty() && found_path.is_none() {
                SourceType::MainFile
            } else {
                SourceType::Legacy
            };

            candidates.push(ConfigCandidate::new(dir.clone(), status, tier, source_type));

            // If this is the first found config, record it
            if found_path.is_none() && status.exists() {
                *found_path = Some(dir.clone());
            }

            // Check for config files in the directory
            if status == PathStatus::Directory {
                self.check_dir_for_configs(dir, tier, options, candidates, found_path);
            }

            // Check for fragments directory
            if options.include_fragments {
                let conf_d = dir.join(&options.fragment_dir);
                if self.fs.is_dir(&conf_d) {
                    candidates.push(ConfigCandidate::new(
                        conf_d.clone(),
                        PathStatus::Directory,
                        tier,
                        SourceType::FragmentsDir,
                    ));

                    // Collect fragment files
                    for entry in self.fs.read_dir(&conf_d) {
                        if self.fs.is_file(&entry)
                            && (fragments.is_empty() || !fragments.contains(&entry))
                        {
                            fragments.push(entry);
                        }
                    }
                }
            }
        }
    }

    /// Check a directory for configuration files.
    fn check_dir_for_configs(
        &self,
        dir: &Path,
        tier: ConfigTier,
        options: &DiscoveryOptions,
        candidates: &mut Vec<ConfigCandidate>,
        found_path: &mut Option<PathBuf>,
    ) {
        // Try concrete filenames from pattern
        if let Some(filenames) = options.pattern.concrete_filenames() {
            for filename in filenames {
                let file_path = dir.join(&filename);
                let status = self.path_status(&file_path);

                candidates.push(ConfigCandidate::new(
                    file_path.clone(),
                    status,
                    tier,
                    SourceType::MainFile,
                ));

                if found_path.is_none() && status.exists() {
                    *found_path = Some(file_path);
                }
            }
        }
    }

    /// Find files matching pattern in directories.
    fn find_files_in_dirs(
        &self,
        dirs: &[PathBuf],
        tier: ConfigTier,
        pattern: &FilePattern,
        candidates: &mut Vec<ConfigCandidate>,
    ) {
        for dir in dirs {
            if !self.fs.is_dir(dir) {
                // Check if the directory path itself matches as a file
                let status = self.path_status(dir);
                if pattern.matches(dir) {
                    candidates.push(ConfigCandidate::new(
                        dir.clone(),
                        status,
                        tier,
                        SourceType::MainFile,
                    ));
                }
                continue;
            }

            // Directory exists - search for matching files
            for entry in self.fs.read_dir(dir) {
                if pattern.matches(&entry) {
                    let status = self.path_status(&entry);
                    candidates.push(ConfigCandidate::new(
                        entry.clone(),
                        status,
                        tier,
                        SourceType::MainFile,
                    ));
                }
            }

            // Also check concrete filenames directly
            if let Some(filenames) = pattern.concrete_filenames() {
                for filename in filenames {
                    let file_path = dir.join(&filename);
                    if pattern.matches(&file_path) {
                        let status = self.path_status(&file_path);
                        candidates.push(ConfigCandidate::new(
                            file_path,
                            status,
                            tier,
                            SourceType::MainFile,
                        ));
                    }
                }
            }
        }
    }

    /// Convert paths to directory info with tier.
    fn dirs_with_tier(&self, paths: Vec<PathBuf>, tier: ConfigTier) -> Vec<DirectoryInfo> {
        paths
            .into_iter()
            .map(|path| DirectoryInfo {
                exists: self.fs.is_dir(&path),
                path,
                tier,
            })
            .collect()
    }

    /// Discover configuration files using a rule set.
    ///
    /// Uses the provided rule set to discover all configuration files,
    /// including main files and fragments. Returns a detailed result
    /// with all matched files grouped by rule.
    ///
    /// # Examples
    ///
    /// ```
    /// use cfgmatic_paths::{PathsBuilder, ConfigRuleSet, ConfigFileRule, FragmentRule};
    ///
    /// let finder = PathsBuilder::new("myapp").build();
    ///
    /// let rules = ConfigRuleSet::builder()
    ///     .main_file(ConfigFileRule::toml("config").required(true))
    ///     .main_file(ConfigFileRule::extensions("config", &["yaml"]))
    ///     .fragments(FragmentRule::new("conf.d", "*.conf"))
    ///     .build();
    ///
    /// let discovery = finder.discover_with_rules(&rules);
    ///
    /// // Process discovered files
    /// for result in &discovery.main_files {
    ///     println!("Rule: {:?}", result.rule.pattern);
    ///     for found in &result.matches {
    ///         println!("  Found: {:?}", found.path);
    ///     }
    /// }
    /// ```
    #[must_use]
    pub fn discover_with_rules(&self, rules: &ConfigRuleSet) -> RuleBasedDiscovery {
        let mut main_files = Vec::new();
        let mut fragments = Vec::new();

        // Process each main file rule
        for rule in &rules.main_files {
            let matches = self.find_by_rule(rule);
            main_files.push(RuleMatchResult {
                rule: rule.clone(),
                matches,
            });
        }

        // Process fragments if configured
        if let Some(fragment_rule) = &rules.fragments {
            fragments = self.find_fragments_by_rule(fragment_rule);
        }

        RuleBasedDiscovery {
            rules: rules.clone(),
            main_files,
            fragments,
        }
    }

    /// Find all files matching a single rule.
    fn find_by_rule(&self, rule: &ConfigFileRule) -> Vec<ConfigCandidate> {
        let mut candidates = Vec::new();

        // Iterate through tiers based on the rule's tier search mode
        for tier in rule.tiers.tiers() {
            let dirs = match tier {
                ConfigTier::User => self.dir_finder.user_dirs(&StdEnv),
                ConfigTier::Local => self.dir_finder.local_dirs(&StdEnv),
                ConfigTier::System => self.dir_finder.system_dirs(&StdEnv),
            };

            let source_type = if tier == ConfigTier::User {
                SourceType::MainFile
            } else {
                SourceType::Legacy
            };

            for dir in dirs {
                self.find_files_in_dirs_with_rule(
                    &[dir],
                    tier,
                    &rule.pattern,
                    &mut candidates,
                    source_type,
                );
            }
        }

        // Sort by tier priority (highest first)
        candidates.sort_by(|a, b| b.tier.cmp(&a.tier));
        candidates
    }

    /// Find files matching pattern in directories with a specific source type.
    fn find_files_in_dirs_with_rule(
        &self,
        dirs: &[PathBuf],
        tier: ConfigTier,
        pattern: &FilePattern,
        candidates: &mut Vec<ConfigCandidate>,
        source_type: SourceType,
    ) {
        for dir in dirs {
            if !self.fs.is_dir(dir) {
                // Check if the directory path itself matches as a file
                let status = self.path_status(dir);
                if pattern.matches(dir) {
                    candidates.push(ConfigCandidate::new(dir.clone(), status, tier, source_type));
                }
                continue;
            }

            // Directory exists - search for matching files
            for entry in self.fs.read_dir(dir) {
                if pattern.matches(&entry) {
                    let status = self.path_status(&entry);
                    candidates.push(ConfigCandidate::new(
                        entry.clone(),
                        status,
                        tier,
                        source_type,
                    ));
                }
            }

            // Also check concrete filenames directly
            if let Some(filenames) = pattern.concrete_filenames() {
                for filename in filenames {
                    let file_path = dir.join(&filename);
                    if pattern.matches(&file_path) {
                        let status = self.path_status(&file_path);
                        candidates.push(ConfigCandidate::new(file_path, status, tier, source_type));
                    }
                }
            }
        }
    }

    /// Find fragment files by a fragment rule.
    fn find_fragments_by_rule(&self, rule: &FragmentRule) -> Vec<RuleMatchResult> {
        let mut results = Vec::new();

        // Create a temporary rule for file matching
        let file_rule = ConfigFileRule {
            pattern: rule.pattern.clone(),
            tiers: rule.tiers,
            required: false,
        };

        // Iterate through tiers based on the fragment rule's tier search mode
        for tier in rule.tiers.tiers() {
            let dirs = match tier {
                ConfigTier::User => self.dir_finder.user_dirs(&StdEnv),
                ConfigTier::Local => self.dir_finder.local_dirs(&StdEnv),
                ConfigTier::System => self.dir_finder.system_dirs(&StdEnv),
            };

            for base_dir in dirs {
                let conf_d = base_dir.join(&rule.dir_name);
                if self.fs.is_dir(&conf_d) {
                    let mut matches = Vec::new();

                    // Find matching files in this directory
                    for entry in self.fs.read_dir(&conf_d) {
                        if rule.pattern.matches(&entry) && self.fs.is_file(&entry) {
                            let status = self.path_status(&entry);
                            matches.push(ConfigCandidate::new(
                                entry.clone(),
                                status,
                                tier,
                                SourceType::FragmentsDir,
                            ));
                        }
                    }

                    if !matches.is_empty() {
                        results.push(RuleMatchResult {
                            rule: file_rule.clone(),
                            matches,
                        });
                    }
                }
            }
        }

        results
    }
}

impl std::fmt::Debug for PathFinder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PathFinder")
            .field("user_dirs", &self.user_dirs())
            .field("local_dirs", &self.local_dirs())
            .field("system_dirs", &self.system_dirs())
            .finish()
    }
}