Install gitignore_parser via pip
masterInstall the library using the standard Python package manager:
pip install gitignore_parserrepository·master·Indexed 42 days ago
https://github.com/mherrmann/gitignore_parserA spec-compliant gitignore parser for Python supporting advanced features such as square bracket pattern matching and top-level path constraints. Provides functions to parse rules from physical files via parse_gitignore or from strings via parse_gitignore_str.
Install the library using the standard Python package manager:
pip install gitignore_parserUse parse_gitignore(path) to load rules from a physical file on disk. This returns a matches function that accepts a file path and returns True if the path is ignored by the rules in that file, or False otherwise.
from gitignore_parser import parse_gitignore
# Returns a function that checks if a path is ignored
matches = parse_gitignore('/path/to/project/.gitignore')
# Check specific files
print(matches('/path/to/project/main.pyc')) # True if ignored
print(matches('/path/to/project/main.py')) # False if not ignoredUse parse_gitignore_str(gitignore_string, base_dir=None) to parse rules provided as a raw string.
Important: When using a string, you should provide the base_dir argument (the directory where the rules are conceptually located) to ensure that relative paths and top-level path rules (e.g., /file.txt) are evaluated correctly against the files you are checking.
from gitignore_parser import parse_gitignore_str
# Define rules as a string and specify the base directory
matches = parse_gitignore_str(
'__pycache__/
*.py[cod]',
base_dir='/home/michael/project'
)
# Check paths relative to the project
print(matches('/home/michael/project/main.pyc')) # True
print(matches('/home/michael/project/main.py')) # False