Search in sources :

Example 1 with DependencyState

use of org.commonjava.maven.ext.core.state.DependencyState in project pom-manipulation-ext by release-engineering.

the class DependencyManipulator method loadRemoteOverrides.

/**
 * This will load the remote overrides. It will first try to load any overrides that might have
 * been prepopulated by the REST scanner, failing that it will load from a remote POM file.
 *
 * @return the loaded overrides
 * @throws ManipulationException if an error occurs.
 */
private Map<ArtifactRef, String> loadRemoteOverrides() throws ManipulationException {
    final DependencyState depState = session.getState(DependencyState.class);
    final RESTState restState = session.getState(RESTState.class);
    final List<ProjectVersionRef> gavs = depState.getRemoteBOMDepMgmt();
    // While in theory we are only mapping ProjectRef -> NewVersion if we store key as ProjectRef we can't then have
    // org.foo:foobar -> 1.2.0.redhat-2
    // org.foo:foobar -> 2.0.0.redhat-2
    // Which is useful for strictAlignment scenarios (although undefined for non-strict).
    Map<ArtifactRef, String> restOverrides = depState.getRemoteRESTOverrides();
    Map<ArtifactRef, String> bomOverrides = new LinkedHashMap<>();
    Map<ArtifactRef, String> mergedOverrides = new LinkedHashMap<>();
    if (gavs != null) {
        final ListIterator<ProjectVersionRef> iter = gavs.listIterator(gavs.size());
        // Iterate in reverse order so that the first GAV in the list overwrites the last
        while (iter.hasPrevious()) {
            final ProjectVersionRef ref = iter.previous();
            Map<ArtifactRef, String> rBom = effectiveModelBuilder.getRemoteDependencyVersionOverrides(ref);
            // We don't normalise the BOM list here as ::applyOverrides can handle multiple GA with different V
            // for strict override. However, it is undefined if strict is not enabled.
            bomOverrides.putAll(rBom);
        }
    }
    if (depState.getPrecedence() == DependencyPrecedence.BOM) {
        mergedOverrides = bomOverrides;
        if (mergedOverrides.isEmpty()) {
            String msg = restState.isEnabled() ? "dependencySource for restURL" : "dependencyManagement";
            logger.warn("No dependencies found for dependencySource {}. Has {} been configured? ", depState.getPrecedence(), msg);
        }
    }
    if (depState.getPrecedence() == DependencyPrecedence.REST) {
        mergedOverrides = restOverrides;
        if (mergedOverrides.isEmpty()) {
            logger.warn("No dependencies found for dependencySource {}. Has restURL been configured? ", depState.getPrecedence());
        }
    } else if (depState.getPrecedence() == DependencyPrecedence.RESTBOM) {
        mergedOverrides = bomOverrides;
        removeDuplicateArtifacts(mergedOverrides, restOverrides);
        mergedOverrides.putAll(restOverrides);
    } else if (depState.getPrecedence() == DependencyPrecedence.BOMREST) {
        mergedOverrides = restOverrides;
        removeDuplicateArtifacts(mergedOverrides, bomOverrides);
        mergedOverrides.putAll(bomOverrides);
    }
    logger.info("Remote precedence is {}", depState.getPrecedence());
    logger.debug("Final remote override list is {}", mergedOverrides);
    return mergedOverrides;
}
Also used : DependencyState(org.commonjava.maven.ext.core.state.DependencyState) ProjectVersionRef(org.commonjava.maven.atlas.ident.ref.ProjectVersionRef) RESTState(org.commonjava.maven.ext.core.state.RESTState) ArtifactRef(org.commonjava.maven.atlas.ident.ref.ArtifactRef) SimpleArtifactRef(org.commonjava.maven.atlas.ident.ref.SimpleArtifactRef) LinkedHashMap(java.util.LinkedHashMap)

Example 2 with DependencyState

use of org.commonjava.maven.ext.core.state.DependencyState in project pom-manipulation-ext by release-engineering.

the class DependencyManipulator method internalApplyChanges.

