Include argument in NAnt executable call if property is not null or empty - conditional-statements

For a build script, part of my process is to deploy files using an in-house executable. We call this with a number of parameters.
On an application I'm working on, it turns out we need to add a parameter. This isn't something that retroactively applies to anything else I've previously worked on, so the idea is that I would only include the new argument if the corresponding property is not null or empty.
Relevant NAnt Call:
<property name="deploy.NewArg" value="" />
<echo message="deploy.NewArg = ${deploy.NewArg}" />
<exec program="C:\Deploy\MyAwesomeDeployProgram.exe">
<arg value="AppTitle=${deploy.AppTitle}" />
<arg value="Environment=${deploy.Environment}" />
<!-- Here's the problem argument... -->
<arg value="MyNewProperty=${deploy.NewArg}" if="${deploy.NewArg}" />
</exec>
The reason what I have is not working, is because of the if clause on the new <arg> tag - the deploy.NewArg string doesn't convert to a boolean statement.
Question: In what way can I perform an "Is Null or Empty" check on an <arg if> parameter? As noted above, I want the MyNewProperty=... argument added if deploy.NewArg is anything but nothing or an empty string.
I checked a number of other StackOverflow questions, as well as the official NAnt arg tag documentation, but could not find how to do this.

It turns out, I needed to get back to the basics, and check out some of my fundamentals and functions. The way to do an 'is empty' check on a property is as below:
<exec program="C:\Deploy\MyAwesomeDeployProgram.exe">
<!-- Other args... -->
<arg value="MyNewProperty=${deploy.NewArg}" if=${string::get-length(deploy.NewArg) > 0}" />
</exec>
For someone who hasn't yet done the research, if only works with a boolean. That being said, booleans can be generated in one of two ways: either an explicit true or false, or by using an expression. Expressions are always contained in ${} brackets. The use of string::get-length() should be obvious.
Bring it all together, and you only include an argument if it's specified.

Related

How to get Directory name in msbuild configuration file?

