如何替换 azure-pipelines.yaml 中的变量字符串?

Mac*_*cke 7 string azure-pipelines

我想设置VersionSuffixfromBuild.Sourcebranch但这失败了,因为SourceBranchcontains refs/heads/<branchname>

- task: DotNetCoreCLI@2
  condition: succeeded()
  inputs: 
    command: 'pack'
    versioningScheme: ByPrereleaseNumber
    majorVersion: '0' 
    minorVersion: '1' 
    patchVersion: '1' 
    packTimezone: 'utc' 
    buildProperties: VersionSuffix=$(Build.SourceBranch)-$(Build.BuildNumber)
Run Code Online (Sandbox Code Playgroud)

我只想在 中添加.Replace('/','_')一些类似的语句$(Build.SourceBranch),但在表达式语法中找不到任何关于如何执行此操作的内容。

发送另一个字符串(即VersionSuffixRaw)并在 .csproj 中创建VersionSuffixwith不起作用String.Replace;由于某种原因,它只是被忽略了。

注意:有Build.SourceBranchNamewhich 具有分支名称的最后一部分,因此如果SourceBranchis refs/heads/feature/fooSourceBranchName将是foo。但是,分支 namdfeature/JIRA-123_foo_unittest将不起作用,因为 _ 在版本字符串中无效。

Yac*_*uzo 11

对于通过搜索发现这一点的其他人,现在有一个替换表达式:MS Doc

大致像这样用连字符替换下划线:

variables:      
  suffix: $[replace(variables['build.sourcebranchname'], '_', '-')]
Run Code Online (Sandbox Code Playgroud)

  • 除了条件之外,我无法让它发挥作用。必须使用这样的模板表达式语法:`${{replace(variables['build.sourcebranchname'],'_','-')}}`否则我会在管道中遇到错误(尽管代码实际上有效,并进行了替换,它仍然给出错误)在我的例子中,我也使用我自己的变量,而不是“内置”变量之一。 (6认同)
  • 何时使用表达式或模板语法非常挑剔。取决于您在何处声明要替换的变量以及在何处进行替换。我的工作变量中有这个怪物:$[replace('${{ lower(variables['build.sourcebranchname'])}}', '_', '-')]。 (3认同)

Lev*_*SFT 5

正如@4c74356b41 指出的那样。您可以尝试添加 powershell 脚本来替换 yaml 构建定义中的 Build.SourceBranch。并将新的 sourcebranch 输出到新变量。然后您可以在接下来的步骤中使用新变量。

下面只是一个简单的例子。单击此处了解更多信息

1、将SourceBranch的“/”替换为“_”并将替换值设置为变量newSourceBranch

- powershell: |
    $newbranch = "$(Build.SourceBranch)" -replace "/", "_"  
    echo "##vso[task.setvariable variable=newSourceBranch;isOutput=true]$newbranch"
  name: branchsetter 
Run Code Online (Sandbox Code Playgroud)

2、按以下步骤使用newSourceBranch。

- powershell: |
    write-host "$(branchsetter.newSourceBranch)"
Run Code Online (Sandbox Code Playgroud)