Writing Building Script

在Gradle运行的时候,会创建一个Project的实例。同时每个Script文件也会被编译为一个实现了Script的类,也就意味着在Script接口里声明的属性和方法在你的Script文件里都是有效的。

定义变量

局部变量

Local variables
1
2
3
4
5
   def dest = "dest"
  task copy(type: Copy) {
      from "source"
      into dest
  }

Extra properties

Extra properties
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
apply plugin: "java"

ext {
    springVersion = "3.1.0.RELEASE"
    emailNotification = "build@master.org"
}

sourceSets.all { ext.purpose = null }

sourceSets {
    main {
        purpose = "production"
    }
    test {
        purpose = "test"
    }
    plugin {
        purpose = "production"
    }
}

task printProperties << {
    println springVersion
    println emailNotification
    sourceSets.matching { it.purpose == "production" }.each { println it.name }
}
  • Gradle的每个对象都可以通过ext来定义属性
  • sourceSets.all { ext.purpose = null }sourceSets包含的每个对象设置一个ext.purpose属性(相当于初始化),不要这句的话,build也能正常运行,但是会有Warning
  • sourceSets是Configures the source sets of this project
  • sourceSets.matching { it.purpose == “production” }.each { println it.name }是Groovy语法,匹配上“production”的再遍历

Groovy语法

Property accessor

Groovy自动为属性添加getter和setter方法

Property accessor
1
2
3
4
5
6
7
// Using a getter method
println project.buildDir
println getProject().getBuildDir()

// Using a setter method
project.buildDir = 'target'
getProject().setBuildDir('target')

Optional parentheses on method calls

方法调用的时候括号是可选的

Optional parentheses
1
2
test.systemProperty 'some.prop', 'value'
test.systemProperty('some.prop', 'value')

List

List
1
2
3
4
5
6
7
// List literal
test.includes = ['org/gradle/api/**', 'org/gradle/internal/**']

List<String> list = new ArrayList<String>()
list.add('org/gradle/api/**')
list.add('org/gradle/internal/**')
test.includes = list

Map

Map
1
2
3
4
5
6
// Map literal
apply plugin: 'java'

Map<String, String> map = new HashMap<String, String>()
map.put('plugin', 'java')
apply(map)
  • 这里apply plugin: ‘java’相当于Ruby里的apply plugin=>’java’

    Closures as the last parameter in a method

Closure
1
2
3
4
5
repositories {
    println "in a closure"
}
repositories() { println "in a closure" }
repositories({ println "in a closure" })
Comments

Comments