Gitignore Parser
gitignore-parser is a spec-compliant Python library for parsing `.gitignore` files and matching paths against their rules. It provides accurate behavior according to the Git documentation for ignore rules. The current version is 0.1.13, and the library receives regular updates for bug fixes and minor improvements.
Warnings
- gotcha Older versions (pre-0.1.8 / pre-0.1.7) had incorrect parsing behavior for certain complex patterns, such as implicit anchoring, multi-asterisks, leading exclamation marks, and slashes in ranges. This could lead to rules not matching as expected according to the gitignore specification.
- gotcha The `parse_gitignore_str()` function, which allows parsing gitignore rules directly from a string without needing a file, was introduced in version 0.1.12. Prior versions only supported parsing from a file path using `parse_gitignore()`.
- gotcha Version 0.1.13 fixed some edge cases related to path matching on Windows, which could lead to incorrect ignore decisions for certain patterns and paths on Windows systems.
Install
-
pip install gitignore-parser
Imports
- parse_gitignore
from gitignore_parser import parse_gitignore
- parse_gitignore_str
from gitignore_parser import parse_gitignore_str
Quickstart
from pathlib import Path
from gitignore_parser import parse_gitignore, parse_gitignore_str
# Example 1: Parsing from a file
gitignore_path = Path("temp_test.gitignore")
gitignore_path.write_text("""
# Ignore build artifacts
/build/
*.log
!important.log
""")
# Create a parser instance from the .gitignore file
parser_file = parse_gitignore(gitignore_path)
# Test matching paths
print(f"Is 'build/app.exe' ignored? {parser_file.match('build/app.exe')}")
print(f"Is 'temp.log' ignored? {parser_file.match('temp.log')}")
print(f"Is 'important.log' ignored? {parser_file.match('important.log')}")
gitignore_path.unlink() # Clean up the temporary file
# Example 2: Parsing from a string (available from v0.1.12+)
gitignore_content = """
# Ignore temporary files
*.tmp
/cache/
"""
parser_str = parse_gitignore_str(gitignore_content)
print(f"Is 'file.tmp' ignored (from string)? {parser_str.match('file.tmp')}")
print(f"Is 'project/cache/data.json' ignored (from string)? {parser_str.match('project/cache/data.json')}")