Gradle學習

gradle 經常使用功能

經常使用命令

  • gradle build -b idgenerator/build.gradle : 指定build文件
  • gradle -Pparam=test : 傳參數

gradle 屬性與命令傳值

  • gradle屬性
    1. gradle.properties : 定義屬性,在build.gradle中能夠經過$properties-name獲取
    2. ext { propName=value } 中定義的屬性能經過propName直接用
    3. gradle properties能夠查看屬性
    4. gradle build -PpropName=value 能夠給properties傳值
  • gradle系統屬性
    1. gradle.properties 處理定義屬性,也能定義系統屬性,系統屬性就是gradle系統的運行的JVM的環境,不是gradle task執行的任務的屬性
    2. systemProp.propName=value, 系統屬性在build.gradle中能夠經過System.properties['propName']獲取
    3. 以ORG_GRADLE_PROJECT.爲前綴的環境變量或者以org.gradle.project.爲前綴的系統屬性均可以看成gradle屬性使用,能夠用來保存密碼
    4. gradle build -DpropName=value 能夠給系統屬性傳值
  • 爲gradle task設置系統屬性
    1. test { systemProperty "spring.profiles.active", "local" }
  • 爲spring指定profiles - 經過傳遞gradle系統屬性給gradle task
    1. test { systemProperty System.properties }
    2. gradle build -Dspring.profiles.active=prod
  • 爲spring指定profiles - 經過properties傳值
    1. test { systemProperty 'spring.profiles.active', $profiles }
    2. gradle build -Pprofiles=prod

gradle緩存和mavenLocal()

  • gradle可使用maven本地倉庫,可是不會將本地倉庫做爲其餘倉庫的緩存
  • gradle使用本身的cache代替maven本地倉庫
  • 因此相似永遠更新0.0.1-SNAPSHOT依賴的狀況下,不能使用mavenLocal(),正確作法升級到0.0.2-SNAPSHOT

spring boot 打包

  • apply plugin: 'org.springframework.boot'
  • bootJar { archiveClassifier = "boot" }

Ktlint代碼format

  • Dependency : classpath "org.jlleitschuh.gradle:ktlint-gradle:8.1.0"
  • apply plugin: "org.jlleitschuh.gradle.ktlint"
  • 命令
    1. gradle ktlintformat
    2. gradle ktlintApplyToIdea : 須要父項目有repository

publish上傳Maven的Repostory

  • apply plugin: 'maven-publish'
  • 父項目添加:html

    publishing {
          repositories {
              mavenLocal()
              maven {
                  def repoKey = 'lib-release/libs-release-local'
                  if (project.version.toString().endsWith("-SNAPSHOT"))
                      repoKey = 'lib-snapshot/libs-snapshot-local'
                  url "https://${xxx}/repository/${repoKey}"
                  credentials {
                      username "${xxx}"
                      password "${xxx}"
                  }
              }
          }
      }
  • 須要publish的項目添加:java

    publishing {
          publications {
              mavenJava(MavenPublication) {
                  groupId "$project.group"
                  version "$project.version"
                  artifactId project.name
                  from components.java
              }
          }
      }

Gradle 父子項目

Parent項目

  • 能夠保留全部文件,也能夠刪除src文件
  • settings.gradle : include "module1", "module2"
  • build.gradle
    1. 可使用subprojects或者allprojects
    2. 將公共都apply/dependencies都放在subprojects

Module項目

  • 只保留src和build.gradle
  • settings.gradle要刪除,不然單獨build項目不會去找parent的build.gradle
  • build.gradle : Parent的build.gradle中有的它不能再有
  • 單獨build
    1. gradle clean build -b module1/build.gradle
    2. 在module1下build
  • module1依賴module2
    1. compile project(":module2")
    2. 單獨build module1會去編譯module2,單不會測試和打包module2

進度

