How to return a value from a phing target? - phing

I would like to have a foreach task like this, which iterates over all the files/directories in a directory "A" -
<foreach param="dirname" absparam="absname" target="subtask">
<fileset dir="${dir.destination}/${dir.subdir}/">
<type type="file" />
</fileset>
</foreach>
The target "subtask" should check if the counterpart of the file/folder exists in another directory "B" (I am comparing directory A and B basically), and return either of the following if it does not -
a flag.
name of the file.
Following is some code for reference -
<target name="subtask">
<if>
<filesmatch file1="${file1}" file2="${file2}"/>
<then>
Return false. But how?
</then>
<else>
Return true of name of the file. How?
</else>
</if>
</target>
Note - It is okay if this can be done without calling a target. I am not sure if the logic can be fit inside the foreachtask itself. Could not find any such thing in the phing documentation.
Basically, I should be having the list of file names which are not present in the directory B, by the end of the loop.
You may also read this question of mine, if you can give some pointers to solve the issue in some other way.
Update
Rephrasing this question, since I feel that the problem description is not clear. The phing documentation says, a target has no return value -
Targets are collections of project components (but not other targets)
that are assigned a unique name within their project. A target
generally performs a specific task -- or calls other targets that
perform specific tasks -- and therefore a target is a bit like a
function (but a target has no return value).
I don't understand why is it designed so. With this bounty, I would like to know if there is some workaround for me other than having to define my own custom tasks in PHP, and then set properties -
$this->getProject()->setNewProperty('modifiedElements', implode("\n\n",$modifiedElementsArray));
which can be accessed in the build file
I have a target which checks whether my production code base has any differences from the expected git revision -
<target name="compare_prod_with_expected_revision">
<input propertyname="box.git_version">
Enter git version of the production codebase:
</input>
<exec command="git reset --hard ${box.git_version}" dir="${dir.scratchpad}" />
<!-- Scratchpad brought to revision ${box.git_version} -->
<echo>Verifying whether production is at revision ${box.git_version}..</echo>
<exec command="diff -arq --exclude='.git' ${dir.scratchpad}/${dir.subdir} ${dir.destination}/${dir.subdir}" outputProperty="diffList"/><!-- #TODO ignore.swp files in this step. Diff says .swp files present in production code. But doing ls -a there does not show the same. -->
<php function="strlen" returnProperty="productionDeviationFromExpectedBranch"><!-- #TODO - find how to not show this step during build process. Put it in a target and set hidden="true" -->
<param value="${diffList}"/>
</php>
<if>
<equals arg1="${productionDeviationFromExpectedBranch}" arg2="0" />
<then>
<echo>Verified production is at revision ${box.git_version}</echo>
</then>
<else>
<echo>Differences - </echo>
<echo>${diffList}</echo>
</else>
</if>
</target>
Now, I want to phingcall this target and would like to access some property set by it.

I think I understood your purposes, and at the same time I feel like you chosen not the optimal tool of doing this.
As you mentioned in your question, official documentation on phing is clear about tasks (targets):
Targets are collections of project components (but not other targets) that are assigned a unique name within their project. A target generally performs a specific task -- or calls other targets that perform specific tasks -- and therefore a target is a bit like a function (but a target has no return value).
Targets should be components of your application, which execute specific task, atomic task. It could be initialization task, configuration fetching, compilation step, assets preparation and dumping, deployment task, clean-up task, etc. There's no "output", returned by target in the standard sense, but the result of target execution is the success of execution itself: success or failure.
One should not try to put way too much of logic into such project targets, as it is not intended to do complicated calculations, do heavy logical decisions, etc. I mean, Phing can do it, such things are possible, but this setup would be bulky, unreadable, and hard to scale/re-factor.
With Phing you can easily define conditional execution and branching of logical flow, you may define the sequence of execution of tasks (dependencies) - this is what makes it laconic and elegant. Keep targets as simple as possible, split the project into small, finished logical tasks.
Based on the projects I've been working with, the biggest targets, probably, were initialization stage and configs fetching. Here's some example, to understand what it might contain, I took it from real project:
<target name="init_configuration">
<echo msg="Define initial configuration for the deployment..." />
<if>
<not>
<isset property="host" />
</not>
<then>
<property name="host" value="dev" override="true" />
<echo message="The value of hostname has been set to ${host}" />
</then>
<else>
<echo message="The value of hostname is ${host}" />
</else>
</if>
<if>
<not>
<isset property="version" />
</not>
<then>
<property name="version" value="1.0.0" override="true" />
<echo message="The value of version has been set to ${version}" />
</then>
<else>
<echo message="The value of version is ${version}" />
</else>
</if>
<property name="host_credital_file" value="config/hosts/${host}.properties" />
<property file="${host_credital_file}" />
<available file="${host_credital_file}" property="hostfilefound" value="true"/>
<fail unless="hostfilefound" message="Missing Hostfile configuration file (${host_credital_file})!" />
<echo msg="Configuration is done" />
</target>
Other targets were extremely simplistic, they are normally – 1-5 lines long, and do only small purpose, small task. This would be, probably, the best recommendation when working with Phing.
The logic which you are trying to put on shoulders of Phing is possible, but would be extremely bulky.
Consider the point: how much quicker, easier, and more readable the same thing could be done with simple bash script in your example. Or even to write small CLI utility in PHP, which will do the job elegantly and quick. After that in Phing you'll leave parametric target which will execute this "revision diff script" from CLI.
Phing is a great tool for what it is designed for, but it can't be an optimal choice for every purpose. Just do not put way to much responsibility and logic into it.
As a workaround, for more complicated things it's better to combine Phing with with something specialized: bash scripting, PHP CLI, nodeJS (+ Grunt, Gulp, etc)... and just to add calls of a Phing targets later.

