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
//! Configuration discovery helpers for [`PathFinder`](super::PathFinder).
use std::path::{Path, PathBuf};
use crate::core::{
ConfigCandidate, ConfigDiscovery, ConfigTier, DiscoveryOptions, FilePattern, PathStatus,
SourceType,
};
use crate::env::StdEnv;
use super::{PathFinder, scan};
impl PathFinder {
/// 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::{DiscoveryOptions, FilePattern, PathsBuilder};
///
/// 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;
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.build_candidates_for_tier(
&dirs,
tier,
options,
&mut candidates,
&mut fragments,
&mut found_path,
);
}
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::{FilePattern, PathsBuilder};
///
/// 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::{FilePattern, PathsBuilder};
///
/// 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();
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) {
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 {
let status = if self.fs.exists(dir) {
if self.fs.is_dir(dir) {
PathStatus::Directory
} else {
PathStatus::File
}
} else {
PathStatus::NotFound
};
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 found_path.is_none() && status.exists() {
*found_path = Some(dir.clone());
}
if status == PathStatus::Directory {
self.check_dir_for_configs(dir, tier, options, candidates, found_path);
}
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,
));
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>,
) {
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 a pattern in a list of directories.
pub(super) fn find_files_in_dirs(
&self,
dirs: &[PathBuf],
tier: ConfigTier,
pattern: &FilePattern,
candidates: &mut Vec<ConfigCandidate>,
) {
candidates.extend(scan::collect_matching_candidates(
self.fs.as_ref(),
dirs,
tier,
pattern,
SourceType::MainFile,
|path| self.path_status(path),
));
}
}