cfgmatic-paths 5.0.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
//! Configuration file rules for multi-file configuration discovery.

use crate::core::{config_tier::ConfigTier, pattern::FilePattern};

/// Rule for finding a single configuration file.
///
/// Defines how to search for a specific configuration file across
/// different tiers (User, Local, System) and what to do when
/// multiple instances are found.
///
/// # Example
///
/// ```
/// use cfgmatic_paths::{ConfigFileRule, TierSearchMode};
///
/// let rule = ConfigFileRule::extensions("config", &["toml", "yaml"])
///     .tiers(TierSearchMode::All)
///     .required(true);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigFileRule {
    /// File pattern to match.
    pub pattern: FilePattern,

    /// Which tiers to search for this file.
    pub tiers: TierSearchMode,

    /// Whether the file is required (error if not found).
    pub required: bool,
}

impl ConfigFileRule {
    /// Create a new rule for a file with a single extension.
    ///
    /// # Example
    ///
    /// ```
    /// use cfgmatic_paths::ConfigFileRule;
    ///
    /// let rule = ConfigFileRule::toml("config");
    /// ```
    #[must_use]
    pub fn toml(base: impl Into<String>) -> Self {
        Self {
            pattern: FilePattern::extensions(base.into(), &["toml"]),
            tiers: TierSearchMode::default(),
            required: false,
        }
    }

    /// Create a new rule for a file with multiple extensions.
    ///
    /// # Example
    ///
    /// ```
    /// use cfgmatic_paths::ConfigFileRule;
    ///
    /// let rule = ConfigFileRule::extensions("config", &["toml", "yaml", "json"]);
    /// ```
    #[must_use]
    pub fn extensions(base: impl Into<String>, extensions: &[&str]) -> Self {
        Self {
            pattern: FilePattern::extensions(base.into(), extensions),
            tiers: TierSearchMode::default(),
            required: false,
        }
    }

    /// Create a new rule for an exact filename match.
    ///
    /// # Example
    ///
    /// ```
    /// use cfgmatic_paths::ConfigFileRule;
    ///
    /// let rule = ConfigFileRule::exact("main.conf");
    /// ```
    #[must_use]
    pub fn exact(name: impl Into<String>) -> Self {
        Self {
            pattern: FilePattern::exact(name.into()),
            tiers: TierSearchMode::default(),
            required: false,
        }
    }

    /// Create a new rule for glob pattern matching.
    ///
    /// # Example
    ///
    /// ```
    /// use cfgmatic_paths::ConfigFileRule;
    ///
    /// let rule = ConfigFileRule::glob("*.conf");
    /// ```
    #[must_use]
    pub fn glob(pattern: impl Into<String>) -> Self {
        Self {
            pattern: FilePattern::glob(pattern.into()),
            tiers: TierSearchMode::default(),
            required: false,
        }
    }

    /// Set which tiers to search.
    ///
    /// # Example
    ///
    /// ```
    /// use cfgmatic_paths::{ConfigFileRule, TierSearchMode, ConfigTier};
    ///
    /// let rule = ConfigFileRule::toml("config")
    ///     .tiers(TierSearchMode::FromTier(ConfigTier::System));
    /// ```
    #[must_use]
    pub const fn tiers(mut self, tiers: TierSearchMode) -> Self {
        self.tiers = tiers;
        self
    }

    /// Mark the file as required.
    ///
    /// # Example
    ///
    /// ```
    /// use cfgmatic_paths::ConfigFileRule;
    ///
    /// let rule = ConfigFileRule::toml("config")
    ///     .required(true);
    /// ```
    #[must_use]
    pub const fn required(mut self, required: bool) -> Self {
        self.required = required;
        self
    }
}

/// How to search tiers for configuration files.
///
/// Defines which configuration tiers (User, Local, System) should be searched
/// and in what order.
///
/// # Example
///
/// ```
/// use cfgmatic_paths::{TierSearchMode, ConfigTier};
///
/// // Search all tiers (default)
/// let mode = TierSearchMode::All;
///
/// // Only user tier
/// let mode = TierSearchMode::UserOnly;
///
/// // User and Local tiers
/// let mode = TierSearchMode::UserAndLocal;
///
/// // From a specific tier upward
/// let mode = TierSearchMode::FromTier(ConfigTier::System);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TierSearchMode {
    /// Only User tier.
    UserOnly,

    /// User and Local tiers.
    UserAndLocal,

    /// All tiers: User, Local, System (default).
    #[default]
    All,

    /// From a specific tier upward (e.g., FromTier(System) means System, Local, User).
    FromTier(ConfigTier),

    /// From a specific tier downward (e.g., FromTier(User) means User only).
    FromTierDownward(ConfigTier),

    /// Custom selection of tiers.
    Custom {
        /// Include User tier.
        user: bool,
        /// Include Local tier.
        local: bool,
        /// Include System tier.
        system: bool,
    },
}

