Search in sources :

Example 1 with Completer

use of org.apache.karaf.shell.api.console.Completer in project karaf by apache.

the class ArgumentCompleter method completeCandidates.

@Override
public void completeCandidates(Session session, final CommandLine list, List<Candidate> candidates) {
    int argIndex = list.getCursorArgumentIndex();
    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(command.getScope()) && !session.resolveCommand(args[index]).equals(command.getScope() + ":" + command.getName())) {
            return;
        }
        // Verify command name
        if (!verifyCompleter(session, commandCompleter, args[index])) {
            return;
        }
        index++;
    } else {
        comp = commandCompleter;
    }
    // Now, check options
    if (comp == null) {
        while (index < argIndex && args[index].startsWith("-")) {
            if (!verifyCompleter(session, optionsCompleter, args[index])) {
                return;
            }
            Option option = options.get(args[index]);
            if (option == null) {
                return;
            }
            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 (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(session, sub, args[index])) {
                return;
            }
            index++;
            indexArg++;
        }
        comp = argsCompleters.get(indexArg >= argsCompleters.size() ? argsCompleters.size() - 1 : indexArg);
    }
    comp.completeCandidates(session, list, candidates);
/* TODO:JLINE
        if (pos == -1) {
            return -1;
        }
        */
/**
         *  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".
         */
/* TODO:JLINE
        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;
        */
}
Also used : Field(java.lang.reflect.Field) Completer(org.apache.karaf.shell.api.console.Completer) NullCompleter(org.apache.karaf.shell.support.completers.NullCompleter) UriCompleter(org.apache.karaf.shell.support.completers.UriCompleter) StringsCompleter(org.apache.karaf.shell.support.completers.StringsCompleter) FileCompleter(org.apache.karaf.shell.support.completers.FileCompleter) Option(org.apache.karaf.shell.api.action.Option)

Example 2 with Completer

use of org.apache.karaf.shell.api.console.Completer in project karaf by apache.

the class HelpCommand method getCompleter.

@Override
public Completer getCompleter(final boolean scoped) {
    return new Completer() {

        @Override
        public int complete(Session session, CommandLine commandLine, List<String> candidates) {
            String[] args = commandLine.getArguments();
            int argIndex = commandLine.getCursorArgumentIndex();
            StringsCompleter completer = new StringsCompleter(Collections.singletonList(getName()));
            if (argIndex == 0) {
                return completer.complete(session, new ArgumentCommandLine(args[argIndex], commandLine.getArgumentPosition()), candidates);
            } else if (!verifyCompleter(session, completer, args[0])) {
                return -1;
            }
            // TODO: use CommandNamesCompleter and better completion wrt parsing etc...
            completer = new StringsCompleter();
            for (Command command : session.getRegistry().getCommands()) {
                if (!Session.SCOPE_GLOBAL.equals(command.getScope())) {
                    completer.getStrings().add(command.getScope() + ":" + command.getName());
                }
                completer.getStrings().add(command.getName());
            }
            completer.getStrings().add("--help");
            if (argIndex == 1) {
                int res;
                if (argIndex < args.length) {
                    res = completer.complete(session, new ArgumentCommandLine(args[argIndex], commandLine.getArgumentPosition()), candidates);
                } else {
                    res = completer.complete(session, new ArgumentCommandLine("", 0), candidates);
                }
                return res + (commandLine.getBufferPosition() - commandLine.getArgumentPosition());
            } else if (!verifyCompleter(session, completer, args[1])) {
                return -1;
            }
            return -1;
        }

        protected boolean verifyCompleter(Session session, Completer completer, String argument) {
            List<String> candidates = new ArrayList<>();
            return completer.complete(session, new ArgumentCommandLine(argument, argument.length()), candidates) != -1 && !candidates.isEmpty();
        }
    };
}
Also used : ArgumentCommandLine(org.apache.karaf.shell.support.completers.ArgumentCommandLine) CommandLine(org.apache.karaf.shell.api.console.CommandLine) ArgumentCommandLine(org.apache.karaf.shell.support.completers.ArgumentCommandLine) StringsCompleter(org.apache.karaf.shell.support.completers.StringsCompleter) Command(org.apache.karaf.shell.api.console.Command) ArrayList(java.util.ArrayList) Completer(org.apache.karaf.shell.api.console.Completer) StringsCompleter(org.apache.karaf.shell.support.completers.StringsCompleter) ArrayList(java.util.ArrayList) List(java.util.List) Session(org.apache.karaf.shell.api.console.Session)

Example 3 with Completer

use of org.apache.karaf.shell.api.console.Completer in project karaf by apache.

the class CommandsCompleter method completeCandidates.

