org.jline.reader.LineReader Java Examples

The following examples show how to use org.jline.reader.LineReader. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: flink   Author: flink-tpc-ds   File: SqlCompleter.java    License: Apache License 2.0 6 votes vote down vote up
public void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) {
	String statement = line.line();

	// remove ';' at the end
	if (statement.endsWith(";")) {
		statement = statement.substring(0, statement.length() - 1);
	}

	// handle SQL client specific commands
	final String statementNormalized = statement.toUpperCase().trim();
	for (String commandHint : COMMAND_HINTS) {
		if (commandHint.startsWith(statementNormalized) && line.cursor() < commandHint.length()) {
			candidates.add(createCandidate(commandHint));
		}
	}

	// fallback to Table API hinting
	try {
		executor.completeStatement(context, statement, line.cursor())
			.forEach(hint -> candidates.add(createCandidate(hint)));
	} catch (SqlExecutionException e) {
		LOG.debug("Could not complete statement at " + line.cursor() + ":" + statement, e);
	}
}
 
Example #2
Source Project: joinery   Author: cardillo   File: Shell.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void complete(final LineReader reader,
        final ParsedLine line, final List<Candidate> candidates) {
    final String expr = line.word().substring(0, line.wordCursor());
    final int dot = expr.lastIndexOf('.') + 1;
    if (dot > 1) {
        final String sym = expr.substring(0, dot - 1);
        final Object value = get(sym, Repl.this);
        if (value instanceof ScriptableObject) {
            ScriptableObject so = (ScriptableObject)value;
            final Object[] ids = so.getAllIds();
            for (final Object id : ids) {
                final String candidate = sym + "." + id;
                candidates.add(new Candidate(
                        candidate,
                        candidate,
                        null,
                        null,
                        null,
                        null,
                        false
                    ));
            }
        }
    }
}
 
Example #3
Source Project: sqlline   Author: julianhyde   File: CompletionTest.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@ParameterizedTest
@MethodSource("sqlKeywordCompletionProvider")
public void testSqlCompletions(String input, String expected) {
  try {
    LineReader lineReader = sqlLine.getLineReader();
    LineReaderCompletionImpl lineReaderCompletion =
        new LineReaderCompletionImpl(lineReader.getTerminal());
    lineReaderCompletion.setCompleter(
        sqlLine.getDatabaseConnection().getSqlCompleter());
    final List<Candidate> actual =
        getLineReaderCompletedList(lineReaderCompletion, input);
    assertEquals(1, actual.size());
    assertEquals(expected, actual.iterator().next().value());
  } catch (Exception e) {
    // fail
    throw new RuntimeException(e);
  }
}
 
Example #4
Source Project: ssh-shell-spring-boot   Author: fonimus   File: AbstractShellHelperTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeEach
public void each() {
    h = new SshShellHelper();
    List<String> auth = Collections.singletonList("ROLE_ACTUATOR");
    lr = mock(LineReader.class);
    ter = mock(Terminal.class);
    writer = mock(PrintWriter.class);
    when(ter.writer()).thenReturn(writer);
    reader = mock(NonBlockingReader.class);
    when(ter.reader()).thenReturn(reader);
    when(lr.getTerminal()).thenReturn(ter);

    SshContext ctx = new SshContext(new SshShellRunnable(new SshShellProperties(), mockChannelSession(4L), null,
            null, null,
            null, null, null, null, null, null, null, null, null), ter, lr,
            new SshAuthentication("user", "user", null, null, auth));
    SshShellCommandFactory.SSH_THREAD_CONTEXT.set(ctx);
    when(ter.getType()).thenReturn("osx");
    when(ter.getSize()).thenReturn(new Size(123, 40));
}
 
