Gradle is an automated build tool based on the groovy language with DSL syntax, a build script that can contain any groovy language elements, each of which is a UTF-8 encoded file.
6-1 Project Object API
As we said earlier, Gradle defines a project in the build script that is associated with each project in the build script that Gradle creates a project type object, and when the build script executes it configures the associated project object Each called method and property in the build script is delegated to the current project object.
Let's look at an example that uses project properties:
nameprintln project.name
The output of the above two println statements is the same; because the Name property is not defined in the current script, it is possible to use auto-delegation as the first, usually we use the second one.
The Project object provides some standard properties that we can easily use in the build script, as follows:
| Name |
Type |
Default Value |
| Project |
Project |
Project Instance Object |
| Name |
String |
The name of the project directory |
| Path |
String |
Absolute path to the project |
| Description |
String |
Project description |
| ProjectDir |
File |
The directory that contains the build script |
| Build |
File |
Projectdir/build |
| Group |
Object |
Not specifically stated |
| Version |
Object |
Not specifically stated |
| Ant |
Antbuilder |
Ant Instance Object |
See the project's API documentation for details on project-specific methods. Here we give an example of project's apply method, as follows:
//加载一个gradle文件apply from: rootProject.getRootDir().getAbsolutePath() + "/common.gradle"
6-2 Script Object API
When Gradle executes a script, it compiles the script into a class that implements script (which is described in the essence compiled class code of groovy script basics in the previous blog), meaning that all properties and methods are declared in the script's interface.
6-3 Gradle Object API
For detailed properties and API introduction points for Gradle objects I can. Here is a direct example of using the Gradle object, as follows:
6-4 gradle Variable declaration
There are two types of variables that can be declared in the Gradle script, as follows:
- Local variables
- Extended variables
The local variable uses the keyword DEF Declaration, which is visible only where it is declared, as follows:
"dest" task copy(type: Copy) { form "source" into dest }
All enhanced objects in Gradle can have custom attributes (such as projects, tasks, source sets, etc.), and you can add multiple properties at once using the EXT extension block. As follows:
"java"ext { springVersion = "3.1.0.RELEASE" emailNotification = "[email protected]"}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}}
Above, we add two extended properties to the project object with an ext extension block, and when these extended properties are added, they can be read and written like predefined properties.
6-5 gradle in groovy use
This is not what to say, specifically, you can refer to the "Groovy script based on the full guide" this blog, there are detailed introduction. Here is a rough summary of our memories:
Groovy automatically converts a reference to a property to the appropriate Getter/setter method.
The parentheses are optional when groovy calls the method.
Groovy provides some shortcuts for the list and map collections, such as Apply plugin: ' java ' in plugin: ' Java ' is actually a method of map,apply in groovy, omitting parentheses.
Alas, go to the previous blog in detail.
"Craftsman Joshui Http://blog.csdn.net/yanbober Reprint Please specify the source." Dot I started Android technology Exchange "
7 gradle File Operation Basics
The actual use of the gradle process most of the time need to manipulate the file, fortunately Gradle provides us with some API to quickly processing.
Locating files:
We can use the Project.file () method to locate a file object (refer to Project's API for details) as follows:
//相对路径File configFile = file(‘src/config.xml‘)//绝对路径File configFile = file(configFile.absolutePath)//项目路径的文件对象 File configFile = file(new File(‘src/config.xml‘))
The file () method can be found from the project's API to receive any form of object arguments, it converts the parameter value to an absolute file object, and usually we can pass a string or file instance, and if the path is an absolute path, it is directly constructed as a file instance. Otherwise it will be constructed as a project directory plus a file object that passes the directory; Of course, the file () method can also identify URLs (such as file:/some/path.xml, etc.).
File collection:
A collection of files is actually a set of files, Gradle uses the FileCollection interface to represent a collection of files, Gradle API implements this interface for many classes, such as dependency configurations. One way to get an filecollection instance is Project.files (), and we can pass any number of object arguments. As follows:
files(‘src/file1.txt‘, new File(‘src/file2.txt‘), [‘src/file3.txt‘, ‘src/file4.txt‘])
Using an iterative operation can also convert it to some other type, and we can use the + operation to merge two file collections, using the-action to subtract a collection of files. Here's an example:
//iterates over the collection of files. each {File file, println File.name}//convert file collection to other types set set = Collection.filesset Set2 = collection as setlist list = collection as liststring path = collection.aspathfile file = Collection.singleFileFile File2 = Collection as file//Add and Decrease file collection def union = collection + files ( ' src/file3.txt ') def different = collection-files ( ' src/file3.txt ')
We can also pass a closure or callback instance parameter to the files () method, call it when querying the contents of the collection, then convert the return value to some file instance, and the return value can be any type of object supported by the files () method. Here's an example:
task list << {File Srcdir //use closure to create a collection of files collection = files {srcdir.listfiles ( )} Srcdir = file ( ' src ') println "Co Ntents of $srcDir. Name "Collection.collect {relativepath (it)}. Sort (). each {println it} srcdir = file ( Span class= "hljs-string" > ' src2 ') println "Contents of $srcDir. Name" Collection.collect { RelativePath (it)}. sort (). each {println it}}
File Tree:
The file tree can represent a directory tree structure or the contents of a zip archive, Filetree inherits from FileCollection, so we can process the file tree like a collection of files, using Project.filetree () method to get the Filetree instance, which creates an object based on the base directory. As follows:
/Create a file tree with one base directory Filetree tree = Filetree (dir:' Src/main ')Add the Include and exclude rules tree.Include' **/*.java ' Tree.exclude' **/abstract* 'Create a tree with a path trees = Filetree (' src ').Include' **/*.java ')Use closure to create a number tree = Filetree (' src ') {Include' **/*.java '}Create a tree with map = Filetree (dir:' Src ',Include' **/*.java ') tree = Filetree (dir:' src ', includes: [' **/*.java ', ' src ', include: **/*.java ', exclude: ' **/*test*/** ') //traverse the tree of files. each {File file, println File}//filter file tree Filetree filtered = tree.matching {include ' org/gradle/api/** '}//merging file tree Afiletree sum = tree + filetree (dir: ' src/test ') //access to the number of elements tree.visit {element, println " $element. RelativePath = $element. File "}
We can also use the contents of compressed files such as zip or tar as a file tree, and the Project.ziptree () and Project.tartree () methods can return a Filetree instance. As follows:
// 使用路径创建一个ZIP文件FileTree zip = zipTree(‘someFile.zip‘)// 使用路径创建一个TAR文件FileTree tar = tarTree(‘someFile.tar‘)//TarTree可以根据文件扩展名得到压缩方式,如果我们想明确的指定压缩方式则可以如下操作FileTree someTar = tarTree(resources.gzip(‘someTar.ext‘))
Specify the input file:
The properties of some objects in Gradle can receive a set of input files, such as the Source property of the Javacomplile task (which defines the compiled Origin file). As follows:
Use a file object to set the source directory compile {Source =File' Src/main/java ')}Use a character path to set the source directory compile {Source =' Src/main/java '}Use a collection to set up multiple source directories compile {Source = [' Src/main/java ',‘.. /shared/java ']}Use FileCollection or Filetree to set the source directory compile {Source = Filetree (dir:' Src/main/java '). Matching {include' org/gradle/api/** '}}//use closures to set source directory compile {source = {// Use the contents of each zip file in the src dir file ( ' src '). Listfil Es (). findAll {it.name. EndsWith ( ". Zip ')}.collect {ziptree (IT)}}}compile {// Add source directory using character path source ' Src/main/java ', ' Src/main/groovy ' //Add source directory using the File object source file ( ". /shared/java ') //use closures to add source directory source { file ( ' src/test/'). Listfiles ()}}
To copy a file:
We can use the Copy task (copy) for file copy operation, the replication task is very extensibility, it can filter the contents of the copied file, use the Copy task to provide the source file you want to copy and a target directory, if you want to specify how the file is copied when you can use the replication rules, The replication rule is an implementation of an Copyspec interface, and we use the Copyspec.from () method to specify the source file, and the Copyspec.into () method specifies the target directory. As follows:
Task Copytask (type:copy) {From' Src/main/webapp 'Into' Build/explodedwar '}task anothercopytask (type:copy) {Copy all files under the Src/main/webapp directoryFrom' Src/main/webapp 'Copy a separate fileFrom' Src/staging/index.html 'Copy a task output fileFrom CopytaskTo explicitly use the outputs property of a task to copy the output file of a taskFrom Copytaskwithpatterns.outputsCopy the contents of a Zip compressed fileFrom Ziptree (' Src/main/assets.zip ')Specify Destination Directoryinto {getdestdir ()}}task copytaskwithpatterns (type:copy) {From' Src/main/webapp 'Into' Build/explodedwar 'Include' **/*.html 'Include' **/*.jsp ' exclude {details, details.File.name.endsWith ('. html ') && details.File.Text.Contains' Staging ')}}task copymethod << {copy {From' Src/main/webapp 'Into' Build/explodedwar 'Include ' **/*.html ' include ' **/*.jsp '}} //Renaming files on replication task rename (type:copy) { from ' Src/main/webapp ' into Span class= "hljs-string" > ' Build/explodedwar ' //use closure map filename Rename {String fileName, Filename. Replace ( '-staging-', ")} // Use regular expressions to map file names rename "(. +)-staging-(. +) ', ' $1$2 ' rename (/(. +)-staging-(. +)/, ' $1$2 ')}
File Synchronization task:
The Sync Task (sync) inherits from the Copy task (copy), which copies the source file to the destination directory when it executes, and then deletes all non-replicated files from the destination directory. As follows:
task libs(type: Sync) { from configurations.runtime into "$buildDir/libs"}
To create an archive file:
Use the archive task to create archive files such as Zip, Tar, Jar, War, Ear, and so on:
‘java‘task zip(type: Zip) { from ‘src/dist‘ into(‘libs‘) { from configurations.runtime }}
ps:http://blog.csdn.net/yanbober/article/details/49314255
Gradle script Snip---copy