public void completeCandidates(Session session, CommandLine commandLine, List<Candidate> candidates) {
    Map<String, Completer>[] allCompleters = checkData();
    List<String> scopes = getCurrentScopes(session);
    sort(allCompleters, scopes);
    String subShell = getCurrentSubShell(session);
    String completion = getCompletionType(session);
    // SUBSHELL mode
    if (Session.COMPLETION_MODE_SUBSHELL.equalsIgnoreCase(completion)) {
        if (subShell.isEmpty()) {
            subShell = Session.SCOPE_GLOBAL;
        }
        List<Completer> completers = new ArrayList<>();
        for (String name : allCompleters[1].keySet()) {
            if (name.startsWith(subShell + ":")) {
                completers.add(allCompleters[1].get(name));
            }
        }
        if (!subShell.equals(Session.SCOPE_GLOBAL)) {
            completers.add(new StringsCompleter(new String[] { "exit" }));
        }
        completers.forEach(c -> c.completeCandidates(session, commandLine, candidates));
        return;
    }
    // FIRST mode
    if (Session.COMPLETION_MODE_FIRST.equalsIgnoreCase(completion)) {
        if (!subShell.isEmpty()) {
            List<Completer> completers = new ArrayList<>();
            for (String name : allCompleters[1].keySet()) {
                if (name.startsWith(subShell + ":")) {
                    completers.add(allCompleters[1].get(name));
                }
            }
            completers.forEach(c -> c.completeCandidates(session, commandLine, candidates));
            if (!candidates.isEmpty()) {
                return;
            }
        }
        List<Completer> compl = new ArrayList<>();
        compl.add(aliasesCompleter);
        compl.addAll(allCompleters[0].values());
        compl.forEach(c -> c.completeCandidates(session, commandLine, candidates));
        return;
    }
    List<Completer> compl = new ArrayList<>();
    compl.add(aliasesCompleter);
    compl.addAll(allCompleters[0].values());
    compl.forEach(c -> c.completeCandidates(session, commandLine, candidates));
}
Also used : StringsCompleter(org.apache.karaf.shell.support.completers.StringsCompleter) ArrayList(java.util.ArrayList) Completer(org.apache.karaf.shell.api.console.Completer) StringsCompleter(org.apache.karaf.shell.support.completers.StringsCompleter) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap) Map(java.util.Map)

Example 4 with Completer

use of org.apache.karaf.shell.api.console.Completer in project karaf by apache.

the class CommandsCompleter method checkData.

@SuppressWarnings("unchecked")
protected Map<String, Completer>[] checkData() {
    // Copy the set to avoid concurrent modification exceptions
    // TODO: fix that in gogo instead
    Collection<Command> commands;
    boolean update;
    synchronized (this) {
        commands = factory.getRegistry().getCommands();
        update = !commands.equals(this.commands);
    }
    if (update) {
        // get command aliases
        Map<String, Completer> global = new HashMap<>();
        Map<String, Completer> local = new HashMap<>();
        // add argument completers for each command
        for (Command command : commands) {
            String key = command.getScope() + ":" + command.getName();
            Completer cg = command.getCompleter(false);
            Completer cl = command.getCompleter(true);
            if (cg == null) {
                if (Session.SCOPE_GLOBAL.equals(command.getScope())) {
                    cg = new FixedSimpleCommandCompleter(Collections.singletonList(command.getName()));
                } else {
                    cg = new FixedSimpleCommandCompleter(Arrays.asList(key, command.getName()));
                }
            }
            if (cl == null) {
                cl = new FixedSimpleCommandCompleter(Collections.singletonList(command.getName()));
            }
            global.put(key, cg);
            local.put(key, cl);
        }
        synchronized (this) {
            this.commands.clear();
            this.globalCompleters.clear();
            this.localCompleters.clear();
            this.commands.addAll(commands);
            this.globalCompleters.putAll(global);
            this.localCompleters.putAll(local);
        }
    }
    synchronized (this) {
        return new Map[] { new HashMap<>(this.globalCompleters), new HashMap<>(this.localCompleters) };
    }
}
Also used : Command(org.apache.karaf.shell.api.console.Command) HashMap(java.util.HashMap) Completer(org.apache.karaf.shell.api.console.Completer) StringsCompleter(org.apache.karaf.shell.support.completers.StringsCompleter) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap) Map(java.util.Map)

Example 5 with Completer

use of org.apache.karaf.shell.api.console.Completer in project karaf by apache.

the class CommandTracker method addingService.