Here is the simple code which I am using. Which gets all the folders in the directory and then give me the Folder name.
<TestProjectFolderPath Include="$([System.IO.Directory]::GetDirectories(`$(SolutionDir)`,`*.Tests`))" />
<TestProjectFolderNames Include="#(TestProjectFolderPath->'$([System.IO.Path]::GetDirectoryName(`$([System.IO.Path]::GetFileName(`%(Identity)`))`)',' ')" />
But in TestProjectFolderNames [System.IO.Path] functions are not getting evaluated and returned as just string eg:
$([System.IO.Path]::GetDirectoryName($([System.IO.Path]::GetFileName(C:\Some.Unit.Tests)))
I need help to understand the correct syntax to get this working.
Using property functions on Item Metadata while transforming an Item is not supported I think (maybe it is in the latest MSBuild version but I cannot test that right now). As a workaround add new Metadata yourself and because it acts like a Property things work out ok for recent MSBuild versions:
<ItemGroup>
<TestProjectFolderPath Include="$([System.IO.Directory]::GetDirectories(`$(SolutionDir)`,`*.Tests`))" />
<TestProjectFolderPath>
<FolderName>$([System.IO.Path]::GetFileName(`%(Identity)`))</FolderName>
</TestProjectFolderPath>
</ItemGroup>
<Message Text="#(TestProjectFolderPath->'%(FolderName)', ' ')" />
edit see comments, according to Sherry for older MSBuild versions the equivalent Item code is:
<TestProjectFolderPath Include="$([System.IO.Directory]::GetDirectories($(SolutionDir),*.Tests))">
<FolderName>$([System.IO.Path]::GetFileName(%(Identity)))</FolderName>
</TestProjectFolderPath>
I left out GetDirectoryName because it makes little sense calling that on the result of GetFileName.

MSBuild Filtering ItemGroup of files with condition

This feels like it's so simple, but I cannot get it to work.
All I'm trying to achieve is a filtered list of the embedded resources. I've tried various approaches but I can't seem to get it right.
Here's what I thought was the right solution:
<ItemGroup>
<AllEmbeddedResources Include="#(EmbeddedResource)" Condition="$(FullPath.Contains('Change')"/>
</ItemGroup>
Edit...
To clarify, the results are without the condition, the list is all embedded resources, with the condition, the group is empty.
I've tried this inside and outside of target's, and I've tried getting the full list in one group, and then filtering in a separate group. I know I'm just misunderstanding some fundamental part of msbuild syntax, I just can't seem to work it out. Looking forward to being shown my stupid mistake!
Inside a target, this can be done using the batching syntax for items and using the System.String.Copy method to be able to call instance functions on the string:
<Target Name="ListAllEmbeddedResources">
<ItemGroup>
<AllEmbeddedResources Include="#(EmbeddedResource)" Condition="$([System.String]::Copy(%(FullPath)).Contains('Change'))" />
</ItemGroup>
<Message Importance="high" Text="AllEmbeddedResources: %(AllEmbeddedResources.Identity)" />
</Target>
Note that this syntax only works inside a target and not during static evaluation (item group directly under the <Project> node).
The Condition Attribute must return a boolean, and it operates on each element of the itemgroup.
You can access each element using %(Identity).
Say you have some unfiltered itemgroup called UnfilteredItems, and you want to filter those into a group called MyFilteredItems, using some regex pattern.
<ItemGroup>
<MyFilteredItems Include="#(UnfilteredItems)" Condition="$([System.Text.RegularExpressions.Regex]::Match(%(Identity),'.*\\bin\\.*').Success)"/>
</ItemGroup>

Msbuild- 'DependsOnTargets' that contain condition

I tried to have a condition on a Target tag, but resulted with the error:
target has a reference to item metadata. References
to item metadata are not allowed in target conditions unless they are part of an item transform.
So i found this work around:
How to add item transform to VS2012 .proj msbuild file
and tried to implement it, but i can't figure up what i am doing wrong because it's not working as expected.
<CallTarget Targets="CopyOldWebConfigJs" />
<Target Name="CopyOldWebConfigJs"
Inputs="#(ContentFiltered)"
Outputs="%(Identity).Dummy"
DependsOnTargets="webConfigJsCase">
<Message Text="web.config.js Case" />
</Target>
<!-- New target to pre-filter list -->
<Target Name="webConfigJsCase"
Inputs="#(FileToPublish)"
Outputs="%(Identity).Dummy">
<ItemGroup>
<ContentFiltered Condition="$([System.Text.RegularExpressions.Regex]::IsMatch('%(FileToPublish.Filename)%(FileToPublish.Extension)', 'web.config.js'))" />
</ItemGroup>
</Target>
I thought that Inputs="#(ContentFiltered)" will contain the lines that DependsOnTargets="webConfigJsCase" find.
But when i run it , i am getting this message: Skipping target "CopyOldWebConfigJs" because it has no inputs.
I know for a fact that the regex work, and it do find a filename_ext that equals web.config.js so it return True
What do i do or understand wrong?
In <ItemGroup><Item/></ItemGroup>, no change will be made to the Item item because no action was specified. If you want to add entries to the item, you must specify Include="".
The <Item/> documentation describes the various attributes for item elements inside of an <ItemGroup/>. Note that at the top-level of an MSBuild file, directly under the <Project/> element, you would use the attributes Include and Exclude while in a <Target/> you would use the attributes Include and Remove. Not including any attributes at all is nonsensical and—as far as I know—no different than simply deleting the entire line. I am surprised MSBuild doesn’t throw an error or warning this is almost certainly a mistake and not intentional.
The Inputs and Outputs attributes on your <Target Name="webConfigJsCase"/> are unnecessary. In fact, they slow MSBuild down by making it loop over the target unnecessarily. You can filter just in the <Item/> like this:
<Target Name="webConfigJsCase">
<ItemGroup>
<ContentFiltered Condition="'%(FileToPublish.Filename)%(FileToPublish.Extension)' == 'web.config.js'" Include="#(FileToPublish)" />
</ItemGroup>
</Target>
Additionally, I assume that you intended your regular expression to match web.config.js but not match webaconfigbjs. You don’t need to use an advanced feature like Regular Expressions here because MSBuild’s built-in condition operators already support simple string comparison. If fixed the condition above to be more readable.

how to use MSBuild ItemGroup members as individual items like Properties?

So I'm kinda getting the hang of writing in MSBuild.
I like the idea storing things in ItemGroups because its easy to iterate, and you can have multple fields.
That makes them sort of like a class (more like a struct) but they respond to the iteration syntax of targets and tasks in a way that feels like a lambda expression.
However I continue to run into situation where I want to access a value of a particular item in an item group, that is, to access it like a property.
In that case I run into the issue of how to isolate a single item within the group.
When the item group is batching in a target or task, because of addressing using a metadata name or because of addressing with the common itemgroup name, you can utilize the value of the 'current' item i.e. #(ItemsName) or %(MetaDataName).
But I want to do things like: use an Item group as a System.Configuration class that contains the values of the entries in a section of a config file. Therefore the normal thing would be to name the ItemGroup itself to match the section name in the config file. however, the ItemGroup is not an addressable element that is accessible through the build engine interface, only the items themselves are addressable.
It might be nice to individually name the items in an ItemGroup rather than name them all the same and use the Include or a metadata field like to distinguish among them. This makes them behave like properties in that they are individually addressable as distinct items. so you could easily use their values in Conditions this way: '#(UniqueItemName->'%(Value)').
However, then the iterable features are essentially lost.
To narrow this down, presume i have a config file that gets read into an Item group by and xml task so that the element names in a section become the name of the items in the item group and attributes of each config file element are attributes that become metadata:
<configItemFlag name="displayDebugMessages" value="true" note="use with abandon" />
<configItemFlag name="displaySecurityValueMessages" value="false" note="use with caution" />
When I want to test this in a Condition, I need to narrow it down to something like this:
<Messge Text="Debug Message: you are debugging!" Condition="'#(configItemFlag->'%(Name)')' == 'displayDebugMessages' AND '#(configItemFlag->'%(Value)')' == 'true'/>
But this only evaluates the comparison and frequently does not evaluate to a single boolean.
So is there any way to syntacticly get this down to a dependable test?
Does this work for what you are trying to do?
<ItemGroup>
<ConfigItemFlag Include="displayDebugMessages">
<Value>true</Value>
<Note>use with abandon</Note>
</ConfigItemFlag>
<ConfigItemFlag Include="displaySecurityValueMessages">
<Value>false</Value>
<Note>use with caution</Note>
</ConfigItemFlag>
</ItemGroup>
<Target Name="Build">
<Message
Condition="
'%(ConfigItemFlag.Identity)' == 'displayDebugMessages' AND
'%(Value)' == 'true'"
Text="Debug Message: you are debugging, %(Note)!"
/>
</Target>
Output:
Build:
Debug Message: you are debugging, use with abandon!
(response to comment)
...the only thing I can offer to be able to use meta as properties isn't all that great, unless the target will make heavy use of them throughout. Basically it involves flattening each item to properties by batching on the item and creating local properties with each batch.
<Target Name="BuildOne"
Outputs="%(ConfigItemFlag.Identity)">
<!-- flatten this batch to properties -->
<PropertyGroup>
<_Identity>%(ConfigItemFlag.Identity)</_Identity>
<_Value>%(ConfigItemFlag.Value)</_Value>
<_Note>%(ConfigItemFlag.Note)</_Note>
</PropertyGroup>
<!-- use meta as properties -->
<Message
Condition="
'$(_Identity)' == 'displayDebugMessages' AND
'$(_Value)' == 'true'"
Text="Debug Message: you are debugging, $(_Note)!"
/>
</Target>
<Target Name="Build" DependsOnTargets="BuildOne"
/>
It seems like you are running into some of the limitations of the msbuild scripting language. Have you thought about writing a custom task to perform what you are looking for? That way you would be able to bring the full power of a full programming language to bear against the simple conditional check you want to perform.

how to get extension name (without dot) in MSBuild

I have an ItemGroup, and I use its metadata as identifiers in my MSBuild project for batch processing. For example:
<BuildStep
TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
BuildUri="$(BuildUri)"
Name="RunUnitTestsStep-%(TestSuite.Filename)-%(TestSuite.Extension)"
Message=" - Unit Tests: %(TestSuite.Filename): %(TestSuite.Extension)">
<Output
TaskParameter="Id"
PropertyName="RunUnitTestsStepId-%(TestSuite.Filename)-%(TestSuite.Extension)" />
</BuildStep>
However, this will not work, because there is a dot in the Extension, which is invalid character for an Id (in the BuildStep task). Thus, the MSBuild always fails on the BuildStep task.
I've been trying to remove the dot, but with no luck. Maybe there is a way to add some metadata to en existing ItemGroup? Ideally, I would like to have something like %(TestSuite.ExtensionWithoutDot). How can I achieve that?
I think you are slightly confused about what the <Output> element is doing here - it will create a property named with the value in the PropertyName attribute, and will set the value of that property to be value of the Id output from the BuildStep task. You have no influence on the value of Id - you just store it in a property for later reference in order to set the status of the build step
With that in mind, I can't see why you are concerned that the Property created would have a name that would include the concatenation of the extension. As long as the property name is unique, you can reference it later in a subsequent BuildStep task, and I presume your testsuite filename is enough to indicate uniqueness.
In fact, you could avoid having to create unique properties that track each testsuite/buildstep pair if you did Target batching:
<Target Name="Build"
Inputs="#(TestSuite)"
Outputs="%(Identity).Dummy">
<!--
Note that even though it looks like we have the entire TestSuite itemgroup here,
We will only have ONE - ie we will execute this target *foreach* item in the group
See http://beaucrawford.net/post/MSBuild-Batching.aspx
-->
<BuildStep
TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
BuildUri="$(BuildUri)"
Name="RunUnitTestsStep-%(TestSuite.Filename)-%(TestSuite.Extension)"
Message=" - Unit Tests: %(TestSuite.Filename): %(TestSuite.Extension)">
<Output
TaskParameter="Id"
PropertyName="TestStepId" />
</BuildStep>
<!--
..Do some stuff here..
-->
<BuildStep Condition=" Evaluate Success Condition Here "
TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
BuildUri="$(BuildUri)"
Id="$(TestStepId)"
Status="Succeeded" />
<BuildStep Condition=" Evaluate Failed Condition Here "
TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
BuildUri="$(BuildUri)"
Id="$(TestStepId)"
Status="Failed" />
</Target>