II. Working with existing buildsspring

  1. Installing Gradle
  2. Using the Gradle Command-Line
  3. The Gradle Wrapper
  4. The Gradle Daemon
  5. Dependency Management Basics
  6. Introduction to multi-project builds
  7. Continuous build
  8. Using the Gradle Graphical User Interface
  9. The Build Environment
  10. Troubleshooting
  11. Embedding Gradle

III. Writing Gradle build scripapi

  1. Build Script Basics
  2. Build Init Plugin
  3. Writing Build Scripts
  4. More about Tasks
  5. Working With Files
  6. Using Ant from Gradle
  7. The Build Lifecycle
  8. Wrapper Plugin
  9. Logging
  10. Dependency Management
  11. Multi-project Builds
  12. Gradle Plugins
  13. Standard Gradle plugins
  14. The Project Report Plugin
  15. The Build Dashboard Plugin
  16. Comparing Builds
  17. Publishing artifacts
  18. The Maven Plugin
  19. The Signing Plugin
  20. Ivy Publishing (new)
  21. Maven Publishing (new)
  22. The Distribution Plugin
  23. The Announce Plugin
  24. The Build Announcements Plugin

IV. Extending the build緩存

  1. Writing Custom Task Classes
  2. Writing Custom Plugins
  3. The Java Gradle Plugin Development Plugin
  4. Organizing Build Logic
  5. Initialization Scripts
  6. The Gradle TestKit

V. Building JVM projectsapp

  1. Java Quickstart
  2. The Java Plugin
  3. Web Application Quickstart
  4. The War Plugin
  5. The Ear Plugin
  6. The Jetty Plugin
  7. The Application Plugin
  8. The Java Library Distribution Plugin
  9. Groovy Quickstart
  10. The Groovy Plugin
  11. The Scala Plugin
  12. The ANTLR Plugin
  13. The Checkstyle Plugin
  14. The CodeNarc Plugin
  15. The FindBugs Plugin
  16. The JDepend Plugin
  17. The PMD Plugin
  18. The JaCoCo Plugin
  19. The Sonar Plugin
  20. The SonarQube Runner Plugin
  21. The OSGi Plugin
  22. The Eclipse Plugins
  23. The IDEA Plugin

VI. The Software model - Next generation Gradle buildsmaven

  1. Rule based model configuration
  2. Software model concepts
  3. Implementing model rules in a plugin
  4. Building Java Libraries
  5. Building Play applications
  6. Building native software
  7. Extending the software model

VII. Appendixide

A. Gradle Samples
B. Potential Traps
C. The Feature Lifecycle
D. Gradle Command Line
Glossaryspring-boot

安裝 Gradle

  • Gradle 官網
  • JDK1.6以上
  • 設置Env,啓用cmd gradle命令
    1. GRADLE_HOME : 不帶;
    2. PATH: %GRADLE_HOME%/bin
    3. 測試 cmd : gradle -v

Gradle HelloWorld

  1. build.gradlepost

    task compile << {
         println 'compiling source'
     }
    
     task compileTest(dependsOn: compile) << {
         println 'compiling unit tests'
     }
     task test(dependsOn: [compile, compileTest]) << {
         println 'running unit tests'
     }
    
     task dist(dependsOn: [compile, test]) << {
         println 'building the distribution'
     }
  2. cmd cd build.gradle所在目錄

    gradle compile compileTest

Gradle Command-line

  • Gradle Command-line Links
  • gradle dist -x test
    • 排除test任務
  • gradle test dist --continue
    • 當test失敗,dist還會繼續,但若是dist依賴test則再也不繼續
  • gradle -b build2.gradle test
    • 選擇build文件
  • gradle -q dist
    • 輸出省略任務名稱
  • gradle dist --profile
    • 輸出任務報表 輸出目錄:build/reports
  • gradle dependencies
    • 輸出項目依賴
  • gradle -m dist
    • 測試任務是否能夠正常運行

其餘

  • gradle tasks --all
    • 顯示任務信息
  • gradle help --task taskName
    • 顯示某個任務Detail信息
  • gradle project
    • 顯示項目信息
  • gradle properties
    • 顯示項目properties

Gradle 腳本編寫之: 基礎篇

