有没有一种方法可以获取 git 存储库中状态为 new/modified/deleted 的文件数?

Is there a method of getting the number of files in git repository with new/modified/deleted status?

我正在编写一个 Python 脚本,用于打印描述当前目录中 git 存储库状态的字符串。这用于在 zsh 中创建右侧提示。输出将如下所示:

jared@Jareds-MacBook-Pro% ⌷                          master(+0, ~0, -0)

现在,我正试图找到一种方法来确定存储库中新文件、修改文件和删除文件的数量,以便我可以更新字符串中的计数。我需要能够在 Python 3 中或通过 subprocess.call() 或 subprocess.check_output() 执行此操作。欢迎提出任何建议。

git status --porcelain | cut -c 2 | sort | uniq -c

感谢@crea1 指正

如果你想要Python中的解,注意git status --porcelain的输出:

 M modified_file.txt
 D deleted_file
?? untracked(new)file

这是代码示例:

from subprocess import PIPE, Popen
from collections import Counter

def count_git_status():
    command = ['git', 'status', '--porcelain']
    pipe = Popen(command, stdout=PIPE)
    status = Counter(line.split()[0] for line in pipe.stdout)
    return status

def main():
    status = count_git_status()
    print('Untracked: {}'.format(status['??']))
    print('Modified:  {}'.format(status['M']))
    print('Deleted:   {}'.format(status['D']))

更新

git branch --list的输出:

  bar
  foo
* master

为了解析,我们寻找以“*”开头的行。这是获取分支的代码。有了这个你可以构建提示:

def git_branch():
    command = ['git', 'branch', '--list']
    pipe = Popen(command, stdout=PIPE)
    return next((x.split()[1] for x in pipe.stdout if x.startswith('* ')), 'unknown branch')