pathspec

1.0.4 · active · verified Sat Mar 28

pathspec is a utility library for gitignore-style pattern matching of file paths, implementing Git's wildmatch/gitignore specification. Current stable version is 1.0.4 (released 2025). The project is actively maintained by Caleb P. Burns and releases roughly a few times per year. It is a zero-dependency pure-Python library widely used by tools such as Black, pip, and Poetry for .gitignore-based file filtering.

Warnings

Install

Imports

Quickstart

Compile gitignore-style patterns with PathSpec (documented semantics) or GitIgnoreSpec (true Git edge-case semantics), match individual paths or walk a directory tree.

from pathspec import PathSpec, GitIgnoreSpec

# --- PathSpec: documented gitignore behaviour ---
patterns = [
    '*.pyc',
    '__pycache__/',
    'dist/',
    '!dist/keep_this.txt',   # negation re-includes a file
]
spec = PathSpec.from_lines('gitignore', patterns)

# Match a list of paths
files = ['src/main.py', 'src/main.pyc', '__pycache__/x.pyc', 'dist/output.whl']
matched = list(spec.match_files(files))
print('Matched (excluded):', matched)
# -> ['src/main.pyc', '__pycache__/x.pyc', 'dist/output.whl']

# --- GitIgnoreSpec: replicates Git's actual edge-case behaviour ---
# Use this when you need to mirror exactly what `git` itself would ignore.
git_spec = GitIgnoreSpec.from_lines(patterns)

# Walk a real directory tree and get files to KEEP (negate=True flips results)
import os, tempfile, pathlib
with tempfile.TemporaryDirectory() as tmpdir:
    # create sample files
    for p in ['a.py', 'a.pyc', '__pycache__/x.pyc']:
        full = pathlib.Path(tmpdir) / p
        full.parent.mkdir(parents=True, exist_ok=True)
        full.write_text('')
    keep = set(git_spec.match_tree_files(tmpdir, negate=True))
    ignore = set(git_spec.match_tree_files(tmpdir))
    print('Keep:', keep)
    print('Ignore:', ignore)

view raw JSON →