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
PathSpecclass is a wrapper around a list of compiledPatterninstances.- __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
PathSpecinstance.patterns (
SequenceorIterable) contains each compiled pattern (Pattern). If not a sequence, it will be converted to alist.backend (
strorNone) is the pattern (regular expression) matching backend to use. Default isNonefor “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 (
SequenceofPattern) contains the compiled patterns.
- __eq__(other: object) bool[source]¶
Tests the equality of this path-spec with other (
PathSpec) by comparing theirself.patternsattributes.
- __len__() int[source]¶
Returns the number of
self.patternsthis path-spec contains (int).
- check_file(file: TStrPath, separators: Collection[str] | None = None) CheckResult[TStrPath][source]¶
Check the files against this path-spec.
file (
stroros.PathLike) is the file path to be matched againstself.patterns.separators (
Collectionofstr; orNone) optionally contains the path separators to normalize. Seenormalize_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 (
Iterableofstroros.PathLike) contains the file paths to be checked againstself.patterns.separators (
Collectionofstr; orNone) optionally contains the path separators to normalize. Seenormalize_file()for more information.Returns an
Iteratoryielding 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 (
stroros.PathLike) is the root directory to search for files.on_error (
CallableorNone) 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 isNoneto ignore file-system exceptions.follow_links (
boolorNone) optionally is whether to walk symbolic links that resolve to directories. Default isNoneforTrue.negate (
boolorNone) is whether to negate the match results of the patterns. IfTrue, a pattern matching a file will exclude the file rather than include it. Default isNoneforFalse.Returns an
Iteratoryielding 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 aCallableused 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 aio.TextIOBase(e.g., fromopen()orio.StringIO) or the result fromstr.splitlines().backend (
strorNone) is the pattern (or regular expression) matching backend to use. Default isNonefor “best” to use the best available backend. Priority of backends is: “re2”, “hyperscan”, “simple”. The “simple” backend is always available.Returns the
PathSpecinstance.
- 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 (
IterableofTreeEntry) contains the entries to be matched againstself.patterns.separators (
Collectionofstr; orNone) optionally contains the path separators to normalize. Seenormalize_file()for more information.negate (
boolorNone) is whether to negate the match results of the patterns. IfTrue, a pattern matching a file will exclude the file rather than include it. Default isNoneforFalse.
- match_file(file: str | PathLike[str], separators: Collection[str] | None = None) bool[source]¶
Matches the file to this path-spec.
file (
stroros.PathLike) is the file path to be matched againstself.patterns.separators (
Collectionofstr) optionally contains the path separators to normalize. Seenormalize_file()for more information.
- 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 (
Iterableofstroros.PathLike) contains the file paths to be matched againstself.patterns.separators (
Collectionofstr; orNone) optionally contains the path separators to normalize. Seenormalize_file()for more information.negate (
boolorNone) is whether to negate the match results of the patterns. IfTrue, a pattern matching a file will exclude the file rather than include it. Default isNoneforFalse.Returns the matched files (
Iteratorofstroros.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 (
stroros.PathLike) is the root directory to search.on_error (
CallableorNone) 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 isNoneto ignore file-system exceptions.follow_links (
boolorNone) optionally is whether to walk symbolic links that resolve to directories. Default isNoneforTrue.negate (
boolorNone) is whether to negate the match results of the patterns. IfTrue, a pattern matching a file will exclude the file rather than include it. Default isNoneforFalse.
- match_tree(*args, **kw) Iterator[str][source]¶
Deprecated since version 0.3.2: This is an alias for the
self.match_tree_filesmethod.
- 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 (
stroros.PathLike) is the root directory to search for files.on_error (
CallableorNone) 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 isNoneto ignore file-system exceptions.follow_links (
boolorNone) optionally is whether to walk symbolic links that resolve to directories. Default isNoneforTrue.negate (
boolorNone) is whether to negate the match results of the patterns. IfTrue, a pattern matching a file will exclude the file rather than include it. Default isNoneforFalse.
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
GitIgnoreSpecclass extendsPathSpecto replicate gitignore behavior. This is usesGitIgnoreSpecPatternto fully replicate Git’s handling.- __eq__(other: object) bool[source]¶
Tests the equality of this gitignore-spec with other (
GitIgnoreSpec) by comparing theirself.patternsattributes. A non-GitIgnoreSpecwill 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
PathSpecinstance.patterns (
SequenceorIterable) contains each compiled pattern (Pattern). If not a sequence, it will be converted to alist.backend (
strorNone) is the pattern (regular expression) matching backend to use. Default isNonefor “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.patternsthis path-spec contains (int).
- check_file(file: TStrPath, separators: Collection[str] | None = None) CheckResult[TStrPath]¶
Check the files against this path-spec.
file (
stroros.PathLike) is the file path to be matched againstself.patterns.separators (
Collectionofstr; orNone) optionally contains the path separators to normalize. Seenormalize_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 (
Iterableofstroros.PathLike) contains the file paths to be checked againstself.patterns.separators (
Collectionofstr; orNone) optionally contains the path separators to normalize. Seenormalize_file()for more information.Returns an
Iteratoryielding 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 (
stroros.PathLike) is the root directory to search for files.on_error (
CallableorNone) 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 isNoneto ignore file-system exceptions.follow_links (
boolorNone) optionally is whether to walk symbolic links that resolve to directories. Default isNoneforTrue.negate (
boolorNone) is whether to negate the match results of the patterns. IfTrue, a pattern matching a file will exclude the file rather than include it. Default isNoneforFalse.Returns an
Iteratoryielding 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 (
IterableofTreeEntry) contains the entries to be matched againstself.patterns.separators (
Collectionofstr; orNone) optionally contains the path separators to normalize. Seenormalize_file()for more information.negate (
boolorNone) is whether to negate the match results of the patterns. IfTrue, a pattern matching a file will exclude the file rather than include it. Default isNoneforFalse.
- match_file(file: str | PathLike[str], separators: Collection[str] | None = None) bool¶
Matches the file to this path-spec.
file (
stroros.PathLike) is the file path to be matched againstself.patterns.separators (
Collectionofstr) optionally contains the path separators to normalize. Seenormalize_file()for more information.
- match_files(files: Iterable[TStrPath], separators: Collection[str] | None = None, *, negate: bool | None = None) Iterator[TStrPath]¶
Matches the files to this path-spec.
files (
Iterableofstroros.PathLike) contains the file paths to be matched againstself.patterns.separators (
Collectionofstr; orNone) optionally contains the path separators to normalize. Seenormalize_file()for more information.negate (
boolorNone) is whether to negate the match results of the patterns. IfTrue, a pattern matching a file will exclude the file rather than include it. Default isNoneforFalse.Returns the matched files (
Iteratorofstroros.PathLike).
- match_tree(*args, **kw) Iterator[str]¶
Deprecated since version 0.3.2: This is an alias for the
self.match_tree_filesmethod.
- 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 (
stroros.PathLike) is the root directory to search.on_error (
CallableorNone) 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 isNoneto ignore file-system exceptions.follow_links (
boolorNone) optionally is whether to walk symbolic links that resolve to directories. Default isNoneforTrue.negate (
boolorNone) is whether to negate the match results of the patterns. IfTrue, a pattern matching a file will exclude the file rather than include it. Default isNoneforFalse.
- 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 (
stroros.PathLike) is the root directory to search for files.on_error (
CallableorNone) 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 isNoneto ignore file-system exceptions.follow_links (
boolorNone) optionally is whether to walk symbolic links that resolve to directories. Default isNoneforTrue.negate (
boolorNone) is whether to negate the match results of the patterns. IfTrue, a pattern matching a file will exclude the file rather than include it. Default isNoneforFalse.
- patterns: Sequence[TPattern_co]¶
patterns (
SequenceofPattern) 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 aio.TextIOBase(e.g., fromopen()orio.StringIO) or the result fromstr.splitlines().pattern_factory does not need to be set for
GitIgnoreSpec. If set, it should be either"gitignore"orGitIgnoreSpecPattern. There is no guarantee it will work with any other pattern class. Default isNoneforGitIgnoreSpecPattern.backend (
strorNone) is the pattern (regular expression) matching backend to use. Default isNonefor “best” to use the best available backend. Priority of backends is: “re2”, “hyperscan”, “simple”. The “simple” backend is always available.Returns the
GitIgnoreSpecinstance.
- class pathspec.gitignore.Self¶
GitIgnoreSpecself 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.
pathspec.pattern¶
This module provides the base definition for patterns.
- class pathspec.pattern.Pattern(include: bool | None)[source]¶
Bases:
objectThe
Patternclass is the abstract definition of a pattern.- __init__(include: bool | None) None[source]¶
Initializes the
Patterninstance.include (
boolorNone) is whether the matched files should be included (True), excluded (False), or is a null-operation (None).
- include¶
include (
boolorNone) 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_filemethod with a loop for similar results.Matches this pattern against the specified files.
files (
Iterableofstr) contains each file relative to the root directory.
- class pathspec.pattern.RegexPattern(pattern: AnyStr | Pattern | None, include: bool | None = None)[source]¶
Bases:
PatternThe
RegexPatternclass is an implementation of a pattern using regular expressions.- __init__(pattern: AnyStr | Pattern | None, include: bool | None = None) None[source]¶
Initializes the
RegexPatterninstance.pattern (
str,bytes,re.Pattern, orNone) is the pattern to compile into a regular expression.include (
boolorNone) must beNoneunless 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, orNone) is the uncompiled, input pattern. This is for reference.
- regex: Pattern | None¶
regex (
re.PatternorNone) 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 theirincludeandregexattributes.
- match_file(file: AnyStr) RegexMatchResult | None[source]¶
Matches this pattern against the specified file.
file (
strorbytes) 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.
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:
RegexPatternWarning
This class is not part of the public API. It is subject to change.
The
_GitIgnoreBasePatternclass is the base implementation for a compiled gitignore pattern.
- class pathspec.patterns.gitignore.base.GitIgnorePatternError[source]¶
Bases:
ValueErrorThe
GitIgnorePatternErrorclass 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:
_GitIgnoreBasePatternThe
GitIgnoreBasicPatternclass 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 (
strorbytes) is the pattern to convert into a regular expression.Returns a
tuplecontaining:
- static escape(s: AnyStr) AnyStr¶
Escape special characters in the given string.
s (
strorbytes) a filename or a string that you want to escape, usually before adding it to a “.gitignore”.
- include¶
include (
boolorNone) 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_filemethod with a loop for similar results.Matches this pattern against the specified files.
files (
Iterableofstr) contains each file relative to the root directory.
- match_file(file: AnyStr) RegexMatchResult | None¶
Matches this pattern against the specified file.
file (
strorbytes) 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, orNone) is the uncompiled, input pattern. This is for reference.
- regex: Pattern | None¶
regex (
re.PatternorNone) 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:
_GitIgnoreBasePatternThe
GitIgnoreSpecPatternclass 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 (
strorbytes) a filename or a string that you want to escape, usually before adding it to a “.gitignore”.
- include¶
include (
boolorNone) 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_filemethod with a loop for similar results.Matches this pattern against the specified files.
files (
Iterableofstr) contains each file relative to the root directory.
- match_file(file: AnyStr) RegexMatchResult | None¶
Matches this pattern against the specified file.
file (
strorbytes) 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, orNone) is the uncompiled, input pattern. This is for reference.
- regex: Pattern | None¶
regex (
re.PatternorNone) is the compiled regular expression for the pattern.
pathspec.util¶
This module provides utility methods for dealing with path-specs.
- class pathspec.util.TPattern¶
Type variable for
Pattern. This is used bypathspec.pathspec.PathSpecto specialize the type of patterns.alias of TypeVar(‘TPattern’, bound=
Pattern)
- class pathspec.util.TPattern_co¶
Type variable for
Patternthat is covariant. This is used bypathspec.pathspec.PathSpecto specialize the type of patterns.alias of TypeVar(‘TPattern_co’, bound=
Pattern, covariant=True)
- class pathspec.util.TStrPath¶
Type variable for
stroros.PathLike.
- pathspec.util.NORMALIZE_PATH_SEPS = []¶
NORMALIZE_PATH_SEPS (
listofstr) contains the path separators that need to be normalized to the POSIX separator for the current operating system. The separators are determined by examiningos.sepandos.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 (
boolorNone) is whether the order of the patterns has been reversed. Default isNoneforFalse. Reversing the order of the patterns is an optimization.Returns a
tuplecontaining whether to include file (boolorNone), and the index of the last matched pattern (intorNone).
- 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 (
IterableofPattern) contains the patterns to use.files (
Iterableofstr) contains the normalized file paths to be matched against patterns.all_matches (
boolorNone) is whether to return all matches patterns (True), or only the last matched pattern (False). Default isNoneforFalse.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 (
stroros.PathLike) is the root directory to search.on_error (
CallableorNone) 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 isNoneto ignore file-system exceptions.follow_links (
boolorNone) optionally is whether to walk symbolic links that resolve to directories. Default isNoneforTrue.Raises
RecursionErrorif recursion is detected.Returns an
Iteratoryielding 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 (
stroros.PathLike) is the root directory to search for files.on_error (
CallableorNone) 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 isNoneto ignore file-system exceptions.follow_links (
boolorNone) optionally is whether to walk symbolic links that resolve to directories. Default isNoneforTrue.Raises
RecursionErrorif recursion is detected.Returns an
Iteratoryielding 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, raisesKeyError.
- pathspec.util.match_file(patterns: Iterable[Pattern], file: str) bool[source]¶
Matches the file to the patterns.
patterns (
IterableofPattern) contains the patterns to use.file (
str) is the normalized file path to be matched against patterns.
- 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 (
IterableofPattern) contains the patterns to use.files (
Iterableofstr) contains the normalized file paths to be matched against patterns.
- 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 (
stroros.PathLike) is the file path.separators (
Collectionofstr; orNone) 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 isNoneforNORMALIZE_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 (
Iterableofstroros.PathLike) contains the file paths to be normalized.separators (
Collectionofstr; orNone) optionally contains the path separators to normalize. Seenormalize_file()for more information.Returns a
dictmapping each normalized file path (str) to the original file paths (listofstroros.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 (
boolorNone) optionally is whether to allow overriding an already registered pattern under the same name (True), instead of raising anAlreadyRegisteredError(False). Default isNoneforFalse.
- exception pathspec.util.AlreadyRegisteredError(name: str, pattern_factory: Callable[[str | bytes], Pattern])[source]¶
Bases:
ExceptionThe
AlreadyRegisteredErrorexception is raised when a pattern factory is registered under a name already in use.
- exception pathspec.util.RecursionError(real_path: str, first_path: str, second_path: str)[source]¶
Bases:
ExceptionThe
RecursionErrorexception is raised when recursion is detected.- property first_path: str¶
first_path (
str) is the first path encountered forself.real_path.
- property second_path: str¶
second_path (
str) is the second path encountered forself.real_path.
- class pathspec.util.CheckResult(file: TStrPath, include: bool | None, index: int | None)[source]¶
-
The
CheckResultclass contains information about the file and which pattern matched it.- file: TStrPath¶
file (
stroros.PathLike) is the file path.
- class pathspec.util.MatchDetail(patterns: Sequence[Pattern])[source]¶
Bases:
objectThe
MatchDetailclass contains information about
- class pathspec.util.TreeEntry(name: str, path: str, lstat: stat_result, stat: stat_result)[source]¶
Bases:
objectThe
TreeEntryclass contains information about a file-system entry.- is_dir(follow_links: bool | None = None) bool[source]¶
Get whether the entry is a directory.
follow_links (
boolorNone) is whether to follow symbolic links. If this isTrue, a symlink to a directory will result inTrue. Default isNoneforTrue.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 (
boolorNone) is whether to follow symbolic links. If this isTrue, a symlink to a regular file will result inTrue. Default isNoneforTrue.Returns whether the entry is a regular file (
bool).
- stat(follow_links: bool | None = None) stat_result[source]¶
Get the cached stat result for the entry.
follow_links (
boolorNone) is whether to follow symbolic links. If this isTrue, the stat result of the linked file will be returned. Default isNoneforTrue.Returns that stat result (
os.stat_result).