AresTransform.groovy 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package com.gradle.ares
  2. import com.gradle.JarZipUtil
  3. import com.gradle.ModifyClassTransform
  4. import org.gradle.api.Project
  5. import org.objectweb.asm.ClassReader
  6. import org.objectweb.asm.ClassWriter
  7. /**
  8. * Created by Glen on 2017/2/7.
  9. */
  10. public class AresTransform extends ModifyClassTransform {
  11. public AresTransform(Project project) {
  12. super(project);
  13. }
  14. @Override
  15. protected void handleChangedFile(File input) {
  16. String path = input.absolutePath.replace("/", "\\")
  17. debug("changed:" + path)
  18. if (input.isFile()) {
  19. if (path.endsWith(".class")) {
  20. modifyClass(input)
  21. } else if (path.endsWith(".jar")) {
  22. boolean modify = false
  23. if (path.contains("exploded-aar") && !path.contains("exploded-aar\\com.android.support")) {
  24. modify = true
  25. }
  26. if (modify) {
  27. //需要处理的jar包
  28. File tmp = new File(input.getParent() + File.separator + "tmp")
  29. tmp.deleteOnExit()
  30. JarZipUtil.unzipJar(input, tmp.absolutePath)
  31. modify = false
  32. tmp.eachFileRecurse { File file ->
  33. if (file.isFile()) {
  34. if (modifyClass(file)) {
  35. modify = true
  36. }
  37. }
  38. }
  39. if (modify) JarZipUtil.zipJar(tmp.absolutePath, input)
  40. }
  41. }
  42. }
  43. }
  44. /**
  45. * 修改类文件
  46. * @param clazz
  47. * @return
  48. */
  49. private boolean modifyClass(File clazz) {
  50. def str = clazz.absolutePath.replace("\\", "/")
  51. if (str.endsWith(MethodAgentVisitor.AgentClass + ".class")) return
  52. if (str.endsWith(MethodLifeCycleVisitor.LifeClass + ".class")) return
  53. ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS)
  54. ClassReader cr = new ClassReader(clazz.bytes)
  55. ClassAdapter adapter = new ClassAdapter(cw, project)
  56. cr.accept(adapter, ClassReader.SKIP_DEBUG)
  57. if (adapter.modify) {
  58. FileOutputStream out = new FileOutputStream(clazz)
  59. out.write(cw.toByteArray())
  60. out.close()
  61. }
  62. return adapter.modify
  63. }
  64. }