python - 有没有办法在 python 中处理忽略文件(如 .gitignore)?

标签 python git ignore

我想编写一个忽略文件和目录的应用程序,就像 git 使用它的 .gitignore 文件那样。目标如下。我的应用程序称为“MyFancyApp”。如果我像这样运行 cli:“MyFancyApp build”,应用程序将在当前目录上运行并收集所有文件并将其放入 Zip 文件中。但我想排除我在 .MyFancyAppIgnore 文件中引用的文件和目录。代码是用 Python 编写的

最佳答案

您可以使用python库GitPython使用 ignored 检查 git 是否会忽略这些文件方法。给定的文件路径列表将检查 git 是否会忽略它们并返回那些文件路径。可以使用 python -m pip install GitPython 来安装它,然后在您的代码中:

import git

flist = [ # list of the files given by glob.glob or otherwise
]
repo = git.Repo(start_dir, search_parent_directories=True)
ignored = repo.ignored(flist)
flist = [f for f in flist if not f in ignored] # Filter the flist
repo.close()
# In your zipping function use the modified flist

注意

我发现有必要在调用 repo.ignored 时使用绝对路径,因此您可能需要使用 pathlib

关于python - 有没有办法在 python 中处理忽略文件(如 .gitignore)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60760161/

相关文章:

python - Scipy kstest 对于相似的值集返回不同的 p 值

git - 如何从 Github pull 特定分支

git - 如何 git cherry-pick 使用二进制文件提交

Mercurial 和忽略模式

python - 弹出一个窗口,里面有文字,并在一定时间后自动关闭

python - 如何内省(introspection) SOAP 数据类型?

python - 为什么 python .pyc 文件包含其源代码的绝对路径?

git - git索引的内容在 merge 期间如何演变( merge 失败后索引中的内容)?

vb.net - 是否有更好的方法让Visual Studio在 Debug模式下忽略try/catch