API

pathspec

The pathspec package provides pattern matching for file paths. So far this only includes Git’s gitignore patterns.

The following classes are imported and made available from the root of the pathspec package:

The following functions are also imported:

The following deprecated functions are also imported to maintain backward compatibility:

pathspec.pathspec

This module provides PathSpec which is an object-oriented interface for pattern matching of files.

class pathspec.pathspec.PathSpec(patterns: Sequence[TPattern_co] | Iterable[TPattern_co], *, backend: Literal['best', 'hyperscan', 're2', 'simple'] | str | None = None, _test_backend_factory: Callable[[Sequence[Pattern]], _Backend] | None = None)[source]

Bases: Generic[TPattern_co]

The PathSpec class is a wrapper around a list of compiled Pattern instances.

__init__(patterns: Sequence[TPattern_co] | Iterable[TPattern_co], *, backend: Literal['best', 'hyperscan', 're2', 'simple'] | str | None = None, _test_backend_factory: Callable[[Sequence[Pattern]], _Backend] | None = None) None[source]

Initializes the PathSpec instance.

patterns (Sequence or Iterable) contains each compiled pattern (Pattern). If not a sequence, it will be converted to a list.

backend (str or None) is the pattern (regular expression) matching backend to use. Default is None for “best” to use the best available backend. Priority of backends is: “re2”, “hyperscan”, “simple”. The “simple” backend is always available.

patterns: Sequence[TPattern_co]

patterns (Sequence of Pattern) contains the compiled patterns.

__eq__(other: object) bool[source]

Tests the equality of this path-spec with other (PathSpec) by comparing their self.patterns attributes.

__len__() int[source]

Returns the number of self.patterns this path-spec contains (int).

check_file(file: TStrPath, separators: Collection[str] | None = None) CheckResult[TStrPath][source]

Check the files against this path-spec.

file (str or os.PathLike) is the file path to be matched against self.patterns.

separators (Collection of str; or None) optionally contains the path separators to normalize. See normalize_file() for more information.

Returns the file check result (CheckResult).

check_files(files: Iterable[TStrPath], separators: Collection[str] | None = None) Iterator[CheckResult[TStrPath]][source]

Check the files against this path-spec.

files (Iterable of str or os.PathLike) contains the file paths to be checked against self.patterns.

separators (Collection of str; or None) optionally contains the path separators to normalize. See normalize_file() for more information.

Returns an Iterator yielding each file check result (CheckResult).

check_tree_files(root: str | PathLike[str], on_error: Callable[[OSError], None] | None = None, follow_links: bool | None = None) Iterator[CheckResult[str]][source]

Walks the specified root path for all files and checks them against this path-spec.

root (str or os.PathLike) is the root directory to search for files.

on_error (Callable or None) optionally is the error handler for file-system exceptions. It will be called with the exception (OSError). Reraise the exception to abort the walk. Default is None to ignore file-system exceptions.

follow_links (bool or None) optionally is whether to walk symbolic links that resolve to directories. Default is None for True.

negate (bool or None) is whether to negate the match results of the patterns. If True, a pattern matching a file will exclude the file rather than include it. Default is None for False.

Returns an Iterator yielding each file check result (CheckResult).

classmethod from_lines(pattern_factory: Literal['gitignore'], lines: Iterable, *, backend: Literal['best', 'hyperscan', 're2', 'simple'] | str | None = None, _test_backend_factory: Callable[[Sequence[Pattern]], _Backend] | None = None) PathSpec[GitIgnoreBasicPattern][source]
classmethod from_lines(pattern_factory: str, lines: Iterable, *, backend: Literal['best', 'hyperscan', 're2', 'simple'] | str | None = None, _test_backend_factory: Callable[[Sequence[Pattern]], _Backend] | None = None) PathSpec[Pattern]
classmethod from_lines(pattern_factory: type[TPattern], lines: Iterable, *, backend: Literal['best', 'hyperscan', 're2', 'simple'] | str | None = None, _test_backend_factory: Callable[[Sequence[Pattern]], _Backend] | None = None) PathSpec[TPattern]
classmethod from_lines(pattern_factory: Callable[[AnyStr], TPattern], lines: Iterable, *, backend: Literal['best', 'hyperscan', 're2', 'simple'] | str | None = None, _test_backend_factory: Callable[[Sequence[Pattern]], _Backend] | None = None) PathSpec[TPattern]

