Search in sources :

Example 66 with NonNull

use of com.android.annotations.NonNull 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 67 with NonNull

use of com.android.annotations.NonNull 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 68 with NonNull

use of com.android.annotations.NonNull in project paraphrase by JakeWharton.

the class ValueResourceParser method parseFile.

/**
   * Parses the file and returns a list of {@link ResourceItem} objects.
   * @return a list of resources.
   *
   * @throws MergingException if a merging exception happens
   */
@NonNull
private List<ResourceItem> parseFile() throws MergingException {
    Document document = parseDocument(file);
    // get the root node
    Node rootNode = document.getDocumentElement();
    if (rootNode == null) {
        return Collections.emptyList();
    }
    NodeList nodes = rootNode.getChildNodes();
    final int count = nodes.getLength();
    // list containing the result
    List<ResourceItem> resources = Lists.newArrayListWithExpectedSize(count);
    for (int i = 0, n = nodes.getLength(); i < n; i++) {
        Node node = nodes.item(i);
        if (node.getNodeType() != Node.ELEMENT_NODE) {
            continue;
        }
        ResourceItem resource = getResource(node);
        if (resource != null) {
            resources.add(resource);
        }
    }
    return resources;
}
Also used : Node(org.w3c.dom.Node) NodeList(org.w3c.dom.NodeList) Document(org.w3c.dom.Document) ResourceItem(com.android.ide.common.res2.ResourceItem) NonNull(com.android.annotations.NonNull)

Example 69 with NonNull

use of com.android.annotations.NonNull in project android by JetBrains.

the class ImportSummary method createSummary.

/**
   * Provides the summary
   */
@NonNull
public String createSummary() {
    StringBuilder sb = new StringBuilder(2000);
    sb.append(MSG_HEADER);
    List<String> problems = Lists.newArrayList();
    problems.addAll(myImporter.getErrors());
    problems.addAll(myImporter.getWarnings());
    if (!problems.isEmpty()) {
        sb.append("\n");
        for (String warning : problems) {
            sb.append(" * ");
            if (myWrapErrorMessages) {
                sb.append(SdkUtils.wrap(warning, 80, "   "));
            } else {
                sb.append(warning);
            }
            sb.append("\n");
        }
    }
    if (myHasRiskyPathChars) {
        sb.append(MSG_RISKY_PROJECT_LOCATION);
        String path = myDestDir.getPath();
        sb.append(path).append("\n");
        for (int i = 0, n = path.length(); i < n; i++) {
            char c = path.charAt(i);
            sb.append(isRiskyPathChar(c) ? '-' : ' ');
        }
        sb.append("\n");
    }
    if (myManifestsMayDiffer) {
        sb.append(MSG_MANIFEST);
    }
    if (!myNotMigrated.isEmpty()) {
        sb.append(MSG_UNHANDLED);
        List<String> modules = Lists.newArrayList(myNotMigrated.keySet());
        Collections.sort(modules);
        for (String module : modules) {
            if (modules.size() > 1) {
                sb.append("From ").append(module).append(":\n");
            }
            List<String> sorted = new ArrayList<String>(myNotMigrated.get(module));
            Collections.sort(sorted);
            for (String path : sorted) {
                sb.append("* ").append(path).append("\n");
            }
        }
    }
    if (!myJarDependencies.isEmpty()) {
        sb.append(MSG_REPLACED_JARS);
        // TODO: Also add note here about switching to AAR's potentially also creating
        // compilation errors because it now enforces that app min sdk version is >= library
        // min sdk version, and suggesting that they re-run import with replaceJars=false
        // if this leads to problems.
        List<File> files = Lists.newArrayList(myJarDependencies.keySet());
        Collections.sort(files);
        for (File file : files) {
            String jar = file.getName();
            GradleCoordinate dependency = myJarDependencies.get(file);
            sb.append(jar).append(" => ").append(dependency).append("\n");
        }
    }
    if (!myGuessedDependencyVersions.isEmpty()) {
        sb.append(MSG_GUESSED_VERSIONS);
        Collections.sort(myGuessedDependencyVersions);
        for (String replaced : myGuessedDependencyVersions) {
            sb.append(replaced).append("\n");
        }
    }
    if (!myLibDependencies.isEmpty()) {
        sb.append(MSG_REPLACED_LIBS);
        List<String> modules = Lists.newArrayList(myLibDependencies.keySet());
        Collections.sort(modules);
        for (String module : modules) {
            List<GradleCoordinate> dependencies = myLibDependencies.get(module);
            if (dependencies.size() == 1) {
                sb.append(module).append(" => ").append(dependencies).append("\n");
            } else {
                sb.append(module).append(" =>\n");
                for (GradleCoordinate dependency : dependencies) {
                    sb.append("    ").append(dependency).append("\n");
                }
            }
        }
    }
    if (!myMoved.isEmpty()) {
        sb.append(MSG_FOLDER_STRUCTURE);
        List<ImportModule> modules = Lists.newArrayList(myMoved.keySet());
        Collections.sort(modules);
        for (ImportModule module : modules) {
            if (modules.size() > 1) {
                sb.append("In ").append(module.getOriginalName()).append(":\n");
            }
            Map<File, File> map = myMoved.get(module);
            List<File> sorted = new ArrayList<File>(map.keySet());
            Collections.sort(sorted);
            for (File from : sorted) {
                sb.append("* ");
                File to = map.get(from);
                assert to != null : from;
                File fromRelative = null;
                File toRelative = null;
                try {
                    fromRelative = module.computeProjectRelativePath(from);
                    if (myDestDir != null) {
                        toRelative = GradleImport.computeRelativePath(myDestDir.getCanonicalFile(), to);
                    }
                } catch (IOException ioe) {
                // pass; use full path
                }
                if (fromRelative == null) {
                    fromRelative = from;
                }
                if (toRelative == null) {
                    toRelative = to;
                }
                sb.append(fromRelative.getPath());
                if (from.isDirectory()) {
                    sb.append(File.separator);
                }
                sb.append(" => ");
                sb.append(toRelative.getPath());
                if (to.isDirectory()) {
                    sb.append(File.separator);
                }
                sb.append("\n");
            }
        }
    }
    if (myImporter.needSupportRepository() && myImporter.isMissingSupportRepository()) {
        sb.append(MSG_MISSING_REPO_1);
        sb.append(myImporter.getSdkLocation()).append("\n");
        sb.append(MSG_MISSING_REPO_2);
    }
    if (myImporter.needGoogleRepository() && myImporter.isMissingGoogleRepository()) {
        sb.append(MSG_MISSING_GOOGLE_REPOSITORY_1);
        sb.append(myImporter.getSdkLocation()).append("\n");
        sb.append(MSG_MISSING_GOOGLE_REPOSITORY_2);
    }
    if (Revision.parseRevision(myImporter.getBuildToolsVersion()).getMajor() < 19) {
        sb.append(MSG_BUILD_TOOLS_VERSION);
    }
    if (!myIgnoredUserHomeProGuardFiles.isEmpty()) {
        sb.append(MSG_USER_HOME_PROGUARD);
        Collections.sort(myIgnoredUserHomeProGuardFiles);
        for (String path : myIgnoredUserHomeProGuardFiles) {
            sb.append(path).append("\n");
        }
    }
    sb.append(MSG_FOOTER);
    return sb.toString().replace("\n", GradleImport.NL);
}
Also used : GradleCoordinate(com.android.ide.common.repository.GradleCoordinate) IOException(java.io.IOException) File(java.io.File) NonNull(com.android.annotations.NonNull)