This is the way I managed to have targets which behave like functions:
<target name="-console-cmd-return-property" hidden="true">
<exec command="${command}" checkreturn="${checkreturn}" logoutput="${logoutput}" outputProperty="${outputProperty}"/>
</target>
It gets invoked like this:
<phingcall target="--console-return-property">
<property name="command" value="ps auxwww"/>
<property name="checkreturn" value="true"/>
<property name="logoutput" value="false"/>
<property name="outputProperty" value="ps_output"/>
</phingcall>
Of course it works because it relies on existing exec, and it is not generic...

The target "subtask" should check if the counterpart of the file/folder exists in another directory "B" (I am comparing directory A and B basically), and return either of the following if it does not -
a flag.
name of the file.
You could compare two directories without using a foreach task like this:
<project name="Phing Build Test" default="print-missing" basedir=".">
<resolvepath propertyName="dir.a" path="path/to/dir/a"/>
<resolvepath propertyName="dir.b" path="path/to/dir/b"/>
<target name="print-missing">
<apply executable="echo" failonerror="false" returnProperty="files.found" outputProperty="missing">
<srcfile/>
<fileset id="srcfiles" dir="${dir.a}" includes="*">
<present present="srconly" targetdir="${dir.b}"/>
</fileset>
</apply>
<if>
<equals arg1="${files.found}" arg2="0"/>
<then>
<echo msg="${missing}"/>
</then>
</if>
</target>
</project>

Related

Controlling the sequence of events in a Wixtoolset (.msi) installer

I am creating a Microsoft Installer (.msi file) using the Wixtoolset (Windows Installer XML). This installer must automate the installation of an existing .exe program (named installer.exe below) and copy a custom configuration file (named settings.conf below) to the target directory. In addition the installer must modify the configuration file using the InstallFiles command below. But the timing of events is critical. If the executable installer runs too early, it fails or exhibits strange behavior. And if the executable installer run too late in the install sequence, it overwrites my modified configuration file with the generic values. I believe this can be done by assigning a string to the Before or After property value. What Before or After property assignment will allow the executable to run properly but not overwrite the configuration file I moved by the CopyFile element? Here is my Wixtoolset XML code.
<Property Id="CONFIGFOLDER" Value="C:\acme\config" >
<Feature
Id="ConfigurationFile"
Title="Configuration File"
Level="1"
<ComponentRef Id="CMP_ACME_Config_File" />
</Feature>
<DirectoryRef Id="TARGETDIR">
<Component Id="CMP_ACME_Config_File" Guid="">
<File
Id="ACME_Config"
Source="MySettings.conf"
KeyPath="yes"
<CopyFile Id="Copy_ACME_Config"
DestinationProperty="CONFIGFOLDER"
DestinationName="settings.conf" />
</File>
</Component>
</DirectoryRef>
<Binary
Id="InstallerEXE"
SourceFile="installer.exe" />
<CustomAction
Id="Launch_Installer"
BinaryKey="InstallerEXE"
Impersonate="yes"
Execute="deferred"
ExeCommand=""
Return="check" />
<InstallExecuteSequence>
<Custom Action="Launch_Installer"
Before="InstallFiles">
</Custom>
</InstallExecuteSequence>
</Property>
I can't explain exactly why this works but assigning "InstallFiles" to the "After" property in the "Custom" element seems to do the trick.
<InstallExecuteSequence>
<Custom Action="Launch_Installer"
After="InstallFiles">
</Custom>
</InstallExecuteSequence>