Compiles the pattern lines.

pattern_factory can be either the name of a registered pattern factory (str), or a Callable used to compile patterns. It must accept an uncompiled pattern (str) and return the compiled pattern (Pattern).

lines (Iterable) yields each uncompiled pattern (str). This simply has to yield each line so that it can be a io.TextIOBase (e.g., from open() or io.StringIO) or the result from str.splitlines().

backend (str or None) is the pattern (or regular expression) matching backend to use. Default is None for “best” to use the best available backend. Priority of backends is: “re2”, “hyperscan”, “simple”. The “simple” backend is always available.

Returns the PathSpec instance.

match_entries(entries: Iterable[TreeEntry], separators: Collection[str] | None = None, *, negate: bool | None = None) Iterator[TreeEntry][source]

Matches the entries to this path-spec.

entries (Iterable of TreeEntry) contains the entries to be matched against self.patterns.

separators (Collection of str; or None) optionally contains the path separators to normalize. See normalize_file() for more information.

negate (bool or None) is whether to negate the match results of the patterns. If True, a pattern matching a file will exclude the file rather than include it. Default is None for False.

Returns the matched entries (Iterator of TreeEntry).

match_file(file: str | PathLike[str], separators: Collection[str] | None = None) bool[source]

Matches the file to this path-spec.

file (str or os.PathLike) is the file path to be matched against self.patterns.

separators (Collection of str) optionally contains the path separators to normalize. See normalize_file() for more information.

Returns True if file matched; otherwise, False.

match_files(files: Iterable[TStrPath], separators: Collection[str] | None = None, *, negate: bool | None = None) Iterator[TStrPath][source]

Matches the files to this path-spec.

files (Iterable of str or os.PathLike) contains the file paths to be matched against self.patterns.

separators (Collection of str; or None) optionally contains the path separators to normalize. See normalize_file() for more information.

negate (bool or None) is whether to negate the match results of the patterns. If True, a pattern matching a file will exclude the file rather than include it. Default is None for False.

Returns the matched files (Iterator of str or os.PathLike).

match_tree_entries(root: str | PathLike[str], on_error: Callable[[OSError], None] | None = None, follow_links: bool | None = None, *, negate: bool | None = None) Iterator[TreeEntry][source]

Walks the specified root path for all files and matches them to this path-spec.

root (str or os.PathLike) is the root directory to search.

on_error (Callable or None) optionally is the error handler for file-system exceptions. It will be called with the exception (OSError). Reraise the exception to abort the walk. Default is None to ignore file-system exceptions.

follow_links (bool or None) optionally is whether to walk symbolic links that resolve to directories. Default is None for True.

negate (bool or None) is whether to negate the match results of the patterns. If True, a pattern matching a file will exclude the file rather than include it. Default is None for False.

Returns the matched files (Iterator of TreeEntry).

match_tree(*args, **kw) Iterator[str][source]

Deprecated since version 0.3.2: This is an alias for the self.match_tree_files method.

match_tree_files(root: str | PathLike[str], on_error: Callable[[OSError], None] | None = None, follow_links: bool | None = None, *, negate: bool | None = None) Iterator[str][source]

Walks the specified root path for all files and matches them to this path-spec.

root (str or os.PathLike) is the root directory to search for files.

on_error (Callable or None) optionally is the error handler for file-system exceptions. It will be called with the exception (OSError). Reraise the exception to abort the walk. Default is None to ignore file-system exceptions.

follow_links (bool or None) optionally is whether to walk symbolic links that resolve to directories. Default is None for True.

negate (bool or None) is whether to negate the match results of the patterns. If True, a pattern matching a file will exclude the file rather than include it. Default is None for False.

Returns the matched files (Iterable of str).

class pathspec.pathspec.Self

PathSpec self type hint to support Python v<3.11 using PEP 673 recommendation.

alias of TypeVar(‘Self’, bound=PathSpec)

pathspec.gitignore

