Search in sources :

Example 1 with CommandLine

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

the class CommandLineParser method parse.

public static String parse(Session session, String command) {
    StringBuilder parsed = new StringBuilder();
    int pos = 0;
    while (pos < command.length()) {
        String rem = command.substring(pos);
        GogoParser cmdNameParser = new GogoParser(rem, rem.length());
        String name = cmdNameParser.value();
        name = session.resolveCommand(name);
        Parser cmdParser = null;
        for (Command cmd : session.getRegistry().getCommands()) {
            if (name.equals(cmd.getScope() + ":" + cmd.getName())) {
                cmdParser = cmd.getParser();
                break;
            }
        }
        if (cmdParser == null) {
            cmdParser = new DefaultParser();
        }
        CommandLine cmdLine = cmdParser.parse(session, rem, rem.length());
        parsed.append(cmdParser.preprocess(session, cmdLine));
        int length = cmdLine.getBuffer().length();
        if (length < rem.length()) {
            char ch = rem.charAt(length);
            if (ch == ';' || ch == '|') {
                parsed.append(" ");
                parsed.append(ch);
                parsed.append(" ");
                length++;
            } else if (ch == '\n') {
                parsed.append(ch);
                length++;
            } else {
                throw new IllegalArgumentException("Unrecognized character: '" + ch + "'");
            }
        }
        pos += length;
    }
    return parsed.toString();
}
Also used : CommandLine(org.apache.karaf.shell.api.console.CommandLine) Command(org.apache.karaf.shell.api.console.Command) GogoParser(org.apache.karaf.shell.support.parsing.GogoParser) DefaultParser(org.apache.karaf.shell.support.parsing.DefaultParser) GogoParser(org.apache.karaf.shell.support.parsing.GogoParser) Parser(org.apache.karaf.shell.api.console.Parser) DefaultParser(org.apache.karaf.shell.support.parsing.DefaultParser)

Example 2 with CommandLine

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

the class ParsingTest method testDefaultParser.

@Test
public void testDefaultParser() {
    String command = " foo  bar (a +  b) ; another command ";
    String subCmd = " foo  bar (a +  b) ";
    DefaultParser parser = new DefaultParser();
    CommandLine line = parser.parse(null, command, command.length());
    assertEquals(3, line.getArguments().length);
    assertEquals("foo", line.getArguments()[0]);
    assertEquals("bar", line.getArguments()[1]);
    assertEquals("(a +  b)", line.getArguments()[2]);
    assertEquals(subCmd, line.getBuffer());
}
Also used : CommandLine(org.apache.karaf.shell.api.console.CommandLine) DefaultParser(org.apache.karaf.shell.support.parsing.DefaultParser) Test(org.junit.Test)

Example 3 with CommandLine

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

the class KarafParser method doParse.

