自动删除gone分支

缘由

工作使用git,通过pr的方式合并,针对每个任务或者bug创建不同的分支,处理签入后分支往往会被删除,结果本地会留下很多gone分支,懒得手动删除,编写脚本自动处理

实现

# 设定utf8输出,避免输出汉字乱码
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
# 切换到git所在目录,该脚本不在git目录下,避免影响源码或者.gitignore
cd XXX  # 工作目录
 
# 执行git branch -vv命令并获取输出
$gitOutput = git branch -vv

Write-Output ">>>>>>>>>>清除gone分支<<<<<<<<<<"

# 列出现有的分支
Write-Output  "现有分支数:" $gitOutput.Count  " 分别是:"
foreach($line in $gitOutput){
   Write-Output $line
}
Write-Output ">>>>>开始处理每个分支>>>>>"
foreach ($line in $gitOutput) {
 # 找到gone分支并输出
    if ($line -match '\[.*: gone\]') {
        # 将多个空格替换成一个,后面用空格split后即可得到各个部分内容
        $line = $line -replace '\s+',' '
        Write-Output  "【检测到gone分支:】"
        $matches = $line.Split(' ')
        # 按照结构,第一列识别当前分支,第二列分支名称
        $branchInfo = @{
            BranchName = $matches[1].Trim()
        }
        $branchName= $branchInfo.BranchName
        # 删除分支红色显示
        $originalColor = $Host.UI.RawUI.ForegroundColor
        $Host.UI.RawUI.ForegroundColor = 'Red'
        Write-Output "Gone 分支名称: $branchName 【将其删除】"
        git branch -D $branchName
        $Host.UI.RawUI.ForegroundColor = $originalColor
    }
    else
    {
     # 保留分支绿色显示
        $originalColor = $Host.UI.RawUI.ForegroundColor
        $Host.UI.RawUI.ForegroundColor = 'Green'
        Write-Output "$line 【不是gone分支,保留】"
        $Host.UI.RawUI.ForegroundColor = $originalColor        
    }
}
Write-Output " "
Write-Output "===处理完成==="
Read-Host
posted @ 2025-06-25 20:03  youdias  阅读(10)  评论(0)    收藏  举报