Search in sources :

Example 6 with ArtifactDependencyModel

use of com.android.tools.idea.gradle.dsl.model.dependencies.ArtifactDependencyModel in project android by JetBrains.

the class GradleDependencyManager method findMissingDependencies.

/**
   * Returns the dependencies that are NOT included in the specified module.
   * Note: the version of the dependency is disregarded.
   *
   * @param module the module to check dependencies in
   * @param dependencies the dependencies of interest.
   * @return a list of the dependencies NOT included in the module
   */
@NotNull
public List<GradleCoordinate> findMissingDependencies(@NotNull Module module, @NotNull Iterable<GradleCoordinate> dependencies) {
    AndroidModuleModel gradleModel = AndroidModuleModel.get(module);
    GradleBuildModel buildModel = GradleBuildModel.get(module);
    if (gradleModel == null && buildModel == null) {
        return Collections.emptyList();
    }
    RepositoryUrlManager manager = RepositoryUrlManager.get();
    List<GradleCoordinate> missingLibraries = Lists.newArrayList();
    for (GradleCoordinate coordinate : dependencies) {
        GradleCoordinate resolvedCoordinate = manager.resolveDynamicCoordinate(coordinate, null);
        if (resolvedCoordinate == null) {
            // We don't have anything installed, but we can keep trying with the unresolved coordinate if we have enough info
            if (coordinate.getArtifactId() == null || coordinate.getGroupId() == null) {
                // TODO Should this be an error ?
                continue;
            }
        } else {
            coordinate = resolvedCoordinate;
        }
        boolean dependencyFound = false;
        // First look in the model returned by Gradle.
        if (gradleModel != null && GradleUtil.dependsOn(gradleModel, String.format("%s:%s", coordinate.getGroupId(), coordinate.getArtifactId()))) {
            // GradleUtil.dependsOn method only checks the android library dependencies.
            // TODO: Consider updating it to also check for java library dependencies.
            dependencyFound = true;
        } else if (buildModel != null) {
            // Now, check in the model obtained from the gradle files.
            for (ArtifactDependencyModel dependency : buildModel.dependencies().artifacts(COMPILE)) {
                if (Objects.equal(coordinate.getGroupId(), dependency.group().value()) && Objects.equal(coordinate.getArtifactId(), dependency.name().value())) {
                    dependencyFound = true;
                    break;
                }
            }
        }
        if (!dependencyFound) {
            missingLibraries.add(coordinate);
        }
    }
    return missingLibraries;
}
Also used : GradleBuildModel(com.android.tools.idea.gradle.dsl.model.GradleBuildModel) GradleCoordinate(com.android.ide.common.repository.GradleCoordinate) RepositoryUrlManager(com.android.tools.idea.templates.RepositoryUrlManager) AndroidModuleModel(com.android.tools.idea.gradle.project.model.AndroidModuleModel) ArtifactDependencyModel(com.android.tools.idea.gradle.dsl.model.dependencies.ArtifactDependencyModel) NotNull(org.jetbrains.annotations.NotNull)

Example 7 with ArtifactDependencyModel

use of com.android.tools.idea.gradle.dsl.model.dependencies.ArtifactDependencyModel in project android by JetBrains.

the class InferSupportAnnotationsAction method checkModules.