Why is NAnt executing my sql scripts in the wrong order?

Here is my Script:
<?xml version="1.0"?>
<project name="createAndPopulateDB" default="deploy">
<property name="sql.connstring" value="Provider=SQLOLEDB;Server=G-PC\sqlexpress;Integrated Security=SSPI" />
<property name="createDB" value="BuildTestDatabase.sql" />
<property name="populateDB" value="CreateTables.sql"/>
<target name="deploy">
<echo message="* Connecting to ${sql.connstring}"/>
<foreach item="File" property="sql.script">
<in>
<items>
<include name="${createDB}" />
<include name="${populateDB}" />
</items>
</in>
<do>
<echo message="* Executing ${path::get-file-name(sql.script)}"/>
<sql connstring="${sql.connstring}" delimiter="go" delimstyle="Line" batch="false" source="${sql.script}"/>
</do>
</foreach>
</target>
</project>
The NAnt script is supposed to call two tsql programs. The first tsql is designed to drop a database if it is present, and if it isn't, create it. The second checks to see if a table is present, and if so, delete it. Similarly if it isn't, it populates the created database with a simple table.
My question is why does it run the populateDB script first?
I found that the best way to determine the order in which the tsql programs are run is through a depends attribute attached to separate targets. This will run them in a predetermined order and is extremely easy to follow logically if the NAnt script is a part of a repository.

Using xmlpeek in Nant script gives odd error

As part of a CI process I am trying to create a buildlabel which consists of the content of an xml element within an xml structure. For this purpose I am using nant and xmlpeek. My problem is that I get an odd error stating:
"Nodeindex '0' is out of range"
This is only the case if the xml file I am xmlpeeking contains a namespace definition in the root node.
Removing the namespace from the xml file gives me the output I expect.
The nant target that generates the error can be boild down to:
<target name="TDSLabel">
<property name="element" value=""/>
<echo message="Getting element" />
<xmlpeek file="C:\xxx\test1.xml" xpath="//Project/PropertyGroup/ProductVersion" property="element"/>
<echo message="The found element value was: ${element}" />
</target>
and the test1.xml file looks like this:
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ProductVersion>9.0.21022</ProductVersion>
</PropertyGroup>
</Project>
You already gave the right hint yourself. It's about the namespace. This should fix it:
<target name="TDSLabel">
<property name="element" value=""/>
<echo message="Getting element" />
<xmlpeek
file="C:\xxx\test1.xml"
xpath="//x:Project/x:PropertyGroup/x:ProductVersion"
property="element"
verbose="true">
<namespaces>
<namespace prefix="x" uri="http://schemas.microsoft.com/developer/msbuild/2003" />
</namespaces>
</xmlpeek>
<echo message="The found element value was: ${element}" />
</target>
Found a similar problem and the anwser to my problem here: XmlPoke and unique nodes. The problem was that I did not include the namespace definition within the xmlpeek element and afterwards omitted the necessary reference to the namespace in my xpath statement:
<xmlpeek file="C:\xxx\test1.xml" xpath="//x:Project/x:PropertyGroup/x:ProductVersion" property="element">
<namespaces>
<namespace prefix="x" uri="http://schemas.microsoft.com/developer/msbuild/2003" />
</namespaces>
</xmlpeek>

How to replace string in a file using NANT?

