Home | History | Annotate | Download | only in options
      1 // Copyright 2014 The Bazel Authors. All rights reserved.
      2 //
      3 // Licensed under the Apache License, Version 2.0 (the "License");
      4 // you may not use this file except in compliance with the License.
      5 // You may obtain a copy of the License at
      6 //
      7 //    http://www.apache.org/licenses/LICENSE-2.0
      8 //
      9 // Unless required by applicable law or agreed to in writing, software
     10 // distributed under the License is distributed on an "AS IS" BASIS,
     11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     12 // See the License for the specific language governing permissions and
     13 // limitations under the License.
     14 
     15 package com.google.devtools.common.options;
     16 
     17 import com.google.devtools.common.options.Converters.BooleanConverter;
     18 
     19 /**
     20  * Converter that can also convert from booleans and enumerations.
     21  *
     22  * <p> This is able to additionally convert from the standard set of
     23  * boolean string values. If there is an overlap in values, those from
     24  * the underlying enumeration will be taken.
     25  */
     26 public abstract class BoolOrEnumConverter<T extends Enum<T>> extends EnumConverter<T>{
     27   private T falseValue;
     28   private T trueValue;
     29 
     30   /**
     31    * You *must* implement a zero-argument constructor that delegates
     32    * to this constructor, passing in the appropriate parameters. This
     33    * comes from the base {@link EnumConverter} class.
     34    *
     35    * @param enumType The type of your enumeration; usually a class literal
     36    *                 like MyEnum.class
     37    * @param typeName The intuitive name of your enumeration, for example, the
     38    *                 type name for CompilationMode might be "compilation mode".
     39    * @param trueValue The enumeration value to associate with {@code true}.
     40    * @param falseValue The enumeration value to associate with {@code false}.
     41    */
     42   protected BoolOrEnumConverter(Class<T> enumType, String typeName, T trueValue, T falseValue) {
     43     super(enumType, typeName);
     44     this.trueValue = trueValue;
     45     this.falseValue = falseValue;
     46   }
     47 
     48   @Override
     49   public T convert(String input) throws OptionsParsingException {
     50     try {
     51       return super.convert(input);
     52     } catch (OptionsParsingException eEnum) {
     53       try {
     54         BooleanConverter booleanConverter = new BooleanConverter();
     55         boolean value = booleanConverter.convert(input);
     56         return value ? trueValue : falseValue;
     57       } catch (OptionsParsingException eBoolean) {
     58         throw eEnum;
     59       }
     60     }
     61   }
     62 }
     63