This module provides GitIgnoreSpec which replicates .gitignore behavior, and handles edge-cases where Git’s behavior differs from what’s documented. Git allows including files from excluded directories which directly contradicts the documentation. This uses GitIgnoreSpecPattern to fully replicate Git’s handling.

class pathspec.gitignore.GitIgnoreSpec(patterns: Sequence[TPattern_co] | Iterable[TPattern_co], *, backend: Literal['best', 'hyperscan', 're2', 'simple'] | str | None = None, _test_backend_factory: Callable[[Sequence[Pattern]], _Backend] | None = None)[source]

Bases: PathSpec[GitIgnoreSpecPattern]

The GitIgnoreSpec class extends PathSpec to replicate gitignore behavior. This is uses GitIgnoreSpecPattern to fully replicate Git’s handling.

__eq__(other: object) bool[source]

Tests the equality of this gitignore-spec with other (GitIgnoreSpec) by comparing their self.patterns attributes. A non-GitIgnoreSpec will not compare equal.

__init__(patterns: Sequence[TPattern_co] | Iterable[TPattern_co], *, backend: Literal['best', 'hyperscan', 're2', 'simple'] | str | None = None, _test_backend_factory: Callable[[Sequence[Pattern]], _Backend] | None = None) None

Initializes the PathSpec instance.

patterns (Sequence or Iterable) contains each compiled pattern (Pattern). If not a sequence, it will be converted to a list.

backend (str or None) is the pattern (regular expression) matching backend to use. Default is None for “best” to use the best available backend. Priority of backends is: “re2”, “hyperscan”, “simple”. The “simple” backend is always available.

__len__() int

Returns the number of self.patterns this path-spec contains (int).

check_file(file: TStrPath, separators: Collection[str] | None = None) CheckResult[TStrPath]

Check the files against this path-spec.

file (str or os.PathLike) is the file path to be matched against self.patterns.

separators (Collection of str; or None) optionally contains the path separators to normalize. See normalize_file() for more information.

Returns the file check result (CheckResult).

check_files(files: Iterable[TStrPath], separators: Collection[str] | None = None) Iterator[CheckResult[TStrPath]]

Check the files against this path-spec.

files (Iterable of str or os.PathLike) contains the file paths to be checked against self.patterns.

separators (Collection of str; or None) optionally contains the path separators to normalize. See normalize_file() for more information.

Returns an Iterator yielding each file check result (CheckResult).

check_tree_files(root: str | PathLike[str], on_error: Callable[[OSError], None] | None = None, follow_links: bool | None = None) Iterator[CheckResult[str]]

Walks the specified root path for all files and checks them against this path-spec.

root (str or os.PathLike) is the root directory to search for files.

on_error (Callable or None) optionally is the error handler for file-system exceptions. It will be called with the exception (OSError). Reraise the exception to abort the walk. Default is None to ignore file-system exceptions.

follow_links (bool or None) optionally is whether to walk symbolic links that resolve to directories. Default is None for True.

negate (bool or None) is whether to negate the match results of the patterns. If True, a pattern matching a file will exclude the file rather than include it. Default is None for False.

Returns an Iterator yielding each file check result (CheckResult).

match_entries(entries: Iterable[TreeEntry], separators: Collection[str] | None = None, *, negate: bool | None = None) Iterator[TreeEntry]

Matches the entries to this path-spec.

entries (Iterable of TreeEntry) contains the entries to be matched against self.patterns.

separators (Collection of str; or None) optionally contains the path separators to normalize. See normalize_file() for more information.

negate (bool or None) is whether to negate the match results of the patterns. If True, a pattern matching a file will exclude the file rather than include it. Default is None for False.

Returns the matched entries (Iterator of TreeEntry).

match_file(file: str | PathLike[str], separators: Collection[str] | None = None) bool

Matches the file to this path-spec.

file (str or os.PathLike) is the file path to be matched against self.patterns.

separators (Collection of str) optionally contains the path separators to normalize. See normalize_file() for more information.

Returns True if file matched; otherwise, False.

match_files(files: Iterable[TStrPath], separators: Collection[str] | None = None, *, negate: bool | None = None) Iterator[TStrPath]

Matches the files to this path-spec.

files (Iterable of str or os.PathLike) contains the file paths to be matched against self.patterns.

