Count Unique Contributors from Git Shortlog in Python
Parses git shortlog -sn output to count the number of unique contributors, handling duplicate entries and variable whitespace.
Python code
25 linesimport subprocess
from collections import Counter
# Mock shortlog output as a list of lines (simulating git shortlog -sn output)
MOCK_SHORTLOG = """ 120 Alice Johnson
88 Bob Smith
45 Alice Johnson
30 Carol Williams
25 Bob Smith
10 Dave Brown
"""
def count_contributors_from_shortlog(text):
"""Parse shortlog text and return number of unique contributors."""
contributors = Counter()
for line in text.strip().splitlines():
parts = line.strip().split(" ")
if len(parts) >= 2:
name = parts[-1].strip()
contributors[name] += 1
return len(contributors)
if __name__ == "__main__":
unique_count = count_contributors_from_shortlog(MOCK_SHORTLOG)
print(f"Unique contributors: {unique_count}")
Output
Unique contributors: 4
How it works
The git shortlog -sn command groups commits by author and prints a count followed by the author's name. By parsing each line and extracting the name portion, we can tally contributors. Using Counter from the standard library allows us to track how many times each name appears. Splitting on double spaces (" ") is a robust way to separate the commit count from the name, even with inconsistent spacing. The final len(contributors) gives the number of unique contributors.
Common mistakes
- Splitting on single spaces instead of double spaces, which breaks when names contain spaces
- Not stripping leading/trailing whitespace from lines before parsing
- Assuming each line is unique, leading to an overcount if the same contributor appears on multiple lines
Variations
- Use `subprocess.run(['git', 'shortlog', '-sn', '--all'])` to get real output from a repository
- Parse with a regex like `r'^\s*(\d+)\s+(.+)$'` to handle arbitrary spacing
Real-world use cases
- Generate a contributor report for a release announcement or project documentation.
- Automate recognition for a team dashboard by counting active developers per sprint.
- Validate that all expected developers have contributed before a code freeze.
Sponsored
More from Git + Python
Keep learning
Related tutorials and quizzes for this topic.