Search code examples
gradlegroovy

Create a directory structure from a path in gradle/groovy


I am implementing a diff package generation task in my project's gradle build from the git command line output. Currently I have a method which will give me a list of changed files from git diff --name-only. What I would like to do is create a directory structure in a new directory which matches the paths of each file. For example: inputting the string repo/dir/file.java would create in an output directory if not already created and inside it the directories head/repo/dir with the current file.java and prev/repo/dir with the previous file.java.

My current plan is to split the string repo/dir/file.java on the forward slash, and create directories until the last element of the split result, then write the file there. but nothing I have been able to come up with in gradle is nice or clean. I am wondering if there is a nicer way to create directories from a string like that.


Solution

  • My current plan is to split the string repo/dir/file.java on the forward slash, and create directories until the last element of the split result

    Rather than splitting your string manually, you could try using File.mkdirs():

    File newDirectoryStructureParent = new File('some/path/to/parent/dir')
    
    def s = 'repo/dir/file.java'
    def newContainer = new File(s, newDirectoryStructureParent).getParent()
    newContainer.mkdirs()