I am trying to replace the occurance of a string in a wxs file using Nant.
I have only found the following example, which uses <replaceString>, but it seems like it can only be used within the copied files. Are there any other way of replacing a string, without actually copying the files over?
<property name="NOW" value="${datetime::now()}" />
<copy todir="out">
<fileset basedir="in">
<include name="**/*" />
</fileset>
<filterchain>
<replacetokens>
<token key="NOW" value="${TODAY}" />
</replacetokens>
<tabstospaces />
</filterchain>
</copy>
Here's the code:
<loadfile file="token.txt" property="token-file">
<filterchain>
<replacetokens>
<token key="NOW" value="${datetime::now()}" />
</replacetokens>
</filterchain>
</loadfile>
The official NAnt docs for <loadfile> element contain the exact sample you need. See the bottom of the page.
Here's how I did it.
<loadfile file="${file}" property="file.content">
<filterchain>
<replacestring from="StringToMatch" to="StringToReplace" ignorecase="true" />
</filterchain>
</loadfile>
<echo file="${file}">${file.content}</echo>
So you are trying to modify a .wxs file which is XML, right?
In this particular case you might use <xmlpoke> if you are able to determine the position of the strings to replace via XPath.
I found a solution for you here: http://frank.overseakids.com/?p=182
<loadfile file=”${dir.template}\template.db_name.sql” property=”restore.db.sql.db_name”>
<filterchain>
<replacetokens>
<!– this looks for tokens like #blah.blah# in the file being loaded and replaces them–>
<token key=”restore.db.prefix” value=”${restore.db.prefix}” />
<token key=”backup.file.path” value=”${backup.file.path}” />
</replacetokens>
</filterchain>
</loadfile>
<property name=”current.db” value=”db_name” />
<property name=”current.log” value=”${dir.log}\${restore.db.logfile.prefix}_db_name.log” />
<property name=”current.file” value=”${dir.template}\restore.db_name.tmp.sql” />
<delete if=”${file::exists(current.file)}” file=”${current.file}” />
<echo file=”${current.file}”>${restore.db.sql.db_name}</echo>
You can wrap this in a <foreach /> element.
I never managed to get the filterchain and replacetokens to work properly. I ended up using this and it works great.
<replacetext filename="${filename}" src="stringToBeReplaced" replacement="replacementString" />
All these answers did not work for me, maybe because I needed to replace a string with spaces in it. Loading a file content with filterchain/replacetokens did nothing to the contents of the associated property. Maybe I'm using it wrong.
The tasks "replacestring" and "replacetext" suggested by #Ally and #John Sterne do not exist.
It's included in a Jenkins build process, thus the ENVIRONMENT variable must be set to the working dir.
<loadfile file="./my/batch.bat" property="file.content" />
<property name="file.content"
value="${string::replace(file.content, 'D:\path to\the working\space', environment::get-variable('WORKSPACE'))}" />
<property name="file.content"
value="${string::replace(file.content, 'Cd C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin', 'CD /D C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin')}" />
<echo file="./my/batch.bat">${file.content}</echo>
I had that problem today. To solve it I used the move command instead of loadfile or copy. This worked for me because since my file was pretty small. The other caution about this is that replacetokens needs a start identifier and end identifier of the token; begintoken and endtoke respectively. If those are not set the default values are the # symbol. So if you want to replace a value such as MY_SERVER_PLACE_HOLDER that means the value in your file must be #MY_SERVER_PLACE_HOLDER#. If you want your token to start with something different than you should specify the begintoken and endtoken values. That should give you an idea of the problems the begin token and endtoken will bring you.
So here is what I did in a nutshell
Moved the file to a temporary location. In that move I used
filterchain with removetokens to change the values in the file.
In step 2, I moved the file back to it's original location.
I then used the delete command to delete the temp folder I created.
Here is a what I did. (May not be syntactically correct since I am not in front of the code at the moment)
<move todir="temp">
<fileset basedir="in">
<include name="myfile.dat" />
</fileset>
<filterchain>
<replacetokens>
<token key="MY_SERVER_PLACE_HOLDER" value="http://www.someserver.com" />
</replacetokens>
<tabstospaces />
</filterchain>
</move>
<move todir="in">
<fileset basedir="temp">
<include name="myfile.dat" />
</fileset>
</move>
<delete dir="temp" />

How do I optionally require a command line arguement for Ant?

I'm new to ant, and I want to require a file name if something other than the default target is used, so the calling syntax would be something like this:
ant specifictarget -Dfile=myfile
I'm using the ant contrib package to give me additional functionality, so I have this:
<if>
<equals arg1="${file}" arg2="" />
<then>
<!-- fail here -->
</then>
</if>
My thinking is that if file was not specified it might be equal to the empty string. Obviously, this didn't work, and I'm not finding any examples on google or the right syntax in the manual.
So what syntax should I use?
You don't really need the contrib package. This is more conveniently done using built-in ant capabilities like if/unless and depends. See below:
<target name="check" unless="file" description="check that the file property is set" >
<fail message="set file property in the command line (e.g. -Dfile=someval)"/>
</target>
<target name="specifictarget" if="file" depends="check" description=" " >
<echo message="do something ${file}"/>
</target>
You've got the right idea. The
ant specifictarget -Dfile=myfile
sets Ant Properties from the command line. All you really need is
<property name="file" value=""/>
for your default value. That way if file is not specified, it will be equal to the empty string.
Since properties are not mutable in Ant, you can add this:
<property name="file" value="" />
This will set the property file to an empty string if it hasn't already been set on the command line. Then your equality test will work as you intended.
Alternately, you can use escape the value since ant just spits out the actual text when it can't do a property substitution.
<if>
<equals arg1="${file}" arg2="$${file}" />
<then>
<echo>BARF!</echo>
</then>
</if>