Example #5
Source Project: ssh-shell-spring-boot   Author: fonimus   File: DemoCommandTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeAll
static void prepare() {
    cmd = new DemoCommand(new SshShellHelper());
    terminal = mock(Terminal.class);
    when(terminal.getSize()).thenReturn(size);
    PrintWriter writer = mock(PrintWriter.class);
    lr = mock(LineReader.class);
    ParsedLine line = mock(ParsedLine.class);
    when(line.line()).thenReturn("y");
    when(lr.getParsedLine()).thenReturn(line);
    when(lr.getTerminal()).thenReturn(terminal);
    when(terminal.writer()).thenReturn(writer);
    reader = mock(NonBlockingReader.class);
    when(terminal.reader()).thenReturn(reader);
    when(terminal.getType()).thenReturn("osx");
    auth = new SshAuthentication("user", "user", null, null, null);
    SshContext ctx = new SshContext(new SshShellRunnable(new SshShellProperties(), null, null, null, null, null,
            null, null, null, null, null, null, null, null), terminal, lr, auth);
    SshShellCommandFactory.SSH_THREAD_CONTEXT.set(ctx);
}
 
Example #6
Source Project: super-cloudops   Author: wl4g   File: DynamicCompleter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void complete(LineReader reader, ParsedLine parsedLine, List<Candidate> candidates) {
	List<String> commands = LineUtils.parse(parsedLine.line());

	// Primary level frist arguments
	if (commands.isEmpty()) {
		new StringsCompleter(registry.getHelpOptions().keySet()).complete(reader, parsedLine, candidates);
	}
	// Secondary primary arguments
	else {
		HelpOptions options = registry.getHelpOptions().get(commands.get(0));
		// Continue before completion
		if (completingCompleted(commands, options)) {
			List<String> candes = new ArrayList<>();
			for (Option opt : options.getOptions()) {
				candes.add(GNU_CMD_SHORT + opt.getOpt());
				candes.add(GNU_CMD_LONG + opt.getLongOpt());
			}
			new StringsCompleter(candes).complete(reader, parsedLine, candidates);
		}
	}

}
 
Example #7
Source Project: Velocity   Author: VelocityPowered   File: VelocityConsole.java    License: MIT License 6 votes vote down vote up
@Override
protected LineReader buildReader(LineReaderBuilder builder) {
  return super.buildReader(builder
      .appName("Velocity")
      .completer((reader, parsedLine, list) -> {
        try {
          boolean isCommand = parsedLine.line().indexOf(' ') == -1;
          List<String> offers = this.server.getCommandManager()
              .offerSuggestions(this, parsedLine.line());
          for (String offer : offers) {
            if (isCommand) {
              list.add(new Candidate(offer.substring(1)));
            } else {
              list.add(new Candidate(offer));
            }
          }
        } catch (Exception e) {
          logger.error("An error occurred while trying to perform tab completion.", e);
        }
      })
  );
}
 
Example #8
Source Project: jsqsh   Author: scgray   File: SqshConsole.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean apply() {

    final Buffer buffer = reader.getBuffer();

    if (context.getCurrentSession().isInputComplete(buffer.toString(), buffer.cursor())) {

        acceptCause = AcceptCause.NORMAL;
        reader.callWidget(LineReader.ACCEPT_LINE);
    }
    else {

        buffer.write('\n');
    }

    return true;
}
 
Example #9
Source Project: picocli   Author: remkop   File: PicocliJLineCompleter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Populates <i>candidates</i> with a list of possible completions for the <i>command line</i>.
 *
 * The list of candidates will be sorted and filtered by the LineReader, so that
 * the list of candidates displayed to the user will usually be smaller than
 * the list given by the completer.  Thus it is not necessary for the completer
 * to do any matching based on the current buffer.  On the contrary, in order
 * for the typo matcher to work, all possible candidates for the word being
 * completed should be returned.
 *
 * @param reader        The line reader
 * @param line          The parsed command line
 * @param candidates    The {@link List} of candidates to populate
 */
//@Override
public void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) {
   // let picocli generate completion candidates for the token where the cursor is at
    String[] words = new String[line.words().size()];
    words = line.words().toArray(words);
    List<CharSequence> cs = new ArrayList<CharSequence>();
    AutoComplete.complete(spec,
            words,
            line.wordIndex(),
            0,
            line.cursor(),
            cs);
    for(CharSequence c: cs){
        candidates.add(new Candidate((String)c)); 
    }
}
 
