Functions/Remove-GitBranchesNotExistantOnline.ps1


function Remove-GitBranchesNotExistantOnline {
    [CmdletBinding()]
    param (
    )

    $GitConfigPath = Join-Path . ".git"

    if (Test-Path $GitConfigPath) {

        $Ignorelist = @("HEAD", "main", "master")

        git fetch -a -p

        $gitBranchesLocal = ((git branch) -replace '\*', "").Trim()
        $gitBranchesRemote = (git branch -r).Trim()

        if ($gitBranchesLocal -match "main") {
            $defaultBranch = "main"
        } elseif ($gitBranchesLocal -match "master") {
            $defaultBranch = "master"
        } else {
            break
        }
        Write-Host "Switching to branch $($defaultBranch)" -ForegroundColor Green
        git switch $defaultBranch

        "-------------------------"
        Write-Host "Local branches" -ForegroundColor Yellow
        $gitBranchesLocal
        # ($gitBranchesLocal).GetType()
        "-------------------------"
        Write-Host "Remote branches" -ForegroundColor Yellow
        $gitBranchesRemote
        "-------------------------`n`n`n"
        "-------------------------"
        $gitBranchesLocal | ForEach-Object {
            # $_
            # "next`n"
            Write-Host "Checking local branch `"$($_)`"" -ForegroundColor Yellow
            if ($Ignorelist -contains $_) {
                Write-Host "Branch $($_) will be ignored" -ForegroundColor Red
            } else {
                # $branchName = ($_ -split "/")[-1]
                if ($gitBranchesRemote -match $_) {
                    Write-Host "This branch exists remote and locally" -ForegroundColor Green
                } else {
                    Write-Host "This branch exists only locally" -ForegroundColor Red
                    if ((Read-Host -Prompt "Delete branch $_? (y/N)") -eq "y") {
                        git branch -d $_
                    }
                }
            }

            "-------------------------"
        }

    } else {
        Write-Warning "This folder is not git folder"
    }
}