Builg.gradle: how to execute code only according to the chosen taste

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 fragrance:

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

Now, due to the declarative nature of gradle, the remoteGitVersion function is executed every time a project is executed, no matter if the assembly layout is internal or something else. Thus, the quota of github API calls is consumed, and after a while I get a nice forbidden message.

How can i avoid this? Is it possible to perform a function only when the selected aroma is correct?

+4
source share
1 answer

Here:

Android/ Gradle , buildType/buildVariant/productFlavor (v0.10 +)

:

1.

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

2. , , .

assembleInternalDebug .

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

3.

productFlavors {
    internal {
        # no buildConfigField here
    }
}

, .

+1

All Articles