package leigh.build;

import com.vdurmont.semver4j.Semver;

import java.util.Map;
import java.util.Properties;

/**
 * This class provides utility methods for working with versions and version strings.
 *
 * @author Alex Leigh
 */
public class VersionUtil {
    /**
     * Given a properties file containing versions with keys ending in <code>keySuffix</code>, strip the pre-release tag
     * if any from the version and update the properties file.
     * <p>
     * Returns <code>true</code> if any entry was modified, otherwise returns <code>false</code>.
     * <p>
     * Limitations: The parser has difficulty with versions that do not include all 3 version numbers,
     * so 1.1-SNAPSHOT may not parse properly, but 1.1.0-SNAPSHOT will. Strictly speaking this is not a
     * limitation as all three numbers are required for a legal Semmantic Version. cite: https://semver.org/
     */
    public static boolean release(Properties p, String keySuffix) {
        boolean didWork = false;

        for (Map.Entry<Object, Object> entry : p.entrySet()) {
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();

            if (key.endsWith(keySuffix)) {
                Semver v = new Semver(value);
                if (v.getSuffixTokens() != null) {
                    p.setProperty(key, v.withClearedSuffix().toString());
                    didWork = true;
                }
            }
        }
        return didWork;
    }
}