impl TierSearchMode {
    /// Returns true if the User tier should be searched.
    #[must_use]
    pub const fn includes_user(&self) -> bool {
        matches!(
            self,
            Self::UserOnly | Self::UserAndLocal | Self::All | Self::FromTierDownward(_)
        ) || matches!(self, Self::Custom { user: true, .. })
            || matches!(self, Self::FromTier(ConfigTier::User))
    }

    /// Returns true if the Local tier should be searched.
    #[must_use]
    pub const fn includes_local(&self) -> bool {
        matches!(self, Self::All | Self::FromTier(ConfigTier::Local))
            || matches!(self, Self::Custom { local: true, .. })
            || matches!(self, Self::FromTier(ConfigTier::System | ConfigTier::User))
    }

    /// Returns true if the System tier should be searched.
    #[must_use]
    pub const fn includes_system(&self) -> bool {
        matches!(self, Self::All)
            || matches!(self, Self::Custom { system: true, .. })
            || matches!(self, Self::FromTier(ConfigTier::System))
    }

    /// Returns an iterator of tiers to search in priority order (User → Local → System).
    #[must_use]
    pub const fn tiers(&self) -> TierIterator {
        TierIterator::new(*self)
    }

    /// Returns the default tier for this mode.
    #[must_use]
    pub const fn default_tier(&self) -> ConfigTier {
        match self {
            Self::FromTier(tier) => *tier,
            _ => ConfigTier::User,
        }
    }
}

/// Iterator over configuration tiers in priority order.
///
/// Yields tiers in the order they should be searched and merged
/// (highest priority first).
#[derive(Debug, Clone)]
pub struct TierIterator {
    /// Search mode determining which tiers to iterate.
    mode: TierSearchMode,
    /// Current iteration state.
    state: u8,
}

impl TierIterator {
    /// Create a new iterator for the given mode.
    #[must_use]
    pub const fn new(mode: TierSearchMode) -> Self {
        Self { mode, state: 0 }
    }
}

impl Iterator for TierIterator {
    type Item = ConfigTier;

    fn next(&mut self) -> Option<Self::Item> {
        let mode = self.mode;
        let state = self.state;
        self.state = state.wrapping_add(1);

        match mode {
            // AllTiers: User → Local → System
            TierSearchMode::All => match state {
                0 => Some(ConfigTier::User),
                1 => Some(ConfigTier::Local),
                2 => Some(ConfigTier::System),
                _ => None,
            },

            // UserOnly
            TierSearchMode::UserOnly => match state {
                0 => Some(ConfigTier::User),
                _ => None,
            },

            // UserAndLocal: User → Local
            TierSearchMode::UserAndLocal => match state {
                0 => Some(ConfigTier::User),
                1 => Some(ConfigTier::Local),
                _ => None,
            },

            // FromTier: tier → tiers above (in priority order: User → Local → System)
            TierSearchMode::FromTier(start) => match state {
                0 => Some(start),
                1 if start < ConfigTier::User => Some(ConfigTier::User),
                1 if start < ConfigTier::Local => Some(ConfigTier::Local),
                _ => None,
            },

            // FromTierDownward: tier → tiers below (in reverse priority: System → Local → User)
            TierSearchMode::FromTierDownward(start) => match state {
                0 => Some(start),
                1 if start > ConfigTier::System => Some(ConfigTier::System),
                1 if start > ConfigTier::Local => Some(ConfigTier::Local),
                _ => None,
            },

            // Custom
            TierSearchMode::Custom {
                user,
                local,
                system,
            } => match state {
                0 if user => Some(ConfigTier::User),
                1 if local => Some(ConfigTier::Local),
                2 if system => Some(ConfigTier::System),
                _ => None,
            },
        }
    }
}

/// Rule for configuration fragment directories (conf.d style).
///
/// Fragment directories contain multiple small configuration files
/// that are merged together.
///
/// # Example
///
/// ```
/// use cfgmatic_paths::{FragmentRule, TierSearchMode};
///
/// let rule = FragmentRule::new("conf.d", "*.conf")
///     .tiers(TierSearchMode::All);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FragmentRule {
    /// Name of the fragment directory (e.g., "conf.d").
    pub dir_name: String,

    /// Pattern for files in the fragment directory.
    pub pattern: FilePattern,

    /// Which tiers to search for fragments.
    pub tiers: TierSearchMode,
}

