org.jline.reader.LineReaderBuilder Java Examples

The following examples show how to use org.jline.reader.LineReaderBuilder. 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 File: ShellUtils.java    From rug-cli with GNU General Public License v3.0 7 votes vote down vote up
public static LineReader lineReader(File historyPath, Optional<SignalHandler> handler,
        Completer... completers) {
    // Protect the history file as may contain sensitive information
    FileUtils.setPermissionsToOwnerOnly(historyPath);

    // Create JLine LineReader
    History history = new DefaultHistory();
    LineReader reader = LineReaderBuilder.builder().terminal(terminal(handler)).history(history)
            .parser(new DefaultParser()).variable(LineReader.HISTORY_FILE, historyPath)
            .completer(new AggregateCompleter(completers)).highlighter(new DefaultHighlighter())
            .build();
    history.attach(reader);

    setOptions(reader);

    return reader;
}
 
Example #2
Source File: Console.java    From xraft with MIT License 6 votes vote down vote up
public Console(Map<NodeId, Address> serverMap) {
    commandMap = buildCommandMap(Arrays.asList(
            new ExitCommand(),
            new ClientAddServerCommand(),
            new ClientRemoveServerCommand(),
            new ClientListServerCommand(),
            new ClientGetLeaderCommand(),
            new ClientSetLeaderCommand(),
            new RaftAddNodeCommand(),
            new RaftRemoveNodeCommand(),
            new KVStoreGetCommand(),
            new KVStoreSetCommand()
    ));
    commandContext = new CommandContext(serverMap);

    ArgumentCompleter completer = new ArgumentCompleter(
            new StringsCompleter(commandMap.keySet()),
            new NullCompleter()
    );
    reader = LineReaderBuilder.builder()
            .completer(completer)
            .build();
}
 
Example #3
Source File: VelocityConsole.java    From Velocity with 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 #4
Source File: SimpleTerminalConsole.java    From TerminalConsoleAppender with 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 #5
Source File: InputReader.java    From presto with Apache License 2.0 6 votes vote down vote up
public InputReader(Path historyFile, Completer... completers)
        throws IOException
{
    Terminal terminal = TerminalBuilder.builder()
            .name("Presto")
            .build();

    reader = LineReaderBuilder.builder()
            .terminal(terminal)
            .variable(HISTORY_FILE, historyFile)
            .variable(SECONDARY_PROMPT_PATTERN, colored("%P -> "))
            .variable(BLINK_MATCHING_PAREN, 0)
            .parser(new InputParser())
            .highlighter(new InputHighlighter())
            .completer(new AggregateCompleter(completers))
            .build();

    reader.unsetOpt(HISTORY_TIMESTAMPED);
}
 
Example #6
Source File: LogServiceShell.java    From incubator-ratis with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  final Terminal terminal = TerminalBuilder.builder()
      .system(true)
      .build();

  History defaultHistory = new DefaultHistory();
  // Register a shutdown-hook per JLine documentation to save history
  Runtime.getRuntime().addShutdownHook(new Thread(() -> {
    try {
      defaultHistory.save();
    } catch (IOException e) {
      LOG.debug("Failed to save terminal history", e);
    }
  }));

  final LineReader lineReader = LineReaderBuilder.builder()
      .terminal(terminal)
      .highlighter(new DefaultHighlighter())
      .history(defaultHistory)
      .build();

  LogServiceShellOpts opts = new LogServiceShellOpts();
  JCommander.newBuilder()
      .addObject(opts)
      .build()
      .parse(args);

  try (LogServiceClient logServiceClient = new LogServiceClient(opts.getMetaQuorum())) {
    LogServiceShell client = new LogServiceShell(terminal, lineReader, logServiceClient);
    client.run();
  }
}
 
Example #7
Source File: SqlLineArgsTest.java    From sqlline with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testAnsiConsoleFormatWithZeroMaxWidthAndExistingTerminal() {
  try {
    new MockUp<DumbTerminal>() {
      @Mock
      public Size getSize() {
        return new Size(80, 20);
      }
    };
    final LineReaderBuilder lineReaderBuilder = LineReaderBuilder.builder()
        .parser(new SqlLineParser(sqlLine))
        .terminal(TerminalBuilder.builder().dumb(true).build());
    sqlLine.setLineReader(lineReaderBuilder.build());
    final String script = "!set maxwidth 0\n"
        + "!set incremental true \n"
        + "!set outputformat ansiconsole \n"
        + "!all \n"
        + "values \n"
        + "(1, '2') \n"
        + ";\n";
    final String line1 = ""
        + "C1          C2\n"
        + "1           2 \n";
    checkScriptFile(script, false,
        equalTo(SqlLine.Status.OK),
        containsString(line1));
  } catch (Exception e) {
    fail("Test failed with ", e);
  }
}
 
