python - 有没有一种简单的方法可以根据 .gitignore 规则匹配文件?

标签 python git gitignore

我正在用 Python 编写一个 git 预提交 Hook ,我想定义一个像 .gitignore 文件这样的黑名单,以便在处理文件之前检查文件。有没有一种简单的方法来检查文件是否根据一组 .gitignore 规则定义?这些规则有点神秘,我宁愿不必重新实现它们。

最佳答案

假设您位于包含 .gitignore 文件的目录中,一个 shell 命令将列出所有忽略的文件:

git ls-files

从 python 你可以简单地调用:

import os
os.system("git ls-files")

您可以像这样提取文件列表:

import subprocess
list_of_files = subprocess.check_output("git ls-files", shell=True).splitlines()

如果您想列出忽略的文件(也就是未跟踪的文件),那么您可以添加选项“--other”:

git ls-files --other

关于python - 有没有一种简单的方法可以根据 .gitignore 规则匹配文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41130632/

相关文章:

python - 在 PyQt 应用程序中 pickle 一个字典

python - Argparse:如果存在 'y',则需要参数 'x'

Python/Django png,gif 转 jpg

git jenkins scm 插件权限被拒绝

git - .gitignore 不会忽略目录

python - 连接到动态数据库参数 sqlalchemy

Git pull - 删除的文件

git - 你需要提交一个 git 子模块还是只提交 gitmodules 文件

xcode - 添加 pod 文件并推送。如何撤消?如何在 Xcode 和 github 中使用 gitignore?

git - 从 .idea 文件夹中 gitignore 什么?