<< 等於 doLast

dependsOn/Lazy dependsOn

  • task dist(dependsOn: test) << {}
  • task dist(dependsOn: 'test') << {}

Dynamic tasks

  • gradle -q task0

    4.times { i ->
          task "task$i" << {
              println "I'm task number $i"
          }
      }
      task0.dependsOn task2, task3
  • gradle -q hello

    task hello << {
          println 'Hello World'
      }
      hello.doFirst {
          println 'Hello doFirst'
      }
      hello.doLast {
          println 'Hello doLast'
      }
      hello << {
          println 'Hello Jude'
      }

task定義 屬性/方法

  • Code

    task test(dependsOn:'dist'){
          ext.myName = "Jude"
          version = "1.0"
      }
      task dist << {
          setTestName('Jude Sheng')
          println test.myName + "$version"
      }        
      String setTestName(String myName) {
          test.ext.myName = myName
      }

默認Tasks

  • defaultTasks 'dist','test'
  • gradle -q

Gradle 腳本編寫之: Gradle方法

  • taskGraph.hasTask / taskGraph.whenReady
    • 當前執行的task中是否有某個task

      gradle.taskGraph.whenReady {taskGraph ->
            if (taskGraph.hasTask(release)) {
                version = '1.0'
            } else {
                version = '1.0-SNAPSHOT'
            }
        }

Gradle 腳本編寫之: API

Project

Gradle Wrapper

生成wrapper文件

  1. gradle wrapper
    • 生成當前gradle版本wrapper文件

      gradlew
          gradlew.bat
          gradle/wrapper/
            gradle-wrapper.jar
            gradle-wrapper.properties
  2. 自定義wrapper所用gradle版本 task

    task wrapper(type: Wrapper) {
         gradleVersion = '2.11'
     }
  3. 使用本地gradle zip文件代替gradle遠程下載,zip包須要放在 gradle\wrapper目錄下

    task wrapper(type: Wrapper) {
         distributionPath = 'gradle-2.11-all.zip'
     }

使用gradlew命令代替gradle命令

  • gradlew dist
    • 第一次會下載而且解壓gradle zip文件至目錄 C:\Users\xxxx.gradle\wrapper,以後不會下載
    • C:\Users\xxxx.gradle文件夾是在你安裝gradle後跑第一個gradle命令自動生成
  • 使用wrapper的gradle版本代替,而不會用本地gradle版本
  • gradle推薦使用wrapper模式,並將生成的wrapper文件加入版本控制

其餘

Daemon使用緩存解決gradle運行速度

  1. 默認關閉Daemon,gradle建議Dev機子都開啓Daemon
  2. 開啓Daemon
    • C:\Users\xxxx\.gradle目錄新建文件 gradle.properties
    • gradle.properties文件添加 org.gradle.daemon=true
      • org.gradle.daemon=true而且Daemon未開啓時,運行gradle命令會自動開啓Daemon
  3. 關閉Daemon
    • gradle --stop
    • 閒置3小時的Daemon進程會自動關閉

支持task名字縮

Java plugin

啓用Java plugin

  1. apply plugin: 'java'
  2. https://docs.gradle.org/3.5/userguide/java_plugin.html

Java plugin 經常使用properties

  • sourceCompatibility = 1.6 : 編譯java version
  • archivesBaseName='ratesds' : jar包等的名字
  • sourceSets.main.java.srcDir("src") :設置java source目錄
    1. sourceSets : SourceSetContainer對象,SourceSet對象的集合
    2. main : SourceSet對象
    3. java : SourceDirectorySet對象
    4. srcDir() : SourceDirectorySet的方法
    5. 直觀寫法

      sourceSets {
           main {
               output.resourcesDir = "$buildDir/target"
               java {
                   srcDirs = ['src']
               }
               resources {
                   srcDirs = ['ds']
               }
           }
       }
  • 依賴包設置

    dependencies {
          compile fileTree('lib') 
      }

