001package org.apache.maven.plugins.enforcer;
002
003/*
004 * Licensed to the Apache Software Foundation (ASF) under one
005 * or more contributor license agreements.  See the NOTICE file
006 * distributed with this work for additional information
007 * regarding copyright ownership.  The ASF licenses this file
008 * to you under the Apache License, Version 2.0 (the
009 * "License"); you may not use this file except in compliance
010 * with the License.  You may obtain a copy of the License at
011 *
012 *  http://www.apache.org/licenses/LICENSE-2.0
013 *
014 * Unless required by applicable law or agreed to in writing,
015 * software distributed under the License is distributed on an
016 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
017 * KIND, either express or implied.  See the License for the
018 * specific language governing permissions and limitations
019 * under the License.
020 */
021
022import java.util.List;
023
024import org.apache.maven.artifact.versioning.ArtifactVersion;
025import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
026import org.apache.maven.artifact.versioning.Restriction;
027import org.apache.maven.artifact.versioning.VersionRange;
028import org.apache.maven.enforcer.rule.api.EnforcerRule;
029import org.apache.maven.enforcer.rule.api.EnforcerRuleException;
030import org.apache.maven.plugin.logging.Log;
031import org.codehaus.plexus.util.StringUtils;
032
033/**
034 * Contains the common code to compare a version against a version range.
035 *
036 * @author <a href="mailto:brianf@apache.org">Brian Fox</a>
037 * @version $Id: AbstractVersionEnforcer.java 1802595 2017-07-21 13:39:48Z rfscholte $
038 */
039public abstract class AbstractVersionEnforcer
040    extends AbstractStandardEnforcerRule
041{
042
043    /**
044     * Specify the required version. Some examples are:
045     * <ul>
046     * <li><code>2.0.4</code> Version 2.0.4 and higher (different from Maven meaning)</li>
047     * <li><code>[2.0,2.1)</code> Versions 2.0 (included) to 2.1 (not included)</li>
048     * <li><code>[2.0,2.1]</code> Versions 2.0 to 2.1 (both included)</li>
049     * <li><code>[2.0.5,)</code> Versions 2.0.5 and higher</li>
050     * <li><code>(,2.0.5],[2.1.1,)</code> Versions up to 2.0.5 (included) and 2.1.1 or higher</li>
051     * </ul>
052     * 
053     * @see {@link #setVersion(String)}
054     * @see {@link #getVersion()}
055     */
056    private String version;
057
058    /**
059     * Compares the specified version to see if it is allowed by the defined version range.
060     *
061     * @param log the log
062     * @param variableName name of variable to use in messages (Example: "Maven" or "Java" etc).
063     * @param requiredVersionRange range of allowed versions.
064     * @param actualVersion the version to be checked.
065     * @throws EnforcerRuleException the enforcer rule exception
066     */
067    // CHECKSTYLE_OFF: LineLength
068    public void enforceVersion( Log log, String variableName, String requiredVersionRange, ArtifactVersion actualVersion )
069        throws EnforcerRuleException
070    // CHECKSTYLE_ON: LineLength
071    {
072        if ( StringUtils.isEmpty( requiredVersionRange ) )
073        {
074            throw new EnforcerRuleException( variableName + " version can't be empty." );
075        }
076        else
077        {
078
079            VersionRange vr;
080            String msg = "Detected " + variableName + " Version: " + actualVersion;
081
082            // short circuit check if the strings are exactly equal
083            if ( actualVersion.toString().equals( requiredVersionRange ) )
084            {
085                log.debug( msg + " is allowed in the range " + requiredVersionRange + "." );
086            }
087            else
088            {
089                try
090                {
091                    vr = VersionRange.createFromVersionSpec( requiredVersionRange );
092
093                    if ( containsVersion( vr, actualVersion ) )
094                    {
095                        log.debug( msg + " is allowed in the range " + requiredVersionRange + "." );
096                    }
097                    else
098                    {
099                        String message = getMessage();
100
101                        if ( StringUtils.isEmpty( message ) )
102                        {
103                            message = msg + " is not in the allowed range " + vr + ".";
104                        }
105
106                        throw new EnforcerRuleException( message );
107                    }
108                }
109                catch ( InvalidVersionSpecificationException e )
110                {
111                    throw new EnforcerRuleException( "The requested " + variableName + " version "
112                        + requiredVersionRange + " is invalid.", e );
113                }
114            }
115        }
116    }
117
118    /**
119     * Copied from Artifact.VersionRange. This is tweaked to handle singular ranges properly. Currently the default
120     * containsVersion method assumes a singular version means allow everything. This method assumes that "2.0.4" ==
121     * "[2.0.4,)"
122     *
123     * @param allowedRange range of allowed versions.
124     * @param theVersion the version to be checked.
125     * @return true if the version is contained by the range.
126     */
127    public static boolean containsVersion( VersionRange allowedRange, ArtifactVersion theVersion )
128    {
129        boolean matched = false;
130        ArtifactVersion recommendedVersion = allowedRange.getRecommendedVersion();
131        if ( recommendedVersion == null )
132        {
133            List<Restriction> restrictions = allowedRange.getRestrictions();
134            for ( Restriction restriction : restrictions )
135            {
136                if ( restriction.containsVersion( theVersion ) )
137                {
138                    matched = true;
139                    break;
140                }
141            }
142        }
143        else
144        {
145            // only singular versions ever have a recommendedVersion
146            @SuppressWarnings( "unchecked" )
147            int compareTo = recommendedVersion.compareTo( theVersion );
148            matched = ( compareTo <= 0 );
149        }
150        return matched;
151    }
152
153    @Override
154    public String getCacheId()
155    {
156        if ( StringUtils.isNotEmpty( version ) )
157        {
158            // return the hashcodes of the parameter that matters
159            return "" + version.hashCode();
160        }
161        else
162        {
163            return "0";
164        }
165
166    }
167
168    @Override
169    public boolean isCacheable()
170    {
171        // the maven version is not going to change between projects in the same build.
172        return true;
173    }
174
175    @Override
176    public boolean isResultValid( EnforcerRule theCachedRule )
177    {
178        // i will always return the hash of the parameters as my id. If my parameters are the same, this
179        // rule must always have the same result.
180        return true;
181    }
182
183    /**
184     * Gets the required version.
185     *
186     * @return the required version
187     */
188    public final String getVersion()
189    {
190        return this.version;
191    }
192
193    /**
194     * Specify the required version. Some examples are:
195     * <ul>
196     * <li><code>2.0.4</code> Version 2.0.4 and higher (different from Maven meaning)</li>
197     * <li><code>[2.0,2.1)</code> Versions 2.0 (included) to 2.1 (not included)</li>
198     * <li><code>[2.0,2.1]</code> Versions 2.0 to 2.1 (both included)</li>
199     * <li><code>[2.0.5,)</code> Versions 2.0.5 and higher</li>
200     * <li><code>(,2.0.5],[2.1.1,)</code> Versions up to 2.0.5 (included) and 2.1.1 or higher</li>
201     * </ul>
202     *
203     * @param theVersion the required version to set
204     */
205    public final void setVersion( String theVersion )
206    {
207        this.version = theVersion;
208    }
209
210}