Search in sources :

Example 1 with AndroidLibrary

use of com.android.builder.model.AndroidLibrary in project atlas by alibaba.

the class TDependencyManager method resolveDependencyForApplicationConfig.

private void resolveDependencyForApplicationConfig(@NonNull final VariantDependencies variantDeps, @Nullable VariantDependencies testedVariantDeps, @Nullable String testedProjectPath, @NonNull Multimap<AndroidLibrary, Configuration> reverseLibMap) {
    boolean needPackageScope = true;
    if (AndroidGradleOptions.buildModelOnly(project)) {
        // if we're only syncing (building the model), then we only need the package
        // scope if we will actually pass it to the IDE.
        Integer modelLevelInt = AndroidGradleOptions.buildModelOnlyVersion(project);
        int modelLevel = AndroidProject.MODEL_LEVEL_0_ORIGNAL;
        if (modelLevelInt != null) {
            modelLevel = modelLevelInt;
        }
        needPackageScope = modelLevel >= AndroidProject.MODEL_LEVEL_2_DEP_GRAPH;
    }
    Configuration compileClasspath = variantDeps.getCompileConfiguration();
    Configuration packageClasspath = variantDeps.getPackageConfiguration();
    if (DEBUG_DEPENDENCY) {
        System.out.println(">>>>>>>>>>");
        System.out.println(project.getName() + ":" + compileClasspath.getName() + "/" + packageClasspath.getName());
    }
    Set<String> resolvedModules = Sets.newHashSet();
    Map<ModuleVersionIdentifier, List<ResolvedArtifact>> artifacts = Maps.newHashMap();
    collectArtifacts(compileClasspath, artifacts);
    collectArtifacts(packageClasspath, artifacts);
    // 不使用官方的扁平化的依赖处理,改用自己处理树状的依赖关系;对于application的依赖,我们只取compile的依赖
    ResolvedDependencyContainer compileResolvedDependencyContainer = new ResolvedDependencyContainer(project);
    Set<ModuleVersionIdentifier> directDependencies = new HashSet<ModuleVersionIdentifier>();
    Set<? extends DependencyResult> projectDependencies = compileClasspath.getIncoming().getResolutionResult().getRoot().getDependencies();
    for (DependencyResult dependencyResult : projectDependencies) {
        if (dependencyResult instanceof ResolvedDependencyResult) {
            ModuleVersionIdentifier moduleVersion = ((ResolvedDependencyResult) dependencyResult).getSelected().getModuleVersion();
            CircleDependencyCheck circleDependencyCheck = new CircleDependencyCheck(moduleVersion);
            if (!directDependencies.contains(moduleVersion)) {
                directDependencies.add(moduleVersion);
                resolveDependency(compileResolvedDependencyContainer, null, ((ResolvedDependencyResult) dependencyResult).getSelected(), artifacts, variantDeps, 0, circleDependencyCheck, circleDependencyCheck.getRootDependencyNode(), resolvedModules);
            }
        }
    }
    AndroidDependencyTree androidDependencyTree = compileResolvedDependencyContainer.reslovedDependencies().toAndroidDependency();
    AtlasBuildContext.androidDependencyTrees.put(variantDeps.getName(), androidDependencyTree);
    //output tree file only once
    if (project.getLogger().isInfoEnabled()) {
        project.getLogger().info("[dependencyTree" + variantDeps.getName() + "]" + JSON.toJSONString(androidDependencyTree.getDependencyJson(), true));
    }
    // 设置reverseMap
    for (AndroidLibrary libInfo : androidDependencyTree.getAarBundles()) {
        reverseLibMap.put(libInfo, variantDeps.getCompileConfiguration());
    }
    Set<String> currentUnresolvedDependencies = Sets.newHashSet();
    // records the artifact we find during package, to detect provided only dependencies.
    Set<String> artifactSet = Sets.newHashSet();
    // start with package dependencies, record the artifacts
    DependencyContainer packagedDependencies;
    if (needPackageScope) {
        packagedDependencies = gatherDependencies(packageClasspath, variantDeps, reverseLibMap, currentUnresolvedDependencies, testedProjectPath, artifactSet, ScopeType.PACKAGE);
    } else {
        packagedDependencies = DependencyContainerImpl.getEmpty();
    }
    // then the compile dependencies, comparing against the record package dependencies
    // to set the provided flag.
    // if we have not compute the package scope, we disable the computation of
    // provided bits. This disables the checks on impossible provided libs (provided aar in
    // apk project).
    ScopeType scopeType = needPackageScope ? ScopeType.COMPILE : ScopeType.COMPILE_ONLY;
    DependencyContainer compileDependencies = gatherDependencies(compileClasspath, variantDeps, reverseLibMap, currentUnresolvedDependencies, testedProjectPath, artifactSet, scopeType);
    if (extraModelInfo.getMode() != STANDARD && compileClasspath.getResolvedConfiguration().hasError()) {
        for (String dependency : currentUnresolvedDependencies) {
            extraModelInfo.handleSyncError(dependency, SyncIssue.TYPE_UNRESOLVED_DEPENDENCY, String.format("Unable to resolve dependency '%s'", dependency));
        }
    }
    // validate the dependencies.
    if (needPackageScope) {
        variantDeps.getChecker().validate(compileDependencies, packagedDependencies, testedVariantDeps);
    }
    if (DEBUG_DEPENDENCY) {
        System.out.println("*** COMPILE DEPS ***");
        for (AndroidLibrary lib : compileDependencies.getAndroidDependencies()) {
            System.out.println("LIB: " + lib);
        }
        for (JavaLibrary jar : compileDependencies.getJarDependencies()) {
            System.out.println("JAR: " + jar);
        }
        for (JavaLibrary jar : compileDependencies.getLocalDependencies()) {
            System.out.println("LOCAL-JAR: " + jar);
        }
        System.out.println("*** PACKAGE DEPS ***");
        for (AndroidLibrary lib : packagedDependencies.getAndroidDependencies()) {
            System.out.println("LIB: " + lib);
        }
        for (JavaLibrary jar : packagedDependencies.getJarDependencies()) {
            System.out.println("JAR: " + jar);
        }
        for (JavaLibrary jar : packagedDependencies.getLocalDependencies()) {
            System.out.println("LOCAL-JAR: " + jar);
        }
        System.out.println("***");
    }
    variantDeps.setDependencies(compileDependencies, packagedDependencies);
    configureBuild(variantDeps);
    if (DEBUG_DEPENDENCY) {
        System.out.println(project.getName() + ":" + compileClasspath.getName() + "/" + packageClasspath.getName());
        System.out.println("<<<<<<<<<<");
    }
}
Also used : Configuration(org.gradle.api.artifacts.Configuration) DependencyResult(org.gradle.api.artifacts.result.DependencyResult) UnresolvedDependencyResult(org.gradle.api.artifacts.result.UnresolvedDependencyResult) ResolvedDependencyResult(org.gradle.api.artifacts.result.ResolvedDependencyResult) AndroidDependencyTree(com.taobao.android.builder.dependency.AndroidDependencyTree) ResolvedDependencyContainer(com.taobao.android.builder.dependency.ResolvedDependencyContainer) DependencyContainer(com.android.builder.dependency.DependencyContainer) ModuleVersionIdentifier(org.gradle.api.artifacts.ModuleVersionIdentifier) ResolvedDependencyContainer(com.taobao.android.builder.dependency.ResolvedDependencyContainer) JavaLibrary(com.android.builder.model.JavaLibrary) AndroidLibrary(com.android.builder.model.AndroidLibrary) CircleDependencyCheck(com.taobao.android.builder.dependency.CircleDependencyCheck) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) ResolvedDependencyResult(org.gradle.api.artifacts.result.ResolvedDependencyResult) HashSet(java.util.HashSet)

