Skip to content

Commit

Permalink
Merge pull request #357 from AArnott/v2.3
Browse files Browse the repository at this point in the history
Merge v2.3 to master
  • Loading branch information
AArnott authored Jun 11, 2019
2 parents 729562c + a37b160 commit 9880338
Show file tree
Hide file tree
Showing 7 changed files with 102 additions and 29 deletions.
9 changes: 1 addition & 8 deletions src/Cake.GitVersioning/Cake.GitVersioning.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<Authors>Chris Crutchfield, Andrew Arnott</Authors>
<Company>andarno</Company>
<Description>Cake wrapper for Nerdbank.GitVersioning. Stamps your assemblies with semver 2.0 compliant git commit specific version information and provides NuGet versioning information as well.</Description>
Expand All @@ -17,14 +18,6 @@
<TargetsForTfmSpecificContentInPackage>$(TargetsForTfmSpecificContentInPackage);PackBuildOutputs</TargetsForTfmSpecificContentInPackage>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DocumentationFile>C:\git\Nerdbank.GitVersioning\src\..\bin\Cake.GitVersioning\Debug\net461\Cake.GitVersioning.xml</DocumentationFile>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<DocumentationFile>C:\git\Nerdbank.GitVersioning\src\..\bin\Cake.GitVersioning\Release\net461\Cake.GitVersioning.xml</DocumentationFile>
</PropertyGroup>

