AresTransform.groovy 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. if (clazz.absolutePath.replace("\\", "/").endsWith(MethodAgentVisitor.AgentClass + ".class")) return
  51. ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS)
  52. ClassReader cr = new ClassReader(clazz.bytes)
  53. ClassAdapter adapter = new ClassAdapter(cw, project)
  54. cr.accept(adapter, ClassReader.SKIP_DEBUG)
  55. if (adapter.modify) {
  56. FileOutputStream out = new FileOutputStream(clazz)
  57. out.write(cw.toByteArray())
  58. out.close()
  59. }
  60. return adapter.modify
  61. }
  62. }