gix-glob-0.17.1/.cargo_vcs_info.json0000644000000001460000000000100126330ustar { "git": { "sha1": "4000197ecc8cf1a5d79361620e4c114f86476703" }, "path_in_vcs": "gix-glob" }gix-glob-0.17.1/Cargo.toml0000644000000070570000000000100106410ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.65" name = "gix-glob" version = "0.17.1" authors = ["Sebastian Thiel "] build = false include = [ "src/**/*", "LICENSE-*", ] autobins = false autoexamples = false autotests = false autobenches = false description = "A crate of the gitoxide project dealing with pattern matching" readme = false license = "MIT OR Apache-2.0" repository = "https://github.com/GitoxideLabs/gitoxide" [package.metadata.docs.rs] all-features = true features = ["document-features"] [lib] name = "gix_glob" path = "src/lib.rs" doctest = false [dependencies.bitflags] version = "2" [dependencies.bstr] version = "1.3.0" features = ["std"] default-features = false [dependencies.document-features] version = "0.2.0" optional = true [dependencies.gix-features] version = "^0.39.0" [dependencies.gix-path] version = "^0.10.13" [dependencies.serde] version = "1.0.114" features = ["derive"] optional = true default-features = false [dev-dependencies] [features] serde = [ "dep:serde", "bstr/serde", "bitflags/serde", ] [lints.clippy] bool_to_int_with_if = "allow" borrow_as_ptr = "allow" cast_lossless = "allow" cast_possible_truncation = "allow" cast_possible_wrap = "allow" cast_precision_loss = "allow" cast_sign_loss = "allow" checked_conversions = "allow" copy_iterator = "allow" default_trait_access = "allow" doc_markdown = "allow" empty_docs = "allow" enum_glob_use = "allow" explicit_deref_methods = "allow" explicit_into_iter_loop = "allow" explicit_iter_loop = "allow" filter_map_next = "allow" fn_params_excessive_bools = "allow" from_iter_instead_of_collect = "allow" if_not_else = "allow" ignored_unit_patterns = "allow" implicit_clone = "allow" inconsistent_struct_constructor = "allow" inefficient_to_string = "allow" inline_always = "allow" items_after_statements = "allow" iter_not_returning_iterator = "allow" iter_without_into_iter = "allow" manual_assert = "allow" manual_is_variant_and = "allow" manual_let_else = "allow" manual_string_new = "allow" many_single_char_names = "allow" match_bool = "allow" match_same_arms = "allow" match_wild_err_arm = "allow" match_wildcard_for_single_variants = "allow" missing_errors_doc = "allow" missing_panics_doc = "allow" module_name_repetitions = "allow" must_use_candidate = "allow" mut_mut = "allow" naive_bytecount = "allow" needless_for_each = "allow" needless_pass_by_value = "allow" needless_raw_string_hashes = "allow" no_effect_underscore_binding = "allow" option_option = "allow" range_plus_one = "allow" redundant_else = "allow" return_self_not_must_use = "allow" should_panic_without_expect = "allow" similar_names = "allow" single_match_else = "allow" stable_sort_primitive = "allow" struct_excessive_bools = "allow" struct_field_names = "allow" too_long_first_doc_paragraph = "allow" too_many_lines = "allow" transmute_ptr_to_ptr = "allow" trivially_copy_pass_by_ref = "allow" unnecessary_join = "allow" unnecessary_wraps = "allow" unreadable_literal = "allow" unused_self = "allow" used_underscore_binding = "allow" wildcard_imports = "allow" [lints.clippy.pedantic] level = "warn" priority = -1 [lints.rust] gix-glob-0.17.1/Cargo.toml.orig000064400000000000000000000020501046102023000143060ustar 00000000000000lints.workspace = true [package] name = "gix-glob" version = "0.17.1" repository = "https://github.com/GitoxideLabs/gitoxide" license = "MIT OR Apache-2.0" description = "A crate of the gitoxide project dealing with pattern matching" authors = ["Sebastian Thiel "] edition = "2021" rust-version = "1.65" include = ["src/**/*", "LICENSE-*"] [lib] doctest = false [features] ## Data structures implement `serde::Serialize` and `serde::Deserialize`. serde = ["dep:serde", "bstr/serde", "bitflags/serde"] [dependencies] gix-path = { version = "^0.10.13", path = "../gix-path" } gix-features = { version = "^0.39.0", path = "../gix-features" } bstr = { version = "1.3.0", default-features = false, features = ["std"] } bitflags = "2" serde = { version = "1.0.114", optional = true, default-features = false, features = ["derive"] } document-features = { version = "0.2.0", optional = true } [dev-dependencies] gix-testtools = { path = "../tests/tools" } [package.metadata.docs.rs] all-features = true features = ["document-features"] gix-glob-0.17.1/LICENSE-APACHE000064400000000000000000000247461046102023000133630ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. gix-glob-0.17.1/LICENSE-MIT000064400000000000000000000017771046102023000130720ustar 00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. gix-glob-0.17.1/src/lib.rs000064400000000000000000000024311046102023000133250ustar 00000000000000//! Provide glob [`Patterns`][Pattern] for matching against paths or anything else. //! ## Feature Flags #![cfg_attr( all(doc, feature = "document-features"), doc = ::document_features::document_features!() )] #![cfg_attr(all(doc, feature = "document-features"), feature(doc_cfg, doc_auto_cfg))] #![deny(missing_docs, rust_2018_idioms)] #![forbid(unsafe_code)] use bstr::BString; /// A glob pattern optimized for matching paths relative to a root directory. /// /// For normal globbing, use [`wildmatch()`] instead. #[derive(PartialEq, Eq, Debug, Hash, Ord, PartialOrd, Clone)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct Pattern { /// the actual pattern bytes pub text: BString, /// Additional information to help accelerate pattern matching. pub mode: pattern::Mode, /// The position in `text` with the first wildcard character, or `None` if there is no wildcard at all. pub first_wildcard_pos: Option, } /// pub mod pattern; pub mod search; /// pub mod wildmatch; pub use wildmatch::function::wildmatch; mod parse; /// Create a [`Pattern`] by parsing `text` or return `None` if `text` is empty. /// /// Note that pub fn parse(text: impl AsRef<[u8]>) -> Option { Pattern::from_bytes(text.as_ref()) } gix-glob-0.17.1/src/parse.rs000064400000000000000000000030561046102023000136750ustar 00000000000000use bstr::ByteSlice; use crate::{pattern, pattern::Mode}; #[inline] /// A sloppy parser that performs only the most basic checks, providing additional information /// using `pattern::Mode` flags. /// /// If `may_alter` is `false`, we won't parse leading `!` or its escaped form. /// /// Returns `(pattern, mode, no_wildcard_len)` pub fn pattern(mut pat: &[u8], may_alter: bool) -> Option<(&[u8], pattern::Mode, Option)> { let mut mode = Mode::empty(); if pat.is_empty() { return None; }; if may_alter { if pat.first() == Some(&b'!') { mode |= Mode::NEGATIVE; pat = &pat[1..]; } else if pat.first() == Some(&b'\\') { let second = pat.get(1); if second == Some(&b'!') || second == Some(&b'#') { pat = &pat[1..]; } } } if pat.iter().all(u8::is_ascii_whitespace) { return None; } if pat.first() == Some(&b'/') { mode |= Mode::ABSOLUTE; pat = &pat[1..]; } if pat.last() == Some(&b'/') { mode |= Mode::MUST_BE_DIR; pat = &pat[..pat.len() - 1]; } if !pat.contains(&b'/') { mode |= Mode::NO_SUB_DIR; } if pat.first() == Some(&b'*') && first_wildcard_pos(&pat[1..]).is_none() { mode |= Mode::ENDS_WITH; } let pos_of_first_wildcard = first_wildcard_pos(pat); Some((pat, mode, pos_of_first_wildcard)) } fn first_wildcard_pos(pat: &[u8]) -> Option { pat.find_byteset(GLOB_CHARACTERS) } pub(crate) const GLOB_CHARACTERS: &[u8] = br"*?[\"; gix-glob-0.17.1/src/pattern.rs000064400000000000000000000153241046102023000142410ustar 00000000000000use std::fmt; use bitflags::bitflags; use bstr::{BStr, ByteSlice}; use crate::{pattern, wildmatch, Pattern}; bitflags! { /// Information about a [`Pattern`]. /// /// Its main purpose is to accelerate pattern matching, or to negate the match result or to /// keep special rules only applicable when matching paths. /// /// The mode is typically created when parsing the pattern by inspecting it and isn't typically handled by the user. #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone, Ord, PartialOrd)] pub struct Mode: u32 { /// The pattern does not contain a sub-directory and - it doesn't contain slashes after removing the trailing one. const NO_SUB_DIR = 1 << 0; /// A pattern that is '*literal', meaning that it ends with what's given here const ENDS_WITH = 1 << 1; /// The pattern must match a directory, and not a file. const MUST_BE_DIR = 1 << 2; /// The pattern matches, but should be negated. Note that this mode has to be checked and applied by the caller. const NEGATIVE = 1 << 3; /// The pattern starts with a slash and thus matches only from the beginning. const ABSOLUTE = 1 << 4; } } /// Describes whether to match a path case sensitively or not. /// /// Used in [`Pattern::matches_repo_relative_path()`]. #[derive(Default, Debug, PartialOrd, PartialEq, Copy, Clone, Hash, Ord, Eq)] pub enum Case { /// The case affects the match #[default] Sensitive, /// Ignore the case of ascii characters. Fold, } /// Instantiation impl Pattern { /// Parse the given `text` as pattern, or return `None` if `text` was empty. pub fn from_bytes(text: &[u8]) -> Option { crate::parse::pattern(text, true).map(|(text, mode, first_wildcard_pos)| Pattern { text: text.into(), mode, first_wildcard_pos, }) } /// Parse the given `text` as pattern without supporting leading `!` or `\\!` , or return `None` if `text` was empty. /// /// This assures that `text` remains entirely unaltered, but removes built-in support for negation as well. pub fn from_bytes_without_negation(text: &[u8]) -> Option { crate::parse::pattern(text, false).map(|(text, mode, first_wildcard_pos)| Pattern { text: text.into(), mode, first_wildcard_pos, }) } } /// Access impl Pattern { /// Return true if a match is negated. pub fn is_negative(&self) -> bool { self.mode.contains(Mode::NEGATIVE) } /// Match the given `path` which takes slashes (and only slashes) literally, and is relative to the repository root. /// Note that `path` is assumed to be relative to the repository. /// /// We may take various shortcuts which is when `basename_start_pos` and `is_dir` come into play. /// `basename_start_pos` is the index at which the `path`'s basename starts. /// /// `case` folding can be configured as well. /// `mode` is used to control how [`crate::wildmatch()`] should operate. pub fn matches_repo_relative_path( &self, path: &BStr, basename_start_pos: Option, is_dir: Option, case: Case, mode: wildmatch::Mode, ) -> bool { let is_dir = is_dir.unwrap_or(false); if !is_dir && self.mode.contains(pattern::Mode::MUST_BE_DIR) { return false; } let flags = mode | match case { Case::Fold => wildmatch::Mode::IGNORE_CASE, Case::Sensitive => wildmatch::Mode::empty(), }; #[cfg(debug_assertions)] { if basename_start_pos.is_some() { debug_assert_eq!( basename_start_pos, path.rfind_byte(b'/').map(|p| p + 1), "BUG: invalid cached basename_start_pos provided" ); } } debug_assert!(!path.starts_with(b"/"), "input path must be relative"); if self.mode.contains(pattern::Mode::NO_SUB_DIR) && !self.mode.contains(pattern::Mode::ABSOLUTE) { let basename = &path[basename_start_pos.unwrap_or_default()..]; self.matches(basename, flags) } else { self.matches(path, flags) } } /// See if `value` matches this pattern in the given `mode`. /// /// `mode` can identify `value` as path which won't match the slash character, and can match /// strings with cases ignored as well. Note that the case folding performed here is ASCII only. /// /// Note that this method uses some shortcuts to accelerate simple patterns, but falls back to /// [wildmatch()][crate::wildmatch()] if these fail. pub fn matches(&self, value: &BStr, mode: wildmatch::Mode) -> bool { match self.first_wildcard_pos { // "*literal" case, overrides starts-with Some(pos) if self.mode.contains(pattern::Mode::ENDS_WITH) && (!mode.contains(wildmatch::Mode::NO_MATCH_SLASH_LITERAL) || !value.contains(&b'/')) => { let text = &self.text[pos + 1..]; if mode.contains(wildmatch::Mode::IGNORE_CASE) { value .len() .checked_sub(text.len()) .map_or(false, |start| text.eq_ignore_ascii_case(&value[start..])) } else { value.ends_with(text.as_ref()) } } Some(pos) => { if mode.contains(wildmatch::Mode::IGNORE_CASE) { if !value .get(..pos) .map_or(false, |value| value.eq_ignore_ascii_case(&self.text[..pos])) { return false; } } else if !value.starts_with(&self.text[..pos]) { return false; } crate::wildmatch(self.text.as_bstr(), value, mode) } None => { if mode.contains(wildmatch::Mode::IGNORE_CASE) { self.text.eq_ignore_ascii_case(value) } else { self.text == value } } } } } impl fmt::Display for Pattern { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.mode.contains(Mode::NEGATIVE) { "!".fmt(f)?; } if self.mode.contains(Mode::ABSOLUTE) { "/".fmt(f)?; } self.text.fmt(f)?; if self.mode.contains(Mode::MUST_BE_DIR) { "/".fmt(f)?; } Ok(()) } } gix-glob-0.17.1/src/search/mod.rs000064400000000000000000000026611046102023000146100ustar 00000000000000//! Utilities for searching matches of paths to patterns. //! //! Please note that these are specific to how both excludes and attributes are searched, and this is //! merely a way to share code among them. use std::path::{Path, PathBuf}; /// pub mod pattern; /// A trait to convert bytes into patterns and their associated value. /// /// This is used for `gitattributes` which have a value, and `gitignore` which don't. pub trait Pattern: Clone + PartialEq + Eq + std::fmt::Debug + std::hash::Hash + Ord + PartialOrd + Default { /// The value associated with a pattern. type Value: PartialEq + Eq + std::fmt::Debug + std::hash::Hash + Ord + PartialOrd + Clone; /// Parse all patterns in `bytes` line by line, ignoring lines with errors, and collect them. fn bytes_to_patterns(bytes: &[u8], source: &Path) -> Vec>; } /// Add the given file at `source` if it exists, otherwise do nothing. /// If a `root` is provided, it's not considered a global file anymore. /// Returns `true` if the file was added, or `false` if it didn't exist. pub fn add_patterns_file( patterns: &mut Vec>, source: PathBuf, follow_symlinks: bool, root: Option<&Path>, buf: &mut Vec, ) -> std::io::Result { let previous_len = patterns.len(); patterns.extend(pattern::List::::from_file(source, root, follow_symlinks, buf)?); Ok(patterns.len() != previous_len) } gix-glob-0.17.1/src/search/pattern.rs000064400000000000000000000141441046102023000155050ustar 00000000000000use std::{ io::Read, path::{Path, PathBuf}, }; use bstr::{BStr, BString, ByteSlice, ByteVec}; use crate::{pattern::Case, search::Pattern}; /// A list of patterns which optionally know where they were loaded from and what their base is. /// /// Knowing their base which is relative to a source directory, it will ignore all path to match against /// that don't also start with said base. #[derive(PartialEq, Eq, Debug, Hash, Ord, PartialOrd, Clone, Default)] pub struct List { /// Patterns and their associated data in the order they were loaded in or specified, /// the line number in its source file or its sequence number (_`(pattern, value, line_number)`_). /// /// During matching, this order is reversed. pub patterns: Vec>, /// The path from which the patterns were read, or `None` if the patterns /// don't originate in a file on disk. pub source: Option, /// The parent directory of source, or `None` if the patterns are _global_ to match against the repository root. /// It's processed to contain slashes only and to end with a trailing slash, and is relative to the repository root. pub base: Option, } /// An association of a pattern with its value, along with a sequence number providing a sort order in relation to its peers. #[derive(PartialEq, Eq, Debug, Hash, Ord, PartialOrd, Clone)] pub struct Mapping { /// The pattern itself, like `/target/*` pub pattern: crate::Pattern, /// The value associated with the pattern. pub value: T, /// Typically the line number in the file the pattern was parsed from. pub sequence_number: usize, } fn read_in_full_ignore_missing(path: &Path, follow_symlinks: bool, buf: &mut Vec) -> std::io::Result { buf.clear(); let file = if follow_symlinks { std::fs::File::open(path) } else { gix_features::fs::open_options_no_follow().read(true).open(path) }; Ok(match file { Ok(mut file) => { if let Err(err) = file.read_to_end(buf) { if io_err_is_dir(&err) { false } else { return Err(err); } } else { true } } Err(err) if err.kind() == std::io::ErrorKind::NotFound || io_err_is_dir(&err) => false, Err(err) => return Err(err), }) } fn io_err_is_dir(err: &std::io::Error) -> bool { // TODO: use the enum variant NotADirectory for this once stabilized let raw = err.raw_os_error(); raw == Some(if cfg!(windows) { 5 } else { 21 }) /* Not a directory */ /* Also that, but under different circumstances */ || raw == Some(20) } /// Instantiation impl List where T: Pattern, { /// `source_file` is the location of the `bytes` which represents a list of patterns, one pattern per line. /// If `root` is `Some(…)` it's used to see `source_file` as relative to itself, if `source_file` is absolute. /// If source is relative and should be treated as base, set `root` to `Some("")`. pub fn from_bytes(bytes: &[u8], source_file: PathBuf, root: Option<&Path>) -> Self { let patterns = T::bytes_to_patterns(bytes, source_file.as_path()); let base = root .and_then(|root| source_file.parent().expect("file").strip_prefix(root).ok()) .and_then(|base| { (!base.as_os_str().is_empty()).then(|| { let mut base: BString = gix_path::to_unix_separators_on_windows(gix_path::into_bstr(base)).into_owned(); base.push_byte(b'/'); base }) }); List { patterns, source: Some(source_file), base, } } /// Create a pattern list from the `source` file, which may be located underneath `root`, while optionally /// following symlinks with `follow_symlinks`, providing `buf` to temporarily store the data contained in the file. pub fn from_file( source: impl Into, root: Option<&Path>, follow_symlinks: bool, buf: &mut Vec, ) -> std::io::Result> { let source = source.into(); Ok(read_in_full_ignore_missing(&source, follow_symlinks, buf)?.then(|| Self::from_bytes(buf, source, root))) } } /// Utilities impl List where T: Pattern, { /// If this list is anchored to a base path, return `relative_path` as being relative to our base and return /// an updated `basename_pos` as well if it was set. /// `case` is respected for the comparison. /// /// This is useful to turn repository-relative paths into paths relative to a particular search base. pub fn strip_base_handle_recompute_basename_pos<'a>( &self, relative_path: &'a BStr, basename_pos: Option, case: Case, ) -> Option<(&'a BStr, Option)> { match self.base.as_deref() { Some(base) => strip_base_handle_recompute_basename_pos(base.as_bstr(), relative_path, basename_pos, case)?, None => (relative_path, basename_pos), } .into() } } /// Return`relative_path` as being relative to `base` along with an updated `basename_pos` if it was set. /// `case` is respected for the comparison. /// /// This is useful to turn repository-relative paths into paths relative to a particular search base. pub fn strip_base_handle_recompute_basename_pos<'a>( base: &BStr, relative_path: &'a BStr, basename_pos: Option, case: Case, ) -> Option<(&'a BStr, Option)> { Some(( match case { Case::Sensitive => relative_path.strip_prefix(base.as_bytes())?.as_bstr(), Case::Fold => { let rela_dir = relative_path.get(..base.len())?; if !rela_dir.eq_ignore_ascii_case(base) { return None; } &relative_path[base.len()..] } }, basename_pos.and_then(|pos| { let pos = pos - base.len(); (pos != 0).then_some(pos) }), )) } gix-glob-0.17.1/src/wildmatch.rs000064400000000000000000000417211046102023000145400ustar 00000000000000use bitflags::bitflags; bitflags! { /// The match mode employed in [`Pattern::matches()`][crate::Pattern::matches()]. #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Debug, Default, Copy, Clone, Eq, PartialEq)] pub struct Mode: u8 { /// Let globs like `*` and `?` not match the slash `/` literal, which is useful when matching paths. const NO_MATCH_SLASH_LITERAL = 1 << 0; /// Match case insensitively for ascii characters only. const IGNORE_CASE = 1 << 1; } } pub(crate) mod function { use bstr::{BStr, ByteSlice}; use crate::wildmatch::Mode; #[derive(Eq, PartialEq)] enum Result { Match, NoMatch, AbortAll, AbortToStarStar, RecursionLimitReached, } const STAR: u8 = b'*'; const BACKSLASH: u8 = b'\\'; const SLASH: u8 = b'/'; const BRACKET_OPEN: u8 = b'['; const BRACKET_CLOSE: u8 = b']'; const COLON: u8 = b':'; const NEGATE_CLASS: u8 = b'!'; /// Setting this limit to something reasonable means less compute time spent on unnecessarily complex patterns, or malicious ones. const RECURSION_LIMIT: usize = 64; fn match_recursive(pattern: &BStr, text: &BStr, mode: Mode, depth: usize) -> Result { if depth == RECURSION_LIMIT { return RecursionLimitReached; } use self::Result::*; let possibly_lowercase = |c: &u8| { if mode.contains(Mode::IGNORE_CASE) { c.to_ascii_lowercase() } else { *c } }; let mut p = pattern.iter().map(possibly_lowercase).enumerate().peekable(); let mut t = text.iter().map(possibly_lowercase).enumerate(); while let Some((mut p_idx, mut p_ch)) = p.next() { let (mut t_idx, mut t_ch) = match t.next() { Some(c) => c, None if p_ch != STAR => return AbortAll, None => (text.len(), 0), }; if p_ch == BACKSLASH { match p.next() { Some((_p_idx, p_ch)) => { if p_ch != t_ch { return NoMatch; } else { continue; } } None => return NoMatch, }; } match p_ch { b'?' => { if mode.contains(Mode::NO_MATCH_SLASH_LITERAL) && t_ch == SLASH { return NoMatch; } else { continue; } } STAR => { let mut match_slash = !mode.contains(Mode::NO_MATCH_SLASH_LITERAL); match p.next() { Some((next_p_idx, next_p_ch)) => { let next; if next_p_ch == STAR { let leading_slash_idx = p_idx.checked_sub(1); while p.next_if(|(_, c)| *c == STAR).is_some() {} next = p.next(); if !mode.contains(Mode::NO_MATCH_SLASH_LITERAL) { match_slash = true; } else if leading_slash_idx.map_or(true, |idx| pattern[idx] == SLASH) && next.map_or(true, |(_, c)| { c == SLASH || (c == BACKSLASH && p.peek().map(|t| t.1) == Some(SLASH)) }) { if next.map_or(NoMatch, |(idx, _)| { match_recursive( pattern[idx + 1..].as_bstr(), text[t_idx..].as_bstr(), mode, depth + 1, ) }) == Match { return Match; } match_slash = true; } else { match_slash = false; } } else { next = Some((next_p_idx, next_p_ch)); } match next { None => { return if !match_slash && text[t_idx..].contains(&SLASH) { NoMatch } else { Match }; } Some((next_p_idx, next_p_ch)) => { p_idx = next_p_idx; p_ch = next_p_ch; if !match_slash && p_ch == SLASH { match text[t_idx..].find_byte(SLASH) { Some(distance_to_slash) => { for _ in t.by_ref().take(distance_to_slash) {} continue; } None => return NoMatch, } } } } } None => { return if !match_slash && text[t_idx..].contains(&SLASH) { NoMatch } else { Match } } } return loop { if !crate::parse::GLOB_CHARACTERS.contains(&p_ch) { loop { if (!match_slash && t_ch == SLASH) || t_ch == p_ch { break; } match t.next() { Some(t) => { t_idx = t.0; t_ch = t.1; } None => break, }; } if t_ch != p_ch { return NoMatch; } } let res = match_recursive(pattern[p_idx..].as_bstr(), text[t_idx..].as_bstr(), mode, depth + 1); if res != NoMatch { if !match_slash || res != AbortToStarStar { return res; } } else if !match_slash && t_ch == SLASH { return AbortToStarStar; } match t.next() { Some(t) => { t_idx = t.0; t_ch = t.1; } None => break AbortAll, }; }; } BRACKET_OPEN => { match p.next() { Some(t) => { p_idx = t.0; p_ch = t.1; } None => return AbortAll, }; if p_ch == b'^' { p_ch = NEGATE_CLASS; } let negated = p_ch == NEGATE_CLASS; let mut next = if negated { p.next() } else { Some((p_idx, p_ch)) }; let mut prev_p_ch = 0; let mut matched = false; let mut p_idx_ofs = 0; loop { let Some((mut p_idx, mut p_ch)) = next else { return AbortAll; }; p_idx += p_idx_ofs; match p_ch { BACKSLASH => match p.next() { Some((_, p_ch)) => { if p_ch == t_ch { matched = true; } else { prev_p_ch = p_ch; } } None => return AbortAll, }, b'-' if prev_p_ch != 0 && p.peek().is_some() && p.peek().map(|t| t.1) != Some(BRACKET_CLOSE) => { p_ch = p.next().expect("peeked").1; if p_ch == BACKSLASH { p_ch = match p.next() { Some(t) => t.1, None => return AbortAll, }; } if t_ch <= p_ch && t_ch >= prev_p_ch { matched = true; } else if mode.contains(Mode::IGNORE_CASE) && t_ch.is_ascii_lowercase() { let t_ch_upper = t_ch.to_ascii_uppercase(); if (t_ch_upper <= p_ch.to_ascii_uppercase() && t_ch_upper >= prev_p_ch.to_ascii_uppercase()) || (t_ch_upper <= prev_p_ch.to_ascii_uppercase() && t_ch_upper >= p_ch.to_ascii_uppercase()) { matched = true; } } prev_p_ch = 0; } BRACKET_OPEN if matches!(p.peek(), Some((_, COLON))) => { p.next(); while p.peek().map_or(false, |t| t.1 != BRACKET_CLOSE) { p.next(); } let closing_bracket_idx = match p.next() { Some((idx, _)) => idx, None => return AbortAll, }; const BRACKET__COLON__BRACKET: usize = 3; if closing_bracket_idx.saturating_sub(p_idx) < BRACKET__COLON__BRACKET || pattern[closing_bracket_idx - 1] != COLON { if t_ch == BRACKET_OPEN { matched = true; } if p_idx > pattern.len() { return AbortAll; } p = pattern[p_idx..].iter().map(possibly_lowercase).enumerate().peekable(); p_idx_ofs += p_idx; } else { let class = &pattern.as_bytes()[p_idx + 2..closing_bracket_idx - 1]; match class { b"alnum" => { if t_ch.is_ascii_alphanumeric() { matched = true; } } b"alpha" => { if t_ch.is_ascii_alphabetic() { matched = true; } } b"blank" => { if t_ch.is_ascii_whitespace() { matched = true; } } b"cntrl" => { if t_ch.is_ascii_control() { matched = true; } } b"digit" => { if t_ch.is_ascii_digit() { matched = true; } } b"graph" => { if t_ch.is_ascii_graphic() { matched = true; } } b"lower" => { if t_ch.is_ascii_lowercase() { matched = true; } } b"print" => { if (0x20u8..=0x7e).contains(&t_ch) { matched = true; } } b"punct" => { if t_ch.is_ascii_punctuation() { matched = true; } } b"space" => { if t_ch == b' ' { matched = true; } } b"upper" => { if t_ch.is_ascii_uppercase() || mode.contains(Mode::IGNORE_CASE) && t_ch.is_ascii_lowercase() { matched = true; } } b"xdigit" => { if t_ch.is_ascii_hexdigit() { matched = true; } } _ => return AbortAll, }; prev_p_ch = 0; } } _ => { prev_p_ch = p_ch; if p_ch == t_ch { matched = true; } } }; next = p.next(); if let Some((_, BRACKET_CLOSE)) = next { break; } } if matched == negated || mode.contains(Mode::NO_MATCH_SLASH_LITERAL) && t_ch == SLASH { return NoMatch; } continue; } non_glob_ch => { if non_glob_ch != t_ch { return NoMatch; } else { continue; } } } } t.next().map_or(Match, |_| NoMatch) } /// Employ pattern matching to see if `value` matches `pattern`. /// /// `mode` can be used to adjust the way the matching is performed. pub fn wildmatch(pattern: &BStr, value: &BStr, mode: Mode) -> bool { let res = match_recursive(pattern, value, mode, 0); if res == Result::RecursionLimitReached { gix_features::trace::error!("Recursion limit of {} reached for pattern '{pattern}'", RECURSION_LIMIT); } res == Result::Match } }