<!-- This is a tools package and should express no dependencies. -->
<ItemDefinitionGroup>
<ProjectReference>
Expand Down
2 changes: 2 additions & 0 deletions src/NerdBank.GitVersioning.Tests/AssemblyInfoTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ namespace AssemblyInfo
[<assembly: System.Reflection.AssemblyFileVersionAttribute(""1.3.1.0"")>]
[<assembly: System.Reflection.AssemblyInformationalVersionAttribute("""")>]
do()
#if NETSTANDARD || NETFRAMEWORK || NETCOREAPP
[<System.CodeDom.Compiler.GeneratedCode(""" + AssemblyVersionInfo.GeneratorName + @""",""" + AssemblyVersionInfo.GeneratorVersion + @""")>]
#endif
type internal ThisAssembly() =
static member internal AssemblyVersion = ""1.3.0.0""
static member internal AssemblyFileVersion = ""1.3.1.0""
Expand Down
61 changes: 58 additions & 3 deletions src/NerdBank.GitVersioning.Tests/BuildIntegrationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,15 @@ public class BuildIntegrationTests : RepoTestBase, IClassFixture<MSBuildFixture>

public BuildIntegrationTests(ITestOutputHelper logger)
: base(logger)
{
// MSBuildExtensions.LoadMSBuild will be called as part of the base constructor, because this class
// implements the IClassFixture<MSBuildFixture> interface. LoadMSBuild will load the MSBuild assemblies.
// This must happen _before_ any method that directly references types in the Microsoft.Build namespace has been called.
// Net, don't init MSBuild-related fields in the constructor, but in a method that is called by the constructor.
this.Init();
}

private void Init()
{
int seed = (int)DateTime.Now.Ticks;
this.random = new Random(seed);
Expand Down Expand Up @@ -651,6 +660,53 @@ public async Task BuildNumber_VariousOptions(bool isPublic, VersionOptions.Cloud
this.AssertStandardProperties(versionOptions, buildResult);
}

[Fact]
public void GitLab_BuildTag()
{
// Based on the values defined in https://docs.gitlab.com/ee/ci/variables/#syntax-of-environment-variables-in-job-scripts
using (ApplyEnvironmentVariables(
CloudBuild.SuppressEnvironment.SetItems(
new Dictionary<string, string>()
{
{ "CI_COMMIT_TAG", "1.0.0" },
{ "CI_COMMIT_SHA", "1ecfd275763eff1d6b4844ea3168962458c9f27a" },
{ "GITLAB_CI", "true" },
{ "SYSTEM_TEAMPROJECTID", string.Empty }
})))
{
var activeCloudBuild = Nerdbank.GitVersioning.CloudBuild.Active;
Assert.NotNull(activeCloudBuild);
Assert.Null(activeCloudBuild.BuildingBranch);
Assert.Equal("refs/tags/1.0.0", activeCloudBuild.BuildingTag);
Assert.Equal("1ecfd275763eff1d6b4844ea3168962458c9f27a", activeCloudBuild.GitCommitId);
Assert.True(activeCloudBuild.IsApplicable);
Assert.False(activeCloudBuild.IsPullRequest);
}
}

[Fact]
public void GitLab_BuildBranch()
{
// Based on the values defined in https://docs.gitlab.com/ee/ci/variables/#syntax-of-environment-variables-in-job-scripts
using (ApplyEnvironmentVariables(
CloudBuild.SuppressEnvironment.SetItems(
new Dictionary<string, string>()
{
{ "CI_COMMIT_REF_NAME", "master" },
{ "CI_COMMIT_SHA", "1ecfd275763eff1d6b4844ea3168962458c9f27a" },
{ "GITLAB_CI", "true" },
})))
{
var activeCloudBuild = Nerdbank.GitVersioning.CloudBuild.Active;
Assert.NotNull(activeCloudBuild);
Assert.Equal("refs/heads/master", activeCloudBuild.BuildingBranch);
Assert.Null(activeCloudBuild.BuildingTag);
Assert.Equal("1ecfd275763eff1d6b4844ea3168962458c9f27a", activeCloudBuild.GitCommitId);
Assert.True(activeCloudBuild.IsApplicable);
Assert.False(activeCloudBuild.IsPullRequest);
}
}

[Fact]
public async Task PublicRelease_RegEx_SatisfiedByCheckedOutBranch()
{
Expand Down Expand Up @@ -743,7 +799,7 @@ public async Task AssemblyInfo(bool isVB, bool includeNonVersionAttributes, bool
if (gitRepo)
{
Assert.True(long.TryParse(result.GitCommitDateTicks, out _), $"Invalid value for GitCommitDateTicks: '{result.GitCommitDateTicks}'");
DateTimeOffset gitCommitDate = new DateTimeOffset(long.Parse(result.GitCommitDateTicks), TimeSpan.Zero);
var gitCommitDate = new DateTime(long.Parse(result.GitCommitDateTicks), DateTimeKind.Utc);
Assert.Equal(gitCommitDate, thisAssemblyClass.GetProperty("GitCommitDate", fieldFlags)?.GetValue(null) ?? thisAssemblyClass.GetField("GitCommitDate", fieldFlags)?.GetValue(null) ?? string.Empty);
}
else
Expand Down Expand Up @@ -957,8 +1013,7 @@ private void AssertStandardProperties(VersionOptions versionOptions, BuildResult

string GetPkgVersionSuffix(bool useSemVer2)
{
string semVer1CommitPrefix = useSemVer2 ? string.Empty : "g";
string pkgVersionSuffix = buildResult.PublicRelease ? string.Empty : $"-{semVer1CommitPrefix}{commitIdShort}";
string pkgVersionSuffix = buildResult.PublicRelease ? string.Empty : $"-g{commitIdShort}";
if (useSemVer2)
{
pkgVersionSuffix += expectedBuildMetadataWithoutCommitId;
Expand Down
6 changes: 3 additions & 3 deletions src/NerdBank.GitVersioning.Tests/VersionOracleTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ public void SemVerStableNonPublicVersion()
var oracle = VersionOracle.Create(this.RepoPath);
oracle.PublicRelease = false;
Assert.Matches(@"^2.3.1-[^g]{10}$", oracle.SemVer1);
Assert.Matches(@"^2.3.1-[^g]{10}$", oracle.SemVer2);
Assert.Matches(@"^2.3.1-g[a-f0-9]{10}$", oracle.SemVer2);
Assert.Matches(@"^2.3.1-g[a-f0-9]{10}$", oracle.NuGetPackageVersion);
Assert.Matches(@"^2.3.1-g[a-f0-9]{10}$", oracle.ChocolateyPackageVersion);
}
Expand All @@ -227,7 +227,7 @@ public void SemVerStableNonPublicVersionShortened()
var oracle = VersionOracle.Create(this.RepoPath);
oracle.PublicRelease = false;
Assert.Matches(@"^2.3.1-[^g]{7}$", oracle.SemVer1);
Assert.Matches(@"^2.3.1-[^g]{7}$", oracle.SemVer2);
Assert.Matches(@"^2.3.1-g[a-f0-9]{7}$", oracle.SemVer2);
Assert.Matches(@"^2.3.1-g[a-f0-9]{7}$", oracle.NuGetPackageVersion);
Assert.Matches(@"^2.3.1-g[a-f0-9]{7}$", oracle.ChocolateyPackageVersion);
}
Expand Down Expand Up @@ -310,7 +310,7 @@ public void CanSetSemVer2ForNuGetPackageVersionNonPublicRelease()
this.InitializeSourceControl();
var oracle = VersionOracle.Create(this.RepoPath);
oracle.PublicRelease = false;
Assert.Equal($"7.8.9-foo.25.{this.CommitIdShort}", oracle.NuGetPackageVersion);
Assert.Equal($"7.8.9-foo.25.g{this.CommitIdShort}", oracle.NuGetPackageVersion);
}

[Fact]
Expand Down
12 changes: 7 additions & 5 deletions src/NerdBank.GitVersioning/CloudBuildServices/GitLab.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;

/// <summary>
Expand All @@ -15,11 +13,15 @@
/// </remarks>
internal class GitLab : ICloudBuild
{
public string BuildingBranch => Environment.GetEnvironmentVariable("CI_COMMIT_REF_NAME");
public string BuildingBranch =>
Environment.GetEnvironmentVariable("CI_COMMIT_TAG") == null ?
$"refs/heads/{Environment.GetEnvironmentVariable("CI_COMMIT_REF_NAME")}" : null;

public string BuildingRef => Environment.GetEnvironmentVariable("CI_COMMIT_TAG");
public string BuildingRef => this.BuildingBranch ?? this.BuildingTag;

public string BuildingTag => Environment.GetEnvironmentVariable("CI_COMMIT_TAG");
public string BuildingTag =>
Environment.GetEnvironmentVariable("CI_COMMIT_TAG") != null ?
$"refs/tags/{Environment.GetEnvironmentVariable("CI_COMMIT_TAG")}" : null;

public string GitCommitId => Environment.GetEnvironmentVariable("CI_COMMIT_SHA");

Expand Down
9 changes: 8 additions & 1 deletion src/NerdBank.GitVersioning/VersionOracle.cs
Original file line number Diff line number Diff line change
Expand Up @@ -429,7 +429,14 @@ public IDictionary<string, string> CloudBuildVersionVars

private string PrereleaseVersionSemVer1 => SemanticVersionExtensions.MakePrereleaseSemVer1Compliant(this.PrereleaseVersion, this.SemVer1NumericIdentifierPadding);

private string GitCommitIdShortForNonPublicPrereleaseTag => (string.IsNullOrEmpty(this.PrereleaseVersion) ? "-" : ".") + this.GitCommitIdShort;
/// <summary>
/// Gets the -gc0ffee or .gc0ffee suffix for the version.
/// </summary>
/// <remarks>
/// The `g` prefix to the commit ID is to remain SemVer2 compliant particularly when the partial commit ID we use is made up entirely of numerals.
/// SemVer2 forbids numerals to begin with leading zeros, but a git commit just might, so we begin with `g` always to avoid failures when the commit ID happens to be problematic.
/// </remarks>
private string GitCommitIdShortForNonPublicPrereleaseTag => (string.IsNullOrEmpty(this.PrereleaseVersion) ? "-" : ".") + "g" + this.GitCommitIdShort;

private VersionOptions.CloudBuildNumberOptions CloudBuildNumberOptions { get; }

Expand Down
32 changes: 23 additions & 9 deletions src/Nerdbank.GitVersioning.Tasks/AssemblyVersionInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@

public class AssemblyVersionInfo : Task
{
/// <summary>
/// The #if expression that surrounds a <see cref="GeneratedCodeAttribute"/> to avoid a compilation failure when targeting the nano framework.
/// </summary>
/// <remarks>
/// See https://github.com/AArnott/Nerdbank.GitVersioning/issues/346
/// </remarks>
private const string CompilerDefinesAroundGeneratedCodeAttribute = "NETSTANDARD || NETFRAMEWORK || NETCOREAPP";

public static readonly string GeneratorName = ThisAssembly.AssemblyName;
public static readonly string GeneratorVersion = ThisAssembly.AssemblyVersion;
#if NET461
Expand Down Expand Up @@ -225,22 +233,22 @@ private static CodeMemberField CreateField(string name, string value)

private static IEnumerable<CodeTypeMember> CreateCommitDateProperty(long ticks)
{
// internal static System.DateTimeOffset GitCommitDate {{ get; }} = new System.DateTimeOffset({ticks}, System.TimeSpan.Zero);");
yield return new CodeMemberField(typeof(DateTimeOffset), "gitCommitDate")
// internal static System.DateTime GitCommitDate {{ get; }} = new System.DateTime({ticks}, System.DateTimeKind.Utc);");
yield return new CodeMemberField(typeof(DateTime), "gitCommitDate")
{
Attributes = MemberAttributes.Private,
InitExpression = new CodeObjectCreateExpression(
typeof(DateTimeOffset),
typeof(DateTime),
new CodePrimitiveExpression(ticks),
new CodePropertyReferenceExpression(
new CodeTypeReferenceExpression(typeof(TimeSpan)),
nameof(TimeSpan.Zero)))
new CodeTypeReferenceExpression(typeof(DateTimeKind)),
nameof(DateTimeKind.Utc)))
};

var property = new CodeMemberProperty()
{
Attributes = MemberAttributes.Assembly,
Type = new CodeTypeReference(typeof(DateTimeOffset)),
Type = new CodeTypeReference(typeof(DateTime)),
Name = "GitCommitDate",
HasGet = true,
HasSet = false,
Expand Down Expand Up @@ -463,7 +471,7 @@ internal override void DeclareAttribute(Type type, string arg)

internal override void AddCommitDateProperty(long ticks)
{
this.codeBuilder.AppendLine($" static member internal GitCommitDate = new DateTimeOffset({ticks}, TimeZpan.Zero)");
this.codeBuilder.AppendLine($" static member internal GitCommitDate = new System.DateTime({ticks}L, System.DateTimeKind.Utc)");
}

internal override void EndThisAssemblyClass()
Expand All @@ -474,7 +482,9 @@ internal override void EndThisAssemblyClass()
internal override void StartThisAssemblyClass()
{
this.codeBuilder.AppendLine("do()");
this.codeBuilder.AppendLine($"#if {CompilerDefinesAroundGeneratedCodeAttribute}");
this.codeBuilder.AppendLine($"[<System.CodeDom.Compiler.GeneratedCode(\"{GeneratorName}\",\"{GeneratorVersion}\")>]");
this.codeBuilder.AppendLine("#endif");
this.codeBuilder.AppendLine("type internal ThisAssembly() =");
}
}
Expand All @@ -493,7 +503,9 @@ internal override void DeclareAttribute(Type type, string arg)

internal override void StartThisAssemblyClass()
{
this.codeBuilder.AppendLine($"#if {CompilerDefinesAroundGeneratedCodeAttribute}");
this.codeBuilder.AppendLine($"[System.CodeDom.Compiler.GeneratedCode(\"{GeneratorName}\",\"{GeneratorVersion}\")]");
this.codeBuilder.AppendLine("#endif");
this.codeBuilder.AppendLine("internal static partial class ThisAssembly {");
}

Expand All @@ -504,7 +516,7 @@ internal override void AddThisAssemblyMember(string name, string value)

internal override void AddCommitDateProperty(long ticks)
{
this.codeBuilder.AppendLine($" internal static readonly System.DateTimeOffset GitCommitDate = new System.DateTimeOffset({ticks}, System.TimeSpan.Zero);");
this.codeBuilder.AppendLine($" internal static readonly System.DateTime GitCommitDate = new System.DateTime({ticks}L, System.DateTimeKind.Utc);");
}

internal override void EndThisAssemblyClass()
Expand All @@ -527,7 +539,9 @@ internal override void DeclareAttribute(Type type, string arg)

internal override void StartThisAssemblyClass()
{
this.codeBuilder.AppendLine($"#If {CompilerDefinesAroundGeneratedCodeAttribute.Replace("||", " Or ")} Then");
this.codeBuilder.AppendLine($"<System.CodeDom.Compiler.GeneratedCode(\"{GeneratorName}\",\"{GeneratorVersion}\")>");
this.codeBuilder.AppendLine("#End If");
this.codeBuilder.AppendLine("Partial Friend NotInheritable Class ThisAssembly");
}

Expand All @@ -538,7 +552,7 @@ internal override void AddThisAssemblyMember(string name, string value)

internal override void AddCommitDateProperty(long ticks)
{
this.codeBuilder.AppendLine($" Friend Shared ReadOnly GitCommitDate As System.DateTimeOffset = New System.DateTimeOffset({ticks}, System.TimeSpan.Zero)");
this.codeBuilder.AppendLine($" Friend Shared ReadOnly GitCommitDate As System.DateTime = New System.DateTime({ticks}L, System.DateTimeKind.Utc)");
}

internal override void EndThisAssemblyClass()
Expand Down

0 comments on commit 9880338

Please sign in to comment.