Java Code Examples for com.android.utils.FileUtils#cleanOutputDir()

The following examples show how to use com.android.utils.FileUtils#cleanOutputDir() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AtlasMainDexMerger.java    From atlas with Apache License 2.0 5 votes vote down vote up
@Override
public void merge(TransformInvocation transformInvocation) {

    if (dexMerger == DexMergerTool.D8) {
        logger.info("D8 is used to merge dex.");
    }

    TransformOutputProvider outputProvider = transformInvocation.getOutputProvider();
    Collection<TransformInput> transformInputs = transformInvocation.getInputs();

    List<File> mainDexFiles = new ArrayList<>();

    final File[][] mergeDexs = {new File[0]};

    File outputDir =
            getDexOutputLocation(outputProvider, "main", TransformManager.SCOPE_FULL_PROJECT);
    // this deletes and creates the dir for the output
    try {
        FileUtils.cleanOutputDir(outputDir);
    } catch (IOException e) {
        e.printStackTrace();
    }

    variantOutputContext.setDexMergeFolder(outputDir);

    transformInputs.forEach((TransformInput transformInput) -> {
        File file = (File) ReflectUtils.getField(transformInput, "optionalRootLocation");
        if (file != null && file.exists()) {
            mainDexFiles.addAll(org.apache.commons.io.FileUtils.listFiles(file, new String[]{"jar", "dex"}, true));
            mergeDexs[0] = file.listFiles(pathname -> pathname.getName().endsWith(".jar") || pathname.isDirectory());
        }
    });


    merge(mainDexFiles,outputDir,mergeDexs);

}
 
Example 2
Source File: MergeAwbAssets.java    From atlas with Apache License 2.0 5 votes vote down vote up
@Override
    protected void doFullTaskAction() throws IOException {
        if (awbBundle.isMBundle){
            return;
        }
        // this is full run, clean the previous output
        File destinationDir = getOutputDir();
        FileUtils.cleanOutputDir(destinationDir);

        List<AssetSet> assetSets = computeAssetSetList();

        // create a new merger and populate it with the sets.
        AssetMerger merger = new AssetMerger();

        try {
            for (AssetSet assetSet : assetSets) {
                // set needs to be loaded.
                assetSet.loadFromFiles(getILogger());
                merger.addDataSet(assetSet);
            }

            // get the merged set and write it down.
            MergedAssetWriter writer = new MergedAssetWriter(destinationDir, workerExecutor);

            merger.mergeData(writer, false /*doCleanUp*/);

            // No exception? Write the known state.
            merger.writeBlobTo(getIncrementalFolder(), writer, false);
        } catch (MergingException e) {
            getLogger().error("Could not merge source set folders: ", e);
            merger.cleanBlob(getIncrementalFolder());
            throw new ResourceException(e.getMessage(), e);
        }
//        if (awbBundle.mBundle){
//            org.apache.commons.io.FileUtils.moveDirectoryToDirectory(destinationDir,variantContext.getVariantData().mergeAssetsTask.getOutputDir(),true);
//        }
    }
 
Example 3
Source File: MergeResources.java    From javafxmobile-plugin with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected void doFullTaskAction() throws IOException {
    ResourcePreprocessor preprocessor = getPreprocessor();

    // this is full run, clean the previous output
    File destinationDir = getOutputDir();
    FileUtils.cleanOutputDir(destinationDir);

    List<ResourceSet> resourceSets = getConfiguredResourceSets(preprocessor);

    // create a new merger and populate it with the sets.
    ResourceMerger merger = new ResourceMerger(minSdk);
    MergingLog mergingLog =
            getBlameLogFolder() != null ? new MergingLog(getBlameLogFolder()) : null;

    try (QueueableResourceCompiler resourceCompiler =
                 processResources
                         ? makeAapt(
                         buildToolInfo.get(),
                         aaptGeneration,
                         getBuilder(),
                         crunchPng,
                         mergingLog)
                         : QueueableResourceCompiler.NONE) {

        for (ResourceSet resourceSet : resourceSets) {
            resourceSet.loadFromFiles(getILogger());
            merger.addDataSet(resourceSet);
        }

        MergedResourceWriter writer =
                new MergedResourceWriter(
                        workerExecutorFacade,
                        destinationDir,
                        getPublicFile(),
                        mergingLog,
                        preprocessor,
                        resourceCompiler,
                        getIncrementalFolder(),
                        null,
                        null,
                        false,
                        getCrunchPng());

        merger.mergeData(writer, false /*doCleanUp*/);

        // No exception? Write the known state.
        merger.writeBlobTo(getIncrementalFolder(), writer, false);
    } catch (MergingException e) {
        System.out.println(e.getMessage());
        merger.cleanBlob(getIncrementalFolder());
        throw new ResourceException(e.getMessage(), e);
    } finally {
        cleanup();
    }
}
 
