Search in sources :

Example 31 with Project

use of org.commonjava.maven.ext.common.model.Project in project pom-manipulation-ext by release-engineering.

the class PomIO method readModelsForManipulation.

/**
 * Read {@link Model} instances by parsing the POM directly. This is useful to escape some post-processing that happens when the
 * {@link MavenProject#getOriginalModel()} instance is set.
 *
 * @param executionRoot the top level pom file.
 * @param peeked a collection of poms resolved from the top level file.
 * @return a collection of Projects
 * @throws ManipulationException if an error occurs.
 */
private List<Project> readModelsForManipulation(File executionRoot, final List<PomPeek> peeked) throws ManipulationException {
    final List<Project> projects = new ArrayList<>();
    final HashMap<Project, ProjectVersionRef> projectToParent = new HashMap<>();
    for (final PomPeek peek : peeked) {
        final File pom = peek.getPom();
        // Sucks, but we have to brute-force reading in the raw model.
        // The effective-model building, below, has a tantalizing getRawModel()
        // method on the result, BUT this seems to return models that have
        // the plugin versions set inside profiles...so they're not entirely
        // raw.
        Model raw = null;
        InputStream in = null;
        try {
            in = new FileInputStream(pom);
            raw = new MavenXpp3Reader().read(in);
        } catch (final IOException | XmlPullParserException e) {
            throw new ManipulationException("Failed to build model for POM: %s.\n--> %s", e, pom, e.getMessage());
        } finally {
            closeQuietly(in);
        }
        if (raw == null) {
            continue;
        }
        final Project project = new Project(pom, raw);
        projectToParent.put(project, peek.getParentKey());
        project.setInheritanceRoot(peek.isInheritanceRoot());
        if (executionRoot.equals(pom)) {
            logger.debug("Setting execution root to {} with file {}" + (project.isInheritanceRoot() ? " and is the inheritance root. " : ""), project, pom);
            project.setExecutionRoot();
            try {
                if (FileUtils.readFileToString(pom).contains(MODIFIED_BY)) {
                    project.setIncrementalPME(true);
                }
            } catch (final IOException e) {
                throw new ManipulationException("Failed to read POM: %s", e, pom);
            }
        }
        projects.add(project);
    }
    // Fill out inheritance info for every project we have created.
    for (Project p : projects) {
        ProjectVersionRef pvr = projectToParent.get(p);
        p.setProjectParent(getParent(projects, pvr));
    }
    return projects;
}
Also used : HashMap(java.util.HashMap) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) MavenXpp3Reader(org.apache.maven.model.io.xpp3.MavenXpp3Reader) PomPeek(org.commonjava.maven.galley.maven.parse.PomPeek) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) MavenProject(org.apache.maven.project.MavenProject) Project(org.commonjava.maven.ext.common.model.Project) ProjectVersionRef(org.commonjava.maven.atlas.ident.ref.ProjectVersionRef) Model(org.apache.maven.model.Model) ManipulationException(org.commonjava.maven.ext.common.ManipulationException) XmlPullParserException(org.codehaus.plexus.util.xml.pull.XmlPullParserException) File(java.io.File)

Example 32 with Project

use of org.commonjava.maven.ext.common.model.Project in project pom-manipulation-ext by release-engineering.

the class PomIO method rewritePOMs.

/**
 * For any project listed as changed (tracked by GA in the session), write the modified model out to disk.
 * Uses JDOM {@link ModelWriter} and {@link MavenJDOMWriter} to preserve as much formatting as possible.
 *
 * @param changed the modified Projects to write out.
 * @return gav execution root GAV
 * @throws ManipulationException if an error occurs.
 */
public GAV rewritePOMs(final Set<Project> changed) throws ManipulationException {
    GAV result = null;
    for (final Project project : changed) {
        if (project.isExecutionRoot()) {
            result = new GAV(Project.modelKey(project.getModel()));
        }
        logger.debug(String.format("%s modified! Rewriting.", project));
        File pom = project.getPom();
        final Model model = project.getModel();
        logger.trace("Rewriting: " + model.toString() + " in place of: " + project.getId() + "\n       to POM: " + pom);
        write(project, pom, model);
        // This is a total hack, but the alternative seems to be adding complexity through a custom model processor.
        if (pom.getName().equals("interpolated-pom.xml")) {
            final File dir = pom.getParentFile();
            pom = dir == null ? new File("pom.xml") : new File(dir, "pom.xml");
            write(project, pom, model);
        }
    }
    return result;
}
Also used : MavenProject(org.apache.maven.project.MavenProject) Project(org.commonjava.maven.ext.common.model.Project) Model(org.apache.maven.model.Model) GAV(org.commonjava.maven.ext.common.model.GAV) File(java.io.File)

Example 33 with Project

use of org.commonjava.maven.ext.common.model.Project in project pom-manipulation-ext by release-engineering.