Example 2 with AndroidLibrary

use of com.android.builder.model.AndroidLibrary in project atlas by alibaba.

the class TDependencyManager method addDependency.

private void addDependency(@NonNull ResolvedComponentResult resolvedComponentResult, @NonNull VariantDependencies configDependencies, @NonNull Configuration configuration, @NonNull Collection<LibraryDependency> outLibraries, @NonNull List<JarDependency> outJars, @NonNull Map<ModuleVersionIdentifier, List<LibraryDependency>> alreadyFoundLibraries, @NonNull Map<ModuleVersionIdentifier, List<JarDependency>> alreadyFoundJars, @NonNull Map<ModuleVersionIdentifier, List<ResolvedArtifact>> artifacts, @NonNull Multimap<AndroidLibrary, Configuration> reverseLibMap, @NonNull Set<String> currentUnresolvedDependencies, @Nullable String testedProjectPath, @NonNull List<String> projectChain, @NonNull Set<String> artifactSet, @NonNull ScopeType scopeType, boolean forceProvided, int indent) {
    ModuleVersionIdentifier moduleVersion = resolvedComponentResult.getModuleVersion();
    if (configDependencies.getChecker().checkForExclusion(moduleVersion)) {
        return;
    }
    if (moduleVersion.getName().equals("support-annotations") && moduleVersion.getGroup().equals("com.android.support")) {
        configDependencies.setAnnotationsPresent(true);
    }
    List<LibraryDependency> libsForThisModule = alreadyFoundLibraries.get(moduleVersion);
    List<JarDependency> jarsForThisModule = alreadyFoundJars.get(moduleVersion);
    if (libsForThisModule != null) {
        if (DEBUG_DEPENDENCY) {
            printIndent(indent, "FOUND LIB: " + moduleVersion.getName());
        }
        outLibraries.addAll(libsForThisModule);
        for (AndroidLibrary lib : libsForThisModule) {
            reverseLibMap.put(lib, configuration);
        }
    } else if (jarsForThisModule != null) {
        if (DEBUG_DEPENDENCY) {
            printIndent(indent, "FOUND JAR: " + moduleVersion.getName());
        }
        outJars.addAll(jarsForThisModule);
    } else {
        if (DEBUG_DEPENDENCY) {
            printIndent(indent, "NOT FOUND: " + moduleVersion.getName());
        }
        // new module! Might be a jar or a library
        // get the associated gradlepath
        ComponentIdentifier id = resolvedComponentResult.getId();
        String gradlePath = (id instanceof ProjectComponentIdentifier) ? ((ProjectComponentIdentifier) id).getProjectPath() : null;
        // check if this is a tested app project (via a separate test module).
        // In which case, all the dependencies must become provided.
        boolean childForceProvided = forceProvided;
        if (scopeType == ScopeType.COMPILE && testedProjectPath != null && testedProjectPath.equals(gradlePath)) {
            childForceProvided = true;
        }
        // get the nested components first.
        List<LibraryDependency> nestedLibraries = Lists.newArrayList();
        List<JarDependency> nestedJars = Lists.newArrayList();
        Set<? extends DependencyResult> dependencies = resolvedComponentResult.getDependencies();
        for (DependencyResult dependencyResult : dependencies) {
            if (dependencyResult instanceof ResolvedDependencyResult) {
                ResolvedComponentResult selected = ((ResolvedDependencyResult) dependencyResult).getSelected();
                List<String> newProjectChain = projectChain;
                ComponentIdentifier identifier = selected.getId();
                if (identifier instanceof ProjectComponentIdentifier) {
                    String projectPath = ((ProjectComponentIdentifier) identifier).getProjectPath();
                    int index = projectChain.indexOf(projectPath);
                    if (index != -1) {
                        projectChain.add(projectPath);
                        String path = Joiner.on(" -> ").join(projectChain.subList(index, projectChain.size()));
                        throw new CircularReferenceException("Circular reference between projects: " + path);
                    }
                    newProjectChain = Lists.newArrayList();
                    newProjectChain.addAll(projectChain);
                    newProjectChain.add(projectPath);
                }
                addDependency(selected, configDependencies, configuration, nestedLibraries, nestedJars, alreadyFoundLibraries, alreadyFoundJars, artifacts, reverseLibMap, currentUnresolvedDependencies, testedProjectPath, newProjectChain, artifactSet, scopeType, childForceProvided, indent + 1);
            } else if (dependencyResult instanceof UnresolvedDependencyResult) {
                ComponentSelector attempted = ((UnresolvedDependencyResult) dependencyResult).getAttempted();
                if (attempted != null) {
                    currentUnresolvedDependencies.add(attempted.toString());
                }
            }
        }
        if (DEBUG_DEPENDENCY) {
            printIndent(indent, "BACK2: " + moduleVersion.getName());
            printIndent(indent, "NESTED LIBS: " + nestedLibraries.size());
            printIndent(indent, "NESTED JARS: " + nestedJars.size());
        }
        // now loop on all the artifact for this modules.
        List<ResolvedArtifact> moduleArtifacts = artifacts.get(moduleVersion);
        if (moduleArtifacts != null) {
            for (ResolvedArtifact artifact : moduleArtifacts) {
                MavenCoordinates mavenCoordinates = createMavenCoordinates(artifact);
                boolean provided = forceProvided;
                String coordKey = computeVersionLessCoordinateKey(mavenCoordinates);
                if (scopeType == ScopeType.PACKAGE) {
                    artifactSet.add(coordKey);
                } else if (scopeType == ScopeType.COMPILE) {
                    provided |= !artifactSet.contains(coordKey);
                }
                if (EXT_LIB_ARCHIVE.equals(artifact.getExtension())) {
                    if (DEBUG_DEPENDENCY) {
                        printIndent(indent, "TYPE: AAR");
                    }
                    if (libsForThisModule == null) {
                        libsForThisModule = Lists.newArrayList();
                        alreadyFoundLibraries.put(moduleVersion, libsForThisModule);
                    }
                    String path = computeArtifactPath(moduleVersion, artifact);
                    String name = computeArtifactName(moduleVersion, artifact);
                    if (DEBUG_DEPENDENCY) {
                        printIndent(indent, "NAME: " + name);
                        printIndent(indent, "PATH: " + path);
                    }
                    File explodedDir = project.file(project.getBuildDir() + "/" + FD_INTERMEDIATES + "/exploded-aar/" + path);
                    @SuppressWarnings("unchecked") LibraryDependency LibraryDependency = new LibraryDependency(artifact.getFile(), explodedDir, nestedLibraries, nestedJars, name, artifact.getClassifier(), gradlePath, null, /*requestedCoordinates*/
                    mavenCoordinates, provided);
                    libsForThisModule.add(LibraryDependency);
                    outLibraries.add(LibraryDependency);
                    reverseLibMap.put(LibraryDependency, configuration);
                } else if (EXT_JAR.equals(artifact.getExtension())) {
                    if (DEBUG_DEPENDENCY) {
                        printIndent(indent, "TYPE: JAR");
                    }
                    nestedLibraries.clear();
                    // check this jar does not have a dependency on an library, as this would not work.
                    if (!nestedLibraries.isEmpty()) {
                        // can detect this an accept it.
                        if (testedProjectPath != null && testedProjectPath.equals(gradlePath)) {
                            // if this is a package scope, then skip the dependencies.
                            if (scopeType == ScopeType.PACKAGE) {
                                recursiveLibSkip(nestedLibraries);
                            } else {
                                // if it's compile scope, make it optional.
                                provided = true;
                            }
                            outLibraries.addAll(nestedLibraries);
                        } else {
                            configDependencies.getChecker().handleIssue(createMavenCoordinates(artifact).toString(), SyncIssue.TYPE_JAR_DEPEND_ON_AAR, SyncIssue.SEVERITY_ERROR, String.format("Module '%s' depends on one or more Android Libraries but is a jar", moduleVersion));
                        }
                    }
                    if (jarsForThisModule == null) {
                        jarsForThisModule = Lists.newArrayList();
                        alreadyFoundJars.put(moduleVersion, jarsForThisModule);
                    }
                    JarDependency jarDependency = new JarDependency(artifact.getFile(), nestedJars, mavenCoordinates, gradlePath, provided);
                    // app module then skip it.
                    if (scopeType == ScopeType.PACKAGE && testedProjectPath != null && testedProjectPath.equals(gradlePath)) {
                        jarDependency.skip();
                        //noinspection unchecked
                        recursiveJavaSkip((List<JarDependency>) jarDependency.getDependencies());
                    }
                    if (DEBUG_DEPENDENCY) {
                        printIndent(indent, "JAR-INFO: " + jarDependency.toString());
                    }
                    jarsForThisModule.add(jarDependency);
                    outJars.add(jarDependency);
                } else if (EXT_ANDROID_PACKAGE.equals(artifact.getExtension())) {
                    String name = computeArtifactName(moduleVersion, artifact);
                    configDependencies.getChecker().handleIssue(name, SyncIssue.TYPE_DEPENDENCY_IS_APK, SyncIssue.SEVERITY_ERROR, String.format("Dependency %s on project %s resolves to an APK archive " + "which is not supported as a compilation dependency. File: %s", name, project.getName(), artifact.getFile()));
                } else if ("apklib".equals(artifact.getExtension())) {
                    String name = computeArtifactName(moduleVersion, artifact);
                    configDependencies.getChecker().handleIssue(name, SyncIssue.TYPE_DEPENDENCY_IS_APKLIB, SyncIssue.SEVERITY_ERROR, String.format("Packaging for dependency %s is 'apklib' and is not supported. " + "Only 'aar' libraries are supported.", name));
                } else if ("awb".equals(artifact.getExtension())) {
                    break;
                } else if ("solib".equals(artifact.getExtension())) {
                    break;
                } else {
                    String name = computeArtifactName(moduleVersion, artifact);
                    logger.warning(String.format("Unrecognized dependency: '%s' (type: '%s', extension: '%s')", name, artifact.getType(), artifact.getExtension()));
                }
            }
        }
        if (DEBUG_DEPENDENCY) {
            printIndent(indent, "DONE: " + moduleVersion.getName());
        }
    }
}
Also used : UnresolvedDependencyResult(org.gradle.api.artifacts.result.UnresolvedDependencyResult) JarDependency(com.android.builder.dependency.JarDependency) ResolvedArtifact(org.gradle.api.artifacts.ResolvedArtifact) Set(java.util.Set) HashSet(java.util.HashSet) ComponentSelector(org.gradle.api.artifacts.component.ComponentSelector) DependencyResult(org.gradle.api.artifacts.result.DependencyResult) UnresolvedDependencyResult(org.gradle.api.artifacts.result.UnresolvedDependencyResult) ResolvedDependencyResult(org.gradle.api.artifacts.result.ResolvedDependencyResult) ProjectComponentIdentifier(org.gradle.api.artifacts.component.ProjectComponentIdentifier) ComponentIdentifier(org.gradle.api.artifacts.component.ComponentIdentifier) CircularReferenceException(org.gradle.api.CircularReferenceException) ModuleVersionIdentifier(org.gradle.api.artifacts.ModuleVersionIdentifier) MavenCoordinates(com.android.builder.model.MavenCoordinates) AndroidLibrary(com.android.builder.model.AndroidLibrary) LibraryDependency(com.android.builder.dependency.LibraryDependency) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) ResolvedComponentResult(org.gradle.api.artifacts.result.ResolvedComponentResult) ProjectComponentIdentifier(org.gradle.api.artifacts.component.ProjectComponentIdentifier) ResolvedDependencyResult(org.gradle.api.artifacts.result.ResolvedDependencyResult) File(java.io.File)

