pub struct PatternList<T: Pattern> {
    pub patterns: Vec<PatternMapping<T::Value>>,
    pub source: Option<PathBuf>,
    pub base: Option<BString>,
}
Expand description

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.

Fields§

§patterns: Vec<PatternMapping<T::Value>>

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.

§source: Option<PathBuf>

The path from which the patterns were read, or None if the patterns don’t originate in a file on disk.

§base: Option<BString>

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.

Implementations§

source is the location of the bytes which represent a list of patterns line by line.

Examples found in repository?
src/match_group.rs (line 192)
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
    pub fn add_patterns_buffer(&mut self, bytes: &[u8], source: impl Into<PathBuf>, root: Option<&Path>) {
        self.patterns
            .push(PatternList::<Ignore>::from_bytes(bytes, source.into(), root));
    }
}

fn read_in_full_ignore_missing(path: &Path, follow_symlinks: bool, buf: &mut Vec<u8>) -> std::io::Result<bool> {
    buf.clear();
    let file = if follow_symlinks {
        std::fs::File::open(path)
    } else {
        git_features::fs::open_options_no_follow().read(true).open(path)
    };
    Ok(match file {
        Ok(mut file) => {
            file.read_to_end(buf)?;
            true
        }
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => false,
        Err(err) => return Err(err),
    })
}

impl<T> PatternList<T>
where
    T: Pattern,
{
    /// `source` is the location of the `bytes` which represent a list of patterns line by line.
    pub fn from_bytes(bytes: &[u8], source: impl Into<PathBuf>, root: Option<&Path>) -> Self {
        let source = source.into();
        let patterns = T::bytes_to_patterns(bytes);

        let base = root
            .and_then(|root| source.parent().expect("file").strip_prefix(root).ok())
            .and_then(|base| {
                (!base.as_os_str().is_empty()).then(|| {
                    let mut base: BString =
                        git_path::to_unix_separators_on_windows(git_path::into_bstr(base)).into_owned();

                    base.push_byte(b'/');
                    base
                })
            });
        PatternList {
            patterns,
            source: Some(source),
            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<PathBuf>,
        root: Option<&Path>,
        follow_symlinks: bool,
        buf: &mut Vec<u8>,
    ) -> std::io::Result<Option<Self>> {
        let source = source.into();
        Ok(read_in_full_ignore_missing(&source, follow_symlinks, buf)?.then(|| Self::from_bytes(buf, source, root)))
    }

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.

Examples found in repository?
src/match_group.rs (line 149)
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
    pub fn from_git_dir(
        git_dir: impl AsRef<Path>,
        excludes_file: Option<PathBuf>,
        buf: &mut Vec<u8>,
    ) -> std::io::Result<Self> {
        let mut group = Self::default();

        let follow_symlinks = true;
        // order matters! More important ones first.
        group.patterns.extend(
            excludes_file
                .map(|file| PatternList::<Ignore>::from_file(file, None, follow_symlinks, buf))
                .transpose()?
                .flatten(),
        );
        group.patterns.extend(PatternList::<Ignore>::from_file(
            git_dir.as_ref().join("info").join("exclude"),
            None,
            follow_symlinks,
            buf,
        )?);
        Ok(group)
    }

    /// See [PatternList::<Ignore>::from_overrides()] for details.
    pub fn from_overrides(patterns: impl IntoIterator<Item = impl Into<OsString>>) -> Self {
        MatchGroup {
            patterns: vec![PatternList::<Ignore>::from_overrides(patterns)],
        }
    }

    /// 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(
        &mut self,
        source: impl Into<PathBuf>,
        follow_symlinks: bool,
        root: Option<&Path>,
        buf: &mut Vec<u8>,
    ) -> std::io::Result<bool> {
        let previous_len = self.patterns.len();
        self.patterns.extend(PatternList::<Ignore>::from_file(
            source.into(),
            root,
            follow_symlinks,
            buf,
        )?);
        Ok(self.patterns.len() != previous_len)
    }

Return a match if a pattern matches relative_path, providing a pre-computed basename_pos which is the starting position of the basename of relative_path. is_dir is true if relative_path is a directory. case specifies whether cases should be folded during matching or not.

Examples found in repository?
src/match_group.rs (line 130)
119
120
121
122
123
124
125
126
127
128
129
130
131
    pub fn pattern_matching_relative_path<'a>(
        &self,
        relative_path: impl Into<&'a BStr>,
        is_dir: Option<bool>,
        case: git_glob::pattern::Case,
    ) -> Option<Match<'_, T::Value>> {
        let relative_path = relative_path.into();
        let basename_pos = relative_path.rfind(b"/").map(|p| p + 1);
        self.patterns
            .iter()
            .rev()
            .find_map(|pl| pl.pattern_matching_relative_path(relative_path, basename_pos, is_dir, case))
    }

Like pattern_matching_relative_path(), but returns an index to the pattern that matched relative_path, instead of the match itself.

Parse a list of patterns, using slashes as path separators

Examples found in repository?
src/match_group.rs (line 165)
163
164
165
166
167
    pub fn from_overrides(patterns: impl IntoIterator<Item = impl Into<OsString>>) -> Self {
        MatchGroup {
            patterns: vec![PatternList::<Ignore>::from_overrides(patterns)],
        }
    }

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Returns the “default value” for a type. Read more
Feeds this value into the given Hasher. Read more
Feeds a slice of this type into the given Hasher. Read more
This method returns an Ordering between self and other. Read more
Compares and returns the maximum of two values. Read more
Compares and returns the minimum of two values. Read more
Restrict a value to a certain interval. Read more
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
This method returns an ordering between self and other values if one exists. Read more
This method tests less than (for self and other) and is used by the < operator. Read more
This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
This method tests greater than (for self and other) and is used by the > operator. Read more
This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.