c# - 检索用于 Jenkins 构建的程序集版本

标签 c# git visual-studio jenkins msbuild

工具

  • MSBuild v14

  • Visual Studio 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."'
        }
     }
}
}

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

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

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

用于编辑 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>

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% 

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

最佳答案

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

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

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

CALL FindAssemblyVersion .\Properties

git tag %VERSION% 
git push http://%gitCredentials%@url:port/repo.git %VERSION%

关于c# - 检索用于 Jenkins 构建的程序集版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49403770/

相关文章:

c# - 是否可以创建一个 C# Windows 服务来检测 Windows XP 上的新文件创建?

c# - 如何知道何时为表单显示消息框?

node.js - Gulp 将 Node 应用的 dist 文件夹部署到 Heroku

git - 如何防止跟踪的配置文件被 git 中的 merge 更改?

Git RPC 失败; curl 18 传输关闭,剩余读取数据未完成

visual-studio - 如何删除 Visual Studio 2019 IDE 中的垂直窗口分割?

c# - 按位或定义 SqlBulkCopyOptions?

c# - 如何使用谓词在 C# 中创建扩展方法

node.js - 将 mocha 与 resharper 一起使用

c# - 将文件位置集合添加到列表的正确方法是什么?