Gitignore Parser

0.1.13 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

This quickstart demonstrates how to create a gitignore parser instance from both a file path and a string, then use its `match()` method to check if specific file paths are ignored according to the rules.

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')}")

view raw JSON →