Example #8
Source File: SqlLineArgsTest.java    From sqlline with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testTableOutputWithZeroMaxWidthAndExistingTerminal() {
  try {
    new MockUp<DumbTerminal>() {
      @Mock
      public Size getSize() {
        return new Size(80, 20);
      }
    };
    final LineReaderBuilder lineReaderBuilder = LineReaderBuilder.builder()
        .parser(new SqlLineParser(sqlLine))
        .terminal(TerminalBuilder.builder().dumb(true).build());
    sqlLine.setLineReader(lineReaderBuilder.build());
    final String script = "!set maxwidth 0\n"
        + "!set incremental true\n"
        + "values (1, cast(null as integer), cast(null as varchar(3)));\n";
    checkScriptFile(script, false,
        equalTo(SqlLine.Status.OK),
        containsString(
            "+-------------+-------------+-----+\n"
                + "|     C1      |     C2      | C3  |\n"
                + "+-------------+-------------+-----+\n"
                + "| 1           | null        |     |\n"
                + "+-------------+-------------+-----+\n"));
  } catch (Exception e) {
    fail("Test failed with ", e);
  }
}
 
Example #9
Source File: SqshConsole.java    From jsqsh with Apache License 2.0 5 votes vote down vote up
public LineReader getSimpleLineReader() {

        if (simpleLineReader == null) {

            simpleLineReader = LineReaderBuilder.builder()
                    .appName("jsqsh")
                    .terminal(newTerminal())
                    .build();
        }

        return simpleLineReader;
    }
 
Example #10
Source File: SqshConsole.java    From jsqsh with Apache License 2.0 5 votes vote down vote up
public SqshConsole(SqshContext context) {

        this.context = context;
        File readlineHistory = new File(context.getConfigDirectory(), "jline_history");
        reader = LineReaderBuilder.builder()
                .appName("jsqsh")
                .terminal(newTerminal())
                .completer(new JLineCompleter(context))
                .parser(new DefaultParser())
                .variable(LineReader.HISTORY_FILE, readlineHistory.toString())
                .build();

        /*
         * This installs a widget that intercepts \n and attempts to determine if the
         * input is "finished" and should be run or if the user should keep typing
         * the current statement. I hate that I have to do this for all of the keymaps
         * that JLine3 has...
         */
        for (String keyMap : reader.getKeyMaps().keySet()) {

            // Bind to CTRL-M (enter)
            reader.getKeyMaps().get(keyMap).bind(new Reference("jsqsh-accept"), ctrl('M'));
            // Bind CTRL-G to automatically do "go"
            reader.getKeyMaps().get(keyMap).bind(new Reference("jsqsh-go"), ctrl('G'));
        }
        reader.getWidgets().put("jsqsh-accept", new JLineAcceptBufferWidget());
        reader.getWidgets().put("jsqsh-go", new JLineExecuteBufferWidget());

        reader.setOpt(LineReader.Option.DISABLE_EVENT_EXPANSION);
    }
 
Example #11
Source File: Shell.java    From joinery with GNU General Public License v3.0 5 votes vote down vote up
private JLineConsole()
throws IOException {
    String name = DataFrame.class.getPackage().getName();
    console = LineReaderBuilder.builder()
                .appName(name)
                .completer(this)
                .build();
}
 
