PowerShell 脚本:本地 Git 仓库自动化管理

# 设置默认提交数量
$defaultCommitLimit = 5

# 获取当前目录下的 Git 仓库
$repoPath = Get-Location

# 切换到 Git 仓库目录
cd $repoPath

# 检查是否是 Git 仓库
if (-not (git rev-parse --is-inside-work-tree)) {
    Write-Host "当前目录不是 Git 仓库,请确保在正确的目录下运行脚本。"
    exit
}

# 提交未保存的修改
git add .
 git commit -m "Automated commit $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"

# 获取当前提交总数
$commitCount = git rev-list --count HEAD

# 如果提交数超过预设值,则合并最老的提交
if ($commitCount -gt $defaultCommitLimit) {
    # 计算需要删除的提交数
    $commitToDelete = $commitCount - $defaultCommitLimit
    
    # 获取最老的提交哈希值
    $oldestCommit = git rev-list --reverse HEAD | Select-Object -First 1
    
    # 合并最老的提交
    git rebase -i $oldestCommit~$commitToDelete
    
    # 在交互式 rebase 中,删除除了第一个提交之外的所有提交
    # 例如,将以下行
    # pick <commit-hash> commit message
    # 改为以下行
    # drop <commit-hash>
    
    # 保存并退出 rebase
    git rebase --continue
}

Write-Host "Git 仓库管理完成。"

使用说明

  1. 将上述脚本保存为 PowerShell 脚本文件,例如 git-automate.ps1
  2. 在 PowerShell 中运行该脚本:

    .\git-automate.ps1

注意事项

  • 确保在 Git 仓库的根目录下运行此脚本。
  • 脚本中的默认提交限制为 5,可以根据需要修改 $defaultCommitLimit 变量的值。
  • 脚本使用交互式 rebase 来合并最老的提交,可能需要手动确认一些操作。

希望这个脚本能够满足您的需求,如果有任何问题或需要进一步的帮助,。

标签: none

评论已关闭