separators (Collection of str; or None) optionally contains the path separators to normalize. See normalize_file() for more information.

negate (bool or None) is whether to negate the match results of the patterns. If True, a pattern matching a file will exclude the file rather than include it. Default is None for False.

Returns the matched files (Iterator of str or os.PathLike).

match_tree(*args, **kw) Iterator[str]

Deprecated since version 0.3.2: This is an alias for the self.match_tree_files method.

match_tree_entries(root: str | PathLike[str], on_error: Callable[[OSError], None] | None = None, follow_links: bool | None = None, *, negate: bool | None = None) Iterator[TreeEntry]

Walks the specified root path for all files and matches them to this path-spec.

root (str or os.PathLike) is the root directory to search.

on_error (Callable or None) optionally is the error handler for file-system exceptions. It will be called with the exception (OSError). Reraise the exception to abort the walk. Default is None to ignore file-system exceptions.

follow_links (bool or None) optionally is whether to walk symbolic links that resolve to directories. Default is None for True.

negate (bool or None) is whether to negate the match results of the patterns. If True, a pattern matching a file will exclude the file rather than include it. Default is None for False.

Returns the matched files (Iterator of TreeEntry).

match_tree_files(root: str | PathLike[str], on_error: Callable[[OSError], None] | None = None, follow_links: bool | None = None, *, negate: bool | None = None) Iterator[str]

Walks the specified root path for all files and matches them to this path-spec.

root (str or os.PathLike) is the root directory to search for files.

on_error (Callable or None) optionally is the error handler for file-system exceptions. It will be called with the exception (OSError). Reraise the exception to abort the walk. Default is None to ignore file-system exceptions.

follow_links (bool or None) optionally is whether to walk symbolic links that resolve to directories. Default is None for True.

negate (bool or None) is whether to negate the match results of the patterns. If True, a pattern matching a file will exclude the file rather than include it. Default is None for False.

Returns the matched files (Iterable of str).

patterns: Sequence[TPattern_co]

patterns (Sequence of Pattern) contains the compiled patterns.

classmethod from_lines(pattern_factory: str | type[Pattern] | Callable[[AnyStr], Pattern] | None, lines: Iterable, *, backend: Literal['best', 'hyperscan', 're2', 'simple'] | str | None = None, _test_backend_factory: Callable[[Sequence[Pattern]], _Backend] | None = None) Self[source]
classmethod from_lines(lines: Iterable, pattern_factory: str | type[Pattern] | Callable[[AnyStr], Pattern] | None = None, *, backend: Literal['best', 'hyperscan', 're2', 'simple'] | str | None = None, _test_backend_factory: Callable[[Sequence[Pattern]], _Backend] | None = None) Self

Compiles the pattern lines.

lines (Iterable) yields each uncompiled pattern (str). This simply has to yield each line, so it can be a io.TextIOBase (e.g., from open() or io.StringIO) or the result from str.splitlines().

pattern_factory does not need to be set for GitIgnoreSpec. If set, it should be either "gitignore" or GitIgnoreSpecPattern. There is no guarantee it will work with any other pattern class. Default is None for GitIgnoreSpecPattern.

backend (str or None) is the pattern (regular expression) matching backend to use. Default is None for “best” to use the best available backend. Priority of backends is: “re2”, “hyperscan”, “simple”. The “simple” backend is always available.

Returns the GitIgnoreSpec instance.

class pathspec.gitignore.Self

GitIgnoreSpec self type hint to support Python v<3.11 using PEP 673 recommendation.

alias of TypeVar(‘Self’, bound=GitIgnoreSpec)

pathspec.backend

This module defines the necessary classes and type hints for exposing the bare minimum of the internal implementations for the pattern (regular expression) matching backends. The exact structure of the backends is not solidified and is subject to change.

class pathspec.backend._Backend[source]

Bases: object

Warning

This class is not part of the public API. It is subject to change.

The _Backend class is the abstract base class defining how to match files against patterns.

pathspec.backend.BackendNamesHint

The supported backend values.

alias of Literal[‘best’, ‘hyperscan’, ‘re2’, ‘simple’]

pathspec.pattern

This module provides the base definition for patterns.

class pathspec.pattern.Pattern(include: bool | None)[source]

