Add ArgumentOrEnvironmentVariable overload for strings.

This commit is contained in:
Adam Patridge 2017-08-25 16:28:43 -06:00
parent 22efc1e2c0
commit 049f8df957
6 changed files with 237 additions and 45 deletions

View file

@ -4,7 +4,7 @@ using Moq;
namespace Cake.ArgumentHelpers.Tests { namespace Cake.ArgumentHelpers.Tests {
[TestFixture()] [TestFixture()]
public class ArgumentOrEnvironmentVariableAliasTests { public class ArgumentOrEnvironmentVariableAlias_BoolTests {
Mock<ICakeContext> cakeContextMock; Mock<ICakeContext> cakeContextMock;
Mock<ICakeArguments> cakeArgumentsMock; Mock<ICakeArguments> cakeArgumentsMock;
Mock<ICakeEnvironment> cakeEnvironmentMock; Mock<ICakeEnvironment> cakeEnvironmentMock;

View file

@ -0,0 +1,136 @@
using NUnit.Framework;
using Cake.Core;
using Moq;
namespace Cake.ArgumentHelpers.Tests {
[TestFixture()]
public class ArgumentOrEnvironmentVariableAlias_StringTests {
Mock<ICakeContext> cakeContextMock;
Mock<ICakeArguments> cakeArgumentsMock;
Mock<ICakeEnvironment> cakeEnvironmentMock;
[SetUp]
public void Setup() {
cakeContextMock = new Mock<ICakeContext>();
cakeArgumentsMock = new Mock<ICakeArguments>();
cakeEnvironmentMock = new Mock<ICakeEnvironment>();
cakeContextMock.Setup(cakeContext => cakeContext.Arguments).Returns(cakeArgumentsMock.Object);
cakeContextMock.Setup(cakeContext => cakeContext.Environment).Returns(cakeEnvironmentMock.Object);
}
void SetupVariables(string key, string environmentPrefix, string argumentValue, string environmentValue) {
bool hasArgument = argumentValue != null;
cakeArgumentsMock.Setup(x => x.HasArgument(key)).Returns(hasArgument);
if (hasArgument) {
cakeArgumentsMock.Setup(x => x.GetArgument(key)).Returns(argumentValue.ToString());
}
bool hasEnvironmentVariable = environmentValue != null;
if (hasEnvironmentVariable)
{
cakeEnvironmentMock.Setup(x => x.GetEnvironmentVariable(environmentPrefix + key)).Returns(environmentValue);
}
}
[Test]
public void SomeArgumentAndNullEnvironment_ReturnsSome() {
var testKey = "someVariable";
var testKeyEnvironmentPrefix = "somePrefix_";
string testArgumentValue = "Some";
string testEnvironmentValue = null;
SetupVariables(testKey, testKeyEnvironmentPrefix, testArgumentValue, testEnvironmentValue);
var expected = testArgumentValue;
var actual = cakeContextMock.Object.ArgumentOrEnvironmentVariable(testKey, testKeyEnvironmentPrefix, (string)null);
Assert.AreEqual(expected, actual, "Didn't find Argument variable.");
}
[Test]
public void NullArgumentAndNullEnvironmentAndNullDefault_ReturnsNull() {
var testKey = "someVariable";
var testKeyEnvironmentPrefix = "somePrefix_";
string testArgumentValue = null;
string testEnvironmentValue = null;
SetupVariables(testKey, testKeyEnvironmentPrefix, testArgumentValue, testEnvironmentValue);
var expected = (string)null;
var actual = cakeContextMock.Object.ArgumentOrEnvironmentVariable(testKey, testKeyEnvironmentPrefix, (string)null);
Assert.AreEqual(expected, actual, "Found unexpected variable value.");
}
[Test]
public void NullArgumentAndSomeEnvironment_ReturnsSome() {
var testKey = "someVariable";
var testKeyEnvironmentPrefix = "somePrefix_";
string testArgumentValue = null;
string testEnvironmentValue = "Some";
SetupVariables(testKey, testKeyEnvironmentPrefix, testArgumentValue, testEnvironmentValue);
var expected = testEnvironmentValue;
var actual = cakeContextMock.Object.ArgumentOrEnvironmentVariable(testKey, testKeyEnvironmentPrefix, (string)null);
Assert.AreEqual(expected, actual, "Didn't find Environment variable.");
}
[Test]
public void NullArgumentAndSomeEnvironmentWithoutPrefix_ReturnsSome() {
var testKey = "someVariable";
var testKeyEnvironmentPrefix = (string)null;
string testArgumentValue = null;
string testEnvironmentValue = "Some";
SetupVariables(testKey, testKeyEnvironmentPrefix, testArgumentValue, testEnvironmentValue);
var expected = testEnvironmentValue;
var actual = cakeContextMock.Object.ArgumentOrEnvironmentVariable(testKey, testKeyEnvironmentPrefix, (string)null);
Assert.AreEqual(expected, actual, "Didn't find Environment variable without prefix.");
}
[Test]
public void SomeArgumentAndOtherEnvironment_ReturnsSome() {
var testKey = "someVariable";
var testKeyEnvironmentPrefix = "somePrefix_";
string testArgumentValue = "Some";
string testEnvironmentValue = "Other";
SetupVariables(testKey, testKeyEnvironmentPrefix, testArgumentValue, testEnvironmentValue);
var expected = testArgumentValue;
var actual = cakeContextMock.Object.ArgumentOrEnvironmentVariable(testKey, testKeyEnvironmentPrefix, (string)null);
Assert.AreEqual(expected, actual, "Didn't find correct variable value from Argument source.");
}
[Test]
public void NullArgumentAndNullEnvironment_ReturnsDefault()
{
var testKey = "someVariable";
var testKeyEnvironmentPrefix = "somePrefix_";
var defaultValue = "Default";
string testArgumentValue = null;
string testEnvironmentValue = null;
SetupVariables(testKey, testKeyEnvironmentPrefix, testArgumentValue, testEnvironmentValue);
var expected = defaultValue;
var actual = cakeContextMock.Object.ArgumentOrEnvironmentVariable(testKey, testKeyEnvironmentPrefix, defaultValue);
Assert.AreEqual(expected, actual, "Didn't fall back on default value.");
}
[Test]
public void NullArgumentAndNullEnvironmentWithoutDefault_ReturnsNull()
{
var testKey = "someVariable";
var testKeyEnvironmentPrefix = "somePrefix_";
string testArgumentValue = null;
string testEnvironmentValue = null;
SetupVariables(testKey, testKeyEnvironmentPrefix, testArgumentValue, testEnvironmentValue);
var expected = (string)null;
var actual = cakeContextMock.Object.ArgumentOrEnvironmentVariable(testKey, testKeyEnvironmentPrefix);
Assert.AreEqual(expected, actual, "Didn't fail to a null value.");
}
}
}

View file

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -43,7 +43,8 @@
</Reference> </Reference>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="ArgumentOrEnvironmentVariableAliasTests.cs" /> <Compile Include="ArgumentOrEnvironmentVariableAlias_StringTests.cs" />
<Compile Include="ArgumentOrEnvironmentVariableAlias_BoolTests.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="packages.config" /> <None Include="packages.config" />
@ -54,5 +55,8 @@
<Name>Cake.ArgumentHelpers</Name> <Name>Cake.ArgumentHelpers</Name>
</ProjectReference> </ProjectReference>
</ItemGroup> </ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project> </Project>

View file

@ -1,13 +1,15 @@
 
Microsoft Visual Studio Solution File, Format Version 12.00 Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15 # Visual Studio 15
VisualStudioVersion = 15.0.26430.13 VisualStudioVersion = 15.0.26730.10
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Cake.ArgumentHelpers", "Cake.ArgumentHelpers\Cake.ArgumentHelpers.csproj", "{9C50A7C4-E00D-4851-8311-81135D062C77}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Cake.ArgumentHelpers", "Cake.ArgumentHelpers\Cake.ArgumentHelpers.csproj", "{9C50A7C4-E00D-4851-8311-81135D062C77}"
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{EA17B50A-988B-47C1-9840-DC7347D88259}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{EA17B50A-988B-47C1-9840-DC7347D88259}"
ProjectSection(SolutionItems) = preProject ProjectSection(SolutionItems) = preProject
LICENSE = LICENSE
Package.nuspec = Package.nuspec Package.nuspec = Package.nuspec
README.md = README.md
EndProjectSection EndProjectSection
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Cake.ArgumentHelpers.Tests", "Cake.ArgumentHelpers.Tests\Cake.ArgumentHelpers.Tests.csproj", "{1297E243-9A95-45A5-A5C6-AAAC94ECEE22}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Cake.ArgumentHelpers.Tests", "Cake.ArgumentHelpers.Tests\Cake.ArgumentHelpers.Tests.csproj", "{1297E243-9A95-45A5-A5C6-AAAC94ECEE22}"
@ -30,42 +32,45 @@ Global
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
EndGlobalSection EndGlobalSection
GlobalSection(MonoDevelopProperties) = preSolution GlobalSection(ExtensibilityGlobals) = postSolution
Policies = $0 SolutionGuid = {E1B5DAA9-DAD7-4FEA-8B04-2E4A112C196F}
$0.TextStylePolicy = $1 EndGlobalSection
$1.NoTabsAfterNonTabs = True GlobalSection(MonoDevelopProperties) = preSolution
$1.inheritsSet = VisualStudio Policies = $0
$1.inheritsScope = text/plain $0.TextStylePolicy = $1
$1.scope = text/x-csharp $1.NoTabsAfterNonTabs = True
$0.CSharpFormattingPolicy = $2 $1.inheritsSet = VisualStudio
$2.NamespaceBraceStyle = EndOfLine $1.inheritsScope = text/plain
$2.ClassBraceStyle = EndOfLine $1.scope = text/x-csharp
$2.InterfaceBraceStyle = EndOfLine $0.CSharpFormattingPolicy = $2
$2.StructBraceStyle = EndOfLine $2.NamespaceBraceStyle = EndOfLine
$2.EnumBraceStyle = EndOfLine $2.ClassBraceStyle = EndOfLine
$2.MethodBraceStyle = EndOfLine $2.InterfaceBraceStyle = EndOfLine
$2.ConstructorBraceStyle = EndOfLine $2.StructBraceStyle = EndOfLine
$2.DestructorBraceStyle = EndOfLine $2.EnumBraceStyle = EndOfLine
$2.ElseNewLinePlacement = NewLine $2.MethodBraceStyle = EndOfLine
$2.BeforeMethodDeclarationParentheses = False $2.ConstructorBraceStyle = EndOfLine
$2.BeforeMethodCallParentheses = False $2.DestructorBraceStyle = EndOfLine
$2.BeforeConstructorDeclarationParentheses = False $2.ElseNewLinePlacement = NewLine
$2.BeforeIndexerDeclarationBracket = False $2.BeforeMethodDeclarationParentheses = False
$2.BeforeDelegateDeclarationParentheses = False $2.BeforeMethodCallParentheses = False
$2.AfterDelegateDeclarationParameterComma = True $2.BeforeConstructorDeclarationParentheses = False
$2.NewParentheses = False $2.BeforeIndexerDeclarationBracket = False
$2.SpacesBeforeBrackets = False $2.BeforeDelegateDeclarationParentheses = False
$2.inheritsSet = Mono $2.AfterDelegateDeclarationParameterComma = True
$2.inheritsScope = text/x-csharp $2.NewParentheses = False
$2.scope = text/x-csharp $2.SpacesBeforeBrackets = False
$2.NewLinesForBracesInTypes = False $2.inheritsSet = Mono
$2.NewLinesForBracesInMethods = False $2.inheritsScope = text/x-csharp
$2.SpacingAfterMethodDeclarationName = False $2.scope = text/x-csharp
$2.SpaceAfterMethodCallName = False $2.NewLinesForBracesInTypes = False
$2.SpaceBeforeOpenSquareBracket = False $2.NewLinesForBracesInMethods = False
$0.DotNetNamingPolicy = $3 $2.SpacingAfterMethodDeclarationName = False
$3.DirectoryNamespaceAssociation = None $2.SpaceAfterMethodCallName = False
$3.ResourceNamePolicy = FileFormatDefault $2.SpaceBeforeOpenSquareBracket = False
StartupItem = Smudges.iOS\Smudges.iOS.csproj $0.DotNetNamingPolicy = $3
EndGlobalSection $3.DirectoryNamespaceAssociation = None
$3.ResourceNamePolicy = FileFormatDefault
StartupItem = Smudges.iOS\Smudges.iOS.csproj
EndGlobalSection
EndGlobal EndGlobal

View file

@ -13,6 +13,7 @@ namespace Cake.ArgumentHelpers {
/// <summary> /// <summary>
/// Get a bool variable from various script inputs: first via Argument, then falling back on EnvironmentVariable, finally falling back on a default. /// Get a bool variable from various script inputs: first via Argument, then falling back on EnvironmentVariable, finally falling back on a default.
/// </summary> /// </summary>
/// <param name="name">The argument name to attempt to find in the command line parameters, prefixing with <paramref name="environmentNamePrefix"/> to attempt to find in environment variables.</param>
/// <param name="environmentNamePrefix">An optional prefix used to qualify the same variable name when present in EnvironmentVariable form (e.g., "MySetting" command-line argument vs. "MyTool_MySetting" environment variable).</param> /// <param name="environmentNamePrefix">An optional prefix used to qualify the same variable name when present in EnvironmentVariable form (e.g., "MySetting" command-line argument vs. "MyTool_MySetting" environment variable).</param>
/// <returns>Value found or default, first checked in command-line argument, then environment variable.</returns> /// <returns>Value found or default, first checked in command-line argument, then environment variable.</returns>
[CakeMethodAlias] [CakeMethodAlias]
@ -25,6 +26,7 @@ namespace Cake.ArgumentHelpers {
/// <summary> /// <summary>
/// Get a bool variable from various script inputs: first via Argument, then falling back on EnvironmentVariable, finally falling back on a default. /// Get a bool variable from various script inputs: first via Argument, then falling back on EnvironmentVariable, finally falling back on a default.
/// </summary> /// </summary>
/// <param name="name">The argument name to attempt to find in either the command line parameters or environment variables.</param>
/// <returns>Value found or default, first checked in command-line argument, then environment variable.</returns> /// <returns>Value found or default, first checked in command-line argument, then environment variable.</returns>
[CakeMethodAlias] [CakeMethodAlias]
[CakeAliasCategory("Argument")] [CakeAliasCategory("Argument")]
@ -32,5 +34,32 @@ namespace Cake.ArgumentHelpers {
public static bool ArgumentOrEnvironmentVariable(this ICakeContext context, string name, bool defaultValue) { public static bool ArgumentOrEnvironmentVariable(this ICakeContext context, string name, bool defaultValue) {
return context.ArgumentOrEnvironmentVariable(name, null, defaultValue); return context.ArgumentOrEnvironmentVariable(name, null, defaultValue);
} }
/// <summary>
/// Get a string variable from various script inputs: first via Argument, then falling back on EnvironmentVariable, finally falling back on a default.
/// </summary>
/// <param name="name">The argument name to attempt to find in the command line parameters, prefixing with <paramref name="environmentNamePrefix"/> to attempt to find in environment variables.</param>
/// <param name="environmentNamePrefix">An optional prefix used to qualify the same variable name when present in EnvironmentVariable form (e.g., "MySetting" command-line argument vs. "MyTool_MySetting" environment variable).</param>
/// <returns>Value found or default, first checked in command-line argument, then environment variable.</returns>
[CakeMethodAlias]
[CakeAliasCategory("Argument")]
[CakeAliasCategory("Environment")]
public static string ArgumentOrEnvironmentVariable(this ICakeContext context, string name, string environmentNamePrefix, string defaultValue) {
return ArgumentAliases.Argument<string>(context, name, EnvironmentAliases.EnvironmentVariable(context, environmentNamePrefix + name)) ?? defaultValue;
}
/// <summary>
/// Get a string variable from various script inputs: first via Argument, then falling back on EnvironmentVariable, finally falling back on a default.
/// </summary>
/// <param name="name">The argument name to attempt to find in the command line parameters, prefixing with <paramref name="environmentNamePrefix"/> to attempt to find in environment variables.</param>
/// <param name="environmentNamePrefix">An optional prefix used to qualify the same variable name when present in EnvironmentVariable form (e.g., "MySetting" command-line argument vs. "MyTool_MySetting" environment variable).</param>
/// <returns>Value found or default, first checked in command-line argument, then environment variable.</returns>
[CakeMethodAlias]
[CakeAliasCategory("Argument")]
[CakeAliasCategory("Environment")]
public static string ArgumentOrEnvironmentVariable(this ICakeContext context, string name, string environmentNamePrefix)
{
return ArgumentOrEnvironmentVariable(context, name, environmentNamePrefix, null);
}
} }
} }

View file

@ -10,9 +10,9 @@ Just reference the Cake.ArgumentHelpers NuGet package directly in your build scr
## Available Aliases ## Available Aliases
Yep, just one so far... Yep, just two so far...
### ArgumentOrEnvironmentVariable ### ArgumentOrEnvironmentVariable (for boolean values)
`bool ArgumentOrEnvironmentVariable(..., string name, string environmentNamePrefix, bool defaultValue)` `bool ArgumentOrEnvironmentVariable(..., string name, string environmentNamePrefix, bool defaultValue)`
@ -32,4 +32,22 @@ Given a potential command line argument of `SomeSetting` that could also be set
var isSomethingTrue = ArgumentOrEnvironmentVariable("SomeSetting", "SomeProject_", false); var isSomethingTrue = ArgumentOrEnvironmentVariable("SomeSetting", "SomeProject_", false);
``` ```
## ### ArgumentOrEnvironmentVariable (for string values)
`string ArgumentOrEnvironmentVariable(..., string name, string environmentNamePrefix[, string defaultValue])`
This is a helper method that simply wraps around nested calls to Arugment and EnvironmentVariable (and offering a fallback default).
It works by getting a string value with multiple fallbacks:
1. Try to get it from `Argument` (e.g., command line: `-SomeSetting="SomeValue"`)
2. Try to get it from `EnvironmentVariable` (e.g., `$env:SomeProject_SomeSetting = "SomeOtherValue";`)
3. Use a `defaultValue` if we don't find it elsewhere
#### Example
Given a potential command line argument of `SomeSetting` that could also be set via an environment variable prefixed with a project name, get the boolean value or `false` if it isn't found:
```csharp
var someVariableValue = ArgumentOrEnvironmentVariable("SomeSetting", "SomeProject_", "SomeFallbackValue");
```