Skip to content

Commit

Permalink
Merge pull request #325 from didi/revert-317-support_agp_3.3
Browse files Browse the repository at this point in the history
Revert "添加对 Android Gradle Plugin 3.3 的支持"
Reverts #317
Testing failed!
  • Loading branch information
superqiaopu authored Jun 28, 2019
2 parents bdba667 + 5a95845 commit 73bd871
Show file tree
Hide file tree
Showing 16 changed files with 134 additions and 279 deletions.
2 changes: 1 addition & 1 deletion PluginDemo/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ dependencies {
// the following aars are also compiled in host project, so they will be filterd when build plugin apk.
// but, wo can still visit their Class and Resources.
implementation 'com.android.support:appcompat-v7:23.4.0'
implementation 'com.didi.virtualapk:core:0.9.9.1-dev'
implementation 'com.didi.virtualapk:0.9.9.1-dev'
}

apply plugin: 'com.didi.virtualapk.plugin'
Expand Down
2 changes: 1 addition & 1 deletion PluginDemo/gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.1-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip
2 changes: 1 addition & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.1-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ package com.didi.virtualapk

import com.android.build.gradle.AppExtension
import com.android.build.gradle.AppPlugin
import com.android.build.gradle.internal.TaskFactory
import com.android.build.gradle.internal.TaskManager
import com.android.build.gradle.internal.api.ApplicationVariantImpl
import com.android.build.gradle.internal.scope.VariantScope
import com.android.build.gradle.internal.variant.VariantFactory
import com.didi.virtualapk.support.TaskFactoryCompat
import com.android.builder.core.VariantType
import com.didi.virtualapk.os.Build
import com.didi.virtualapk.tasks.AssemblePlugin
import com.didi.virtualapk.utils.Log
import com.didi.virtualapk.utils.Reflect
import groovy.transform.TypeChecked
import org.gradle.api.Action
import org.gradle.api.Plugin
import org.gradle.api.Project
Expand All @@ -31,7 +32,7 @@ public abstract class BasePlugin implements Plugin<Project> {

protected Project project
protected Instantiator instantiator
def taskFactory
protected TaskFactory taskFactory

boolean checkVariantFactoryInvoked

Expand All @@ -44,6 +45,8 @@ public abstract class BasePlugin implements Plugin<Project> {
public void apply(Project project) {
this.project = project

Build.initGradleVersion(project)

AppPlugin appPlugin = project.plugins.findPlugin(AppPlugin)

Reflect reflect = Reflect.on(appPlugin.variantManager)
Expand All @@ -68,7 +71,14 @@ public abstract class BasePlugin implements Plugin<Project> {

project.extensions.create('virtualApk', VAExtention)

taskFactory = TaskFactoryCompat.getTaskFactory(appPlugin, project)
if (Build.isSupportVersion(project, Build.VERSION_CODE.V3_1_X)) {
TaskManager taskManager = Reflect.on(appPlugin).field('taskManager').get()
taskFactory = taskManager.getTaskFactory()
} else {
taskFactory = Reflect.on('com.android.build.gradle.internal.TaskContainerAdaptor')
.create(project.tasks)
.get()
}
project.afterEvaluate {

if (!checkVariantFactoryInvoked) {
Expand All @@ -81,7 +91,7 @@ public abstract class BasePlugin implements Plugin<Project> {
def final variantPluginTaskName = createPluginTaskName(variantAssembleTaskName)
final def configAction = new AssemblePlugin.ConfigAction(project, variant)

TaskFactoryCompat.add(taskFactory, variantPluginTaskName, AssemblePlugin, configAction)
taskFactory.create(variantPluginTaskName, AssemblePlugin, configAction)

Action action = new Action<Task>() {
@Override
Expand All @@ -90,7 +100,11 @@ public abstract class BasePlugin implements Plugin<Project> {
}
}

TaskFactoryCompat.configure(taskFactory, "assemblePlugin", action)
if (Build.isSupportVersion(project, Build.VERSION_CODE.V3_1_X)) {
taskFactory.configure("assemblePlugin", action)
} else {
taskFactory.named("assemblePlugin", action)
}
}
}
}
Expand All @@ -105,19 +119,35 @@ public abstract class BasePlugin implements Plugin<Project> {
return name.replace('Release', '')
}

/**
* 通过启动命令判断是否要运行的是是打插件包的 Task
*/
private boolean evaluateBuildingPlugin(AppPlugin appPlugin, Project project) {
def startParameter = project.gradle.startParameter
def targetTasks = startParameter.taskNames

def pluginTasks = ['assemblePlugin'] as List<String>

if (!appPlugin.variantManager.productFlavors.isEmpty()) {
appPlugin.variantManager.variantScopes
.findAll { it.variantConfiguration.buildType.name == "release" }
.forEach { VariantScope scope -> addTaskToListForScope(scope, pluginTasks) }
appPlugin.variantManager.buildTypes.each {
def buildType = it.value.buildType
if ('release' != buildType.name) {
return
}
if (appPlugin.variantManager.productFlavors.isEmpty()) {
return
}

appPlugin.variantManager.productFlavors.each {
String variantName
if (Build.isSupportVersion(project, Build.VERSION_CODE.V3_1_X)) {
variantName = Reflect.on('com.android.build.gradle.internal.core.VariantConfiguration')
.call('computeFullName', it.key, buildType, VariantType.DEFAULT, null)
.get()
} else {
variantName = Reflect.on('com.android.builder.core.VariantConfiguration')
.call('computeFullName', it.key, buildType, VariantType.DEFAULT, null)
.get()
}
def variantPluginTaskName = createPluginTaskName("assemble${variantName.capitalize()}Plugin".toString())
pluginTasks.add(variantPluginTaskName)
}
}

// pluginTasks.each {
Expand All @@ -141,13 +171,6 @@ public abstract class BasePlugin implements Plugin<Project> {
return isBuildingPlugin
}

@TypeChecked
private void addTaskToListForScope(VariantScope scope, List<String> pluginTasks) {
String variantName = scope.fullVariantName
def variantPluginTaskName = createPluginTaskName("assemble${variantName.capitalize()}Plugin".toString())
pluginTasks.add(variantPluginTaskName)
}

protected abstract void beforeCreateAndroidTasks(boolean isBuildingPlugin)

protected final VAExtention getVirtualApk() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
package com.didi.virtualapk


import com.android.build.gradle.api.ApplicationVariant
import com.android.build.gradle.internal.api.ApplicationVariantImpl
import com.android.build.gradle.internal.ide.ArtifactDependencyGraph
import com.android.build.gradle.internal.pipeline.TransformTask
import com.android.build.gradle.internal.publishing.AndroidArtifacts
import com.android.build.gradle.internal.transforms.ProGuardTransform
import com.android.build.gradle.tasks.ProcessAndroidResources
import com.didi.virtualapk.support.ArtifactDependencyGraphCompat
import com.didi.virtualapk.support.ResolvedArtifactCompat
import com.didi.virtualapk.os.Build
import com.didi.virtualapk.utils.FileUtil
import com.didi.virtualapk.utils.Log
import com.didi.virtualapk.utils.Reflect
import com.google.common.collect.ImmutableMap
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.artifacts.component.ComponentIdentifier
Expand All @@ -35,14 +36,14 @@ public class VAHostPlugin implements Plugin<Project> {

this.project = project

Build.initGradleVersion(project)

//The target project must be a android application module
if (!project.plugins.hasPlugin('com.android.application')) {
Log.e(TAG, "application required!")
return
}

Log.i(TAG, "android gradle plugin version is " + Build.AGP_VERSION)

vaHostDir = new File(project.getBuildDir(), "VAHost")

project.afterEvaluate {
Expand Down Expand Up @@ -90,20 +91,28 @@ public class VAHostPlugin implements Plugin<Project> {
FileUtil.saveFile(vaHostDir, "versions", {
List<String> deps = new ArrayList<String>()
Log.i TAG, "Used compileClasspath: ${applicationVariant.name}"
Set compileArtifacts = ArtifactDependencyGraphCompat.getAllArtifacts(project, applicationVariant)
Set<ArtifactDependencyGraph.HashableResolvedArtifactResult> compileArtifacts
if (Build.isSupportVersion(project, Build.VERSION_CODE.V3_1_X)) {
ImmutableMap<String, String> buildMapping = Reflect.on('com.android.build.gradle.internal.ide.ModelBuilder')
.call('computeBuildMapping', project.gradle)
.get()
compileArtifacts = ArtifactDependencyGraph.getAllArtifacts(
applicationVariant.variantData.scope, AndroidArtifacts.ConsumedConfigType.COMPILE_CLASSPATH, null, buildMapping)
} else {
compileArtifacts = ArtifactDependencyGraph.getAllArtifacts(
applicationVariant.variantData.scope, AndroidArtifacts.ConsumedConfigType.COMPILE_CLASSPATH, null)
}

compileArtifacts.each { artifact ->
// artifact 在 3.3 以上是 com.android.build.gradle.internal.ide.dependencies.ResolvedArtifact
// artifact 在 3.3 以下是 org.gradle.api.artifacts.result.ResolvedArtifactResult
ComponentIdentifier id = ResolvedArtifactCompat.getComponentIdentifier(artifact)
compileArtifacts.each { ArtifactDependencyGraph.HashableResolvedArtifactResult artifact ->
ComponentIdentifier id = artifact.id.componentIdentifier
if (id instanceof ProjectComponentIdentifier) {
deps.add("${id.projectPath.replace(':', '')}" +
":${ResolvedArtifactCompat.getVariantName(artifact)}" +
":unspecified ${getArtifactFileLength(artifact)}")
deps.add("${id.projectPath.replace(':', '')}:${ArtifactDependencyGraph.getVariant(artifact)}:unspecified ${artifact.file.length()}")

} else if (id instanceof ModuleComponentIdentifier) {
deps.add("${id.group}:${id.module}:${id.version} ${getArtifactFileLength(artifact)}")
deps.add("${id.group}:${id.module}:${id.version} ${artifact.file.length()}")

} else {
// deps.add("${id.displayName.replace(':', '')}:unspecified:unspecified ${getArtifactFileLength(artifact)}")
deps.add("${artifact.id.displayName.replace(':', '')}:unspecified:unspecified ${artifact.file.length()}")
}
}

Expand All @@ -114,10 +123,6 @@ public class VAHostPlugin implements Plugin<Project> {

}

private long getArtifactFileLength(artifact){
return ResolvedArtifactCompat.getFile(artifact).length()
}

/**
* Save R symbol file
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import com.android.build.gradle.internal.api.ApplicationVariantImpl
import com.android.build.gradle.options.BooleanOption
import com.android.build.gradle.options.ProjectOptions
import com.didi.virtualapk.hooker.*
import com.didi.virtualapk.os.Build
import com.didi.virtualapk.transform.StripClassAndResTransform
import com.didi.virtualapk.utils.FileBinaryCategory
import com.didi.virtualapk.utils.Log
Expand Down Expand Up @@ -228,11 +227,8 @@ class VAPlugin extends BasePlugin {

AppPlugin appPlugin = project.plugins.findPlugin(AppPlugin)
ProjectOptions projectOptions = Reflect.on(appPlugin).field('projectOptions').get()
// 330 此处已经无效了,永远为 true
if (!Build.isSupportVersion(Build.VERSION_CODE.V3_3_X)){
if (projectOptions.get(BooleanOption.ENABLE_DEX_ARCHIVE)) {
throw new InvalidUserDataException("Can't using incremental dexing mode, please add 'android.useDexArchive=false' in gradle.properties of :${project.name}.")
}
if (projectOptions.get(BooleanOption.ENABLE_DEX_ARCHIVE)) {
throw new InvalidUserDataException("Can't using incremental dexing mode, please add 'android.useDexArchive=false' in gradle.properties of :${project.name}.")
}
// project.ext.set('android.useDexArchive', false)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import com.android.builder.model.AndroidLibrary
import com.android.utils.FileUtils
import com.didi.virtualapk.collector.res.ResourceEntry
import com.didi.virtualapk.collector.res.StyleableEntry
import com.didi.virtualapk.os.Build
import com.didi.virtualapk.utils.Log
import com.google.common.collect.ArrayListMultimap
import com.google.common.collect.ListMultimap
Expand Down Expand Up @@ -99,24 +98,12 @@ class AarDependenceInfo extends DependenceInfo {
* @return package name of this library
*/
public String getPackage() {
File manifest = getLibManifestFile()
File manifest = getFile(library.manifest, 'manifests', 'full', library.projectVariant, SdkConstants.ANDROID_MANIFEST_XML)
Log.i 'AarDependenceInfo', "Found [${library.resolvedCoordinates}]'s manifest file: ${manifest}"
def xmlManifest = new XmlParser().parse(manifest)
return xmlManifest.@package
}

File getLibManifestFile() {
if (Build.V3_3_OR_LATER) {
return getFile(library.manifest, 'library_manifest', library.projectVariant, SdkConstants.ANDROID_MANIFEST_XML)
} else if (Build.V3_2_OR_LATER) {
return getFile(library.manifest, 'merged_manifests',library.projectVariant,
"process${library.projectVariant.capitalize()}Manifest","merged",
SdkConstants.ANDROID_MANIFEST_XML)
} else {
return getFile(library.manifest, 'manifests', 'full', library.projectVariant, SdkConstants.ANDROID_MANIFEST_XML)
}
}

File getIntermediatesDir() {
if (intermediatesFile == null) {
String path = library.folder.path
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.didi.virtualapk.hooker

import com.android.build.gradle.api.ApkVariant
import com.android.build.gradle.tasks.ManifestProcessorTask
import com.android.build.gradle.tasks.MergeManifests
import com.didi.virtualapk.os.Build
import com.didi.virtualapk.collector.dependence.DependenceInfo
import com.didi.virtualapk.support.ScopeCompat
Expand All @@ -24,7 +24,7 @@ import java.util.function.Predicate
*
* @author zhengtao
*/
class MergeManifestsHooker extends GradleTaskHooker<ManifestProcessorTask> {
class MergeManifestsHooker extends GradleTaskHooker<MergeManifests> {

public static final String ANDROID_NAMESPACE = 'http://schemas.android.com/apk/res/android'

Expand All @@ -38,9 +38,9 @@ class MergeManifestsHooker extends GradleTaskHooker<ManifestProcessorTask> {
}

@Override
void beforeTaskExecute(ManifestProcessorTask task) {
void beforeTaskExecute(MergeManifests task) {

Set<String> stripAarNames = vaContext.stripDependencies.
def stripAarNames = vaContext.stripDependencies.
findAll {
it.dependenceType == DependenceInfo.DependenceType.AAR
}.
Expand All @@ -57,9 +57,9 @@ class MergeManifestsHooker extends GradleTaskHooker<ManifestProcessorTask> {
* Filter specific attributes from <application /> element after MergeManifests task executed
*/
@Override
void afterTaskExecute(ManifestProcessorTask task) {
void afterTaskExecute(MergeManifests task) {
def MERGED_MANIFESTS = ScopeCompat.getArtifact(project, "MERGED_MANIFESTS")
if (Build.V3_1_OR_LATER) {
if (Build.isSupportVersion(project,Build.VERSION_CODE.V3_1_X)) {
File outputFile = (Reflect.on('com.android.build.gradle.internal.scope.ExistingBuildElements')
.call('from', MERGED_MANIFESTS, ScopeCompat.getArtifactFile(scope, project, MERGED_MANIFESTS))
.call('element', variantData.outputScope.mainSplit))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
package com.didi.virtualapk.hooker

import com.android.build.gradle.api.ApkVariant
import com.android.build.gradle.internal.ide.ArtifactDependencyGraph
import com.android.build.gradle.internal.tasks.AppPreBuildTask
import com.android.builder.model.Dependencies
import com.android.builder.model.SyncIssue
import com.didi.virtualapk.os.Build
import com.didi.virtualapk.collector.dependence.AarDependenceInfo
import com.didi.virtualapk.collector.dependence.DependenceInfo
import com.didi.virtualapk.collector.dependence.JarDependenceInfo
import com.didi.virtualapk.support.ArtifactDependencyGraphCompat
import com.didi.virtualapk.utils.FileUtil
import com.didi.virtualapk.utils.Log
import com.didi.virtualapk.utils.Reflect
import com.google.common.collect.ImmutableMap
import org.gradle.api.Project

import java.util.function.Consumer

/**
* Gather list of dependencies(aar&jar) need to be stripped&retained after the PrepareDependenciesTask finished.
* The entire stripped operation throughout the build lifecycle is based on the result of this hooker。
Expand Down Expand Up @@ -57,8 +63,21 @@ class PrepareDependenciesHooker extends GradleTaskHooker<AppPreBuildTask> {
*/
@Override
void afterTaskExecute(AppPreBuildTask task) {

Dependencies dependencies = ArtifactDependencyGraphCompat.createDependencies(project,scope)
Consumer consumer = new Consumer<SyncIssue>() {
@Override
void accept(SyncIssue syncIssue) {
Log.i 'PrepareDependenciesHooker', "Error: ${syncIssue}"
}
}
Dependencies dependencies
if (Build.isSupportVersion(project, Build.VERSION_CODE.V3_1_X)) {
ImmutableMap<String, String> buildMapping = Reflect.on('com.android.build.gradle.internal.ide.ModelBuilder')
.call('computeBuildMapping', project.gradle)
.get()
dependencies = new ArtifactDependencyGraph().createDependencies(scope, false, buildMapping, consumer)
} else {
dependencies = new ArtifactDependencyGraph().createDependencies(scope, false, consumer)
}

dependencies.libraries.each {
def mavenCoordinates = it.resolvedCoordinates
Expand Down Expand Up @@ -118,7 +137,6 @@ class PrepareDependenciesHooker extends GradleTaskHooker<AppPreBuildTask> {
mark()
}


void checkDependencies() {
ArrayList<DependenceInfo> allRetainedDependencies = new ArrayList<>()
allRetainedDependencies.addAll(retainedAarLibs)
Expand Down
Loading

0 comments on commit 73bd871

Please sign in to comment.