impl FragmentRule {
    /// Create a new fragment rule.
    ///
    /// # Example
    ///
    /// ```
    /// use cfgmatic_paths::FragmentRule;
    ///
    /// let rule = FragmentRule::new("conf.d", "*.conf");
    /// ```
    #[must_use]
    pub fn new(dir_name: impl Into<String>, pattern: impl Into<String>) -> Self {
        Self {
            dir_name: dir_name.into(),
            pattern: FilePattern::glob(pattern),
            tiers: TierSearchMode::default(),
        }
    }

    /// Set which tiers to search.
    #[must_use]
    pub const fn tiers(mut self, tiers: TierSearchMode) -> Self {
        self.tiers = tiers;
        self
    }
}

/// Set of configuration file rules.
///
/// Defines all configuration files for an application, including
/// main files, fragments, and legacy files.
///
/// # Example
///
/// ```
/// use cfgmatic_paths::{ConfigRuleSet, ConfigFileRule, FragmentRule};
///
/// let rules = ConfigRuleSet::builder()
///     .main_file(ConfigFileRule::toml("config").required(true))
///     .main_file(ConfigFileRule::extensions("config", &["yaml"]))
///     .fragments(FragmentRule::new("conf.d", "*.conf"))
///     .build();
/// ```
#[derive(Debug, Clone, Default)]
pub struct ConfigRuleSet {
    /// Main configuration files.
    pub main_files: Vec<ConfigFileRule>,

    /// Fragment directory rule (optional).
    pub fragments: Option<FragmentRule>,
}

impl ConfigRuleSet {
    /// Create a new empty rule set.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a new builder for rule sets.
    #[must_use]
    pub fn builder() -> ConfigRuleSetBuilder {
        ConfigRuleSetBuilder::new()
    }

    /// Add a main file rule.
    pub fn add_main_file(&mut self, rule: ConfigFileRule) {
        self.main_files.push(rule);
    }

    /// Set the fragment rule.
    pub fn set_fragments(&mut self, fragments: FragmentRule) {
        self.fragments = Some(fragments);
    }

    /// Get all main file rules.
    #[must_use]
    pub fn main_files(&self) -> &[ConfigFileRule] {
        &self.main_files
    }

    /// Get the fragment rule if set.
    #[must_use]
    pub const fn fragments(&self) -> Option<&FragmentRule> {
        self.fragments.as_ref()
    }
}

/// Builder for creating configuration rule sets.
#[derive(Debug, Clone, Default)]
pub struct ConfigRuleSetBuilder {
    /// Rules being built.
    rules: ConfigRuleSet,
}

impl ConfigRuleSetBuilder {
    /// Create a new builder.
    #[must_use]
    pub fn new() -> Self {
        Self {
            rules: ConfigRuleSet::new(),
        }
    }

    /// Add a main file rule.
    #[must_use]
    pub fn main_file(mut self, rule: ConfigFileRule) -> Self {
        self.rules.add_main_file(rule);
        self
    }

    /// Set the fragment rule.
    #[must_use]
    pub fn fragments(mut self, fragments: FragmentRule) -> Self {
        self.rules.set_fragments(fragments);
        self
    }

    /// Build the rule set.
    #[must_use]
    pub fn build(self) -> ConfigRuleSet {
        self.rules
    }
}

/// Result of rule-based configuration discovery.
///
/// Contains all discovered configuration files grouped by rule,
/// along with fragment information.
///
/// # Example
///
/// ```
/// use cfgmatic_paths::{PathsBuilder, ConfigRuleSet, ConfigFileRule, FragmentRule};
///
/// let finder = PathsBuilder::new("myapp").build();
///
/// let rules = ConfigRuleSet::builder()
///     .main_file(ConfigFileRule::toml("config"))
///     .fragments(FragmentRule::new("conf.d", "*.conf"))
///     .build();
///
/// let discovery = finder.discover_with_rules(&rules);
///
/// // Get all file paths for loading
/// for path in discovery.all_paths() {
///     println!("Found: {}", path.display());
/// }
///
/// // Check if required files are present
/// if let Some(missing) = discovery.missing_required() {
///     eprintln!("Missing required file: {:?}", missing);
/// }
/// ```
#[derive(Debug, Clone)]
pub struct RuleBasedDiscovery {
    /// The rule set that was used for discovery.
    pub rules: ConfigRuleSet,

    /// Discovered main files grouped by rule.
    pub main_files: Vec<RuleMatchResult>,