Example #12
Source File: CliClientTest.java    From flink with 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();
	String sessionId = mockExecutor.openSession(context);

	final SqlCompleter completer = new SqlCompleter(sessionId, 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 #13
Source File: LogServiceShell.java    From ratis with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  final Terminal terminal = TerminalBuilder.builder()
      .system(true)
      .build();

  History defaultHistory = new DefaultHistory();
  // Register a shutdown-hook per JLine documentation to save history
  Runtime.getRuntime().addShutdownHook(new Thread(() -> {
    try {
      defaultHistory.save();
    } catch (IOException e) {
      LOG.debug("Failed to save terminal history", e);
    }
  }));

  final LineReader lineReader = LineReaderBuilder.builder()
      .terminal(terminal)
      .highlighter(new DefaultHighlighter())
      .history(defaultHistory)
      .build();

  LogServiceShellOpts opts = new LogServiceShellOpts();
  JCommander.newBuilder()
      .addObject(opts)
      .build()
      .parse(args);

  try (LogServiceClient logServiceClient = new LogServiceClient(opts.metaQuorum)) {
    LogServiceShell client = new LogServiceShell(terminal, lineReader, logServiceClient);
    client.run();
  }
}
 
Example #14
Source File: ConsoleIO.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Build JLine line reader with default history
 *
 * @return line reader
 */
private LineReader buildLineReader() {
	History history = new DefaultHistory();
	LineReader reader = LineReaderBuilder.builder().terminal(this.terminal).history(history).build();

	Path file = Paths.get(appInfo.getDataDirectory().toString(), "history.txt");
	reader.setVariable(LineReader.HISTORY_FILE, file);

	return reader;
}
 
Example #15
Source File: NukkitConsole.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected LineReader buildReader(LineReaderBuilder builder) {
    builder.completer(new NukkitConsoleCompleter(server));
    builder.appName("Nukkit");
    builder.option(LineReader.Option.HISTORY_BEEP, false);
    builder.option(LineReader.Option.HISTORY_IGNORE_DUPS, true);
    builder.option(LineReader.Option.HISTORY_IGNORE_SPACE, true);
    return super.buildReader(builder);
}
 
Example #16
Source File: AbstractClientShellHandler.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
/**
 * Create {@link LineReader}.
 * 
 * @return
 */
private LineReader createLineReader() {
	try {
		return LineReaderBuilder.builder().appName("Devops Shell Cli").completer(new DynamicCompleter(getSingle()))
				.terminal(TerminalBuilder.terminal()).build();
	} catch (IOException e) {
		throw new IllegalStateException(e);
	}
}
 
Example #17
Source File: JLineReader.java    From ksql-fork-with-deep-learning-function with Apache License 2.0 5 votes vote down vote up
public JLineReader(Terminal terminal) {
  // The combination of parser/expander here allow for multiple-line commands connected by '\\'
  DefaultParser parser = new DefaultParser();
  parser.setEofOnEscapedNewLine(true);
  parser.setQuoteChars(new char[0]);
  parser.setEscapeChars(new char[]{'\\'});

  final Expander expander = new NoOpExpander();
  // TODO: specify a completer to use here via a call to LineReaderBuilder.completer()
  this.lineReader = LineReaderBuilder.builder()
      .appName("KSQL")
      .expander(expander)
      .parser(parser)
      .terminal(terminal)
      .build();

  this.lineReader.setOpt(LineReader.Option.HISTORY_IGNORE_DUPS);
  this.lineReader.setOpt(LineReader.Option.HISTORY_IGNORE_SPACE);

  Path historyFilePath = Paths.get(System.getProperty(
      "history-file",
      System.getProperty("user.home")
      + "/.ksql-history"
  )).toAbsolutePath();
  if (CliUtils.createFile(historyFilePath)) {
    this.lineReader.setVariable(LineReader.HISTORY_FILE, historyFilePath);
    LOGGER.info("Command history saved at: " + historyFilePath);
  } else {
    terminal.writer().println(String.format(
        "WARNING: Unable to create command history file '%s', command history will not be saved.",
        historyFilePath
    ));
  }

  this.lineReader.unsetOpt(LineReader.Option.HISTORY_INCREMENTAL);
  this.history = new DefaultHistory(this.lineReader);

  this.prompt = DEFAULT_PROMPT;
}
 