Example #10
Source Project: TerminalConsoleAppender   Author: Minecrell   File: SimpleTerminalConsole.java    License: MIT License 6 votes vote down vote up
private void readCommands(Terminal terminal) {
    LineReader reader = buildReader(LineReaderBuilder.builder().terminal(terminal));
    TerminalConsoleAppender.setReader(reader);

    try {
        String line;
        while (isRunning()) {
            try {
                line = reader.readLine("> ");
            } catch (EndOfFileException ignored) {
                // Continue reading after EOT
                continue;
            }

            if (line == null) {
                break;
            }

            processInput(line);
        }
    } catch (UserInterruptException e) {
        shutdown();
    } finally {
        TerminalConsoleAppender.setReader(null);
    }
}
 
Example #11
Source Project: nifi   Author: apache   File: TestCLICompleter.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setupCompleter() {
    Assume.assumeTrue("Test only runs on *nix", !SystemUtils.IS_OS_WINDOWS);
    final Session session = new InMemorySession();
    final ClientFactory<NiFiClient> niFiClientFactory = new NiFiClientFactory();
    final ClientFactory<NiFiRegistryClient> nifiRegClientFactory = new NiFiRegistryClientFactory();

    final Context context = new StandardContext.Builder()
            .output(System.out)
            .session(session)
            .nifiClientFactory(niFiClientFactory)
            .nifiRegistryClientFactory(nifiRegClientFactory)
            .build();

    final Map<String,Command> commands = CommandFactory.createTopLevelCommands(context);
    final Map<String,CommandGroup> commandGroups = CommandFactory.createCommandGroups(context);

    completer = new CLICompleter(commands.values(), commandGroups.values());
    lineReader = Mockito.mock(LineReader.class);
}
 
Example #12
Source Project: incubator-ratis   Author: apache   File: PutToLogCommand.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void run(Terminal terminal, LineReader lineReader, LogServiceClient client, String[] args) {
  if (args.length != 2) {
    terminal.writer().println("ERROR - Usage: put <name> <value>");
    return;
  }
  String name = args[0];
  String value = args[1];
  try (LogStream stream = client.getLog(LogName.of(name));
      LogWriter writer = stream.createWriter()) {
    writer.write(ByteBuffer.wrap(value.getBytes(StandardCharsets.UTF_8)));
  } catch (Exception e) {
    terminal.writer().println("Error writing to log");
    e.printStackTrace(terminal.writer());
  }
}
 
Example #13
Source Project: incubator-ratis   Author: apache   File: ExportLogCommand.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void run(Terminal terminal, LineReader lineReader, LogServiceClient client, String[] args) {
  if (args.length != 3) {
    terminal.writer().println("ERROR - Usage: export <name> <location> <recordId>");
    return;
  }
  String logName = args[0];
  String location = args[1];
  long recordId = Long.parseLong(args[2]);
  try {
    client.exportLog(LogName.of(logName), location,recordId);
    terminal.writer().println("Export Log request is submitted successfully!!");
  } catch (Exception e) {
    terminal.writer().println("Failed to export log!!");
    e.printStackTrace(terminal.writer());
  }
}
 
Example #14
Source Project: sqlline   Author: julianhyde   File: SqlLineArgsTest.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testAnsiConsoleFormatWithNonExistingTerminalAndSmallWidth() {
  new MockUp<SqlLine>() {
    @Mock
    LineReader getLineReader() {
      return null;
    }
  };
  final String script = "!set maxwidth 0\n"
      + "!set incremental true \n"
      + "!set outputformat ansiconsole \n"
      + "values (1, '2');\n";
  final String line1 = ""
      + "\n"
      + "\n";
  checkScriptFile(script, true, equalTo(SqlLine.Status.OK),
      containsString(line1));
}
 
Example #15
Source Project: incubator-ratis   Author: apache   File: ListLogsCommand.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void run(Terminal terminal, LineReader lineReader, LogServiceClient client, String[] args) {
  if (args.length != 0) {
    terminal.writer().println("ERROR - Usage: list");
    return;
  }

  try {
    List<LogInfo> logs = client.listLogs();
    StringBuilder sb = new StringBuilder();
    for (LogInfo log : logs) {
      if (sb.length() > 0) {
        sb.append("\n");
      }
      sb.append(log.getLogName().getName());
    }
    terminal.writer().println(sb.toString());
  } catch (IOException e) {
    terminal.writer().println("Failed to list available logs");
    e.printStackTrace(terminal.writer());
  }
}
 
