Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Tuesday, August 2, 2016

How to change the proguard mapping file name in gradle for Android project

How to change the proguard mapping file name in gradle for Android project


I have android project based on gradle and I want to change mapping.txt file name after it's generated for my build. How can it be done?

upd

How it can be done in build.gradle? Since I have access there to my flavors and other stiff, I would like to create mapping file name based on flavor/build variant version.

Answer by Konrad Krakowiak for How to change the proguard mapping file name in gradle for Android project


Use this command in your proguard-rules.pro file:

-printmapping path/to/your/file/file_name.txt  

the file will be written in part {root}/path/to/your/file with file_name.txt name.

If you want to have different setting for different flavors you can define many proguard-rules for them

I found one more idea but I am not sure that it is right way.

You can define your path in flavors:

productFlavors {      test1 {          applicationId "com.android.application.test"          project.ext."${name}Path" = 'path/one/mapp.txt'      }      test2 {          project.ext."${name}Path" = 'path/two/mapp.txt'      }  }  

And as next you can define new task before $asseble{variant.name.capitalize()} task as is shown below:

android.applicationVariants.all { variant ->      def envFlavor = variant.productFlavors.get(0).name        def modifyProguardPath = tasks.create(name: "modifyProguardFor${variant.name.capitalize()}", type: Exec) {          def pathToMap = project."${envFlavor}Test1"          doFirst {              println "==== Edit start: $pathToMap ===="          }          doLast {              println "==== Edit end: $pathToMap ===="          }          executable "${rootDir}/utils/test.bash"          args pathToMap      }        project.tasks["assemble${variant.name.capitalize()}"].dependsOn(modifyProguardPath);  }  

and in script ${root}/utils/test.bash - you can modify proguard-rules.pro.

But I think that exist better solution.

Answer by olegflo for How to change the proguard mapping file name in gradle for Android project


Many thanx to Sergii Pechenizkyi who helped me to found this good solution.

To implement copying of proguard mapping files for each flavor we can create "root" task copyProguardMappingTask and number of dynamic tasks for each flavor

def copyProguardMappingTask = project.tasks.create("copyProguardMapping")  applicationVariants.all { variant ->      variant.outputs.each { output ->          ...          if (variant.getBuildType().isMinifyEnabled()) {              def copyProguardMappingVariantTask = project.tasks.create("copyProguardMapping${variant.name.capitalize()}", Copy)                def fromPath = variant.mappingFile;              def intoPath = output.outputFile.parent;                copyProguardMappingVariantTask.from(fromPath)              copyProguardMappingVariantTask.into(intoPath)              copyProguardMappingVariantTask.rename('mapping.txt', "mapping-${variant.name}.txt")                copyProguardMappingVariantTask.mustRunAfter variant.assemble              copyProguardMappingTask.dependsOn copyProguardMappingVariantTask          }      }  }  

afterwards we should run this task after assembling our project. I use jenkins and my tasks option looks like

gradle clean assembleProjectName copyProguardMapping  

It works like a charm.

Answer by igorepst for How to change the proguard mapping file name in gradle for Android project


Simpler solution.

applicationVariants.all { variant ->          if (variant.getBuildType().isMinifyEnabled()) {              variant.assemble.doLast {                  copy {                      from variant.mappingFile                      into "${rootDir}/proguardTools"                      rename { String fileName ->                          "mapping-${variant.name}.txt"                      }                  }              }          }      }  

Answer by Pinhassi for How to change the proguard mapping file name in gradle for Android project


Since the last update variant.mappingFile is not longer available. (I use ProGuard version 4.7, AndroidStudio 2.0)

This is (part of) my build.gradle file:

