gix-pathspec-0.6.0/.cargo_vcs_info.json0000644000000001520000000000100134310ustar { "git": { "sha1": "eb6aa8f502314f886fc4ea3d52ab220763968208" }, "path_in_vcs": "gix-pathspec" }gix-pathspec-0.6.0/Cargo.toml0000644000000024700000000000100114340ustar # 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-pathspec" version = "0.6.0" authors = ["Sebastian Thiel "] include = [ "src/**/*", "LICENSE-*", "README.md", ] description = "A crate of the gitoxide project dealing magical pathspecs" readme = "README.md" license = "MIT OR Apache-2.0" repository = "https://github.com/Byron/gitoxide" [lib] doctest = false [dependencies.bitflags] version = "2" [dependencies.bstr] version = "1.3.0" features = ["std"] default-features = false [dependencies.gix-attributes] version = "^0.22.0" [dependencies.gix-config-value] version = "^0.14.4" [dependencies.gix-glob] version = "^0.16.0" [dependencies.gix-path] version = "^0.10.4" [dependencies.thiserror] version = "1.0.26" [dev-dependencies.once_cell] version = "1.12.0" [dev-dependencies.serial_test] version = "2.0.0" gix-pathspec-0.6.0/Cargo.toml.orig000064400000000000000000000015371046102023000151200ustar 00000000000000[package] name = "gix-pathspec" version = "0.6.0" repository = "https://github.com/Byron/gitoxide" license = "MIT OR Apache-2.0" description = "A crate of the gitoxide project dealing magical pathspecs" authors = ["Sebastian Thiel "] edition = "2021" rust-version = "1.65" include = ["src/**/*", "LICENSE-*", "README.md"] [lib] doctest = false [dependencies] gix-glob = { version = "^0.16.0", path = "../gix-glob" } gix-path = { version = "^0.10.4", path = "../gix-path" } gix-attributes = { version = "^0.22.0", path = "../gix-attributes" } gix-config-value = { version = "^0.14.4", path = "../gix-config-value" } bstr = { version = "1.3.0", default-features = false, features = ["std"]} bitflags = "2" thiserror = "1.0.26" [dev-dependencies] gix-testtools = { path = "../tests/tools" } once_cell = "1.12.0" serial_test = "2.0.0" gix-pathspec-0.6.0/LICENSE-APACHE000064400000000000000000000247461046102023000141640ustar 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-pathspec-0.6.0/LICENSE-MIT000064400000000000000000000017771046102023000136730ustar 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-pathspec-0.6.0/README.md000064400000000000000000000010321046102023000134760ustar 00000000000000# `gix-pathspec` ### Testing #### Fuzzing `cargo fuzz` is used for fuzzing, installable with `cargo install cargo-fuzz`. Targets can be listed with `cargo fuzz list` and executed via `cargo +nightly fuzz run `, where `` can be `parse` for example. ### Notes - There is one additional keyword that `git` can parse, but that this crate doesn't support yet: the `prefix` keyword [Here is a commit](https://github.com/git/git/commit/5be4efbefafcd5b81fe3d97e8395da1887b4902a) in which `prefix` is somewhat explained. gix-pathspec-0.6.0/src/defaults.rs000064400000000000000000000053311046102023000151710ustar 00000000000000use std::ffi::OsString; use crate::{Defaults, MagicSignature, SearchMode}; /// pub mod from_environment { /// The error returned by [Defaults::from_environment()](super::Defaults::from_environment()). #[derive(Debug, thiserror::Error)] #[allow(missing_docs)] pub enum Error { #[error(transparent)] ParseValue(#[from] gix_config_value::Error), #[error("Glob and no-glob settings are mutually exclusive")] MixedGlobAndNoGlob, } } impl Defaults { /// Initialize this instance using information from the environment as /// [per the official documentation](https://git-scm.com/book/en/v2/Git-Internals-Environment-Variables) *(look for `PATHSPECS`)*, /// calling `var(variable_name)` for each variable that should be obtained. /// /// Used environment variables are `GIT_GLOB_PATHSPECS`, `GIT_NOGLOB_PATHSPECS`, `GIT_LITERAL_PATHSPECS` and `GIT_ICASE_PATHSPECS`. /// Note that there are lot of failure modes, and instead of offering lenient parsing, the caller may ignore errors and /// use other defaults instead. /// /// ### Deviation /// /// Instead of failing if `GIT_LITERAL_PATHSPECS` is used with glob globals, we ignore these. Also our implementation allows global /// `icase` settings in combination with this setting. pub fn from_environment(var: &mut dyn FnMut(&str) -> Option) -> Result { let mut env_bool = |name: &str| -> Result, gix_config_value::Error> { var(name) .map(|val| gix_config_value::Boolean::try_from(val).map(|b| b.0)) .transpose() }; let literal = env_bool("GIT_LITERAL_PATHSPECS")?.unwrap_or_default(); let signature = env_bool("GIT_ICASE_PATHSPECS")? .and_then(|val| val.then_some(MagicSignature::ICASE)) .unwrap_or_default(); if literal { return Ok(Defaults { signature, search_mode: SearchMode::Literal, literal, }); } let glob = env_bool("GIT_GLOB_PATHSPECS")?; let mut search_mode = glob .and_then(|glob| glob.then_some(SearchMode::PathAwareGlob)) .unwrap_or_default(); search_mode = env_bool("GIT_NOGLOB_PATHSPECS")? .map(|no_glob| { if glob.unwrap_or_default() && no_glob { Err(from_environment::Error::MixedGlobAndNoGlob) } else { Ok(SearchMode::Literal) } }) .transpose()? .unwrap_or(search_mode); Ok(Defaults { signature, search_mode, literal, }) } } gix-pathspec-0.6.0/src/lib.rs000064400000000000000000000134521046102023000141330ustar 00000000000000//! Parse [path specifications](https://git-scm.com/docs/gitglossary#Documentation/gitglossary.txt-aiddefpathspecapathspec) and //! see if a path matches. #![deny(missing_docs, rust_2018_idioms)] #![forbid(unsafe_code)] use std::path::PathBuf; use bitflags::bitflags; use bstr::BString; /// `gix-glob` types are available through [`attributes::glob`]. pub use gix_attributes as attributes; /// pub mod normalize { use std::path::PathBuf; /// The error returned by [Pattern::normalize()](super::Pattern::normalize()). #[derive(Debug, thiserror::Error)] #[allow(missing_docs)] pub enum Error { #[error("The path '{}' is not inside of the worktree '{}'", path.display(), worktree_path.display())] AbsolutePathOutsideOfWorktree { path: PathBuf, worktree_path: PathBuf }, #[error("The path '{}' leaves the repository", path.display())] OutsideOfWorktree { path: PathBuf }, } } mod pattern; /// pub mod search; /// pub mod parse; /// Default settings for some fields of a [`Pattern`]. /// /// These can be used to represent `GIT_*_PATHSPECS` environment variables, for example. #[derive(Debug, Default, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)] pub struct Defaults { /// The default signature. pub signature: MagicSignature, /// The default search-mode. /// /// Note that even if it's [`SearchMode::Literal`], the pathspecs will be parsed as usual, but matched verbatim afterwards. /// /// Note that pathspecs can override this the [`SearchMode::Literal`] variant with an explicit `:(glob)` prefix. pub search_mode: SearchMode, /// If set, the pathspec will not be parsed but used verbatim. Implies [`SearchMode::Literal`] for `search_mode`. pub literal: bool, } /// pub mod defaults; /// A lists of pathspec patterns, possibly from a file. /// /// Pathspecs are generally relative to the root of the repository. #[derive(Debug, Clone)] pub struct Search { /// 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. 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, /// If `true`, this means all `patterns` are exclude patterns. This means that if there is no match /// (which would exclude an item), we would actually match it for lack of exclusion. all_patterns_are_excluded: bool, /// The amount of bytes that are in common among all `patterns` and that aren't matched case-insensitively common_prefix_len: usize, } /// The output of a pathspec [parsing][parse()] operation. It can be used to match against a one or more paths. #[derive(Default, PartialEq, Eq, Debug, Hash, Ord, PartialOrd, Clone)] pub struct Pattern { /// The path part of a pathspec, which is typically a path possibly mixed with glob patterns. /// Note that it might be an empty string as well. /// /// For example, `:(top,literal,icase,attr,exclude)some/path` would yield `some/path`. path: BString, /// All magic signatures that were included in the pathspec. pub signature: MagicSignature, /// The search mode of the pathspec. pub search_mode: SearchMode, /// All attributes that were included in the `ATTR` part of the pathspec, if present. /// /// `:(attr:a=one b=):path` would yield attribute `a` and `b`. pub attributes: Vec, /// If `true`, we are a special Nil pattern and always match. nil: bool, /// The length of bytes in `path` that belong to the prefix, which will always be matched case-sensitively /// on case-sensitive filesystems. /// /// That way, even though pathspecs are applied from the top, we can emulate having changed directory into /// a specific sub-directory in a case-sensitive file-system, even if the rest of the pathspec can be set to /// match case-insensitively. /// Is set by [Pattern::normalize()]. prefix_len: usize, } bitflags! { /// Flags to represent 'magic signatures' which are parsed behind colons, like `:top:`. #[derive(Default, PartialEq, Eq, Debug, Hash, Ord, PartialOrd, Clone, Copy)] pub struct MagicSignature: u32 { /// Matches patterns from the root of the repository const TOP = 1 << 0; /// Matches patterns in case insensitive mode const ICASE = 1 << 1; /// Excludes the matching patterns from the previous results const EXCLUDE = 1 << 2; /// The pattern must match a directory, and not a file. /// This is equivalent to how it's handled in `gix-glob` const MUST_BE_DIR = 1 << 3; } } /// Parts of [magic signatures][MagicSignature] which don't stack as they all configure /// the way path specs are matched. #[derive(Default, PartialEq, Eq, Debug, Hash, Ord, PartialOrd, Clone, Copy)] pub enum SearchMode { /// Expand special characters like `*` similar to how the shell would do it. /// /// See [`PathAwareGlob`](SearchMode::PathAwareGlob) for the alternative. #[default] ShellGlob, /// Special characters in the pattern, like `*` or `?`, are treated literally, effectively turning off globbing. Literal, /// A single `*` will not match a `/` in the pattern, but a `**` will PathAwareGlob, } /// Parse a git-style pathspec into a [`Pattern`], /// setting the given `default` values in case these aren't specified in `input`. /// /// Note that empty [paths](Pattern::path) are allowed here, and generally some processing has to be performed. pub fn parse(input: &[u8], default: Defaults) -> Result { Pattern::from_bytes(input, default) } gix-pathspec-0.6.0/src/parse.rs000064400000000000000000000206401046102023000144740ustar 00000000000000use std::borrow::Cow; use bstr::{BStr, BString, ByteSlice, ByteVec}; use crate::{Defaults, MagicSignature, Pattern, SearchMode}; /// The error returned by [parse()][crate::parse()]. #[derive(thiserror::Error, Debug)] #[allow(missing_docs)] pub enum Error { #[error("An empty string is not a valid pathspec")] EmptyString, #[error("Found {keyword:?} in signature, which is not a valid keyword")] InvalidKeyword { keyword: BString }, #[error("Unimplemented short keyword: {short_keyword:?}")] Unimplemented { short_keyword: char }, #[error("Missing ')' at the end of pathspec signature")] MissingClosingParenthesis, #[error("Attribute has non-ascii characters or starts with '-': {attribute:?}")] InvalidAttribute { attribute: BString }, #[error("Invalid character in attribute value: {character:?}")] InvalidAttributeValue { character: char }, #[error("Escape character '\\' is not allowed as the last character in an attribute value")] TrailingEscapeCharacter, #[error("Attribute specification cannot be empty")] EmptyAttribute, #[error("Only one attribute specification is allowed in the same pathspec")] MultipleAttributeSpecifications, #[error("'literal' and 'glob' keywords cannot be used together in the same pathspec")] IncompatibleSearchModes, } impl Pattern { /// Try to parse a path-spec pattern from the given `input` bytes. pub fn from_bytes( input: &[u8], Defaults { signature, search_mode, literal, }: Defaults, ) -> Result { if input.is_empty() { return Err(Error::EmptyString); } if literal { return Ok(Self::from_literal(input, signature)); } if input.as_bstr() == ":" { return Ok(Pattern { nil: true, ..Default::default() }); } let mut p = Pattern { signature, search_mode: SearchMode::default(), ..Default::default() }; let mut cursor = 0; if input.first() == Some(&b':') { cursor += 1; p.signature |= parse_short_keywords(input, &mut cursor)?; if let Some(b'(') = input.get(cursor) { cursor += 1; parse_long_keywords(input, &mut p, &mut cursor)?; } } if search_mode != Default::default() && p.search_mode == Default::default() { p.search_mode = search_mode; } let mut path = &input[cursor..]; if path.last() == Some(&b'/') { p.signature |= MagicSignature::MUST_BE_DIR; path = &path[..path.len() - 1]; } p.path = path.into(); Ok(p) } /// Take `input` literally without parsing anything. This will also set our mode to `literal` to allow this pathspec to match `input` verbatim, and /// use `default_signature` as magic signature. pub fn from_literal(input: &[u8], default_signature: MagicSignature) -> Self { Pattern { path: input.into(), signature: default_signature, search_mode: SearchMode::Literal, ..Default::default() } } } fn parse_short_keywords(input: &[u8], cursor: &mut usize) -> Result { let unimplemented_chars = b"\"#%&'-',;<=>@_`~"; let mut signature = MagicSignature::empty(); while let Some(&b) = input.get(*cursor) { *cursor += 1; signature |= match b { b'/' => MagicSignature::TOP, b'^' | b'!' => MagicSignature::EXCLUDE, b':' => break, _ if unimplemented_chars.contains(&b) => { return Err(Error::Unimplemented { short_keyword: b.into(), }); } _ => { *cursor -= 1; break; } } } Ok(signature) } fn parse_long_keywords(input: &[u8], p: &mut Pattern, cursor: &mut usize) -> Result<(), Error> { let end = input.find(")").ok_or(Error::MissingClosingParenthesis)?; let input = &input[*cursor..end]; *cursor = end + 1; if input.is_empty() { return Ok(()); } split_on_non_escaped_char(input, b',', |keyword| { let attr_prefix = b"attr:"; match keyword { b"attr" => {} b"top" => p.signature |= MagicSignature::TOP, b"icase" => p.signature |= MagicSignature::ICASE, b"exclude" => p.signature |= MagicSignature::EXCLUDE, b"literal" => match p.search_mode { SearchMode::PathAwareGlob => return Err(Error::IncompatibleSearchModes), _ => p.search_mode = SearchMode::Literal, }, b"glob" => match p.search_mode { SearchMode::Literal => return Err(Error::IncompatibleSearchModes), _ => p.search_mode = SearchMode::PathAwareGlob, }, _ if keyword.starts_with(attr_prefix) => { if p.attributes.is_empty() { p.attributes = parse_attributes(&keyword[attr_prefix.len()..])?; } else { return Err(Error::MultipleAttributeSpecifications); } } _ => { return Err(Error::InvalidKeyword { keyword: BString::from(keyword), }); } }; Ok(()) }) } fn split_on_non_escaped_char( input: &[u8], split_char: u8, mut f: impl FnMut(&[u8]) -> Result<(), Error>, ) -> Result<(), Error> { let mut i = 0; let mut last = 0; for window in input.windows(2) { i += 1; if window[0] != b'\\' && window[1] == split_char { let keyword = &input[last..i]; f(keyword)?; last = i + 1; } } let last_keyword = &input[last..]; f(last_keyword) } fn parse_attributes(input: &[u8]) -> Result, Error> { if input.is_empty() { return Err(Error::EmptyAttribute); } let unescaped = unescape_attribute_values(input.into())?; gix_attributes::parse::Iter::new(unescaped.as_bstr()) .map(|res| res.map(gix_attributes::AssignmentRef::to_owned)) .collect::, _>>() .map_err(|e| Error::InvalidAttribute { attribute: e.attribute }) } fn unescape_attribute_values(input: &BStr) -> Result, Error> { if !input.contains(&b'=') { return Ok(Cow::Borrowed(input)); } let mut out: Cow<'_, BStr> = Cow::Borrowed("".into()); for attr in input.split(|&c| c == b' ') { let split_point = attr.find_byte(b'=').map_or_else(|| attr.len(), |i| i + 1); let (name, value) = attr.split_at(split_point); if value.contains(&b'\\') { let out = out.to_mut(); out.push_str(name); out.push_str(unescape_and_check_attr_value(value.into())?); out.push(b' '); } else { check_attribute_value(value.as_bstr())?; match out { Cow::Borrowed(_) => { let end = out.len() + attr.len() + 1; out = Cow::Borrowed(&input[0..end.min(input.len())]); } Cow::Owned(_) => { let out = out.to_mut(); out.push_str(name); out.push_str(value); out.push(b' '); } } } } Ok(out) } fn unescape_and_check_attr_value(value: &BStr) -> Result { let mut out = BString::from(Vec::with_capacity(value.len())); let mut bytes = value.iter(); while let Some(mut b) = bytes.next().copied() { if b == b'\\' { b = *bytes.next().ok_or(Error::TrailingEscapeCharacter)?; } out.push(validated_attr_value_byte(b)?); } Ok(out) } fn check_attribute_value(input: &BStr) -> Result<(), Error> { match input.iter().copied().find(|b| !is_valid_attr_value(*b)) { Some(b) => Err(Error::InvalidAttributeValue { character: b as char }), None => Ok(()), } } fn is_valid_attr_value(byte: u8) -> bool { byte.is_ascii_alphanumeric() || b",-_".contains(&byte) } fn validated_attr_value_byte(byte: u8) -> Result { if is_valid_attr_value(byte) { Ok(byte) } else { Err(Error::InvalidAttributeValue { character: byte as char, }) } } gix-pathspec-0.6.0/src/pattern.rs000064400000000000000000000166151046102023000150460ustar 00000000000000use std::path::{Component, Path, PathBuf}; use bstr::{BStr, BString, ByteSlice, ByteVec}; use crate::{normalize, MagicSignature, Pattern, SearchMode}; /// Access impl Pattern { /// Returns `true` if this seems to be a pathspec that indicates that 'there is no pathspec'. /// /// Note that such a spec is `:`. pub fn is_nil(&self) -> bool { self.nil } /// Return the prefix-portion of the `path` of this spec, which is a *directory*. /// It can be empty if there is no prefix. /// /// A prefix is effectively the CWD seen as relative to the working tree, and it's assumed to /// match case-sensitively. This makes it useful for skipping over large portions of input by /// directly comparing them. pub fn prefix_directory(&self) -> &BStr { self.path[..self.prefix_len].as_bstr() } /// Return the path of this spec, typically used for matching. pub fn path(&self) -> &BStr { self.path.as_ref() } } /// Mutation impl Pattern { /// Normalize the pattern's path by assuring it's relative to the root of the working tree, and contains /// no relative path components. Further, it assures that `/` are used as path separator. /// /// If `self.path` is a relative path, it will be put in front of the pattern path if `self.signature` isn't indicating `TOP` already. /// If `self.path` is an absolute path, we will use `root` to make it worktree relative if possible. /// /// `prefix` can be empty, we will still normalize this pathspec to resolve relative path components, and /// it is assumed not to contain any relative path components, e.g. '', 'a', 'a/b' are valid. /// `root` is the absolute path to the root of either the worktree or the repository's `git_dir`. pub fn normalize(&mut self, prefix: &Path, root: &Path) -> Result<&mut Self, normalize::Error> { fn prefix_components_to_subtract(path: &Path) -> usize { let parent_component_end_bound = path.components().enumerate().fold(None::, |acc, (idx, c)| { matches!(c, Component::ParentDir).then_some(idx + 1).or(acc) }); let count = path .components() .take(parent_component_end_bound.unwrap_or(0)) .map(|c| match c { Component::ParentDir => 1_isize, Component::Normal(_) => -1, _ => 0, }) .sum::(); (count > 0).then_some(count as usize).unwrap_or_default() } let mut path = gix_path::from_bstr(self.path.as_bstr()); let mut num_prefix_components = 0; let mut was_absolute = false; if gix_path::is_absolute(path.as_ref()) { was_absolute = true; let rela_path = match path.strip_prefix(root) { Ok(path) => path, Err(_) => { return Err(normalize::Error::AbsolutePathOutsideOfWorktree { path: path.into_owned(), worktree_path: root.into(), }) } }; path = rela_path.to_owned().into(); } else if !prefix.as_os_str().is_empty() && !self.signature.contains(MagicSignature::TOP) { debug_assert_eq!( prefix .components() .filter(|c| matches!(c, Component::Normal(_))) .count(), prefix.components().count(), "BUG: prefixes must not have relative path components, or calculations here will be wrong so pattern won't match" ); num_prefix_components = prefix .components() .count() .saturating_sub(prefix_components_to_subtract(path.as_ref())); path = prefix.join(path).into(); } let assure_path_cannot_break_out_upwards = Path::new(""); let path = match gix_path::normalize(path.as_ref().into(), assure_path_cannot_break_out_upwards) { Some(path) => { if was_absolute { num_prefix_components = path.components().count().saturating_sub( if self.signature.contains(MagicSignature::MUST_BE_DIR) { 0 } else { 1 }, ); } path } None => { return Err(normalize::Error::OutsideOfWorktree { path: path.into_owned(), }) } }; self.path = if path == Path::new(".") { BString::from(".") } else { let cleaned = PathBuf::from_iter(path.components().filter(|c| !matches!(c, Component::CurDir))); let mut out = gix_path::to_unix_separators_on_windows(gix_path::into_bstr(cleaned)).into_owned(); self.prefix_len = { if self.signature.contains(MagicSignature::MUST_BE_DIR) { out.push(b'/'); } let len = out .find_iter(b"/") .take(num_prefix_components) .last() .unwrap_or_default(); if self.signature.contains(MagicSignature::MUST_BE_DIR) { out.pop(); } len }; out }; Ok(self) } } /// Access impl Pattern { /// Return `true` if this pathspec is negated, which means it will exclude an item from the result set instead of including it. pub fn is_excluded(&self) -> bool { self.signature.contains(MagicSignature::EXCLUDE) } /// Translate ourselves to a long display format, that when parsed back will yield the same pattern. /// /// Note that the pub fn to_bstring(&self) -> BString { if self.is_nil() { ":".into() } else { let mut buf: BString = ":(".into(); if self.signature.contains(MagicSignature::TOP) { buf.push_str("top,"); } if self.signature.contains(MagicSignature::EXCLUDE) { buf.push_str("exclude,"); } if self.signature.contains(MagicSignature::ICASE) { buf.push_str("icase,"); } match self.search_mode { SearchMode::ShellGlob => {} SearchMode::Literal => buf.push_str("literal,"), SearchMode::PathAwareGlob => buf.push_str("glob,"), } if self.attributes.is_empty() { if buf.last() == Some(&b',') { buf.pop(); } } else { buf.push_str("attr:"); for attr in &self.attributes { let attr = attr.as_ref().to_string().replace(',', "\\,"); buf.push_str(&attr); buf.push(b' '); } buf.pop(); // trailing ' ' } buf.push(b')'); buf.extend_from_slice(&self.path); if self.signature.contains(MagicSignature::MUST_BE_DIR) { buf.push(b'/'); } buf } } } impl std::fmt::Display for Pattern { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.to_bstring().fmt(f) } } gix-pathspec-0.6.0/src/search/init.rs000064400000000000000000000122021046102023000155650ustar 00000000000000use std::path::Path; use crate::{search::Spec, MagicSignature, Pattern, Search}; /// Create a new specification to support matches from `pathspec`, [normalizing](Pattern::normalize()) it with `prefix` and `root`. fn mapping_from_pattern( mut pathspec: Pattern, prefix: &Path, root: &Path, sequence_number: usize, ) -> Result, crate::normalize::Error> { pathspec.normalize(prefix, root)?; let mut match_all = pathspec.is_nil(); let glob = { let mut g = gix_glob::Pattern::from_bytes_without_negation(&pathspec.path).unwrap_or_else(|| { match_all = true; // This pattern is setup to match literally as all-whitespace. gix_glob::Pattern { text: pathspec.path.clone(), mode: gix_glob::pattern::Mode::empty(), first_wildcard_pos: None, } }); g.mode |= gix_glob::pattern::Mode::ABSOLUTE; if pathspec.signature.contains(MagicSignature::MUST_BE_DIR) { g.mode |= gix_glob::pattern::Mode::MUST_BE_DIR; } g }; Ok(gix_glob::search::pattern::Mapping { pattern: glob, value: Spec { attrs_match: { (!pathspec.attributes.is_empty()).then(|| { let mut out = gix_attributes::search::Outcome::default(); out.initialize_with_selection( &Default::default(), pathspec.attributes.iter().map(|a| a.name.as_str()), ); out }) }, pattern: pathspec, }, sequence_number, }) } fn common_prefix_len(patterns: &[gix_glob::search::pattern::Mapping]) -> usize { let mut count = 0; let len = patterns .iter() .filter(|p| !p.value.pattern.is_excluded()) .map(|p| { count += 1; if p.value.pattern.signature.contains(MagicSignature::ICASE) { p.value.pattern.prefix_len } else { p.pattern.first_wildcard_pos.unwrap_or(p.pattern.text.len()) } }) .min() .unwrap_or_default(); if len == 0 { return 0; } let mut max_len = len; if count < 2 { return max_len; } let mut patterns = patterns .iter() .filter(|p| !p.value.pattern.is_excluded()) .map(|p| &p.value.pattern.path); let base = &patterns.next().expect("at least two patterns"); for path in patterns { for (idx, (a, b)) in base[..max_len].iter().zip(path[..max_len].iter()).enumerate() { if *a != *b { max_len = idx; break; } } } max_len } /// Lifecycle impl Search { /// Create a search from ready-made `pathspecs`, and [normalize](Pattern::normalize()) them with `prefix` and `root`. /// `root` is the absolute path to the worktree root, if available, or the `git_dir` in case of bare repositories. /// If `pathspecs` doesn't yield any pattern, we will match everything automatically. If `prefix` is also provided and not empty, /// an artificial pattern will be added to yield all. pub fn from_specs( pathspecs: impl IntoIterator, prefix: Option<&std::path::Path>, root: &std::path::Path, ) -> Result { fn inner( pathspecs: &mut dyn Iterator, prefix: Option<&std::path::Path>, root: &std::path::Path, ) -> Result { let prefix = prefix.unwrap_or(std::path::Path::new("")); let mut patterns = pathspecs .enumerate() .map(|(idx, pattern)| mapping_from_pattern(pattern, prefix, root, idx)) .collect::, _>>()?; if patterns.is_empty() && !prefix.as_os_str().is_empty() { patterns.push(mapping_from_pattern( Pattern::from_literal(&[], MagicSignature::MUST_BE_DIR), prefix, root, 0, )?); } // Excludes should always happen first so we know a match is authoritative (otherwise we could find a non-excluding match first). patterns.sort_by(|a, b| { a.value .pattern .is_excluded() .cmp(&b.value.pattern.is_excluded()) .reverse() }); let common_prefix_len = common_prefix_len(&patterns); Ok(Search { all_patterns_are_excluded: patterns.iter().all(|s| s.value.pattern.is_excluded()), patterns, source: None, common_prefix_len, }) } inner(&mut pathspecs.into_iter(), prefix, root) } /// Obtain ownership of the normalized pathspec patterns that were used for the search. pub fn into_patterns(self) -> impl Iterator { self.patterns.into_iter().map(|p| p.value.pattern) } } gix-pathspec-0.6.0/src/search/matching.rs000064400000000000000000000151001046102023000164140ustar 00000000000000use bstr::{BStr, BString, ByteSlice}; use gix_glob::pattern::Case; use crate::{ search::{Match, Spec}, MagicSignature, Pattern, Search, SearchMode, }; impl Search { /// Return the first [`Match`] of `relative_path`, or `None`. /// `is_dir` is `true` if `relative_path` is a directory. /// `attributes` is called as `attributes(relative_path, case, is_dir, outcome) -> has_match` to obtain for attributes for `relative_path`, if /// the underlying pathspec defined an attribute filter, to be stored in `outcome`, returning true if there was a match. /// All attributes of the pathspec have to be present in the defined value for the pathspec to match. /// /// Note that `relative_path` is expected to be starting at the same root as is assumed for this pattern, see [`Pattern::normalize()`]. /// Further, empty searches match everything, as if `:` was provided. /// /// ### Deviation /// /// The case-sensivity of the attribute match is controlled by the sensitivity of the pathspec, instead of being based on the /// case folding settings of the repository. That way we assure that the matching is consistent. /// Higher-level crates should control this default case folding of pathspecs when instantiating them, which is when they can /// set it to match the repository setting for more natural behaviour when, for instance, adding files to a repository: /// as it stands, on a case-insensitive file system, `touch File && git add file` will not add the file, but also not error. pub fn pattern_matching_relative_path( &mut self, relative_path: &BStr, is_dir: Option, attributes: &mut dyn FnMut(&BStr, Case, bool, &mut gix_attributes::search::Outcome) -> bool, ) -> Option> { let basename_not_important = None; if relative_path .get(..self.common_prefix_len) .map_or(true, |rela_path_prefix| rela_path_prefix != self.common_prefix()) { return None; } let is_dir = is_dir.unwrap_or(false); let patterns_len = self.patterns.len(); let res = self.patterns.iter_mut().find_map(|mapping| { let ignore_case = mapping.value.pattern.signature.contains(MagicSignature::ICASE); let prefix = mapping.value.pattern.prefix_directory(); if ignore_case && !prefix.is_empty() { let pattern_requirement_is_met = relative_path.get(prefix.len()).map_or_else(|| is_dir, |b| *b == b'/'); if !pattern_requirement_is_met || relative_path.get(..prefix.len()).map(ByteSlice::as_bstr) != Some(prefix) { return None; } } let case = if ignore_case { Case::Fold } else { Case::Sensitive }; let mut is_match = mapping.value.pattern.is_nil() || mapping.value.pattern.path.is_empty(); if !is_match { is_match = if mapping.pattern.first_wildcard_pos.is_none() { match_verbatim(mapping, relative_path, is_dir, case) } else { let wildmatch_mode = match mapping.value.pattern.search_mode { SearchMode::ShellGlob => Some(gix_glob::wildmatch::Mode::empty()), SearchMode::Literal => None, SearchMode::PathAwareGlob => Some(gix_glob::wildmatch::Mode::NO_MATCH_SLASH_LITERAL), }; match wildmatch_mode { Some(wildmatch_mode) => { let is_match = mapping.pattern.matches_repo_relative_path( relative_path, basename_not_important, Some(is_dir), case, wildmatch_mode, ); if !is_match { match_verbatim(mapping, relative_path, is_dir, case) } else { true } } None => match_verbatim(mapping, relative_path, is_dir, case), } } } if let Some(attrs) = mapping.value.attrs_match.as_mut() { if !attributes(relative_path, Case::Sensitive, is_dir, attrs) { // we have attrs, but it didn't match any return None; } for (actual, expected) in attrs.iter_selected().zip(mapping.value.pattern.attributes.iter()) { if actual.assignment != expected.as_ref() { return None; } } } is_match.then_some(Match { pattern: &mapping.value.pattern, sequence_number: mapping.sequence_number, }) }); if res.is_none() && self.all_patterns_are_excluded { static MATCH_ALL_STAND_IN: Pattern = Pattern { path: BString::new(Vec::new()), signature: MagicSignature::empty(), search_mode: SearchMode::ShellGlob, attributes: Vec::new(), prefix_len: 0, nil: true, }; Some(Match { pattern: &MATCH_ALL_STAND_IN, sequence_number: patterns_len, }) } else { res } } } fn match_verbatim( mapping: &gix_glob::search::pattern::Mapping, relative_path: &BStr, is_dir: bool, case: Case, ) -> bool { let pattern_len = mapping.value.pattern.path.len(); let mut relative_path_ends_with_slash_at_pattern_len = false; let match_is_allowed = relative_path.get(pattern_len).map_or_else( || relative_path.len() == pattern_len, |b| { relative_path_ends_with_slash_at_pattern_len = *b == b'/'; relative_path_ends_with_slash_at_pattern_len }, ); let pattern_requirement_is_met = !mapping.pattern.mode.contains(gix_glob::pattern::Mode::MUST_BE_DIR) || (relative_path_ends_with_slash_at_pattern_len || is_dir); if match_is_allowed && pattern_requirement_is_met { let dir_or_file = &relative_path[..mapping.value.pattern.path.len()]; match case { Case::Sensitive => mapping.value.pattern.path == dir_or_file, Case::Fold => mapping.value.pattern.path.eq_ignore_ascii_case(dir_or_file), } } else { false } } gix-pathspec-0.6.0/src/search/mod.rs000064400000000000000000000036701046102023000154120ustar 00000000000000use bstr::{BStr, ByteSlice}; use crate::{Pattern, Search}; /// Describes a matching pattern within a search for ignored paths. #[derive(PartialEq, Eq, Debug, Hash, Ord, PartialOrd, Clone)] pub struct Match<'a> { /// The matching search specification, which contains the pathspec as well. pub pattern: &'a Pattern, /// The number of the sequence the matching pathspec was in, or the line of pathspec file it was read from if [Search::source] is not `None`. pub sequence_number: usize, } mod init; impl Match<'_> { /// Return `true` if the pathspec that matched was negative, which excludes this item from the set. pub fn is_excluded(&self) -> bool { self.pattern.is_excluded() } } /// Access impl Search { /// Return an iterator over the patterns that participate in the search. pub fn patterns(&self) -> impl Iterator + '_ { self.patterns.iter().map(|m| &m.value.pattern) } /// Return the portion of the prefix among all of the pathspecs involved in this search, or an empty string if /// there is none. It doesn't have to end at a directory boundary though, nor does it denote a directory. /// /// Note that the common_prefix is always matched case-sensitively, and it is useful to skip large portions of input. /// Further, excluded pathspecs don't participate which makes this common prefix inclusive. To work correctly though, /// one will have to additionally match paths that have the common prefix with that pathspec itself to assure it is /// not excluded. pub fn common_prefix(&self) -> &BStr { self.patterns .iter() .find(|p| !p.value.pattern.is_excluded()) .map_or("".into(), |m| m.value.pattern.path[..self.common_prefix_len].as_bstr()) } } #[derive(Default, Clone, Debug)] pub(crate) struct Spec { pub pattern: Pattern, pub attrs_match: Option, } mod matching;