* * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder; /** * Gitignore matches against text. * * @author Ahmed Abdou */ class Gitignore { /** * Returns a regexp which is the equivalent of the gitignore pattern. * * @return string The regexp */ public static function toRegex(string $gitignoreFileContent): string { $gitignoreFileContent = preg_replace('/^[^\\\r\n]*#.*/m', '', $gitignoreFileContent); $gitignoreLines = preg_split('/\r\n|\r|\n/', $gitignoreFileContent); $positives = []; $negatives = []; foreach ($gitignoreLines as $i => $line) { $line = trim($line); if ('' === $line) { continue; } if (1 === preg_match('/^!/', $line)) { $positives[$i] = null; $negatives[$i] = self::getRegexFromGitignore(preg_replace('/^!(.*)/', '${1}', $line), true); continue; } $negatives[$i] = null; $positives[$i] = self::getRegexFromGitignore($line); } $index = 0; $patterns = []; foreach ($positives as $pattern) { if (null === $pattern) { continue; } $negativesAfter = array_filter(\array_slice($negatives, ++$index)); if ([] !== $negativesAfter) { $pattern .= sprintf('(?'.$regex.'($|\/.*))'; } }