|
| 1 | +use crate::{normalize, MagicSignature, MatchMode, Pattern}; |
| 2 | +use bstr::{BStr, BString, ByteSlice, ByteVec}; |
| 3 | +use std::path::{Component, Path, PathBuf}; |
| 4 | + |
| 5 | +/// Access |
| 6 | +impl Pattern { |
| 7 | + /// Returns `true` if this seems to be a pathspec that indicates that 'there is no pathspec'. |
| 8 | + /// |
| 9 | + /// Note that such a spec is `:`. |
| 10 | + pub fn is_nil(&self) -> bool { |
| 11 | + self.nil |
| 12 | + } |
| 13 | + |
| 14 | + /// Return the prefix-portion of the `path` of this spec, which is a *directory*. |
| 15 | + /// It can be empty if there is no prefix. |
| 16 | + /// |
| 17 | + /// A prefix is effectively the CWD seen as relative to the working tree, and it's assumed to |
| 18 | + /// match case-sensitively. This makes it useful for skipping over large portions of input by |
| 19 | + /// directly comparing them. |
| 20 | + pub fn prefix_directory(&self) -> &BStr { |
| 21 | + self.path[..self.prefix_len].as_bstr() |
| 22 | + } |
| 23 | + |
| 24 | + /// Return the path of this spec, typically used for matching. |
| 25 | + pub fn path(&self) -> &BStr { |
| 26 | + self.path.as_ref() |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +/// Mutation |
| 31 | +impl Pattern { |
| 32 | + /// Normalize the pattern's path by assuring it's relative to the root of the working tree, and contains |
| 33 | + /// no relative path components. Further, it assures that `/` are used as path separator. |
| 34 | + /// |
| 35 | + /// 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. |
| 36 | + /// If `self.path` is an absolute path, we will use `root` to make it worktree relative if possible. |
| 37 | + /// |
| 38 | + /// `prefix` can be empty, we will still normalize this pathspec to resolve relative path components, and |
| 39 | + /// it is assumed not to contain any relative path components, e.g. '', 'a', 'a/b' are valid. |
| 40 | + /// `root` is the absolute path to the root of either the worktree or the repository's `git_dir`. |
| 41 | + pub fn normalize(&mut self, prefix: &Path, root: &Path) -> Result<&mut Self, normalize::Error> { |
| 42 | + fn prefix_components_to_subtract(path: &Path) -> usize { |
| 43 | + let parent_component_end_bound = path.components().enumerate().fold(None::<usize>, |acc, (idx, c)| { |
| 44 | + matches!(c, Component::ParentDir).then_some(idx + 1).or(acc) |
| 45 | + }); |
| 46 | + let count = path |
| 47 | + .components() |
| 48 | + .take(parent_component_end_bound.unwrap_or(0)) |
| 49 | + .map(|c| match c { |
| 50 | + Component::ParentDir => 1_isize, |
| 51 | + Component::Normal(_) => -1, |
| 52 | + _ => 0, |
| 53 | + }) |
| 54 | + .sum::<isize>(); |
| 55 | + (count > 0).then_some(count as usize).unwrap_or_default() |
| 56 | + } |
| 57 | + |
| 58 | + let mut path = gix_path::from_bstr(self.path.as_ref()); |
| 59 | + let mut num_prefix_components = 0; |
| 60 | + let mut was_absolute = false; |
| 61 | + if gix_path::is_absolute(path.as_ref()) { |
| 62 | + was_absolute = true; |
| 63 | + let rela_path = match path.strip_prefix(root) { |
| 64 | + Ok(path) => path, |
| 65 | + Err(_) => { |
| 66 | + return Err(normalize::Error::AbsolutePathOutsideOfWorktree { |
| 67 | + path: path.into_owned(), |
| 68 | + worktree_path: root.into(), |
| 69 | + }) |
| 70 | + } |
| 71 | + }; |
| 72 | + path = rela_path.to_owned().into(); |
| 73 | + } else if !prefix.as_os_str().is_empty() && !self.signature.contains(MagicSignature::TOP) { |
| 74 | + debug_assert_eq!( |
| 75 | + prefix |
| 76 | + .components() |
| 77 | + .filter(|c| matches!(c, Component::Normal(_))) |
| 78 | + .count(), |
| 79 | + prefix.components().count(), |
| 80 | + "BUG: prefixes must not have relative path components, or calculations here will be wrong so pattern won't match" |
| 81 | + ); |
| 82 | + num_prefix_components = prefix |
| 83 | + .components() |
| 84 | + .count() |
| 85 | + .saturating_sub(prefix_components_to_subtract(path.as_ref())); |
| 86 | + path = prefix.join(path).into(); |
| 87 | + } |
| 88 | + |
| 89 | + let assure_path_cannot_break_out_upwards = Path::new(""); |
| 90 | + let path = match gix_path::normalize(path.as_ref(), assure_path_cannot_break_out_upwards) { |
| 91 | + Some(path) => { |
| 92 | + if was_absolute { |
| 93 | + num_prefix_components = path.components().count().saturating_sub( |
| 94 | + if self.signature.contains(MagicSignature::MUST_BE_DIR) { |
| 95 | + 0 |
| 96 | + } else { |
| 97 | + 1 |
| 98 | + }, |
| 99 | + ); |
| 100 | + } |
| 101 | + path |
| 102 | + } |
| 103 | + None => { |
| 104 | + return Err(normalize::Error::OutsideOfWorktree { |
| 105 | + path: path.into_owned(), |
| 106 | + }) |
| 107 | + } |
| 108 | + }; |
| 109 | + |
| 110 | + self.path = if path == Path::new(".") { |
| 111 | + BString::from(".") |
| 112 | + } else { |
| 113 | + let cleaned = PathBuf::from_iter(path.components().filter(|c| !matches!(c, Component::CurDir))); |
| 114 | + let mut out = gix_path::to_unix_separators_on_windows(gix_path::into_bstr(cleaned)).into_owned(); |
| 115 | + self.prefix_len = { |
| 116 | + if self.signature.contains(MagicSignature::MUST_BE_DIR) { |
| 117 | + out.push(b'/'); |
| 118 | + } |
| 119 | + let len = out |
| 120 | + .find_iter(b"/") |
| 121 | + .take(num_prefix_components) |
| 122 | + .last() |
| 123 | + .unwrap_or_default(); |
| 124 | + if self.signature.contains(MagicSignature::MUST_BE_DIR) { |
| 125 | + out.pop(); |
| 126 | + } |
| 127 | + len |
| 128 | + }; |
| 129 | + out |
| 130 | + }; |
| 131 | + |
| 132 | + Ok(self) |
| 133 | + } |
| 134 | +} |
| 135 | + |
| 136 | +/// Access |
| 137 | +impl Pattern { |
| 138 | + /// Return `true` if this pathspec is negated, which means it will exclude an item from the result set instead of including it. |
| 139 | + pub fn is_excluded(&self) -> bool { |
| 140 | + self.signature.contains(MagicSignature::EXCLUDE) |
| 141 | + } |
| 142 | + |
| 143 | + /// Translate ourselves to a long display format, that when parsed back will yield the same pattern. |
| 144 | + /// |
| 145 | + /// Note that the |
| 146 | + pub fn to_bstring(&self) -> BString { |
| 147 | + if self.is_nil() { |
| 148 | + ":".into() |
| 149 | + } else { |
| 150 | + let mut buf: BString = ":(".into(); |
| 151 | + if self.signature.contains(MagicSignature::TOP) { |
| 152 | + buf.push_str("top,"); |
| 153 | + } |
| 154 | + if self.signature.contains(MagicSignature::EXCLUDE) { |
| 155 | + buf.push_str("exclude,"); |
| 156 | + } |
| 157 | + if self.signature.contains(MagicSignature::ICASE) { |
| 158 | + buf.push_str("icase,"); |
| 159 | + } |
| 160 | + match self.search_mode { |
| 161 | + MatchMode::ShellGlob => {} |
| 162 | + MatchMode::Literal => buf.push_str("literal,"), |
| 163 | + MatchMode::PathAwareGlob => buf.push_str("glob,"), |
| 164 | + } |
| 165 | + if self.attributes.is_empty() { |
| 166 | + if buf.last() == Some(&b',') { |
| 167 | + buf.pop(); |
| 168 | + } |
| 169 | + } else { |
| 170 | + buf.push_str("attr:"); |
| 171 | + for attr in &self.attributes { |
| 172 | + let attr = attr.as_ref().to_string().replace(',', "\\,"); |
| 173 | + buf.push_str(&attr); |
| 174 | + buf.push(b' '); |
| 175 | + } |
| 176 | + buf.pop(); // trailing ' ' |
| 177 | + } |
| 178 | + buf.push(b')'); |
| 179 | + buf.extend_from_slice(&self.path); |
| 180 | + if self.signature.contains(MagicSignature::MUST_BE_DIR) { |
| 181 | + buf.push(b'/'); |
| 182 | + } |
| 183 | + buf |
| 184 | + } |
| 185 | + } |
| 186 | +} |
| 187 | + |
| 188 | +impl std::fmt::Display for Pattern { |
| 189 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 190 | + self.to_bstring().fmt(f) |
| 191 | + } |
| 192 | +} |
0 commit comments