Example 4
Source File: AtlasDexArchiveBuilderTransform.java    From atlas with Apache License 2.0 4 votes vote down vote up
private List<File> convertToDexArchive(
        @NonNull Context context,
        @NonNull QualifiedContent input,
        @NonNull TransformOutputProvider outputProvider,
        boolean isIncremental)
        throws Exception {

    logger.verbose("Dexing {}", input.getFile().getAbsolutePath());
    ImmutableList.Builder<File> dexArchives = ImmutableList.builder();
    for (int bucketId = 0; bucketId < NUMBER_OF_BUCKETS; bucketId++) {
        File preDexOutputFile = getPreDexFile(outputProvider, input, bucketId);
        if (input.getFile().isDirectory()) {
            File cachedVersion = cacheHandler.getCachedVersionIfPresent(input.getFile());
            dexArchives.add(preDexOutputFile);
            if (cachedVersion != null) {
                FileUtils.copyDirectoryContentToDirectory(cachedVersion, preDexOutputFile);
                return dexArchives.build();

            }
        }
        if (preDexOutputFile.isDirectory() && preDexOutputFile.exists()) {
            FileUtils.cleanOutputDir(preDexOutputFile);
        }else {
            FileUtils.deleteIfExists(preDexOutputFile);
        }
        AtlasDexArchiveBuilderTransform.DexConversionParameters parameters =
                new AtlasDexArchiveBuilderTransform.DexConversionParameters(
                        input,
                        preDexOutputFile,
                        NUMBER_OF_BUCKETS,
                        bucketId,
                        minSdkVersion,
                        dexOptions.getAdditionalParameters(),
                        inBufferSize,
                        outBufferSize,
                        dexer,
                        isDebuggable,
                        isIncremental,
                        false);

        if (useGradleWorkers) {
            context.getWorkerExecutor()
                    .submit(
                            DexArchiveBuilderTransform.DexConversionWorkAction.class,
                            configuration -> {
                                configuration.setIsolationMode(IsolationMode.NONE);
                                configuration.setParams(parameters);
                            });
        } else {
            executor.execute(
                    () -> {
                        ProcessOutputHandler outputHandler =
                                new ParsingProcessOutputHandler(
                                        new ToolOutputParser(
                                                new DexParser(), Message.Kind.ERROR, logger),
                                        new ToolOutputParser(new DexParser(), logger),
                                        errorReporter);
                        ProcessOutput output = null;
                        try (Closeable ignored = output = outputHandler.createOutput()) {
                            launchProcessing(
                                    parameters,
                                    output.getStandardOutput(),
                                    output.getErrorOutput());
                        } finally {
                            if (output != null) {
                                try {
                                    outputHandler.handleOutput(output);
                                } catch (ProcessException e) {
                                    // ignore this one
                                }
                            }
                        }
                        return null;
                    });
        }
    }
    List<File> files = dexArchives.build();
    return files;
}
 