@Override
public Object addingService(final ServiceReference reference) {
    Object service = context.getService(reference);
    if (service instanceof CommandWithAction) {
        final CommandWithAction oldCommand = (CommandWithAction) service;
        final org.apache.karaf.shell.api.console.Command command = new org.apache.karaf.shell.api.console.Command() {

            @Override
            public String getScope() {
                return reference.getProperty(CommandProcessor.COMMAND_SCOPE).toString();
            }

            @Override
            public String getName() {
                return reference.getProperty(CommandProcessor.COMMAND_FUNCTION).toString();
            }

            @Override
            public String getDescription() {
                final Command cmd = oldCommand.getActionClass().getAnnotation(Command.class);
                if (cmd != null) {
                    return cmd.description();
                }
                try {
                    Method method = oldCommand.getActionClass().getMethod("description");
                    method.setAccessible(true);
                    return (String) method.invoke(oldCommand.createNewAction());
                } catch (Throwable ignore) {
                }
                return getName();
            }

            @Override
            public Completer getCompleter(final boolean scoped) {
                final ArgumentCompleter completer = new ArgumentCompleter(oldCommand, getScope(), getName(), scoped);
                return completer::complete;
            }

            @Override
            public Parser getParser() {
                return null;
            }

            @Override
            public Object execute(Session session, List<Object> arguments) throws Exception {
                // TODO: remove not really nice cast
                CommandSession commandSession = (CommandSession) session.get(".commandSession");
                return oldCommand.execute(commandSession, arguments);
            }
        };
        sessionFactory.getRegistry().register(command);
        return command;
    } else if (service instanceof org.apache.felix.gogo.commands.CommandWithAction) {
        final org.apache.felix.gogo.commands.CommandWithAction oldCommand = (org.apache.felix.gogo.commands.CommandWithAction) service;
        final org.apache.karaf.shell.api.console.Command command = new org.apache.karaf.shell.api.console.Command() {

            @Override
            public String getScope() {
                return reference.getProperty(CommandProcessor.COMMAND_SCOPE).toString();
            }

            @Override
            public String getName() {
                return reference.getProperty(CommandProcessor.COMMAND_FUNCTION).toString();
            }

            @Override
            public String getDescription() {
                final org.apache.felix.gogo.commands.Command cmd = oldCommand.getActionClass().getAnnotation(org.apache.felix.gogo.commands.Command.class);
                if (cmd != null) {
                    return cmd.description();
                }
                try {
                    Method method = oldCommand.getActionClass().getMethod("description");
                    method.setAccessible(true);
                    return (String) method.invoke(oldCommand.createNewAction());
                } catch (Throwable ignore) {
                }
                return getName();
            }

            @Override
            public Completer getCompleter(final boolean scoped) {
                final OldArgumentCompleter completer = new OldArgumentCompleter(oldCommand, getScope(), getName(), scoped);
                return completer::complete;
            }

            @Override
            public Parser getParser() {
                return null;
            }

            @Override
            public Object execute(Session session, List<Object> arguments) throws Exception {
                // TODO: remove not really nice cast
                CommandSession commandSession = (CommandSession) session.get(".commandSession");
                return oldCommand.execute(commandSession, arguments);
            }
        };
        sessionFactory.getRegistry().register(command);
        return command;
    } else {
        return null;
    }
}
Also used : List(java.util.List) Completer(org.apache.karaf.shell.api.console.Completer) Method(java.lang.reflect.Method) CommandWithAction(org.apache.karaf.shell.commands.CommandWithAction) Parser(org.apache.karaf.shell.api.console.Parser) CommandSession(org.apache.felix.service.command.CommandSession) Command(org.apache.karaf.shell.commands.Command) Session(org.apache.karaf.shell.api.console.Session) CommandSession(org.apache.felix.service.command.CommandSession)

Aggregations

Completer (org.apache.karaf.shell.api.console.Completer)6 StringsCompleter (org.apache.karaf.shell.support.completers.StringsCompleter)5 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 List (java.util.List)2 Map (java.util.Map)2 TreeMap (java.util.TreeMap)2 Command (org.apache.karaf.shell.api.console.Command)2 Session (org.apache.karaf.shell.api.console.Session)2 FileCompleter (org.apache.karaf.shell.support.completers.FileCompleter)2 NullCompleter (org.apache.karaf.shell.support.completers.NullCompleter)2 UriCompleter (org.apache.karaf.shell.support.completers.UriCompleter)2 File (java.io.File)1 Field (java.lang.reflect.Field)1 Method (java.lang.reflect.Method)1 Collection (java.util.Collection)1 EnumSet (java.util.EnumSet)1 HashSet (java.util.HashSet)1 Set (java.util.Set)1 CommandSession (org.apache.felix.service.command.CommandSession)1