private Set<Project> internalApplyChanges(final List<Project> projects, Map<ArtifactRef, String> overrides) throws ManipulationException {
    final DependencyState state = session.getState(DependencyState.class);
    final Set<Project> result = new HashSet<>();
    for (final Project project : projects) {
        final Model model = project.getModel();
        if (!overrides.isEmpty() || !state.getDependencyExclusions().isEmpty()) {
            apply(project, model, overrides);
            result.add(project);
        }
    }
    // If we've changed something now update any old properties with the new values.
    if (!result.isEmpty()) {
        logger.info("Iterating for standard overrides...");
        for (Project project : versionPropertyUpdateMap.keySet()) {
            logger.debug("Checking property override within project {} ", project);
            for (final Map.Entry<String, String> entry : versionPropertyUpdateMap.get(project).entrySet()) {
                PropertiesUtils.PropertyUpdate found = PropertiesUtils.updateProperties(session, project, false, entry.getKey(), entry.getValue());
                if (found == PropertiesUtils.PropertyUpdate.NOTFOUND) {
                    // Problem in this scenario is that we know we have a property update map but we have not found a
                    // property to update. Its possible this property has been inherited from a parent. Override in the
                    // top pom for safety.
                    logger.info("Unable to find a property for {} to update", entry.getKey());
                    logger.info("Adding property {} with {} ", entry.getKey(), entry.getValue());
                    // We know the inheritance root is at position 0 in the inherited list...
                    project.getInheritedList().get(0).getModel().getProperties().setProperty(entry.getKey(), entry.getValue());
                }
            }
        }
        logger.info("Iterating for explicit overrides...");
        for (Project project : explicitVersionPropertyUpdateMap.keySet()) {
            logger.debug("Checking property override within project {} ", project);
            for (final Map.Entry<String, String> entry : explicitVersionPropertyUpdateMap.get(project).entrySet()) {
                PropertiesUtils.PropertyUpdate found = PropertiesUtils.updateProperties(session, project, true, entry.getKey(), entry.getValue());
                if (found == PropertiesUtils.PropertyUpdate.NOTFOUND) {
                    // Problem in this scenario is that we know we have a property update map but we have not found a
                    // property to update. Its possible this property has been inherited from a parent. Override in the
                    // top pom for safety.
                    logger.info("Unable to find a property for {} to update for explicit overrides", entry.getKey());
                    logger.info("Adding property {} with {} ", entry.getKey(), entry.getValue());
                    // We know the inheritance root is at position 0 in the inherited list...
                    project.getInheritedList().get(0).getModel().getProperties().setProperty(entry.getKey(), entry.getValue());
                }
            }
        }
    }
    return result;
}
Also used : Project(org.commonjava.maven.ext.common.model.Project) DependencyState(org.commonjava.maven.ext.core.state.DependencyState) Model(org.apache.maven.model.Model) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) WildcardMap(org.commonjava.maven.ext.core.util.WildcardMap) PropertiesUtils(org.commonjava.maven.ext.core.util.PropertiesUtils) HashSet(java.util.HashSet)

Example 3 with DependencyState

use of org.commonjava.maven.ext.core.state.DependencyState in project pom-manipulation-ext by release-engineering.

the class RelocationManipulator method updateDependencyExclusion.

/**
 * @param depPvr the resolved dependency we are processing the exclusion for.
 * @param relocation Map containing the update information for relocations.
 */
private void updateDependencyExclusion(ProjectVersionRef depPvr, ProjectVersionRef relocation) {
    final DependencyState state = session.getState(DependencyState.class);
    if (relocation.getVersionString().equals(WildcardMap.WILDCARD)) {
        logger.debug("No version alignment to perform for relocations");
    } else {
        String artifact = depPvr.getArtifactId();
        if (!relocation.getArtifactId().equals(WildcardMap.WILDCARD)) {
            artifact = relocation.getArtifactId();
        }
        logger.debug("Adding dependencyOverride {} & {}", relocation.getGroupId() + ':' + artifact + "@*", relocation.getVersionString());
        state.updateExclusions(relocation.getGroupId() + ':' + artifact + "@*", relocation.getVersionString());
    }
}
Also used : DependencyState(org.commonjava.maven.ext.core.state.DependencyState)

Example 4 with DependencyState

use of org.commonjava.maven.ext.core.state.DependencyState in project pom-manipulation-ext by release-engineering.

the class DependencyManipulator method apply.

/**
 * Applies dependency overrides to the project.
 */
