Skip to main content

cargo_zng/res/built_in/
glob.rs

1use crate::util::glob_walker;
2
3use super::*;
4
5const GLOB_HELP: &str = "
6Copy all matches in place
7
8The request file:
9  source/l10n/fluent-files 'glob
10   | # localization dir
11   | l10n
12   | # only Fluent files
13   | **/*.ftl
14   | # except test locales
15   | !:**/pseudo*
16
17Copies all '.ftl' not in a *pseudo* path to:
18  target/l10n/
19
20The first path pattern is required and defines the entries that
21will be copied, an initial pattern with '**' flattens the matches.
22The path is relative to the Cargo workspace root.
23
24The subsequent patterns are optional and filter each file or dir selected by
25the first pattern. The paths are relative to each match, if it is a file 
26the filters apply to the file name only, if it is a dir the filters apply to
27the dir and descendants.
28
29The glob pattern syntax is:
30
31     ? — Matches any single character.
32     * — Matches any (possibly empty) sequence of characters.
33    ** — Matches the current directory and arbitrary subdirectories.
34   [c] — Matches any character inside the brackets.
35  [!c] — Negates the brackets match.
36 {a,b} — Matches any of the inner patterns.
37
38And in filter patterns only:
39
40!:pattern — negates the entire pattern.
41
42Matching is case insensitive in all platforms.
43
44";
45pub(super) fn glob() {
46    help(GLOB_HELP);
47
48    // target derived from the request place
49    let target = path(ZR_TARGET);
50    let target = target.parent().unwrap();
51
52    let request_path = path(ZR_REQUEST);
53    let mut lines = read_lines(&request_path);
54    let (ln, selection) = lines
55        .next()
56        .unwrap_or_else(|| fatal!("expected at least one path pattern"))
57        .unwrap_or_else(|e| fatal!("{e}"));
58
59    // parse first pattern
60    let selection = glob_walker(&selection, true).unwrap_or_else(|e| fatal!("at line {ln}, {e}"));
61    // parse filter patterns
62    let mut filters = vec![];
63    for r in lines {
64        let (ln, filter) = r.unwrap_or_else(|e| fatal!("{e}"));
65        let (filter, matches_if) = if let Some(f) = filter.strip_prefix("!:") {
66            (f, false)
67        } else {
68            (filter.as_str(), true)
69        };
70        let pat = globset::GlobBuilder::new(filter)
71            .case_insensitive(true)
72            .build()
73            .unwrap_or_else(|e| fatal!("at line {ln}, {e}"))
74            .compile_matcher();
75        filters.push((pat, matches_if));
76    }
77    // collect first matches
78    let selection = {
79        let mut s = vec![];
80        for entry in selection {
81            s.push(entry.unwrap_or_else(|e| fatal!("{e}")).into_path());
82        }
83        // sorted for deterministic results in case flattened files override previous
84        s.sort();
85        s
86    };
87
88    let mut any = false;
89
90    'apply: for source in selection {
91        if source.is_dir() {
92            let filters_root = source.parent().map(Path::to_owned).unwrap_or_default();
93            'copy_dir: for entry in walkdir::WalkDir::new(&source).sort_by_file_name() {
94                let source = entry.unwrap_or_else(|e| fatal!("cannot walkdir entry `{}`, {e}", source.display()));
95                let source = source.path();
96                // filters match 'entry/**'
97                let match_source = source.strip_prefix(&filters_root).unwrap();
98                for (filter, matches_if) in &filters {
99                    if filter.is_match(match_source) != *matches_if {
100                        continue 'copy_dir;
101                    }
102                }
103                let target = target.join(match_source);
104
105                any = true;
106                if source.is_dir() {
107                    fs::create_dir_all(&target).unwrap_or_else(|e| fatal!("cannot create dir `{}`, {e}", source.display()));
108                } else {
109                    if let Some(p) = &target.parent() {
110                        fs::create_dir_all(p).unwrap_or_else(|e| fatal!("cannot create dir `{}`, {e}", p.display()));
111                    }
112                    fs::copy(source, &target)
113                        .unwrap_or_else(|e| fatal!("cannot copy `{}` to `{}`, {e}", source.display(), target.display()));
114                }
115                println!("{}", display_path(&target));
116            }
117        } else if source.is_file() {
118            // filters match 'entry'
119            let source_name = source.file_name().unwrap().to_string_lossy();
120            for (filter, matches_if) in &filters {
121                if filter.is_match(&*source_name) != *matches_if {
122                    continue 'apply;
123                }
124            }
125            let target = target.join(source_name.as_ref());
126
127            any = true;
128            fs::copy(&source, &target).unwrap_or_else(|e| fatal!("cannot copy `{}` to `{}`, {e}", source.display(), target.display()));
129            println!("{}", display_path(&target));
130        } else if source.is_symlink() {
131            symlink_warn(&source);
132        }
133    }
134
135    if !any {
136        warn!("no match")
137    }
138}