gitignore_parser for Python

repository·master·Indexed 42 days ago

https://github.com/mherrmann/gitignore_parser

A 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.

Tokens
537
Snippets
3
Records
3
Agent score
3%

What's inside gitignore_parser

  1. Parse a .gitignore file using parse_gitignore

    master

    Use 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 ignored
  2. Parse gitignore rules from a string using parse_gitignore_str

    master

    Use 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