remove-except 0.5.1

A Rust CLI to keep selected paths or glob matches and remove everything else under a root.
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
use std::path::Path;

#[cfg(any(windows, unix))]
use anyhow::Context;
use anyhow::Result;
use globset::GlobBuilder;
#[cfg(not(any(windows, unix)))]
use globset::{GlobSet, GlobSetBuilder};
#[cfg(any(windows, unix))]
use regex_automata::{meta::Regex, util::syntax};

use crate::error::{invalid, invalid_with_source};
use crate::path::{
    is_absolute_pattern, is_drive_relative_path, normalize_absolute_for_match, path_matches_prefix,
    paths_equal,
};

#[cfg(windows)]
fn windows_glob_regex(glob: &globset::Glob) -> Result<String> {
    Ok(format!("(?i:{})", unicode_glob_regex(glob)?))
}

#[cfg(any(windows, unix))]
fn unicode_glob_regex(glob: &globset::Glob) -> Result<String> {
    let byte_regex = glob
        .regex()
        .strip_prefix("(?-u)")
        .context("Glob regex did not use the expected byte mode prefix")?;
    decode_utf8_regex_literals(byte_regex)
}

#[cfg(any(windows, unix))]
fn decode_utf8_regex_literals(regex: &str) -> Result<String> {
    let bytes = regex.as_bytes();
    let mut decoded = String::with_capacity(regex.len());
    let mut offset = 0;

    while offset < bytes.len() {
        if bytes.get(offset..offset + 2) == Some(br"\\") {
            decoded.push_str(r"\\");
            offset += 2;
            continue;
        }
        if let Some((byte, next_offset)) = regex_hex_escape(bytes, offset)
            && byte >= 0x80
        {
            let mut utf8 = vec![byte];
            offset = next_offset;
            while let Some((next_byte, after_escape)) = regex_hex_escape(bytes, offset) {
                if next_byte < 0x80 {
                    break;
                }
                utf8.push(next_byte);
                offset = after_escape;
            }
            let literal = std::str::from_utf8(&utf8)
                .context("Glob regex contained an invalid UTF-8 literal")?;
            decoded.push_str(literal);
            continue;
        }

        let character = regex[offset..]
            .chars()
            .next()
            .context("Glob regex ended unexpectedly")?;
        decoded.push(character);
        offset += character.len_utf8();
    }

    Ok(decoded)
}

#[cfg(any(windows, unix))]
fn regex_hex_escape(bytes: &[u8], offset: usize) -> Option<(u8, usize)> {
    let escape = bytes.get(offset..offset + 4)?;
    if escape[0] != b'\\' || escape[1] != b'x' {
        return None;
    }
    let high = hex_digit(escape[2])?;
    let low = hex_digit(escape[3])?;
    Some(((high << 4) | low, offset + 4))
}

#[cfg(any(windows, unix))]
fn hex_digit(byte: u8) -> Option<u8> {
    match byte {
        b'0'..=b'9' => Some(byte - b'0'),
        b'a'..=b'f' => Some(byte - b'a' + 10),
        b'A'..=b'F' => Some(byte - b'A' + 10),
        _ => None,
    }
}

/// Compiles keep patterns into a matcher and records literal directory prefixes.
pub(super) fn compile_patterns(root: &Path, patterns: &[String]) -> Result<CompiledPatterns> {
    let root_text = normalize_absolute_for_match(&root.to_string_lossy());
    #[cfg(not(any(windows, unix)))]
    let mut builder = GlobSetBuilder::new();
    let mut prefixes = Vec::with_capacity(patterns.len());
    #[cfg(any(windows, unix))]
    let mut regexes = Vec::with_capacity(patterns.len());

    for raw in patterns {
        if raw.is_empty() {
            return Err(invalid("Pattern must not be empty"));
        }
        if raw.split(['/', '\\']).any(|component| component == "..") {
            return Err(invalid(format!(
                "Parent directory traversal is not allowed in pattern: {raw}"
            )));
        }

        let pattern = normalize_pattern(&root_text, raw)?;
        let glob = GlobBuilder::new(&pattern)
            .literal_separator(true)
            .build()
            .map_err(|error| invalid_with_source(error, format!("Invalid glob pattern: {raw}")))?;
        #[cfg(windows)]
        regexes.push(windows_glob_regex(&glob)?);
        #[cfg(unix)]
        regexes.push(unicode_glob_regex(&glob)?);
        #[cfg(not(any(windows, unix)))]
        builder.add(glob);

        if !has_glob_syntax(&pattern) {
            prefixes.push(pattern.trim_end_matches('/').to_owned());
        }
    }

    #[cfg(any(windows, unix))]
    let matcher = Regex::builder()
        .syntax(syntax::Config::new().dot_matches_new_line(true))
        .build_many(&regexes)
        .context("Failed to compile keep patterns")?;
    #[cfg(not(any(windows, unix)))]
    let matcher = builder.build()?;

    Ok(CompiledPatterns { matcher, prefixes })
}