Example 5
Source File: AtlasDexArchiveBuilderTransform.java    From atlas with Apache License 2.0 4 votes vote down vote up
private List<File> convertAwbToDexArchive(
        @NonNull Context context,
        @NonNull QualifiedContent input,
        @NonNull File outputProvider,
        boolean isIncremental,
        boolean awb)
        throws Exception {

    int count = 0;
    if (input.getFile().isFile()) {
         count = computerClassCount(input.getFile());
       
    }else if (input.getFile().isDirectory()){
        count = 1;
    }
    logger.verbose("Dexing {}", input.getFile().getAbsolutePath());

    ImmutableList.Builder<File> dexArchives = ImmutableList.builder();

    for (int bucketId = 0; bucketId < count; bucketId++) {
        File preDexOutputFile = getAwbPreDexFile(outputProvider, input, bucketId);
        if (input.getFile().isDirectory()) {
            File cachedVersion = cacheHandler.getCachedVersionIfPresent(input.getFile());
            dexArchives.add(preDexOutputFile);
            if (cachedVersion != null) {
                FileUtils.copyDirectoryContentToDirectory(cachedVersion, preDexOutputFile);
                return dexArchives.build();
            }
        }
        if (preDexOutputFile.isDirectory() && preDexOutputFile.exists()) {
            FileUtils.cleanOutputDir(preDexOutputFile);
        }else {
            FileUtils.deleteIfExists(preDexOutputFile);
        }
        AtlasDexArchiveBuilderTransform.DexConversionParameters parameters =
                new AtlasDexArchiveBuilderTransform.DexConversionParameters(
                        input,
                        preDexOutputFile,
                        NUMBER_OF_BUCKETS,
                        bucketId,
                        minSdkVersion,
                        dexOptions.getAdditionalParameters(),
                        inBufferSize,
                        outBufferSize,
                        dexer,
                        isDebuggable,
                        false,
                        awb);

        if (useGradleWorkers) {
            context.getWorkerExecutor()
                    .submit(
                            DexArchiveBuilderTransform.DexConversionWorkAction.class,
                            configuration -> {
                                configuration.setIsolationMode(IsolationMode.NONE);
                                configuration.setParams(parameters);
                            });
        } else {
            executor.execute(
                    () -> {
                        ProcessOutputHandler outputHandler =
                                new ParsingProcessOutputHandler(
                                        new ToolOutputParser(
                                                new DexParser(), Message.Kind.ERROR, logger),
                                        new ToolOutputParser(new DexParser(), logger),
                                        errorReporter);
                        ProcessOutput output = null;
                        try (Closeable ignored = output = outputHandler.createOutput()) {
                            launchProcessing(
                                    parameters,
                                    output.getStandardOutput(),
                                    output.getErrorOutput());
                        } finally {
                            if (output != null) {
                                try {
                                    outputHandler.handleOutput(output);
                                } catch (ProcessException e) {
                                    // ignore this one
                                }
                            }
                        }
                        return null;
                    });
        }
    }

   List<File>files =  dexArchives.build();
    return files;
}
 
Example 6
Source File: AtlasDexArchiveBuilderTransform.java    From atlas with Apache License 2.0 4 votes vote down vote up
private void processAwbDexArchive(TransformInvocation transformInvocation, List<QualifiedContent> listFiles) throws Exception {

        File awbApkOutputDir = ((AppVariantContext) variantContext).getAwbApkOutputDir();
        FileUtils.cleanOutputDir(awbApkOutputDir);

        AtlasDependencyTree atlasDependencyTree = AtlasBuildContext.androidDependencyTrees.get(
                variantContext.getScope().getFullVariantName());

        if (null == atlasDependencyTree) {
            return;
        }

        for (final AwbBundle awbBundle : atlasDependencyTree.getAwbBundles()) {

            Multimap<QualifiedContent, File> cacheableItems = HashMultimap.create();

            List<QualifiedContent> qualifiedContents = new LinkedList<>();

            long start = System.currentTimeMillis();


            // if some of our .jar input files exist, just reset the inputDir to null
            AwbTransform awbTransform = variantContext.getAppVariantOutputContext(ApkDataUtils.get(variantOutput)).getAwbTransformMap()
                    .get(awbBundle.getName());
            List<File> inputFiles = new ArrayList<File>();
            inputFiles.addAll(awbTransform.getInputFiles());
            inputFiles.addAll(awbTransform.getInputLibraries());
            if (null != awbTransform.getInputDirs()) {
                inputFiles.addAll(awbTransform.getInputDirs());
            }

            for (File file : inputFiles) {
                logger.warning(awbBundle.getName()+":"+file.getAbsolutePath());
                boolean find = false;
                for (QualifiedContent content : listFiles) {
                    if (content.getFile().getAbsolutePath().equals(file.getAbsolutePath())) {
                        find = true;
                        qualifiedContents.add(content);
                        break;
                    }
                }

                if (!find) {
                    if (file.isDirectory()) {
                        DirectoryInput directoryInput = TransformInputUtils.makeDirectoryInput(file,variantContext);
                        qualifiedContents.add(directoryInput);
                    } else if (file.isFile()) {
                        JarInput jarInput = TransformInputUtils.makeJarInput(file,variantContext);
                        qualifiedContents.add(jarInput);
                    }

                }

            }
            for (QualifiedContent qualifiedContent : qualifiedContents) {
                if (qualifiedContent.getFile().isDirectory()) {
                    List<File>awbFiles = convertAwbToDexArchive(
                            transformInvocation.getContext(),
                            qualifiedContent, variantContext.getAwbDexAchiveOutput(awbBundle), transformInvocation.isIncremental()
                    ,true);
                    cacheableItems.putAll(qualifiedContent, awbFiles);

                } else {
                    List<File> jarFiles = processAwbJarInput(transformInvocation.getContext(), transformInvocation.isIncremental(), (JarInput) qualifiedContent, variantContext.getAwbDexAchiveOutput(awbBundle));
                    cacheableItems.putAll(qualifiedContent, jarFiles);
                }
            }

            cacheItems.putAll(cacheableItems);


        }
    }
 
