检索程序集版本以在 Jenkins 构建中使用

Sul*_*phy 5 c# git msbuild visual-studio jenkins

工具

  • MSBuild v14

  • 视觉工作室2013

  • 在 Windows Server 2012 上运行的 Jenkins v2.111

  • Git(本地文件服务器上的裸存储库)

  • Windows 批处理

我的目标

使用 MSBuild 构建 c# Visual Studio 项目,该项目从项目 AssemblyInfo.cs 中提取主要版本号和次要版本号,以供在生成期间使用。构建会生成类似 1.2.$BUILD_NUMBER 的内容,从而产生类似 1.2.121、1.2.122、1.2.123 等的内容。一旦用户选择“发布”构建,文件夹名称中具有正确版本的 clickonce 部署将被复制到其目标位置,并将标签应用于 Git 存储库。

管道示例

以下是我所做的“正在进行的工作”。欢迎提出任何改进建议。对于那些想知道为什么我将代码库复制到临时文件夹的人来说。我在 Jenkins 中使用多分支作业,自动生成的文件夹非常长!这给我带来了一些错误,比如我的文件名、项目名或两者都太长(因为整个路径超过了 255 个左右的字符长度)。因此,解决这个问题的唯一方法是复制内容,以便构建和发布能够正常进行。

pipeline {
agent none
stages {
    stage ('Checkout'){
    agent any
        steps 
        {
            checkout scm
        }
    }

    stage ('Nuget Restore'){
    agent any
    steps
    {
        bat 'nuget restore "%WORKSPACE%\\src\\Test\\MyTestSolution.sln"'
    }
    }

    stage('Build Debug') {
    agent any
        steps 
        {
            bat "xcopy %WORKSPACE%\\src\\* /ey d:\\temp\\"
            bat "\"${tool 'MSBuild'}\" d:\\temp\\Test\\MyTestSolution.sln /p:Configuration=Debug /target:publish /property:PublishUrl=d:\\temp\\ /p:OutputPath=d:\\temp\\build\\ /p:GenerateBootstrapperSdkPath=\"C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v8.1A\\Bootstrapper\" /p:VersionAssembly=1.0.$BUILD_NUMBER /p:ApplicationVersion=1.0.$BUILD_NUMBER"         
        }
    }


     stage('Deploy to Dev'){
     agent none
       steps {
            script {
                env.DEPLOY_TO_DEV = input message: 'Deploy to dev?',
                parameters: [choice(name: 'Deploy to dev staging area?', choices: 'no\nyes', description: 'Choose "yes" if you want to deploy this build')]
            }
        }
     }

     stage ('Deploying to Dev')
     {
     agent any
        when {
            environment name: 'DEPLOY_TO_DEV', value: 'yes'
        }
        steps {
            echo 'Deploying debug build...'

       }

     }

     stage ('Git tagging')
     {
     agent any
        steps 
        {
        bat 'd:\\BuildTargets\\TagGit.bat %WORKSPACE% master v1.0.%BUILD_NUMBER%.0(DEV) "DEV: Build deployed."'
        }
     }
}
}
Run Code Online (Sandbox Code Playgroud)

目前我已经在上面的脚本中对主要版本和次要版本进行了硬编码。我想从 AssemblyInfo.cs 中提取这些值,以便开发人员可以从那里控制它,而无需编辑 Jenkinsfile。有什么建议/最佳实践来实现这一目标吗?

因为我正在为 winforms 应用程序进行 clickonce 部署,所以我必须使用 MSBuild 的 VersionAssembly 和 ApplicationVersion 开关来传递版本。这似乎有助于在 MSBuild 发布文件时正确标记文件夹。我的设置中是否遗漏了一些可以取消这些开关并使生活变得更简单的东西?

我的管道中的最后一个操作是触发 .bat 文件以将标签添加回存储库的 master 分支。这是我需要使管道脚本可以访问主要版本和次要版本的另一个原因。

用于编辑 AssemblyInfo.cs 的 MSBuild 目标

此代码取自此处:http://www.lionhack.com/2014/02/13/msbuild-override- assembly-version/

<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
   <PropertyGroup>
    <CompileDependsOn>
        CommonBuildDefineModifiedAssemblyVersion;
        $(CompileDependsOn);
    </CompileDependsOn>