// For Android we need to check SDK version and possibly update the gradle project file
protected boolean checkModules(@NotNull Project project, @NotNull AnalysisScope scope, @NotNull Map<Module, PsiFile> modules) {
    Set<Module> modulesWithoutAnnotations = new HashSet<>();
    Set<Module> modulesWithLowVersion = new HashSet<>();
    for (Module module : modules.keySet()) {
        AndroidModuleInfo info = AndroidModuleInfo.get(module);
        if (info != null && info.getBuildSdkVersion() != null && info.getBuildSdkVersion().getFeatureLevel() < MIN_SDK_WITH_NULLABLE) {
            modulesWithLowVersion.add(module);
        }
        GradleBuildModel buildModel = GradleBuildModel.get(module);
        if (buildModel == null) {
            Logger.getInstance(InferSupportAnnotationsAction.class).warn("Unable to find Gradle build model for module " + module.getModuleFilePath());
            continue;
        }
        boolean dependencyFound = false;
        DependenciesModel dependenciesModel = buildModel.dependencies();
        if (dependenciesModel != null) {
            for (ArtifactDependencyModel dependency : dependenciesModel.artifacts(COMPILE)) {
                String notation = dependency.compactNotation().value();
                if (notation.startsWith(SdkConstants.APPCOMPAT_LIB_ARTIFACT) || notation.startsWith(SdkConstants.SUPPORT_LIB_ARTIFACT) || notation.startsWith(SdkConstants.ANNOTATIONS_LIB_ARTIFACT)) {
                    dependencyFound = true;
                    break;
                }
            }
        }
        if (!dependencyFound) {
            modulesWithoutAnnotations.add(module);
        }
    }
    if (!modulesWithLowVersion.isEmpty()) {
        Messages.showErrorDialog(project, String.format("Infer Support Annotations requires the project sdk level be set to %1$d or greater.", MIN_SDK_WITH_NULLABLE), "Infer Support Annotations");
        return false;
    }
    if (modulesWithoutAnnotations.isEmpty()) {
        return true;
    }
    String moduleNames = StringUtil.join(modulesWithoutAnnotations, Module::getName, ", ");
    int count = modulesWithoutAnnotations.size();
    String message = String.format("The %1$s %2$s %3$sn't refer to the existing '%4$s' library with Android nullity annotations. \n\n" + "Would you like to add the %5$s now?", pluralize("module", count), moduleNames, count > 1 ? "do" : "does", SupportLibrary.SUPPORT_ANNOTATIONS.getArtifactId(), pluralize("dependency", count));
    if (Messages.showOkCancelDialog(project, message, "Infer Nullity Annotations", Messages.getErrorIcon()) == Messages.OK) {
        LocalHistoryAction action = LocalHistory.getInstance().startAction(ADD_DEPENDENCY);
        try {
            new WriteCommandAction(project, ADD_DEPENDENCY) {

                @Override
                protected void run(@NotNull Result result) throws Throwable {
                    RepositoryUrlManager manager = RepositoryUrlManager.get();
                    String annotationsLibraryCoordinate = manager.getLibraryStringCoordinate(SupportLibrary.SUPPORT_ANNOTATIONS, true);
                    for (Module module : modulesWithoutAnnotations) {
                        addDependency(module, annotationsLibraryCoordinate);
                    }
                    GradleSyncInvoker.Request request = new GradleSyncInvoker.Request().setGenerateSourcesOnSuccess(false);
                    GradleSyncInvoker.getInstance().requestProjectSync(project, request, new GradleSyncListener.Adapter() {

                        @Override
                        public void syncSucceeded(@NotNull Project project) {
                            restartAnalysis(project, scope);
                        }
                    });
                }
            }.execute();
        } finally {
            action.finish();
        }
    }
    return false;
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) RepositoryUrlManager(com.android.tools.idea.templates.RepositoryUrlManager) ArtifactDependencyModel(com.android.tools.idea.gradle.dsl.model.dependencies.ArtifactDependencyModel) NotNull(org.jetbrains.annotations.NotNull) Result(com.intellij.openapi.application.Result) AndroidModuleInfo(com.android.tools.idea.model.AndroidModuleInfo) Project(com.intellij.openapi.project.Project) GradleBuildModel(com.android.tools.idea.gradle.dsl.model.GradleBuildModel) LocalHistoryAction(com.intellij.history.LocalHistoryAction) DependenciesModel(com.android.tools.idea.gradle.dsl.model.dependencies.DependenciesModel) Module(com.intellij.openapi.module.Module)

Example 8 with ArtifactDependencyModel

use of com.android.tools.idea.gradle.dsl.model.dependencies.ArtifactDependencyModel in project android by JetBrains.

the class PsLibraryDependency method setVersion.

