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.

Easy Python 3.9+ Aug 9, 2026 Git + Python 13 views 0 copies

Python code

25 lines
Python 3.9+
import 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

stdout
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

  1. Use `subprocess.run(['git', 'shortlog', '-sn', '--all'])` to get real output from a repository
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Git + Python

Related tutorials and quizzes for this topic.