Example #18
Source File: TerminalUi.java    From milkman with MIT License 5 votes vote down vote up
@PostConstruct
@SneakyThrows
public void setup() {
	cmd = new CommandLine(CommandSpec.create()
			.name("")
			.addSubcommand(null, commandSpecFactory.getSpecFor(wsCmd))
			.addSubcommand(null, commandSpecFactory.getSpecFor(execCmd))
			.addSubcommand(null, commandSpecFactory.getSpecFor(editCmd))
			.addSubcommand(null, commandSpecFactory.getSpecFor(quitCmd))
			.addSubcommand(null, commandSpecFactory.getSpecFor(colCmd)));
       
	cmd.setExecutionExceptionHandler(new IExecutionExceptionHandler() {
		
		@Override
		public int handleExecutionException(Exception ex, CommandLine commandLine, ParseResult parseResult)
				throws Exception {
			System.out.println(ex.getMessage());
			log.error("Command execution failed", ex);
			return 0;
		}
	});
       
       terminal = TerminalBuilder.builder()
       		.build();
       reader = LineReaderBuilder.builder()
               .terminal(terminal)
               .completer(new PicocliJLineCompleter(cmd.getCommandSpec()))
               .parser(new DefaultParser())
               .build();
       rightPrompt = null;
}
 
Example #19
Source File: CliClientTest.java    From flink with 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 #20
Source File: CliClient.java    From flink with 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 #21
Source File: CliClientTest.java    From Flink-CEPplus with 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 #22
Source File: CliClient.java    From Flink-CEPplus with 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 #23
Source File: TerminalProcessor.java    From sshd-shell-spring-boot with Apache License 2.0 4 votes vote down vote up
private LineReader newLineReaderInstance(final Terminal terminal) {
    return LineReaderBuilder.builder()
            .terminal(terminal)
            .completer(completer)
            .build();
}
 
Example #24
Source File: InteractiveMode.java    From rdflint with MIT License 4 votes vote down vote up
/**
 * execute interacitve mode.
 */
void execute(Map<String, String> cmdOptions) throws IOException {
  // initialize graph model
  Model m = ModelFactory.createDefaultModel();

  // initialize jline
  Terminal terminal = TerminalBuilder.builder()
      .system(true)
      .build();
  LineReader lineReader = LineReaderBuilder.builder()
      .terminal(terminal)
      .completer(new InteractiveCompleter(m))
      .parser(new InteractiveParser())
      .build();

  String welcome = MessageFormat
      .format(messages.getString("interactivemode.welcome"), RdfLint.VERSION);
  System.out.println(welcome);// NOPMD

  RdfLintParameters params = new RdfLintParameters();
  try {
    // load configurations
    params = ConfigurationLoader.loadParameters(cmdOptions);
    // load rdf
    m.removeAll();
    m.add(DatasetLoader.loadRdfSet(params, params.getTargetDir()));
  } catch (Exception ex) {
    System.out.println(ex.getLocalizedMessage()); // NOPMD
  }

  while (true) {
    String line;

    try {
      line = lineReader.readLine("SPARQL> ");
    } catch (UserInterruptException | EndOfFileException e) {
      return;
    }

    if (!interactiveCommand(System.out, line, params, cmdOptions, m)) {
      return;
    }
  }
}
 
Example #25
Source File: CliShell.java    From samza with Apache License 2.0 4 votes vote down vote up
CliShell(CliEnvironment environment) throws ExecutorException {
  if (environment == null) {
    throw new IllegalArgumentException();
  }

  // Terminal
  try {
    terminal = TerminalBuilder.builder().name(CliConstants.WINDOW_TITLE).build();
  } catch (IOException e) {
    throw new CliException("Error when creating terminal", e);
  }

  // Terminal writer
  writer = terminal.writer();

  // LineReader
  final DefaultParser parser = new DefaultParser().eofOnEscapedNewLine(true).eofOnUnclosedQuote(true);
  lineReader = LineReaderBuilder.builder()
      .appName(CliConstants.APP_NAME)
      .terminal(terminal)
      .parser(parser)
      .highlighter(new CliHighlighter())
      .completer(new StringsCompleter(CliCommandType.getAllCommands()))
      .build();

  // Command Prompt
  firstPrompt = new AttributedStringBuilder().style(AttributedStyle.DEFAULT.foreground(AttributedStyle.YELLOW))
      .append(CliConstants.PROMPT_1ST + CliConstants.PROMPT_1ST_END)
      .toAnsi();

  // Execution context and executor
  executor = environment.getExecutor();
  exeContext = new ExecutionContext();
  executor.start(exeContext);

  // Command handlers
  if (commandHandlers == null) {
    commandHandlers = new ArrayList<>();
  }
  commandHandlers.add(new CliCommandHandler());
  commandHandlers.addAll(environment.getCommandHandlers());
  for (CommandHandler commandHandler : commandHandlers) {
    LOG.info("init commandHandler {}", commandHandler.getClass().getName());
    commandHandler.init(this, environment, terminal, exeContext);
  }
}
 
