Reputation: 4810
I'm writing a Python script that prints a string describing the state of a git repository in the current directory. This is being used for creating a right-sided prompt in zsh. The output will look like the right side of this:
jared@Jareds-MacBook-Pro% ⌷ master(+0, ~0, -0)
Right now, I'm trying to find a method of determining the number of new, modified, and deleted files in the repository so that I can update the counts in the string. I need to be able to do this either in Python 3 or through subprocess.call() or subprocess.check_output(). Any suggestions are welcome.
Upvotes: 1
Views: 567
Reputation: 40723
If you want the solution in Python, note that the output of git status --porcelain
:
M modified_file.txt
D deleted_file
?? untracked(new)file
Here is the code sample:
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']))
The output of git branch --list
:
bar
foo
* master
To parse, we look for the line that starts with '*'. Here is the code to get the branch. With this you can construct the prompt:
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')
Upvotes: 2
Reputation: 9559
git status --porcelain | cut -c 2 | sort | uniq -c
Thanks @crea1 for the correction
Upvotes: 3