Example 70 with NonNull

use of com.android.annotations.NonNull in project android by JetBrains.

the class GradleImport method exportIntoProject.

/**
   * Like {@link #exportProject(java.io.File, boolean)}, but writes into an existing
   * project instead of creating a new one.
   * <p>
   * <b>NOTE</b>: When performing an import into an existing project, note that
   * you should call {@link #setImportIntoExisting(boolean)} before the call to
   * read in projects ({@link #importProjects(java.util.List)}. Note also that
   * you should call {@link #setPerModuleRepositories(boolean)} with a suitable
   * value based on whether the existing project defines shared repositories.
   * This is similar to how we pass the "perModuleRepositories" variable to
   * our Freemarker templates (such as
   * templates/gradle-projects/NewAndroidModule/root/build.gradle.ftl ) so it
   * can decide whether to include this info in the new module. In Studio we
   * set it based on whether $PROJECT/build.gradle contains "repositories" (this
   * is done in NewModuleWizard).
   * </p>
   *
   * @param projectDir     the root directory containing the project to write into
   * @param updateSettings whether the importer should attempt to update the settings.gradle
   *                       file in the project or not. Clients such as Android Studio may
   *                       wish to pass false here in order to handle this part
   * @param writeSummary   whether we should generate an import summary
   * @param destDirMap     optional map from ADT project dir to destination directory to
   *                       write each module as.
   * @return the list of imported module directories
   */
@NonNull
public List<File> exportIntoProject(@NonNull File projectDir, boolean updateSettings, boolean writeSummary, @Nullable Map<File, File> destDirMap) throws IOException {
    mySummary.setDestDir(projectDir);
    List<File> imported = Lists.newArrayListWithExpectedSize(myRootModules.size());
    for (ImportModule module : getModulesToImport()) {
        File moduleDir = null;
        if (destDirMap != null) {
            moduleDir = destDirMap.get(module.getDir());
        }
        if (moduleDir == null) {
            moduleDir = new File(projectDir, module.getModuleName());
            if (moduleDir.exists()) {
                module.pickUniqueName(projectDir);
                moduleDir = new File(projectDir, module.getModuleName());
                assert !moduleDir.exists();
            }
        }
        exportModule(moduleDir, module);
        imported.add(moduleDir);
    }
    if (updateSettings) {
        exportSettingsGradle(new File(projectDir, FN_SETTINGS_GRADLE), true);
    }
    if (writeSummary) {
        mySummary.write(new File(projectDir, IMPORT_SUMMARY_TXT));
    }
    return imported;
}
Also used : File(java.io.File) NonNull(com.android.annotations.NonNull)

Aggregations

NonNull (com.android.annotations.NonNull)89 File (java.io.File)23 TextRange (com.intellij.openapi.util.TextRange)13 IOException (java.io.IOException)11 ArrayList (java.util.ArrayList)8 OutputFile (com.android.build.OutputFile)5 DefaultPosition (com.android.tools.klint.detector.api.DefaultPosition)5 Position (com.android.tools.klint.detector.api.Position)5 Issue (com.android.tools.klint.detector.api.Issue)4 Position (com.android.tools.lint.detector.api.Position)4 Module (com.intellij.openapi.module.Module)4 StringReader (java.io.StringReader)4 AbstractInsnNode (org.jetbrains.org.objectweb.asm.tree.AbstractInsnNode)4 Node (org.w3c.dom.Node)4 NodeList (org.w3c.dom.NodeList)4 InputSource (org.xml.sax.InputSource)4 Nullable (com.android.annotations.Nullable)3 AaptPackageProcessBuilder (com.android.builder.core.AaptPackageProcessBuilder)3 AtlasBuilder (com.android.builder.core.AtlasBuilder)3 AndroidProject (com.android.builder.model.AndroidProject)3