diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/api/AbstractVersionDetails.java b/versions-common/src/main/java/org/codehaus/mojo/versions/api/AbstractVersionDetails.java index 02f7bae7d..77b54464d 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/api/AbstractVersionDetails.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/api/AbstractVersionDetails.java @@ -19,12 +19,7 @@ * under the License. */ -import java.util.Arrays; -import java.util.Collections; -import java.util.Iterator; -import java.util.Objects; -import java.util.Optional; -import java.util.TreeSet; +import java.util.*; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -64,45 +59,64 @@ public abstract class AbstractVersionDetails implements VersionDetails { */ private ArtifactVersion currentVersion = null; + private VersionRange currentVersionRange = null; protected boolean verboseDetail = true; protected AbstractVersionDetails() {} - @Override - public Restriction restrictionFor(Optional scope) throws InvalidSegmentException { - // one range spec can have multiple restrictions, and multiple 'lower bound', we want the highest one. - // [1.0,2.0),[3.0,4.0) -> 3.0 - ArtifactVersion highestLowerBound = currentVersion; - if (currentVersion != null) { - try { - highestLowerBound = - VersionRange.createFromVersionSpec(currentVersion.toString()).getRestrictions().stream() - .map(Restriction::getLowerBound) - .filter(Objects::nonNull) - .max(getVersionComparator()) - .orElse(currentVersion); - } catch (InvalidVersionSpecificationException ignored) { - ignored.printStackTrace(System.err); - } - } - - final ArtifactVersion currentVersion = highestLowerBound; - ArtifactVersion nextVersion = scope.filter(s -> s.isMajorTo(SUBINCREMENTAL)) - .map(s -> (ArtifactVersion) new BoundArtifactVersion(currentVersion, Segment.of(s.value() + 1))) + /** + *

One range spec can have multiple restrictions, and multiple 'lower bound', we want the highest one.

+ *

[1.0,2.0),[3.0,4.0) -> 3.0

+ * @param versionSpec version specification, possibly containing multiple ranges + * @return highest lower bound of the given version specification + */ + private ArtifactVersion getHighestLowerBound() { + return currentVersionRange.getRestrictions().stream() + .map(Restriction::getLowerBound) + .filter(Objects::nonNull) + .max(getVersionComparator()) .orElse(currentVersion); + } + + @Override + public Restriction restrictionForSelectedSegment(Optional selectedSegment) throws InvalidSegmentException { + ArtifactVersion highestLowerBound = getHighestLowerBound(); + ArtifactVersion nextVersion = selectedSegment + .filter(s -> s.isMajorTo(SUBINCREMENTAL)) + .map(Segment::minorTo) + .map(s -> (ArtifactVersion) new BoundArtifactVersion(highestLowerBound, s)) + .orElse(highestLowerBound); return new Restriction( nextVersion, false, - scope.filter(MAJOR::isMajorTo) - .map(s -> (ArtifactVersion) new BoundArtifactVersion(currentVersion, s)) + selectedSegment + .filter(MAJOR::isMajorTo) + .map(s -> (ArtifactVersion) new BoundArtifactVersion(highestLowerBound, s)) .orElse(null), false); } + @Override + public Restriction restrictionForUnchangedSegment(Optional unchangedSegment, boolean allowDowngrade) + throws InvalidSegmentException { + ArtifactVersion highestLowerBound = getHighestLowerBound(); + ArtifactVersion lowerBound = allowDowngrade + ? getLowerBound(highestLowerBound, unchangedSegment) + .map(DefaultArtifactVersionCache::of) + .orElse(null) + : highestLowerBound; + ArtifactVersion upperBound = unchangedSegment + .map(s -> (ArtifactVersion) new BoundArtifactVersion( + highestLowerBound, s.isMajorTo(SUBINCREMENTAL) ? Segment.minorTo(s) : s)) + .orElse(null); + return new Restriction(lowerBound, allowDowngrade, upperBound, allowDowngrade); + } + @Override public Restriction restrictionForIgnoreScope(Optional ignored) { - ArtifactVersion nextVersion = ignored.map(s -> (ArtifactVersion) new BoundArtifactVersion(currentVersion, s)) - .orElse(currentVersion); + ArtifactVersion highestLowerBound = getHighestLowerBound(); + ArtifactVersion nextVersion = ignored.map(s -> (ArtifactVersion) new BoundArtifactVersion(highestLowerBound, s)) + .orElse(highestLowerBound); return new Restriction(nextVersion, false, null, false); } @@ -119,6 +133,11 @@ public final ArtifactVersion getCurrentVersion() { @Override public final void setCurrentVersion(ArtifactVersion currentVersion) { this.currentVersion = currentVersion; + try { + currentVersionRange = VersionRange.createFromVersionSpec(currentVersion.toString()); + } catch (InvalidVersionSpecificationException e) { + e.printStackTrace(); + } } @Override @@ -216,8 +235,8 @@ public final ArtifactVersion[] getNewerVersions( .orElse(null) : currentVersion; ArtifactVersion upperBound = unchangedSegment - .map(s -> (ArtifactVersion) new BoundArtifactVersion( - currentVersion, s.isMajorTo(SUBINCREMENTAL) ? Segment.of(s.value() + 1) : s)) + .map(s -> (ArtifactVersion) + new BoundArtifactVersion(currentVersion, s.isMajorTo(SUBINCREMENTAL) ? Segment.minorTo(s) : s)) .orElse(null); Restriction restriction = new Restriction(lowerBound, allowDowngrade, upperBound, allowDowngrade); @@ -226,26 +245,22 @@ public final ArtifactVersion[] getNewerVersions( @Override public Optional getNewestVersion( - String versionString, Optional upperBoundSegment, boolean includeSnapshots, boolean allowDowngrade) + Optional unchangedSegment, boolean includeSnapshots, boolean allowDowngrade) throws InvalidSegmentException { - ArtifactVersion currentVersion = DefaultArtifactVersionCache.of(versionString); - ArtifactVersion lowerBound = allowDowngrade - ? getLowerBound(currentVersion, upperBoundSegment) - .map(DefaultArtifactVersionCache::of) - .orElse(null) - : currentVersion; - ArtifactVersion upperBound = upperBoundSegment - .map(s -> (ArtifactVersion) new BoundArtifactVersion( - currentVersion, s.isMajorTo(SUBINCREMENTAL) ? Segment.of(s.value() + 1) : s)) - .orElse(null); - - Restriction restriction = new Restriction(lowerBound, allowDowngrade, upperBound, allowDowngrade); + Restriction restriction = restrictionForUnchangedSegment(unchangedSegment, allowDowngrade); return Arrays.stream(getVersions(includeSnapshots)) .filter(candidate -> isVersionInRestriction(restriction, candidate)) .filter(candidate -> includeSnapshots || !ArtifactUtils.isSnapshot(candidate.toString())) .max(getVersionComparator()); } + @Override + public Optional getNewestVersion( + String ignored, Optional unchangedSegment, boolean includeSnapshots, boolean allowDowngrade) + throws InvalidSegmentException { + return getNewestVersion(unchangedSegment, includeSnapshots, allowDowngrade); + } + @Override public final ArtifactVersion[] getVersions(Restriction restriction, boolean includeSnapshots) { return getVersions(null, restriction, includeSnapshots); @@ -264,10 +279,10 @@ public final ArtifactVersion[] getVersions( } @Override - public final ArtifactVersion getNewestUpdate( + public final ArtifactVersion getNewestUpdateWithinSegment( ArtifactVersion currentVersion, Optional updateScope, boolean includeSnapshots) { try { - return getNewestVersion(restrictionFor(updateScope), includeSnapshots); + return getNewestVersion(restrictionForSelectedSegment(updateScope), includeSnapshots); } catch (InvalidSegmentException e) { return null; } @@ -277,16 +292,16 @@ public final ArtifactVersion getNewestUpdate( public final ArtifactVersion[] getAllUpdates( ArtifactVersion currentVersion, Optional updateScope, boolean includeSnapshots) { try { - return getVersions(restrictionFor(updateScope), includeSnapshots); + return getVersions(restrictionForSelectedSegment(updateScope), includeSnapshots); } catch (InvalidSegmentException e) { return null; } } @Override - public final ArtifactVersion getNewestUpdate(Optional updateScope, boolean includeSnapshots) { + public final ArtifactVersion getNewestUpdateWithinSegment(Optional updateScope, boolean includeSnapshots) { if (isCurrentVersionDefined()) { - return getNewestUpdate(getCurrentVersion(), updateScope, includeSnapshots); + return getNewestUpdateWithinSegment(getCurrentVersion(), updateScope, includeSnapshots); } return null; } @@ -435,7 +450,7 @@ public final ArtifactVersion[] getReportUpdates(Optional updateScope, b private Stream getArtifactVersionStream(Optional updateScope, boolean includeSnapshots) { if (isCurrentVersionDefined()) { try { - Restriction restriction = restrictionFor(updateScope); + Restriction restriction = restrictionForSelectedSegment(updateScope); return Arrays.stream(getVersions(includeSnapshots)) .filter(candidate -> isVersionInRestriction(restriction, candidate)); diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/api/ArtifactVersionsCache.java b/versions-common/src/main/java/org/codehaus/mojo/versions/api/ArtifactVersionsCache.java index 8df888dfa..4eea8923c 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/api/ArtifactVersionsCache.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/api/ArtifactVersionsCache.java @@ -27,7 +27,7 @@ import org.apache.commons.lang3.tuple.Triple; /** - * Utility providing a cached {@link ArtifactVersions#getNewestUpdate(Optional, boolean)} API + * Utility providing a cached {@link ArtifactVersions#getNewestUpdateWithinSegment(Optional, boolean)} API */ public class ArtifactVersionsCache { private TriFunction, Boolean, ?> cachedFunction; diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/api/PropertyVersions.java b/versions-common/src/main/java/org/codehaus/mojo/versions/api/PropertyVersions.java index b61b47990..bc695c9e3 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/api/PropertyVersions.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/api/PropertyVersions.java @@ -320,7 +320,7 @@ public ArtifactVersion getNewestVersion( ? null : upperBoundSegment .map(s -> (ArtifactVersion) new BoundArtifactVersion( - currentVersion, s.isMajorTo(SUBINCREMENTAL) ? Segment.of(s.value() + 1) : s)) + currentVersion, s.isMajorTo(SUBINCREMENTAL) ? Segment.minorTo(s) : s)) .orElse(null); if (helper.getLog().isDebugEnabled()) { helper.getLog().debug("Property ${" + property.getName() + "}: upperBound is: " + upperBound); diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/api/Segment.java b/versions-common/src/main/java/org/codehaus/mojo/versions/api/Segment.java index 9aa90ca05..20ccf4d21 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/api/Segment.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/api/Segment.java @@ -19,6 +19,8 @@ * under the License. */ +import java.util.Optional; + /** * Indicates the segment along with its 0-based index * @@ -46,6 +48,26 @@ public static Segment of(int index) { return values()[index]; } + /** + * Creates a segment that has a greater scope than the given segment or {@code null} + * if the segment is already {@link #MAJOR} + * @param other segment that the new segment is to be based on + * @return that has a greater scope than the given segment or {@code null} + * if the segment is already {@link #MAJOR} + */ + public static Segment majorTo(Segment other) { + return Optional.ofNullable(other).map(s -> of(s.value() - 1)).orElse(null); + } + + /** + * Creates a segment that has a lesser scope than the given segment + * @param other segment that the new segment is to be based on + * @return that has a lesser scope than the given segment + */ + public static Segment minorTo(Segment other) { + return Optional.ofNullable(other).map(s -> of(s.value() + 1)).orElse(MAJOR); + } + /** * Returns true if the given segment is more major than the other * @param other other segment to compare diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/api/VersionDetails.java b/versions-common/src/main/java/org/codehaus/mojo/versions/api/VersionDetails.java index 79b369bf6..0ce6b4fdd 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/api/VersionDetails.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/api/VersionDetails.java @@ -199,7 +199,7 @@ ArtifactVersion getNewestVersion( * should be included. * * @param versionString current version - * @param upperBoundSegment the upper bound segment; empty() means no upper bound + * @param unchangedSegment segment that may not be changed; empty() means no upper bound * @param includeSnapshots whether snapshot versions should be included * @param allowDowngrade whether to allow downgrading if the current version is a snapshots and snapshots * are disallowed @@ -208,7 +208,26 @@ ArtifactVersion getNewestVersion( * the segment count) */ Optional getNewestVersion( - String versionString, Optional upperBoundSegment, boolean includeSnapshots, boolean allowDowngrade) + Optional unchangedSegment, boolean includeSnapshots, boolean allowDowngrade) + throws InvalidSegmentException; + + /** + * Returns the latest version, newer than the given version, given the upper bound segment and whether snapshots + * should be included. + * + * @param versionString current version + * @param unchangedSegment segment that may not be changed; empty() means no upper bound + * @param includeSnapshots whether snapshot versions should be included + * @param allowDowngrade whether to allow downgrading if the current version is a snapshots and snapshots + * are disallowed + * @return newer version or {@link Optional#empty()} if none can be found + * @throws InvalidSegmentException if the requested segment is outside the bounds (less than 1 or greater than + * the segment count) + * @deprecated please use {@link #getNewestVersion(Optional, boolean, boolean)} + */ + @Deprecated + Optional getNewestVersion( + String versionString, Optional unchangedSegment, boolean includeSnapshots, boolean allowDowngrade) throws InvalidSegmentException; /** @@ -223,7 +242,7 @@ Optional getNewestVersion( * @throws InvalidSegmentException thrown if the updateScope is greater than the number of segments * @since 1.0-beta-1 */ - ArtifactVersion getNewestUpdate( + ArtifactVersion getNewestUpdateWithinSegment( ArtifactVersion currentVersion, Optional updateScope, boolean includeSnapshots) throws InvalidSegmentException; @@ -285,8 +304,9 @@ ArtifactVersion[] getAllUpdates( throws InvalidSegmentException; /** - * Returns the newest version newer than the specified current version, but within the specified update scope or - * null if no such version exists. + *

Returns the newest version newer than the specified current version, only within the segment specified + * by {@code updateScope} or {@code null} if no such version exists.

+ *

If {@code updateScope} is {@link Optional#empty()}, will return all updates.

* * @param updateScope the update scope to include. * @param includeSnapshots true if snapshots are to be included. @@ -295,7 +315,7 @@ ArtifactVersion[] getAllUpdates( * @throws InvalidSegmentException thrown if the updateScope is greater than the number of segments * @since 1.0-beta-1 */ - ArtifactVersion getNewestUpdate(Optional updateScope, boolean includeSnapshots) + ArtifactVersion getNewestUpdateWithinSegment(Optional updateScope, boolean includeSnapshots) throws InvalidSegmentException; /** @@ -331,21 +351,29 @@ ArtifactVersion[] getAllUpdates(Optional updateScope, boolean includeSn /** *

Returns a {@linkplain Restriction} object for computing version upgrades - * with the given segment allowing updates, with all more major segments locked in place.

- *

The resulting restriction could be thought of as one - * retaining the versions on positions up to the held position, - * the position right after the position held in place will be incremented by one, - * and on all positions which are more minor than that, the range would contain -∞ - * for the bottom bound and +∞ for the above bound.

- *

This will allow matching the required versions while not matching versions which are considered - * inferior than the zeroth version, i.e. versions with a qualifier.

+ * within the given segment allowing updates, with all more major segments locked in place, + * but also ignoring all version updates from lesser scopes.

+ * + * @param selectedSegment segment, for which the restriction is to be built or {@link Optional#empty()} for no restriction + * @return {@linkplain Restriction} object based on the arguments + * @throws InvalidSegmentException if the requested segment is outside the bounds (less than 1 or greater than + * the segment count) + */ + Restriction restrictionForSelectedSegment(Optional selectedSegment) throws InvalidSegmentException; + + /** + *

Returns a {@linkplain Restriction} object for computing version upgrades + * within the all segments minor/lesser to the provided {@code unchangedSegment}.

+ *

If the provided segment is {@link Optional#empty()}, all possible updates are returned.

* - * @param scope most major segment where updates are allowed Optional.empty() for no restriction + * @param unchangedSegment segment, which should not be changed or {@link Optional#empty()} for no restriction + * @param allowDowngrade whether downgrades are allowed * @return {@linkplain Restriction} object based on the arguments * @throws InvalidSegmentException if the requested segment is outside the bounds (less than 1 or greater than * the segment count) */ - Restriction restrictionFor(Optional scope) throws InvalidSegmentException; + Restriction restrictionForUnchangedSegment(Optional unchangedSegment, boolean allowDowngrade) + throws InvalidSegmentException; /** * Returns the {@link Restriction} objects for a segemnt scope which is to be ignored. diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/utils/SegmentUtils.java b/versions-common/src/main/java/org/codehaus/mojo/versions/utils/SegmentUtils.java index 791d954a8..e37a0349e 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/utils/SegmentUtils.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/utils/SegmentUtils.java @@ -26,9 +26,7 @@ import static java.util.Optional.empty; import static java.util.Optional.of; -import static org.codehaus.mojo.versions.api.Segment.INCREMENTAL; -import static org.codehaus.mojo.versions.api.Segment.MAJOR; -import static org.codehaus.mojo.versions.api.Segment.MINOR; +import static org.codehaus.mojo.versions.api.Segment.*; /** * Utility class for manipulating with {@link Segment} objects @@ -79,7 +77,8 @@ public static Optional determineUnchangedSegment( : allowIncrementalUpdates ? of(MINOR) : of(INCREMENTAL); if (log != null && log.isDebugEnabled()) { log.debug(unchangedSegment - .map(s -> Segment.of(s.value() + 1).toString()) + .map(Segment::minorTo) + .map(Segment::toString) .orElse("ALL") + " version changes allowed"); } return unchangedSegment; diff --git a/versions-common/src/test/java/org/codehaus/mojo/versions/api/ArtifactVersionsTest.java b/versions-common/src/test/java/org/codehaus/mojo/versions/api/ArtifactVersionsTest.java index 6f1342d6d..5e1ee942c 100644 --- a/versions-common/src/test/java/org/codehaus/mojo/versions/api/ArtifactVersionsTest.java +++ b/versions-common/src/test/java/org/codehaus/mojo/versions/api/ArtifactVersionsTest.java @@ -20,6 +20,7 @@ */ import java.util.Arrays; +import java.util.Optional; import org.apache.maven.artifact.DefaultArtifact; import org.apache.maven.artifact.handler.DefaultArtifactHandler; @@ -38,9 +39,7 @@ import static org.codehaus.mojo.versions.api.Segment.MINOR; import static org.codehaus.mojo.versions.api.Segment.SUBINCREMENTAL; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.arrayContaining; -import static org.hamcrest.Matchers.arrayWithSize; -import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @@ -181,8 +180,9 @@ public void testReportLabels() { Arrays.asList(versions), new MavenVersionComparator()); - assertThat(instance.getNewestUpdate(of(SUBINCREMENTAL), false).toString(), is("1.1.0-2")); - assertThat(instance.getNewestUpdate(of(INCREMENTAL), false).toString(), is("1.1.3")); + assertThat( + instance.getNewestUpdateWithinSegment(of(SUBINCREMENTAL), false).toString(), is("1.1.0-2")); + assertThat(instance.getNewestUpdateWithinSegment(of(INCREMENTAL), false).toString(), is("1.1.3")); } @Test @@ -198,13 +198,17 @@ public void testGetNewerVersionsWithSnapshot() throws InvalidSegmentException { arrayContaining(DefaultArtifactVersionCache.of("1.0.0"))); } - @Test - public void testAllVersionsForIgnoreScopeSubIncremental() { - ArtifactVersion[] versions = versions("1.0.0", "1.0.0-1", "1.0.1"); - ArtifactVersions instance = new ArtifactVersions( + private static ArtifactVersions createInstance(ArtifactVersion[] versions) { + return new ArtifactVersions( new DefaultArtifact("default-group", "dummy-api", "1.0.0", "foo", "bar", "jar", null), Arrays.asList(versions), new MavenVersionComparator()); + } + + @Test + public void testAllVersionsForIgnoreScopeSubIncremental() { + ArtifactVersion[] versions = versions("1.0.0", "1.0.0-1", "1.0.1"); + ArtifactVersions instance = createInstance(versions); Restriction restriction = instance.restrictionForIgnoreScope(of(SUBINCREMENTAL)); ArtifactVersion[] filteredVersions = instance.getVersions(restriction, false); assertThat(filteredVersions, arrayWithSize(1)); @@ -214,10 +218,7 @@ public void testAllVersionsForIgnoreScopeSubIncremental() { @Test public void testAllVersionsForIgnoreScopeIncremental() { ArtifactVersion[] versions = versions("1.0.0", "1.0.0-1", "1.0.1", "1.1.0"); - ArtifactVersions instance = new ArtifactVersions( - new DefaultArtifact("default-group", "dummy-api", "1.0.0", "foo", "bar", "jar", null), - Arrays.asList(versions), - new MavenVersionComparator()); + ArtifactVersions instance = createInstance(versions); Restriction restriction = instance.restrictionForIgnoreScope(of(INCREMENTAL)); ArtifactVersion[] filteredVersions = instance.getVersions(restriction, false); assertThat(filteredVersions, arrayWithSize(1)); @@ -227,10 +228,7 @@ public void testAllVersionsForIgnoreScopeIncremental() { @Test public void testAllVersionsForIgnoreScopeMinor() { ArtifactVersion[] versions = versions("1.0.0", "1.0.0-1", "1.0.1", "1.1.0", "2.0.0"); - ArtifactVersions instance = new ArtifactVersions( - new DefaultArtifact("default-group", "dummy-api", "1.0.0", "foo", "bar", "jar", null), - Arrays.asList(versions), - new MavenVersionComparator()); + ArtifactVersions instance = createInstance(versions); Restriction restriction = instance.restrictionForIgnoreScope(of(MINOR)); ArtifactVersion[] filteredVersions = instance.getVersions(restriction, false); assertThat(filteredVersions, arrayWithSize(1)); @@ -240,12 +238,60 @@ public void testAllVersionsForIgnoreScopeMinor() { @Test public void testAllVersionsForIgnoreScopeMajor() { ArtifactVersion[] versions = versions("1.0.0", "1.0.0-1", "1.0.1", "1.1.0", "2.0.0"); - ArtifactVersions instance = new ArtifactVersions( - new DefaultArtifact("default-group", "dummy-api", "1.0.0", "foo", "bar", "jar", null), - Arrays.asList(versions), - new MavenVersionComparator()); + ArtifactVersions instance = createInstance(versions); Restriction restriction = instance.restrictionForIgnoreScope(of(MAJOR)); ArtifactVersion[] filteredVersions = instance.getVersions(restriction, false); assertThat(filteredVersions, arrayWithSize(0)); } + + @Test + public void testGetReportNewestUpdateWithOnlyMajorUpdate() { + ArtifactVersion[] versions = versions("1.0.0", "2.0.0"); + ArtifactVersions instance = createInstance(versions); + assertThat(instance.getReportNewestUpdate(Optional.empty(), true).toString(), is("2.0.0")); + assertThat(instance.getReportNewestUpdate(of(MAJOR), true), hasToString("2.0.0")); + assertThat(instance.getReportNewestUpdate(of(MINOR), true), nullValue()); + assertThat(instance.getReportNewestUpdate(of(INCREMENTAL), true), nullValue()); + assertThat(instance.getReportNewestUpdate(of(SUBINCREMENTAL), true), nullValue()); + } + + @Test + public void testGetReportNewestUpdateWithMinorAndMajor() { + ArtifactVersion[] versions = versions("1.0.0", "1.1.0", "2.0.0"); + ArtifactVersions instance = createInstance(versions); + assertThat(instance.getReportNewestUpdate(Optional.empty(), true).toString(), is("2.0.0")); + assertThat(instance.getReportNewestUpdate(of(MAJOR), true), hasToString("2.0.0")); + assertThat(instance.getReportNewestUpdate(of(MINOR), true), hasToString("1.1.0")); + assertThat(instance.getReportNewestUpdate(of(INCREMENTAL), true), nullValue()); + assertThat(instance.getReportNewestUpdate(of(SUBINCREMENTAL), true), nullValue()); + } + + @Test + public void testGetReportNewestUpdateWithIncrementalAndMajor() { + ArtifactVersion[] versions = versions("1.0.0", "1.0.1", "2.0.0"); + ArtifactVersions instance = createInstance(versions); + assertThat(instance.getReportNewestUpdate(Optional.empty(), true).toString(), is("2.0.0")); + assertThat(instance.getReportNewestUpdate(of(MAJOR), true), hasToString("2.0.0")); + assertThat(instance.getReportNewestUpdate(of(MINOR), true), nullValue()); + assertThat(instance.getReportNewestUpdate(of(INCREMENTAL), true), hasToString("1.0.1")); + assertThat(instance.getReportNewestUpdate(of(SUBINCREMENTAL), true), nullValue()); + } + + @Test + public void testGetNewestVersionWithLesserSegment() throws InvalidSegmentException { + ArtifactVersion[] versions = versions("1.0.0-1"); + ArtifactVersions instance = createInstance(versions); + assertThat(instance.getNewestVersion(of(MAJOR), false, false).get(), hasToString("1.0.0-1")); + assertThat(instance.getNewestVersion(of(MINOR), false, false).get(), hasToString("1.0.0-1")); + assertThat(instance.getNewestVersion(of(INCREMENTAL), false, false).get(), hasToString("1.0.0-1")); + } + + @Test + public void testGetNewestVersionWithLesserSegmentWithSnapshots() throws InvalidSegmentException { + ArtifactVersion[] versions = versions("1.0.0-1-SNAPSHOT"); + ArtifactVersions instance = createInstance(versions); + assertThat(instance.getNewestVersion(of(MAJOR), true, false).get(), hasToString("1.0.0-1-SNAPSHOT")); + assertThat(instance.getNewestVersion(of(MINOR), true, false).get(), hasToString("1.0.0-1-SNAPSHOT")); + assertThat(instance.getNewestVersion(of(INCREMENTAL), true, false).get(), hasToString("1.0.0-1-SNAPSHOT")); + } } diff --git a/versions-common/src/test/java/org/codehaus/mojo/versions/utils/SegmentUtilsTest.java b/versions-common/src/test/java/org/codehaus/mojo/versions/utils/SegmentUtilsTest.java index 7d22804b3..36a8c17de 100644 --- a/versions-common/src/test/java/org/codehaus/mojo/versions/utils/SegmentUtilsTest.java +++ b/versions-common/src/test/java/org/codehaus/mojo/versions/utils/SegmentUtilsTest.java @@ -18,6 +18,10 @@ * under the License. */ +import java.util.Optional; + +import org.apache.maven.plugin.logging.Log; +import org.codehaus.mojo.versions.api.Segment; import org.junit.Test; import static java.util.Optional.empty; @@ -53,6 +57,26 @@ public void testMajor() { @Test public void testEmpty() { - assertThat(determineUnchangedSegment(true, true, true, null), is(empty())); + Optional result; + boolean allowMinorUpdates = true; + boolean allowIncrementalUpdates = true; + Log log = null; + if (log != null && !allowIncrementalUpdates) { + log.info("Assuming allowMinorUpdates false because allowIncrementalUpdates is false."); + } + + Optional unchangedSegment = allowIncrementalUpdates + ? empty() + : allowMinorUpdates && allowIncrementalUpdates + ? of(MAJOR) + : allowIncrementalUpdates ? of(MINOR) : of(INCREMENTAL); + if (log != null && log.isDebugEnabled()) { + log.debug(unchangedSegment + .map(Segment::minorTo) + .map(Segment::toString) + .orElse("ALL") + " version changes allowed"); + } + result = unchangedSegment; + assertThat(result, is(empty())); } } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayDependencyUpdatesMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayDependencyUpdatesMojo.java index bb0600c73..392c3d770 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayDependencyUpdatesMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayDependencyUpdatesMojo.java @@ -21,13 +21,7 @@ import javax.inject.Inject; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.TreeSet; +import java.util.*; import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.artifact.versioning.ArtifactVersion; @@ -43,6 +37,7 @@ import org.codehaus.mojo.versions.api.VersionRetrievalException; import org.codehaus.mojo.versions.api.recording.ChangeRecorder; import org.codehaus.mojo.versions.filtering.WildcardMatcher; +import org.codehaus.mojo.versions.ordering.InvalidSegmentException; import org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader; import org.codehaus.mojo.versions.utils.DependencyComparator; import org.codehaus.mojo.versions.utils.SegmentUtils; @@ -50,13 +45,9 @@ import static java.util.Collections.emptySet; import static java.util.Optional.empty; -import static java.util.Optional.of; import static org.apache.commons.lang3.StringUtils.countMatches; -import static org.codehaus.mojo.versions.api.Segment.MAJOR; import static org.codehaus.mojo.versions.filtering.DependencyFilter.filterDependencies; -import static org.codehaus.mojo.versions.utils.MavenProjectUtils.extractDependenciesFromDependencyManagement; -import static org.codehaus.mojo.versions.utils.MavenProjectUtils.extractDependenciesFromPlugins; -import static org.codehaus.mojo.versions.utils.MavenProjectUtils.extractPluginDependenciesFromPluginsInPluginManagement; +import static org.codehaus.mojo.versions.utils.MavenProjectUtils.*; /** * Displays all dependencies that have newer versions available. @@ -218,9 +209,6 @@ public class DisplayDependencyUpdatesMojo extends AbstractVersionsDisplayMojo { /** * Whether to allow the major version number to be changed. * - *

Note: {@code false} also implies {@linkplain #allowAnyUpdates} - * to be {@code false}

- * * @since 2.5 */ @Parameter(property = "allowMajorUpdates", defaultValue = "true") @@ -229,8 +217,7 @@ public class DisplayDependencyUpdatesMojo extends AbstractVersionsDisplayMojo { /** *

Whether to allow the minor version number to be changed.

* - *

Note: {@code false} also implies {@linkplain #allowAnyUpdates} - * and {@linkplain #allowMajorUpdates} to be {@code false}

+ *

Note: {@code false} also implies {@linkplain #allowMajorUpdates} to be {@code false}

* * @since 2.5 */ @@ -240,29 +227,14 @@ public class DisplayDependencyUpdatesMojo extends AbstractVersionsDisplayMojo { /** *

Whether to allow the incremental version number to be changed.

* - *

Note: {@code false} also implies {@linkplain #allowAnyUpdates}, - * {@linkplain #allowMajorUpdates}, and {@linkplain #allowMinorUpdates} - * to be {@code false}

+ *

Note: {@code false} also implies {@linkplain #allowMajorUpdates} + * and {@linkplain #allowMinorUpdates} to be {@code false}

* * @since 2.5 */ @Parameter(property = "allowIncrementalUpdates", defaultValue = "true") private boolean allowIncrementalUpdates = true; - /** - * Whether to allow any version change to be allowed. This keeps - * compatibility with previous versions of the plugin. - * If you set this to false you can control changes in version - * number by {@link #allowMajorUpdates}, {@link #allowMinorUpdates} or - * {@link #allowIncrementalUpdates}. - * - * @since 2.5 - * @deprecated This will be removed with version 3.0.0 - */ - @Deprecated - @Parameter(property = "allowAnyUpdates", defaultValue = "true") - private boolean allowAnyUpdates = true; - /** * Whether to show additional information such as dependencies that do not need updating. Defaults to false. * @@ -310,7 +282,7 @@ public class DisplayDependencyUpdatesMojo extends AbstractVersionsDisplayMojo { /** *

Only take these artifacts into consideration:
* Comma-separated list of {@code groupId:[artifactId[:version]]} patterns

- * + *

* The wildcard "*" can be used as the only, first, last or both characters in each token. * The version token does support version ranges. *

@@ -497,8 +469,8 @@ protected void validateInput() throws MojoExecutionException { /** * Validates a list of GAV strings - * @param gavList list of the input GAV strings - * @param numSections number of sections in the GAV to verify against + * @param gavList list of the input GAV strings + * @param numSections number of sections in the GAV to verify against * @param argumentName argument name to indicate in the exception * @throws MojoExecutionException if the argument is invalid */ @@ -509,40 +481,24 @@ static void validateGAVList(List gavList, int numSections, String argume } } - private Optional calculateUpdateScope() { - return allowAnyUpdates - ? empty() - : of(SegmentUtils.determineUnchangedSegment( - allowMajorUpdates, allowMinorUpdates, allowIncrementalUpdates, getLog()) - .map(s -> Segment.of(s.value() + 1)) - .orElse(MAJOR)); - } - private void logUpdates(Map updates, String section) { List withUpdates = new ArrayList<>(); List usingCurrent = new ArrayList<>(); for (ArtifactVersions versions : updates.values()) { String left = " " + ArtifactUtils.versionlessKey(versions.getArtifact()) + " "; final String current; - ArtifactVersion latest; - if (versions.isCurrentVersionDefined()) { - current = versions.getCurrentVersion().toString(); - latest = versions.getNewestUpdate(calculateUpdateScope(), allowSnapshots); - } else { - ArtifactVersion newestVersion = - versions.getNewestVersion(versions.getArtifact().getVersionRange(), allowSnapshots); - current = versions.getArtifact().getVersionRange().toString(); - latest = newestVersion == null - ? null - : versions.getNewestUpdate(newestVersion, calculateUpdateScope(), allowSnapshots); - if (latest != null - && ArtifactVersions.isVersionInRange( - latest, versions.getArtifact().getVersionRange())) { - latest = null; - } + Optional latest; + Optional unchangedSegment = SegmentUtils.determineUnchangedSegment( + allowMajorUpdates, allowMinorUpdates, allowIncrementalUpdates, getLog()); + try { + latest = versions.getNewestVersion(unchangedSegment, allowSnapshots, false); + } catch (InvalidSegmentException e) { + latest = empty(); } - String right = " " + (latest == null ? current : current + " -> " + latest); - List t = latest == null ? usingCurrent : withUpdates; + String right = " " + + latest.map(v -> versions.getCurrentVersion() + " -> " + v) + .orElse(versions.getCurrentVersion().toString()); + List t = latest.isPresent() ? withUpdates : usingCurrent; if (right.length() + left.length() + 3 > INFO_PAD_SIZE + getOutputLineWidthOffset()) { t.add(left + "..."); t.add(StringUtils.leftPad(right, INFO_PAD_SIZE + getOutputLineWidthOffset())); diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayExtensionUpdatesMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayExtensionUpdatesMojo.java index 1b6d389e2..c34bff0e5 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayExtensionUpdatesMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayExtensionUpdatesMojo.java @@ -282,7 +282,7 @@ private List getRawModels() throws MojoFailureException { private Optional calculateUpdateScope() { return of(SegmentUtils.determineUnchangedSegment( allowMajorUpdates, allowMinorUpdates, allowIncrementalUpdates, getLog()) - .map(s -> Segment.of(s.value() + 1)) + .map(Segment::minorTo) .orElse(MAJOR)); } @@ -295,14 +295,14 @@ private void logUpdates(Map updates) { ArtifactVersion latest; if (versions.isCurrentVersionDefined()) { current = versions.getCurrentVersion().toString(); - latest = versions.getNewestUpdate(calculateUpdateScope(), allowSnapshots); + latest = versions.getNewestUpdateWithinSegment(calculateUpdateScope(), allowSnapshots); } else { ArtifactVersion newestVersion = versions.getNewestVersion(versions.getArtifact().getVersionRange(), allowSnapshots); current = versions.getArtifact().getVersionRange().toString(); latest = newestVersion == null ? null - : versions.getNewestUpdate(newestVersion, calculateUpdateScope(), allowSnapshots); + : versions.getNewestUpdateWithinSegment(newestVersion, calculateUpdateScope(), allowSnapshots); if (latest != null && ArtifactVersions.isVersionInRange( latest, versions.getArtifact().getVersionRange())) { diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayPropertyUpdatesMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayPropertyUpdatesMojo.java index ba5a0061e..34065d53a 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayPropertyUpdatesMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayPropertyUpdatesMojo.java @@ -31,6 +31,7 @@ import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.repository.RepositorySystem; @@ -42,7 +43,10 @@ import org.codehaus.mojo.versions.api.recording.ChangeRecorder; import org.codehaus.mojo.versions.ordering.InvalidSegmentException; import org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader; -import org.codehaus.mojo.versions.utils.SegmentUtils; + +import static java.util.Optional.empty; +import static java.util.Optional.of; +import static org.codehaus.mojo.versions.api.Segment.*; /** * Displays properties that are linked to artifact versions and have updates available. @@ -168,8 +172,27 @@ public void execute() throws MojoExecutionException, MojoFailureException { continue; } - Optional unchangedSegment = SegmentUtils.determineUnchangedSegment( - allowMajorUpdates, allowMinorUpdates, allowIncrementalUpdates, getLog()); + Log log = getLog(); + if (log != null && !allowIncrementalUpdates) { + log.info("Assuming allowMinorUpdates false because allowIncrementalUpdates is false."); + } + + if (log != null && !allowMinorUpdates) { + log.info("Assuming allowMajorUpdates false because allowMinorUpdates is false."); + } + + Optional unchangedSegment1 = allowMajorUpdates && allowMinorUpdates && allowIncrementalUpdates + ? empty() + : allowMinorUpdates && allowIncrementalUpdates + ? of(MAJOR) + : allowIncrementalUpdates ? of(MINOR) : of(INCREMENTAL); + if (log != null && log.isDebugEnabled()) { + log.debug(unchangedSegment1 + .map(Segment::minorTo) + .map(Segment::toString) + .orElse("ALL") + " version changes allowed"); + } + Optional unchangedSegment = unchangedSegment1; try { ArtifactVersion winner = version.getNewestVersion( currentVersion, diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/ResolveRangesMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/ResolveRangesMojo.java index f9ccfdad0..e8c3acc3d 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/ResolveRangesMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/ResolveRangesMojo.java @@ -35,6 +35,7 @@ import org.apache.maven.model.Dependency; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.repository.RepositorySystem; @@ -48,7 +49,10 @@ import org.codehaus.mojo.versions.api.recording.ChangeRecorder; import org.codehaus.mojo.versions.ordering.InvalidSegmentException; import org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader; -import org.codehaus.mojo.versions.utils.SegmentUtils; + +import static java.util.Optional.empty; +import static java.util.Optional.of; +import static org.codehaus.mojo.versions.api.Segment.*; /** * Attempts to resolve dependency version ranges to the specific version being used in the build. For example a version @@ -288,8 +292,27 @@ private void resolvePropertyRanges(ModifiedPomXMLEventReader pom) property.setVersion(currentVersion); - Optional unchangedSegment = SegmentUtils.determineUnchangedSegment( - allowMajorUpdates, allowMinorUpdates, allowIncrementalUpdates, getLog()); + Log log = getLog(); + if (log != null && !allowIncrementalUpdates) { + log.info("Assuming allowMinorUpdates false because allowIncrementalUpdates is false."); + } + + if (log != null && !allowMinorUpdates) { + log.info("Assuming allowMajorUpdates false because allowMinorUpdates is false."); + } + + Optional unchangedSegment1 = allowMajorUpdates && allowMinorUpdates && allowIncrementalUpdates + ? empty() + : allowMinorUpdates && allowIncrementalUpdates + ? of(MAJOR) + : allowIncrementalUpdates ? of(MINOR) : of(INCREMENTAL); + if (log != null && log.isDebugEnabled()) { + log.debug(unchangedSegment1 + .map(Segment::minorTo) + .map(Segment::toString) + .orElse("ALL") + " version changes allowed"); + } + Optional unchangedSegment = unchangedSegment1; // TODO: Check if we could add allowDowngrade ? try { updatePropertyToNewestVersion(pom, property, version, currentVersion, false, unchangedSegment); diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UpdateParentMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UpdateParentMojo.java index 376c95b2d..dbf78238c 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UpdateParentMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UpdateParentMojo.java @@ -30,6 +30,7 @@ import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.repository.RepositorySystem; @@ -45,9 +46,11 @@ import org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader; import org.codehaus.mojo.versions.utils.DefaultArtifactVersionCache; import org.codehaus.mojo.versions.utils.DependencyBuilder; -import org.codehaus.mojo.versions.utils.SegmentUtils; +import static java.util.Optional.empty; +import static java.util.Optional.of; import static org.apache.maven.shared.utils.StringUtils.isBlank; +import static org.codehaus.mojo.versions.api.Segment.*; /** * Sets the parent version to the latest parent version. @@ -212,8 +215,27 @@ protected ArtifactVersion resolveTargetVersion(String initialVersion) } final ArtifactVersions versions = getHelper().lookupArtifactVersions(artifact, false); - Optional unchangedSegment = SegmentUtils.determineUnchangedSegment( - allowMajorUpdates, allowMinorUpdates, allowIncrementalUpdates, getLog()); + Log log = getLog(); + if (log != null && !allowIncrementalUpdates) { + log.info("Assuming allowMinorUpdates false because allowIncrementalUpdates is false."); + } + + if (log != null && !allowMinorUpdates) { + log.info("Assuming allowMajorUpdates false because allowMinorUpdates is false."); + } + + Optional unchangedSegment1 = allowMajorUpdates && allowMinorUpdates && allowIncrementalUpdates + ? empty() + : allowMinorUpdates && allowIncrementalUpdates + ? of(MAJOR) + : allowIncrementalUpdates ? of(MINOR) : of(INCREMENTAL); + if (log != null && log.isDebugEnabled()) { + log.debug(unchangedSegment1 + .map(Segment::minorTo) + .map(Segment::toString) + .orElse("ALL") + " version changes allowed"); + } + Optional unchangedSegment = unchangedSegment1; // currentVersion (set to parentVersion here) is not included in the version range for searching upgrades // unless we set allowDowngrade to true diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UpdatePropertiesMojoBase.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UpdatePropertiesMojoBase.java index 3274bb2f4..a8e7c232e 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UpdatePropertiesMojoBase.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UpdatePropertiesMojoBase.java @@ -23,6 +23,7 @@ import org.apache.maven.artifact.versioning.ArtifactVersion; import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.repository.RepositorySystem; import org.apache.maven.wagon.Wagon; @@ -37,7 +38,9 @@ import org.codehaus.mojo.versions.recording.DefaultPropertyChangeRecord; import org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader; -import static org.codehaus.mojo.versions.utils.SegmentUtils.determineUnchangedSegment; +import static java.util.Optional.empty; +import static java.util.Optional.of; +import static org.codehaus.mojo.versions.api.Segment.*; /** * Common base class for {@link UpdatePropertiesMojo} @@ -133,8 +136,27 @@ protected void update(ModifiedPomXMLEventReader pom, Map unchangedSegment = determineUnchangedSegment( - allowMajorUpdates, allowMinorUpdates, allowIncrementalUpdates, getLog()); + Log log = getLog(); + if (log != null && !allowIncrementalUpdates) { + log.info("Assuming allowMinorUpdates false because allowIncrementalUpdates is false."); + } + + if (log != null && !allowMinorUpdates) { + log.info("Assuming allowMajorUpdates false because allowMinorUpdates is false."); + } + + Optional unchangedSegment1 = allowMajorUpdates && allowMinorUpdates && allowIncrementalUpdates + ? empty() + : allowMinorUpdates && allowIncrementalUpdates + ? of(MAJOR) + : allowIncrementalUpdates ? of(MINOR) : of(INCREMENTAL); + if (log != null && log.isDebugEnabled()) { + log.debug(unchangedSegment1 + .map(Segment::minorTo) + .map(Segment::toString) + .orElse("ALL") + " version changes allowed"); + } + Optional unchangedSegment = unchangedSegment1; try { ArtifactVersion targetVersion = updatePropertyToNewestVersion( pom, property, version, currentVersion, allowDowngrade, unchangedSegment); diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseLatestReleasesMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseLatestReleasesMojo.java index ea316a38f..9f4118237 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseLatestReleasesMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseLatestReleasesMojo.java @@ -33,6 +33,7 @@ import org.apache.maven.model.DependencyManagement; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.repository.RepositorySystem; @@ -44,10 +45,11 @@ import org.codehaus.mojo.versions.api.recording.DependencyChangeRecord; import org.codehaus.mojo.versions.ordering.InvalidSegmentException; import org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader; -import org.codehaus.mojo.versions.utils.SegmentUtils; import static java.util.Collections.singletonList; import static java.util.Optional.empty; +import static java.util.Optional.of; +import static org.codehaus.mojo.versions.api.Segment.*; /** * Replaces any release versions (i.e. versions that are not snapshots and do not @@ -149,8 +151,27 @@ private void useLatestReleases( Collection dependencies, DependencyChangeRecord.ChangeKind changeKind) throws XMLStreamException, MojoExecutionException, VersionRetrievalException { - Optional unchangedSegment = SegmentUtils.determineUnchangedSegment( - allowMajorUpdates, allowMinorUpdates, allowIncrementalUpdates, getLog()); + Log log = getLog(); + if (log != null && !allowIncrementalUpdates) { + log.info("Assuming allowMinorUpdates false because allowIncrementalUpdates is false."); + } + + if (log != null && !allowMinorUpdates) { + log.info("Assuming allowMajorUpdates false because allowMinorUpdates is false."); + } + + Optional unchangedSegment1 = allowMajorUpdates && allowMinorUpdates && allowIncrementalUpdates + ? empty() + : allowMinorUpdates && allowIncrementalUpdates + ? of(MAJOR) + : allowIncrementalUpdates ? of(MINOR) : of(INCREMENTAL); + if (log != null && log.isDebugEnabled()) { + log.debug(unchangedSegment1 + .map(Segment::minorTo) + .map(Segment::toString) + .orElse("ALL") + " version changes allowed"); + } + Optional unchangedSegment = unchangedSegment1; useLatestVersions( pom, diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseLatestSnapshotsMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseLatestSnapshotsMojo.java index 7b00dac7f..ca1de3046 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseLatestSnapshotsMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseLatestSnapshotsMojo.java @@ -29,6 +29,7 @@ import org.apache.maven.model.DependencyManagement; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.repository.RepositorySystem; @@ -40,10 +41,11 @@ import org.codehaus.mojo.versions.api.recording.DependencyChangeRecord; import org.codehaus.mojo.versions.ordering.InvalidSegmentException; import org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader; -import org.codehaus.mojo.versions.utils.SegmentUtils; import static java.util.Collections.singletonList; import static java.util.Optional.empty; +import static java.util.Optional.of; +import static org.codehaus.mojo.versions.api.Segment.*; /** * Replaces any release versions with the latest snapshot version (if it has been deployed). @@ -128,8 +130,27 @@ private void useLatestSnapshots( Collection dependencies, DependencyChangeRecord.ChangeKind changeKind) throws XMLStreamException, MojoExecutionException, VersionRetrievalException { - Optional unchangedSegment = SegmentUtils.determineUnchangedSegment( - allowMajorUpdates, allowMinorUpdates, allowIncrementalUpdates, getLog()); + Log log = getLog(); + if (log != null && !allowIncrementalUpdates) { + log.info("Assuming allowMinorUpdates false because allowIncrementalUpdates is false."); + } + + if (log != null && !allowMinorUpdates) { + log.info("Assuming allowMajorUpdates false because allowMinorUpdates is false."); + } + + Optional unchangedSegment1 = allowMajorUpdates && allowMinorUpdates && allowIncrementalUpdates + ? empty() + : allowMinorUpdates && allowIncrementalUpdates + ? of(MAJOR) + : allowIncrementalUpdates ? of(MINOR) : of(INCREMENTAL); + if (log != null && log.isDebugEnabled()) { + log.debug(unchangedSegment1 + .map(Segment::minorTo) + .map(Segment::toString) + .orElse("ALL") + " version changes allowed"); + } + Optional unchangedSegment = unchangedSegment1; useLatestVersions( pom, diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseLatestVersionsMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseLatestVersionsMojo.java index 1dc4615cc..c324ef2d6 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseLatestVersionsMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseLatestVersionsMojo.java @@ -27,6 +27,7 @@ import org.apache.maven.model.DependencyManagement; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.repository.RepositorySystem; @@ -38,10 +39,11 @@ import org.codehaus.mojo.versions.api.recording.DependencyChangeRecord; import org.codehaus.mojo.versions.ordering.InvalidSegmentException; import org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader; -import org.codehaus.mojo.versions.utils.SegmentUtils; import static java.util.Collections.singletonList; import static java.util.Optional.empty; +import static java.util.Optional.of; +import static org.codehaus.mojo.versions.api.Segment.*; /** * Replaces any version with the latest version found in the artifactory. @@ -143,8 +145,27 @@ private void useLatestVersions( Collection dependencies, DependencyChangeRecord.ChangeKind changeKind) throws XMLStreamException, MojoExecutionException, VersionRetrievalException { - Optional unchangedSegment = SegmentUtils.determineUnchangedSegment( - allowMajorUpdates, allowMinorUpdates, allowIncrementalUpdates, getLog()); + Log log = getLog(); + if (log != null && !allowIncrementalUpdates) { + log.info("Assuming allowMinorUpdates false because allowIncrementalUpdates is false."); + } + + if (log != null && !allowMinorUpdates) { + log.info("Assuming allowMajorUpdates false because allowMinorUpdates is false."); + } + + Optional unchangedSegment1 = allowMajorUpdates && allowMinorUpdates && allowIncrementalUpdates + ? empty() + : allowMinorUpdates && allowIncrementalUpdates + ? of(MAJOR) + : allowIncrementalUpdates ? of(MINOR) : of(INCREMENTAL); + if (log != null && log.isDebugEnabled()) { + log.debug(unchangedSegment1 + .map(Segment::minorTo) + .map(Segment::toString) + .orElse("ALL") + " version changes allowed"); + } + Optional unchangedSegment = unchangedSegment1; useLatestVersions( pom, diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseNextSnapshotsMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseNextSnapshotsMojo.java index 802528c54..8e4e96998 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseNextSnapshotsMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/UseNextSnapshotsMojo.java @@ -28,6 +28,7 @@ import org.apache.maven.model.DependencyManagement; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.repository.RepositorySystem; @@ -39,10 +40,11 @@ import org.codehaus.mojo.versions.api.recording.DependencyChangeRecord; import org.codehaus.mojo.versions.ordering.InvalidSegmentException; import org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader; -import org.codehaus.mojo.versions.utils.SegmentUtils; import static java.util.Collections.singletonList; import static java.util.Optional.empty; +import static java.util.Optional.of; +import static org.codehaus.mojo.versions.api.Segment.*; /** * Replaces any release versions with the next snapshot version (if it has been deployed). @@ -127,8 +129,27 @@ private void useNextSnapshots( Collection dependencies, DependencyChangeRecord.ChangeKind changeKind) throws XMLStreamException, MojoExecutionException, VersionRetrievalException { - Optional unchangedSegment = SegmentUtils.determineUnchangedSegment( - allowMajorUpdates, allowMinorUpdates, allowIncrementalUpdates, getLog()); + Log log = getLog(); + if (log != null && !allowIncrementalUpdates) { + log.info("Assuming allowMinorUpdates false because allowIncrementalUpdates is false."); + } + + if (log != null && !allowMinorUpdates) { + log.info("Assuming allowMajorUpdates false because allowMinorUpdates is false."); + } + + Optional unchangedSegment1 = allowMajorUpdates && allowMinorUpdates && allowIncrementalUpdates + ? empty() + : allowMinorUpdates && allowIncrementalUpdates + ? of(MAJOR) + : allowIncrementalUpdates ? of(MINOR) : of(INCREMENTAL); + if (log != null && log.isDebugEnabled()) { + log.debug(unchangedSegment1 + .map(Segment::minorTo) + .map(Segment::toString) + .orElse("ALL") + " version changes allowed"); + } + Optional unchangedSegment = unchangedSegment1; useLatestVersions( pom, diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/OverviewStats.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/OverviewStats.java index 1553ccdfa..5b5d64750 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/OverviewStats.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/OverviewStats.java @@ -57,7 +57,7 @@ public class OverviewStats { * @param updates collection of all version updates, typically from * {@linkplain org.codehaus.mojo.versions.reporting.model.DependencyUpdatesModel#getAllUpdates()} * @param cache if not null, cache to retrieve the version information, initialised with - * the {@link ArtifactVersions#getNewestUpdate(Optional, boolean)} update information + * the {@link ArtifactVersions#getNewestUpdateWithinSegment(Optional, boolean)} update information * @param subclass of {@linkplain OverviewStats} * @param subclass of {@linkplain ArtifactVersions} * @param allowSnapshots whether snapshots should be included @@ -86,7 +86,7 @@ protected static ArtifactVersion getNewestUpd ArtifactVersionsCache cache, V details, Optional segment, boolean allowSnapshots) { return cache != null ? cache.get(details, segment, allowSnapshots) - : details.getNewestUpdate(segment, allowSnapshots); + : details.getNewestUpdateWithinSegment(segment, allowSnapshots); } public int getMajor() { diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/PluginOverviewStats.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/PluginOverviewStats.java index 5fa0e5632..a9ab2b1a8 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/PluginOverviewStats.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/reporting/PluginOverviewStats.java @@ -53,7 +53,7 @@ public void incrementDependencies() { * * @param updates collection of all version updates, typically from {@linkplain PluginUpdatesModel#getAllUpdates()} * @param cache if not null, cache to retrieve the version information, initialised with - * the {@link ArtifactVersions#getNewestUpdate(Optional, boolean)} update information + * the {@link ArtifactVersions#getNewestUpdateWithinSegment(Optional, boolean)} update information * @param always equal to {@linkplain PluginOverviewStats} * @param always equal to {@linkplain PluginUpdatesDetails} * @param allowSnapshots whether snapshots should be included diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/xml/DependencyUpdatesXmlReportRenderer.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/xml/DependencyUpdatesXmlReportRenderer.java index d009a3853..8cdec4a6a 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/xml/DependencyUpdatesXmlReportRenderer.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/xml/DependencyUpdatesXmlReportRenderer.java @@ -60,7 +60,7 @@ public class DependencyUpdatesXmlReportRenderer implements ReportRenderer { private final DependencyUpdatesModel model; private final Path outputFile; private final ArtifactVersionsCache newestUpdateCache = - new ArtifactVersionsCache(AbstractVersionDetails::getNewestUpdate); + new ArtifactVersionsCache(AbstractVersionDetails::getNewestUpdateWithinSegment); private final boolean allowSnapshots; @@ -126,7 +126,7 @@ private static List createDependencyInfo( setType(e.getKey().getType()); setClassifier(e.getKey().getClassifier()); - ofNullable(e.getValue().getNewestUpdate(empty(), allowSnapshots)) + ofNullable(e.getValue().getNewestUpdateWithinSegment(empty(), allowSnapshots)) .map(ArtifactVersion::toString) .ifPresent(this::setLastVersion); diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/xml/PluginUpdatesXmlReportRenderer.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/xml/PluginUpdatesXmlReportRenderer.java index c2921d3bd..7aac9e16a 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/xml/PluginUpdatesXmlReportRenderer.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/xml/PluginUpdatesXmlReportRenderer.java @@ -60,7 +60,7 @@ public class PluginUpdatesXmlReportRenderer implements ReportRenderer { private final PluginUpdatesModel model; private final Path outputFile; private final ArtifactVersionsCache newestUpdateCache = - new ArtifactVersionsCache(AbstractVersionDetails::getNewestUpdate); + new ArtifactVersionsCache(AbstractVersionDetails::getNewestUpdateWithinSegment); private final boolean allowSnapshots; @@ -126,7 +126,7 @@ private static List createPluginInfo( setType(e.getKey().getType()); setClassifier(e.getKey().getClassifier()); - ofNullable(e.getValue().getNewestUpdate(empty(), allowSnapshots)) + ofNullable(e.getValue().getNewestUpdateWithinSegment(empty(), allowSnapshots)) .map(ArtifactVersion::toString) .ifPresent(this::setLastVersion); diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/xml/PropertyUpdatesXmlReportRenderer.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/xml/PropertyUpdatesXmlReportRenderer.java index 5806f217f..8ad0e612f 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/xml/PropertyUpdatesXmlReportRenderer.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/xml/PropertyUpdatesXmlReportRenderer.java @@ -59,7 +59,7 @@ public class PropertyUpdatesXmlReportRenderer implements ReportRenderer { private final PropertyUpdatesModel model; private final Path outputFile; private final ArtifactVersionsCache newestUpdateCache = - new ArtifactVersionsCache(AbstractVersionDetails::getNewestUpdate); + new ArtifactVersionsCache(AbstractVersionDetails::getNewestUpdateWithinSegment); private final boolean allowSnapshots; /** @@ -128,7 +128,7 @@ private static List createPropertyInfo( .collect(Collectors.toList())); } setCurrentVersion(e.getKey().getVersion()); - ofNullable(e.getValue().getNewestUpdate(empty(), allowSnapshots)) + ofNullable(e.getValue().getNewestUpdateWithinSegment(empty(), allowSnapshots)) .map(ArtifactVersion::toString) .ifPresent(this::setLastVersion); diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/DisplayDependencyUpdatesMojoTest.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/DisplayDependencyUpdatesMojoTest.java index bb039104d..399159583 100644 --- a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/DisplayDependencyUpdatesMojoTest.java +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/DisplayDependencyUpdatesMojoTest.java @@ -20,21 +20,19 @@ */ import java.io.File; -import java.io.IOException; import java.nio.file.Files; -import java.nio.file.Path; import java.util.Arrays; import java.util.HashMap; import java.util.List; import org.apache.maven.model.Model; import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.testing.AbstractMojoTestCase; import org.apache.maven.plugin.testing.MojoRule; import org.apache.maven.project.MavenProject; import org.codehaus.mojo.versions.filtering.WildcardMatcher; import org.codehaus.mojo.versions.model.TestIgnoreVersions; +import org.codehaus.mojo.versions.utils.CloseableTempFile; import org.codehaus.mojo.versions.utils.DependencyBuilder; import org.hamcrest.Matchers; import org.junit.Rule; @@ -45,16 +43,9 @@ import static java.util.Collections.singletonList; import static org.codehaus.mojo.versions.model.TestIgnoreVersions.TYPE_REGEX; import static org.codehaus.mojo.versions.model.TestIgnoreVersions.matches; -import static org.codehaus.mojo.versions.utils.MockUtils.mockAetherRepositorySystem; -import static org.codehaus.mojo.versions.utils.MockUtils.mockMavenSession; -import static org.codehaus.mojo.versions.utils.MockUtils.mockRepositorySystem; +import static org.codehaus.mojo.versions.utils.MockUtils.*; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.anyOf; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.*; /** * Basic tests for {@linkplain DisplayDependencyUpdatesMojo}. @@ -83,10 +74,7 @@ public void testValidateGAVListFailed() { @Test public void testRuleSetPresentAndWorking() throws Exception { - File outputFile = null; - try { - outputFile = File.createTempFile("display-dependency-updates", ""); - assert outputFile.exists(); + try (CloseableTempFile tempFile = new CloseableTempFile("display-dependency-updates")) { DisplayDependencyUpdatesMojo mojo = (DisplayDependencyUpdatesMojo) mojoRule.lookupConfiguredMojo( new File("target/test-classes/org/codehaus/mojo/display-dependency-updates/ruleset"), @@ -108,7 +96,7 @@ public void testRuleSetPresentAndWorking() throws Exception { .withVersion(".+-M\\d+")))); // This is just an example of how to create it-style tests as unit tests; the advantage is easier debugging - mojo.outputFile = outputFile; + mojo.outputFile = tempFile.getPath().toFile(); mojo.aetherRepositorySystem = mockAetherRepositorySystem(new HashMap() { { put("dummy-api", new String[] {"1.0.0", "1.0.1", "1.1.0-M1", "1.2.0-SNAPSHOT"}); @@ -117,10 +105,8 @@ public void testRuleSetPresentAndWorking() throws Exception { assertThat(mojo.ruleSet.getIgnoreVersions(), Matchers.hasSize(3)); mojo.execute(); - List output = Files.readAllLines(outputFile.toPath(), UTF_8); + List output = Files.readAllLines(tempFile.getPath(), UTF_8); assertThat(output, not(hasItem(containsString("1.1.0-M1")))); - } finally { - assert outputFile == null || !outputFile.exists() || outputFile.delete(); } } @@ -145,12 +131,8 @@ private MavenProject createProject() { } @Test - public void testVersionsWithQualifiersNotConsideredAsMinorUpdates() - throws MojoExecutionException, MojoFailureException, IllegalAccessException, IOException { - Path tempPath = null; - try { - tempPath = Files.createTempFile("display-dependency-updates", ""); - final File tempFile = tempPath.toFile(); + public void testVersionsWithQualifiersNotConsideredAsMinorUpdates() throws Exception { + try (CloseableTempFile tempFile = new CloseableTempFile("display-dependency-updates")) { new DisplayDependencyUpdatesMojo( mockRepositorySystem(), mockAetherRepositorySystem(new HashMap() { @@ -164,13 +146,12 @@ public void testVersionsWithQualifiersNotConsideredAsMinorUpdates() null) { { setProject(createProject()); - setVariableValueToObject(this, "allowAnyUpdates", false); setVariableValueToObject(this, "allowMajorUpdates", false); setVariableValueToObject(this, "processDependencies", true); setVariableValueToObject(this, "dependencyIncludes", singletonList(WildcardMatcher.WILDCARD)); setVariableValueToObject(this, "dependencyExcludes", emptyList()); this.allowSnapshots = true; - this.outputFile = tempFile; + this.outputFile = tempFile.getPath().toFile(); setPluginContext(new HashMap<>()); session = mockMavenSession(); @@ -178,25 +159,17 @@ public void testVersionsWithQualifiersNotConsideredAsMinorUpdates() }.execute(); assertThat( - String.join("", Files.readAllLines(tempPath)), + String.join("", Files.readAllLines(tempFile.getPath())), not(anyOf( containsString("2.0.0-SNAPSHOT"), containsString("2.0.0-beta"), containsString("2.0.0-rc1")))); - } finally { - if (tempPath != null && Files.exists(tempPath)) { - Files.delete(tempPath); - } } } @Test - public void testAllowMajorUpdatesFalse() - throws MojoExecutionException, MojoFailureException, IllegalAccessException, IOException { - Path tempPath = null; - try { - tempPath = Files.createTempFile("display-dependency-updates", ""); - final File tempFile = tempPath.toFile(); + public void testAllowMajorUpdatesFalse() throws Exception { + try (CloseableTempFile tempFile = new CloseableTempFile("display-dependency-updates")) { new DisplayDependencyUpdatesMojo( mockRepositorySystem(), mockAetherRepositorySystem(new HashMap() { @@ -208,36 +181,27 @@ public void testAllowMajorUpdatesFalse() null) { { setProject(createProject()); - setVariableValueToObject(this, "allowAnyUpdates", false); setVariableValueToObject(this, "allowMajorUpdates", false); setVariableValueToObject(this, "processDependencies", true); setVariableValueToObject(this, "dependencyIncludes", singletonList(WildcardMatcher.WILDCARD)); setVariableValueToObject(this, "dependencyExcludes", emptyList()); - this.outputFile = tempFile; + this.outputFile = tempFile.getPath().toFile(); setPluginContext(new HashMap<>()); session = mockMavenSession(); } }.execute(); - String output = String.join("", Files.readAllLines(tempPath)); + String output = String.join("", Files.readAllLines(tempFile.getPath())); assertThat(output, containsString("1.1.0")); assertThat(output, not(containsString("2.0.0"))); - } finally { - if (tempPath != null && Files.exists(tempPath)) { - Files.delete(tempPath); - } } } @Test - public void testAllowMinorUpdatesFalse() - throws MojoExecutionException, MojoFailureException, IllegalAccessException, IOException { - Path tempPath = null; - try { - tempPath = Files.createTempFile("display-dependency-updates", ""); - final File tempFile = tempPath.toFile(); + public void testAllowMinorUpdatesFalse() throws Exception { + try (CloseableTempFile tempFile = new CloseableTempFile("display-dependency-updates")) { new DisplayDependencyUpdatesMojo( mockRepositorySystem(), mockAetherRepositorySystem(new HashMap() { @@ -249,37 +213,28 @@ public void testAllowMinorUpdatesFalse() null) { { setProject(createProject()); - setVariableValueToObject(this, "allowAnyUpdates", false); setVariableValueToObject(this, "allowMinorUpdates", false); setVariableValueToObject(this, "processDependencies", true); setVariableValueToObject(this, "dependencyIncludes", singletonList(WildcardMatcher.WILDCARD)); setVariableValueToObject(this, "dependencyExcludes", emptyList()); - this.outputFile = tempFile; + this.outputFile = tempFile.getPath().toFile(); setPluginContext(new HashMap<>()); session = mockMavenSession(); } }.execute(); - String output = String.join("", Files.readAllLines(tempPath)); + String output = String.join("", Files.readAllLines(tempFile.getPath())); assertThat(output, containsString("1.0.1")); assertThat(output, not(containsString("1.1.0"))); assertThat(output, not(containsString("2.0.0"))); - } finally { - if (tempPath != null && Files.exists(tempPath)) { - Files.delete(tempPath); - } } } @Test - public void testAllowIncrementalUpdatesFalse() - throws MojoExecutionException, MojoFailureException, IllegalAccessException, IOException { - Path tempPath = null; - try { - tempPath = Files.createTempFile("display-dependency-updates", ""); - final File tempFile = tempPath.toFile(); + public void testAllowIncrementalUpdatesFalse() throws Exception { + try (CloseableTempFile tempFile = new CloseableTempFile("display-dependency-updates")) { new DisplayDependencyUpdatesMojo( mockRepositorySystem(), mockAetherRepositorySystem(new HashMap() { @@ -291,38 +246,29 @@ public void testAllowIncrementalUpdatesFalse() null) { { setProject(createProject()); - setVariableValueToObject(this, "allowAnyUpdates", false); setVariableValueToObject(this, "allowIncrementalUpdates", false); setVariableValueToObject(this, "processDependencies", true); setVariableValueToObject(this, "dependencyIncludes", singletonList(WildcardMatcher.WILDCARD)); setVariableValueToObject(this, "dependencyExcludes", emptyList()); - this.outputFile = tempFile; + this.outputFile = tempFile.getPath().toFile(); setPluginContext(new HashMap<>()); session = mockMavenSession(); } }.execute(); - String output = String.join("", Files.readAllLines(tempPath)); + String output = String.join("", Files.readAllLines(tempFile.getPath())); assertThat(output, containsString("1.0.0-1")); assertThat(output, not(containsString("1.0.1"))); assertThat(output, not(containsString("1.1.0"))); assertThat(output, not(containsString("2.0.0"))); - } finally { - if (tempPath != null && Files.exists(tempPath)) { - Files.delete(tempPath); - } } } @Test - public void testVersionsWithQualifiersNotConsideredAsIncrementalUpdates() - throws MojoExecutionException, MojoFailureException, IllegalAccessException, IOException { - Path tempPath = null; - try { - tempPath = Files.createTempFile("display-dependency-updates", ""); - final File tempFile = tempPath.toFile(); + public void testVersionsWithQualifiersNotConsideredAsIncrementalUpdates() throws Exception { + try (CloseableTempFile tempFile = new CloseableTempFile("display-dependency-updates")) { new DisplayDependencyUpdatesMojo( mockRepositorySystem(), mockAetherRepositorySystem(new HashMap() { @@ -336,13 +282,12 @@ public void testVersionsWithQualifiersNotConsideredAsIncrementalUpdates() null) { { setProject(createProject()); - setVariableValueToObject(this, "allowAnyUpdates", false); setVariableValueToObject(this, "allowMinorUpdates", false); setVariableValueToObject(this, "processDependencies", true); setVariableValueToObject(this, "dependencyIncludes", singletonList(WildcardMatcher.WILDCARD)); setVariableValueToObject(this, "dependencyExcludes", emptyList()); this.allowSnapshots = true; - this.outputFile = tempFile; + this.outputFile = tempFile.getPath().toFile(); setPluginContext(new HashMap<>()); session = mockMavenSession(); @@ -350,24 +295,17 @@ public void testVersionsWithQualifiersNotConsideredAsIncrementalUpdates() }.execute(); assertThat( - String.join("", Files.readAllLines(tempPath)), + String.join("", Files.readAllLines(tempFile.getPath())), not(anyOf( containsString("1.9.0-SNAPSHOT"), containsString("1.9.0-beta"), containsString("1.9.0-rc1")))); - } finally { - if (tempPath != null && Files.exists(tempPath)) { - Files.delete(tempPath); - } } } @Test public void testDetermineUpdatedSegment() throws Exception { - File outputFile = null; - try { - outputFile = File.createTempFile("display-dependency-updates", ""); - assert outputFile.exists(); + try (CloseableTempFile tempFile = new CloseableTempFile("display-dependency-updates")) { DisplayDependencyUpdatesMojo mojo = (DisplayDependencyUpdatesMojo) mojoRule.lookupConfiguredMojo( new File("target/test-classes/org/codehaus/mojo/display-dependency-updates/ruleset"), @@ -390,7 +328,7 @@ public void testDetermineUpdatedSegment() throws Exception { .withVersion(".+-M\\d+")))); // This is just an example of how to create it-style tests as unit tests; the advantage is easier debugging - mojo.outputFile = outputFile; + mojo.outputFile = tempFile.getPath().toFile(); mojo.aetherRepositorySystem = mockAetherRepositorySystem(new HashMap() { { put("dummy-api", new String[] {"1.0.0", "1.0.1", "1.1.0-M1", "1.2.0-SNAPSHOT"}); @@ -399,26 +337,21 @@ public void testDetermineUpdatedSegment() throws Exception { assertThat(mojo.ruleSet.getIgnoreVersions(), Matchers.hasSize(3)); mojo.execute(); - List output = Files.readAllLines(outputFile.toPath(), UTF_8); + List output = Files.readAllLines(tempFile.getPath(), UTF_8); assertThat(output, not(hasItem(containsString("1.1.0-M1")))); - } finally { - assert outputFile == null || !outputFile.exists() || outputFile.delete(); } } @Test public void testVersionInterpolation() throws Exception { - File outputFile = null; - try { - outputFile = File.createTempFile("display-dependency-updates", ""); - assert outputFile.exists(); + try (CloseableTempFile tempFile = new CloseableTempFile("display-dependency-updates")) { DisplayDependencyUpdatesMojo mojo = (DisplayDependencyUpdatesMojo) mojoRule.lookupConfiguredMojo( new File("target/test-classes/org/codehaus/mojo/display-dependency-updates/version-interpolation"), "display-dependency-updates"); // This is just an example of how to create it-style tests as unit tests; the advantage is easier debugging - mojo.outputFile = outputFile; + mojo.outputFile = tempFile.getPath().toFile(); mojo.aetherRepositorySystem = mockAetherRepositorySystem(new HashMap() { { put("dummy-api", new String[] {"2.0.1"}); @@ -426,25 +359,19 @@ public void testVersionInterpolation() throws Exception { }); setVariableValueToObject(mojo, "processDependencyManagementTransitive", false); mojo.execute(); - List output = Files.readAllLines(outputFile.toPath(), UTF_8); + List output = Files.readAllLines(tempFile.getPath(), UTF_8); assertThat(output, not(hasItem(containsString("mycomponent.version")))); - } finally { - assert outputFile == null || !outputFile.exists() || outputFile.delete(); } } @Test - public void testAllowSnapshots() - throws MojoExecutionException, MojoFailureException, IllegalAccessException, IOException { - Path tempPath = null; - try { - tempPath = Files.createTempFile("display-dependency-updates", ""); - File tempFile = tempPath.toFile(); + public void testAllowSnapshots() throws Exception { + try (CloseableTempFile tempFile = new CloseableTempFile("display-dependency-updates")) { new DisplayDependencyUpdatesMojo( mockRepositorySystem(), mockAetherRepositorySystem(new HashMap() { { - put("default-dependency", new String[] {"1.0.0", "1.0.1-SNAPSHOT"}); + put("default-dependency", new String[] {"2.0.0-SNAPSHOT"}); } }), null, @@ -455,20 +382,60 @@ public void testAllowSnapshots() setVariableValueToObject(this, "dependencyIncludes", singletonList(WildcardMatcher.WILDCARD)); setVariableValueToObject(this, "dependencyExcludes", emptyList()); this.allowSnapshots = true; - this.outputFile = tempFile; + this.outputFile = tempFile.getPath().toFile(); setPluginContext(new HashMap<>()); session = mockMavenSession(); } }.execute(); - String output = String.join("", Files.readAllLines(tempPath)); + String output = String.join("", Files.readAllLines(tempFile.getPath())); - assertThat(output, containsString("1.0.1-SNAPSHOT")); - } finally { - if (tempPath != null && Files.exists(tempPath)) { - Files.delete(tempPath); - } + assertThat(output, containsString("2.0.0-SNAPSHOT")); } } + + private void testAllowUpdatesFromLesserSegments(String availableVersion) throws Exception { + try (CloseableTempFile tempFile = new CloseableTempFile("display-dependency-updates")) { + new DisplayDependencyUpdatesMojo( + mockRepositorySystem(), + mockAetherRepositorySystem(new HashMap() { + { + put("default-dependency", new String[] {availableVersion}); + } + }), + null, + null) { + { + setProject(createProject()); + setVariableValueToObject(this, "processDependencies", true); + setVariableValueToObject(this, "dependencyIncludes", singletonList(WildcardMatcher.WILDCARD)); + setVariableValueToObject(this, "dependencyExcludes", emptyList()); + this.outputFile = tempFile.getPath().toFile(); + setPluginContext(new HashMap<>()); + + session = mockMavenSession(); + } + }.execute(); + + String output = String.join("", Files.readAllLines(tempFile.getPath())); + + assertThat(output, containsString(availableVersion)); + } + } + + @Test + public void testAllowUpdatesFromLesserSegmentsMinor() throws Exception { + testAllowUpdatesFromLesserSegments("1.1.0"); + } + + @Test + public void testAllowUpdatesFromLesserSegmentsIncremental() throws Exception { + testAllowUpdatesFromLesserSegments("1.0.1"); + } + + @Test + public void testAllowUpdatesFromLesserSegmentsSubIncremental() throws Exception { + testAllowUpdatesFromLesserSegments("1.0.0-1"); + } } diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/DisplayParentUpdatesMojoTest.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/DisplayParentUpdatesMojoTest.java new file mode 100644 index 000000000..ab7752d5b --- /dev/null +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/DisplayParentUpdatesMojoTest.java @@ -0,0 +1,118 @@ +package org.codehaus.mojo.versions; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Collections; +import java.util.HashMap; + +import org.apache.maven.model.Model; +import org.apache.maven.project.MavenProject; +import org.apache.maven.repository.RepositorySystem; +import org.codehaus.mojo.versions.utils.TestChangeRecorder; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import static org.apache.commons.codec.CharEncoding.UTF_8; +import static org.codehaus.mojo.versions.utils.MockUtils.*; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; + +/** + * Basic tests for {@linkplain DisplayDependencyUpdatesMojo}. + * + * @author Andrzej Jarmoniuk + */ +public class DisplayParentUpdatesMojoTest { + + private TestChangeRecorder changeRecorder; + private Path tempFile; + private DisplayParentUpdatesMojo mojo; + private static RepositorySystem repositorySystem; + + private static org.eclipse.aether.RepositorySystem aetherRepositorySystem; + + @BeforeClass + public static void setUpStatic() { + repositorySystem = mockRepositorySystem(); + aetherRepositorySystem = mockAetherRepositorySystem(new HashMap() { + { + put("parent-artifact", new String[] {"7", "9"}); + } + }); + } + + @Before + public void setUp() throws IllegalAccessException, IOException { + tempFile = Files.createTempFile("display-parent-updates", "txt"); + changeRecorder = new TestChangeRecorder(); + mojo = + new DisplayParentUpdatesMojo( + repositorySystem, aetherRepositorySystem, null, changeRecorder.asTestMap()) { + { + setProject(createProject()); + reactorProjects = Collections.emptyList(); + session = mockMavenSession(); + outputFile = tempFile.toFile(); + outputEncoding = UTF_8; + setPluginContext(new HashMap()); + } + }; + } + + @After + public void tearDown() throws IOException { + Files.deleteIfExists(tempFile); + } + + private MavenProject createProject() { + return new MavenProject() { + { + setModel(new Model() { + { + setGroupId("default-group"); + setArtifactId("project-artifact"); + setVersion("1.0.1-SNAPSHOT"); + } + }); + + setParent(new MavenProject() { + { + setGroupId("default-group"); + setArtifactId("parent-artifact"); + setVersion("9"); + } + }); + } + }; + } + + @Test + public void testSingleDigitVersions() throws Exception { + mojo.execute(); + String output = String.join("", Files.readAllLines(tempFile)); + assertThat(output, not(containsString("7"))); + } +} diff --git a/versions-test/src/main/java/org/codehaus/mojo/versions/utils/CloseableTempFile.java b/versions-test/src/main/java/org/codehaus/mojo/versions/utils/CloseableTempFile.java new file mode 100644 index 000000000..a1d67b723 --- /dev/null +++ b/versions-test/src/main/java/org/codehaus/mojo/versions/utils/CloseableTempFile.java @@ -0,0 +1,48 @@ +package org.codehaus.mojo.versions.utils; + +/* + * Copyright MojoHaus and Contributors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +/** + * Closeable temporary file + */ +public class CloseableTempFile implements AutoCloseable { + private final Path path; + + /** + * @return path of the temporary file + */ + public Path getPath() { + return path; + } + + /** + * Creates a new temporary file with the given prefix + * @param prefix prefix of the temporary file + * @throws IOException thrown if file creation fails + */ + public CloseableTempFile(String prefix) throws IOException { + path = Files.createTempFile(prefix, ".tmp"); + } + + @Override + public void close() throws Exception { + Files.deleteIfExists(path); + } +}