2017-08-14 37 views
0

我正在研究一組使用Gradle作爲構建工具的項目。這不是一個多項目設置,儘管我希望能夠在每個項目中重用一些常見的Gradle腳本,以便與項目相關的一致性。如何跨項目重用Gradle定義

例如,對於Java組件,我希望生成的JAR文件中的清單文件具有相同的信息。特別是,所有項目將具有相同的主版本和次版本號,而補丁版本將專門針對項目。

這裏是我試過到目前爲止:

master.gradle - 跨項目

group 'com.example' 

ext.majorVersion = 2 
ext.minorVersion = 3 
ext.patchVersion = 0; // Projects to override 

def patchVersion() { 
    return patchVersion; 
} 

apply plugin: 'java' 

jar { 
    manifest { 
    attributes 'Bundle-Vendor': 'Example Company', 
     'Bundle-Description': 'Project ABC', 
     'Implementation-Title': project.name, 
     'Implementation-Version': majorVersion + '.' + minorVersion + '.' + patchVersion() 
    } 
} 

build.gradle共享 - 對於項目之一

apply from: 'master.gradle' 

patchVersion = 3 

task hello { 
    println 'Version: ' + majorVersion + '.' + minorVersion + '.' + patchVersion 
} 

如果我從運行gradle hello jar在命令行中,我從hello任務獲得Version: 2.3.3。但是,JAR文件清單包含2.3.0這不是我想要的。我如何獲得正確的補丁版本到清單中?更一般地說,我如何讓項目向主腳本提供信息?

+0

你需要構建它作爲一個插件。 –

+0

你可以提供更多的細節嗎?主腳本是插件嗎?如果是這樣,你能指出相關的doco嗎?謝謝。 – dave

+0

請參閱https://docs.gradle.org/4.1/userguide/custom_plugins.html。特別是關於「從構建中獲得輸入」的部分。 –

回答

0

根據@Oliver Charlesworth的建議,我提出了以下建議。我不得不編寫一個簡單的插件來保存版本信息並將其用作擴展對象。請注意(正如Gradle文件中的評論所建議的那樣),項目應用和設置的順序非常重要。不同的排序會導致編譯器錯誤或在設置之前使用的值。

如果有人想提出改進建議,請這樣做。

master.gradle

group 'com.example' 

// N.B. The individual project must have applied the semantic version 
// plugin and set the patch version before applying this file. 
// Otherwise the following will fail. 
// Specify the major and minor version numbers. 
project.semver.major = 2 
project.semver.minor = 3 
project.version = project.semver 

apply plugin: 'java' 

jar { 
    manifest { 
     attributes 'Bundle-Vendor': 'Example Company', 
      'Bundle-Description': project.description, 
      'Implementation-Title': project.name, 
      'Implementation-Version': project.semver 
    } 
} 

build.gradle

// Describe the project before importing the master gradle file 
project.description = 'Content Upload Assistant' 

// Specify the patch version 
apply plugin: SemanticVersionPlugin 
project.semver.patch = 3 

// Load the master gradle file in the context of the project and the semantic version 
apply from: 'master.gradle' 

的簡單的插件可以在下面找到。目前它與應用程序源代碼一起使用,但它應該與主Gradle文件一起移出到一個庫中。

buildSrc/src/main/groovy/SemanticVersionPlugin.groovy

import org.gradle.api.Plugin 
import org.gradle.api.Project 

class SemanticVersionPlugin implements Plugin<Project> { 
    void apply(Project project) { 
     project.extensions.create('semver', SemanticVersion) 
    } 
} 

class SemanticVersion { 
    int major 
    int minor 
    int patch 

    String toString() { 
     return major + '.' + minor + '.' + patch 
    } 
}