1

I am looking for a solution that would recursively remove a folder created with Files.createTempDirectory() when my (Jenkins) Groovy script ends.

If you read the documentation createTempDirectory() does not remove folder and even if you try to use the delete-on-exit, it will fail if the folder has other files inside.

Please note that I am looking for a solution that would not have to add extra code at the end of the Groovy script or to add try/catch methods. That's because these Groovy codes are compiled from multiple re-usable parts.

A working solution should not need to add extra code at the end of the script, probably using a hooking mechanism to register the directory removal operation.

import java.nio.file.Files
x = Files.createTempDirectory()
// <-- add some magic hook to tell to remove 'x' folder recursively on exit
// a lot of code I cannot touch

References

sorin
  • 161,544
  • 178
  • 535
  • 806

3 Answers3

2

How about below?

def result = x.deleteDir()
assert result
Rao
  • 20,781
  • 11
  • 57
  • 77
2

The code below will remove recursively all files and folders from the temp directory on exit.

mydir = Files.createTempDirectory()
addShutdownHook {
    mydir.deleteDir()
}

This code works for normal Groovy execution but it fails on Jenkins Grooby based pipelines because:

an exception which occurred:
    in field delegate
    in field closures
    in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@782f5796
Caused: java.io.NotSerializableException: sun.nio.fs.UnixPath
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:860)

So, I am still working on addressing the "CPS" aspect, the first attempts failed with the same errors:

@NonCPS
def mkdtemp(String s) {
    mydir = Files.createTempDirectory("cp-")
        addShutdownHook {
            mydir.deleteDir()
            println "cleaned"
        }
    mydir.toString()
}

node {
   mkdtemp('xxx')
}
sorin
  • 161,544
  • 178
  • 535
  • 806
0

How about finally?

def tmp = Files.createTempDirectory()
try {
  // do something with tmp
}
finally {
  tmp.toFile().deleteDir()
}
ceving
  • 21,900
  • 13
  • 104
  • 178