Example 7
Source File: TaobaoInstantRunDex.java    From atlas with Apache License 2.0 4 votes vote down vote up
@Override
    public void transform(@NonNull TransformInvocation invocation)
            throws IOException, TransformException, InterruptedException {

        File outputFolder = variantScope.getReloadDexOutputFolder();
//        boolean changesAreCompatible =
//                variantScope.getInstantRunBuildContext().hasPassedVerification();
//        boolean restartDexRequested =
//                variantScope.getGlobalScope().isActive(OptionalCompilationStep.RESTART_ONLY);

//        if (!changesAreCompatible || restartDexRequested) {
            FileUtils.cleanOutputDir(outputFolder);
//            return;
//        }

        // create a tmp jar file.
        File classesJar = new File(outputFolder, "classes.jar");
        if (classesJar.exists()) {
            FileUtils.delete(classesJar);
        }
        Files.createParentDirs(classesJar);
        final TaobaoInstantRunDex.JarClassesBuilder jarClassesBuilder = getJarClassBuilder(classesJar);

        try {
            for (TransformInput input : invocation.getReferencedInputs()) {
                for (DirectoryInput directoryInput : input.getDirectoryInputs()) {
                    if (!directoryInput.getContentTypes()
                            .contains(ExtendedContentType.CLASSES_ENHANCED)) {
                        continue;
                    }
                    final File folder = directoryInput.getFile();
                    if (invocation.isIncremental()) {
                        for (Map.Entry<File, Status> entry :
                                directoryInput.getChangedFiles().entrySet()) {
                            if (entry.getValue() != Status.REMOVED) {
                                File file = entry.getKey();
                                if (file.isFile()) {
                                    jarClassesBuilder.add(folder, file);
                                }
                            }
                        }
                    } else {
                        Iterable<File> files = FileUtils.getAllFiles(folder);
                        for (File inputFile : files) {
                            jarClassesBuilder.add(folder, inputFile);
                        }
                    }
                }
            }
        } finally {
            jarClassesBuilder.close();
        }

        // if no files were added, clean up and return.
        if (jarClassesBuilder.isEmpty()) {
            FileUtils.cleanOutputDir(outputFolder);
            return;
        }

        if (preloadJarHooker != null){
           classesJar = preloadJarHooker.process(classesJar);
        }

        final ImmutableList.Builder<File> inputFiles = ImmutableList.builder();
        inputFiles.add(classesJar);

        try {
            variantScope
                    .getInstantRunBuildContext()
                    .startRecording(InstantRunBuildContext.TaskType.INSTANT_RUN_DEX);
            convertByteCode(inputFiles.build(), outputFolder);
            variantScope
                    .getInstantRunBuildContext()
                    .addChangedFile(FileType.RELOAD_DEX, new File(outputFolder, "classes.dex"));
        } catch (ProcessException e) {
            throw new TransformException(e);
        } finally {
            variantScope
                    .getInstantRunBuildContext()
                    .stopRecording(InstantRunBuildContext.TaskType.INSTANT_RUN_DEX);
        }

        variantScope.getInstantRunBuildContext().close();

        if (variantContext.getScope().getInstantRunBuildContext().isInInstantRunMode()) {
            InstantRunBuildContext instantRunBuildContext = variantContext.getScope().getInstantRunBuildContext();
            InstantRunBuildContext.Artifact artifact = instantRunBuildContext.getLastBuild().getArtifactForType(FileType.RELOAD_DEX);
            File patchFile = artifact.getLocation();
            String baseVersion = ApkDataUtils.get(variantOutput).getVersionName();
            if (artifact!= null && patchFile.exists()) {
                File finalFile = variantContext.getAppVariantOutputContext(ApkDataUtils.get(variantOutput)).getIPatchFile(baseVersion);
                zipPatch(finalFile, patchFile);
            }else {
                logger.warning("patchFile is not exist or no classes is modified!");
            }
            return;
        }
    }