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

Отчёт о конфликтах Git

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

Python Windows macOS Linux Новичок
Скачать conflict_report.py
Описание

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

Скрипт получает список неразрешённых файлов через git diff --diff-filter=U и подсчитывает строки с маркерами конфликтов. Отчёт помогает оценить объём ручной работы и не забыть про файлы, которые легко пропустить. По желанию результат сохраняется в JSON.

Запуск

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

python conflict_report.py --repo .

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

Примеры

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

  • python conflict_report.py --repo .
  • python conflict_report.py --repo . --json conflicts.json
Зависимости

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

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
Исходник

conflict_report.py

#!/usr/bin/env python3
"""Отчёт о конфликтах слияния в git-репозитории."""
from __future__ import annotations

import argparse
import json
import shutil
import subprocess
from pathlib import Path

MARKERS = ("<<<<<<<", "=======", ">>>>>>>")


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 count_markers(path: Path) -> dict[str, int]:
    counts = {marker: 0 for marker in MARKERS}
    try:
        with path.open("r", encoding="utf-8", errors="replace") as handle:
            for line in handle:
                stripped = line.lstrip()
                for marker in MARKERS:
                    if stripped.startswith(marker):
                        counts[marker] += 1
    except OSError:
        pass
    return counts


def main() -> int:
    parser = argparse.ArgumentParser(description="Показать конфликты слияния")
    parser.add_argument("--repo", default=".", 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

    check = git(repo, "rev-parse", "--is-inside-work-tree")
    if check.returncode != 0:
        print(f"Это не git-репозиторий: {repo}")
        return 2

    result = git(repo, "diff", "--name-only", "--diff-filter=U")
    conflicts = [line.strip() for line in result.stdout.splitlines() if line.strip()]
    report = []
    for name in conflicts:
        counts = count_markers(repo / name)
        report.append({"file": name, "markers": counts, "total": sum(counts.values())})

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

    if not report:
        print("Конфликтов не найдено.")
        return 0

    print(f"Конфликтов: {len(report)}")
    for item in report:
        print(f"  {item['file']}  маркеров: {item['total']}")
    print("После ручного разрешения выполните git add и git commit.")
    return 0


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

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

CLI 1.0.0

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

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

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

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

Категория

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

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