Paul
Paul

Reputation: 85

Jenkins ant plugin has wrong value for ${user.dir} working directory

I have the following build file in C:\A\B

<project name="demo" default="printCWD">
    <target name="printCWD">
        <echo message="user.dir=${user.dir}"/>
    </target>
</project>

and run this command whilst in C:\A

ant -buildfile B\build.xml

it prints "C:\A"

But from the Ant plug-in installed on a Jenkins CI machine, which has the Buildfile setting set to "B/build.xml", it prints "/workspace/B"

Why is it on my local machine it prints the folder from which I invoked the ant command, yet on the Jenkins CI server it prints the folder that the buildfile is in?

Many thanks for any help.

Paul

Upvotes: 2

Views: 1155

Answers (1)

M A
M A

Reputation: 72884

It's because the Jenkins Ant plugin is changing the working directory to the directory containing the buildfile just before executing it, therefore causing user.dir to point to that directory (/workspace/B).

A look at the source code of the Ant plugin at https://github.com/jenkinsci/ant-plugin/blob/master/src/main/java/hudson/tasks/Ant.java reveals that the working directory is changed to the parent of the build file, specifically in this line (note the call to pwd(buildFilePath.getParent()):

r = launcher.launch().cmds(args).envs(env).stdout(aca).pwd(buildFilePath.getParent()).join();

Given this difference in behavior between locally and on Jenkins, I wouldn't personally rely on the user.dir property. If you want to access the current workspace of the Jenkins job, you can use the built-in environment variables provided by Jenkins:

<property environment="env"/>

<target name="printCWD">
    <echo message="workspace=${env.WORKSPACE}"/>
</target>

If you don't want to explicitly reference the WORKSPACE env variable in the buildfile, you can provide a custom property to pass it from outside (with the default value set to user.dir):

<property name="root.dir" value="${user.dir}" />  <!-- default value -->

<target name="printCWD">
    <echo message="root.dir=${root.dir}"/>
</target>

Then pass -Droot.dir=${WORKSPACE} in the Jenkins job.

Upvotes: 1

Related Questions