</PropertyGroup>
<Target Name="CommonBuildDefineModifiedAssemblyVersion" Condition="'$(VersionAssembly)' != ''">
    <!-- Find AssemblyInfo.cs or AssemblyInfo.vb in the "Compile" Items. Remove it from "Compile" Items because we will use a modified version instead. -->
    <ItemGroup>
        <OriginalAssemblyInfo Include="@(Compile)" Condition="%(Filename) == 'AssemblyInfo' And (%(Extension) == '.vb' Or %(Extension) == '.cs')" />
        <Compile Remove="**/AssemblyInfo.vb" />
        <Compile Remove="**/AssemblyInfo.cs" />
    </ItemGroup>
    <!-- Copy the original AssemblyInfo.cs/.vb to obj\ folder, i.e. $(IntermediateOutputPath). The copied filepath is saved into @(ModifiedAssemblyInfo) Item. -->
    <Copy SourceFiles="@(OriginalAssemblyInfo)"
          DestinationFiles="@(OriginalAssemblyInfo->'$(IntermediateOutputPath)%(Identity)')">
        <Output TaskParameter="DestinationFiles" ItemName="ModifiedAssemblyInfo"/>
    </Copy>
    <!-- Replace the version bit (in AssemblyVersion and AssemblyFileVersion attributes) using regular expression. Use the defined property: $(VersionAssembly). -->
    <Message Text="Setting AssemblyVersion to $(VersionAssembly)" />
    <RegexUpdateFile Files="@(ModifiedAssemblyInfo)"
                Regex="Version\(&quot;(\d+)\.(\d+)(\.(\d+)\.(\d+)|\.*)&quot;\)"
                ReplacementText="Version(&quot;$(VersionAssembly)&quot;)"
                />
    <!-- Include the modified AssemblyInfo.cs/.vb file in "Compile" items (instead of the original). -->
    <ItemGroup>
        <Compile Include="@(ModifiedAssemblyInfo)" />
    </ItemGroup>
</Target>
<UsingTask TaskName="RegexUpdateFile" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
    <ParameterGroup>
        <Files ParameterType="Microsoft.Build.Framework.ITaskItem[]" Required="true" />
        <Regex ParameterType="System.String" Required="true" />
        <ReplacementText ParameterType="System.String" Required="true" />
    </ParameterGroup>
    <Task>
        <Reference Include="System.Core" />
        <Using Namespace="System" />
        <Using Namespace="System.IO" />
        <Using Namespace="System.Text.RegularExpressions" />
        <Using Namespace="Microsoft.Build.Framework" />
        <Using Namespace="Microsoft.Build.Utilities" />
        <Code Type="Fragment" Language="cs">
            <![CDATA[
            try {
                var rx = new System.Text.RegularExpressions.Regex(this.Regex);
                for (int i = 0; i < Files.Length; ++i)
                {
                    var path = Files[i].GetMetadata("FullPath");
                    if (!File.Exists(path)) continue;

                    var txt = File.ReadAllText(path);
                    txt = rx.Replace(txt, this.ReplacementText);
                    File.WriteAllText(path, txt);
                }
                return true;
            }
            catch (Exception ex) {
                Log.LogErrorFromException(ex);
                return false;
            }
        ]]>
        </Code>
    </Task>
</UsingTask>

</Project>
Run Code Online (Sandbox Code Playgroud)

Git 标记

该bat文件被启动并传递用于创建标签并将其推送到定义的存储库的值。

echo off
set gitPath=%1
set gitBranchName=%2
set gitTag=%3
set gitMessage=%4
@echo on
@echo Adding tag to %gitBranchName% branch.
@echo Working at path %gitPath%
@echo Tagging with %gitTag%
@echo Using commit message: %gitMessage%

d:
cd %gitPath%
git checkout %gitBranchName%
git pull
git tag -a %gitTag% -m %gitMessage%
git push origin %gitBranchName% %gitTag% 
Run Code Online (Sandbox Code Playgroud)

如果有任何其他金块可以帮助简化或改进整个工作流程,我们也欢迎!

Ony*_*din 3

我最近遇到了同样的问题,我通过创建 Windows 脚本解决了这个问题。

for /f delims^=^"^ tokens^=2 %%i in ('findstr "AssemblyFileVersion" %1\\AssemblyFile.cs') DO SET VERSION=%%i
Run Code Online (Sandbox Code Playgroud)

此脚本从 AssemblyInfo.cs 中提取版本号并将其放入变量中,以便稍后可以使用它来标记提交(尽管在同一步骤中):

CALL FindAssemblyVersion .\Properties

git tag %VERSION% 
git push http://%gitCredentials%@url:port/repo.git %VERSION%
Run Code Online (Sandbox Code Playgroud)