首页 > 解决方案 > 需要一个正则表达式来从我的 Git 标记版本字符串中提取描述部分

问题描述

我目前有以下 PS 脚本来从 Git 标签中提取 SW 版本并将其集成到构建的程序集中。这适用于标签,例如v1.2.3并创建文件版本和产品版本,例如1.2.3.161.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 输出的破折号和属于描述的破折号。

标签: regexgitpowershellversion-control

解决方案


使用 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

推荐阅读