Java plugin 經常使用Tasks

  • compileJava : 編譯class
    1. sourceSets.main.java.srcDir("src")
  • processResources : 拷貝resources
  • jar : 打成jar包
  • javadoc : 生成document html
  • build : 全套服務
  • clean : 刪除build文件夾

Copy Task

task copyLib << {
    File scooby = file("$buildDir/target/scooby")
    int scoobySize = scooby.listFiles().length
    scoobySize.times { i ->
        String path = scooby.listFiles()[i].getPath() + "/lib"
        println 'start to copy libs into ' + path
        copy {
            from "lib"
            into path
        }
        copy {
            from "$buildDir/libs"
            into path
        }
    }
}

Zip Task

task zip(type: Zip) {
    from "$buildDir/target/RatesDSCommonConfigs"
    archiveName "RatesDSCommonConfigs.zip"
    doFirst {
        println "Start to create the zip file for RatesDSCommonConfigs"
    }
}
task zipDS {
    File scooby = file("$buildDir/target/scooby")
    int scoobySize = scooby.listFiles().length
    scoobySize.times { i ->
        String scoobyDS = scooby.listFiles()[i].getPath()
        String scoobyDSName = scooby.listFiles()[i].getName()
        String tarFileName = scoobyDSName + ".zip"
        task "zip_$scoobyDSName" (type: Zip) {
            from scoobyDS
            archiveName tarFileName
            doFirst {
                println "Start to create the zip file for $scoobyDSName"
            }
        }
        zip.dependsOn "zip_$scoobyDSName"
    }
}

RatesDS2.0

apply plugin: 'java'

archivesBaseName = 'cv-ratesds'

sourceCompatibility = 1.6

sourceSets {
    main {
        output.resourcesDir = "$buildDir/target/RatesDSCommonConfigs"
        java {
            srcDirs = ['src']
        }
        resources {
            srcDirs = ['resources']
        }
    }
}


dependencies {
    compile fileTree('lib') 
}

task copyDS(dependsOn: [build]) <<{
    println 'start to copy DS processes'
    copy {
        from 'ds'
        into "$buildDir/target"
    }
}

task copyLib(dependsOn: [copyDS]) << {
    File scooby = file("$buildDir/target/scooby")
    int scoobySize = scooby.listFiles().length
    scoobySize.times { i ->
        String path = scooby.listFiles()[i].getPath() + "/lib"
        println 'start to copy libs into ' + path
        copy {
            from "lib"
            into path
            exclude "scooby"
        }
        copy {
            from "$buildDir/libs"
            into path
        }
    }
}

task tar(type: Tar) {
    File install = file("$buildDir/install")
    from "$buildDir/target/RatesDSCommonConfigs"
    destinationDir install
    archiveName "RatesDSCommonConfigs.tar"
    doFirst {
        println "Start to create the tar file for RatesDSCommonConfigs"
    }
    tar.dependsOn copyLib
}

task tarScoobyConfig(type: Tar) {
    File install = file("$buildDir/install")
    from "$buildDir/target/RatesDSCommonConfigs/ScoobyConfig"
    destinationDir install
    archiveName "ScoobyConfig.tar"
    doFirst {
        println "Start to create the tar file for ScoobyConfig"
    }
    tar.dependsOn tarScoobyConfig
}

task tarDS {
    File install = file("$buildDir/install")
    File scooby = file("ds/scooby")
    int scoobySize = scooby.listFiles().length
    scoobySize.times { i ->
        String scoobyDSName = scooby.listFiles()[i].getName()
        String tarFileName = scoobyDSName + ".tar"
        String scoobyPath = "$buildDir/target/scooby/" + scoobyDSName
        task "tar_$scoobyDSName" (type: Tar) {
            from scoobyPath
            destinationDir install
            archiveName tarFileName
            doFirst {
                println "Start to create the tar file for $scoobyDSName"
            }
        }
        tar.dependsOn "tar_$scoobyDSName"
    }
}

task install(dependsOn:[tar]) {
    println 'start to install RatesDS2.0'
}
相關文章
相關標籤/搜索