我想编写一个忽略文件和目录的应用程序,就像 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/