Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass argument to NAnt exec task conditionally based on the property existence?

Tags:

xml

nant

I'd like to call a certain EXE from my NAnt script, and pass a property as an argument in case the property exists, or don't pass anything otherwise.

The below code seems to fit just for this case, but it doesn't work:

<exec program="notepad.exe">
  <arg line="${file}" if="${property::exists('file')}" />
</exec>

It throw Property 'file' has not been set error. Looks like it evaluates the property ignoring the condition. I would expect it to ignore the entire <arg> element in case its condition is false.

If I define the property above this block, it obviously works fine (even if the property is empty). It could be worth a workaround if it's a single case, but I have to pass a number of properties the same way. Besides, <if> is not a valid element under <exec>...

How to achieve this? Any ideas?

like image 367
Yan Sklyarenko Avatar asked Sep 20 '12 15:09

Yan Sklyarenko


1 Answers

I dag out an old thread at NAnt mailing list, which actually gives the best suggestion for a workaround (to my case). It's based on the fact that <property> task works as expected. The workaround introduces an extra property to set depending on whether the original property is defined or not.

Like this:

<target name="example">
  <property name="arg.value" value="${arg}" if="${property::exists('arg')}" />
  <property name="arg.value" value="" unless="${property::exists('arg')}" />
  <exec program="program.exe">
    <arg value="${arg.value}" />
  </exec>
</target>

In my case it turns out to be easier to always set a property with default value, and even don't introduce an extra property - just pass the original property to <arg/>:

<target name="example">
  <property name="arg.value" value="default value" overwrite="false" />
  <exec program="program.exe">
    <arg value="${arg.value}" />
  </exec>
</target>

It can (and will) be overwritten in other include files.

I have also found another thread where the same question was asked, and a person involved into the NAnt development suggested to indicate whether people are interested in a patch to fix this for <arg> element. As far as I can see, no one demonstrated the interest :), hence the behavior wasn't changed.

I managed to put a little time investigating what a fix could be, and it seems that it's only about adding ExpandProperties=false to the TaskAttribute for e.g. the line property of the <arg> task. The same is done for <property value="..."> attribute where it works as expected. I didn't try it out, though - if I have some more time one of these days, I will and post an update here.

like image 134
Yan Sklyarenko Avatar answered Oct 06 '22 19:10

Yan Sklyarenko