automattic/ignorefile

Handle .gitignore style files.

v2.1.0 2024-08-29 19:01 UTC

README

This small library allows for processing of .gitignore-style files in PHP.

It follows the documentation at gitignore, even in cases where git itself does not.

Installation

Require using composer require automattic/ignorefile.

Usage

// Read a .myignore file.
$ignore = new IgnoreFile();
$ignore->add( file_get_contents( '.myignore' ) );

// Test if a file is ignored.
if ( $ignore->ignores( $filename ) ) {
        echo "$filename is ignored\n";
} else {
        echo "$filename is not ignored\n";
}

// Filter ignored files from an array of files.
$filesToProcess = $ignore->filter( $allFiles );

// Load all .myignore files in a directory tree, then list all non-ignored files.
$ignore = new IgnoreFile();
$iter = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( '.' ) );
foreach ( $iter as $path ) {
        if ( basename( $path ) === '.myignore' ) {
                $ignore->add( file_get_contents( $path ), dirname( $path ) . '/' );
        }
}

$iter = new RecursiveIteratorIterator(
    $ignore->filterIterator( new RecursiveDirectoryIterator( '.' ) )
);
foreach ( $iter as $file ) {
        echo "$file\n";
}

Strict mode

To match git's behavior, invalid patterns passed to add() will be silently ignored. If you'd rather have exceptions thrown, set $ignore->strictMode to true.

Known incompatibilities with git

As of git 2.43.0.

The gitignore documentation refers to fnmatch for specifics of *, ?, and bracket expressions. That in turn refers to a few other documents.

Inspiration

I needed something similar to the npm module ignore for PHP, but couldn't find one. So I wrote one, copying the fairly comprehensive set of tests to make sure my implementation was accurate.