default default void setVersion(@NotNull String version) {
    boolean modified = false;
    ArtifactDependencyModel reference = null;
    for (DependencyModel parsedDependency : getParsedModels()) {
        if (parsedDependency instanceof ArtifactDependencyModel) {
            ArtifactDependencyModel dependency = (ArtifactDependencyModel) parsedDependency;
            dependency.setVersion(version);
            if (reference == null) {
                reference = dependency;
            }
            modified = true;
        }
    }
    if (modified) {
        GradleVersion parsedVersion = GradleVersion.parse(version);
        PsArtifactDependencySpec resolvedSpec = getResolvedSpec();
        String resolvedVersion = nullToEmpty(resolvedSpec.version);
        if (parsedVersion.compareTo(resolvedVersion) != 0) {
            // Update the "resolved" spec with the new version
            resolvedSpec = new PsArtifactDependencySpec(resolvedSpec.name, resolvedSpec.group, version);
            setResolvedSpec(resolvedSpec);
        }
        setDeclaredSpec(createSpec(reference));
        setModified(true);
        getParent().fireDependencyModifiedEvent((PsDependency) this);
    }
}
Also used : DependencyModel(com.android.tools.idea.gradle.dsl.model.dependencies.DependencyModel) ArtifactDependencyModel(com.android.tools.idea.gradle.dsl.model.dependencies.ArtifactDependencyModel) ArtifactDependencyModel(com.android.tools.idea.gradle.dsl.model.dependencies.ArtifactDependencyModel) GradleVersion(com.android.ide.common.repository.GradleVersion)

Example 9 with ArtifactDependencyModel

use of com.android.tools.idea.gradle.dsl.model.dependencies.ArtifactDependencyModel in project android by JetBrains.

the class PsParsedDependencies method findLibraryDependency.

@Nullable
public ArtifactDependencyModel findLibraryDependency(@NotNull GradleModuleVersion moduleVersion) {
    Collection<ArtifactDependencyModel> potentialMatches = myParsedArtifactDependencies.get(createIdFrom(moduleVersion));
    if (potentialMatches.size() == 1) {
        // Only one found. Just use it.
        return getFirstItem(potentialMatches);
    }
    String version = nullToEmpty(moduleVersion.getVersion());
    Map<GradleVersion, ArtifactDependencyModel> dependenciesByVersion = Maps.newHashMap();
    for (ArtifactDependencyModel potentialMatch : potentialMatches) {
        String potentialVersion = nullToEmpty(potentialMatch.version().value());
        if (version.equals(potentialVersion)) {
            // Perfect version match. Use it.
            return potentialMatch;
        }
        if (isNotEmpty(potentialVersion)) {
            // Collect all the "parsed" dependencies with same group and name, to make a best guess later.
            GradleVersion parsedVersion = GradleVersion.tryParse(potentialVersion);
            if (parsedVersion != null) {
                dependenciesByVersion.put(parsedVersion, potentialMatch);
            }
        }
    }
    if (isNotEmpty(version) && !dependenciesByVersion.isEmpty()) {
        GradleVersion parsedVersion = GradleVersion.tryParse(version);
        if (parsedVersion != null) {
            for (GradleVersion potentialVersion : dependenciesByVersion.keySet()) {
                if (parsedVersion.compareTo(potentialVersion) > 0) {
                    return dependenciesByVersion.get(potentialVersion);
                }
            }
        }
    }
    return null;
}
Also used : ArtifactDependencyModel(com.android.tools.idea.gradle.dsl.model.dependencies.ArtifactDependencyModel) GradleVersion(com.android.ide.common.repository.GradleVersion) Nullable(org.jetbrains.annotations.Nullable)

Example 10 with ArtifactDependencyModel

use of com.android.tools.idea.gradle.dsl.model.dependencies.ArtifactDependencyModel in project android by JetBrains.

the class PsAndroidDependencyCollection method addLibrary.

