• Stars
    star
    513
  • Rank 86,178 (Top 2 %)
  • Language Pascal
  • License
    MIT License
  • Created over 9 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Git and SemVer Info from MSBuild, C# and VB

Icon GitInfo

Git Info from MSBuild, C# and VB

A fresh and transparent approach to Git information retrieval from MSBuild and Code without using any custom tasks or compiled code and tools, obscure settings, format strings, etc.

Latest version Downloads License Build status

Usage

After installing via NuGet:

PM> Install-Package GitInfo

By default, if the containing project is a C#, F# or VB project, a compile-time generated source file will contain all the git information and can be accessed from anywhere within the assembly, as constants in a ThisAssembly (partial) class and its nested Git static class:

Console.WriteLine(ThisAssembly.Git.Commit);

NOTE: you may need to close and reopen the solution in order for Visual Studio to refresh intellisense and show the ThisAssembly type the first time after installing the package.

By default, GitInfo will also set $(Version) and $(PackageVersion) which the .NET SDK uses for deriving the AssemblyInfo, FileVersion and InformationalVersion values, as well as for packing. This default version is formatted from the following populated MSBuild properties: $(GitSemVerMajor).$(GitSemVerMinor).$(GitSemVerPatch)$(GitSemVerDashLabel)+$(GitBranch).$(GitCommit).

So, straight after install and build/pack, you will get some versioning in place :).

Alternatively, you can opt-out of this default versioning by setting GitVersion=false in your project file, if you want to just leverage the Git information and/or version properties/constants yourself:

<PropertyGroup>
    <GitVersion>false</GitVersion>
</PropertyGroup>

This allows you to use the provided constants to build any versioning attributes you want, with whatever information you want, without resorting to settings, format strings or anything, just plain code:

C#:

[assembly: AssemblyVersion (ThisAssembly.Git.BaseVersion.Major + "." + ThisAssembly.Git.BaseVersion.Minor + "." + ThisAssembly.Git.BaseVersion.Patch)]

[assembly: AssemblyFileVersion (ThisAssembly.Git.SemVer.Major + "." + ThisAssembly.Git.SemVer.Minor + "." + ThisAssembly.Git.SemVer.Patch)]

[assembly: AssemblyInformationalVersion (
	ThisAssembly.Git.SemVer.Major + "." + 
	ThisAssembly.Git.SemVer.Minor + "." + 
	ThisAssembly.Git.Commits + "-" + 
	ThisAssembly.Git.Branch + "+" + 
	ThisAssembly.Git.Commit)]

F#:

module AssemblyInfo

open System.Reflection

[<assembly: AssemblyVersion (ThisAssembly.Git.BaseVersion.Major + "." + ThisAssembly.Git.BaseVersion.Minor + "." + ThisAssembly.Git.BaseVersion.Patch)>]

[<assembly: AssemblyFileVersion (ThisAssembly.Git.SemVer.Major + "." + ThisAssembly.Git.SemVer.Minor + "." + ThisAssembly.Git.SemVer.Patch)>]

[<assembly: AssemblyInformationalVersion (
    ThisAssembly.Git.SemVer.Major + "." + 
    ThisAssembly.Git.SemVer.Minor + "." + 
    ThisAssembly.Git.Commits + "-" + 
    ThisAssembly.Git.Branch + "+" + 
    ThisAssembly.Git.Commit)>]

do ()

VB:

<Assembly: AssemblyVersion(ThisAssembly.Git.BaseVersion.Major + "." + ThisAssembly.Git.BaseVersion.Minor + "." + ThisAssembly.Git.BaseVersion.Patch)>
<Assembly: AssemblyFileVersion(ThisAssembly.Git.SemVer.Major + "." + ThisAssembly.Git.SemVer.Minor + "." + ThisAssembly.Git.SemVer.Patch)>
<Assembly: AssemblyInformationalVersion(
    ThisAssembly.Git.SemVer.Major + "." +
    ThisAssembly.Git.SemVer.Minor + "." +
    ThisAssembly.Git.Commits + "-" +
    ThisAssembly.Git.Branch + "+" +
    ThisAssembly.Git.Commit)>

