我正在使用双启动计算机。通常,我将在Linux(Linux Mint 18.3)中进行编码,但偶尔在W10分区中进行编码。
对于给定的Gradle项目,我始终希望使用“ installDist”的可执行文件输出到同一位置。因此,我在build.gradle中包含了以下几行:
def currentOS = org.gradle.internal.os.OperatingSystem.current()
def platform
if (currentOS.isWindows()) {
platform = 'win'
} else if (currentOS.isLinux()) {
platform = 'linux'
} else if (currentOS.isMacOsX()) {
// platform = 'mac'
throw new Exception( "not configured for Mac OS: $currentOS" )
}
else {
throw new Exception( "attempt to run on unknown platform: $currentOS" )
}
println "OS/platform |$platform|"
String operativeDir
def homePath = System.properties['user.home']
// in W10 homePath is apparently "D:\My Documents"
// in linux homePath is "/home/mike"
// no doubt I could use java.nio.file.Path for a more elegant solution:
String pathSeparator = platform == 'linux'? '/' : '\\'
// would be better to get the My Documents path from an Env Var in Linux:
String myDoxPath = platform == 'linux'? '/media/mike/W10 D drive/My Documents' : homePath
operativeDir = "$myDoxPath${pathSeparator}software projects${pathSeparator}operative${pathSeparator}${name}"
// get version number: must be a version.properties file at the path indicated
ConfigObject conf = new ConfigSlurper().parse( file("src/main/resources/version.properties").toURI().toURL())
version = conf.versionNumber
println "version is $version"
installDist{
destinationDir = file( "$operativeDir/$version" )
}
...问题是,所有这些都是样板:我希望将其包含在我开发的每个项目中。目前,它使我的build.gradle变得混乱不堪。将“样板”作为某种模块“装载”到Gradle的标准/最佳方法是什么?
正如usr-local-ΕΨΗΕΛΩΝ
在评论中指出的,如果您发现自己在许多项目中都有重复的构建逻辑,那么自定义Gradle插件就是解决方案。
您可以使用Build Init Plugin生成骨架Gradle插件。您需要全局安装Gradle以便在任何地方调用gradle
。请参阅说明here以安装Gradle。
例如,要定义platform
属性,您的插件可以执行以下操作:
import org.gradle.api.GradleException; import org.gradle.api.Project; import org.gradle.api.Plugin; import org.gradle.internal.os.OperatingSystem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ExamplePlugin implements Plugin<Project> { private static final Logger log = LoggerFactory.getLogger(ExamplePlugin.class); public void apply(Project project) { String platform = inferPlatform(project); project.getExtensions().getExtraProperties().set("platform", platform); log.info("OS/platform |{}|", platform); } private String inferPlatform(Project project) { // OperatingSystem is an INTERNAL package. // It is strongly recommended you not use internal Gradle APIs. OperatingSystem currentOS = OperatingSystem.current(); if (currentOS.isWindows()) { return "win"; } else if (currentOS.isLinux()) { return "linux"; } else { throw new GradleException("unsupported OS: " + currentOS.toString()); } } }
我已经给出了Java示例,但是您也可以用Groovy或Kotlin编写插件。
一旦有了插件,只需将其发布到本地或发布到Gradle插件门户。