Example 3 with AndroidLibrary

use of com.android.builder.model.AndroidLibrary in project atlas by alibaba.

the class AtlasBuilder method processResources.

/**
     * 对主bundle的资源进行处理
     *
     * @param aaptCommand
     * @param enforceUniquePackageName
     * @param processOutputHandler
     * @throws IOException
     * @throws InterruptedException
     * @throws ProcessException
     */
public void processResources(AaptPackageProcessBuilder aaptCommand, boolean enforceUniquePackageName, ProcessOutputHandler processOutputHandler) throws IOException, InterruptedException, ProcessException {
    checkState(getTargetInfo() != null, "Cannot call processResources() before setTargetInfo() is called.");
    BuildToolInfo buildToolInfo = getTargetInfo().getBuildTools();
    // launch aapt: create the command line
    ProcessInfo processInfo = aaptCommand.build(buildToolInfo, getTargetInfo().getTarget(), getLogger());
    processInfo = new TProcessInfo(processInfo);
    // 打印日志
    //        if (null != getLogger()) {
    //            getLogger().info("[Aapt]" + processInfo.getExecutable() + " "
    //                    + StringUtils.join(processInfo.getArgs(), " "));
    //        }
    ProcessResult result = getProcessExecutor().execute(processInfo, processOutputHandler);
    result.rethrowFailure().assertNormalExitValue();
    // If the project has libraries, R needs to be created for each library.
    if (aaptCommand.getSourceOutputDir() != null && !aaptCommand.getLibraries().isEmpty()) {
        SymbolLoader fullSymbolValues = null;
        // First pass processing the libraries, collecting them by packageName,
        // and ignoring the ones that have the same package name as the application
        // (since that R class was already created).
        String appPackageName = aaptCommand.getPackageForR();
        if (appPackageName == null) {
            appPackageName = ManifestFileUtils.getPackage(aaptCommand.getManifestFile());
        }
        // list of all the symbol loaders per package names.
        Multimap<String, SymbolLoader> libMap = ArrayListMultimap.create();
        for (AndroidLibrary lib : aaptCommand.getLibraries()) {
            if (lib.isOptional()) {
                continue;
            }
            String packageName = ManifestFileUtils.getPackage(lib.getManifest());
            if (appPackageName == null) {
                continue;
            }
            if (appPackageName.equals(packageName)) {
                if (enforceUniquePackageName) {
                    String msg = String.format("Error: A library uses the same package as this project: %s", packageName);
                    throw new RuntimeException(msg);
                }
                // ignore libraries that have the same package name as the app
                continue;
            }
            File rFile = lib.getSymbolFile();
            // if the library has no resource, this file won't exist.
            if (rFile.isFile()) {
                // resources anywhere.
                if (fullSymbolValues == null) {
                    fullSymbolValues = new SymbolLoader(new File(aaptCommand.getSymbolOutputDir(), "R.txt"), getLogger());
                    fullSymbolValues.load();
                }
                SymbolLoader libSymbols = new SymbolLoader(rFile, getLogger());
                libSymbols.load();
                // store these symbols by associating them with the package name.
                libMap.put(packageName, libSymbols);
            }
        }
        // now loop on all the package name, merge all the symbols to write, and write them
        for (String packageName : libMap.keySet()) {
            Collection<SymbolLoader> symbols = libMap.get(packageName);
            if (enforceUniquePackageName && symbols.size() > 1) {
                String msg = String.format("Error: more than one library with package name '%s'", packageName);
                throw new RuntimeException(msg);
            }
            SymbolWriter writer = new SymbolWriter(aaptCommand.getSourceOutputDir(), packageName, fullSymbolValues, false);
            for (SymbolLoader symbolLoader : symbols) {
                writer.addSymbolsToWrite(symbolLoader);
            }
            writer.write();
        }
    }
}
Also used : SymbolWriter(com.android.builder.internal.SymbolWriter) BuildToolInfo(com.android.sdklib.BuildToolInfo) AndroidLibrary(com.android.builder.model.AndroidLibrary) ProcessResult(com.android.ide.common.process.ProcessResult) ProcessInfo(com.android.ide.common.process.ProcessInfo) SymbolLoader(com.android.builder.internal.SymbolLoader) File(java.io.File)

