Skip to content

Add assembly-file-versioning-format with support for environment variables #1385

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,16 @@ while still updating the `AssemblyVersion` and `AssemblyInformationVersion`
attributes. Valid values: `MajorMinorPatchTag`, `MajorMinorPatch`, `MajorMinor`,
`Major`, `None`.

### assembly-file-versioning-format
Set this to any of the available [variables](/more-info/variables) in combination (but not necessary) with
a process scoped environment variable. It overwrites the value of `assembly-file-versioning-scheme`. To reference
an environment variable, use `$`
Example Syntax #1: `'{Major}.{Minor}.{Patch}.{$JENKINS_BUILD_NUMBER??fallback_string}'`. Uses `JENKINS_BUILD_NUMBER`
if available in the environment otherwise the `fallback_string`
Example Syntax #2: `'{Major}.{Minor}.{Patch}.{$JENKINS_BUILD_NUMBER}'`. Uses `JENKINS_BUILD_NUMBER`
if available in the environment otherwise the parsing fails.
String interpolation is supported as in `assembly-informational-format`

### assembly-informational-format
Set this to any of the available [variables](/more-info/variables) to change the
value of the `AssemblyInformationalVersion` attribute. Default set to
Expand Down
2 changes: 1 addition & 1 deletion src/GitVersionCore.Tests/CommitDateTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public void CommitDateFormatTest(string format, string expectedOutcome)

},
new EffectiveConfiguration(
AssemblyVersioningScheme.MajorMinorPatch, AssemblyFileVersioningScheme.MajorMinorPatch, "", VersioningMode.ContinuousDelivery, "", "", "", IncrementStrategy.Inherit,
AssemblyVersioningScheme.MajorMinorPatch, AssemblyFileVersioningScheme.MajorMinorPatch, "", "", VersioningMode.ContinuousDelivery, "", "", "", IncrementStrategy.Inherit,
"", true, "", "", false, "", "", "", "", CommitMessageIncrementMode.Enabled, 4, 4, 4, Enumerable.Empty<IVersionFilter>(), false, true, format)
);

Expand Down
1 change: 1 addition & 0 deletions src/GitVersionCore.Tests/GitVersionCore.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@
<Compile Include="Helpers\PathHelper.cs" />
<Compile Include="IntegrationTests\MasterScenarios.cs" />
<Compile Include="SemanticVersionTests.cs" />
<Compile Include="StringFormatWithExtensionTests.cs" />
<Compile Include="TestableVersionVariables.cs" />
<Compile Include="TestEffectiveConfiguration.cs" />
<Compile Include="TestFileSystem.cs" />
Expand Down
75 changes: 75 additions & 0 deletions src/GitVersionCore.Tests/StringFormatWithExtensionTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
using System;

using GitVersion;
using NUnit.Framework;

