create_file.groovy

create_file.groovy 文件包含运行步骤的命令的 Groovy 脚本。

Groovy 是用于 Java™ 平台的动态脚本语言(类似于 Python、Ruby 和 Perl)。大多数 Java 代码也是语法上有效的 Groovy,这使 Groovy 受到 Java 程序员的欢迎。Groovy 提供了对正则表达式的本机支持。

脚本的第一行创建属性对象 props。然后它尝试装入从服务器发送的文件(由 ${PLUGIN_OUTPUT_PROPS} 变量指定)中的属性。如果它可以装入该文件,那么它填充 props;否则它会抛出异常。

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);
}

为了运行命令(创建文件),脚本使用步骤本身定义的属性。脚本从 props 中检索这三个属性并创建对应的局部变量。

然后,脚本创建一个名称由 fileName 指定的文件并测试 overwrite 布尔型变量。如果存在同名文件并且 overwrite 为 false,那么脚本将结束(失败),退出码为 1。可以在处理后过程中检查退出码。

否则,contents 的内容将写入该文件。一条消息将写入至输出日志,并且退出码设置为 0(成功)。

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)

反馈