use of org.apache.karaf.shell.commands.Option in project karaf by apache.
the class ArgumentCompleter method complete.
public int complete(final String buffer, final int cursor, final List<String> candidates) {
ArgumentList list = delimit(buffer, cursor);
int argpos = list.getArgumentPosition();
int argIndex = list.getCursorArgumentIndex();
//Store the argument list so that it can be used by completers.
CommandSession commandSession = CommandSessionHolder.getSession();
if (commandSession != null) {
commandSession.put(ARGUMENTS_LIST, list);
}
Completer comp = null;
String[] args = list.getArguments();
int index = 0;
// First argument is command name
if (index < argIndex) {
// Verify command name
if (!verifyCompleter(commandCompleter, args[index])) {
return -1;
}
// - we have a session
if (!args[index].contains(":") && commandSession != null) {
Function f1 = unProxy((Function) commandSession.get("*:" + args[index]));
Function f2 = unProxy(this.function);
if (f1 != null && f1 != f2) {
return -1;
}
}
index++;
} else {
comp = commandCompleter;
}
// Now, check options
if (comp == null) {
while (index < argIndex && args[index].startsWith("-")) {
if (!verifyCompleter(optionsCompleter, args[index])) {
return -1;
}
Option option = options.get(args[index]);
if (option == null) {
return -1;
}
Field field = fields.get(option);
if (field != null && field.getType() != boolean.class && field.getType() != Boolean.class) {
if (++index == argIndex) {
comp = NullCompleter.INSTANCE;
}
}
index++;
}
if (comp == null && index >= argIndex && index < args.length && args[index].startsWith("-")) {
comp = optionsCompleter;
}
}
//Now check for if last Option has a completer
int lastAgurmentIndex = argIndex - 1;
if (lastAgurmentIndex >= 1) {
Option lastOption = options.get(args[lastAgurmentIndex]);
if (lastOption != null) {
Field lastField = fields.get(lastOption);
if (lastField != null && lastField.getType() != boolean.class && lastField.getType() != Boolean.class) {
Option option = lastField.getAnnotation(Option.class);
if (option != null) {
Completer optionValueCompleter = null;
String name = option.name();
if (optionalCompleters != null && name != null) {
optionValueCompleter = optionalCompleters.get(name);
if (optionValueCompleter == null) {
String[] aliases = option.aliases();
if (aliases.length > 0) {
for (int i = 0; i < aliases.length && optionValueCompleter == null; i++) {
optionValueCompleter = optionalCompleters.get(option.aliases()[i]);
}
}
}
}
if (optionValueCompleter != null) {
comp = optionValueCompleter;
}
}
}
}
}
// Check arguments
if (comp == null) {
int indexArg = 0;
while (index < argIndex) {
Completer sub = argsCompleters.get(indexArg >= argsCompleters.size() ? argsCompleters.size() - 1 : indexArg);
if (!verifyCompleter(sub, args[index])) {
return -1;
}
index++;
indexArg++;
}
comp = argsCompleters.get(indexArg >= argsCompleters.size() ? argsCompleters.size() - 1 : indexArg);
}
int ret = comp.complete(list.getCursorArgument(), argpos, candidates);
if (ret == -1) {
return -1;
}
int pos = ret + (list.getBufferPosition() - argpos);
if ((buffer != null) && (cursor != buffer.length()) && isDelimiter(buffer, cursor)) {
for (int i = 0; i < candidates.size(); i++) {
String val = candidates.get(i);
while ((val.length() > 0) && isDelimiter(val, val.length() - 1)) {
val = val.substring(0, val.length() - 1);
}
candidates.set(i, val);
}
}
return pos;
}
use of org.apache.karaf.shell.commands.Option in project karaf by apache.
the class ActionMetaData method printUsage.
public void printUsage(Action action, PrintStream out, boolean globalScope, int termWidth) {
if (command != null) {
List<Argument> argumentsSet = new ArrayList<>(arguments.keySet());
argumentsSet.sort(Comparator.comparing(Argument::index));
Set<Option> optionsSet = new HashSet<>(options.keySet());
optionsSet.add(HelpOption.HELP);
if (command != null && (command.description() != null || command.name() != null)) {
out.println(INTENSITY_BOLD + "DESCRIPTION" + INTENSITY_NORMAL);
out.print(" ");
if (command.name() != null) {
if (globalScope) {
out.println(INTENSITY_BOLD + command.name() + INTENSITY_NORMAL);
} else {
out.println(command.scope() + ":" + INTENSITY_BOLD + command.name() + INTENSITY_NORMAL);
}
out.println();
}
out.print("\t");
out.println(command.description());
out.println();
}
StringBuffer syntax = new StringBuffer();
if (command != null) {
if (globalScope) {
syntax.append(command.name());
} else {
syntax.append(String.format("%s:%s", command.scope(), command.name()));
}
}
if (options.size() > 0) {
syntax.append(" [options]");
}
if (arguments.size() > 0) {
syntax.append(' ');
for (Argument argument : argumentsSet) {
if (!argument.required()) {
syntax.append(String.format("[%s] ", argument.name()));
} else {
syntax.append(String.format("%s ", argument.name()));
}
}
}
out.println(INTENSITY_BOLD + "SYNTAX" + INTENSITY_NORMAL);
out.print(" ");
out.println(syntax.toString());
out.println();
if (arguments.size() > 0) {
out.println(INTENSITY_BOLD + "ARGUMENTS" + INTENSITY_NORMAL);
for (Argument argument : argumentsSet) {
out.print(" ");
out.println(INTENSITY_BOLD + argument.name() + INTENSITY_NORMAL);
ActionMetaData.printFormatted(" ", argument.description(), termWidth, out, true);
if (!argument.required()) {
if (argument.valueToShowInHelp() != null && argument.valueToShowInHelp().length() != 0) {
if (Argument.DEFAULT_STRING.equals(argument.valueToShowInHelp())) {
Object o = getDefaultValue(action, argument);
String defaultValue = getDefaultValueString(o);
if (defaultValue != null) {
printDefaultsTo(out, defaultValue);
}
} else {
printDefaultsTo(out, argument.valueToShowInHelp());
}
}
}
}
out.println();
}
if (options.size() > 0) {
out.println(INTENSITY_BOLD + "OPTIONS" + INTENSITY_NORMAL);
for (Option option : optionsSet) {
String opt = option.name();
for (String alias : option.aliases()) {
opt += ", " + alias;
}
out.print(" ");
out.println(INTENSITY_BOLD + opt + INTENSITY_NORMAL);
ActionMetaData.printFormatted(" ", option.description(), termWidth, out, true);
if (option.valueToShowInHelp() != null && option.valueToShowInHelp().length() != 0) {
if (Option.DEFAULT_STRING.equals(option.valueToShowInHelp())) {
Object o = getDefaultValue(action, option);
String defaultValue = getDefaultValueString(o);
if (defaultValue != null) {
printDefaultsTo(out, defaultValue);
}
} else {
printDefaultsTo(out, option.valueToShowInHelp());
}
}
}
out.println();
}
if (command.detailedDescription().length() > 0) {
out.println(INTENSITY_BOLD + "DETAILS" + INTENSITY_NORMAL);
String desc = getDetailedDescription();
ActionMetaData.printFormatted(" ", desc, termWidth, out, true);
}
}
}
use of org.apache.karaf.shell.commands.Option in project karaf by apache.
the class DefaultActionPreparator method prepare.
public boolean prepare(Action action, CommandSession session, List<Object> params) throws Exception {
ActionMetaData actionMetaData = new ActionMetaDataFactory().create(action.getClass());
Map<Option, Field> options = actionMetaData.getOptions();
Map<Argument, Field> arguments = actionMetaData.getArguments();
List<Argument> orderedArguments = actionMetaData.getOrderedArguments();
Command command2 = actionMetaData.getCommand();
if (command2 == null) {
// to avoid NPE with subshell
return true;
}
String commandErrorSt = (command2 != null) ? COLOR_RED + "Error executing command " + command2.scope() + ":" + INTENSITY_BOLD + command2.name() + INTENSITY_NORMAL + COLOR_DEFAULT + ": " : "";
for (Object param : params) {
if (HelpOption.HELP.name().equals(param)) {
int termWidth = getWidth(session);
boolean globalScope = NameScoping.isGlobalScope(session, actionMetaData.getCommand().scope());
actionMetaData.printUsage(action, System.out, globalScope, termWidth);
return false;
}
}
// Populate
Map<Option, Object> optionValues = new HashMap<Option, Object>();
Map<Argument, Object> argumentValues = new HashMap<Argument, Object>();
boolean processOptions = true;
int argIndex = 0;
for (Iterator<Object> it = params.iterator(); it.hasNext(); ) {
Object param = it.next();
if (processOptions && param instanceof String && ((String) param).startsWith("-")) {
boolean isKeyValuePair = ((String) param).indexOf('=') != -1;
String name;
Object value = null;
if (isKeyValuePair) {
name = ((String) param).substring(0, ((String) param).indexOf('='));
value = ((String) param).substring(((String) param).indexOf('=') + 1);
} else {
name = (String) param;
}
Option option = null;
for (Option opt : options.keySet()) {
if (name.equals(opt.name()) || Arrays.asList(opt.aliases()).contains(name)) {
option = opt;
break;
}
}
if (option == null) {
throw new CommandException(commandErrorSt + "undefined option " + INTENSITY_BOLD + param + INTENSITY_NORMAL + "\n" + "Try <command> --help' for more information.", "Undefined option: " + param);
}
Field field = options.get(option);
if (value == null && (field.getType() == boolean.class || field.getType() == Boolean.class)) {
value = Boolean.TRUE;
}
if (value == null && it.hasNext()) {
value = it.next();
}
if (value == null) {
throw new CommandException(commandErrorSt + "missing value for option " + INTENSITY_BOLD + param + INTENSITY_NORMAL, "Missing value for option: " + param);
}
if (option.multiValued()) {
@SuppressWarnings("unchecked") List<Object> l = (List<Object>) optionValues.get(option);
if (l == null) {
l = new ArrayList<Object>();
optionValues.put(option, l);
}
l.add(value);
} else {
optionValues.put(option, value);
}
} else {
processOptions = false;
if (argIndex >= orderedArguments.size()) {
throw new CommandException(commandErrorSt + "too many arguments specified", "Too many arguments specified");
}
Argument argument = orderedArguments.get(argIndex);
if (!argument.multiValued()) {
argIndex++;
}
if (argument.multiValued()) {
@SuppressWarnings("unchecked") List<Object> l = (List<Object>) argumentValues.get(argument);
if (l == null) {
l = new ArrayList<Object>();
argumentValues.put(argument, l);
}
l.add(param);
} else {
argumentValues.put(argument, param);
}
}
}
// Check required arguments / options
for (Option option : options.keySet()) {
if (option.required() && optionValues.get(option) == null) {
throw new CommandException(commandErrorSt + "option " + INTENSITY_BOLD + option.name() + INTENSITY_NORMAL + " is required", "Option " + option.name() + " is required");
}
}
for (Argument argument : orderedArguments) {
if (argument.required() && argumentValues.get(argument) == null) {
throw new CommandException(commandErrorSt + "argument " + INTENSITY_BOLD + argument.name() + INTENSITY_NORMAL + " is required", "Argument " + argument.name() + " is required");
}
}
// Convert and inject values
for (Map.Entry<Option, Object> entry : optionValues.entrySet()) {
Field field = options.get(entry.getKey());
Object value;
try {
value = convert(action, session, entry.getValue(), field.getGenericType());
} catch (Exception e) {
throw new CommandException(commandErrorSt + "unable to convert option " + INTENSITY_BOLD + entry.getKey().name() + INTENSITY_NORMAL + " with value '" + entry.getValue() + "' to type " + new GenericType(field.getGenericType()).toString(), "Unable to convert option " + entry.getKey().name() + " with value '" + entry.getValue() + "' to type " + new GenericType(field.getGenericType()).toString(), e);
}
field.setAccessible(true);
field.set(action, value);
}
for (Map.Entry<Argument, Object> entry : argumentValues.entrySet()) {
Field field = arguments.get(entry.getKey());
Object value;
try {
value = convert(action, session, entry.getValue(), field.getGenericType());
} catch (Exception e) {
throw new CommandException(commandErrorSt + "unable to convert argument " + INTENSITY_BOLD + entry.getKey().name() + INTENSITY_NORMAL + " with value '" + entry.getValue() + "' to type " + new GenericType(field.getGenericType()).toString(), "Unable to convert argument " + entry.getKey().name() + " with value '" + entry.getValue() + "' to type " + new GenericType(field.getGenericType()).toString(), e);
}
field.setAccessible(true);
field.set(action, value);
}
return true;
}
use of org.apache.karaf.shell.commands.Option in project karaf by apache.
the class ActionMetaDataFactory method create.
public ActionMetaData create(Class<? extends Action> actionClass) {
Command command = getCommand(actionClass);
Map<Option, Field> options = new HashMap<>();
Map<Argument, Field> arguments = new HashMap<>();
List<Argument> orderedArguments = new ArrayList<>();
for (Class<?> type = actionClass; type != null; type = type.getSuperclass()) {
for (Field field : type.getDeclaredFields()) {
Option option = field.getAnnotation(Option.class);
if (option == null) {
option = getAndConvertDeprecatedOption(field);
}
if (option != null) {
options.put(option, field);
}
Argument argument = field.getAnnotation(Argument.class);
if (argument == null) {
argument = getAndConvertDeprecatedArgument(field);
}
if (argument != null) {
argument = replaceDefaultArgument(field, argument);
arguments.put(argument, field);
int index = argument.index();
while (orderedArguments.size() <= index) {
orderedArguments.add(null);
}
if (orderedArguments.get(index) != null) {
throw new IllegalArgumentException("Duplicate argument index: " + index + " on Action " + actionClass.getName());
}
orderedArguments.set(index, argument);
}
}
}
assertIndexesAreCorrect(actionClass, orderedArguments);
return new ActionMetaData(actionClass, command, options, arguments, orderedArguments, null);
}
use of org.apache.karaf.shell.commands.Option in project karaf by apache.
the class ArgumentCompleter method complete.
public int complete(final Session session, final CommandLine list, final List<String> candidates) {
int argpos = list.getArgumentPosition();
int argIndex = list.getCursorArgumentIndex();
//Store the argument list so that it can be used by completers.
CommandSession commandSession = CommandSessionHolder.getSession();
if (commandSession != null) {
commandSession.put(ARGUMENTS_LIST, list);
}
Completer comp = null;
String[] args = list.getArguments();
int index = 0;
// First argument is command name
if (index < argIndex) {
// Verify scope
if (!Session.SCOPE_GLOBAL.equals(scope) && !session.resolveCommand(args[index]).equals(scope + ":" + name)) {
return -1;
}
// Verify command name
if (!verifyCompleter(commandCompleter, args[index])) {
return -1;
}
index++;
} else {
comp = commandCompleter;
}
// Now, check options
if (comp == null) {
while (index < argIndex && args[index].startsWith("-")) {
if (!verifyCompleter(optionsCompleter, args[index])) {
return -1;
}
Option option = options.get(args[index]);
if (option == null) {
return -1;
}
Field field = fields.get(option);
if (field != null && field.getType() != boolean.class && field.getType() != Boolean.class) {
if (++index == argIndex) {
comp = NullCompleter.INSTANCE;
}
}
index++;
}
if (comp == null && index >= argIndex && index < args.length && args[index].startsWith("-")) {
comp = optionsCompleter;
}
}
//Now check for if last Option has a completer
int lastAgurmentIndex = argIndex - 1;
if (lastAgurmentIndex >= 1) {
Option lastOption = options.get(args[lastAgurmentIndex]);
if (lastOption != null) {
Field lastField = fields.get(lastOption);
if (lastField != null && lastField.getType() != boolean.class && lastField.getType() != Boolean.class) {
Option option = lastField.getAnnotation(Option.class);
if (option != null) {
Completer optionValueCompleter = null;
String name = option.name();
if (optionalCompleters != null && name != null) {
optionValueCompleter = optionalCompleters.get(name);
if (optionValueCompleter == null) {
String[] aliases = option.aliases();
if (aliases.length > 0) {
for (int i = 0; i < aliases.length && optionValueCompleter == null; i++) {
optionValueCompleter = optionalCompleters.get(option.aliases()[i]);
}
}
}
}
if (optionValueCompleter != null) {
comp = optionValueCompleter;
}
}
}
}
}
// Check arguments
if (comp == null) {
int indexArg = 0;
while (index < argIndex) {
Completer sub = argsCompleters.get(indexArg >= argsCompleters.size() ? argsCompleters.size() - 1 : indexArg);
if (!verifyCompleter(sub, args[index])) {
return -1;
}
index++;
indexArg++;
}
comp = argsCompleters.get(indexArg >= argsCompleters.size() ? argsCompleters.size() - 1 : indexArg);
}
int ret = comp.complete(list.getCursorArgument(), argpos, candidates);
if (ret == -1) {
return -1;
}
int pos = ret + (list.getBufferPosition() - argpos);
/**
* Special case: when completing in the middle of a line, and the
* area under the cursor is a delimiter, then trim any delimiters
* from the candidates, since we do not need to have an extra
* delimiter.
*
* E.g., if we have a completion for "foo", and we
* enter "f bar" into the buffer, and move to after the "f"
* and hit TAB, we want "foo bar" instead of "foo bar".
*/
String buffer = list.getBuffer();
int cursor = list.getBufferPosition();
if ((buffer != null) && (cursor != buffer.length()) && isDelimiter(buffer, cursor)) {
for (int i = 0; i < candidates.size(); i++) {
String val = candidates.get(i);
while ((val.length() > 0) && isDelimiter(val, val.length() - 1)) {
val = val.substring(0, val.length() - 1);
}
candidates.set(i, val);
}
}
return pos;
}
Aggregations