Bases: object

The Pattern class is the abstract definition of a pattern.

__init__(include: bool | None) None[source]

Initializes the Pattern instance.

include (bool or None) is whether the matched files should be included (True), excluded (False), or is a null-operation (None).

include

include (bool or None) is whether the matched files should be included (True), excluded (False), or is a null-operation (None).

match(files: Iterable[str]) Iterator[str][source]

Deprecated since version 0.10.0: This method is no longer used. Use the self.match_file method with a loop for similar results.

Matches this pattern against the specified files.

files (Iterable of str) contains each file relative to the root directory.

Returns an Iterable yielding each matched file path (str).

match_file(file: str) Any | None[source]

Matches this pattern against the specified file.

file (str) is the normalized file path to match against.

Returns the match result if file matched; otherwise, None.

class pathspec.pattern.RegexPattern(pattern: AnyStr | Pattern | None, include: bool | None = None)[source]

Bases: Pattern

The RegexPattern class is an implementation of a pattern using regular expressions.

__init__(pattern: AnyStr | Pattern | None, include: bool | None = None) None[source]

Initializes the RegexPattern instance.

pattern (str, bytes, re.Pattern, or None) is the pattern to compile into a regular expression.

include (bool or None) must be None unless pattern is a precompiled regular expression (re.Pattern) in which case it is whether matched files should be included (True), excluded (False), or is a null operation (None).

Note

Subclasses do not need to support the include parameter.

pattern: str | bytes | Pattern | None

pattern (str, bytes, re.Pattern, or None) is the uncompiled, input pattern. This is for reference.

regex: Pattern | None

regex (re.Pattern or None) is the compiled regular expression for the pattern.

__eq__(other: object) bool[source]

Tests the equality of this regex pattern with other (RegexPattern) by comparing their include and regex attributes.

match_file(file: AnyStr) RegexMatchResult | None[source]

Matches this pattern against the specified file.

file (str or bytes) is the file path relative to the root directory (e.g., “relative/path/to/file”).

Returns the match result (RegexMatchResult) if file matched; otherwise, None.

classmethod pattern_to_regex(pattern: AnyStr) tuple[AnyStr | None, bool | None][source]

Convert the pattern into an uncompiled regular expression.

pattern (str or bytes) is the pattern to convert into a regular expression.

Returns a tuple containing:

  • pattern (str, bytes or None) is the uncompiled regular expression .

  • include (bool or None) is whether matched files should be included (True), excluded (False), or is a null-operation (None).

Note

The default implementation simply returns pattern and True.

class pathspec.pattern.RegexMatchResult(match: Match)[source]

Bases: object

The RegexMatchResult data class is used to return information about the matched regular expression.

__init__(match: Match) None
match: Match

match (re.Match) is the regex match result.

pathspec.patterns.gitignore

The pathspec.patterns.gitignore package provides the gitignore implementations.

The following classes are imported and made available from this package:

pathspec.patterns.gitignore.base

This module provides common classes for the gitignore patterns.

class pathspec.patterns.gitignore.base._GitIgnoreBasePattern(pattern: AnyStr | Pattern | None, include: bool | None = None)[source]

Bases: RegexPattern

Warning

This class is not part of the public API. It is subject to change.

The _GitIgnoreBasePattern class is the base implementation for a compiled gitignore pattern.

class pathspec.patterns.gitignore.base.GitIgnorePatternError[source]

Bases: ValueError

The GitIgnorePatternError class indicates an invalid gitignore pattern.

pathspec.patterns.gitignore.basic

This module provides GitIgnoreBasicPattern which implements Git’s gitignore patterns as documented. This differs from how Git actually behaves when including files in excluded directories.

class pathspec.patterns.gitignore.basic.GitIgnoreBasicPattern(pattern: AnyStr | Pattern | None, include: bool | None = None)[source]

Bases: _GitIgnoreBasePattern

The GitIgnoreBasicPattern class represents a compiled gitignore pattern as documented. This is registered as “gitignore”.

classmethod pattern_to_regex(pattern: AnyStr) tuple[AnyStr | None, bool | None][source]

Convert the pattern into a regular expression.

pattern (str or bytes) is the pattern to convert into a regular expression.

