Gradle: getting the root directory of the project directory at startup using a custom build file

The structure of my Gradle project is as follows:

Project โ”œโ”€โ”€ app โ””โ”€โ”€ build.gradle โ”œโ”€โ”€ foo โ””โ”€โ”€ bar.txt ยท ยท ยท โ””โ”€โ”€ build.gradle 

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

But this, unfortunately, does not work if you run the Gradle script because of the project directory, for example, by doing something like this:

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

If the previous Gradle command is looking for the foo directory in the parent Project object, because I started the script there.

Is there a way to get the absolute project path where build.gradle is, even if you run your script from another directory? Or is there another way to get a link to a directory in the same folder as the script?

I also tried with getClass().protectionDomain.codeSource.location.path , but it returns the path to the Gradle cache directory.

+6
source share
3 answers

new File('foo') by definition (look at its JavaDoc) makes a path relative to the current working directory, so it depends on what you invoke the application on. If you need the path to the project folder, use project.file('foo') or as project by default to solve the method simply file('foo') , and you will get the relative path allowed for the project directory and not for the working directory. So use file('foo').absolutePath and everything will be fine.

+8
source

I overcame this problem by putting Java userDir in the project directory (i.e. project.projectDir ) at the top of my build.gradle file as follows:

  System.setProperty( "user.dir", project.projectDir.toString() ) println " project dir: "+ System.getProperty("user.dir"); 

This can be verified by running a separate (Groovy) code, for example:

  println "User Dir: ${System.getProperty( 'user.dir' )}" 

You can display the values โ€‹โ€‹of the Gradle project before and after using these operators.

  println "Root project: ${project.rootProject}"; println " rootDir: ${project.rootDir}" println " projectDir: ${project.projectDir}"; println " project dir: ${System.getProperty("user.dir")}"; 

If you have subprojects, projectDir does not match rootDir .

This did not fix my actual problem, but I found that I was opening the correct file (relative to the location of build.gradle .

+10
source

In the build.gradle file, just use projectDir to get the absolute path to the build.gradle file. from there you can navigate through the project files. read this for more info:

https://www.tutorialspoint.com/gradle/gradle_build_script.htm

0
source

Source: https://habr.com/ru/post/1014056/


All Articles