Example #16
Source Project: rug-cli   Author: atomist-attic   File: LoginCommand.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void login(String username, String code, Settings settings) {
    printBanner();

    LineReader reader = ShellUtils.lineReader(null, Optional.empty());
    try {
        if (username == null) {
            username = reader.readLine(getPrompt("Username"));
        }
        String password = reader.readLine(getPrompt("Password"), new Character('*'));
        postForTokenAndHandleResponse(username, password, code, settings, reader);
    }
    catch (EndOfFileException | UserInterruptException e) {
        log.error("Canceled!");
    }
    finally {
        ShellUtils.shutdown(reader);
    }
}
 
Example #17
Source Project: rug-cli   Author: atomist-attic   File: LoginCommand.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void postForTokenAndHandleResponse(String username, String password, String code,
        Settings settings, LineReader reader) {
    Status status = new LoginOperations().postForToken(username, password, code, settings);

    if (status == Status.OK) {
        log.newline();
        log.info(Style.green(
                "Successfully logged in to GitHub and stored token in ~/.atomist/cli.yml"));
    }
    else if (status == Status.BAD_CREDENTIALS) {
        throw new CommandException(
                "Provided credentials are invalid. Please try again with correct credentials.",
                "login");
    }
    else if (status == Status.MFA_REQUIRED) {
        log.newline();
        log.info("  Please provide a MFA code");
        code = reader.readLine(getPrompt("MFA code"));
        postForTokenAndHandleResponse(username, password, code, settings, reader);
    }
}
 
Example #18
Source Project: flink   Author: apache   File: SqlCompleter.java    License: Apache License 2.0 6 votes vote down vote up
public void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) {
	String statement = line.line();

	// remove ';' at the end
	if (statement.endsWith(";")) {
		statement = statement.substring(0, statement.length() - 1);
	}

	// handle SQL client specific commands
	final String statementNormalized = statement.toUpperCase().trim();
	for (String commandHint : COMMAND_HINTS) {
		if (commandHint.startsWith(statementNormalized) && line.cursor() < commandHint.length()) {
			candidates.add(createCandidate(getCompletionHint(statementNormalized, commandHint)));
		}
	}

	// fallback to Table API hinting
	try {
		executor.completeStatement(sessionId, statement, line.cursor())
			.forEach(hint -> candidates.add(createCandidate(hint)));
	} catch (SqlExecutionException e) {
		LOG.debug("Could not complete statement at " + line.cursor() + ":" + statement, e);
	}
}
 
Example #19
Source Project: rug-cli   Author: atomist-attic   File: ArchiveNameCompleter.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) {
    if (line.words().size() == 2) {
        String cmd = line.words().get(0);
        String word = line.word();

        if (COMMANDS.contains(cmd)) {
            // group is already specified; only provide artifacts now
            if (word.contains(":")) {
                String group = word.split(":")[0] + ":";
                archivesFromCache().stream().filter(a -> a.startsWith(group))
                        .collect(Collectors.toSet())
                        .forEach(a -> candidates.add(new Candidate(a)));
            }
            // sill completing group
            else {
                archivesFromCache().stream().map(a -> a.split(":")[0])
                        .collect(Collectors.toSet()).forEach(a -> candidates
                                .add(new Candidate(a + ":", a, null, null, null, null, false)));
            }
        }
    }
}
 
Example #20
Source Project: sqlline   Author: julianhyde   File: SqlLineParser.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private String getPaddedPrompt(String waitingPattern) {
  if (sqlLine.getOpts().getShowLineNumbers()
      && sqlLine.getLineReader() != null) {
    sqlLine.getLineReader()
        .setVariable(LineReader.SECONDARY_PROMPT_PATTERN, "%N%P.%M> ");
    return waitingPattern;
  } else {
    if (sqlLine.getLineReader() != null) {
      sqlLine.getLineReader().setVariable(LineReader.SECONDARY_PROMPT_PATTERN,
          LineReaderImpl.DEFAULT_SECONDARY_PROMPT_PATTERN);
    }
    int length = sqlLine.getPromptHandler().getPrompt().columnLength();
    StringBuilder prompt = new StringBuilder(length);
    for (int i = 0;
         i < length - "> ".length() - waitingPattern.length(); i++) {
      prompt.append(i % 2 == 0 ? '.' : ' ');
    }
    prompt.append(waitingPattern);
    return prompt.toString();
  }
}
 
