create_file.groovy

The create_file.groovy file contains the Groovy script that will perfrom the step's command. Groovy is a dynamic scripting language (similar to Python, Ruby, and Perl) for the Java platform. Most Java code is also syntactically valid Groovy, which makes Groovy popular with Java programers. Groovy provides native support for regular expressions.

This first lines of the script create a properties object, props, then attempts to load the properties from the file sent from the server (specified by the ${PLUGIN_OUTPUT_PROPS} variable). If it can load the file, it populates props; otherwise, it throws an exception.

        
final def workDir = new File('.').canonicalFile
final def props = new Properties();
final def inputPropsFile = new File(args[0]);
try {
    inputPropsStream = new FileInputStream(inputPropsFile);
    props.load(inputPropsStream);
}
catch (IOException e) {
    throw new RuntimeException(e);
}

To perform the command—create a file—the script uses the properties defined by the step itself. The script retrieves the three properties from props and creates corresponding local variables.

Next, the script creates a file with a name specified by fileName, and tests the overwrite boolean variable. If a file with the same name exists and overwrite is false, the script ends (fails) with an exit code of 1. Exit codes can be examined during post-processing.

Otherwise, the file is written with the content of contents, a message is written to the output log, and the exit code is set to 0 (success).

        
final def fileName = props['file']
final def overwrite = props['overwrite']?.toBoolean()
final def contents = props['contents']?:''

try {
    def file = new File(fileName).canonicalFile
    if (file.exists() && !overwrite) {
        println "File $file already exists!"
        System.exit 1
    }
    else {
        file.write(contents)
        println "Successfully ${overwrite?'replaced':'created'} file 
            $file with contents:"
        println contents
    }
}
catch (Exception e) {
    println "Error creating file $file: ${e.message}"
    System.exit(1)
}

System.exit(0)