Git指定范围提交信息查询及PowerShell脚本实现咨询
问题解答
1. 检索指定范围的提交信息
完全可以通过git log命令直接实现,支持标签、提交哈希或两者组合的范围查询:
- 两个标签之间:使用标签名作为范围,语法为
git log <起始标签>..<结束标签>,例如:
该命令会输出从git log v1.0..v2.0v1.0之后到v2.0的所有提交。如果需要包含v1.0本身,可使用三个点:git log v1.0...v2.0 - 两个提交之间:用提交哈希(或短哈希)替换标签即可,语法为
git log <起始提交哈希>..<结束提交哈希>,例如:git log a1b2c3..d4e5f6 - 标签与提交组合:混合使用标签和提交哈希,比如从某个标签到某个提交:
或者从某个提交到某个标签:git log v1.0..d4e5f6git log a1b2c3..v2.0
如果需要指定特定分支(无需切换到该分支),可以在范围前加上分支名:
git log mybranch v1.0..v2.0
2. PowerShell脚本实现工具
可以编写一个PowerShell脚本,接收仓库路径、分支、范围参数,并将结果导出到文本文件。以下是完整示例:
param( [Parameter(Mandatory=$true)] [string]$RepoPath, [Parameter(Mandatory=$true)] [string]$BranchName, [Parameter(Mandatory=$true)] [string]$StartRef, # 可以是标签名、提交哈希或日期 [Parameter(Mandatory=$true)] [string]$EndRef, # 可以是标签名、提交哈希或日期 [Parameter(Mandatory=$true)] [string]$OutputPath ) # 切换到仓库目录 Set-Location -Path $RepoPath # 检查分支是否存在 if (-not (git branch --list $BranchName)) { Write-Error "分支 $BranchName 不存在于仓库中" exit 1 } # 判断输入是否为日期格式,兼容日期范围查询 $isDateStart = [DateTime]::TryParse($StartRef, [ref]$null) $isDateEnd = [DateTime]::TryParse($EndRef, [ref]$null) if ($isDateStart -and $isDateEnd) { $gitLogCommand = "git log $BranchName --since='$StartRef' --until='$EndRef'" } else { $gitLogCommand = "git log $BranchName $StartRef..$EndRef" } # 执行命令并导出到文件 Invoke-Expression $gitLogCommand | Out-File -FilePath $OutputPath -Encoding utf8 Write-Host "提交记录已成功导出到 $OutputPath"
使用说明
- 将上述脚本保存为
Get-GitCommitRange.ps1 - 在PowerShell中运行脚本,传入参数:
# 标签范围示例 .\Get-GitCommitRange.ps1 -RepoPath "C:\MyGitRepo" -BranchName "main" -StartRef "v1.0" -EndRef "v2.0" -OutputPath "C:\Temp\Git_Output\tag_range_log.txt" # 日期范围示例 .\Get-GitCommitRange.ps1 -RepoPath "C:\MyGitRepo" -BranchName "main" -StartRef "8/17/2021" -EndRef "8/23/2021" -OutputPath "C:\Temp\Git_Output\date_range_log.txt" - 如果需要包含起始点提交,可将命令中的
$StartRef..$EndRef改为$StartRef...$EndRef。
内容的提问来源于stack exchange,提问作者TJunky
相关产品推荐
相关产品推荐

