gpt4 book ai didi

PHP根据.gitignore过滤文件和路径

转载 作者:可可西里 更新时间:2023-11-01 13:37:01 25 4
gpt4 key购买 nike

我想使用 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 文件

您需要忽略注释,注意否定运算符 (!),并注意 glob。

这个是,给予或接受,会变成这样:

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;
}

(注意:以上都没有经过测试,但它们应该能让您朝着正确的方向前进。)

关于PHP根据.gitignore过滤文件和路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19981583/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com