Разработка и Git

Статистика репозитория и авторов

Считает коммиты, добавленные и удалённые строки, активные дни и вклад авторов за период.

Python Windows macOS Linux Средний
Скачать repo_stats.py
Описание

Что делает скрипт

Скрипт разбирает git log с numstat и собирает сводку по репозиторию и авторам. Можно ограничить период и автора, а результат сохранить в JSON. История только читается, рабочее дерево не меняется.

Запуск

Быстрый старт

python repo_stats.py --repo . --since 2025-01-01

Скачайте файл, откройте терминал в папке со скриптом и выполните команду. В Linux и macOS интерпретатор может называться python3, в Windows - python или py.

Примеры

Другие варианты

  • python repo_stats.py --repo .
  • python repo_stats.py --repo . --since 2025-01-01 --json stats.json
  • python repo_stats.py --repo . --author user --since 2025-06-01
Зависимости

Что понадобится

Git 2.40+ Система контроля версий
Windows winget install Git.Git
macOS brew install git
Linux sudo apt install git
Python 3.10+ Только стандартная библиотека
Windows winget install Python.Python.3.12
macOS brew install python
Linux sudo apt install python3
Исходник

repo_stats.py

#!/usr/bin/env python3
"""Статистика git-репозитория по коммитам и авторам."""
from __future__ import annotations

import argparse
import json
import re
import shutil
import subprocess
from collections import defaultdict
from pathlib import Path

NUMSTAT = re.compile(r"^(\d+|-)\t(\d+|-)\t(.+)$")


def git(repo: Path, *args: str) -> subprocess.CompletedProcess[str]:
    return subprocess.run(
        ["git", "-C", str(repo), *args],
        capture_output=True,
        text=True,
        encoding="utf-8",
        errors="replace",
    )


def main() -> int:
    parser = argparse.ArgumentParser(description="Статистика git-репозитория")
    parser.add_argument("--repo", default=".", help="Путь к репозиторию")
    parser.add_argument("--since", help="Начало периода, например 2025-01-01")
    parser.add_argument("--author", help="Фильтр по автору")
    parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON")
    args = parser.parse_args()

    if not shutil.which("git"):
        print("Не найден git.")
        return 2
    repo = Path(args.repo).expanduser().resolve()
    if not repo.is_dir():
        print(f"Папка не найдена: {repo}")
        return 2
    if git(repo, "rev-parse", "--is-inside-work-tree").returncode != 0:
        print(f"Это не git-репозиторий: {repo}")
        return 2

    cmd = ["log", "--numstat", "--date=short", "--pretty=format:commit%x09%H%x09%an%x09%ad%x09%s"]
    if args.since:
        cmd.append(f"--since={args.since}")
    if args.author:
        cmd.append(f"--author={args.author}")

    result = git(repo, *cmd)
    if result.returncode != 0:
        print(result.stderr.strip())
        return 1

    commits = 0
    added = 0
    deleted = 0
    files: set[str] = set()
    active_dates: set[str] = set()
    authors: dict[str, dict[str, int]] = defaultdict(lambda: {"commits": 0, "added": 0, "deleted": 0})

    for line in result.stdout.splitlines():
        if line.startswith("commit\t"):
            parts = line.split("\t", 4)
            if len(parts) < 5:
                continue
            commits += 1
            author = parts[2]
            date = parts[3]
            active_dates.add(date)
            authors[author]["commits"] += 1
            continue
        match = NUMSTAT.match(line)
        if not match:
            continue
        add_value, del_value, path = match.groups()
        add_count = int(add_value) if add_value.isdigit() else 0
        del_count = int(del_value) if del_value.isdigit() else 0
        added += add_count
        deleted += del_count
        files.add(path)
        if commits:
            last_author = parts[2] if "parts" in locals() else ""
            if last_author:
                authors[last_author]["added"] += add_count
                authors[last_author]["deleted"] += del_count

    if commits == 0:
        print("Коммитов по заданным фильтрам не найдено.")
        return 0

    ranking = sorted(
        authors.items(),
        key=lambda item: (item[1]["commits"], item[1]["added"]),
        reverse=True,
    )
    payload = {
        "repo": str(repo),
        "commits": commits,
        "authors": len(authors),
        "added": added,
        "deleted": deleted,
        "files": len(files),
        "active_days": len(active_dates),
        "ranking": [
            {"author": name, **values} for name, values in ranking
        ],
    }

    if args.json:
        args.json.write_text(
            json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
            encoding="utf-8",
        )

    print(f"Репозиторий: {repo}")
    print(f"Коммитов: {commits}, авторов: {len(authors)}, активных дней: {len(active_dates)}")
    print(f"Строк добавлено: {added}, удалено: {deleted}, файлов затронуто: {len(files)}")
    print()
    print(f"{'Коммиты':>7} {'Добавлено':>10} {'Удалено':>9}  Автор")
    for name, values in ranking[:10]:
        print(f"{values['commits']:7d} {values['added']:10d} {values['deleted']:9d}  {name}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.

CLI 1.0.0

Скачать без браузера

Команда скачает этот файл в текущую папку. CLI работает на Windows, macOS и Linux.

scriptdock get dev-repo-stats
  • Поиск по всему каталогу
  • Python 3.10+
  • Без внешних пакетов
Скачать CLI

GUI-версия готовится. Подробнее

Категория

Разработка и Git

Git, сборка, тесты, зависимости, логи и обслуживание проектов.