Example 4 with AndroidLibrary

use of com.android.builder.model.AndroidLibrary in project atlas by alibaba.

the class AtlasBuilder method processAwbSymbols.

/**
     * 处理Awb的资源文件
     *
     * @param aaptCommand
     * @throws IOException
     */
public void processAwbSymbols(AaptPackageProcessBuilder aaptCommand, File mainSymbolFile, boolean enforceUniquePackageName) throws IOException {
    //1. 首先将主的R.txt和awb生成的R.txt进行merge操作
    File awbSymbolFile = new File(aaptCommand.getSymbolOutputDir(), "R.txt");
    File mergedSymbolFile = new File(aaptCommand.getSymbolOutputDir(), "R-all.txt");
    //合并2个R.txt文件
    try {
        getLogger().info("mainSymbolFile:" + mainSymbolFile);
        if (null != mainSymbolFile && mainSymbolFile.exists()) {
            FileUtils.copyFile(mainSymbolFile, mergedSymbolFile);
        }
        FileUtils.writeLines(mergedSymbolFile, FileUtils.readLines(awbSymbolFile), true);
    } catch (IOException e) {
        throw new RuntimeException("Could not load file ", e);
    }
    //生成awb的java文件
    SymbolLoader awbSymbols = null;
    // First pass processing the libraries, collecting them by packageName,
    // and ignoring the ones that have the same package name as the application
    // (since that R class was already created).
    String appPackageName = aaptCommand.getPackageForR();
    if (appPackageName == null) {
        appPackageName = ManifestFileUtils.getPackage(aaptCommand.getManifestFile());
    }
    awbSymbols = new SymbolLoader(mergedSymbolFile, getLogger());
    awbSymbols.load();
    SymbolWriter writer = new SymbolWriter(aaptCommand.getSourceOutputDir(), appPackageName, awbSymbols, false);
    writer.addSymbolsToWrite(awbSymbols);
    getLogger().info("SymbolWriter Package:" + appPackageName + " to dir:" + aaptCommand.getSourceOutputDir());
    writer.write();
    //再写入各自awb依赖的aar的资源
    if (!aaptCommand.getLibraries().isEmpty()) {
        // list of all the symbol loaders per package names.
        Multimap<String, SymbolLoader> libMap = ArrayListMultimap.create();
        for (AndroidLibrary lib : aaptCommand.getLibraries()) {
            if (lib.isOptional()) {
                continue;
            }
            String packageName = ManifestFileUtils.getPackage(lib.getManifest());
            if (appPackageName == null) {
                continue;
            }
            if (appPackageName.equals(packageName)) {
                if (enforceUniquePackageName) {
                    String msg = String.format("Error: A library uses the same package as this project: %s\n" + "You can temporarily disable this error with android.enforceUniquePackageName=false\n" + "However, this is temporary and will be enforced in 1.0", packageName);
                    throw new RuntimeException(msg);
                }
                // ignore libraries that have the same package name as the app
                continue;
            }
            File rFile = lib.getSymbolFile();
            // if the library has no resource, this file won't exist.
            if (rFile.isFile()) {
                SymbolLoader libSymbols = new SymbolLoader(rFile, getLogger());
                libSymbols.load();
                // store these symbols by associating them with the package name.
                libMap.put(packageName, libSymbols);
            }
        }
        // now loop on all the package name, merge all the symbols to write, and write them
        for (String packageName : libMap.keySet()) {
            Collection<SymbolLoader> symbols = libMap.get(packageName);
            if (enforceUniquePackageName && symbols.size() > 1) {
                String msg = String.format("Error: more than one library with package name '%s'\n" + "You can temporarily disable this error with android.enforceUniquePackageName=false\n" + "However, this is temporary and will be enforced in 1.0", packageName);
                throw new RuntimeException(msg);
            }
            SymbolWriter libWriter = new SymbolWriter(aaptCommand.getSourceOutputDir(), packageName, awbSymbols, false);
            for (SymbolLoader symbolLoader : symbols) {
                libWriter.addSymbolsToWrite(symbolLoader);
            }
            getLogger().info("SymbolWriter Package:" + packageName + " to dir:" + aaptCommand.getSourceOutputDir());
            libWriter.write();
        }
    }
}
Also used : SymbolWriter(com.android.builder.internal.SymbolWriter) AndroidLibrary(com.android.builder.model.AndroidLibrary) IOException(java.io.IOException) File(java.io.File) SymbolLoader(com.android.builder.internal.SymbolLoader)

