org.crsh.cmdline.OptionDescriptor Maven / Gradle / Ivy
/*
* Copyright (C) 2012 eXo Platform SAS.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.crsh.cmdline;
import org.crsh.cmdline.binding.TypeBinding;
import org.crsh.cmdline.matcher.CmdSyntaxException;
import org.crsh.cmdline.spi.Completer;
import org.crsh.cmdline.type.ValueType;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class OptionDescriptor extends ParameterDescriptor {
/** . */
private final int arity;
/** . */
private final List names;
public OptionDescriptor(
B binding,
ParameterType> type,
List names,
Description info,
boolean required,
boolean password,
boolean unquote,
Class extends Completer> completerType,
Annotation annotation) throws IllegalValueTypeException, IllegalParameterException {
super(
binding,
type,
info,
required,
password,
unquote,
completerType,
annotation);
//
if (getMultiplicity() == Multiplicity.MULTI && getType() == ValueType.BOOLEAN) {
throw new IllegalParameterException();
}
//
names = new ArrayList(names);
for (String name : names) {
if (name == null) {
throw new IllegalParameterException("Option name must not be null");
}
if (name.length() == 0) {
throw new IllegalParameterException("Option name cannot be empty");
}
if (name.contains("-")) {
throw new IllegalParameterException("Option name must not contain the hyphen character");
}
}
//
if (getType() == ValueType.BOOLEAN) {
arity = 0;
} else {
arity = 1;
}
//
this.names = Collections.unmodifiableList(names);
}
public int getArity() {
return arity;
}
public List getNames() {
return names;
}
@Override
public Object parse(List values) throws CmdSyntaxException {
if (arity == 0) {
if (values.size() > 0) {
throw new CmdSyntaxException("Too many option values: " + values);
}
// It's a boolean and it is true
return Boolean.TRUE;
} else {
if (getMultiplicity() == Multiplicity.SINGLE) {
if (values.size() > 1) {
throw new CmdSyntaxException("Too many option values: " + values);
}
String value = values.get(0);
try {
return parse(value);
} catch (Exception e) {
throw new CmdSyntaxException("Could not parse value: <" + value + ">");
}
} else {
List