spacifici
spacifici

Reputation: 2186

builg.gradle: how to execute code only on selected flavor

I declared this function in my Android project build.gradle:

def remoteGitVertsion() {
  def jsonSlurper = new JsonSlurper()
  def object = jsonSlurper.parse(new URL("https://api.github.com/repos/github/android/commits"))
  assert object instanceof List
  object[0].sha
}

And this flavor:

android {
  ...
  productFlavors {
    internal {
      def lastRemoteVersion = remoteGitVersion()
      buildConfigField "String", "LAST_REMOTE_VERSION", "\"" + lastRemoteVersion + "\""
    }
    ...
  }
  ...
}

Now, due to gradle declarative nature, the remoteGitVersion function is executed every time the project is built, it doesn't matter if the build flavor is internal or something else. So, the github API call quota is consumed and, after a little while, I receive a nice forbidden message.

How can I avoid this? Is it possible to execute the function only when the selected flavor is the right one?

Upvotes: 6

Views: 2705

Answers (1)

Steffen Funke
Steffen Funke

Reputation: 2468

Took reference from here:

In Android/Gradle how to define a task that only runs when building specific buildType/buildVariant/productFlavor (v0.10+)

To recap:

1. Wrap your flavor specific logic into a task

task fetchGitSha << {
    android.productFlavors.internal {
        def lastRemoteVersion = remoteGitVersion()
        buildConfigField "String", "LAST_REMOTE_VERSION", "\"" + lastRemoteVersion + "\""
    }
}

2. Make the task being called whenever you build your variant, and only then.

You could use assembleInternalDebug to hook into, in your case.

tasks.whenTaskAdded { task ->
    if(task.name == 'assembleInternalDebug') {
        task.dependsOn fetchGitSha
    }
}

3. Make sure to remove the dynamic stuff from your flavor definition

productFlavors {
    internal {
        # no buildConfigField here
    }
}

Hope that helps.

Upvotes: 3

Related Questions