EnumParser.java

package net.morimekta.terminal.args.parser;

import net.morimekta.terminal.args.ArgException;
import net.morimekta.terminal.args.ValueParser;

import java.util.EnumSet;

/**
 * A converter to enum constant values.
 */
public class EnumParser<E extends Enum<E>> implements ValueParser<E> {
    private final Class<E>   type;
    private final EnumSet<E> set;

    /**
     * @param klass The enum class.
     * @param set   The enum set of allowed values.
     */
    public EnumParser(Class<E> klass, EnumSet<E> set) {
        this.type = klass;
        this.set = set.clone();
    }

    /**
     * @param klass The enum class to get allow all enum values of.
     */
    public EnumParser(Class<E> klass) {
        this(klass, EnumSet.allOf(klass));
    }

    @Override
    public E parse(String name) {
        return set.stream()
                  .filter(e -> e.name().equals(name))
                  .findFirst()
                  .orElseThrow(() -> new ArgException("Invalid %s value %s", type.getSimpleName(), name));
    }
}