the class DependencyManipulator method removeReactorGAs.

/**
 * Remove version overrides which refer to projects in the current reactor.
 * Projects in the reactor include things like inter-module dependencies
 * which should never be overridden.
 * @param versionOverrides current set of ArtifactRef:newVersion overrides.
 * @return A new Map with the reactor GAs removed.
 */
private Map<ArtifactRef, String> removeReactorGAs(final Map<ArtifactRef, String> versionOverrides) throws ManipulationException {
    final Map<ArtifactRef, String> reducedVersionOverrides = new LinkedHashMap<>(versionOverrides);
    for (final Project project : session.getProjects()) {
        final String reactorGA = gav(project.getModel());
        reducedVersionOverrides.remove(SimpleArtifactRef.parse(reactorGA));
    }
    return reducedVersionOverrides;
}
Also used : Project(org.commonjava.maven.ext.common.model.Project) ArtifactRef(org.commonjava.maven.atlas.ident.ref.ArtifactRef) SimpleArtifactRef(org.commonjava.maven.atlas.ident.ref.SimpleArtifactRef) LinkedHashMap(java.util.LinkedHashMap)

Example 34 with Project

use of org.commonjava.maven.ext.common.model.Project in project pom-manipulation-ext by release-engineering.

the class RESTCollector method collect.

/**
 * Prescans the Project to build up a list of Project GAs and also the various Dependencies.
 */
private void collect(final List<Project> projects) throws ManipulationException {
    final RESTState state = session.getState(RESTState.class);
    final VersioningState vs = session.getState(VersioningState.class);
    final DependencyState ds = session.getState(DependencyState.class);
    final PluginState ps = session.getState(PluginState.class);
    if (!session.isEnabled() || !state.isEnabled()) {
        logger.debug(getClass().getSimpleName() + ": Nothing to do!");
        return;
    }
    final ArrayList<ProjectVersionRef> restParam = new ArrayList<>();
    final ArrayList<ProjectVersionRef> newProjectKeys = new ArrayList<>();
    final String override = vs.getOverride();
    for (final Project project : projects) {
        if (isEmpty(override)) {
            // TODO: Check this : For the rest API I think we need to check every project GA not just inheritance root.
            // Strip SNAPSHOT from the version for matching. DA will handle OSGi conversion.
            ProjectVersionRef newKey = new SimpleProjectVersionRef(project.getKey());
            if (project.getKey().getVersionString().endsWith("-SNAPSHOT")) {
                if (!vs.preserveSnapshot()) {
                    newKey = new SimpleProjectVersionRef(project.getKey().asProjectRef(), project.getKey().getVersionString().substring(0, project.getKey().getVersionString().indexOf("-SNAPSHOT")));
                } else {
                    logger.warn("SNAPSHOT detected for REST call but preserve-snapshots is enabled.");
                }
            }
            newProjectKeys.add(newKey);
        } else if (project.isExecutionRoot()) {
            // We want to manually override the version ; therefore ignore what is in the project and calculate potential
            // matches for that instead.
            Project p = projects.get(0);
            newProjectKeys.add(new SimpleProjectVersionRef(p.getGroupId(), p.getArtifactId(), override));
        }
    }
    restParam.addAll(newProjectKeys);
    // We only recognise dependencyManagement of the form g:a:version-rebuild not g:a:version-rebuild-<numeric>.
    for (ProjectVersionRef bom : (ds.getRemoteBOMDepMgmt() == null ? Collections.<ProjectVersionRef>emptyList() : ds.getRemoteBOMDepMgmt())) {
        if (!Version.hasBuildNumber(bom.getVersionString()) && bom.getVersionString().contains(PropertiesUtils.getSuffix(session))) {
            // Create the dummy PVR to send to DA (which requires a numeric suffix).
            ProjectVersionRef newBom = new SimpleProjectVersionRef(bom.asProjectRef(), bom.getVersionString() + "-0");
            logger.debug("Adding dependencyManagement BOM {} into REST call.", newBom);
            restParam.add(newBom);
        }
    }
    Set<ArtifactRef> localDeps = establishAllDependencies(session, projects, null);
    // Need to send that to the rest interface to get a translation.
    for (ArtifactRef p : localDeps) {
        restParam.add(p.asProjectVersionRef());
    }
    // Call the REST to populate the result.
    logger.debug("Passing {} GAVs following into the REST client api {} ", restParam.size(), restParam);
    logger.info("Calling REST client...");
    long start = System.nanoTime();
    Map<ProjectVersionRef, String> restResult = null;
    try {
        restResult = state.getVersionTranslator().translateVersions(restParam);
    } finally {
        printFinishTime(start, (restResult != null));
    }
    logger.debug("REST Client returned {} ", restResult);
    // Process rest result for boms
    ListIterator<ProjectVersionRef> iterator = (ds.getRemoteBOMDepMgmt() == null ? Collections.<ProjectVersionRef>emptyList().listIterator() : ds.getRemoteBOMDepMgmt().listIterator());
    while (iterator.hasNext()) {
        ProjectVersionRef pvr = iterator.next();
        // As before, only process the BOMs if they are of the format <rebuild suffix> without a numeric portion.
        if (!Version.hasBuildNumber(pvr.getVersionString()) && pvr.getVersionString().contains(PropertiesUtils.getSuffix(session))) {
            // Create the dummy PVR to compare with results to...
            ProjectVersionRef newBom = new SimpleProjectVersionRef(pvr.asProjectRef(), pvr.getVersionString() + "-0");
            if (restResult.keySet().contains(newBom)) {
                ProjectVersionRef replacementBOM = new SimpleProjectVersionRef(pvr.asProjectRef(), restResult.get(newBom));
                logger.debug("Replacing BOM value of {} with {}.", pvr, replacementBOM);
                iterator.remove();
                iterator.add(replacementBOM);
            }
        }
    }
    vs.setRESTMetadata(parseVersions(session, projects, state, newProjectKeys, restResult));
    final Map<ArtifactRef, String> overrides = new HashMap<>();
    // Convert the loaded remote ProjectVersionRefs to the original ArtifactRefs
    for (ArtifactRef a : localDeps) {
        if (restResult.containsKey(a.asProjectVersionRef())) {
            overrides.put(a, restResult.get(a.asProjectVersionRef()));
        }
    }
    logger.debug("Setting REST Overrides {} ", overrides);
    ds.setRemoteRESTOverrides(overrides);
    // Unfortunately as everything is just GAVs we have to send everything to the PluginManipulator as well.
    ps.setRemoteRESTOverrides(overrides);
}
Also used : PluginState(org.commonjava.maven.ext.core.state.PluginState) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SimpleProjectVersionRef(org.commonjava.maven.atlas.ident.ref.SimpleProjectVersionRef) ArtifactRef(org.commonjava.maven.atlas.ident.ref.ArtifactRef) SimpleScopedArtifactRef(org.commonjava.maven.ext.common.model.SimpleScopedArtifactRef) SimpleArtifactRef(org.commonjava.maven.atlas.ident.ref.SimpleArtifactRef) Project(org.commonjava.maven.ext.common.model.Project) DependencyState(org.commonjava.maven.ext.core.state.DependencyState) ProjectVersionRef(org.commonjava.maven.atlas.ident.ref.ProjectVersionRef) SimpleProjectVersionRef(org.commonjava.maven.atlas.ident.ref.SimpleProjectVersionRef) VersioningState(org.commonjava.maven.ext.core.state.VersioningState) RESTState(org.commonjava.maven.ext.core.state.RESTState)