/// Reports whether a normalized pattern uses glob syntax.
///
/// Only patterns without glob syntax also keep everything beneath a matching
/// directory. Braces are alternation syntax. On non-Windows platforms, a
/// backslash is a glob escape rather than a path separator.
fn has_glob_syntax(pattern: &str) -> bool {
    #[cfg(windows)]
    const GLOB_SYNTAX: [char; 5] = ['*', '?', '[', '{', '}'];
    #[cfg(not(windows))]
    const GLOB_SYNTAX: [char; 6] = ['*', '?', '[', '{', '}', '\\'];
    pattern.contains(GLOB_SYNTAX)
}

pub(super) struct CompiledPatterns {
    #[cfg(any(windows, unix))]
    matcher: Regex,
    #[cfg(not(any(windows, unix)))]
    matcher: GlobSet,
    prefixes: Vec<String>,
}

impl CompiledPatterns {
    pub(super) fn matches(&self, path: &str) -> bool {
        #[cfg(any(windows, unix))]
        if self.matcher.is_match(path.as_bytes()) {
            return true;
        }
        #[cfg(not(any(windows, unix)))]
        if self.matcher.is_match(path) {
            return true;
        }

        self.prefixes
            .iter()
            .any(|prefix| path_matches_prefix(path, prefix))
    }
}

/// Converts an absolute pattern to a root-relative pattern and rejects paths outside the root.
pub(super) fn normalize_pattern(root_text: &str, pattern: &str) -> Result<String> {
    if is_drive_relative_path(pattern) {
        return Err(invalid(format!(
            "Drive-relative patterns are not supported: {pattern}"
        )));
    }

    let normalized = normalize_absolute_for_match(pattern);
    let root_text = normalize_absolute_for_match(root_text);

    if is_absolute_pattern(pattern) {
        let boundary_root = root_text.trim_end_matches('/');
        let Some(relative) = strip_case_insensitive_prefix(&normalized, boundary_root) else {
            return Err(invalid(format!(
                "Absolute pattern is outside the processing root: {pattern}"
            )));
        };
        Ok(normalize_relative_pattern(relative))
    } else {
        Ok(normalize_relative_pattern(&normalized))
    }
}

fn normalize_relative_pattern(pattern: &str) -> String {
    pattern
        .split('/')
        .filter(|component| !component.is_empty() && *component != ".")
        .collect::<Vec<_>>()
        .join("/")
}

fn strip_case_insensitive_prefix<'a>(path: &'a str, prefix: &str) -> Option<&'a str> {
    let mut path_chars = path.char_indices();
    let mut prefix_bytes = 0;
    for _ in prefix.chars() {
        let (index, character) = path_chars.next()?;
        prefix_bytes = index + character.len_utf8();
    }
    if !paths_equal(&path[..prefix_bytes], prefix) {
        return None;
    }
    let suffix = &path[prefix_bytes..];
    if suffix.is_empty() {
        Some(suffix)
    } else {
        suffix.strip_prefix('/')
    }
}

#[cfg(all(test, unix))]
mod unix_tests {
    use globset::GlobBuilder;
    use regex_automata::meta::Regex;

    use super::unicode_glob_regex;

    fn compile_unix_glob(pattern: &str) -> Regex {
        let glob = GlobBuilder::new(pattern)
            .literal_separator(true)
            .build()
            .unwrap();
        Regex::new(&unicode_glob_regex(&glob).unwrap()).unwrap()
    }

