我想使用 PHP 读取 .gitignore 配置忽略的所有文件和路径。就像 git 的做法一样。
可以重复读取目录并对每个文件使用正则表达式进行过滤。但如果路径中的文件过多,则效果不佳。
有什么好的和最有效的方法来读取 .gitignore 忽略的目标文件和路径?
您需要分几个步骤进行:
1 - 找到 .gitignore 文件
每个文件夹都可以有一个,因此不要假设只有一个文件夹。
子模块有一个指向主 .git 文件夹的 .git 链接,因此也要小心不要过早停止。
它会像这样:
function find_gitignore_files($dir) {
$files = array();
while (true) {
$file = "$dir/.gitignore";
if (is_file($file)) $files[] = $file;
if (is_dir("$dir/.git") && !is_link("$dir/.git")) break; # stop here
if (dirname($dir) === '.') break; # and here
$dir = dirname($dir);
}
return $files;
}
2 - 解析每个 .gitignore 文件
您需要忽略注释,注意否定运算符 (!
),并注意球体。
无论给予还是接受,这将是这样的:
function parse_git_ignore_file($file) { # $file = '/absolute/path/to/.gitignore'
$dir = dirname($file);
$matches = array();
$lines = file($file);
foreach ($lines as $line) {
$line = trim($line);
if ($line === '') continue; # empty line
if (substr($line, 0, 1) == '#') continue; # a comment
if (substr($line, 0, 1) == '!') { # negated glob
$line = substr($line, 1);
$files = array_diff(glob("$dir/*"), glob("$dir/$line"));
} else { # normal glob
$files = glob("$dir/$line");
}
$matches = array_merge($matches, $files);
}
return $matches;
}
(注意:以上均未经过测试,但它们应该能让您朝着正确的方向前进。)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)