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

Удалённые ветки и устаревшие ссылки

Показывает ветки origin с датой, возрастом и признаком наличия локальной отслеживающей ветки.

PowerShell Windows Средний
Скачать Git-RemoteBranches.ps1
Описание

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

Скрипт читает refs/remotes и не выполняет git remote prune. Ветки старше заданного числа дней помечаются как устаревшие, а отсутствие локальной пары помогает найти забытые ветки. Удаление остаётся ручным решением.

Перед запуском
  • Скрипт не удаляет удалённые ветки и не делает prune.
Запуск

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

powershell -File Git-RemoteBranches.ps1 -Path . -Remote origin -StaleDays 90

Скачайте файл, откройте терминал в папке со скриптом и выполните команду. Запускайте в PowerShell 5.1 или PowerShell 7.

Примеры

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

  • powershell -File Git-RemoteBranches.ps1 -Path .
  • powershell -File Git-RemoteBranches.ps1 -Path . -Remote origin -StaleDays 60 -Csv remote.csv
Зависимости

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

PowerShell 5.1+ Встроен в Windows 10 и 11
Windows Встроен в Windows 10/11 (PowerShell 5.1)
Git 2.40+ Система контроля версий
Windows winget install Git.Git
Исходник

Git-RemoteBranches.ps1

[CmdletBinding()]
param(
    [string]$Path = ".",
    [string]$Remote = "origin",
    [ValidateRange(1, 3650)]
    [int]$StaleDays = 90,
    [string]$Csv
)

$ErrorActionPreference = 'Stop'

if (-not (Get-Command git -ErrorAction SilentlyContinue)) {
    throw "git not found in PATH"
}

$repo = (Resolve-Path -LiteralPath $Path -ErrorAction Stop).Path
$null = & git -C $repo rev-parse --is-inside-work-tree 2>$null
if ($LASTEXITCODE -ne 0) {
    throw "Not a git repository: $repo"
}

$null = & git -C $repo remote get-url $Remote 2>$null
if ($LASTEXITCODE -ne 0) {
    throw "Remote not found: $Remote"
}

$tracked = @{}
$localLines = @(& git -C $repo for-each-ref "--format=%(refname:short)|%(upstream:short)" refs/heads 2>$null)
foreach ($line in $localLines) {
    $parts = $line -split '\|', 2
    if ($parts.Count -eq 2 -and $parts[1].Trim()) {
        $tracked[$parts[1].Trim()] = $true
    }
}

$format = '%(refname:short)|%(committerdate:iso8601)|%(subject)'
$lines = @(& git -C $repo for-each-ref "--format=$format" "refs/remotes/$Remote" 2>$null)
$rows = @()
foreach ($line in $lines) {
    if ([string]::IsNullOrWhiteSpace($line)) {
        continue
    }
    $parts = $line -split '\|', 3
    $name = $parts[0].Trim()
    if ($name.EndsWith('/HEAD')) {
        continue
    }
    $dateText = if ($parts.Count -gt 1) { $parts[1].Trim() } else { '' }
    $subject = if ($parts.Count -gt 2) { $parts[2].Trim() } else { '' }
    $age = -1
    try {
        $date = [datetime]::Parse($dateText, [Globalization.CultureInfo]::InvariantCulture)
        $age = [math]::Floor(((Get-Date) - $date).TotalDays)
    } catch {
        $age = -1
    }
    $rows += [pscustomobject]@{
        Branch   = $name
        AgeDays  = $age
        Stale    = ($age -ge $StaleDays)
        Local    = $tracked.ContainsKey($name)
        Subject  = $subject
    }
}

if ($rows.Count -eq 0) {
    Write-Host "No remote branches found for $Remote."
    exit 0
}

$rows | Sort-Object @{ Expression = 'Stale'; Descending = $true }, @{ Expression = 'AgeDays'; Descending = $true } |
    Format-Table -AutoSize

if ($Csv) {
    $rows | Export-Csv -LiteralPath $Csv -NoTypeInformation -Encoding UTF8
    Write-Host "CSV saved: $Csv"
}

Write-Host "Report only. Use git remote prune $Remote manually after review."

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

CLI 1.0.0

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

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

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

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

Категория

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

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

Теги