NOTE: when generating your own assembly version attributes, you will need to turn off the corresponding assembly version attribute generation from the .NET SDK, by setting the relevant properties to false: GenerateAssemblyVersionAttribute, GenerateAssemblyFileVersionAttribute and GenerateAssemblyInformationalVersionAttribute.

MSBuild:

<!-- Just edit .csproj file -->  
<PropertyGroup>
    <!-- We'll do our own versioning -->
    <GitVersion>false</GitVersion>
</PropertyGroup>
<ItemGroup>
  <PackageReference Include="GitInfo" PrivateAssets="all" />
</ItemGroup>

<Target Name="PopulateInfo" DependsOnTargets="GitVersion" BeforeTargets="GetAssemblyVersion;GenerateNuspec;GetPackageContents">
    <PropertyGroup>
      <Version>$(GitSemVerMajor).$(GitSemVerMinor).$(GitSemVerPatch)$(GitSemVerDashLabel)+$(GitBranch).$(GitCommit)</Version>
      <PackageVersion>$(Version)</PackageVersion>
      
      <RepositoryBranch>$(GitBranch)</RepositoryBranch>
      <RepositoryCommit>$(GitCommit)</RepositoryCommit>
      <SourceRevisionId>$(GitBranch) $(GitCommit)</SourceRevisionId>
    </PropertyGroup>
</Target>

NOTE: because the provided properties are populated via targets that need to run before they are available, you cannot use the GitInfo-provided properties in a PropertyGroup at the project level. You can only use them from within a target that in turn depends on the relevant target from GitInfo (typically, GitVersion as shown above, if you consume the SemVer properties).

Because this information is readily available whenever you build the project, you never depend on CI build scripts that generate versions for you, and you can always compile locally exactly the same version of an assembly that was built by a CI server.

You can read more about this project at the GitInfo announcement blog post.

Details

Exposes the following information for use directly from any MSBuild target that depends on the GitInfo target:

  $(GitRepositoryUrl)
  $(GitBranch)
  $(GitCommit)
  $(GitCommitDate)
  $(GitCommits)
  $(GitTag)
  $(GitBaseTag)
  $(GitBaseVersionMajor)
  $(GitBaseVersionMinor)
  $(GitBaseVersionPatch)
  $(GitSemVerMajor)
  $(GitSemVerMinor)
  $(GitSemVerPatch)
  $(GitSemVerLabel)
  $(GitSemVerDashLabel)
  $(GitSemVerSource)
  $(GitIsDirty)

For C#, F# and VB, constants are generated too so that the same information can be accessed from code:

  ThisAssembly.Git.RepositoryUrl
  ThisAssembly.Git.Branch
  ThisAssembly.Git.Commit
  ThisAssembly.Git.Commits
  ThisAssembly.Git.Tag
  ThisAssembly.Git.BaseTag
  ThisAssembly.Git.BaseVersion.Major
  ThisAssembly.Git.BaseVersion.Minor
  ThisAssembly.Git.BaseVersion.Patch
  ThisAssembly.Git.SemVer.Major
  ThisAssembly.Git.SemVer.Minor
  ThisAssembly.Git.SemVer.Patch
  ThisAssembly.Git.SemVer.Label
  ThisAssembly.Git.SemVer.DashLabel
  ThisAssembly.Git.SemVer.Source
  ThisAssembly.Git.IsDirty