Example 35 with Project

use of org.commonjava.maven.ext.common.model.Project in project pom-manipulation-ext by release-engineering.

the class JSONManipulatorTest method testNotFound.

@Test(expected = ManipulationException.class)
public void testNotFound() throws Exception {
    String modifyPath = "$.I.really.do.not.exist.repository.url";
    File target = tf.newFile();
    FileUtils.copyFile(npmFile, target);
    Project project = new Project(null, target, null);
    jsonManipulator.internalApplyChanges(project, new JSONState.JSONOperation(target.getName(), modifyPath, null));
}
Also used : Project(org.commonjava.maven.ext.common.model.Project) File(java.io.File) JSONState(org.commonjava.maven.ext.core.state.JSONState) Test(org.junit.Test) JSONIOTest(org.commonjava.maven.ext.io.JSONIOTest)

Aggregations

Project (org.commonjava.maven.ext.common.model.Project)56 Model (org.apache.maven.model.Model)27 Test (org.junit.Test)25 HashSet (java.util.HashSet)21 File (java.io.File)19 HashMap (java.util.HashMap)11 ManipulationSession (org.commonjava.maven.ext.core.ManipulationSession)9 Profile (org.apache.maven.model.Profile)7 ManipulationException (org.commonjava.maven.ext.common.ManipulationException)7 PomIO (org.commonjava.maven.ext.io.PomIO)7 ArrayList (java.util.ArrayList)6 Properties (java.util.Properties)6 ArtifactRef (org.commonjava.maven.atlas.ident.ref.ArtifactRef)6 ProjectVersionRef (org.commonjava.maven.atlas.ident.ref.ProjectVersionRef)6 Map (java.util.Map)5 Dependency (org.apache.maven.model.Dependency)5 SimpleProjectVersionRef (org.commonjava.maven.atlas.ident.ref.SimpleProjectVersionRef)5 SimpleArtifactRef (org.commonjava.maven.atlas.ident.ref.SimpleArtifactRef)4 DependencyState (org.commonjava.maven.ext.core.state.DependencyState)4 IOException (java.io.IOException)3