private void apply(final Project project, final Model model, final Map<ArtifactRef, String> overrides) throws ManipulationException {
    // Map of Group : Map of artifactId [ may be wildcard ] : value
    final WildcardMap<String> explicitOverrides = new WildcardMap<>();
    final String projectGA = ga(project);
    final DependencyState dependencyState = session.getState(DependencyState.class);
    final CommonState commonState = session.getState(CommonState.class);
    logger.info("Processing project {} ", projectGA);
    Map<ArtifactRef, String> moduleOverrides = new LinkedHashMap<>(overrides);
    moduleOverrides = removeReactorGAs(moduleOverrides);
    try {
        moduleOverrides = applyModuleVersionOverrides(projectGA, dependencyState.getDependencyExclusions(), moduleOverrides, explicitOverrides);
        logger.debug("Module overrides are:\n{}", moduleOverrides);
        logger.debug("Explicit overrides are:\n{}", explicitOverrides);
    } catch (InvalidRefException e) {
        logger.error("Invalid module exclusion override {} : {} ", moduleOverrides, explicitOverrides);
        throw e;
    }
    if (project.isInheritanceRoot()) {
        // Handle the situation where the top level parent refers to a prior build that is in the BOM.
        if (project.getModelParent() != null) {
            for (Map.Entry<ArtifactRef, String> entry : moduleOverrides.entrySet()) {
                String oldValue = project.getModelParent().getVersion();
                String newValue = entry.getValue();
                if (entry.getKey().asProjectRef().equals(SimpleProjectRef.parse(ga(project.getModelParent())))) {
                    if (commonState.getStrict()) {
                        if (!PropertiesUtils.checkStrictValue(session, oldValue, newValue)) {
                            if (commonState.getFailOnStrictViolation()) {
                                throw new ManipulationException("Parent reference {} replacement: {} of original version: {} violates the strict version-alignment rule!", ga(project.getModelParent()), newValue, oldValue);
                            } else {
                                logger.warn("Parent reference {} replacement: {} of original version: {} violates the strict version-alignment rule!", ga(project.getModelParent()), newValue, oldValue);
                                // a new property either.
                                continue;
                            }
                        }
                    }
                    logger.debug(" Modifying parent reference from {} to {} for {} ", model.getParent().getVersion(), newValue, ga(project.getModelParent()));
                    model.getParent().setVersion(newValue);
                    break;
                }
            }
            // Apply any explicit overrides to the top level parent. Convert it to a simulated
            // dependency so we can reuse applyExplicitOverrides.
            HashMap<ArtifactRef, Dependency> pDepMap = new HashMap<>();
            Dependency d = new Dependency();
            d.setGroupId(project.getModelParent().getGroupId());
            d.setArtifactId(project.getModelParent().getArtifactId());
            d.setVersion(project.getModelParent().getVersion());
            pDepMap.put(SimpleArtifactRef.parse(d.getManagementKey()), d);
            applyExplicitOverrides(project, pDepMap, explicitOverrides, commonState, explicitVersionPropertyUpdateMap);
            project.getModelParent().setVersion(d.getVersion());
        }
        if (session.getState(DependencyState.class).getOverrideDependencies()) {
            // Apply overrides to project dependency management
            logger.debug("Applying overrides to managed dependencies for: {}", projectGA);
            final Map<ArtifactRef, String> nonMatchingVersionOverrides = applyOverrides(project, project.getResolvedManagedDependencies(session), explicitOverrides, moduleOverrides);
            final Map<ArtifactRef, String> matchedOverrides = new LinkedHashMap<>(moduleOverrides);
            matchedOverrides.keySet().removeAll(nonMatchingVersionOverrides.keySet());
            applyExplicitOverrides(project, project.getResolvedManagedDependencies(session), explicitOverrides, commonState, explicitVersionPropertyUpdateMap);
            if (commonState.getOverrideTransitive()) {
                final List<Dependency> extraDeps = new ArrayList<>();
                // Add dependencies to Dependency Management which did not match any existing dependency
                for (final ArtifactRef var : overrides.keySet()) {
                    if (!nonMatchingVersionOverrides.containsKey(var)) {
                        // This one in the remote pom was already dealt with ; continue.
                        continue;
                    }
                    final Dependency newDependency = new Dependency();
                    newDependency.setGroupId(var.getGroupId());
                    newDependency.setArtifactId(var.getArtifactId());
                    newDependency.setType(var.getType());
                    newDependency.setClassifier(var.getClassifier());
                    final String artifactVersion = moduleOverrides.get(var);
                    newDependency.setVersion(artifactVersion);
                    extraDeps.add(newDependency);
                    logger.debug("New entry added to <DependencyManagement/> - {} : {} ", var, artifactVersion);
                }
                // If the model doesn't have any Dependency Management set by default, create one for it
                DependencyManagement dependencyManagement = model.getDependencyManagement();
                if (extraDeps.size() > 0) {
                    if (dependencyManagement == null) {
                        dependencyManagement = new DependencyManagement();
                        model.setDependencyManagement(dependencyManagement);
                        logger.debug("Added <DependencyManagement/> for current project");
                    }
                    dependencyManagement.getDependencies().addAll(0, extraDeps);
                }
            } else {
                logger.debug("Non-matching dependencies ignored.");
            }
        } else {
            logger.debug("NOT applying overrides to managed dependencies for top-pom: {}", projectGA);
        }
    } else {
        // If a child module has a depMgmt section we'll change that as well.
        if (session.getState(DependencyState.class).getOverrideDependencies()) {
            logger.debug("Applying overrides to managed dependencies for: {}", projectGA);
            applyOverrides(project, project.getResolvedManagedDependencies(session), explicitOverrides, moduleOverrides);
            applyExplicitOverrides(project, project.getResolvedManagedDependencies(session), explicitOverrides, commonState, explicitVersionPropertyUpdateMap);
        } else {
            logger.debug("NOT applying overrides to managed dependencies for: {}", projectGA);
        }
    }
    if (session.getState(DependencyState.class).getOverrideDependencies()) {
        logger.debug("Applying overrides to concrete dependencies for: {}", projectGA);
        // Apply overrides to project direct dependencies
        applyOverrides(project, project.getResolvedDependencies(session), explicitOverrides, moduleOverrides);
        applyExplicitOverrides(project, project.getResolvedDependencies(session), explicitOverrides, commonState, explicitVersionPropertyUpdateMap);
        final HashMap<Profile, HashMap<ArtifactRef, Dependency>> pd = project.getResolvedProfileDependencies(session);
        final HashMap<Profile, HashMap<ArtifactRef, Dependency>> pmd = project.getResolvedProfileManagedDependencies(session);
        for (Profile p : pd.keySet()) {
            applyOverrides(project, pd.get(p), explicitOverrides, moduleOverrides);
            applyExplicitOverrides(project, pd.get(p), explicitOverrides, commonState, explicitVersionPropertyUpdateMap);
        }
        for (Profile p : pmd.keySet()) {
            applyOverrides(project, pmd.get(p), explicitOverrides, moduleOverrides);
            applyExplicitOverrides(project, pmd.get(p), explicitOverrides, commonState, explicitVersionPropertyUpdateMap);
        }
    } else {
        logger.debug("NOT applying overrides to concrete dependencies for: {}", projectGA);
    }
}
Also used : CommonState(org.commonjava.maven.ext.core.state.CommonState) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) InvalidRefException(org.commonjava.maven.atlas.ident.ref.InvalidRefException) ArrayList(java.util.ArrayList) Dependency(org.apache.maven.model.Dependency) Profile(org.apache.maven.model.Profile) ArtifactRef(org.commonjava.maven.atlas.ident.ref.ArtifactRef) SimpleArtifactRef(org.commonjava.maven.atlas.ident.ref.SimpleArtifactRef) LinkedHashMap(java.util.LinkedHashMap) WildcardMap(org.commonjava.maven.ext.core.util.WildcardMap) DependencyState(org.commonjava.maven.ext.core.state.DependencyState) ManipulationException(org.commonjava.maven.ext.common.ManipulationException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) WildcardMap(org.commonjava.maven.ext.core.util.WildcardMap) DependencyManagement(org.apache.maven.model.DependencyManagement)