Available MSBuild properties to customize the behavior:

  $(GitVersion): set to 'false' to prevent setting Version 
                 and PackageVersion.

  $(GitThisAssembly): set to 'false' to prevent assembly 
                      metadata and constants generation.

  $(GitThisAssemblyMetadata): set to 'false' to prevent assembly 
                              metadata generation only. Defaults 
                              to 'false'. If 'true', it will also 
                              provide assembly metadata attributes 
                              for each of the populated values.

  $(ThisAssemblyNamespace): allows overriding the namespace
                            for the ThisAssembly class.
                            Defaults to the global namespace.

  $(GitRemote): name of remote to get repository url for.
                Defaults to 'origin'.

  $(GitDefaultBranch): determines the base branch used to 
                       calculate commits on top of current branch.
                       Defaults to 'main'.

  $(GitVersionFile): determines the name of a file in the Git 
                     repository root used to provide the base 
                     version info.
                     Defaults to 'GitInfo.txt'.

  $(GitInfoReportImportance): allows rendering all the retrieved
                              git information with the specified
                              message importance ('high', 
                              'normal' or 'low').
                              Defaults to 'low'.

  $(GitIgnoreBranchVersion) and $(GitIgnoreTagVersion): determines 
                            whether the branch and tags (if any) 
                            will be used to find a base version.
                            Defaults to empty value (no ignoring).

  $(GitSkipCache): whether to cache the Git information determined
           in a previous build in a GitInfo.cache for
           performance reasons.
           Defaults to empty value (no ignoring).

  $(GitCachePath): where to cache the determined Git information
				   gives the chance to use a shared location
				   for different projects. this can improve
				   the overall build time.
				   has to end with a path seperator
				   Defaults to empty value ('$(IntermediateOutputPath)').

  $(GitNameRevOptions): Options passed to git name-rev when finding
              a branch name for the current commit (Detached head). The default is
              '--refs=refs/heads/* --no-undefined --always'
              meaning branch names only, falling back to commit hash.
              For legacy behavior where $(GitBranch) for detached head
              can also be a tag name, use '--refs=refs/*'.
              Refs can be included and excluded, see git name-rev docs.

  $(GitTagRegex): Regular expression used with git describe to filter the tags 
                  to consider for base version lookup.
                  Defaults to * (all)
           
  $(GitBaseVersionRegex): Regular expression used to match and validate valid base versions
                          in branch, tag or file sources. By default, matches any string that 
                          *ends* in a valid SemVer2 string.
                          Defaults to 'v?(?<MAJOR>\d+)\.(?<MINOR>\d+)\.(?<PATCH>\d+)(?:\-(?<LABEL>[\dA-Za-z\-\.]+))?$|^(?<LABEL>[\dA-Za-z\-\.]+)\-v?(?<MAJOR>\d+)\.(?<MINOR>\d+)\.(?<PATCH>\d+)$'

Goals

  • No compiled code or tools -> 100% transparency
  • Trivially added/installed via a NuGet package
  • No format strings or settings to learn
  • Simple well-structured .targets file with plain MSBuild and no custom tasks
  • Optional embedding of Git info in assembly metadata
  • Optional use of Git info to build arbitrary assembly/file version information, both in C# as well as VB.
  • Trivially modified/improved generated code by just adjusting a C# or F# or VB template included in the NuGet package
  • 100% incremental build-friendly and high-performing (all proper Inputs/Outputs in place, smart caching of Git info, etc.)

Sponsors

Clarius Org Christian Findlay C. Augusto Proiete Kirill Osenkov MFB Technologies, Inc. SandRock Eric C Andy Gocke

Sponsor this project  

Learn more about GitHub Sponsors

More Repositories

1

moq

The most popular and friendly mocking framework for .NET
C#
5,709
star
2

ThisAssembly

Exposes project and assembly level information as constants in the ThisAssembly class using source generators powered by Roslyn.
C#
418
star
3

SmallSharp

Create, edit and run multiple C# top-level programs in the same project by just selecting the startup program from the start button.
C#
279
star
4

nugetizer

A simple to understand packing model for authoring NuGet packages
C#
253
star
5

avatar

A modern compile-time generated interception/proxy library
C#
139
star
6

NuDoq

A standalone API to read .NET XML documentation files and optionally augment it with reflection information.
C#
105
star
7

dotnet-file

Download, update and sync loose files from URLs
C#
52
star
8

dotnet-vs

A global tool for managing Visual Studio installations
C#
49
star
9

DependencyInjection.Attributed

Provides compile-time discovery and code generation of service registrations from attributed types
C#
36
star
10

CloudActors

