How to delete a temporary folder when exiting groovy?

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

If you read the documentation, then createTempDirectory () will not delete the folder, and even if you try to use delete-on-exit, it will not succeed if there are other files inside the folder.

Note that I'm looking for a solution that should not add extra code at the end of the Groovy script or to add try / catch methods. This is because these Groovy codes are compiled from several reusable parts.

A working solution should not contain additional code at the end of the script, possibly using a connection mechanism to register a directory deletion 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

+1
source share
2 answers

How about below?

 def result = x.deleteDir() assert result 
+2
source

In the code below, all files and folders from the temp directory are recursively deleted upon exit.

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

This code works for normal Groovy execution, but it does not work based on Jenkins Grooby, 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 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') } 
+2
source

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


All Articles