Skip to content

Commit 6c88c60

Browse files
authored
Merge pull request #159 from heaths/issue130
Add option to set all cloud variables
2 parents 146671c + 37d476d commit 6c88c60

File tree

7 files changed

+124
-7
lines changed

7 files changed

+124
-7
lines changed

src/NerdBank.GitVersioning.Tests/BuildIntegrationTests.cs

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -484,14 +484,15 @@ public static object[][] CloudBuildVariablesData
484484
{
485485
return new object[][]
486486
{
487-
new object[] { CloudBuild.VSTS, "##vso[task.setvariable variable={NAME};]{VALUE}" },
487+
new object[] { CloudBuild.VSTS, "##vso[task.setvariable variable={NAME};]{VALUE}", false },
488+
new object[] { CloudBuild.VSTS, "##vso[task.setvariable variable={NAME};]{VALUE}", true },
488489
};
489490
}
490491
}
491492

492493
[Theory]
493494
[MemberData(nameof(CloudBuildVariablesData))]
494-
public async Task CloudBuildVariables_SetInCI(IReadOnlyDictionary<string, string> properties, string expectedMessage)
495+
public async Task CloudBuildVariables_SetInCI(IReadOnlyDictionary<string, string> properties, string expectedMessage, bool setAllVariables)
495496
{
496497
using (ApplyEnvironmentVariables(properties))
497498
{
@@ -506,7 +507,7 @@ public async Task CloudBuildVariables_SetInCI(IReadOnlyDictionary<string, string
506507
var versionOptions = new VersionOptions
507508
{
508509
Version = SemanticVersion.Parse("1.0"),
509-
CloudBuild = new VersionOptions.CloudBuildOptions { SetVersionVariables = true },
510+
CloudBuild = new VersionOptions.CloudBuildOptions { SetAllVariables = setAllVariables, SetVersionVariables = true },
510511
};
511512
this.WriteVersionFile(versionOptions);
512513
this.InitializeSourceControl();
@@ -533,6 +534,19 @@ public async Task CloudBuildVariables_SetInCI(IReadOnlyDictionary<string, string
533534
Assert.Equal(buildResult.BuildVersionSimple, buildResult.GitBuildVersionSimple);
534535
Assert.Equal(buildResult.AssemblyInformationalVersion, buildResult.GitAssemblyInformationalVersion);
535536

537+
if (setAllVariables)
538+
{
539+
// Assert that some project properties were set as build properties prefaced with "NBGV_".
540+
Assert.Equal(buildResult.GitCommitIdShort, buildResult.NBGV_GitCommitIdShort);
541+
Assert.Equal(buildResult.NuGetPackageVersion, buildResult.NBGV_NuGetPackageVersion);
542+
}
543+
else
544+
{
545+
// Assert that the NBGV_ prefixed properties are *not* set.
546+
Assert.Equal(string.Empty, buildResult.NBGV_GitCommitIdShort);
547+
Assert.Equal(string.Empty, buildResult.NBGV_NuGetPackageVersion);
548+
}
549+
536550
// Assert that env variables were also set in context of the build.
537551
Assert.True(buildResult.LoggedEvents.Any(e => string.Equals(e.Message, $"n1=v1", StringComparison.OrdinalIgnoreCase)));
538552

@@ -1127,6 +1141,10 @@ internal BuildResults(BuildResult buildResult, IReadOnlyList<BuildEventArgs> log
11271141
public string GitBuildVersionSimple => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("GitBuildVersionSimple");
11281142
public string GitAssemblyInformationalVersion => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("GitAssemblyInformationalVersion");
11291143

1144+
// Just a sampling of other properties optionally set in cloud build.
1145+
public string NBGV_GitCommitIdShort => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("NBGV_GitCommitIdShort");
1146+
public string NBGV_NuGetPackageVersion => this.BuildResult.ProjectStateAfterBuild.GetPropertyValue("NBGV_NuGetPackageVersion");
1147+
11301148
public override string ToString()
11311149
{
11321150
var sb = new StringBuilder();

src/NerdBank.GitVersioning.Tests/VersionFileTests.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,7 @@ public void SetVersion_WritesSimplestFile(string version, string assemblyVersion
142142
[InlineData(@"{""cloudBuild"":{""buildNumber"":{""enabled"":true,""includeCommitId"":{""when"":""always"",""where"":""buildMetadata""}}}}", @"{""cloudBuild"":{""buildNumber"":{""enabled"":true,""includeCommitId"":{""when"":""always""}}}}")]
143143
[InlineData(@"{""cloudBuild"":{""buildNumber"":{""enabled"":true,""includeCommitId"":{""when"":""nonPublicReleaseOnly"",""where"":""fourthVersionComponent""}}}}", @"{""cloudBuild"":{""buildNumber"":{""enabled"":true,""includeCommitId"":{""where"":""fourthVersionComponent""}}}}")]
144144
[InlineData(@"{""cloudBuild"":{""setVersionVariables"":true}}", @"{}")]
145+
[InlineData(@"{""cloudBuild"":{""setAllVariables"":false}}", @"{}")]
145146
public void JsonMinification(string full, string minimal)
146147
{
147148
var settings = VersionOptions.GetJsonSettings();

src/NerdBank.GitVersioning/VersionOptions.cs

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -458,12 +458,16 @@ public class CloudBuildOptions : IEquatable<CloudBuildOptions>
458458
/// </summary>
459459
internal static readonly CloudBuildOptions DefaultInstance = new CloudBuildOptions(isReadOnly: true)
460460
{
461+
setAllVariables = false,
461462
setVersionVariables = true,
462463
};
463464

464465
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
465466
private readonly bool isReadOnly;
466467

468+
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
469+
private bool? setAllVariables;
470+
467471
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
468472
private bool? setVersionVariables;
469473

@@ -486,6 +490,15 @@ protected CloudBuildOptions(bool isReadOnly)
486490
this.isReadOnly = isReadOnly;
487491
}
488492

493+
/// <summary>
494+
/// Gets or sets a value indicating whether to elevate all build properties to cloud build variables prefaced with "NBGV_".
495+
/// </summary>
496+
public bool? SetAllVariables
497+
{
498+
get => this.setAllVariables;
499+
set => this.SetIfNotReadOnly(ref this.setAllVariables, value);
500+
}
501+
489502
/// <summary>
490503
/// Gets or sets a value indicating whether to elevate certain calculated version build properties to cloud build variables.
491504
/// </summary>
@@ -495,6 +508,12 @@ public bool? SetVersionVariables
495508
set => this.SetIfNotReadOnly(ref this.setVersionVariables, value);
496509
}
497510

511+
/// <summary>
512+
/// Gets a value indicating whether to elevate all build properties to cloud build variables prefaced with "NBGV_".
513+
/// </summary>
514+
[JsonIgnore]
515+
public bool SetAllVariablesOrDefault => this.SetAllVariables ?? DefaultInstance.SetAllVariables.Value;
516+
498517
/// <summary>
499518
/// Gets a value indicating whether to elevate certain calculated version build properties to cloud build variables.
500519
/// </summary>
@@ -562,13 +581,15 @@ public bool Equals(CloudBuildOptions x, CloudBuildOptions y)
562581
}
563582

564583
return x.SetVersionVariablesOrDefault == y.SetVersionVariablesOrDefault
584+
&& x.SetAllVariablesOrDefault == y.SetAllVariablesOrDefault
565585
&& CloudBuildNumberOptions.EqualWithDefaultsComparer.Singleton.Equals(x.BuildNumberOrDefault, y.BuildNumberOrDefault);
566586
}
567587

568588
/// <inheritdoc />
569589
public int GetHashCode(CloudBuildOptions obj)
570590
{
571-
return obj.SetVersionVariablesOrDefault ? 1 : 0
591+
return (obj.SetVersionVariablesOrDefault ? 1 : 0)
592+
+ (obj.SetAllVariablesOrDefault ? 1 : 0)
572593
+ obj.BuildNumberOrDefault.GetHashCode();
573594
}
574595
}

src/NerdBank.GitVersioning/VersionOptionsContractResolver.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,11 @@ protected override JsonProperty CreateProperty(MemberInfo member, MemberSerializ
4444
property.ShouldSerialize = instance => !((VersionOptions)instance).CloudBuildOrDefault.IsDefault;
4545
}
4646

47+
if (property.DeclaringType == typeof(VersionOptions.CloudBuildOptions) && member.Name == nameof(VersionOptions.CloudBuildOptions.SetAllVariables))
48+
{
49+
property.ShouldSerialize = instance => ((VersionOptions.CloudBuildOptions)instance).SetAllVariablesOrDefault != VersionOptions.CloudBuildOptions.DefaultInstance.SetAllVariables.Value;
50+
}
51+
4752
if (property.DeclaringType == typeof(VersionOptions.CloudBuildOptions) && member.Name == nameof(VersionOptions.CloudBuildOptions.SetVersionVariables))
4853
{
4954
property.ShouldSerialize = instance => ((VersionOptions.CloudBuildOptions)instance).SetVersionVariablesOrDefault != VersionOptions.CloudBuildOptions.DefaultInstance.SetVersionVariables.Value;

src/NerdBank.GitVersioning/VersionOracle.cs

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System.Globalization;
66
using System.IO;
77
using System.Linq;
8+
using System.Reflection;
89
using System.Text.RegularExpressions;
910
using Validation;
1011

@@ -124,11 +125,13 @@ public string CloudBuildNumber
124125
/// <summary>
125126
/// Gets a value indicating whether the cloud build number should be set.
126127
/// </summary>
128+
[Ignore]
127129
public bool CloudBuildNumberEnabled => this.CloudBuildNumberOptions.EnabledOrDefault;
128130

129131
/// <summary>
130132
/// Gets the build metadata identifiers, including the git commit ID as the first identifier if appropriate.
131133
/// </summary>
134+
[Ignore]
132135
public IEnumerable<string> BuildMetadataWithCommitId
133136
{
134137
get
@@ -228,16 +231,53 @@ public IEnumerable<string> BuildMetadataWithCommitId
228231
/// </summary>
229232
public Version Version { get; }
230233

234+
/// <summary>
235+
/// Gets a value indicating whether to set all cloud build variables prefaced with "NBGV_".
236+
/// </summary>
237+
[Ignore]
238+
public bool CloudBuildAllVarsEnabled => this.VersionOptions?.CloudBuildOrDefault.SetAllVariablesOrDefault
239+
?? VersionOptions.CloudBuildOptions.DefaultInstance.SetAllVariablesOrDefault;
240+
241+
/// <summary>
242+
/// Gets a dictionary of all cloud build variables that applies to this project,
243+
/// regardless of the current setting of <see cref="CloudBuildAllVarsEnabled"/>.
244+
/// </summary>
245+
[Ignore]
246+
public IDictionary<string, string> CloudBuildAllVars
247+
{
248+
get
249+
{
250+
var variables = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
251+
252+
var properties = this.GetType().GetTypeInfo().GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance);
253+
foreach (var property in properties)
254+
{
255+
if (property.GetCustomAttribute<IgnoreAttribute>() == null)
256+
{
257+
var value = property.GetValue(this);
258+
if (value != null)
259+
{
260+
variables.Add($"NBGV_{property.Name}", value.ToString());
261+
}
262+
}
263+
}
264+
265+
return variables;
266+
}
267+
}
268+
231269
/// <summary>
232270
/// Gets a value indicating whether to set cloud build version variables.
233271
/// </summary>
272+
[Ignore]
234273
public bool CloudBuildVersionVarsEnabled => this.VersionOptions?.CloudBuildOrDefault.SetVersionVariablesOrDefault
235274
?? VersionOptions.CloudBuildOptions.DefaultInstance.SetVersionVariablesOrDefault;
236275

237276
/// <summary>
238277
/// Gets a dictionary of cloud build variables that applies to this project,
239278
/// regardless of the current setting of <see cref="CloudBuildVersionVarsEnabled"/>.
240279
/// </summary>
280+
[Ignore]
241281
public IDictionary<string, string> CloudBuildVersionVars
242282
{
243283
get
@@ -254,6 +294,7 @@ public IDictionary<string, string> CloudBuildVersionVars
254294
/// <summary>
255295
/// Gets the list of build metadata identifiers to include in semver version strings.
256296
/// </summary>
297+
[Ignore]
257298
public List<string> BuildMetadata { get; } = new List<string>();
258299

259300
/// <summary>
@@ -450,5 +491,10 @@ private static bool IsVersionFileChangedInWorkingTree(VersionOptions committedVe
450491
// A missing working version is a change only if it was previously commited.
451492
return committedVersion != null;
452493
}
494+
495+
[AttributeUsage(AttributeTargets.Property)]
496+
private class IgnoreAttribute : Attribute
497+
{
498+
}
453499
}
454500
}

src/NerdBank.GitVersioning/version.schema.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,11 @@
9494
"type": "object",
9595
"description": "Options that are applicable specifically to cloud builds (e.g. VSTS, AppVeyor, TeamCity)",
9696
"properties": {
97+
"setAllVariables": {
98+
"type": "boolean",
99+
"default": false,
100+
"description": "Elevates all build properties to cloud build variables prefaced with \"NBGV_\""
101+
},
97102
"setVersionVariables": {
98103
"type": "boolean",
99104
"default": true,

src/Nerdbank.GitVersioning.Tasks/GetBuildVersion.cs

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -190,11 +190,32 @@ protected override bool ExecuteInner()
190190
this.NuGetPackageVersion = oracle.NuGetPackageVersion;
191191
this.NpmPackageVersion = oracle.NpmPackageVersion;
192192

193+
IEnumerable<ITaskItem> cloudBuildVersionVars = null;
193194
if (oracle.CloudBuildVersionVarsEnabled)
194195
{
195-
this.CloudBuildVersionVars = oracle.CloudBuildVersionVars
196-
.Select(item => new TaskItem(item.Key, new Dictionary<string, string> { { "Value", item.Value } }))
197-
.ToArray();
196+
cloudBuildVersionVars = oracle.CloudBuildVersionVars
197+
.Select(item => new TaskItem(item.Key, new Dictionary<string, string> { { "Value", item.Value } }));
198+
}
199+
200+
if (oracle.CloudBuildAllVarsEnabled)
201+
{
202+
var allVariables = oracle.CloudBuildAllVars
203+
.Select(item => new TaskItem(item.Key, new Dictionary<string, string> { { "Value", item.Value } }));
204+
205+
if (cloudBuildVersionVars != null)
206+
{
207+
cloudBuildVersionVars = cloudBuildVersionVars
208+
.Union(allVariables);
209+
}
210+
else
211+
{
212+
cloudBuildVersionVars = allVariables;
213+
}
214+
}
215+
216+
if (cloudBuildVersionVars != null)
217+
{
218+
this.CloudBuildVersionVars = cloudBuildVersionVars.ToArray();
198219
}
199220

200221
return !this.Log.HasLoggedErrors;

0 commit comments

Comments
 (0)