regex - 需要一个正则表达式来从我的 Git 标记版本字符串中提取描述部分
问题描述
我目前有以下 PS 脚本来从 Git 标签中提取 SW 版本并将其集成到构建的程序集中。这适用于标签,例如v1.2.3
并创建文件版本和产品版本,例如1.2.3.16
和 1.2.3.16-13b05b79
# Get version info from Git. For example: v1.2.3-45-g6789abc
$gitVersion = git describe --match "v[0-9]*" --long --always --dirty;
# Get name of current branch
$gitBranch = git rev-parse --abbrev-ref HEAD;
# Write Git information to version.txt
$versionFile = $args[1] + "\version.txt";
"version: " + $gitVersion > $versionFile;
"branch: " + $gitBranch >> $versionFile;
# Parse Git version info into semantic pieces
$gitVersion -match '[v](.*)-(\d+)-[g](.+)$';
$gitTag = $Matches[1];
$gitCount = $Matches[2];
$gitSHA1 = $Matches[3];
# Define file variables
$assemblyFile = $args[0] + "\Properties\AssemblyInfo.cs";
# Read template file, overwrite place holders with git version info
$newAssemblyContent = Get-Content $assemblyFile |
%{$_ -replace '\$FILEVERSION\$', ($gitTag + "." + $gitCount) } |
%{$_ -replace '\$INFOVERSION\$', ($gitTag + "." + $gitCount + "-" + $gitSHA1) };
echo "Injecting Git Version Info to AssemblyInfo.cs"
$newAssemblyContent > $assemblyFile;
我现在想在这个脚本中扩展正则表达式,这样我就可以使用带有简短描述的标签,例如v1.2.3-description
,其中description
可以是可变长度的。理想情况下,正则表达式应该允许在描述中使用破折号,这样它v1.2.3-description-with-dashes
也是有效的以及 Git 标签中允许的任何其他字符。
对我来说这很困难(我已经尝试过)是该git describe
命令将其输出为v1.2.3-description-with-dashes-16
,我如何区分属于 Git 输出的破折号和属于描述的破折号。
解决方案
使用 RegEx(并使用新示例),您可以执行以下操作:
$gitVersion -match '(?<tag>v\d+\.\d+\.\d+)(?:-?(?<description>\D+)?)(?:-?(?<count>\d+)?)(?:-?(?<sha1>gd[0-9a-f]+))(?:-?(?<dirty>.+)?)'
$gitTag = $Matches['tag']
$gitDescription = ($Matches['description']).Trim("-")
$gitCount = if($Matches['count']) { $Matches['count'] } else { 1 } # if no count is found, we assume 1 ??
$gitSHA1 = $Matches['sha1']
$gitDirty = $Matches['dirty']
试验结果:
teststring tag description count sha1 dirty --------------------------------------------------- ------- ------------------------- ----- --------- ----- v1.2.3-123-gd9b5a775-dirty v1.2.3 123 gd9b5a775 dirty v1.2.3-description-123-gd9b5a775-dirty v1.2.3 description- 123 gd9b5a775 dirty v1.2.3-description-with-dashes-123-gd9b5a775-dirty v1.2.3 description-with-dashes- 123 gd9b5a775 dirty v1.2.3-description-with-dashes-123-gd9b5a775 v1.2.3 description-with-dashes- 123 gd9b5a775 v1.2.3-description-with-dashes-gd9b5a775 v1.2.3 description-with-dashes- gd9b5a775 v1.2.3-45-gd9b5a775 v1.2.3 45 gd9b5a775 v1.2.3-gd9b5a775 v1.2.3 gd9b5a775
推荐阅读
- android - 颤振仅重建地图上当前的位置点(setState)
- r - 如何使用 Rmarkdown 防止 pdf 输出中的连字符?
- ios - 如何在 iOS/Swift/Xcode 中播放一次抽签动画然后从帧循环到帧?
- c++ - crypto++ 可以同时使用 [Private]key 对象[在多线程中]
- .net - Nuget 项目上的黄色三角形?无法解析此引用。找不到程序集“NHibernate”
- javascript - 尝试使用 Tempermonkey 随机更改 Steam 背景,总是出现“Parsing Error: Unexpected Token”错误
- html - 特定的 HTML 标题属性值使元素消失
- javascript - 输入数据后我的表格显示不正确
- javascript - fullpage.js - Fp-auto-height 中间部分在单击anchor 和 moveTo() 最后一部分时没有达到其实际高度
- node.js - 如何获得相关的 package.json 依赖项以在 Windows 上使用 AWS 的 sam build 命令?