Gradle copy and rename in loop

I'm working with Android Studio 3.

For each flavor, I want to copy mapping.txt and rename it.

My Gradle task :

task deployApks(type: Copy) {
        android.applicationVariants.all { variant ->
            if (variant.buildType.name == 'release') {
            variant.outputs.all {
                  def flavor = variant.productFlavors.name.get(0)

                  def dirApk = System.getProperty("user.dir") + '/app/build/' + flavor + '/release/'
                  def dirMapping = System.getProperty("user.dir") + '/app/build/outputs/mapping/' + flavor + '/release/'

                  //copy apk and mapping.txt
                  from dirApk, dirMapping
                  include '*-release.apk', 'mapping.txt'
                  into dirDeploy

                  //rename mapping.txt
                  from dirDeploy
                  include 'mapping.txt'
                  into dirDeploy
                  rename 'mapping.txt', 'mapping-' + flavor + '.txt'
                  println("Rename mapping.txt tomapping-" + flavor + ".txt")
             }
        }
    }
}

What I want in deploy directory :

  • flavor1-release.apk

  • mapping-flavor1.txt

  • flavor2-release.apk

  • mapping-flavor2.txt

What I get :

  • flavor1-release.apk

  • mapping-flavor1.txt

  • flavor2-release.apk

Is gradle copy asynchronous.?

It looks like if renaming is done after all copies.

1 answer

  • answered 2017-11-13 11:03 Opal

    You may not know but gradle build consists of 3 phases:

    • initialisation
    • configuration
    • execution

    Task (including Copy you used) actions (a task is a collection of actions run in order) are configured in the second phase. Eve if you put loop in task's body the last iteration will win. The easiest way is to change your task to the following (copying manually):

    task deployApks {
      doLast {
        android.applicationVariants.all { variant ->
          if (variant.buildType.name == 'release') {
          variant.outputs.all {
            def flavor = variant.productFlavors.name.get(0)
    
            def dirApk = System.getProperty("user.dir") + '/app/build/' + flavor + '/release/'
            def dirMapping = System.getProperty("user.dir") + '/app/build/outputs/mapping/' + flavor + '/release/'
    
            //copy apk and mapping.txt
            copy {
              from dirApk, dirMapping
              include '*-release.apk', 'mapping.txt'
              into dirDeploy
              rename 'mapping.txt', 'mapping-' + flavor + '.txt'
            }
           }
          }
        }
      }
    }
    

    If that solves the problem - (you don't need to task caching) you can work with. Otherwise you need to configure Copy task appropriately or even write a custom task.