Example 5 with DependencyState

use of org.commonjava.maven.ext.core.state.DependencyState in project pom-manipulation-ext by release-engineering.

the class DependencyManipulator method init.

/**
 * Initialize the {@link DependencyState} state holder in the {@link ManipulationSession}. This state holder detects
 * version-change configuration from the Maven user properties (-D properties from the CLI) and makes it available for
 * later.
 */
@Override
public void init(final ManipulationSession session) throws ManipulationException {
    session.setState(new DependencyState(session.getUserProperties()));
    this.session = session;
}
Also used : DependencyState(org.commonjava.maven.ext.core.state.DependencyState)

Aggregations

DependencyState (org.commonjava.maven.ext.core.state.DependencyState)7 HashMap (java.util.HashMap)3 LinkedHashMap (java.util.LinkedHashMap)3 ArtifactRef (org.commonjava.maven.atlas.ident.ref.ArtifactRef)3 SimpleArtifactRef (org.commonjava.maven.atlas.ident.ref.SimpleArtifactRef)3 ArrayList (java.util.ArrayList)2 Map (java.util.Map)2 ProjectVersionRef (org.commonjava.maven.atlas.ident.ref.ProjectVersionRef)2 Project (org.commonjava.maven.ext.common.model.Project)2 CommonState (org.commonjava.maven.ext.core.state.CommonState)2 RESTState (org.commonjava.maven.ext.core.state.RESTState)2 VersioningState (org.commonjava.maven.ext.core.state.VersioningState)2 WildcardMap (org.commonjava.maven.ext.core.util.WildcardMap)2 HashSet (java.util.HashSet)1 DefaultMavenExecutionRequest (org.apache.maven.execution.DefaultMavenExecutionRequest)1 DefaultMavenExecutionResult (org.apache.maven.execution.DefaultMavenExecutionResult)1 MavenExecutionRequest (org.apache.maven.execution.MavenExecutionRequest)1 MavenSession (org.apache.maven.execution.MavenSession)1 Dependency (org.apache.maven.model.Dependency)1 DependencyManagement (org.apache.maven.model.DependencyManagement)1