Example #21
Source Project: ratis   Author: hortonworks   File: PutToLogCommand.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void run(Terminal terminal, LineReader lineReader, LogServiceClient client, String[] args) {
  if (args.length != 2) {
    terminal.writer().println("ERROR - Usage: put <name> <value>");
    return;
  }
  String name = args[0];
  String value = args[1];
  try (LogStream stream = client.getLog(LogName.of(name));
      LogWriter writer = stream.createWriter()) {
    writer.write(ByteBuffer.wrap(value.getBytes(StandardCharsets.UTF_8)));
  } catch (Exception e) {
    terminal.writer().println("Error writing to log");
    e.printStackTrace(terminal.writer());
  }
}
 
Example #22
Source Project: jsqsh   Author: scgray   File: JLineCompleter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void complete(LineReader lineReader, ParsedLine parsedLine, List<Candidate> list) {

    Session session = ctx.getCurrentSession();
    ConnectionContext conn = session.getConnectionContext();
    if (conn != null) {
        
        Completer completer = conn.getTabCompleter(session,
            parsedLine.line(), parsedLine.cursor(), parsedLine.word());
        String name = completer.next();
        while (name != null) {
            
            list.add(new Candidate(name));
            name = completer.next();
        }
    }
}
 
Example #23
Source Project: ratis   Author: hortonworks   File: ListLogsCommand.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void run(Terminal terminal, LineReader lineReader, LogServiceClient client, String[] args) {
  if (args.length != 0) {
    terminal.writer().println("ERROR - Usage: list");
    return;
  }

  try {
    List<LogInfo> logs = client.listLogs();
    StringBuilder sb = new StringBuilder();
    for (LogInfo log : logs) {
      if (sb.length() > 0) {
        sb.append("\n");
      }
      sb.append(log.getLogName().getName());
    }
    terminal.writer().println(sb.toString());
  } catch (IOException e) {
    terminal.writer().println("Failed to list available logs");
    e.printStackTrace(terminal.writer());
  }
}
 
Example #24
Source Project: samza   Author: apache   File: CliHighlighter.java    License: Apache License 2.0 6 votes vote down vote up
public AttributedString highlight(LineReader reader, String buffer) {
  AttributedStringBuilder builder = new AttributedStringBuilder();
  List<String> tokens = splitWithSpace(buffer);

  for (String token : tokens) {
    if (isKeyword(token)) {
      builder.style(AttributedStyle.BOLD.foreground(AttributedStyle.YELLOW))
              .append(token);
    } else {
      builder.style(AttributedStyle.DEFAULT)
              .append(token);
    }
  }

  return builder.toAttributedString();
}
 
Example #25
Source Project: presto   Author: prestosql   File: InputHighlighter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public AttributedString highlight(LineReader reader, String buffer)
{
    TokenSource tokens = StatementSplitter.getLexer(buffer, STATEMENT_DELIMITERS);
    AttributedStringBuilder builder = new AttributedStringBuilder();

    boolean error = false;
    while (true) {
        Token token = tokens.nextToken();
        int type = token.getType();
        if (type == Token.EOF) {
            break;
        }
        String text = token.getText();

        if (error || (type == SqlBaseLexer.UNRECOGNIZED)) {
            error = true;
            builder.styled(ERROR_STYLE, text);
        }
        else if (isKeyword(text)) {
            builder.styled(KEYWORD_STYLE, text);
        }
        else if (isString(type)) {
            builder.styled(STRING_STYLE, text);
        }
        else if (isNumber(type)) {
            builder.styled(NUMBER_STYLE, text);
        }
        else if (isComment(type)) {
            builder.styled(COMMENT_STYLE, text);
        }
        else {
            builder.append(text);
        }
    }

    return builder.toAttributedString();
}
 
Example #26
Source Project: jsqsh   Author: scgray   File: Setup.java    License: Apache License 2.0 5 votes vote down vote up
private void cls(LineReader in) {

        // Clear screen, cursor to 0,0
        in.getTerminal().writer().write(Ansi.clearScreen());
        in.getTerminal().writer().write(Ansi.cursorMove(0,0));
        in.getTerminal().writer().flush();;
    }
 
