You can get an array of files to ignore from a .gitignore
file and check against that. To do that, you would need to read the file and match files using the glob
function.
First, get the contents of the file:
$contents = file_get_contents($pathToGitIgnoreFile);
$path = dirname(realpath($pathToGitIgnoreFile));
You can also use the directory of the .gitignore
file to match files in the same directory as the gitignore.
Next, we need to split the contents into individual rules. Rules start on their own line in the file. Lines that start with the pound symbol (#
) are comments, so we can just use a regular expression to find non-blank lines that aren't comments:
$rules = array();
preg_match_all('/[\\A\\v]([^#\\v]\\V*)[\\z\\v]?/', $contents, $rules);
$rules = $rules[1];
Then all you have to do is iterate through the rules and use glob
to create an array of file names to ignore:
$files = array();
foreach ($rules as $rule)
{
if (strpos($rule, '!') === 0) // negative rule
$files = array_diff($files, glob($path . DIRECTORY_SEPARATOR . substr($rule, 1)));
else
$files = array_merge($files, glob($path . DIRECTORY_SEPARATOR . $rule));
}
$files = array_unique($files);
I didn't test this code, so comment below if it doesn't work for you.