EnumParser.java

/*
 * Copyright 2023 Terminal Utils Authors
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

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));
    }
}