views:

36

answers:

1

In my NAnt script I have a compile target that calls csc. Currently it fails because no inputs are specified:

  <target name="compile">
    <csc
      target="library"
      output="${umbraco.bin.dir}\Mammoth.${project::get-name()}.dll">
      <sources>
        <include name="project/*.cs" />
      </sources>
      <references>
      </references>
    </csc>    
  </target>

How do I tell NAnt to not execute the csc task if there are no CS files? I read about the 'if' attribute but am unsure what expression to use with it, as ${file::exists('*.cs')} does not work.

The build script is a template for Umbraco (a CMS) projects and may or may not ever have .cs source files in the project. Ideally I would like to not have developers need to remember to modify the NAnt script to include the compile task when .cs files are added to the project (or exclude it when all .cs files are removed).

A: 

This is about NAnt filesets. <sources> is of type fileset. Handling those filesets often is awkward in NAnt. Since there is no function fileset::is-empty we need to check this explicitly:

<fileset id="sourcefiles">
  <include name="project/*.cs" />
</fileset>
<property
  name="sourcefiles.count"
  value="0" />
<foreach item="File" property="filename">
  <in>
    <items refid="sourcefiles" />
  </in>
  <do>
    <property
      name="sourcefiles.count"
      value="${int::parse(sourcefiles.count) + 1}" />
  </do>
</foreach>
<if test="${int::parse(sourcefiles.count) > 0}">
  <csc
    target="library"
    output="${umbraco.bin.dir}\Mammoth.${project::get-name()}.dll">
    <sources refid="sourcefiles" />
    <references>
    </references>
  </csc>
</if>

I agree that this is somewhat cumbersome but I'm not aware of an alternative. Well, you could use attribute failonempty on the fileset but then you would need to handle the exception.

Update: Just yesterday I found an alternative: If you don't mind using NAntContrib there is a function fileset::has-files. This is the code:

<fileset id="sourcefiles">
  <include name="project/*.cs" />
</fileset>
<if test="${fileset::has-files('sourcefiles')}">
  <csc
    target="library"
    output="${umbraco.bin.dir}\Mammoth.${project::get-name()}.dll">
    <sources refid="sourcefiles" />
    <references>
    </references>
  </csc>
</if>
The Chairman
wow. thanks. There's a lot in your answer I didn't know NAnt could do :)
rob_g