How do you get the path of the running script in groovy?
groovy
Solution
As of Groovy 2.3.0 the `@SourceURI` annotation can be used to populate a variable with the URI of the script's location. This URI can then be used to get the path to the script:
import groovy.transform.SourceURI
import java.nio.file.Path
import java.nio.file.Paths
@SourceURI
URI sourceUri
Path scriptLocation = Paths.get(sourceUri)
Note that this will only work if the URI is a `file:` URI (or another URI scheme type with an installed FileSystemProvider), otherwise a FileSystemNotFoundException will be thrown by the `Paths.get(URI)` call. In particular, certain Groovy runtimes such as groovyshell and nextflow return a `data:` URI, which will not typically match an installed `FileSystemProvider`.
Problem
I'm writing a groovy script that I want to be controlled via a properties file stored in the same folder. However, I want to be able to call this script from anywhere. When I run the script it always looks for the properties file based on where it is run from, not where the script is. How can I access the path of the script file from within the script?