Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

gradle

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?

like image 477
spacifici Avatar asked Nov 01 '22 10:11

spacifici


1 Answers

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.

like image 171
Steffen Funke Avatar answered Nov 12 '22 20:11

Steffen Funke