    #[test]
    fn question_mark_matches_one_unicode_scalar_without_crossing_separators() {
        let matcher = compile_unix_glob("?.txt");
        assert!(matcher.is_match("é.txt".as_bytes()));
        assert!(matcher.is_match("あ.txt".as_bytes()));
        assert!(!matcher.is_match("e\u{301}.txt".as_bytes()));
        assert!(!matcher.is_match("ee.txt".as_bytes()));
        assert!(!matcher.is_match("nested/é.txt".as_bytes()));
    }

    #[test]
    fn question_marks_match_each_scalar_in_a_combining_sequence() {
        let matcher = compile_unix_glob("??.txt");
        assert!(matcher.is_match("e\u{301}.txt".as_bytes()));
        assert!(!matcher.is_match("é.txt".as_bytes()));
    }

    #[test]
    fn character_classes_match_unicode_scalars_and_ranges() {
        let listed = compile_unix_glob("[éあ].txt");
        assert!(listed.is_match("é.txt".as_bytes()));
        assert!(listed.is_match("あ.txt".as_bytes()));
        assert!(!listed.is_match("è.txt".as_bytes()));
        assert!(!listed.is_match("e\u{301}.txt".as_bytes()));

        let range = compile_unix_glob("[è-ê].txt");
        assert!(range.is_match("è.txt".as_bytes()));
        assert!(range.is_match("é.txt".as_bytes()));
        assert!(range.is_match("ê.txt".as_bytes()));
        assert!(!range.is_match("ë.txt".as_bytes()));

        let negated = compile_unix_glob("[!é].txt");
        assert!(!negated.is_match("é.txt".as_bytes()));
        assert!(negated.is_match("è.txt".as_bytes()));
        assert!(!negated.is_match("e\u{301}.txt".as_bytes()));
    }

    #[test]
    fn unicode_matching_preserves_case_and_glob_separator_rules() {
        let case_sensitive = compile_unix_glob("é.txt");
        assert!(case_sensitive.is_match("é.txt".as_bytes()));
        assert!(!case_sensitive.is_match("É.txt".as_bytes()));

        let single_level = compile_unix_glob("*.txt");
        assert!(single_level.is_match("é.txt".as_bytes()));
        assert!(!single_level.is_match("nested/é.txt".as_bytes()));

        let recursive = compile_unix_glob("**/*.txt");
        assert!(recursive.is_match("é.txt".as_bytes()));
        assert!(recursive.is_match("nested/é.txt".as_bytes()));
    }

    #[test]
    fn escaped_glob_characters_remain_literal() {
        let matcher = compile_unix_glob(r"\*.txt");
        assert!(matcher.is_match("*.txt".as_bytes()));
        assert!(!matcher.is_match("x.txt".as_bytes()));
    }
}

#[cfg(test)]
mod normalization_tests {
    use super::normalize_pattern;

    #[cfg(any(windows, unix))]
    #[test]
    fn recursive_globs_preserve_newline_matching() {
        for (pattern, path) in [
            ("**", "a\nb"),
            ("dir/**", "dir/a\nb"),
            ("**/x", "a\nb/x"),
            ("dir/**/x", "dir/a\nb/x"),
            ("**/*.txt", "a\nb/nested/file.txt"),
        ] {
            let compiled =
                super::compile_patterns(std::path::Path::new("/work"), &[pattern.to_owned()])
                    .unwrap();
            assert!(compiled.matches(path), "{pattern:?} should keep {path:?}");
        }
    }

    #[cfg(any(windows, unix))]
    #[test]
    fn regex_literal_decoding_preserves_escaped_backslashes() {
        for regex in [
            r"^\\x80\.txt$",
            r"^\\xC3\.txt$",
            r"^\\xc3\\xa9\.txt$",
            r"^[\\x80]\.txt$",
        ] {
            assert_eq!(super::decode_utf8_regex_literals(regex).unwrap(), regex);
        }
        assert_eq!(
            super::decode_utf8_regex_literals(r"^\\x80\xc3\xa9\.txt$").unwrap(),
            "^\\\\x80é\\.txt$"
        );
    }

    #[test]
    fn root_patterns_normalize_to_an_empty_relative_pattern() {
        assert_eq!(normalize_pattern("/work", ".").unwrap(), "");
        assert_eq!(normalize_pattern("/work", "./").unwrap(), "");
        assert_eq!(normalize_pattern("/work", "./.").unwrap(), "");
    }