Returns a tuple containing:

  • pattern (str, bytes or None) is the uncompiled regular expression.

  • include (bool or None) is whether matched files should be included (True), excluded (False), or is a null-operation (None).

static escape(s: AnyStr) AnyStr

Escape special characters in the given string.

s (str or bytes) a filename or a string that you want to escape, usually before adding it to a “.gitignore”.

Returns the escaped string (str or bytes).

include

include (bool or None) is whether the matched files should be included (True), excluded (False), or is a null-operation (None).

match(files: Iterable[str]) Iterator[str]

Deprecated since version 0.10.0: This method is no longer used. Use the self.match_file method with a loop for similar results.

Matches this pattern against the specified files.

files (Iterable of str) contains each file relative to the root directory.

Returns an Iterable yielding each matched file path (str).

match_file(file: AnyStr) RegexMatchResult | None

Matches this pattern against the specified file.

file (str or bytes) is the file path relative to the root directory (e.g., “relative/path/to/file”).

Returns the match result (RegexMatchResult) if file matched; otherwise, None.

pattern: str | bytes | Pattern | None

pattern (str, bytes, re.Pattern, or None) is the uncompiled, input pattern. This is for reference.

regex: Pattern | None

regex (re.Pattern or None) is the compiled regular expression for the pattern.

pathspec.patterns.gitignore.spec

This module provides GitIgnoreSpecPattern which implements Git’s gitignore patterns, and handles edge-cases where Git’s behavior differs from what’s documented. Git allows including files from excluded directories which appears to contradict the documentation. Git discards patterns with invalid range notation. This is used by GitIgnoreSpec to fully replicate Git’s handling.

class pathspec.patterns.gitignore.spec.GitIgnoreSpecPattern(pattern: AnyStr | Pattern | None, include: bool | None = None)[source]

Bases: _GitIgnoreBasePattern

The GitIgnoreSpecPattern class represents a compiled gitignore pattern with special handling for edge-cases to replicate Git’s behavior.

This is registered under the deprecated name “gitwildmatch” for backward compatibility with v0.12. The registered name will be removed in a future version.

static escape(s: AnyStr) AnyStr

Escape special characters in the given string.

s (str or bytes) a filename or a string that you want to escape, usually before adding it to a “.gitignore”.

Returns the escaped string (str or bytes).

include

include (bool or None) is whether the matched files should be included (True), excluded (False), or is a null-operation (None).

match(files: Iterable[str]) Iterator[str]

Deprecated since version 0.10.0: This method is no longer used. Use the self.match_file method with a loop for similar results.

Matches this pattern against the specified files.

files (Iterable of str) contains each file relative to the root directory.

Returns an Iterable yielding each matched file path (str).

match_file(file: AnyStr) RegexMatchResult | None

Matches this pattern against the specified file.

file (str or bytes) is the file path relative to the root directory (e.g., “relative/path/to/file”).

Returns the match result (RegexMatchResult) if file matched; otherwise, None.

pattern: str | bytes | Pattern | None

pattern (str, bytes, re.Pattern, or None) is the uncompiled, input pattern. This is for reference.

regex: Pattern | None

regex (re.Pattern or None) is the compiled regular expression for the pattern.

classmethod pattern_to_regex(pattern: AnyStr) tuple[AnyStr | None, bool | None][source]

Convert the pattern into a regular expression.

pattern (str or bytes) is the pattern to convert into a regular expression.

Returns a tuple containing:

  • pattern (str, bytes or None) is the uncompiled regular expression.

  • include (bool or None) is whether matched files should be included (True), excluded (False), or is a null-operation (None).

pathspec.util

This module provides utility methods for dealing with path-specs.

class pathspec.util.TPattern

Type variable for Pattern. This is used by pathspec.pathspec.PathSpec to specialize the type of patterns.

alias of TypeVar(‘TPattern’, bound=Pattern)

class pathspec.util.TPattern_co

Type variable for Pattern that is covariant. This is used by pathspec.pathspec.PathSpec to specialize the type of patterns.

alias of TypeVar(‘TPattern_co’, bound=Pattern, covariant=True)

class pathspec.util.TStrPath

Type variable for str or os.PathLike.

alias of TypeVar(‘TStrPath’, bound=str | PathLike[str])

