# Encapsulation in build scripts using nant

When writing build scripts it’s very easy for it to descend into complete Xml hell when you’re using a tool like nant.

I wondered previously whether it was possible to TDD build files and while this is difficult given the dependency model most build tools follow. That doesn’t mean we can’t apply other good design principles from the coding world however.

Encapsulation is one of the key principles of OOP and it can be applied in build files too. Stephen Chu talks about this in his post on Pragmatic Nant Scripting where he recommends having 3 different levels of targets to help create this encapsulation.

I’ve been trying to follow this advice with our build scripts and today Bernardo made the suggestion of using macros in an English readable way. He calls it OO Scripting - it’s effectively a DSL inside a DSL if you like.

I was having problems with the ncover nant task - the following error message was being thrown every time I called it:

I managed to find the source code for that class and had a look at it but I couldn’t figure out what was going wrong without debugging through it. The strange thing was that it worked fine from the command line which suggested to me that I was getting something simple wrong.

I created a cover.tests macro to encapsulate the details of how I was executing the coverage.

The plan was to get it working using an exec call to the ncover executable and then phase the ncover nant task back in when I’d figured out what I was doing wrong.

This is what I started out with:


<macrodef name="cover.tests">
<attributes>
<attribute name="in.assemblies" />
</attributes>
<sequential>
<copy file="\path\to\Coverage.xsl" tofile="${report.dir}\Coverage.xsl" /> <exec program="..\lib\NCover-1.5.8\NCover.Console.exe"> <arg value="..\lib\nunit-2.4\nunit-console.exe" /> <arg value="${build.dir}\UnitTests\UnitTests.dll" />
<arg value="//a" />
<arg value="${in.assemblies}" /> <arg value="//x" /> <arg value="${report.dir}\Unit.Test.Coverage.xml" />
</exec>
</sequential>
</macrodef>


//a is the assemblies to include in the report

//x is the name of the report xml file which will be created

The full list is here.

The macro was called like this:

 1 2 3 ~~~   ~~~ 
I substituted the ncover task back in with the same parameters as above and low and behold it worked!
 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ~~~   program=“..\lib\NCover-1.5.8\NCover.Console.exe” commandLineExe=“..\lib\nunit-2.4\nunit-console.exe” commandLineArgs=“${build.dir}\UnitTests\UnitTests.dll” coverageFile=“${report.dir}\Unit.Test.Coverage.xml” assemblyList=“\${in.assemblies}” /> ~~~ 
I’m not sure exactly what the problem parameter was but encapsulating this part of the build gave me the option of working that out in a way that impacted very little of the rest of the build file.

Update Fixed the first example to include the opening as pointed out by Vikram in the comments. Thanks again Vikram for pointing that out!