Example #27
Source Project: sqlline   Author: julianhyde   File: SqlLineOpts.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void setMode(String mode) {
  final LineReader reader = sqlLine.getLineReader();
  if (reader == null || reader.getKeyMaps() == null) {
    return;
  }
  final Map<String, KeyMap<Binding>> keyMaps = reader.getKeyMaps();
  switch (mode) {
  case LineReader.EMACS:
  case SqlLineProperty.DEFAULT:
    set(BuiltInProperty.MODE, LineReader.EMACS);
    keyMaps.put(LineReader.MAIN, keyMaps.get(LineReader.EMACS));
    break;
  case "vi":
    set(BuiltInProperty.MODE, mode);
    keyMaps.put(LineReader.MAIN, keyMaps.get(LineReader.VIINS));
    break;
  default:
    sqlLine.error(
        sqlLine.loc("unknown-value", MODE.propertyName(),
            mode, Arrays.asList(LineReader.EMACS, "vi")));
  }
}
 
Example #28
Source Project: Flink-CEPplus   Author: ljygz   File: CliClientTest.java    License: Apache License 2.0 5 votes vote down vote up
private void verifySqlCompletion(String statement, int position, List<String> expectedHints, List<String> notExpectedHints) throws IOException {
	final SessionContext context = new SessionContext("test-session", new Environment());
	final MockExecutor mockExecutor = new MockExecutor();

	final SqlCompleter completer = new SqlCompleter(context, mockExecutor);
	final SqlMultiLineParser parser = new SqlMultiLineParser();

	try (Terminal terminal = TerminalUtils.createDummyTerminal()) {
		final LineReader reader = LineReaderBuilder.builder().terminal(terminal).build();

		final ParsedLine parsedLine = parser.parse(statement, position, Parser.ParseContext.COMPLETE);
		final List<Candidate> candidates = new ArrayList<>();
		final List<String> results = new ArrayList<>();
		completer.complete(reader, parsedLine, candidates);
		candidates.forEach(item -> results.add(item.value()));

		assertTrue(results.containsAll(expectedHints));

		assertEquals(statement, mockExecutor.receivedStatement);
		assertEquals(context, mockExecutor.receivedContext);
		assertEquals(position, mockExecutor.receivedPosition);
		assertTrue(results.contains("HintA"));
		assertTrue(results.contains("Hint B"));

		results.retainAll(notExpectedHints);
		assertEquals(0, results.size());
	}
}
 
Example #29
Source Project: flink   Author: flink-tpc-ds   File: CliClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a CLI instance with a custom terminal. Make sure to close the CLI instance
 * afterwards using {@link #close()}.
 */
@VisibleForTesting
public CliClient(Terminal terminal, SessionContext context, Executor executor) {
	this.terminal = terminal;
	this.context = context;
	this.executor = executor;

	// make space from previous output and test the writer
	terminal.writer().println();
	terminal.writer().flush();

	// initialize line lineReader
	lineReader = LineReaderBuilder.builder()
		.terminal(terminal)
		.appName(CliStrings.CLI_NAME)
		.parser(new SqlMultiLineParser())
		.completer(new SqlCompleter(context, executor))
		.build();
	// this option is disabled for now for correct backslash escaping
	// a "SELECT '\'" query should return a string with a backslash
	lineReader.option(LineReader.Option.DISABLE_EVENT_EXPANSION, true);
	// set strict "typo" distance between words when doing code completion
	lineReader.setVariable(LineReader.ERRORS, 1);
	// perform code completion case insensitive
	lineReader.option(LineReader.Option.CASE_INSENSITIVE, true);

	// create prompt
	prompt = new AttributedStringBuilder()
		.style(AttributedStyle.DEFAULT.foreground(AttributedStyle.GREEN))
		.append("Flink SQL")
		.style(AttributedStyle.DEFAULT)
		.append("> ")
		.toAnsi();
}
 
Example #30
Source Project: Cleanstone   Author: CleanstoneMC   File: InteractiveShellLifecycle.java    License: MIT License 5 votes vote down vote up
@Lazy
public InteractiveShellLifecycle(LineReader lineReader, PromptProvider promptProvider, Shell shell) {
    this.lineReader = lineReader;
    this.promptProvider = promptProvider;
    this.shell = shell;
    this.thread = new Thread(this);
}