官术网_书友最值得收藏!

Writing a build script

In the first chapter, we have already written our first build script. Let's create a similar build script with a simple task. Gradle will look for a file with the name build.gradle in the current directory. The build.gradle file contains the tasks that make up our project. In this example, we define a simple task that prints out a simple message to the console:

// Assign value to description property. 
project.description = 'Simple project' 
 
// DSL to create a new task using 
// Groovy << operator. 
task simple << { 
    println 'Running simple task for project ' + 
      project.description 
} 

If we run the build, we see the following output in the console:

:simple
Running simple task for project Simple project
BUILD SUCCESSFUL
Total time: 0.57 secs

A couple of interesting things happen with this small build script. Gradle reads the script file and creates a Project object. The build script configures the Project object, and finally, the set of tasks to be executed is determined and executed.

So, it is important to note that Gradle creates a Project object for us. The Project object has several properties and methods and it is available in our build scripts. We can use the project variable name to reference the Project object, but we can also leave out this variable name to reference properties and methods of the Project object. Gradle will automatically try to map properties and methods in the build script to the Project object.

In our simple build script, we assign the Simple project value to the description project property. We used the explicit project variable name and Groovy property assignment syntax. The following build script uses a different syntax, which is a bit more like Java, to get the same result:

// Use setDescription method 
// to assign value instead of 
// Groovy assignment. 
project.setDescription('Simple project') 
 
// Use create method to add new 
// task instead of Groovy << operator. 
project.getTasks().create('simple') { 
    println 'Running simple task for project ' + 
      project.description 
} 

Here, we use the Java syntax to set and get the value of the description property of the Project object. We are very flexible in our syntax, but we will stick to the Groovy syntax for the rest of the book as it results in more readable build scripts.

主站蜘蛛池模板: 湾仔区| 玛纳斯县| 上饶县| 石河子市| 苗栗县| 炉霍县| 东光县| 青阳县| 浑源县| 巩义市| 香河县| 建德市| 神木县| 巫溪县| 湖南省| 宣化县| 会昌县| 兰溪市| 墨玉县| 三门峡市| 延庆县| 万盛区| 正宁县| 桃源县| 曲麻莱县| 宁乡县| 达日县| 普定县| 酒泉市| 治多县| 文昌市| 拜城县| 潢川县| 鄄城县| 巴彦县| 富锦市| 集安市| 苗栗市| 蒙自县| 泌阳县| 嘉义市|