Gradle cheat sheet

Yaniv   January 19, 2017   No Comments on Gradle cheat sheet

Gradle is a great tool for building applications. Below is a cheat sheet for the most common implementations.

Useful properties

  • projectDir – the project’s directory, where build.gradle file is located
  • buildDir – the directory where Gradle is building, usually located under the build dir, inside the project’s directory.

Task execution order

Gradle determines the exectuion order for tasks at the configuration stage.
The execution order of tasks that linked via dependsOn is not determined and can be random.

In case two tasks are planned to run, mustRunAfter tells Gradle’s execution planner to ensure a task will run only after another task has been completed.

task a << {
    println "Task A"
}

task b << {
    println "Task B"
}
// ensure that task a will run only after task b:
a.mustRunAfter b

task c {
   dependsOn a
   dependsOn b
}

In the example above:

  • gradle a – will run only task a
  • gradle b – will run only task b
  • gradle c – will run task b, then task a

Export of check out from SVN

Use the SVNTools plugin from: https://github.com/martoe/gradle-svntools-plugin

Thus plugin includes many useful SVN functions, such as export, checkout, etc.

In grade.properties, define the properties below for the SVN user and password:

svnUsername = foo
svnPassword = bar

In build.gradle:

// Add to import section, at the top of the build.gradle file:
import at.bxm.gradleplugins.svntools.tasks

// Add to the plugins section:
plugins {
  id "at.bxm.svntools" version "2.1"
}

// add a task to export:
task exportSomething(type: SvnExport) {
  svnUrl = "http://svn.somehost.org/repo/some_project"
  targetDir = "$project.buildDir/exports/some_project"
}

 

Download file

Add download plugin from https://github.com/michel-kraemer/gradle-download-task:

// Add to import section, at the top of the build.gradle file:
import de.undercouch.gradle.tasks.download.Download

// Add to the plugins section:
plugins {
    id "de.undercouch.download" version "3.1.2"
}

// add a task to export:
task downloadFile(type: Download) {
 src 'http://www.somehost.com/file.zip'
 dest project.buildDir
}

Detect the OS Gradle is running on

Grade has built in function that returns the OS type. You can use it to run OS specific build code:

// Add to import section, at the top of the build.gradle file:
import org.gradle.internal.os.OperatingSystem

task doSomething {
    if (OperatingSystem.current().isMacOsX()) {
       // do some mac specific code
    }
    else if (OperatingSystem.current().isLinux()) {
       // do some Linux specific code
    }
   else if (OperatingSystem.current().isWindows()) {
       // do some Windows specific code
   }
}

Leave a Reply

Your email address will not be published. Required fields are marked *