001/*
002 * Forge Mod Loader
003 * Copyright (c) 2012-2013 cpw.
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser Public License v2.1
006 * which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
008 * 
009 * Contributors:
010 *     cpw - implementation
011 */
012
013package cpw.mods.fml.common.versioning;
014
015import java.util.List;
016import java.util.logging.Level;
017
018import com.google.common.base.Splitter;
019import com.google.common.base.Strings;
020import com.google.common.collect.Lists;
021
022import cpw.mods.fml.common.FMLLog;
023import cpw.mods.fml.common.LoaderException;
024
025/**
026 * Parses version strings according to the specification here:
027 * http://docs.codehaus.org/display/MAVEN/Versioning
028 * and allows for comparison of versions based on that document.
029 * Bounded version specifications are defined as
030 * http://maven.apache.org/plugins/maven-enforcer-plugin/rules/versionRanges.html
031 *
032 * Borrows heavily from maven version range management code
033 *
034 * @author cpw
035 *
036 */
037public class VersionParser
038{
039    private static final Splitter SEPARATOR = Splitter.on('@').omitEmptyStrings().trimResults();
040    public static ArtifactVersion parseVersionReference(String labelledRef)
041    {
042        if (Strings.isNullOrEmpty(labelledRef))
043        {
044            throw new RuntimeException(String.format("Empty reference %s", labelledRef));
045        }
046        List<String> parts = Lists.newArrayList(SEPARATOR.split(labelledRef));
047        if (parts.size()>2)
048        {
049            throw new RuntimeException(String.format("Invalid versioned reference %s", labelledRef));
050        }
051        if (parts.size()==1)
052        {
053            return new DefaultArtifactVersion(parts.get(0), true);
054        }
055        return new DefaultArtifactVersion(parts.get(0),parseRange(parts.get(1)));
056    }
057
058    public static boolean satisfies(ArtifactVersion target, ArtifactVersion source)
059    {
060        return target.containsVersion(source);
061    }
062
063    public static VersionRange parseRange(String range)
064    {
065        try
066        {
067            return VersionRange.createFromVersionSpec(range);
068        }
069        catch (InvalidVersionSpecificationException e)
070        {
071            FMLLog.log(Level.SEVERE, e, "Unable to parse a version range specification successfully %s", range);
072            throw new LoaderException(e);
073        }
074    }
075}