An opinionated, simplified and uniform Cloud Native actors' library that integrates with Microsoft Orleans.
C#
33
star
11

RxFree

An ultra-lightweight Rx source-only nuget to avoid depending on the full System.Reactive for IObservable<T> producers
C#
32
star
12

SponsorLink

SponsorLink: an attempt at OSS sustainability
C#
31
star
13

xunit.assemblyfixture

Provides per-assembly fixture state support for xunit
C#
24
star
14

WebSocketPipe

System.IO.Pipelines API adapter for System.Net.WebSockets
C#
24
star
15

Merq

Internal application architecture via command and event messages
C#
23
star
16

TableStorage

Repository pattern with POCO object support for storing to Azure / Cosmos DB Table Storage
C#
21
star
17

Injector

Allows injecting .NET code into another Windows process
C++
12
star
18

WebSocketeer

High-performance intuitive API for Azure Web PubSub protobuf subprotocol
C#
11
star
19

xunit.vsix

Xunit for creating VSIX integration tests
C#
10
star
20

dotnet-tor

A .NET cross-platform CLI app that uses TorSharp to run a local proxy
C#
10
star
21

oss

Basic repo configuration for my OSS projects
SCSS
10
star
22

azdo

Home for azdo.io and accompanying linkinator source
C#
9
star
23

Dynamically

Instantiate record types from dynamic data with compatible structural shapes, in-memory with no reflection or serialization, via compile-time source generators.
C#
9
star
24

Web

XLinq to Web
HTML
8
star
25

chromium

Run a portable Chromium using dotnet 6+ and nuget.
C#
8
star
26

WebSocketChannel

High-performance System.Threading.Channels API adapter for System.Net.WebSockets
C#
8
star
27

dotnet-evergreen

A dotnet tool runner that automatically updates the tool package before and while running it
C#
6
star
28

CredentialManager

Packages the Git Credential Manager cross-platform implementation for Windows, macOS and Linux for use as a generic credential manager.
C#
6
star
29

dotnet-gcm

A dotnet global tool to interface with the Git Credentials Manager Core
C#
5
star
30

dotnet-eventgrid

Azure Function app and accompanying dotnet global tool to monitor Azure EventGrid streams in real-time.
C#
5
star
31

System.Diagnostics.Tracer

An improved API on top of System.Diagnostics
C#
5
star
32

json

JsonPeek and JsonPoke tasks implementations
C#
5
star
33

dotnet-stop

Gracefully stops processes by sending them SIGINT (Ctrl+C) in a cross platform way.
C#
4
star
34

nosayudamos.org

C#
3
star
35

catbag

A repository of loose helpers, base clases and assorted code
C#
3
star
36

scraper

A web scraping app that runs on Azure Container Apps
C#
3
star
37

actions-bot

A GitHub Action that sets bot secrets as git defaults if present
3
star
38

tsh

C#
2
star
39

cloudy

Spike on cloud-first architecture for apps, heavily event-driven
C#
2
star
40

PackageReferenceCleaner

Clean your PackageReferences with PrivateAssets=all into beautiful one-liners, automatically
C#
2
star
41

shields

Custom endpoints for custom badges using https://shields.io/endpoint
C#
2
star
42

Cognitive

Unified Cognitive API for Azure, Amazon and Google
C#
2
star
43

html

Loads Html documents as XLinq XDocuments
HTML
2
star
44

epub

A lightweight library that implements EPUB standard
C#
2
star
45

sponsors

Automatically updated list of devlooped sponsors
1
star
46

yaml

YamlPeek MSBuild Task
C#
1
star
47

actions-includes

Processes include HTML comments in files and inserts the included files
PowerShell
1
star
48

jq

A nuget distribution of the official JQ implementation, for easy consumption from .NET
C#
1
star
49

Azure.Functions.OpenApi

A zero-code OpenAPI (Swagger) basic generator for Azure Functions
C#
1
star
50

Mvp.Xml

C#
1
star
51

StreamR

An opinionated streaming-based library for running assistants with support for tool/function invocation and assistant behavior composition.
C#
1
star