Search in sources :

Example 81 with GradleException

use of org.gradle.api.GradleException in project atlas by alibaba.

the class ProcessAwbAndroidResources method doFullTaskAction.

@Override
protected void doFullTaskAction() throws IOException {
    // we have to clean the source folder output in case the package name changed.
    File srcOut = getSourceOutputDir();
    if (srcOut != null) {
        //            FileUtils.emptyFolder(srcOut);
        srcOut.delete();
        srcOut.mkdirs();
    }
    @Nullable File resOutBaseNameFile = getPackageOutputFile();
    // If are in instant run mode and we have an instant run enabled manifest
    File instantRunManifest = getInstantRunManifestFile();
    File manifestFileToPackage = instantRunBuildContext.isInInstantRunMode() && instantRunManifest != null && instantRunManifest.exists() ? instantRunManifest : getManifestFile();
    //增加awb模块编译所需要的额外参数
    addAaptOptions();
    AaptPackageProcessBuilder aaptPackageCommandBuilder = new AaptPackageProcessBuilder(manifestFileToPackage, getAaptOptions()).setAssetsFolder(getAssetsDir()).setResFolder(getResDir()).setLibraries(getLibraries()).setPackageForR(getPackageForR()).setSourceOutputDir(absolutePath(srcOut)).setSymbolOutputDir(absolutePath(getTextSymbolOutputDir())).setResPackageOutput(absolutePath(resOutBaseNameFile)).setProguardOutput(absolutePath(getProguardOutputFile())).setType(getType()).setDebuggable(getDebuggable()).setPseudoLocalesEnabled(getPseudoLocalesEnabled()).setResourceConfigs(getResourceConfigs()).setSplits(getSplits()).setPreferredDensity(getPreferredDensity());
    @NonNull AtlasBuilder builder = (AtlasBuilder) getBuilder();
    //        MergingLog mergingLog = new MergingLog(getMergeBlameLogFolder());
    //
    //        ProcessOutputHandler processOutputHandler = new ParsingProcessOutputHandler(
    //                new ToolOutputParser(new AaptOutputParser(), getILogger()),
    //                 builder.getErrorReporter());
    ProcessOutputHandler processOutputHandler = new LoggedProcessOutputHandler(getILogger());
    try {
        builder.processAwbResources(aaptPackageCommandBuilder, getEnforceUniquePackageName(), processOutputHandler, getMainSymbolFile());
        if (resOutBaseNameFile != null) {
            if (instantRunBuildContext.isInInstantRunMode()) {
                instantRunBuildContext.addChangedFile(InstantRunBuildContext.FileType.RESOURCES, resOutBaseNameFile);
                // get the new manifest file CRC
                JarFile jarFile = new JarFile(resOutBaseNameFile);
                String currentIterationCRC = null;
                try {
                    ZipEntry entry = jarFile.getEntry(SdkConstants.ANDROID_MANIFEST_XML);
                    if (entry != null) {
                        currentIterationCRC = String.valueOf(entry.getCrc());
                    }
                } finally {
                    jarFile.close();
                }
                // check the manifest file binary format.
                File crcFile = new File(instantRunSupportDir, "manifest.crc");
                if (crcFile.exists() && currentIterationCRC != null) {
                    // compare its content with the new binary file crc.
                    String previousIterationCRC = Files.readFirstLine(crcFile, Charsets.UTF_8);
                    if (!currentIterationCRC.equals(previousIterationCRC)) {
                        instantRunBuildContext.close();
                        instantRunBuildContext.setVerifierResult(InstantRunVerifierStatus.BINARY_MANIFEST_FILE_CHANGE);
                    }
                }
                // write the new manifest file CRC.
                Files.createParentDirs(crcFile);
                Files.write(currentIterationCRC, crcFile, Charsets.UTF_8);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new GradleException("process res exception", e);
    }
}
Also used : LoggedProcessOutputHandler(com.android.ide.common.process.LoggedProcessOutputHandler) ProcessOutputHandler(com.android.ide.common.process.ProcessOutputHandler) AaptPackageProcessBuilder(com.android.builder.core.AaptPackageProcessBuilder) NonNull(com.android.annotations.NonNull) ZipEntry(java.util.zip.ZipEntry) GradleException(org.gradle.api.GradleException) AtlasBuilder(com.android.builder.core.AtlasBuilder) LoggedProcessOutputHandler(com.android.ide.common.process.LoggedProcessOutputHandler) JarFile(java.util.jar.JarFile) JarFile(java.util.jar.JarFile) OutputFile(org.gradle.api.tasks.OutputFile) File(java.io.File) InputFile(org.gradle.api.tasks.InputFile) Nullable(com.android.annotations.Nullable) StopExecutionException(org.gradle.api.tasks.StopExecutionException) IOException(java.io.IOException) GradleException(org.gradle.api.GradleException)

Example 82 with GradleException

use of org.gradle.api.GradleException in project atlas by alibaba.

the class DataBindingRenameTask method createAwbPackages.

/**
     * 生成so的目录
     */
@TaskAction
void createAwbPackages() throws ExecutionException, InterruptedException {
    AndroidDependencyTree androidDependencyTree = AtlasBuildContext.androidDependencyTrees.get(getVariantName());
    if (null == androidDependencyTree) {
        return;
    }
    ExecutorServicesHelper executorServicesHelper = new ExecutorServicesHelper(taskName, getLogger(), 0);
    List<Runnable> runnables = new ArrayList<>();
    for (final AwbBundle awbBundle : androidDependencyTree.getAwbBundles()) {
        runnables.add(new Runnable() {

            @Override
            public void run() {
                try {
                    File dataBindingClazzFolder = appVariantOutputContext.getVariantContext().getJAwbavaOutputDir(awbBundle);
                    String packageName = ManifestFileUtils.getPackage(awbBundle.getOrgManifestFile());
                    String appName = appVariantContext.getVariantConfiguration().getOriginalApplicationId();
                    //删除那些已经存在的类
                    File dataMapperClazz = new File(dataBindingClazzFolder, "android/databinding/DataBinderMapper.class");
                    if (!dataMapperClazz.exists()) {
                        throw new GradleException("missing datamapper class");
                    }
                    FileInputStream fileInputStream = new FileInputStream(dataMapperClazz);
                    ClassReader in1 = new ClassReader(fileInputStream);
                    ClassWriter cw = new ClassWriter(0);
                    Map<String, String> reMapping = new HashedMap();
                    reMapping.put(appName.replace(".", "/") + "/BR", packageName.replace(".", "/") + "/BR");
                    RemappingClassAdapter remappingClassAdapter = new RemappingClassAdapter(cw, new SimpleRemapper(reMapping));
                    in1.accept(remappingClassAdapter, 8);
                    ClassReader in2 = new ClassReader(cw.toByteArray());
                    ClassWriter cw2 = new ClassWriter(0);
                    Set<String> renames = new HashSet<String>();
                    renames.add("android/databinding/DataBinderMapper");
                    in2.accept(new ClassRenamer(cw2, renames, packageName.replace(".", "/") + "/DataBinderMapper"), 8);
                    File destClass = new File(dataBindingClazzFolder, packageName.replace(".", "/") + "/DataBinderMapper.class");
                    destClass.getParentFile().mkdirs();
                    FileOutputStream fileOutputStream = new FileOutputStream(destClass);
                    fileOutputStream.write(cw2.toByteArray());
                    IOUtils.closeQuietly(fileOutputStream);
                    IOUtils.closeQuietly(fileInputStream);
                    FileUtils.deleteDirectory(new File(dataBindingClazzFolder, "android/databinding"));
                    FileUtils.deleteDirectory(new File(dataBindingClazzFolder, "com/android/databinding"));
                    File appDir = new File(dataBindingClazzFolder, appName.replace(".", "/"));
                    if (appDir.exists()) {
                        File[] files = appDir.listFiles(new FileFilter() {

                            @Override
                            public boolean accept(File pathname) {
                                return pathname.isFile() && !pathname.isDirectory();
                            }
                        });
                        for (File tmp : files) {
                            FileUtils.forceDelete(tmp);
                        }
                    }
                } catch (Throwable e) {
                    e.printStackTrace();
                    throw new GradleException("package awb failed");
                }
            }
        });
    }
    executorServicesHelper.execute(runnables);
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) ArrayList(java.util.ArrayList) AndroidDependencyTree(com.taobao.android.builder.dependency.AndroidDependencyTree) FileInputStream(java.io.FileInputStream) ExecutorServicesHelper(com.taobao.android.builder.tools.concurrent.ExecutorServicesHelper) SimpleRemapper(org.objectweb.asm.commons.SimpleRemapper) RemappingClassAdapter(org.objectweb.asm.commons.RemappingClassAdapter) GradleException(org.gradle.api.GradleException) FileOutputStream(java.io.FileOutputStream) AwbBundle(com.taobao.android.builder.dependency.model.AwbBundle) HashedMap(org.apache.commons.collections.map.HashedMap) FileFilter(java.io.FileFilter) File(java.io.File) Map(java.util.Map) HashedMap(org.apache.commons.collections.map.HashedMap) MtlBaseTaskAction(com.taobao.android.builder.tasks.manager.MtlBaseTaskAction) TaskAction(org.gradle.api.tasks.TaskAction)

Example 83 with GradleException

use of org.gradle.api.GradleException in project atlas by alibaba.

the class TPatchDiffResAPBuildTask method doAction.

@TaskAction
protected void doAction() throws IOException {
    manifestFile = getManifestFile();
    aaptOptions = getAaptOptions();
    diffResDir = getDiffResDir();
    resourceConfigs = getResourceConfigs();
    preferredDensity = getPreferredDensity();
    //TODO  minifyManifest
    File miniManifest = new File(packageOutputFile.getParentFile(), "AndroidManifest.xml");
    try {
        ManifestFileUtils.minifyManifest(manifestFile, miniManifest);
    } catch (DocumentException e) {
        throw new GradleException(e.getMessage());
    }
    File assetsFolder = new File(diffResDir, "assets");
    File resFolder = new File(diffResDir, "res");
    if (!assetsFolder.exists()) {
        assetsFolder.mkdirs();
    }
    if (!resFolder.exists()) {
        resFolder.mkdirs();
    }
    AaptPackageProcessBuilder aaptPackageCommandBuilder = new AaptPackageProcessBuilder(miniManifest, aaptOptions).setAssetsFolder(assetsFolder).setResFolder(resFolder).setLibraries(libraries).setPackageForR(packageForR).setResPackageOutput(packageOutputFile.getAbsolutePath()).setType(type).setDebuggable(debuggable).setPseudoLocalesEnabled(pseudoLocalesEnabled).setResourceConfigs(resourceConfigs).setSplits(splits).setPreferredDensity(preferredDensity);
    @NonNull AndroidBuilder builder = getBuilder();
    MergingLog mergingLog = new MergingLog(mergeBlameLogFolder);
    ProcessOutputHandler processOutputHandler = new ParsingProcessOutputHandler(new ToolOutputParser(new AaptOutputParser(), getILogger()), new MergingLogRewriter(mergingLog, builder.getErrorReporter()));
    try {
        if (builder instanceof AtlasBuilder) {
            ((AtlasBuilder) builder).processResources(aaptPackageCommandBuilder, enforceUniquePackageName, processOutputHandler);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } catch (ProcessException e) {
        throw new RuntimeException(e);
    }
}
Also used : ParsingProcessOutputHandler(com.android.ide.common.blame.ParsingProcessOutputHandler) ProcessOutputHandler(com.android.ide.common.process.ProcessOutputHandler) MergingLog(com.android.ide.common.blame.MergingLog) AaptOutputParser(com.android.ide.common.blame.parser.aapt.AaptOutputParser) IOException(java.io.IOException) MergingLogRewriter(com.android.ide.common.blame.MergingLogRewriter) ProcessException(com.android.ide.common.process.ProcessException) AaptPackageProcessBuilder(com.android.builder.core.AaptPackageProcessBuilder) ToolOutputParser(com.android.ide.common.blame.parser.ToolOutputParser) DocumentException(org.dom4j.DocumentException) GradleException(org.gradle.api.GradleException) NonNull(com.android.annotations.NonNull) AndroidBuilder(com.android.builder.core.AndroidBuilder) AtlasBuilder(com.android.builder.core.AtlasBuilder) File(java.io.File) InputFile(org.gradle.api.tasks.InputFile) ParsingProcessOutputHandler(com.android.ide.common.blame.ParsingProcessOutputHandler) MtlBaseTaskAction(com.taobao.android.builder.tasks.manager.MtlBaseTaskAction) TaskAction(org.gradle.api.tasks.TaskAction)

Example 84 with GradleException

use of org.gradle.api.GradleException in project atlas by alibaba.

the class AwbProguradHook method hookProguardTask.

/**
     * hook混淆的任务,加入awb的混淆配置
     *
     * @param appVariantContext
     */
public void hookProguardTask(final AppVariantContext appVariantContext) {
    final VariantScope variantScope = appVariantContext.getScope();
    List<TransformTask> proguaradTransformTasks = getTransformTaskByTransformType(appVariantContext, ProGuardTransform.class);
    for (TransformTask proguaradTransformTask : proguaradTransformTasks) {
        final ProGuardTransform proGuardTransform = (ProGuardTransform) proguaradTransformTask.getTransform();
        if (null != proGuardTransform) {
            proguaradTransformTask.doFirst(new Action<Task>() {

                @Override
                public void execute(Task task) {
                    GlobalScope globalScope = variantScope.getGlobalScope();
                    File proguardOut = new File(Joiner.on(File.separatorChar).join(String.valueOf(globalScope.getBuildDir()), FD_OUTPUTS, "mapping", variantScope.getVariantConfiguration().getDirName()));
                    //为了方便排查,先把configuration打印到目录
                    proGuardTransform.printconfiguration(new File(proguardOut, "tmp_config.cfg"));
                    final File outConfigFile = new File(proguardOut, "awb_config.cfg");
                    //增加awb的配置
                    AndroidDependencyTree dependencyTree = AtlasBuildContext.androidDependencyTrees.get(variantScope.getVariantConfiguration().getFullName());
                    if (null == dependencyTree) {
                        throw new StopExecutionException("DependencyTree cannot be null!");
                    }
                    if (dependencyTree.getAwbBundles().size() > 0) {
                        BaseVariantOutputData vod = appVariantContext.getVariantData().getOutputs().get(0);
                        AppVariantOutputContext appVariantOutputContext = getAppVariantOutputContext(appVariantContext, vod);
                        File awbObfuscatedDir = new File(globalScope.getIntermediatesDir(), "/classes-proguard/" + variantScope.getVariantConfiguration().getDirName());
                        AwbProguardConfiguration awbProguardConfiguration = new AwbProguardConfiguration(appVariantOutputContext.getAwbTransformMap().values(), awbObfuscatedDir, appVariantOutputContext);
                        try {
                            awbProguardConfiguration.printConfigFile(outConfigFile);
                        } catch (IOException e) {
                            throw new GradleException("", e);
                        }
                        proGuardTransform.setConfigurationFiles(new Supplier<Collection<File>>() {

                            @Override
                            public Collection<File> get() {
                                Set<File> proguardFiles = new HashSet<File>();
                                ((HashSet<File>) proguardFiles).add(outConfigFile);
                                return proguardFiles;
                            }
                        });
                    }
                    File mappingFile = null;
                    if (null != appVariantContext.apContext.getApExploredFolder() && appVariantContext.apContext.getApExploredFolder().exists()) {
                        mappingFile = new File(appVariantContext.apContext.getApExploredFolder(), "mapping.txt");
                    } else {
                        mappingFile = new File(appVariantContext.getScope().getGlobalScope().getProject().getProjectDir(), "mapping.txt");
                    }
                    if (null != mappingFile && mappingFile.exists()) {
                        proGuardTransform.applyTestedMapping(mappingFile);
                    }
                }
            });
        }
    }
}
Also used : GlobalScope(com.android.build.gradle.internal.scope.GlobalScope) VariantScope(com.android.build.gradle.internal.scope.VariantScope) TransformTask(com.android.build.gradle.internal.pipeline.TransformTask) Task(org.gradle.api.Task) AndroidDependencyTree(com.taobao.android.builder.dependency.AndroidDependencyTree) BaseVariantOutputData(com.android.build.gradle.internal.variant.BaseVariantOutputData) AppVariantOutputContext(com.android.build.gradle.internal.api.AppVariantOutputContext) IOException(java.io.IOException) ProGuardTransform(com.android.build.gradle.internal.transforms.ProGuardTransform) StopExecutionException(org.gradle.api.tasks.StopExecutionException) AwbProguardConfiguration(com.taobao.android.builder.tasks.app.bundle.AwbProguardConfiguration) GradleException(org.gradle.api.GradleException) TransformTask(com.android.build.gradle.internal.pipeline.TransformTask) Supplier(java.util.function.Supplier) File(java.io.File)

Example 85 with GradleException

use of org.gradle.api.GradleException in project atlas by alibaba.

the class DiffBundleInfoTask method getArtifactBundleInfo.

private Set<ArtifactBundleInfo> getArtifactBundleInfo(DependencyDiff dependencyDiff, File mainfestFile, File apDir) throws IOException, DocumentException {
    Set<ArtifactBundleInfo> artifactBundleInfos = new HashSet<ArtifactBundleInfo>();
    if (null == apDir) {
        throw new GradleException("No Ap dependency found!");
    }
    File apManifest = new File(apDir, "AndroidManifest.xml");
    String apVersion = null;
    try {
        apVersion = ManifestFileUtils.getVersionName(apManifest);
    } catch (Exception e) {
        throw new GradleException(e.getMessage(), e);
    }
    // 1. 首先添加主bundle
    ArtifactBundleInfo mainBundleInfo = getMainArtifactBundInfo(mainfestFile);
    mainBundleInfo.setBaseVersion(apVersion);
    mainBundleInfo.setMainBundle(true);
    mainBundleInfo.setVersion(appVariantOutputContext.getVariantContext().getVariantConfiguration().getVersionName());
    if (dependencyDiff.getMainDexDiffs().size() > 0) {
        mainBundleInfo.setDiffType(DiffType.MODIFY);
    } else {
        mainBundleInfo.setDiffType(DiffType.NONE);
    }
    artifactBundleInfos.add(mainBundleInfo);
    // 2. 添加各自的bundle
    AndroidDependencyTree androidDependencyTree = AtlasBuildContext.androidDependencyTrees.get(appVariantOutputContext.getVariantContext().getVariantConfiguration().getFullName());
    for (AwbBundle awbBundle : androidDependencyTree.getAwbBundles()) {
        BundleInfo bundleInfo = awbBundle.bundleInfo;
        ArtifactBundleInfo awbBundleInfo = new ArtifactBundleInfo();
        awbBundleInfo.setMainBundle(false);
        awbBundleInfo.setDependency(bundleInfo.getDependency());
        awbBundleInfo.setPkgName(bundleInfo.getPkgName());
        awbBundleInfo.setApplicationName(bundleInfo.getApplicationName());
        awbBundleInfo.setArtifactId(awbBundle.getResolvedCoordinates().getArtifactId());
        awbBundleInfo.setName(bundleInfo.getName());
        String version = bundleInfo.getVersion();
        if (version.indexOf("@") > 0) {
            String[] arr = version.split("@");
            version = arr[arr.length - 1];
        }
        awbBundleInfo.setVersion(version);
        String libBundleName = getBundleName(awbBundle);
        if (dependencyDiff.getAwbDiffs().contains(libBundleName)) {
            if (dependencyDiff.getNewAwbs().contains(libBundleName)) {
                awbBundleInfo.setDiffType(DiffType.ADD);
            } else {
                awbBundleInfo.setDiffType(DiffType.MODIFY);
            }
        } else {
            awbBundleInfo.setDiffType(DiffType.NONE);
        }
        artifactBundleInfos.add(awbBundleInfo);
    }
    return artifactBundleInfos;
}
Also used : ArtifactBundleInfo(com.taobao.android.object.ArtifactBundleInfo) BundleInfo(com.taobao.android.builder.tools.bundleinfo.model.BundleInfo) ArtifactBundleInfo(com.taobao.android.object.ArtifactBundleInfo) GradleException(org.gradle.api.GradleException) AndroidDependencyTree(com.taobao.android.builder.dependency.AndroidDependencyTree) AwbBundle(com.taobao.android.builder.dependency.model.AwbBundle) File(java.io.File) IOException(java.io.IOException) GradleException(org.gradle.api.GradleException) HashSet(java.util.HashSet)

Aggregations

GradleException (org.gradle.api.GradleException)114 File (java.io.File)40 IOException (java.io.IOException)32 TaskAction (org.gradle.api.tasks.TaskAction)16 ArrayList (java.util.ArrayList)10 UncheckedIOException (org.gradle.api.UncheckedIOException)10 MtlBaseTaskAction (com.taobao.android.builder.tasks.manager.MtlBaseTaskAction)9 AndroidDependencyTree (com.taobao.android.builder.dependency.AndroidDependencyTree)8 HashSet (java.util.HashSet)8 FileOutputStream (java.io.FileOutputStream)6 Method (java.lang.reflect.Method)6 UncheckedException (org.gradle.internal.UncheckedException)6 AwbBundle (com.taobao.android.builder.dependency.model.AwbBundle)5 URL (java.net.URL)5 List (java.util.List)5 ConsoleRenderer (org.gradle.internal.logging.ConsoleRenderer)5 ProcessOutputHandler (com.android.ide.common.process.ProcessOutputHandler)4 FileInputStream (java.io.FileInputStream)4 InvocationTargetException (java.lang.reflect.InvocationTargetException)4 MalformedURLException (java.net.MalformedURLException)4