我如何从VS / msbuild中提取Git commit hash? [英] How can I extract Git commit hash from VS/msbuild?

查看:409
本文介绍了我如何从VS / msbuild中提取Git commit hash?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

开发人员在他们的机器上运行一个PowerShell脚本,通过MSBuild将各种Nuget包发布到OctopusDeploy。

这个场景是:

我们希望将当前的git commit的哈希(Git repo的基础与 .sln 目录相同)作为生成版本号的一部分。要做到这一点,我们大概需要提取当前提交的散列并将其插入到版本号字符串中,然后我们将其作为参数传递给MSBuild。

所以问题是,如何我们可以从MSBuild或Visual Studio中获得这个吗?不能保证开发者将安装Git命令行,但他们至少会安装VS2015,并且已经内置了Git支持,所以你会认为有一些方法可以从中获得最新的Git commit的哈希值?如果您进入Visual Studio GUI并查看源代码管理部分,您可以看到散列。



是否有一些命令行工具与Visual Studio 2015或更高版本捆绑在一起这将返回当前的Git提交的散列?

解决方案

您的要求不依赖于 git.exe 使这个变得复杂。
然而,如果你想使用Visual Studio使用的库LibGit2Sharp并进行Visual Studio集成,你可以像这样做一些疯狂的事情。



添加一个新的目标到你的项目文件。我假设你正在使用C#,所以在将它添加到你的csproj之后



< Import Project =$(MSBuildToolsPath)\Microsoft。 CSharp.targets/>


$ b

 < PropertyGroup> 
< CodeFile> $(MSBuildProjectDirectory)\HelloGit.cs< / CodeFile>
< CodeFileText> $([System.IO.File] :: ReadAllText($(CodeFile)))< / CodeFileText>
< CodeFileText> $([MSBuild] :: Unescape($(CodeFileText)))< / CodeFileText>
< / PropertyGroup>

< UsingTask TaskName =HelloGitTaskFactory =CodeTaskFactoryAssemblyFile =$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll>
< ParameterGroup>
< Sha1 ParameterType =System.StringRequired =FalseOutput =True/>
< Repository ParameterType =System.StringRequired =TrueOutput =False/>
< / ParameterGroup>
<任务>
< Reference Include =System.Xml,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089/>
<引用包含=C:\程序文件(x86)\ Microsoft Visual Studio 14.0 \ Common \ IDE \ CommonExtensions \ Microsoft \ TeamFoundation \ Team Explorer \LibGit2Sharp.dll />
< Using Namespace =System/>
< Using Namespace =System.IO/>
< Code Type =ClassLanguage =cs>
$(CodeFileText)
< / Code>
< /任务>
< / UsingTask>

<目标名称=RunTaskAfterTargets =BeforeBuild>

< HelloGit Repository =$(MSBuildProjectDirectory)>
< Output TaskParameter =Sha1PropertyName =CommitId/>
< / HelloGit>
< Warning Text =您的提交是:$(CommitId)/>

< / Target>

这样做是在当前项目目录中查找HelloGit.cs。它的内容看起来像这样...