pathspec.util.NORMALIZE_PATH_SEPS = []

NORMALIZE_PATH_SEPS (list of str) contains the path separators that need to be normalized to the POSIX separator for the current operating system. The separators are determined by examining os.sep and os.altsep.

pathspec.util.append_dir_sep(path: Path) str[source]

Appends the path separator to the path if the path is a directory. This can be used to aid in distinguishing between directories and files on the file-system by relying on the presence of a trailing path separator.

path (pathlib.Path) is the path to use.

Returns the path (str).

pathspec.util.check_match_file(patterns: Iterable[tuple[int, Pattern]], file: str, is_reversed: bool | None = None) tuple[bool | None, int | None][source]

Check the file against the patterns.

patterns (Iterable) yields each indexed pattern (tuple) which contains the pattern index (int) and actua pattern (Pattern).

file (str) is the normalized file path to be matched against patterns.

is_reversed (bool or None) is whether the order of the patterns has been reversed. Default is None for False. Reversing the order of the patterns is an optimization.

Returns a tuple containing whether to include file (bool or None), and the index of the last matched pattern (int or None).

pathspec.util.detailed_match_files(patterns: Iterable[Pattern], files: Iterable[str], all_matches: bool | None = None) dict[str, MatchDetail][source]

Matches the files to the patterns, and returns which patterns matched the files.

patterns (Iterable of Pattern) contains the patterns to use.

files (Iterable of str) contains the normalized file paths to be matched against patterns.

all_matches (bool or None) is whether to return all matches patterns (True), or only the last matched pattern (False). Default is None for False.

Returns the matched files (dict) which maps each matched file (str) to the patterns that matched in order (MatchDetail).

pathspec.util.iter_tree(root, on_error=None, follow_links=None)[source]

Deprecated since version 0.10.0: This is an alias for the iter_tree_files() function.

pathspec.util.iter_tree_entries(root: str | PathLike[str], on_error: Callable[[OSError], None] | None = None, follow_links: bool | None = None) Iterator[TreeEntry][source]

Walks the specified directory for all files and directories.

root (str or os.PathLike) is the root directory to search.

on_error (Callable or None) optionally is the error handler for file-system exceptions. It will be called with the exception (OSError). Reraise the exception to abort the walk. Default is None to ignore file-system exceptions.

follow_links (bool or None) optionally is whether to walk symbolic links that resolve to directories. Default is None for True.

Raises RecursionError if recursion is detected.

Returns an Iterator yielding each file or directory entry (TreeEntry) relative to root.

pathspec.util.iter_tree_files(root: str | PathLike[str], on_error: Callable[[OSError], None] | None = None, follow_links: bool | None = None) Iterator[str][source]

Walks the specified directory for all files.

root (str or os.PathLike) is the root directory to search for files.

on_error (Callable or None) optionally is the error handler for file-system exceptions. It will be called with the exception (OSError). Reraise the exception to abort the walk. Default is None to ignore file-system exceptions.

follow_links (bool or None) optionally is whether to walk symbolic links that resolve to directories. Default is None for True.

Raises RecursionError if recursion is detected.

Returns an Iterator yielding the path to each file (str) relative to root.

pathspec.util.lookup_pattern(name: str) Callable[[AnyStr], Pattern][source]

Looks up a registered pattern factory by name.

name (str) is the name of the pattern factory.

Returns the registered pattern factory (Callable). If no pattern factory is registered, raises KeyError.

pathspec.util.match_file(patterns: Iterable[Pattern], file: str) bool[source]

Matches the file to the patterns.

patterns (Iterable of Pattern) contains the patterns to use.

file (str) is the normalized file path to be matched against patterns.

Returns True if file matched; otherwise, False.

pathspec.util.match_files(patterns: Iterable[Pattern], files: Iterable[str]) set[str][source]

Deprecated since version 0.10.0: This function is no longer used. Use the match_file() function with a loop for better results.

Matches the files to the patterns.

patterns (Iterable of Pattern) contains the patterns to use.

files (Iterable of str) contains the normalized file paths to be matched against patterns.

Returns the matched files (set of str).

pathspec.util.normalize_file(file: str | PathLike[str], separators: Collection[str] | None = None) str[source]

