VersionStrategy.java

  1. /*
  2.  * Licensed under the Apache License, Version 2.0 (the "License");
  3.  * you may not use this file except in compliance with the License.
  4.  * You may obtain a copy of the License at
  5.  *
  6.  * http://www.apache.org/licenses/LICENSE-2.0
  7.  *
  8.  * Unless required by applicable law or agreed to in writing, software
  9.  * distributed under the License is distributed on an "AS IS" BASIS,
  10.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11.  * See the License for the specific language governing permissions and
  12.  * limitations under the License.
  13.  */

  14. package de.softwareforge.testing.maven;

  15. import org.eclipse.aether.util.version.GenericVersionScheme;
  16. import org.eclipse.aether.version.InvalidVersionSpecificationException;
  17. import org.eclipse.aether.version.Version;
  18. import org.eclipse.aether.version.VersionRange;

  19. interface VersionStrategy {

  20.     static VersionStrategy partialMatch(String partial) {
  21.         return artifactVersion -> partial.isEmpty()
  22.                 || artifactVersion.toString().equals(partial)
  23.                 || artifactVersion.toString().startsWith(partial + '.');
  24.     }

  25.     static VersionStrategy exactMatch(String version) {
  26.         return artifactVersion -> artifactVersion.toString().equals(version);
  27.     }

  28.     static VersionStrategy semVerMatchMajor(int major) {
  29.         return new SemVerVersionStrategy(major, -1);
  30.     }

  31.     static VersionStrategy semVerMatchMinor(int major, int minor) {
  32.         return new SemVerVersionStrategy(major, minor);
  33.     }

  34.     boolean matchVersion(Version version);

  35.     class SemVerVersionStrategy implements VersionStrategy {

  36.         private static final GenericVersionScheme SCHEME = new GenericVersionScheme();

  37.         private final VersionRange range;

  38.         SemVerVersionStrategy(int major, int minor) {

  39.             StringBuilder matchString = new StringBuilder("[")
  40.                     .append(major)
  41.                     .append('.');

  42.             if (minor > 0) {
  43.                 matchString.append(minor)
  44.                         .append('.');
  45.             }

  46.             matchString.append("*]");

  47.             try {
  48.                 this.range = SCHEME.parseVersionRange(matchString.toString());
  49.             } catch (InvalidVersionSpecificationException e) {
  50.                 throw new IllegalArgumentException(e);
  51.             }
  52.         }

  53.         @Override
  54.         public boolean matchVersion(Version version) {
  55.             return range.containsVersion(version);
  56.         }
  57.     }
  58. }