Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to strip the basedir from an absolute path to get a relative path?

Tags:

In the build.xml of my project I have a property defined:

<property name="somedir.dir" location="my_project/some_dir"/> 

The value of ${somedir.dir} will be an absolute path: /home/myuser/my_project/some_dir.

What I need is just the relative path ./my_project/some_dir without the ${basedir} value /home/myuser. How can I achieve this using Ant?

So far I found a solution by converting the property to a path and then use "pathconvert", but I don't think this is a nice solution:

<path id="temp.path">     <pathelement location="${somedir.dir}" /> </path> <pathconvert property="relative.dir" refid="temp.path">     <globmapper from="${basedir}/*" to="./*" /> </pathconvert> 

Any other (more elegant) suggestions?

like image 255
blackicecube Avatar asked Jan 08 '10 06:01

blackicecube


People also ask

How do you convert an absolute path to a relative path?

The absolutePath function works by beginning at the starting folder and moving up one level for each "../" in the relative path. Then it concatenates the changed starting folder with the relative path to produce the equivalent absolute path.

Can an absolute path be a relative path?

In simple words, an absolute path refers to the same location in a file system relative to the root directory, whereas a relative path points to a specific location in a file system relative to the current directory you are working on.

How do you make a relative path?

Relative paths make use of two special symbols, a dot (.) and a double-dot (..), which translate into the current directory and the parent directory. Double dots are used for moving up in the hierarchy.


2 Answers

Since Ant 1.8.0 you can use the relative attribute of the Ant property task for this.

For example:

<property name="somedir.dir" location="my_project/some_dir"/> <echo message="${somedir.dir}" />  <property name="somedir.rel" value="${somedir.dir}" relative="yes" /> <echo message="${somedir.rel}" /> 

Leads to:

 [echo] /home/.../stack_overflow/ant/my_project/some_dir  [echo] my_project/some_dir 
like image 90
martin clayton Avatar answered Sep 25 '22 13:09

martin clayton


A slightly less verbose solution would be specifying somepath inside <pathconvert>:

<pathconvert property="relative.dir">   <path location="${somepath}"/>   <globmapper from="${basedir}/*" to="./*" /> </pathconvert> 
like image 30
Garns Avatar answered Sep 22 '22 13:09

Garns