import java.util.regex.Matcher  import java.util.regex.Pattern    def getCurrentFlavor() {      Gradle gradle = getGradle()      String  tskReqStr = gradle.getStartParameter().getTaskRequests().toString()        Pattern pattern;        if( tskReqStr.contains( "assemble" ) )          pattern = Pattern.compile("assemble(\\w+)(Release|Debug)")      else          pattern = Pattern.compile("generate(\\w+)(Release|Debug)")        Matcher matcher = pattern.matcher( tskReqStr )        if( matcher.find() )          return matcher.group(1).toLowerCase()      else      {          println "NO MATCH FOUND"          return "";      }  }    buildTypes {      release {          proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'          minifyEnabled true            applicationVariants.all { variant ->              variant.outputs.each { output ->                  output.outputFile = new File(output.outputFile.parent, "${variant.name}_v${variant.versionName}.apk")              }              def mappingFile = "${rootDir}\\app\\build\\outputs\\mapping\\${getCurrentFlavor()}\\release\\mapping.txt"              println("mappingFile:  ${mappingFile}")              if (variant.getBuildType().isMinifyEnabled()) {                  variant.assemble.doLast {                      copy {                          from "${mappingFile}"                          into "${rootDir}"                          rename { String fileName ->                              "mapping-${variant.name}.txt"                          }                      }                  }              }          }        }        debug {          minifyEnabled false          useProguard false            applicationVariants.all { variant ->              variant.outputs.each { output ->                  output.outputFile = new File(output.outputFile.parent, "${variant.name}_v${variant.versionName}.apk")              }          }      }    }  

Answer by Dimitar Darazhanski for How to change the proguard mapping file name in gradle for Android project


Pinhassi's solution above works great and it is conforms to the latest Gradle changes. There are a couple of things though that I had to change:

  1. The module name is hardcoded ("app"), which is not ideal since in a lot of cases (including mine) that will not be true. It is better to dynamically detect the module name.
  2. The mapping file also only conforms to the Windows file system by having backward escaped slashes ("\"). If you are on a *NIX system like Linux or Mac, you need to replace those with forward non escaped slashes ("/")
  3. Changed a bit the renaming of the .apk file to include the project name and added a date/time stamp at the end.

Here is the finished code:

import java.util.regex.Matcher  import java.util.regex.Pattern    buildTypes {          release {          debuggable false          minifyEnabled true          proguardFiles 'proguard.cfg'            // Rename the apk file and copy the ProGuard mapping file to the root of the project          applicationVariants.all { variant ->              if (variant.getBuildType().name.equals("release")) {                  def formattedDate = new Date().format('yyyyMMddHHmmss')                  def projectName = ""                  variant.outputs.each { output ->                      def fullName = output.outputFile.name                      projectName = fullName.substring(0, fullName.indexOf('-'))                      // ${variant.name} has the value of "paidRelease"                      output.outputFile = new File((String) output.outputFile.parent, (String) output.outputFile.name.replace(".apk", "-v${variant.versionName}-${formattedDate}.apk"))                  }                  def mappingFile = "${rootDir}/${projectName}/build/outputs/mapping/${getCurrentFlavor()}/release/mapping.txt"                  println("mappingFile:  ${mappingFile}")                  if (variant.getBuildType().isMinifyEnabled()) {                      variant.assemble.doLast {                          copy {                              from "${mappingFile}"                              into "${rootDir}"                              rename { String fileName ->                                  "mapping-${variant.name}.txt"                              }                          }                      }                  }              }          }      }            debug {              debuggable true          }      }    def getCurrentFlavor() {      Gradle gradle = getGradle()      String  tskReqStr = gradle.getStartParameter().getTaskRequests().toString()      Pattern pattern;        if( tskReqStr.contains( "assemble" ) )          pattern = Pattern.compile("assemble(\\w+)(Release|Debug)")      else          pattern = Pattern.compile("generate(\\w+)(Release|Debug)")        Matcher matcher = pattern.matcher( tskReqStr )        if( matcher.find() )          return matcher.group(1).toLowerCase()      else {          println "NO MATCH FOUND"          return "";      }  }  


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.