    #[test]
    fn normalizes_dot_components_and_repeated_separators() {
        assert_eq!(
            normalize_pattern("/work", "nested/./keep//file.txt").unwrap(),
            "nested/keep/file.txt"
        );
        assert_eq!(
            normalize_pattern("/work", "/work/nested//./keep.txt").unwrap(),
            "nested/keep.txt"
        );
    }

    #[cfg(windows)]
    #[test]
    fn normalizes_windows_separators_in_absolute_patterns() {
        assert_eq!(
            normalize_pattern("C:/work", r"C:\work\nested\.\keep.txt").unwrap(),
            "nested/keep.txt"
        );
        assert_eq!(
            normalize_pattern("C:/work", r"C:\work\nested\\keep.txt").unwrap(),
            "nested/keep.txt"
        );
    }

    #[test]
    fn preserves_whitespace_in_patterns() {
        assert_eq!(
            normalize_pattern("/work", " keep.txt ").unwrap(),
            " keep.txt "
        );
    }

    #[test]
    fn absolute_sibling_with_shared_text_prefix_is_outside_root() {
        let temp = assert_fs::TempDir::new().unwrap();
        let root = temp.path().join("work");
        let sibling_pattern = temp.path().join("work-sibling").join("*");

        let error = normalize_pattern(&root.to_string_lossy(), &sibling_pattern.to_string_lossy())
            .unwrap_err();

        assert!(error.to_string().contains("outside the processing root"));
    }
}

#[cfg(all(test, windows))]
mod tests {
    use anyhow::Context;
    use globset::GlobBuilder;
    use regex_automata::meta::Regex;

    use super::{decode_utf8_regex_literals, normalize_pattern, windows_glob_regex};

    fn compile_windows_glob(pattern: &str) -> Regex {
        let glob = GlobBuilder::new(pattern)
            .literal_separator(true)
            .build()
            .unwrap();
        Regex::new(&windows_glob_regex(&glob).unwrap()).unwrap()
    }

    #[test]
    fn windows_glob_uses_unicode_simple_case_folding() {
        let umlaut = compile_windows_glob("ä.txt");
        assert!(umlaut.is_match("Ä.txt".as_bytes()));

        let sharp_s = compile_windows_glob("ß.txt");
        assert!(sharp_s.is_match("ẞ.txt".as_bytes()));
        assert!(!sharp_s.is_match("SS.txt".as_bytes()));
    }

    #[test]
    fn windows_question_mark_matches_one_unicode_scalar() {
        let matcher = compile_windows_glob("?.txt");
        assert!(matcher.is_match("é.txt".as_bytes()));
        assert!(!matcher.is_match("ee.txt".as_bytes()));
    }

    #[test]
    fn windows_character_classes_keep_glob_syntax_under_case_folding() {
        let matcher = compile_windows_glob("[Ä].txt");
        assert!(matcher.is_match("ä.txt".as_bytes()));
        assert!(!matcher.is_match("b.txt".as_bytes()));
    }

    #[test]
    fn windows_globs_preserve_recursive_and_single_level_separators() {
        let recursive = compile_windows_glob("root/**/*.txt");
        assert!(recursive.is_match("ROOT/Ä.txt".as_bytes()));
        assert!(recursive.is_match("root/nested/ä.txt".as_bytes()));

        let single_level = compile_windows_glob("root/*.txt");
        assert!(single_level.is_match("ROOT/Ä.txt".as_bytes()));
        assert!(!single_level.is_match("root/nested/ä.txt".as_bytes()));
    }

    #[test]
    fn absolute_pattern_boundary_uses_simple_fold_without_byte_length_assumptions() {
        assert_eq!(
            normalize_pattern("C:/Keep", "c:/Keep/file.txt").unwrap(),
            "file.txt"
        );
        assert!(normalize_pattern("C:/keep", "c:/keeping/file.txt").is_err());
    }

    #[test]
    fn decodes_non_ascii_literals_without_rewriting_regex_syntax() {
        let glob = GlobBuilder::new("[Ä]?.txt")
            .literal_separator(true)
            .build()
            .unwrap();
        let decoded = decode_utf8_regex_literals(
            glob.regex()
                .strip_prefix("(?-u)")
                .context("expected byte regex mode")
                .unwrap(),
        )
        .unwrap();
        assert!(decoded.contains("[Ä]"));
        assert!(decoded.contains("[^/]"));
    }
}