如何配置gradle应用程序插件以将user.dir设置为脚本的位置?

时间:2016-08-30 14:49:40

标签: gradle gradle-plugin

gradle应用程序插件会创建以下目录结构

应用       bin - 启动服务器的脚本       lib - jar文件    {来自src / dist的任何其他东西都在应用程序中}

我无法弄清楚的是脚本不会使服务器在app目录中运行而烦人。有没有办法可以配置它并在app目录中运行? (或者让它将user.dir设置为相对于bin目录的..)。

这是非常令人沮丧的,因为我必须做某种检查并且错误地说该程序必须从app diretory运行,所以我知道如何查找文件。

现在,如果你有房产 -Dlogback.configurationFile =配置/ logback.xml

并且您从应用程序目录以外的机器上的任何位置运行启动脚本,以静默方式停止工作。

感谢, 迪安

2 个答案:

答案 0 :(得分:2)

以下代码对我有用(仅在linux上测试过,不确定windows部分(

// set user.dir to the distribution directory so that the config directory can be located
CreateStartScripts startScripts = project.startScripts
startScripts.with {
    doLast {
        unixScript.text = unixScript.text.replaceFirst('(?<=DEFAULT_JVM_OPTS=)((\'|\")(.*)(\'|"))(?=\n)',
                 "-Duser.dir=$APP_HOME")
        windowsScript.text = windowsScript.text.replaceFirst('(?<=DEFAULT_JVM_OPTS=)(.*)(?=\r\n)',
                '-Duser.dir=%APP_HOME%')
    }
}

答案 1 :(得分:1)

根据Jeff Gaer的回答,我在我的gradle / groovy版本上得到了以下答案。 gradle版本2.14-rc-1 groovy 2.4.4

我只在mac上测试过。

BIG注意:bash有一个&#39;&#34; args&#34;&#39;在脚本中这是令人讨厌的,而Windows只有&#34; args&#34;所以我必须做的替换有点不同。我将答案标记为正确,因为它让我得到答案。

applicationDefaultJvmArgs = ['JVM_ARGS_TRICK']

//Here, we must modify the start scripts to set user.dir property so no matter where the script is run from,
//the user.dir will point to APPNAME directory
CreateStartScripts startScripts = project.startScripts
startScripts.with {
doLast {
    //A slash in groovy allows us to not escape double quotes AND single quotes
    def slashString = /'"JVM_ARGS_TRICK"'/
    //for some reason, gradle prints '"jvm args"'  why?  I don't know but must swap quote and double quote
    unixScript.text = unixScript.text.replace(slashString,
               '"-Dlogback.configurationFile=$APP_HOME/config/logback.xml -Duser.dir=$APP_HOME"')
    windowsScript.text = windowsScript.text.replace('"JVM_ARGS_TRICK"',
               '"-Dlogback.configurationFile=%APP_HOME%/config/logback.xml -Duser.dir=%APP_HOME%"')
}
}