Skip to main content

langcodec_cli/
path_glob.rs

1use std::collections::HashSet;
2use std::path::{Path, PathBuf};
3
4use globset::{GlobBuilder, GlobSetBuilder};
5use ignore::WalkBuilder;
6use rayon::prelude::*;
7
8fn has_glob_meta(s: &str) -> bool {
9    s.bytes().any(|b| matches!(b, b'*' | b'?' | b'[' | b'{'))
10}
11
12// Extract the directory components before the first component containing glob
13// metadata. A partial component can name an existing directory (for example,
14// `values` in `values*`), but it is not a safe traversal root because matching
15// sibling directories such as `values-es` live beside it.
16fn static_prefix_dir(pattern: &str) -> PathBuf {
17    let mut root = PathBuf::new();
18
19    for component in Path::new(pattern).components() {
20        if has_glob_meta(&component.as_os_str().to_string_lossy()) {
21            break;
22        }
23        root.push(component.as_os_str());
24    }
25
26    if root.as_os_str().is_empty() {
27        PathBuf::from(".")
28    } else {
29        root
30    }
31}
32
33/// Expand possible glob patterns in a list of input strings into concrete file paths.
34/// Uses ignore + globset for fast, parallel, .gitignore-aware traversal.
35pub fn expand_input_globs(inputs: &Vec<String>) -> Result<Vec<String>, String> {
36    // Build one GlobSet for all patterns (literal_separator to avoid '/' matching)
37    let mut builder = GlobSetBuilder::new();
38    for pat in inputs {
39        let glob = GlobBuilder::new(pat)
40            .literal_separator(true)
41            .build()
42            .map_err(|e| format!("Invalid glob pattern '{}': {}", pat, e))?;
43        builder.add(glob);
44    }
45    let set = builder
46        .build()
47        .map_err(|e| format!("Failed to build glob set: {}", e))?;
48
49    // Collect unique roots to minimize directory walks
50    let mut roots: Vec<PathBuf> = Vec::new();
51    for pat in inputs {
52        let root = if has_glob_meta(pat) {
53            static_prefix_dir(pat)
54        } else {
55            Path::new(pat)
56                .parent()
57                .map(|p| p.to_path_buf())
58                .unwrap_or_else(|| PathBuf::from("."))
59        };
60        if !roots.iter().any(|r| r == &root) {
61            roots.push(root);
62        }
63    }
64
65    // Walk roots in parallel and match files against the GlobSet
66    let collected: Vec<String> = roots
67        .par_iter()
68        .map(|root| {
69            let mut out: Vec<String> = Vec::new();
70            let walker = WalkBuilder::new(root)
71                .git_ignore(true)
72                .git_global(true)
73                .git_exclude(true)
74                .hidden(false)
75                .ignore(true)
76                .parents(true)
77                .build();
78
79            for dent in walker {
80                let dent = match dent {
81                    Ok(d) => d,
82                    Err(_e) => continue,
83                };
84                let ftype = match dent.file_type() {
85                    Some(t) => t,
86                    None => continue,
87                };
88                if !ftype.is_file() {
89                    continue;
90                }
91                let s = dent.path().to_string_lossy();
92                if set.is_match(s.as_ref()) {
93                    out.push(s.to_string());
94                }
95            }
96            out
97        })
98        .flatten()
99        .collect();
100
101    // If nothing matched, preserve original inputs to surface errors later
102    if collected.is_empty() {
103        return Ok(inputs.clone());
104    }
105
106    // Deduplicate while preserving order
107    let mut seen: HashSet<String> = HashSet::new();
108    let mut results: Vec<String> = Vec::with_capacity(collected.len());
109    for s in collected {
110        if seen.insert(s.clone()) {
111            results.push(s);
112        }
113    }
114    Ok(results)
115}
116
117#[derive(Debug)]
118pub struct UnfilteredGlobExpansion {
119    pub paths: Vec<String>,
120    pub errors: Vec<String>,
121}
122
123/// Expands one check input without applying ignore files or hidden-file rules.
124///
125/// Unlike [`expand_input_globs`], this preserves traversal failures so callers
126/// performing validation can report incomplete filesystem coverage. Globset is
127/// retained here because the CLI documents brace patterns such as
128/// `*.{strings,xcstrings}`.
129pub fn expand_input_glob_unfiltered(input: &str) -> UnfilteredGlobExpansion {
130    if !has_glob_meta(input) {
131        return UnfilteredGlobExpansion {
132            paths: vec![input.to_string()],
133            errors: Vec::new(),
134        };
135    }
136
137    let matcher = match GlobBuilder::new(input).literal_separator(true).build() {
138        Ok(glob) => glob.compile_matcher(),
139        Err(error) => {
140            return UnfilteredGlobExpansion {
141                paths: Vec::new(),
142                errors: vec![format!("Invalid glob pattern '{}': {}", input, error)],
143            };
144        }
145    };
146
147    let root = static_prefix_dir(input);
148    let walker = WalkBuilder::new(root)
149        .git_ignore(false)
150        .git_global(false)
151        .git_exclude(false)
152        .hidden(false)
153        .ignore(false)
154        .parents(false)
155        .build();
156    let mut paths = Vec::new();
157    let mut errors = Vec::new();
158
159    for entry in walker {
160        match entry {
161            Ok(entry) if entry.file_type().is_some_and(|kind| kind.is_file()) => {
162                let path = entry.path().to_string_lossy();
163                if matcher.is_match(path.as_ref()) {
164                    paths.push(path.into_owned());
165                }
166            }
167            Ok(_) => {}
168            Err(error) => errors.push(format!(
169                "Failed to traverse glob pattern '{}': {}",
170                input, error
171            )),
172        }
173    }
174
175    paths.sort();
176    paths.dedup();
177    errors.sort();
178    errors.dedup();
179    if paths.is_empty() && errors.is_empty() {
180        paths.push(input.to_string());
181    }
182
183    UnfilteredGlobExpansion { paths, errors }
184}
185
186#[cfg(test)]
187mod tests {
188    use std::fs;
189
190    use tempfile::TempDir;
191
192    use super::{expand_input_glob_unfiltered, expand_input_globs};
193
194    #[test]
195    fn glob_component_uses_its_parent_as_the_walk_root() {
196        let temp_dir = TempDir::new().unwrap();
197        let values = temp_dir.path().join("res/values/strings.xml");
198        let values_es = temp_dir.path().join("res/values-es/strings.xml");
199        fs::create_dir_all(values.parent().unwrap()).unwrap();
200        fs::create_dir_all(values_es.parent().unwrap()).unwrap();
201        fs::write(&values, "<resources />").unwrap();
202        fs::write(&values_es, "<resources />").unwrap();
203
204        let pattern = format!("{}/res/values*/strings.xml", temp_dir.path().display());
205        let mut expanded = expand_input_globs(&vec![pattern]).unwrap();
206        expanded.sort();
207
208        let mut expected = vec![
209            values.to_string_lossy().into_owned(),
210            values_es.to_string_lossy().into_owned(),
211        ];
212        expected.sort();
213        assert_eq!(expanded, expected);
214    }
215
216    #[test]
217    fn literal_input_behavior_is_unchanged() {
218        let temp_dir = TempDir::new().unwrap();
219        let input = temp_dir.path().join("res/values/strings.xml");
220        fs::create_dir_all(input.parent().unwrap()).unwrap();
221        fs::write(&input, "<resources />").unwrap();
222        let input = input.to_string_lossy().into_owned();
223
224        assert_eq!(
225            expand_input_globs(&vec![input.clone()]).unwrap(),
226            vec![input]
227        );
228    }
229
230    #[test]
231    fn unfiltered_glob_includes_ignored_and_brace_matches() {
232        let temp_dir = TempDir::new().unwrap();
233        let strings = temp_dir.path().join("ignored.strings");
234        let catalog = temp_dir.path().join("ignored.xcstrings");
235        fs::write(
236            temp_dir.path().join(".gitignore"),
237            "ignored.strings\nignored.xcstrings\n",
238        )
239        .unwrap();
240        fs::write(&strings, "").unwrap();
241        fs::write(&catalog, "").unwrap();
242
243        let pattern = format!(
244            "{}/*.{{strings,xcstrings}}",
245            temp_dir.path().to_string_lossy()
246        );
247        let expansion = expand_input_glob_unfiltered(&pattern);
248
249        assert!(expansion.errors.is_empty());
250        assert_eq!(
251            expansion.paths,
252            vec![
253                strings.to_string_lossy().into_owned(),
254                catalog.to_string_lossy().into_owned(),
255            ]
256        );
257    }
258
259    #[test]
260    fn unfiltered_glob_surfaces_traversal_errors() {
261        let temp_dir = TempDir::new().unwrap();
262        let missing_root = temp_dir.path().join("missing");
263        let pattern = format!("{}/*.xcstrings", missing_root.to_string_lossy());
264
265        let expansion = expand_input_glob_unfiltered(&pattern);
266
267        assert!(expansion.paths.is_empty());
268        assert!(
269            expansion
270                .errors
271                .iter()
272                .any(|error| error.contains("Failed to traverse"))
273        );
274    }
275}