@Nullable
private PsAndroidDependency addLibrary(@NotNull Library library, @NotNull PsAndroidArtifact artifact) {
    PsParsedDependencies parsedDependencies = myParent.getParsedDependencies();
    MavenCoordinates coordinates = library.getResolvedCoordinates();
    if (coordinates != null) {
        PsArtifactDependencySpec spec = PsArtifactDependencySpec.create(coordinates);
        ArtifactDependencyModel matchingParsedDependency = parsedDependencies.findLibraryDependency(coordinates, artifact::contains);
        if (matchingParsedDependency != null) {
            String parsedVersionValue = matchingParsedDependency.version().value();
            if (parsedVersionValue != null) {
                // The dependency has a version in the build.gradle file.
                // "tryParse" just in case the build.file has an invalid version.
                GradleVersion parsedVersion = GradleVersion.tryParse(parsedVersionValue);
                GradleVersion versionFromGradle = GradleVersion.parse(coordinates.getVersion());
                if (parsedVersion != null && compare(parsedVersion, versionFromGradle) == 0) {
                    // Match.
                    return addLibrary(library, spec, artifact, matchingParsedDependency);
                } else {
                    // Version mismatch. This can happen when the project specifies an artifact version but Gradle uses a different version
                    // from a transitive dependency.
                    // Example:
                    // 1. Module 'app' depends on module 'lib'
                    // 2. Module 'app' depends on Guava 18.0
                    // 3. Module 'lib' depends on Guava 19.0
                    // Gradle will force module 'app' to use Guava 19.0
                    // This is a case that may look as a version mismatch:
                    //
                    // testCompile 'junit:junit:4.11+'
                    // androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
                    //
                    // Here 'espresso' brings junit 4.12, but there is no mismatch with junit 4.11, because they are in different artifacts.
                    PsLibraryAndroidDependency potentialDuplicate = null;
                    for (PsLibraryAndroidDependency dependency : myLibraryDependenciesBySpec.values()) {
                        if (dependency.getParsedModels().contains(matchingParsedDependency)) {
                            potentialDuplicate = dependency;
                            break;
                        }
                    }
                    if (potentialDuplicate != null) {
                    // TODO match ArtifactDependencyModel#configurationName with potentialDuplicate.getContainers().artifact
                    }
                    // Create the dependency model that will be displayed in the "Dependencies" table.
                    addLibrary(library, spec, artifact, matchingParsedDependency);
                    // Create a dependency model for the transitive dependency, so it can be displayed in the "Variants" tool window.
                    return addLibrary(library, spec, artifact, null);
                }
            }
        } else {
            // This dependency was not declared, it could be a transitive one.
            return addLibrary(library, spec, artifact, null);
        }
    }
    return null;
}
Also used : PsArtifactDependencySpec(com.android.tools.idea.gradle.structure.model.PsArtifactDependencySpec) ArtifactDependencyModel(com.android.tools.idea.gradle.dsl.model.dependencies.ArtifactDependencyModel) PsParsedDependencies(com.android.tools.idea.gradle.structure.model.PsParsedDependencies) GradleVersion(com.android.ide.common.repository.GradleVersion) Nullable(org.jetbrains.annotations.Nullable)

Aggregations

ArtifactDependencyModel (com.android.tools.idea.gradle.dsl.model.dependencies.ArtifactDependencyModel)28 GradleBuildModel (com.android.tools.idea.gradle.dsl.model.GradleBuildModel)17 DependenciesModel (com.android.tools.idea.gradle.dsl.model.dependencies.DependenciesModel)12 NotNull (org.jetbrains.annotations.NotNull)7 Project (com.intellij.openapi.project.Project)6 GradleVersion (com.android.ide.common.repository.GradleVersion)5 PsArtifactDependencySpec (com.android.tools.idea.gradle.structure.model.PsArtifactDependencySpec)5 File (java.io.File)5 ArtifactDependencySpec (com.android.tools.idea.gradle.dsl.model.dependencies.ArtifactDependencySpec)4 PsParsedDependencies (com.android.tools.idea.gradle.structure.model.PsParsedDependencies)4 RepositoryUrlManager (com.android.tools.idea.templates.RepositoryUrlManager)4 Module (com.intellij.openapi.module.Module)4 VirtualFile (com.intellij.openapi.vfs.VirtualFile)4 GradleCoordinate (com.android.ide.common.repository.GradleCoordinate)3 ExpectedArtifactDependency (com.android.tools.idea.gradle.dsl.model.dependencies.ArtifactDependencyTest.ExpectedArtifactDependency)3 WriteCommandAction (com.intellij.openapi.command.WriteCommandAction)3 Nullable (org.jetbrains.annotations.Nullable)3 DependencyModel (com.android.tools.idea.gradle.dsl.model.dependencies.DependencyModel)2 AndroidModuleModel (com.android.tools.idea.gradle.project.model.AndroidModuleModel)2 PsProject (com.android.tools.idea.gradle.structure.model.PsProject)2