Example #26
Source File: Client.java    From batfish with Apache License 2.0 4 votes vote down vote up
public Client(Settings settings) {
  _additionalBatfishOptions = new HashMap<>();
  _bfq = new TreeMap<>();
  _settings = settings;

  switch (_settings.getRunMode()) {
    case batch:
      if (_settings.getBatchCommandFile() == null) {
        System.err.println(
            "org.batfish.client: Command file not specified while running in batch mode.");
        System.err.printf(
            "Use '-%s <cmdfile>' if you want batch mode, or '-%s interactive' if you want "
                + "interactive mode\n",
            Settings.ARG_COMMAND_FILE, Settings.ARG_RUN_MODE);
        System.exit(1);
      }
      _logger = new BatfishLogger(_settings.getLogLevel(), false, _settings.getLogFile());
      break;
    case interactive:
      System.err.println(
          "This is not a supported client for Batfish. Please use pybatfish following the "
              + "instructions in the README: https://github.com/batfish/batfish/#how-do-i-get-started");
      try {
        _reader =
            LineReaderBuilder.builder()
                .terminal(TerminalBuilder.builder().build())
                .completer(new ArgumentCompleter(new CommandCompleter(), new NullCompleter()))
                .build();
        Path historyPath = Paths.get(System.getenv(ENV_HOME), HISTORY_FILE);
        historyPath.toFile().createNewFile();
        _reader.setVariable(LineReader.HISTORY_FILE, historyPath.toAbsolutePath().toString());
        _reader.unsetOpt(Option.INSERT_TAB); // supports completion with nothing entered

        @SuppressWarnings("PMD.CloseResource") // PMD does not understand things closed later.
        PrintWriter pWriter = new PrintWriter(_reader.getTerminal().output(), true);
        @SuppressWarnings("PMD.CloseResource") // PMD does not understand things closed later.
        OutputStream os = new WriterOutputStream(pWriter, StandardCharsets.UTF_8);
        @SuppressWarnings("PMD.CloseResource") // PMD does not understand things closed later.
        PrintStream ps = new PrintStream(os, true);
        _logger = new BatfishLogger(_settings.getLogLevel(), false, ps);
      } catch (Exception e) {
        System.err.printf("Could not initialize client: %s\n", e.getMessage());
        e.printStackTrace();
      }
      break;
    default:
      System.err.println("org.batfish.client: Unknown run mode.");
      System.exit(1);
  }
}
 
Example #27
Source File: SimpleTerminalConsole.java    From TerminalConsoleAppender with MIT License 3 votes vote down vote up
/**
 * Configures the {@link LineReaderBuilder} and {@link LineReader} with
 * additional options.
 *
 * <p>Override this method to make further changes, (e.g. call
 * {@link LineReaderBuilder#appName(String)} or
 * {@link LineReaderBuilder#completer(Completer)}).</p>
 *
 * <p>The default implementation sets some opinionated default options,
 * which are considered to be appropriate for most applications:</p>
 *
 * <ul>
 *     <li>{@link LineReader.Option#DISABLE_EVENT_EXPANSION}: JLine implements
 *     <a href="http://www.gnu.org/software/bash/manual/html_node/Event-Designators.html">
 *     Bash's Event Designators</a> by default. These usually do not
 *     behave as expected in a simple command environment, so it's
 *     recommended to disable it.</li>
 *     <li>{@link LineReader.Option#INSERT_TAB}: By default, JLine inserts
 *     a tab character when attempting to tab-complete on empty input.
 *     It is more intuitive to show a list of commands instead.</li>
 * </ul>
 *
 * @param builder The builder to configure
 * @return The built line reader
 */
protected LineReader buildReader(LineReaderBuilder builder) {
    LineReader reader = builder.build();
    reader.setOpt(LineReader.Option.DISABLE_EVENT_EXPANSION);
    reader.unsetOpt(LineReader.Option.INSERT_TAB);
    return reader;
}