Normalizes the file path to use the POSIX path separator (i.e., "/"), and make the paths relative (remove leading "/").

file (str or os.PathLike) is the file path.

separators (Collection of str; or None) optionally contains the path separators to normalize. This does not need to include the POSIX path separator ("/"), but including it will not affect the results. Default is None for NORMALIZE_PATH_SEPS. To prevent normalization, pass an empty container (e.g., an empty tuple ()).

Returns the normalized file path (str).

pathspec.util.normalize_files(files: Iterable[str | PathLike[str]], separators: Collection[str] | None = None) dict[str, list[str | PathLike[str]]][source]

Deprecated since version 0.10.0: This function is no longer used. Use the normalize_file() function with a loop for better results.

Normalizes the file paths to use the POSIX path separator.

files (Iterable of str or os.PathLike) contains the file paths to be normalized.

separators (Collection of str; or None) optionally contains the path separators to normalize. See normalize_file() for more information.

Returns a dict mapping each normalized file path (str) to the original file paths (list of str or os.PathLike).

pathspec.util.register_pattern(name: str, pattern_factory: Callable[[str | bytes], Pattern] | type[Pattern], override: bool | None = None) None[source]

Registers the specified pattern factory.

name (str) is the name to register the pattern factory under.

pattern_factory (Callable) is used to compile patterns. It must accept an uncompiled pattern (str) and return the compiled pattern (Pattern).

override (bool or None) optionally is whether to allow overriding an already registered pattern under the same name (True), instead of raising an AlreadyRegisteredError (False). Default is None for False.

exception pathspec.util.AlreadyRegisteredError(name: str, pattern_factory: Callable[[str | bytes], Pattern])[source]

Bases: Exception

The AlreadyRegisteredError exception is raised when a pattern factory is registered under a name already in use.

property message: str

message (str) is the error message.

property name: str

name (str) is the name of the registered pattern.

property pattern_factory: Callable[[str | bytes], Pattern]

pattern_factory (Callable) is the registered pattern factory.

exception pathspec.util.RecursionError(real_path: str, first_path: str, second_path: str)[source]

Bases: Exception

The RecursionError exception is raised when recursion is detected.

property first_path: str

first_path (str) is the first path encountered for self.real_path.

property message: str

message (str) is the error message.

property real_path: str

real_path (str) is the real path that recursion was encountered on.

property second_path: str

second_path (str) is the second path encountered for self.real_path.

class pathspec.util.CheckResult(file: TStrPath, include: bool | None, index: int | None)[source]

Bases: Generic[TStrPath]

The CheckResult class contains information about the file and which pattern matched it.

file: TStrPath

file (str or os.PathLike) is the file path.

include: bool | None

include (bool or None) is whether to include or exclude the file. If None, no pattern matched.

index: int | None

index (int or None) is the index of the last pattern that matched. If None, no pattern matched.

class pathspec.util.MatchDetail(patterns: Sequence[Pattern])[source]

Bases: object

The MatchDetail class contains information about

patterns

patterns (Sequence of Pattern) contains the patterns that matched the file in the order they were encountered.

class pathspec.util.TreeEntry(name: str, path: str, lstat: stat_result, stat: stat_result)[source]

Bases: object

The TreeEntry class contains information about a file-system entry.

name: str

name (str) is the base name of the entry.

path: str

path (str) is the path of the entry.

is_dir(follow_links: bool | None = None) bool[source]

Get whether the entry is a directory.

follow_links (bool or None) is whether to follow symbolic links. If this is True, a symlink to a directory will result in True. Default is None for True.

Returns whether the entry is a directory (bool).

is_file(follow_links: bool | None = None) bool[source]

Get whether the entry is a regular file.

follow_links (bool or None) is whether to follow symbolic links. If this is True, a symlink to a regular file will result in True. Default is None for True.

Returns whether the entry is a regular file (bool).

Returns whether the entry is a symbolic link (bool).

stat(follow_links: bool | None = None) stat_result[source]

Get the cached stat result for the entry.

follow_links (bool or None) is whether to follow symbolic links. If this is True, the stat result of the linked file will be returned. Default is None for True.

Returns that stat result (os.stat_result).