Debian Codegraph @

README-dist.rst

raw
1
2 PathSpec
3 ========
4
5 *pathspec* is a utility library for pattern matching of file paths. So far this
6 only includes Git's `gitignore`_ pattern matching.
7
8 .. _`gitignore`: http://git-scm.com/docs/gitignore
9
10
11 Tutorial
12 --------
13
14 Say you have a "Projects" directory and you want to back it up, but only
15 certain files, and ignore others depending on certain conditions::
16
17 >>> from pathspec import PathSpec
18 >>> # The gitignore-style patterns for files to select, but we're including
19 >>> # instead of ignoring.
20 >>> spec_text = """
21 ...
22 ... # This is a comment because the line begins with a hash: "#"
23 ...
24 ... # Include several project directories (and all descendants) relative to
25 ... # the current directory. To reference only a directory you must end with a
26 ... # slash: "/"
27 ... /project-a/
28 ... /project-b/
29 ... /project-c/
30 ...
31 ... # Patterns can be negated by prefixing with exclamation mark: "!"
32 ...
33 ... # Ignore temporary files beginning or ending with "~" and ending with
34 ... # ".swp".
35 ... !~*
36 ... !*~
37 ... !*.swp
38 ...
39 ... # These are python projects so ignore compiled python files from
40 ... # testing.
41 ... !*.pyc
42 ...
43 ... # Ignore the build directories but only directly under the project
44 ... # directories.
45 ... !/*/build/
46 ...
47 ... """
48
49 The ``PathSpec`` class provides an abstraction around pattern implementations,
50 and we want to compile our patterns as "gitignore" patterns. You could call it a
51 wrapper for a list of compiled patterns::
52
53 >>> spec = PathSpec.from_lines('gitignore', spec_text.splitlines())
54
55 If we wanted to manually compile the patterns, we can use the ``GitIgnoreBasicPattern``
56 class directly. It is used in the background for "gitignore" which internally
57 converts patterns to regular expressions::
58
59 >>> from pathspec.patterns.gitignore.basic import GitIgnoreBasicPattern
60 >>> patterns = map(GitIgnoreBasicPattern, spec_text.splitlines())
61 >>> spec = PathSpec(patterns)
62
63 ``PathSpec.from_lines()`` is a class method which simplifies that.
64
65 If you want to load the patterns from file, you can pass the file object
66 directly as well::
67
68 >>> with open('patterns.list', 'r') as fh:
69 >>> spec = PathSpec.from_lines('gitignore', fh)
70
71 You can perform matching on a whole directory tree with::
72
73 >>> matches = set(spec.match_tree_files('path/to/directory'))
74
75 Or you can perform matching on a specific set of file paths with::
76
77 >>> matches = set(spec.match_files(file_paths))
78
79 Or check to see if an individual file matches::
80
81 >>> is_matched = spec.match_file(file_path)
82
83 There's actually two implementations of "gitignore". The basic implementation is
84 used by ``PathSpec`` and follows patterns as documented by `gitignore`_.
85 However, Git's behavior differs from the documented patterns. There's some
86 edge-cases, and in particular, Git allows including files from excluded
87 directories which appears to contradict the documentation. ``GitIgnoreSpec``
88 handles these cases to more closely replicate Git's behavior::
89
90 >>> from pathspec import GitIgnoreSpec
91 >>> spec = GitIgnoreSpec.from_lines(spec_text.splitlines())
92
93 You do not specify the style of pattern for ``GitIgnoreSpec`` because it should
94 always use ``GitIgnoreSpecPattern`` internally.
95
96
97 Performance
98 -----------
99
100 Running lots of regular expression matches against thousands of files in Python
101 is slow. Alternate regular expression backends can be used to improve
102 performance. ``PathSpec`` and ``GitIgnoreSpec`` both accept a ``backend``
103 parameter to control the backend. The default is "best" to automatically choose
104 the best available backend. There are currently 3 backends.
105
106 The "simple" backend is the default and it simply uses Python's ``re.Pattern``
107 objects that are normally created. This can be the fastest when there's only 1
108 or 2 patterns.
109
110 The "hyperscan" backend uses the `hyperscan`_ library. Hyperscan tends to be at
111 least 2 times faster than "simple", and generally slower than "re2". This can be
112 faster than "re2" under the right conditions with pattern counts of 1-25.
113
114 The "re2" backend uses the `google-re2`_ library (not to be confused with the
115 *re2* library on PyPI which is unrelated and abandoned). Google's re2 tends to
116 be significantly faster than "simple", and 3 times faster than "hyperscan" at
117 high pattern counts.
118
119 See `benchmarks_backends.md`_ for comparisons between native Python regular
120 expressions and the optional backends.
121
122
123 .. _`benchmarks_backends.md`: https://github.com/cpburnz/python-pathspec/blob/master/benchmarks_backends.md
124 .. _`google-re2`: https://pypi.org/project/google-re2/
125 .. _`hyperscan`: https://pypi.org/project/hyperscan/
126
127
128 FAQ
129 ---
130
131
132 1. How do I ignore files like *.gitignore*?
133 +++++++++++++++++++++++++++++++++++++++++++
134
135 ``GitIgnoreSpec`` (and ``PathSpec``) positively match files by default. To find
136 the files to keep, and exclude files like *.gitignore*, you need to set
137 ``negate=True`` to flip the results::
138
139 >>> from pathspec import GitIgnoreSpec
140 >>> spec = GitIgnoreSpec.from_lines([...])
141 >>> keep_files = set(spec.match_tree_files('path/to/directory', negate=True))
142 >>> ignore_files = set(spec.match_tree_files('path/to/directory'))
143
144
145 License
146 -------
147
148 *pathspec* is licensed under the `Mozilla Public License Version 2.0`_. See
149 `LICENSE`_ or the `FAQ`_ for more information.
150
151 In summary, you may use *pathspec* with any closed or open source project
152 without affecting the license of the larger work so long as you:
153
154 - give credit where credit is due,
155
156 - and release any custom changes made to *pathspec*.
157
158 .. _`Mozilla Public License Version 2.0`: http://www.mozilla.org/MPL/2.0
159 .. _`LICENSE`: LICENSE
160 .. _`FAQ`: http://www.mozilla.org/MPL/2.0/FAQ.html
161
162
163 Source
164 ------
165
166 The source code for *pathspec* is available from the GitHub repo
167 `cpburnz/python-pathspec`_.
168
169 .. _`cpburnz/python-pathspec`: https://github.com/cpburnz/python-pathspec
170
171
172 Installation
173 ------------
174
175 *pathspec* is available for install through `PyPI`_::
176
177 pip install pathspec
178
179 *pathspec* can also be built from source. The following packages will be
180 required:
181
182 - `build`_ (>=0.6.0)
183
184 *pathspec* can then be built and installed with::
185
186 python -m build
187 pip install dist/pathspec-*-py3-none-any.whl
188
189 The following optional dependencies can be installed:
190
191 - `google-re2`_: Enables optional "re2" backend.
192 - `hyperscan`_: Enables optional "hyperscan" backend.
193 - `typing-extensions`_: Improves some type hints.
194
195 .. _`PyPI`: http://pypi.python.org/pypi/pathspec
196 .. _`build`: https://pypi.org/project/build/
197 .. _`typing-extensions`: https://pypi.org/project/typing-extensions/
198
199
200 Documentation
201 -------------
202
203 Documentation for *pathspec* is available on `Read the Docs`_.
204
205 The full change history can be found in `CHANGES.rst`_ and `Change History`_.
206
207 An upgrade guide is available in `UPGRADING.rst`_ and `Upgrade Guide`_.
208
209 .. _`CHANGES.rst`: https://github.com/cpburnz/python-pathspec/blob/master/CHANGES.rst
210 .. _`Change History`: https://python-path-specification.readthedocs.io/en/stable/changes.html
211 .. _`Read the Docs`: https://python-path-specification.readthedocs.io
212 .. _`UPGRADING.rst`: https://github.com/cpburnz/python-pathspec/blob/master/UPGRADING.rst
213 .. _`Upgrade Guide`: https://python-path-specification.readthedocs.io/en/stable/upgrading.html
214
215
216 Other Languages
217 ---------------
218
219 The related project `pathspec-ruby`_ (by *highb*) provides a similar library as
220 a `Ruby gem`_.
221
222 .. _`pathspec-ruby`: https://github.com/highb/pathspec-ruby
223 .. _`Ruby gem`: https://rubygems.org/gems/pathspec
224
225
226 Change History
227 ==============
228
229
230 1.1.1 (2026-04-26)
231 ------------------
232
233 Improvements:
234
235 - Improved type checking with mypy and pyright.
236
237 Bug fixes:
238
239 - Fixed typing on `PathSpec[TPattern]` to `PathSpec[TPattern_co]`.
240 - Added missing variant type-hint `type[Pattern]` to `PathSpec.from_lines()` parameter `pattern_factory`.
241 - Fixed possible type error when using `+` and `+=` operators on `PathSpec`.
242
243
244 1.1.0 (2026-04-22)
245 ------------------
246
247 New features:
248
249 - `Issue #108`_: Specialize pattern type for `PathSpec` as `PathSpec[TPattern]` for better debugging of `PathSpec().patterns`.
250
251 Bug fixes:
252
253 - `Issue #93`_: Git discards invalid range notation. `GitIgnoreSpecPattern` now discards patterns with invalid range notation like Git.
254 - `Pull #106`_: Fix escape() not escaping backslash characters.
255
256 Improvements:
257
258 - `Pull #110`_: Nicer debug print outs (and str for regex pattern).
259
260
261 .. _`Pull #106`: https://github.com/cpburnz/python-pathspec/pull/106
262 .. _`Issue #108`: https://github.com/cpburnz/python-pathspec/issues/108
263 .. _`Pull #110`: https://github.com/cpburnz/python-pathspec/pull/110
264
265
266 1.0.4 (2026-01-26)
267 ------------------
268
269 Bug fixes:
270
271 - `Issue #103`_: Using re2 fails if pyre2 is also installed.
272
273 .. _`Issue #103`: https://github.com/cpburnz/python-pathspec/issues/103
274
275
276 1.0.3 (2026-01-09)
277 ------------------
278
279 Bug fixes:
280
281 - `Issue #101`_: pyright strict errors with pathspec >= 1.0.0.
282 - `Issue #102`_: No module named 'tomllib'.
283
284
285 .. _`Issue #101`: https://github.com/cpburnz/python-pathspec/issues/101
286 .. _`Issue #102`: https://github.com/cpburnz/python-pathspec/issues/102
287
288
289 1.0.2 (2026-01-07)
290 ------------------
291
292 Bug fixes:
293
294 - Type hint `collections.abc.Callable` does not properly replace `typing.Callable` until Python 3.9.2.
295
296
297 1.0.1 (2026-01-06)
298 ------------------
299
300 Bug fixes:
301
302 - `Issue #100`_: ValueError(f"{patterns=!r} cannot be empty.") when using black.
303
304
305 .. _`Issue #100`: https://github.com/cpburnz/python-pathspec/issues/100
306
307
308 1.0.0 (2026-01-05)
309 ------------------
310
311 Major changes:
312
313 - `Issue #91`_: Dropped support of EoL Python 3.8.
314 - Added concept of backends to allow for faster regular expression matching. The backend can be controlled using the `backend` argument to `PathSpec()`, `PathSpec.from_lines()`, `GitIgnoreSpec()`, and `GitIgnoreSpec.from_lines()`.
315 - Renamed "gitwildmatch" pattern back to "gitignore". The "gitignore" pattern behaves slightly differently when used with `PathSpec` (*gitignore* as documented) than with `GitIgnoreSpec` (replicates *Git*'s edge cases).
316
317 API changes:
318
319 - Breaking: protected method `pathspec.pathspec.PathSpec._match_file()` (with a leading underscore) has been removed and replaced by backends. This does not affect normal usage of `PathSpec` or `GitIgnoreSpec`. Only custom subclasses will be affected. If this breaks your usage, let me know by `opening an issue <https://github.com/cpburnz/python-pathspec/issues>`_.
320 - Deprecated: "gitwildmatch" is now an alias for "gitignore".
321 - Deprecated: `pathspec.patterns.GitWildMatchPattern` is now an alias for `pathspec.patterns.gitignore.spec.GitIgnoreSpecPattern`.
322 - Deprecated: `pathspec.patterns.gitwildmatch` module has been replaced by the `pathspec.patterns.gitignore` package.
323 - Deprecated: `pathspec.patterns.gitwildmatch.GitWildMatchPattern` is now an alias for `pathspec.patterns.gitignore.spec.GitIgnoreSpecPattern`.
324 - Deprecated: `pathspec.patterns.gitwildmatch.GitWildMatchPatternError` is now an alias for `pathspec.patterns.gitignore.GitIgnorePatternError`.
325 - Removed: `pathspec.patterns.gitwildmatch.GitIgnorePattern` has been deprecated since v0.4 (2016-07-15).
326 - Signature of method `pathspec.pattern.RegexPattern.match_file()` has been changed from `def match_file(self, file: str) -> RegexMatchResult | None` to `def match_file(self, file: AnyStr) -> RegexMatchResult | None` to reflect usage.
327 - Signature of class method `pathspec.pattern.RegexPattern.pattern_to_regex()` has been changed from `def pattern_to_regex(cls, pattern: str) -> tuple[str, bool]` to `def pattern_to_regex(cls, pattern: AnyStr) -> tuple[AnyStr | None, bool | None]` to reflect usage and documentation.
328
329 New features:
330
331 - Added optional "hyperscan" backend using `hyperscan`_ library. It will automatically be used when installed. This dependency can be installed with ``pip install 'pathspec[hyperscan]'``.
332 - Added optional "re2" backend using the `google-re2`_ library. It will automatically be used when installed. This dependency can be installed with ``pip install 'pathspec[re2]'``.
333 - Added optional dependency on `typing-extensions`_ library to improve some type hints.
334
335 Bug fixes:
336
337 - `Issue #93`_: Do not remove leading spaces.
338 - `Issue #95`_: Matching for files inside folder does not seem to behave like .gitignore's.
339 - `Issue #98`_: UnboundLocalError in RegexPattern when initialized with `pattern=None`.
340 - Type hint on return value of `pathspec.pattern.RegexPattern.match_file()` to match documentation.
341
342 Improvements:
343
344 - Mark Python 3.13 and 3.14 as supported.
345 - No-op patterns are now filtered out when matching files, slightly improving performance.
346 - Fix performance regression in `iter_tree_files()` from v0.10.
347
348
349 .. _`Issue #38`: https://github.com/cpburnz/python-pathspec/issues/38
350 .. _`Issue #91`: https://github.com/cpburnz/python-pathspec/issues/91
351 .. _`Issue #93`: https://github.com/cpburnz/python-pathspec/issues/93
352 .. _`Issue #95`: https://github.com/cpburnz/python-pathspec/issues/95
353 .. _`Issue #98`: https://github.com/cpburnz/python-pathspec/issues/98
354 .. _`google-re2`: https://pypi.org/project/google-re2/
355 .. _`hyperscan`: https://pypi.org/project/hyperscan/
356 .. _`typing-extensions`: https://pypi.org/project/typing-extensions/