namespace GitVersionCore.Tests
{
[TestFixture]

public class StringFormatWithExtensionTests
{
[Test]
public void FormatWith_NoTokens()
{
var propertyObject = new { };
var target = "Some String without tokens";
var expected = target;
var actual = target.FormatWith(propertyObject);
Assert.AreEqual(expected, actual);
}

[Test]
public void FormatWith_SingleSimpleToken()
{
var propertyObject = new { SomeProperty = "SomeValue" };
var target = "{SomeProperty}";
var expected = "SomeValue";
var actual = target.FormatWith(propertyObject);
Assert.AreEqual(expected, actual);
}

[Test]
public void FormatWith_MultipleTokensAndVerbatimText()
{
var propertyObject = new { SomeProperty = "SomeValue", AnotherProperty = "Other Value" };
var target = "{SomeProperty} some text {AnotherProperty}";
var expected = "SomeValue some text Other Value";
var actual = target.FormatWith(propertyObject);
Assert.AreEqual(expected, actual);
}

[Test]
public void FormatWith_EnvVarToken()
{
Environment.SetEnvironmentVariable("GIT_VERSION_TEST_VAR", "Env Var Value");
var propertyObject = new { };
var target = "{$GIT_VERSION_TEST_VAR}";
var expected = "Env Var Value";
var actual = target.FormatWith(propertyObject);
Assert.AreEqual(expected, actual);
}

[Test]
public void FormatWith_EnvVarTokenWithFallback()
{
Environment.SetEnvironmentVariable("GIT_VERSION_TEST_VAR", "Env Var Value");
var propertyObject = new { };
var target = "{$GIT_VERSION_TEST_VAR??fallback}";
var expected = "Env Var Value";
var actual = target.FormatWith(propertyObject);
Assert.AreEqual(expected, actual);
}

[Test]
public void FormatWith_UnsetEnvVarTokenWithFallback()
{
Environment.SetEnvironmentVariable("GIT_VERSION_UNSET_TEST_VAR", null);
var propertyObject = new { };
var target = "{$GIT_VERSION_UNSET_TEST_VAR??fallback}";
var expected = "fallback";
var actual = target.FormatWith(propertyObject);
Assert.AreEqual(expected, actual);
}
}
}
3 changes: 2 additions & 1 deletion src/GitVersionCore.Tests/TestEffectiveConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ public class TestEffectiveConfiguration : EffectiveConfiguration
public TestEffectiveConfiguration(
AssemblyVersioningScheme assemblyVersioningScheme = AssemblyVersioningScheme.MajorMinorPatch,
AssemblyFileVersioningScheme assemblyFileVersioningScheme = AssemblyFileVersioningScheme.MajorMinorPatch,
string assemblyFileVersioningSchemeFormat = null,
string assemblyInformationalFormat = null,
VersioningMode versioningMode = VersioningMode.ContinuousDelivery,
string gitTagPrefix = "v",
Expand All @@ -32,7 +33,7 @@ public TestEffectiveConfiguration(
bool tracksReleaseBranches = false,
bool isRelease = false,
string commitDateFormat = "yyyy-MM-dd") :
base(assemblyVersioningScheme, assemblyFileVersioningScheme, assemblyInformationalFormat, versioningMode, gitTagPrefix, tag, nextVersion, IncrementStrategy.Patch,
base(assemblyVersioningScheme, assemblyFileVersioningScheme, assemblyInformationalFormat, assemblyFileVersioningSchemeFormat, versioningMode, gitTagPrefix, tag, nextVersion, IncrementStrategy.Patch,
branchPrefixToTrim, preventIncrementForMergedBranchVersion, tagNumberPattern, continuousDeploymentFallbackTag,
trackMergeTarget,
majorMessage, minorMessage, patchMessage, noBumpMessage,
Expand Down
3 changes: 3 additions & 0 deletions src/GitVersionCore/Configuration/Config.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ public Config()
[YamlMember(Alias = "assembly-informational-format")]
public string AssemblyInformationalFormat { get; set; }

[YamlMember(Alias = "assembly-file-versioning-format")]
public string AssemblyFileVersioningFormat { get; set; }

[YamlMember(Alias = "mode")]
public VersioningMode? VersioningMode { get; set; }

Expand Down
1 change: 1 addition & 0 deletions src/GitVersionCore/Configuration/ConfigurationProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ public static void ApplyDefaultsTo(Config config)
config.AssemblyVersioningScheme = config.AssemblyVersioningScheme ?? AssemblyVersioningScheme.MajorMinorPatch;
config.AssemblyFileVersioningScheme = config.AssemblyFileVersioningScheme ?? AssemblyFileVersioningScheme.MajorMinorPatch;
config.AssemblyInformationalFormat = config.AssemblyInformationalFormat;
config.AssemblyFileVersioningFormat = config.AssemblyFileVersioningFormat;
config.TagPrefix = config.TagPrefix ?? DefaultTagPrefix;
config.VersioningMode = config.VersioningMode ?? VersioningMode.ContinuousDelivery;
config.ContinuousDeploymentFallbackTag = config.ContinuousDeploymentFallbackTag ?? "ci";
Expand Down
3 changes: 3 additions & 0 deletions src/GitVersionCore/EffectiveConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ public EffectiveConfiguration(
AssemblyVersioningScheme assemblyVersioningScheme,
AssemblyFileVersioningScheme assemblyFileVersioningScheme,
string assemblyInformationalFormat,
string assemblyFileVersioningFormat,
VersioningMode versioningMode, string gitTagPrefix,
string tag, string nextVersion, IncrementStrategy increment,
string branchPrefixToTrim,
Expand All @@ -35,6 +36,7 @@ public EffectiveConfiguration(
AssemblyVersioningScheme = assemblyVersioningScheme;
AssemblyFileVersioningScheme = assemblyFileVersioningScheme;
AssemblyInformationalFormat = assemblyInformationalFormat;
AssemblyFileVersioningFormat = assemblyFileVersioningFormat;
VersioningMode = versioningMode;
GitTagPrefix = gitTagPrefix;
Tag = tag;
Expand Down Expand Up @@ -67,6 +69,7 @@ public EffectiveConfiguration(
public AssemblyVersioningScheme AssemblyVersioningScheme { get; private set; }
public AssemblyFileVersioningScheme AssemblyFileVersioningScheme { get; private set; }
public string AssemblyInformationalFormat { get; private set; }
public string AssemblyFileVersioningFormat { get; private set; }

/// <summary>
/// Git tag prefix
Expand Down
3 changes: 2 additions & 1 deletion src/GitVersionCore/GitVersionContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ void CalculateEffectiveConfiguration()
var assemblyVersioningScheme = FullConfiguration.AssemblyVersioningScheme.Value;
var assemblyFileVersioningScheme = FullConfiguration.AssemblyFileVersioningScheme.Value;
var assemblyInformationalFormat = FullConfiguration.AssemblyInformationalFormat;
var assemblyFileVersioningFormat = FullConfiguration.AssemblyFileVersioningFormat;
var gitTagPrefix = FullConfiguration.TagPrefix;
var majorMessage = FullConfiguration.MajorVersionBumpMessage;
var minorMessage = FullConfiguration.MinorVersionBumpMessage;
Expand All @@ -132,7 +133,7 @@ void CalculateEffectiveConfiguration()
var commitMessageVersionBump = currentBranchConfig.CommitMessageIncrementing ?? FullConfiguration.CommitMessageIncrementing.Value;

Configuration = new EffectiveConfiguration(
assemblyVersioningScheme, assemblyFileVersioningScheme, assemblyInformationalFormat, versioningMode, gitTagPrefix,
assemblyVersioningScheme, assemblyFileVersioningScheme, assemblyInformationalFormat, assemblyFileVersioningFormat, versioningMode, gitTagPrefix,
tag, nextVersion, incrementStrategy,
currentBranchConfig.Regex,
preventIncrementForMergedBranchVersion,
Expand Down
3 changes: 2 additions & 1 deletion src/GitVersionCore/GitVersionCore.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@
<Compile Include="GitVersionException.cs" />
<Compile Include="GitVersionInformationResources\GitVersionInformationGenerator.cs" />
<Compile Include="Helpers\EncodingHelper.cs" />
<Compile Include="Helpers\EnvironmentHelper.cs" />
<Compile Include="Helpers\FileSystem.cs" />
<Compile Include="Helpers\IFileSystem.cs" />
<Compile Include="Helpers\IThreadSleep.cs" />
Expand Down Expand Up @@ -232,4 +233,4 @@
</Target>
<Import Project="..\packages\PepitaPackage.1.21.4\build\PepitaPackage.targets" Condition="Exists('..\packages\PepitaPackage.1.21.4\build\PepitaPackage.targets')" />
<Import Project="..\packages\Fody.2.0.8\build\portable-net+sl+win+wpa+wp\Fody.targets" Condition="Exists('..\packages\Fody.2.0.8\build\portable-net+sl+win+wpa+wp\Fody.targets')" />
</Project>
</Project>
12 changes: 12 additions & 0 deletions src/GitVersionCore/Helpers/EnvironmentHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using System;

namespace GitVersion.Helpers
{
public class EnvironmentHelper
{
public static string GetEnvironmentVariableForProcess(string envVar)
{
return Environment.GetEnvironmentVariable(envVar, EnvironmentVariableTarget.Process);
}
}
}
23 changes: 22 additions & 1 deletion src/GitVersionCore/OutputVariables/VariableProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,27 @@ public static VersionVariables GetVariablesFor(SemanticVersion semanticVersion,
}
}

string assemblyFileVersioningFormat;
string assemblyFileSemVer;

if (!(string.IsNullOrEmpty(config.AssemblyFileVersioningFormat)))
{
//assembly-file-versioning-format value if provided in the config, overwrites the exisiting AssemblyFileSemVer
try
{
assemblyFileVersioningFormat = config.AssemblyFileVersioningFormat.FormatWith<SemanticVersionFormatValues>(semverFormatValues);
assemblyFileSemVer = assemblyFileVersioningFormat;
}
catch (ArgumentException formex)
{
throw new WarningException(string.Format("Unable to format AssemblyFileVersioningFormat. Check your format string: {0}", formex.Message));
}
}
else
{
assemblyFileSemVer = semverFormatValues.AssemblyFileSemVer;
}

var variables = new VersionVariables(
semverFormatValues.Major,
semverFormatValues.Minor,
Expand All @@ -76,7 +97,7 @@ public static VersionVariables GetVariablesFor(SemanticVersion semanticVersion,
semverFormatValues.LegacySemVerPadded,
semverFormatValues.FullSemVer,
semverFormatValues.AssemblySemVer,
semverFormatValues.AssemblyFileSemVer,
assemblyFileSemVer,
semverFormatValues.PreReleaseTag,
semverFormatValues.PreReleaseTagWithDash,
semverFormatValues.PreReleaseLabel,
Expand Down
35 changes: 30 additions & 5 deletions src/GitVersionCore/StringFormatWith.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ namespace GitVersion

static class StringFormatWithExtension
{
private static readonly Regex TokensRegex = new Regex(@"{\w+}", RegexOptions.Compiled);
private static readonly Regex TokensRegex = new Regex(@"{\$??\w+(\?\?\w+)??}", RegexOptions.Compiled);

/// <summary>
/// Formats a string template with the given source object.
Expand All @@ -30,13 +30,39 @@ public static string FormatWith<T>(this string template, T source)
foreach (Match match in TokensRegex.Matches(template))
{
var memberAccessExpression = TrimBraces(match.Value);
Func<object, string> expression = CompileDataBinder(objType, memberAccessExpression);
string propertyValue = expression(source);
string propertyValue = null;

// Support evaluation of environment variables in the format string
// For example: {$JENKINS_BUILD_NUMBER??fall-back-string}
if (memberAccessExpression.StartsWith("$"))
{
memberAccessExpression = memberAccessExpression.TrimStart('$').TrimEnd('$');
string envVar = memberAccessExpression, fallback = null;
string[] components = (memberAccessExpression.Contains("??")) ? memberAccessExpression.Split(new string[] { "??" }, StringSplitOptions.None) : null;
if (components != null)
{
envVar = components[0];
fallback = components[1];
}

propertyValue = Helpers.EnvironmentHelper.GetEnvironmentVariableForProcess(envVar);
if (propertyValue == null)
{
if (fallback != null)
propertyValue = fallback;
else
throw new ArgumentException(string.Format("Environment variable {0} not found and no fallback string provided", envVar));
}
}
else
{
Func<object, string> expression = CompileDataBinder(objType, memberAccessExpression);
propertyValue = expression(source);
}
template = template.Replace(match.Value, propertyValue);
}

return template;

}


Expand Down Expand Up @@ -73,6 +99,5 @@ static Func<object, string> CompileDataBinder(Type type, string expr)

return Expression.Lambda<Func<object, string>>(body, param).Compile();
}

}
}