    /// Discovered fragment files.
    pub fragments: Vec<RuleMatchResult>,
}

impl RuleBasedDiscovery {
    /// Check if any files were found.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.main_files.iter().all(|r| r.matches.is_empty())
            && self.fragments.iter().all(|r| r.matches.is_empty())
    }

    /// Get the total count of all discovered files.
    #[must_use]
    pub fn file_count(&self) -> usize {
        let main_count: usize = self.main_files.iter().map(|r| r.matches.len()).sum();
        let fragment_count: usize = self.fragments.iter().map(|r| r.matches.len()).sum();
        main_count + fragment_count
    }

    /// Get all file paths from main files, sorted by priority (highest first).
    ///
    /// Returns paths in merge order: lowest priority first, highest priority last.
    /// This allows sequential merging where later files override earlier ones.
    #[must_use]
    pub fn main_paths(&self) -> Vec<std::path::PathBuf> {
        let mut paths = Vec::new();
        for result in &self.main_files {
            for candidate in &result.matches {
                paths.push(candidate.path.clone());
            }
        }
        // Sort by tier priority (lowest first for merge order)
        paths.sort_by_key(|p| {
            self.main_files
                .iter()
                .flat_map(|r| &r.matches)
                .find(|c| &c.path == p)
                .map_or(std::cmp::Reverse(0), |c| {
                    std::cmp::Reverse(u8::from(c.tier))
                })
        });
        paths
    }

    /// Get all file paths from fragments, sorted by priority (highest first).
    ///
    /// Returns paths in merge order: lowest priority first, highest priority last.
    #[must_use]
    pub fn fragment_paths(&self) -> Vec<std::path::PathBuf> {
        let mut paths = Vec::new();
        for result in &self.fragments {
            for candidate in &result.matches {
                paths.push(candidate.path.clone());
            }
        }
        // Sort by tier priority (lowest first for merge order)
        paths.sort_by_key(|p| {
            self.fragments
                .iter()
                .flat_map(|r| &r.matches)
                .find(|c| &c.path == p)
                .map_or(std::cmp::Reverse(0), |c| {
                    std::cmp::Reverse(u8::from(c.tier))
                })
        });
        paths
    }

    /// Get all discovered file paths (both main and fragments).
    ///
    /// Returns paths in merge order: main files first (by tier), then fragments.
    #[must_use]
    pub fn all_paths(&self) -> Vec<std::path::PathBuf> {
        let mut paths = self.main_paths();
        paths.extend(self.fragment_paths());
        paths
    }

    /// Get candidates for main files sorted by merge priority.
    #[must_use]
    pub fn main_candidates(&self) -> Vec<&ConfigCandidate> {
        let mut candidates: Vec<&ConfigCandidate> = self
            .main_files
            .iter()
            .flat_map(|r| r.matches.iter())
            .collect();
        candidates.sort_by_key(|c| std::cmp::Reverse(u8::from(c.tier)));
        candidates
    }

    /// Get candidates for fragments sorted by merge priority.
    #[must_use]
    pub fn fragment_candidates(&self) -> Vec<&ConfigCandidate> {
        let mut candidates: Vec<&ConfigCandidate> = self
            .fragments
            .iter()
            .flat_map(|r| r.matches.iter())
            .collect();
        candidates.sort_by_key(|c| std::cmp::Reverse(u8::from(c.tier)));
        candidates
    }

    /// Check if a required rule has no matching files.
    ///
    /// Returns the first required rule that has no matches.
    #[must_use]
    pub fn missing_required(&self) -> Option<&ConfigFileRule> {
        self.rules.main_files.iter().find(|rule| {
            rule.required && {
                !self
                    .main_files
                    .iter()
                    .any(|r| &r.rule == *rule && !r.matches.is_empty())
            }
        })
    }

    /// Get all existing files (filter out non-existent candidates).
    #[must_use]
    pub fn existing_files(&self) -> Vec<&ConfigCandidate> {
        self.main_candidates()
            .into_iter()
            .chain(self.fragment_candidates())
            .filter(|c| c.status.exists())
            .collect()
    }
}

/// Result of searching for files by a single rule.
///
/// Contains the rule that was used and all matching files found.
#[derive(Debug, Clone)]
pub struct RuleMatchResult {
    /// The rule that was used for matching.
    pub rule: ConfigFileRule,

    /// Files that matched the rule.
    pub matches: Vec<ConfigCandidate>,
}

/// Re-export for convenience at the crate level.
pub use crate::core::discovery::ConfigCandidate;