如何在我的PS脚本中获取Git commit哈希? [英] How can I get the Git commit hash in my PS script?
问题描述
我正在使用PowerShell脚本调用msbuild
,并将版本号传递给OctopusDeploy,如下所示:
I'm using a PowerShell script to call msbuild
and pass in a version number to OctopusDeploy like this:
msbuild "Xyz.sln" /t:Rebuild /p:Configuration=Release /p:RunOctoPack=true /p:OctopackPackageVersion=$versionNumber
...其中$ versionNumber在PS脚本中生成.我想做的是将Git commit哈希的前16个字符添加到版本字符串的末尾,这样它最终看起来像:
... where $versionNumber is generated in the PS script. What I want to do is add the first 16 characters of the Git commit hash to the end of the version string so it will end up looking like:
2.yyyyMMdd.HHmmss-git-6d34e44340f95c2a
我该怎么做?考虑到它们已经内置了Git支持,我是否可以让msbuild
或Visual Studio以某种方式返回当前的git commit哈希?
How can I do this? Can I get msbuild
or Visual Studio to return the current git commit hash somehow, considering they now have built-in Git support?
推荐答案
我最后所做的只是将Powershell脚本(文件NGit.dll
,Sharpen.dll
和ICSharpCode.SharpZipLib.dll
)旁边的束NGit
捆绑在一起,然后使用这样的代码生成带有git hash后缀的版本号:
What I did in the end was just bundle NGit
next to my Powershell script (files NGit.dll
, Sharpen.dll
, and ICSharpCode.SharpZipLib.dll
) then use some code like this to generate the version number with git hash suffixed:
[System.Reflection.Assembly]::LoadFrom("Ngit.dll") | Out-Null
[System.Reflection.Assembly]::LoadFrom("Sharpen.dll") | Out-Null
[System.Reflection.Assembly]::LoadFrom("ICSharpCode.SharpZipLib.dll") | Out-Null
# *** Git repo base path (should contain .sln file) ***
$repoPath = "C:\Path\To\Repo"
# *** OctopusDeploy API key for publishing ***
$octoApiKey = "API-[PublishKey]"
#######################################################
# *** Get and process current Git commit hash ***
$sharpenRepoPath = New-Object -TypeName Sharpen.FilePath -ArgumentList "$($repoPath)\.git"
$repoBuilder = New-Object -TypeName NGit.RepositoryBuilder
$repo = $repoBuilder.SetGitDir($sharpenRepoPath).Build()
$headHash = $repo.Resolve("HEAD").Name.Substring(0,12)
# *** Version when pushing to OctopusDeploy NuGet ***
$versionNumber = "2." + [datetime]::now.tostring("yyyyMMdd.HHmmss") + "-git-" + $headHash
# *** Pause before publish ****
Write-Host "About to publish to OctopusDeploy NuGet with version number:"
Write-Host " $($versionNumber)"
cmd /c pause
# *** OctopusDeploy build and push ***
msbuild "$repoPath\MySolution.sln" /t:Rebuild /p:Configuration=Release /p:RunOctoPack=true /p:OctopackPackageVersion=$versionNumber /p:OctoPackPublishPackageToHttp=https://my.nuget.server/nuget/packages /p:OctoPackPublishApiKey=$octoApiKey
这篇关于如何在我的PS脚本中获取Git commit哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!