private ParsedLine doParse(String line, int cursor, ParseContext parseContext) throws SyntaxError {
    Program program = null;
    List<Statement> statements = null;
    String repaired = line;
    while (program == null) {
        try {
            org.apache.felix.gogo.runtime.Parser parser = new org.apache.felix.gogo.runtime.Parser(repaired);
            program = parser.program();
            statements = parser.statements();
        } catch (EOFError e) {
            // Make sure we don't loop forever
            if (parseContext == ParseContext.COMPLETE && repaired.length() < line.length() + 1024) {
                repaired = repaired + " " + e.repair();
            } else {
                throw e;
            }
        }
    }
    // Find corresponding statement
    Statement statement = null;
    for (int i = statements.size() - 1; i >= 0; i--) {
        Statement s = statements.get(i);
        if (s.start() <= cursor) {
            boolean isOk = true;
            // check if there are only spaces after the previous statement
            if (s.start() + s.length() < cursor) {
                for (int j = s.start() + s.length(); isOk && j < cursor; j++) {
                    isOk = Character.isWhitespace(line.charAt(j));
                }
            }
            statement = s;
            break;
        }
    }
    if (statement != null && statement.tokens() != null && !statement.tokens().isEmpty()) {
        String cmdName = session.resolveCommand(statement.tokens().get(0).toString());
        String[] parts = cmdName.split(":");
        Command cmd = parts.length == 2 ? session.getRegistry().getCommand(parts[0], parts[1]) : null;
        Parser cmdParser = cmd != null ? cmd.getParser() : null;
        if (cmdParser != null) {
            final CommandLine cmdLine = cmdParser.parse(session, statement.toString(), cursor - statement.start());
            return new ParsedLine() {

                @Override
                public String word() {
                    return cmdLine.getCursorArgument();
                }

                @Override
                public int wordCursor() {
                    return cmdLine.getArgumentPosition();
                }

                @Override
                public int wordIndex() {
                    return cmdLine.getCursorArgumentIndex();
                }

                @Override
                public List<String> words() {
                    return Arrays.asList(cmdLine.getArguments());
                }

                @Override
                public String line() {
                    return cmdLine.getBuffer();
                }

                @Override
                public int cursor() {
                    return cmdLine.getBufferPosition();
                }
            };
        }
        if (repaired != line) {
            Token stmt = statement.subSequence(0, line.length() - statement.start());
            List<Token> tokens = new ArrayList<>(statement.tokens());
            Token last = tokens.get(tokens.size() - 1);
            tokens.set(tokens.size() - 1, last.subSequence(0, line.length() - last.start()));
            return new ParsedLineImpl(program, stmt, cursor, tokens);
        }
        return new ParsedLineImpl(program, statement, cursor, statement.tokens());
    } else {
        // TODO:
        return new ParsedLineImpl(program, program, cursor, Collections.singletonList(program));
    }
}
Also used : Program(org.apache.felix.gogo.runtime.Parser.Program) Statement(org.apache.felix.gogo.runtime.Parser.Statement) ArrayList(java.util.ArrayList) Token(org.apache.felix.gogo.runtime.Token) Parser(org.apache.karaf.shell.api.console.Parser) CommandLine(org.apache.karaf.shell.api.console.CommandLine) Command(org.apache.karaf.shell.api.console.Command) ParsedLineImpl(org.apache.felix.gogo.jline.ParsedLineImpl) ParsedLine(org.jline.reader.ParsedLine) EOFError(org.apache.felix.gogo.runtime.EOFError)

Example 4 with CommandLine

use of org.apache.karaf.shell.api.console.CommandLine in project fuse-karaf by jboss-fuse.

the class CredentialStoreProtectionCompletionSupport method complete.

/**
 * Performs completion for any {@code -k} or {@code --protection-attributes} parameters firstly by suggesting an
 * option part, then providing completion for values for a specific option.
 *
 * @param session
 *            the current {@link Session}
 * @param commandLine
 *            the pre-parsed {@link CommandLine}
 * @param candidates
 *            a list to fill with possible completion candidates
 * @return the index of the{@link CommandLine} for which the completion will be relative
 */
@Override
public int complete(final Session session, final CommandLine commandLine, final List<String> candidates) {
    final String[] arguments = commandLine.getArguments();
    int protectionTypeIdx = -1;
    for (int i = 0; i < arguments.length; i++) {
        final String argument = arguments[i];
        if ("-p".equals(argument) || "--protection-type".equals(argument)) {
            protectionTypeIdx = i;
            break;
        }
    }
    // do we have protection type specified
    if ((protectionTypeIdx < 0) || (arguments.length <= (protectionTypeIdx + 1))) {
        return -1;
    }
    // parse the protection type argument
    final String protectionTypeString = arguments[protectionTypeIdx + 1];
    final ProtectionType protectionType;
    try {
        protectionType = ProtectionType.valueOf(protectionTypeString);
    } catch (final IllegalArgumentException e) {
        return -1;
    }
    // these are supported options for the specified protection type, we sort them for binarySearch below
    final String[] supportedOptions = Arrays.stream(protectionType.getSupportedOptions()).sorted().toArray(String[]::new);
    // the user may have already chosen an option ("option=") part
    final String option = optionOf(commandLine.getCursorArgument());
    if (!option.isEmpty() && (Arrays.binarySearch(supportedOptions, option) >= 0)) {
        // if the user has chosen the option part, provide completion on the value part
        final String[] options = Arrays.stream(protectionType.getOptionValuesFor(option)).map(o -> option + "=" + o).toArray(String[]::new);
        return new StringsCompleter(options).complete(session, commandLine, candidates);
    }
    final Set<String> usedOptions = usedOptions(arguments);
    // use supported options without any used options
    final int complete = new StringsCompleter(Arrays.stream(supportedOptions).filter(o -> !usedOptions.contains(o)).map(o -> o + "=").toArray(String[]::new)).complete(session, commandLine, candidates);
    for (final ListIterator<String> i = candidates.listIterator(); i.hasNext(); ) {
        String candidate = i.next();
        if (candidate.endsWith("= ")) {
            i.set(candidate.substring(0, candidate.length() - 1));
        }
    }
    return complete;
}
Also used : HashSet(java.util.HashSet) Session(org.apache.karaf.shell.api.console.Session) ProtectionType(org.jboss.fuse.credential.store.karaf.util.ProtectionType) Arrays(java.util.Arrays) List(java.util.List) Completer(org.apache.karaf.shell.api.console.Completer) ListIterator(java.util.ListIterator) StringsCompleter(org.apache.karaf.shell.support.completers.StringsCompleter) Service(org.apache.karaf.shell.api.action.lifecycle.Service) Set(java.util.Set) CommandLine(org.apache.karaf.shell.api.console.CommandLine) ProtectionType(org.jboss.fuse.credential.store.karaf.util.ProtectionType) StringsCompleter(org.apache.karaf.shell.support.completers.StringsCompleter)

