Search code examples
gradlegroovy

Gradle: getting the root project directory path when starting with a custom build file


The structure of my Gradle project is the following:

Project
├── app
     └── build.gradle
├── foo
     └── bar.txt
·
·
·
└── build.gradle

Normally to get the absolute path of the foo folder I can just simply do new File('foo').getAbsolutePath() in the root build.gradle file.

But this unfortunately doesn't work if you run the gradle script from outside the project directory, for example doing something like this:

$ trunk/gradlew -b trunk/build.gradle tasks

With the previous command gradle is looking for the foo directory in the parent of the Project, because I started the script from there.

Is there a way to get the absolute path of the Project where the build.gradle is, even if you start your script from another directory? Or is there any other way to get a reference of a directory in the same folder where the script is?

I've tried also with getClass().protectionDomain.codeSource.location.path but it is returning the path to the gradle cache directory.


Solution

  • new File('foo') by definition (look at its JavaDoc) makes a path relative to the current working directory, so depends on where you call the app from. If you want a path relative to the project folder, use project.file('foo'), or as project is the default for resolving the method just file('foo') and you get the relative path resolved against the project directory, not the working directory. So use file('foo').absolutePath and you will be fine.