Example 5 with AndroidLibrary

use of com.android.builder.model.AndroidLibrary in project atlas by alibaba.

the class CopyAwoSolibTask method doFullTaskAction.

@TaskAction
public void doFullTaskAction() {
    if (!outputDir.exists()) {
        outputDir.mkdirs();
    }
    Set<String> removeSoFiles = new HashSet<String>();
    Set<String> supportAbis = new HashSet<String>();
    //为了兼容之前老的aar,awb格式
    File libJniFolder = new File(awbBundle.getFolder(), "libs");
    if (libJniFolder.exists() && libJniFolder.isDirectory()) {
        NativeSoUtils.copyLocalNativeLibraries(libJniFolder, outputDir, supportAbis, removeSoFiles, getILogger());
    }
    File libJniFolder2 = new File(awbBundle.getFolder(), "jni");
    if (libJniFolder2.exists() && libJniFolder2.isDirectory()) {
        NativeSoUtils.copyLocalNativeLibraries(libJniFolder2, outputDir, supportAbis, removeSoFiles, getILogger());
    }
    File libJniFolder3 = new File(awbBundle.getFolder(), "jniLibs");
    if (libJniFolder3.exists() && libJniFolder3.isDirectory()) {
        NativeSoUtils.copyLocalNativeLibraries(libJniFolder3, outputDir, supportAbis, removeSoFiles, getILogger());
    }
    List<? extends AndroidLibrary> deps = awbBundle.getLibraryDependencies();
    for (AndroidLibrary dep : deps) {
        File depJniFolder = dep.getJniFolder();
        if (depJniFolder.exists() && depJniFolder.isDirectory()) {
            NativeSoUtils.copyLocalNativeLibraries(depJniFolder, outputDir, supportAbis, removeSoFiles, getILogger());
        }
        //为了兼容之前老的aar,awb格式
        File depLibsFolder = new File(dep.getFolder(), "libs");
        if (depLibsFolder.exists() && depLibsFolder.isDirectory()) {
            NativeSoUtils.copyLocalNativeLibraries(depLibsFolder, outputDir, supportAbis, removeSoFiles, getILogger());
        }
    }
    List<SoLibrary> solibs = awbBundle.getSoLibraries();
    if (null != solibs) {
        for (SoLibrary solib : solibs) {
            File explodeFolder = solib.getFolder();
            if (!explodeFolder.exists()) {
                LibraryCache.unzipAar(solib.getSoLibFile(), explodeFolder, getProject());
            }
            if (explodeFolder.exists() && explodeFolder.isDirectory()) {
                NativeSoUtils.copyLocalNativeLibraries(explodeFolder, outputDir, supportAbis, removeSoFiles, getILogger());
            }
        }
    }
}
Also used : AndroidLibrary(com.android.builder.model.AndroidLibrary) SoLibrary(com.taobao.android.builder.dependency.model.SoLibrary) File(java.io.File) HashSet(java.util.HashSet) MtlBaseTaskAction(com.taobao.android.builder.tasks.manager.MtlBaseTaskAction) TaskAction(org.gradle.api.tasks.TaskAction)

Aggregations

AndroidLibrary (com.android.builder.model.AndroidLibrary)59 File (java.io.File)39 AwbBundle (com.taobao.android.builder.dependency.model.AwbBundle)13 JavaLibrary (com.android.builder.model.JavaLibrary)11 ArrayList (java.util.ArrayList)11 MtlBaseTaskAction (com.taobao.android.builder.tasks.manager.MtlBaseTaskAction)9 SoLibrary (com.taobao.android.builder.dependency.model.SoLibrary)8 TaskAction (org.gradle.api.tasks.TaskAction)8 NotNull (org.jetbrains.annotations.NotNull)8 GradleException (org.gradle.api.GradleException)6 VariantScope (com.android.build.gradle.internal.scope.VariantScope)5 MavenCoordinates (com.android.builder.model.MavenCoordinates)5 Variant (com.android.builder.model.Variant)5 AndroidModuleModel (com.android.tools.idea.gradle.project.model.AndroidModuleModel)5 Module (com.intellij.openapi.module.Module)5 JarFile (java.util.jar.JarFile)5 IOException (java.io.IOException)4 HashSet (java.util.HashSet)4 InputFile (org.gradle.api.tasks.InputFile)4 AndroidFacet (org.jetbrains.android.facet.AndroidFacet)4