Example 5 with CommandLine

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

the class CommandLineParser method buildCommandLine.

public static CommandLine buildCommandLine(Session session, final String command, int cursor, AtomicInteger begOfLine) {
    int pos = 0;
    while (true) {
        String rem = command.substring(pos);
        GogoParser cmdNameParser = new GogoParser(rem, rem.length());
        String name = cmdNameParser.value();
        name = session.resolveCommand(name);
        Parser cmdParser = null;
        for (Command cmd : session.getRegistry().getCommands()) {
            if (name.equals(cmd.getScope() + ":" + cmd.getName())) {
                cmdParser = cmd.getParser();
                break;
            }
        }
        if (cmdParser == null) {
            cmdParser = new DefaultParser();
        }
        CommandLine cmdLine = cmdParser.parse(session, rem, cursor - pos);
        int length = cmdLine.getBuffer().length();
        if (length < rem.length()) {
            char ch = rem.charAt(length);
            if (ch == ';' || ch == '|') {
                length++;
            } else {
                throw new IllegalArgumentException("Unrecognized character: '" + ch + "'");
            }
        }
        pos += length;
        if (cursor <= pos) {
            begOfLine.set(pos - length);
            return cmdLine;
        }
    }
}
Also used : CommandLine(org.apache.karaf.shell.api.console.CommandLine) Command(org.apache.karaf.shell.api.console.Command) GogoParser(org.apache.karaf.shell.support.parsing.GogoParser) DefaultParser(org.apache.karaf.shell.support.parsing.DefaultParser) GogoParser(org.apache.karaf.shell.support.parsing.GogoParser) Parser(org.apache.karaf.shell.api.console.Parser) DefaultParser(org.apache.karaf.shell.support.parsing.DefaultParser)

Aggregations

CommandLine (org.apache.karaf.shell.api.console.CommandLine)9 Command (org.apache.karaf.shell.api.console.Command)5 ArrayList (java.util.ArrayList)4 Parser (org.apache.karaf.shell.api.console.Parser)4 DefaultParser (org.apache.karaf.shell.support.parsing.DefaultParser)3 HashSet (java.util.HashSet)2 List (java.util.List)2 ParsedLineImpl (org.apache.felix.gogo.jline.ParsedLineImpl)2 Program (org.apache.felix.gogo.runtime.Parser.Program)2 Statement (org.apache.felix.gogo.runtime.Parser.Statement)2 Completer (org.apache.karaf.shell.api.console.Completer)2 Session (org.apache.karaf.shell.api.console.Session)2 ArgumentCommandLine (org.apache.karaf.shell.support.completers.ArgumentCommandLine)2 StringsCompleter (org.apache.karaf.shell.support.completers.StringsCompleter)2 GogoParser (org.apache.karaf.shell.support.parsing.GogoParser)2 ParsedLine (org.jline.reader.ParsedLine)2 Test (org.junit.Test)2 Arrays (java.util.Arrays)1 ListIterator (java.util.ListIterator)1 Set (java.util.Set)1