你可以用一个内联代码任务来完成这个任务(例如嵌入的C#内部的XML),但是由于任务很长,我想要用VS编辑它作为一个单独的文件。


$ b

  using System; 
使用System.Collections.Generic;
使用System.Linq;
使用System.Reflection;
使用System.Runtime.CompilerServices;
使用System.Text;
使用LibGit2Sharp;
使用Microsoft.Build.Framework;
使用Microsoft.Build.Utilities;


命名空间GitIntrospection {
public class HelloGit:Task {
public override bool Execute(){
AppDomain.CurrentDomain.AssemblyResolve + =(sender, args)=> {
if(args.Name.Contains(LibGit2Sharp)){
return Assembly.LoadFrom(C:\\ Program Files(x86)\\ Microsoft Visual Studio 14.0 \ \Common7\\IDE\\CommonExtensions\\\ Microsoft\\TeamFoundation\\Team Explorer\\LibGit2Sharp.dll);
}
返回null;
};

GetCommit();

return!Log.HasLoggedErrors;
}

// [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)]
private void GetCommit(){
Repository repository = new Repository(Repository);

this.Sha1 = repository.Commits.First()。Id.Sha;
}

[输出]
公共字符串Sha1 {get;组; }

[必需的]
public string Repository {get;组; }
}
}

现在,当您构建项目时,被提取并记录为警告。这适用于Visual Studio和MS Build内部。



适用于命令行

在Visual Studio中工作
< img src =https://i.stack.imgur.com/jV2F3.pngalt =在Visual Studio中工作>



结果甚至似乎同意 git.exe ...这很方便


备选1
您可以使用 git.exe < Exec> 任务!



选择2
您可以使用PowerShell来加载LibGit2Sharp组件bly并调用相同的方法。

The scenario is:

Developers are running a PowerShell script from their machines to publish various Nuget packages to OctopusDeploy via MSBuild. We'd like to make the current git commit's hash (the base of the Git repo is the same as the .sln directory) part of the generated version number. To do this we presumably need to extract the current commit's hash and plug it into the version number string we then pass into MSBuild as a parameter.

So the question is, how can we get this from MSBuild or Visual Studio? There's no guarantee that a developer will have Git commandline installed, but they will have at least VS2015 installed and that has Git support built-in so you'd think there would be some way to get the latest Git commit's hash from this? You could see the hash if you went into the Visual Studio GUI and looked in the source control section.

Is there some commandline tool that comes bundled with Visual Studio 2015 or later that will return the current Git commit's hash?

解决方案

Your requirement to not depend on git.exe makes this complicated. However if you want to use the library that Visual Studio uses, LibGit2Sharp and have Visual Studio integration you can do something crazy like this.

Add a new target to your project file. I'm assuming you are using C# so add it to your csproj after

<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />

  <PropertyGroup>
    <CodeFile>$(MSBuildProjectDirectory)\HelloGit.cs</CodeFile>
    <CodeFileText>$([System.IO.File]::ReadAllText("$(CodeFile)"))</CodeFileText>
    <CodeFileText>$([MSBuild]::Unescape("$(CodeFileText)"))</CodeFileText>
  </PropertyGroup>

  <UsingTask TaskName="HelloGit" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll">
    <ParameterGroup>
      <Sha1 ParameterType="System.String" Required="False" Output="True" />
      <Repository ParameterType="System.String" Required="True" Output="False" />
    </ParameterGroup>
    <Task>
      <Reference Include="System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      <Reference Include="C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\LibGit2Sharp.dll" />
      <Using Namespace="System" />
      <Using Namespace="System.IO" />
      <Code Type="Class" Language="cs">
        $(CodeFileText)
      </Code>
    </Task>
  </UsingTask>

  <Target Name="RunTask" AfterTargets="BeforeBuild">

    <HelloGit Repository="$(MSBuildProjectDirectory)">
      <Output TaskParameter="Sha1" PropertyName="CommitId" />
    </HelloGit>
    <Warning Text="Your commit is: $(CommitId)" />

  </Target>

What this does is look in the current project directory for "HelloGit.cs". The contents of which look like this...

You could do this with an inline code task (e.g. embedded C# inside XML) but since the task is quite long I wanted to edit it in VS Code as a separate file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using LibGit2Sharp;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;


namespace GitIntrospection {
    public class HelloGit : Task {
        public override bool Execute() {
            AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => {
                if (args.Name.Contains("LibGit2Sharp")) {
                    return Assembly.LoadFrom("C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\IDE\\CommonExtensions\\Microsoft\\TeamFoundation\\Team Explorer\\LibGit2Sharp.dll");
                }
                return null;
            };

            GetCommit();

            return !Log.HasLoggedErrors;
        }

        // [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)]
        private void GetCommit() {
            Repository repository = new Repository(Repository);

            this.Sha1 = repository.Commits.First().Id.Sha;
        }

        [Output]
        public string Sha1 { get; set; }

        [Required]
        public string Repository { get; set; }
    }
}

Now when you build your project the latest commit will be extracted and logged as a warning. This works both inside Visual Studio and inside MS Build.

Works on the command line

Works inside Visual Studio

The results even seem to agree with git.exe... that's handy

Alternative 1 You could just use git.exe and an <Exec> task!

Alternative 2 You could use PowerShell to load the LibGit2Sharp assembly and call the same methods.

这篇关于我如何从VS / msbuild中提取Git commit hash?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