You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by pa...@apache.org on 2026/09/14 11:21:31 UTC
(groovy) 12/20: GROOVY-12403: review follow-ups for the groovysh embedding API
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch GROOVY_6_0_X
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit d4a7d9ec9567a789235ce521f5f13d6052e8f938
Author: Paul King <pa...@asert.com.au>
AuthorDate: Mon Sep 14 13:42:01 2026 +1000
GROOVY-12403: review follow-ups for the groovysh embedding API
Builds on the previous commit.
Correctness:
- ExtraConsoleCommands.commandInfo(String) ignored its argument and
returned the whole POSIX command-name list, so /help described all
thirteen console commands as "date" and completion candidates showed
the same. It now derives a one-line description per command, lazily
and cached, from the usage text the command itself parses. The test
that asserted the old behaviour is replaced by one that pins the new.
Embedding API:
- GroovyshOptions now mirrors JLine's ShellBuilder wherever an
equivalent exists, so a later move onto org.jline.shell need not
break this API: extraCommandRegistry becomes groups(CommandGroup...),
and prompt(String), rightPrompt, historyFile(Path) and
onReaderReady(Consumer<LineReader>) are added. The compiler
configuration, engine, bindings, banner and result/error handlers
have no ShellBuilder equivalent and keep their own names.
- The published API no longer names JLine types deprecated since
JLine 4.0. Command groups arrive as org.jline.shell.CommandGroup and
are adapted with CommandRegistryAdapter; ResultHandler takes a
Printer; ErrorHandler takes the error plus the default renderer.
groovysh's internals stay on org.jline.console.
- Embedder groups are registered ahead of groovysh's own, so a host
console can override a built-in command name.
- historyFile is wired with an explicit null check: Groovy truth on a
Path is Files.exists, so an elvis would discard a history file that
does not exist yet.
Documentation:
- The three embedding examples were included without a listing block
and rendered as prose. They are wrapped now, and the GroovyshOptions
example shows the hooks rather than --help.
- GroovyEngine(ClassLoader, Binding, CompilerConfiguration) documents
that a compatible EngineClassLoader is adopted rather than wrapped,
and that engines sharing one then share its class cache.
- ARCHITECTURE.md records which JLine API groovysh is on, why it has
not moved to org.jline.shell, and what the migration path is.
Housekeeping:
- @Incubating on the rest of the new surface, not just GroovyshOptions.
- ExtraConsoleCommands suppresses the deprecation warning it inherited
from Main before being extracted; GroovyshOptions drops a suppression
it never needed.
- The ThreadInterrupt test uses a daemon thread and a bounded loop, so
a missed interrupt cannot leave a core spinning for the rest of the
forked JVM.
- Unnecessary groovy.lang imports; import order in Main.
- jline-shell is declared explicitly now that it is referenced.
---
subprojects/groovy-groovysh/ARCHITECTURE.md | 38 +++++
subprojects/groovy-groovysh/build.gradle | 1 +
.../groovy/groovysh/ExtraConsoleCommands.groovy | 60 +++++--
.../apache/groovy/groovysh/GroovyshOptions.java | 173 +++++++++++++++++----
.../groovy/org/apache/groovy/groovysh/Main.groovy | 35 +++--
.../apache/groovy/groovysh/jline/GroovyEngine.java | 28 +++-
.../groovy-groovysh/src/spec/doc/groovysh.adoc | 48 ++++--
.../src/spec/test/EmbeddingSpecTest.groovy | 43 ++++-
.../groovysh/ExtraConsoleCommandsTest.groovy | 27 +++-
.../groovy/groovysh/GroovyshEmbeddingTest.groovy | 121 +++++++++-----
.../groovy/groovysh/GroovyshOptionsTest.groovy | 64 ++++----
.../groovy/groovysh/jline/GroovyEngineTest.groovy | 9 +-
12 files changed, 489 insertions(+), 158 deletions(-)
diff --git a/subprojects/groovy-groovysh/ARCHITECTURE.md b/subprojects/groovy-groovysh/ARCHITECTURE.md
index ed2a40309f..be512c493c 100644
--- a/subprojects/groovy-groovysh/ARCHITECTURE.md
+++ b/subprojects/groovy-groovysh/ARCHITECTURE.md
@@ -239,6 +239,44 @@ the public seams rather than copying `Main`:
`/pwd`, `/cd`, the POSIX-style commands, and `/!`.
`Main.ExtraConsoleCommands` is a deprecated subclass.
+Where a `GroovyshOptions` setting has an equivalent on JLine's
+`ShellBuilder`, it uses the same name and parameter type on purpose.
+
+## JLine: which API we are on, and why
+
+groovysh is built on `org.jline.console` — `SystemRegistryImpl`,
+`ConsoleEngineImpl`, `Builtins`, `JlineCommandRegistry`,
+`DefaultPrinter`, `ScriptEngine`. None of those *classes* is
+deprecated, but five interfaces in that package are, as of JLine 4.0:
+`CommandRegistry`, `ConsoleEngine`, `SystemRegistry`, `CommandMethods`,
+`CommandInput` (plus the `CmdDesc` / `CmdLine` / `ArgDesc` description
+types).
+
+The successor is `org.jline.shell` (`Shell`, `CommandDispatcher`,
+`CommandGroup`, `Command`, `ShellBuilder`), a compile-scope transitive
+dependency of `jline-console` and so already on our classpath. We have
+not moved onto it, for one structural reason: it models a *command*
+shell, not a language REPL. `DefaultCommandDispatcher` throws
+`UnknownCommandException` instead of falling through to a script
+engine, and `Shell.run()` discards the value of `dispatcher.execute`,
+so there is nowhere to print a result. Those semantics are exactly
+what the deprecated console layer supplies. In JLine 4.4.3 the console
+implementations contain no references to `org.jline.shell` either, so
+there is no upstream migration to follow yet.
+
+What we do instead: keep the deprecated types out of the *published*
+embedding API. `GroovyshOptions.groups` takes `org.jline.shell.CommandGroup`
+and wraps it with `CommandRegistryAdapter`; the result and error
+handlers take `Printer` and plain JDK types.
+
+Revisit when JLine rebases the console implementations on
+`org.jline.shell`, or announces a removal release for
+`org.jline.console`. The migration path, when it comes, is a
+`CommandDispatcher` subclass: `DefaultCommandDispatcher.execute(String)`
+is public, non-final and returns `Object`, so it can intercept the
+unknown-command path and delegate to `GroovyEngine` while keeping
+JLine's pipelines, redirection and job control.
+
The user-facing description is
[`src/spec/doc/groovysh.adoc`](src/spec/doc/groovysh.adoc)
"Embedding groovysh". Tests live in `GroovyEngineTest`,
diff --git a/subprojects/groovy-groovysh/build.gradle b/subprojects/groovy-groovysh/build.gradle
index 7abbc203d1..f0b9134065 100644
--- a/subprojects/groovy-groovysh/build.gradle
+++ b/subprojects/groovy-groovysh/build.gradle
@@ -46,6 +46,7 @@ dependencies {
implementation "org.jline:jline-builtins:${versions.jline}"
implementation "org.jline:jline-reader:${versions.jline}"
implementation "org.jline:jline-console:${versions.jline}"
+ implementation "org.jline:jline-shell:${versions.jline}"
implementation "org.jline:jline-terminal-jni:${versions.jline}"
implementation("org.jline:jline-terminal:${versions.jline}") {
// exclude(group: 'junit', module: 'junit')
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/ExtraConsoleCommands.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/ExtraConsoleCommands.groovy
index 6aaf57765f..f0acc3eead 100644
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/ExtraConsoleCommands.groovy
+++ b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/ExtraConsoleCommands.groovy
@@ -21,6 +21,7 @@ package org.apache.groovy.groovysh
import org.apache.groovy.groovysh.jline.GroovyEngine
import org.apache.groovy.groovysh.jline.GroovyPosixCommands
import org.apache.groovy.groovysh.jline.GroovyPosixContext
+import org.apache.groovy.lang.annotation.Incubating
import org.jline.builtins.Completers
import org.jline.builtins.Options
import org.jline.builtins.PosixCommands
@@ -38,6 +39,7 @@ import org.jline.utils.InfoCmp.Capability
import org.jline.utils.OSUtils
import java.nio.file.Path
+import java.util.concurrent.ConcurrentHashMap
import java.util.function.Function
/**
@@ -54,7 +56,8 @@ import java.util.function.Function
*
* @since 7.0.0
*/
-@SuppressWarnings('resource')
+@Incubating
+@SuppressWarnings(['resource', 'deprecation'])
class ExtraConsoleCommands extends JlineCommandRegistry implements CommandRegistry {
/**
@@ -62,8 +65,21 @@ class ExtraConsoleCommands extends JlineCommandRegistry implements CommandRegist
*/
static final List<String> POSIX_COMMANDS = ['/ls', '/wc', '/sort', '/head', '/tail', '/cat', '/grep'].asImmutable()
+ private static final String[] CLEAR_USAGE = [
+ '/clear - clear terminal',
+ 'Usage: /clear',
+ ' -? --help Displays command help'
+ ]
+
+ private static final String[] SHELL_USAGE = [
+ '/!<command> - execute shell command',
+ 'Usage: /!<command>',
+ ' -? --help Displays command help'
+ ]
+
private final LineReader reader
private final GroovyEngine scriptEngine
+ private final Map<String, List<String>> commandInfos = new ConcurrentHashMap<>()
private PosixCommandsRegistry posix
/**
@@ -193,13 +209,8 @@ class ExtraConsoleCommands extends JlineCommandRegistry implements CommandRegist
}
private void clear(CommandInput input) {
- final String[] usage = [
- "/clear - clear terminal",
- "Usage: /clear",
- " -? --help Displays command help"
- ]
try {
- parseOptions(usage, input.args())
+ parseOptions(CLEAR_USAGE, input.args())
terminal().puts(Capability.clear_screen)
terminal().flush()
} catch (Exception e) {
@@ -225,14 +236,9 @@ class ExtraConsoleCommands extends JlineCommandRegistry implements CommandRegist
}
private void shell(CommandInput input) {
- final String[] usage = [
- "/!<command> - execute shell command",
- "Usage: /!<command>",
- " -? --help Displays command help"
- ]
if (input.args().length == 1 && (input.args()[0].equals("-?") || input.args()[0].equals("--help"))) {
try {
- parseOptions(usage, input.args())
+ parseOptions(SHELL_USAGE, input.args())
} catch (Exception e) {
saveException(e)
}
@@ -249,13 +255,35 @@ class ExtraConsoleCommands extends JlineCommandRegistry implements CommandRegist
}
/**
- * Returns summary text for the specified command.
+ * Returns summary text for the specified command. The first entry is the
+ * one-line description JLine renders beside the command in {@code /help}
+ * and in completion candidates.
*
* @param command command name to describe
- * @return help lines for the command
+ * @return help lines for the command, empty when it is not one of ours
*/
@Override
List<String> commandInfo(String command) {
- posix.commandNames.toList()
+ commandInfos.computeIfAbsent(command) { String cmd ->
+ String[] usage = usageFor(cmd)
+ usage == null || usage.length == 0 ? [] : [summarise(usage[0])].asImmutable()
+ }
+ }
+
+ private String[] usageFor(String command) {
+ switch (command) {
+ case '/clear' -> CLEAR_USAGE
+ case '/!' -> SHELL_USAGE
+ default -> hasCommand(command) ? adjustUsage(command[1..-1], command) : null
+ }
+ }
+
+ /**
+ * Reduces a usage headline such as {@code "/ls - list files"} to the
+ * description alone.
+ */
+ private static String summarise(String headline) {
+ int dash = headline.indexOf(' -')
+ (dash < 0 ? headline : headline.substring(dash + 2)).trim()
}
}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/GroovyshOptions.java b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/GroovyshOptions.java
index 699911e34f..37122ef5a0 100644
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/GroovyshOptions.java
+++ b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/GroovyshOptions.java
@@ -21,30 +21,39 @@ package org.apache.groovy.groovysh;
import org.apache.groovy.groovysh.jline.GroovyEngine;
import org.apache.groovy.lang.annotation.Incubating;
import org.codehaus.groovy.control.CompilerConfiguration;
-import org.jline.console.CommandRegistry;
-import org.jline.console.ConsoleEngine;
-import org.jline.console.SystemRegistry;
+import org.jline.console.Printer;
+import org.jline.reader.LineReader;
+import org.jline.shell.CommandGroup;
+import org.jline.shell.ShellBuilder;
import org.jline.terminal.Terminal;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
+import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* Configuration for embedding groovysh programmatically via
* {@link Main#start(GroovyshOptions, String[])}.
* <p>
+ * Where a setting has an equivalent on JLine's {@link ShellBuilder},
+ * this class deliberately uses the same name and parameter type, so that a future
+ * move of groovysh onto {@code org.jline.shell} is re-plumbing rather than a break
+ * in Groovy's API. The Groovy-specific settings — compiler configuration, engine,
+ * bindings, banner, and the result/error handlers a language REPL needs and a
+ * command shell does not — have no such equivalent.
+ * <p>
* Binding variables stay in {@link #getBindings()}; they are not mixed
* with embedding hooks. Construct with {@link #builder()}.
*
* @since 7.0.0
*/
@Incubating
-@SuppressWarnings("deprecation")
public final class GroovyshOptions {
/**
@@ -55,11 +64,11 @@ public final class GroovyshOptions {
/**
* Renders {@code result} after a line has been executed.
*
- * @param console the console engine used by the session
- * @param result the value returned by {@code SystemRegistry.execute}, which may be {@code null}
+ * @param printer the printer used by the session
+ * @param result the value returned by the command dispatch, which may be {@code null}
* @throws Exception if rendering fails; groovysh then routes it to the error handler
*/
- void handle(ConsoleEngine console, Object result) throws Exception;
+ void handle(Printer printer, Object result) throws Exception;
}
/**
@@ -72,32 +81,41 @@ public final class GroovyshOptions {
* {@code UserInterruptException} and {@code EndOfFileException} are
* not delivered here; {@link Main} treats those as control flow.
*
- * @param registry the system registry for the session
+ * A handler that throws is not caught again: the error escapes the REPL
+ * loop and {@link Main#start(GroovyshOptions, String[])} returns 1.
+ *
* @param error the thrown error or exception
+ * @param defaultTrace groovysh's own renderer, for a handler that wants to delegate
*/
- void handle(SystemRegistry registry, Throwable error);
+ void handle(Throwable error, Consumer<Throwable> defaultTrace);
}
private final CompilerConfiguration compilerConfiguration;
private final GroovyEngine engine;
private final Map<String, Object> bindings;
- private final List<CommandRegistry> extraCommandRegistries;
+ private final List<CommandGroup> groups;
private final Supplier<String> prompt;
+ private final Supplier<String> rightPrompt;
private final ResultHandler resultHandler;
private final ErrorHandler errorHandler;
private final boolean showBanner;
private final Terminal terminal;
+ private final Path historyFile;
+ private final Consumer<LineReader> onReaderReady;
private GroovyshOptions(Builder builder) {
this.compilerConfiguration = builder.compilerConfiguration;
this.engine = builder.engine;
this.bindings = Collections.unmodifiableMap(new LinkedHashMap<>(builder.bindings));
- this.extraCommandRegistries = Collections.unmodifiableList(new ArrayList<>(builder.extraCommandRegistries));
+ this.groups = Collections.unmodifiableList(new ArrayList<>(builder.groups));
this.prompt = builder.prompt;
+ this.rightPrompt = builder.rightPrompt;
this.resultHandler = builder.resultHandler;
this.errorHandler = builder.errorHandler;
this.showBanner = builder.showBanner;
this.terminal = builder.terminal;
+ this.historyFile = builder.historyFile;
+ this.onReaderReady = builder.onReaderReady;
}
/**
@@ -139,12 +157,14 @@ public final class GroovyshOptions {
}
/**
- * Extra command registries appended after groovysh's own registries.
+ * Command groups contributed by the embedder. They are resolved
+ * <em>before</em> groovysh's own commands, so a group may override a
+ * built-in command name.
*
* @return an unmodifiable list, never {@code null}
*/
- public List<CommandRegistry> getExtraCommandRegistries() {
- return extraCommandRegistries;
+ public List<CommandGroup> getGroups() {
+ return groups;
}
/**
@@ -157,7 +177,16 @@ public final class GroovyshOptions {
}
/**
- * Result renderer. {@code null} means print {@code result?.toString()} via the console engine.
+ * Right-hand prompt supplier invoked on each REPL iteration.
+ *
+ * @return the right prompt supplier, or {@code null} for none
+ */
+ public Supplier<String> getRightPrompt() {
+ return rightPrompt;
+ }
+
+ /**
+ * Result renderer. {@code null} means print {@code result?.toString()} via the printer.
*
* @return the result handler, or {@code null}
*/
@@ -166,7 +195,7 @@ public final class GroovyshOptions {
}
/**
- * Error renderer. {@code null} means {@code SystemRegistry.trace(error)}.
+ * Error renderer. {@code null} means groovysh's own trace.
*
* @return the error handler, or {@code null}
*/
@@ -192,6 +221,27 @@ public final class GroovyshOptions {
return terminal;
}
+ /**
+ * History file for the session. {@code null} means groovysh's own
+ * {@code groovysh_history} in the user state directory.
+ *
+ * @return the history file, or {@code null}
+ */
+ public Path getHistoryFile() {
+ return historyFile;
+ }
+
+ /**
+ * Callback invoked once the {@link LineReader} has been built, for settings
+ * this class does not model — the secondary prompt pattern, key bindings,
+ * reader options.
+ *
+ * @return the callback, or {@code null}
+ */
+ public Consumer<LineReader> getOnReaderReady() {
+ return onReaderReady;
+ }
+
/**
* Builder for {@link GroovyshOptions}.
*
@@ -202,12 +252,15 @@ public final class GroovyshOptions {
private CompilerConfiguration compilerConfiguration;
private GroovyEngine engine;
private final Map<String, Object> bindings = new LinkedHashMap<>();
- private final List<CommandRegistry> extraCommandRegistries = new ArrayList<>();
+ private final List<CommandGroup> groups = new ArrayList<>();
private Supplier<String> prompt;
+ private Supplier<String> rightPrompt;
private ResultHandler resultHandler;
private ErrorHandler errorHandler;
private boolean showBanner = true;
private Terminal terminal;
+ private Path historyFile;
+ private Consumer<LineReader> onReaderReady;
private Builder() {
}
@@ -267,33 +320,49 @@ public final class GroovyshOptions {
}
/**
- * Appends an extra command registry.
+ * Appends command groups. Mirrors {@code ShellBuilder.groups(CommandGroup...)}.
*
- * @param registry the registry to append, must not be {@code null}
+ * @param groups groups to append; {@code null} entries are rejected
* @return this builder
*/
- public Builder extraCommandRegistry(CommandRegistry registry) {
- this.extraCommandRegistries.add(Objects.requireNonNull(registry, "registry"));
+ public Builder groups(CommandGroup... groups) {
+ if (groups != null) {
+ for (CommandGroup group : groups) {
+ this.groups.add(Objects.requireNonNull(group, "group"));
+ }
+ }
return this;
}
/**
- * Appends extra command registries.
+ * Appends command groups.
*
- * @param registries registries to append; {@code null} is ignored
+ * @param groups groups to append; {@code null} is ignored
* @return this builder
*/
- public Builder extraCommandRegistries(Iterable<? extends CommandRegistry> registries) {
- if (registries != null) {
- for (CommandRegistry registry : registries) {
- extraCommandRegistry(registry);
+ public Builder groups(Iterable<? extends CommandGroup> groups) {
+ if (groups != null) {
+ for (CommandGroup group : groups) {
+ this.groups.add(Objects.requireNonNull(group, "group"));
}
}
return this;
}
/**
- * Sets the prompt supplier. Called once per REPL iteration.
+ * Sets a fixed prompt. Mirrors {@code ShellBuilder.prompt(String)}.
+ *
+ * @param prompt the prompt text, or {@code null} for {@code "groovy> "}
+ * @return this builder
+ */
+ public Builder prompt(String prompt) {
+ this.prompt = prompt == null ? null : () -> prompt;
+ return this;
+ }
+
+ /**
+ * Sets the prompt supplier, called once per REPL iteration.
+ * Mirrors {@code ShellBuilder.prompt(Supplier)}.
*
* @param prompt the supplier, or {@code null} for {@code "groovy> "}
* @return this builder
@@ -303,6 +372,28 @@ public final class GroovyshOptions {
return this;
}
+ /**
+ * Sets a fixed right-hand prompt. Mirrors {@code ShellBuilder.rightPrompt(String)}.
+ *
+ * @param rightPrompt the prompt text, or {@code null} for none
+ * @return this builder
+ */
+ public Builder rightPrompt(String rightPrompt) {
+ this.rightPrompt = rightPrompt == null ? null : () -> rightPrompt;
+ return this;
+ }
+
+ /**
+ * Sets the right-hand prompt supplier. Mirrors {@code ShellBuilder.rightPrompt(Supplier)}.
+ *
+ * @param rightPrompt the supplier, or {@code null} for none
+ * @return this builder
+ */
+ public Builder rightPrompt(Supplier<String> rightPrompt) {
+ this.rightPrompt = rightPrompt;
+ return this;
+ }
+
/**
* Sets the result handler.
*
@@ -317,7 +408,7 @@ public final class GroovyshOptions {
/**
* Sets the error handler.
*
- * @param errorHandler the handler, or {@code null} for {@code SystemRegistry.trace}
+ * @param errorHandler the handler, or {@code null} for groovysh's own trace
* @return this builder
*/
public Builder errorHandler(ErrorHandler errorHandler) {
@@ -338,6 +429,7 @@ public final class GroovyshOptions {
/**
* Supplies a terminal instead of letting {@link Main} build one from CLI flags.
+ * Mirrors {@code ShellBuilder.terminal(Terminal)}.
*
* @param terminal the terminal, or {@code null} to build the default
* @return this builder
@@ -347,6 +439,29 @@ public final class GroovyshOptions {
return this;
}
+ /**
+ * Sets the history file. Mirrors {@code ShellBuilder.historyFile(Path)}.
+ *
+ * @param historyFile the file, or {@code null} for groovysh's own
+ * @return this builder
+ */
+ public Builder historyFile(Path historyFile) {
+ this.historyFile = historyFile;
+ return this;
+ }
+
+ /**
+ * Registers a callback invoked once the {@link LineReader} is built.
+ * Mirrors {@code ShellBuilder.onReaderReady(Consumer)}.
+ *
+ * @param onReaderReady the callback, or {@code null} for none
+ * @return this builder
+ */
+ public Builder onReaderReady(Consumer<LineReader> onReaderReady) {
+ this.onReaderReady = onReaderReady;
+ return this;
+ }
+
/**
* Builds an immutable options object.
*
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/Main.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/Main.groovy
index 8597da4868..d2441496e4 100644
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/Main.groovy
+++ b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/Main.groovy
@@ -18,23 +18,23 @@
*/
package org.apache.groovy.groovysh
-import org.apache.groovy.groovysh.ExtraConsoleCommands as DefaultExtraConsoleCommands
-
import groovy.cli.internal.CliBuilderInternal
import groovy.cli.internal.OptionAccessor
+import org.apache.groovy.groovysh.ExtraConsoleCommands as DefaultExtraConsoleCommands
import org.apache.groovy.groovysh.jline.GroovyBuiltins
-import org.apache.groovy.lang.annotation.Incubating
import org.apache.groovy.groovysh.jline.GroovyCommands
import org.apache.groovy.groovysh.jline.GroovyConsoleEngine
import org.apache.groovy.groovysh.jline.GroovyEngine
import org.apache.groovy.groovysh.jline.GroovyPrinter
import org.apache.groovy.groovysh.jline.GroovySystemRegistry
import org.apache.groovy.groovysh.util.DocFinder
+import org.apache.groovy.lang.annotation.Incubating
import org.codehaus.groovy.tools.shell.util.MessageSource
import org.jline.builtins.ClasspathResourceUtil
import org.jline.builtins.ConfigurationPath
import org.jline.builtins.SyntaxHighlighter
import org.jline.console.CommandRegistry
+import org.jline.console.impl.CommandRegistryAdapter
import org.jline.console.ConsoleEngine
import org.jline.console.Printer
import org.jline.console.impl.SystemHighlighter
@@ -64,6 +64,7 @@ import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.attribute.PosixFilePermission
import java.nio.file.attribute.PosixFilePermissions
+import java.util.function.Consumer
import java.util.function.Supplier
import static org.jline.jansi.AnsiRenderer.render
@@ -335,8 +336,9 @@ class Main {
// handles the concurrent-creation race, and falls back on non-POSIX file systems.
// Creating it here first is what used to defeat that and leave it at the umask
// default. Only an already-open file is adjusted.
- .variable(LineReader.HISTORY_FILE,
- tightenStateFile(userStateDirectory.resolve('groovysh_history')))
+ .variable(LineReader.HISTORY_FILE, groovyshOptions.historyFile != null
+ ? groovyshOptions.historyFile
+ : tightenStateFile(userStateDirectory.resolve('groovysh_history')))
.option(Option.INSERT_BRACKET, true)
.option(Option.EMPTY_WORD_OPTIONS, false)
.option(Option.USE_FORWARD_SLASH, true)
@@ -346,6 +348,7 @@ class Main {
reader.setVariable(
LineReader.BLINK_MATCHING_PAREN, 0) // if enabled cursor remains in begin parenthesis (gitbash)
}
+ groovyshOptions.onReaderReady?.accept(reader)
def extra = new DefaultExtraConsoleCommands(Paths.get(System.getProperty('user.dir')), scriptEngine, reader)
Supplier<Path> workDir = extra::currentDir
@@ -363,8 +366,8 @@ class Main {
GroovySystemRegistry systemRegistry = new GroovySystemRegistry(parser, terminal, workDir, configPath).tap {
groupCommandsInHelp(false)
- def registries = [extra, consoleEngine, builtins, groovy]
- registries.addAll(groovyshOptions.extraCommandRegistries)
+ def registries = groovyshOptions.groups.collect { new CommandRegistryAdapter(it) as CommandRegistry }
+ registries.addAll([extra, consoleEngine, builtins, groovy])
setCommandRegistries(registries.toArray(new CommandRegistry[0]))
addCompleter(scriptEngine.scriptCompleter)
setScriptDescription(scriptEngine::scriptDescription)
@@ -401,6 +404,7 @@ class Main {
}
Supplier<String> prompt = groovyshOptions.prompt ?: ({ 'groovy> ' } as Supplier<String>)
+ Supplier<String> rightPrompt = groovyshOptions.rightPrompt
if (groovyshOptions.showBanner) {
if (options.q) {
@@ -430,7 +434,7 @@ class Main {
} else {
// for debugging
// line = lines[index++]
- line = reader.readLine(prompt.get())
+ line = reader.readLine(prompt.get(), rightPrompt?.get(), (Character) null, null)
}
line = line.readLines().collect{ s ->
// remove Groovy continuation character for repl not Groovy's sake
@@ -444,7 +448,7 @@ class Main {
}
}
Object result = systemRegistry.execute(line)
- emitResult(consoleEngine, result, groovyshOptions.resultHandler)
+ emitResult(printer, result, groovyshOptions.resultHandler)
// consoleEngine.println([(Printer.OBJECT_TO_STRING): [(Object) : { o -> o.toString() }] ], result)
} catch (UserInterruptException e) {
// Ignore
@@ -452,7 +456,7 @@ class Main {
String pl = e.getPartialLine()
if (pl != null) { // execute last line from redirected file (required for Windows)
try {
- emitResult(consoleEngine, systemRegistry.execute(pl), groovyshOptions.resultHandler)
+ emitResult(printer, systemRegistry.execute(pl), groovyshOptions.resultHandler)
} catch (Exception e2) {
emitError(systemRegistry, e2, groovyshOptions.errorHandler)
}
@@ -487,19 +491,20 @@ class Main {
start(GroovyshOptions.builder().build(), args)
}
- private static void emitResult(ConsoleEngine console, Object result, GroovyshOptions.ResultHandler handler) throws Exception {
+ private static void emitResult(Printer printer, Object result, GroovyshOptions.ResultHandler handler) throws Exception {
if (handler != null) {
- handler.handle(console, result)
+ handler.handle(printer, result)
} else {
- console.println(result?.toString())
+ printer.println(result?.toString())
}
}
private static void emitError(GroovySystemRegistry registry, Throwable error, GroovyshOptions.ErrorHandler handler) {
+ Consumer<Throwable> defaultTrace = registry::trace
if (handler != null) {
- handler.handle(registry, error)
+ handler.handle(error, defaultTrace)
} else {
- registry.trace(error)
+ defaultTrace.accept(error)
}
}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyEngine.java b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyEngine.java
index cceb00c408..0de65e6075 100644
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyEngine.java
+++ b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyEngine.java
@@ -22,6 +22,7 @@ import groovy.lang.MissingPropertyException;
import groovy.lang.Script;
import org.apache.groovy.ast.tools.ImmutablePropertyUtils;
import org.apache.groovy.groovysh.Main;
+import org.apache.groovy.lang.annotation.Incubating;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.ModuleImportHelper;
import org.codehaus.groovy.control.MultipleCompilationErrorsException;
@@ -225,6 +226,7 @@ public class GroovyEngine implements ScriptEngine {
* {@link CompilerConfiguration#DEFAULT}
* @since 7.0.0
*/
+ @Incubating
public GroovyEngine(CompilerConfiguration configuration) {
this(null, null, configuration);
}
@@ -232,14 +234,24 @@ public class GroovyEngine implements ScriptEngine {
/**
* Constructs a GroovyEngine with an explicit parent class loader, binding,
* and compiler configuration.
+ * <p>
+ * As with {@link GroovyShell}, an {@link EngineClassLoader} whose configuration
+ * is the same instance as {@code configuration} becomes the engine class loader
+ * itself rather than its parent; any other loader is wrapped. Two engines sharing
+ * one loader that way also share its class cache, so a cache purge from either —
+ * {@code /reset} and the type-redefinition paths do this — discards the other's
+ * classes, and their script classes occupy one namespace. Pass a plain
+ * {@link ClassLoader}, or a configuration this loader does not already hold, to
+ * get a child loader instead.
*
- * @param parent parent class loader, or {@code null} to use the thread
- * context class loader
+ * @param parent class loader to use as parent, or to adopt as described above;
+ * {@code null} uses the thread context class loader
* @param binding shared binding, or {@code null} to create a new one
* @param configuration compiler configuration, or {@code null} for
* {@link CompilerConfiguration#DEFAULT}
* @since 7.0.0
*/
+ @Incubating
public GroovyEngine(ClassLoader parent, Binding binding, CompilerConfiguration configuration) {
sharedData = binding != null ? binding : new Binding();
compilerConfiguration = configuration != null ? configuration : CompilerConfiguration.DEFAULT;
@@ -284,6 +296,7 @@ public class GroovyEngine implements ScriptEngine {
* @return a shell that uses {@code classLoader} as its loader
* @since 7.0.0
*/
+ @Incubating
protected GroovyShell createShell(ClassLoader classLoader, Binding binding, CompilerConfiguration configuration) {
return new GroovyShell(classLoader, binding, configuration);
}
@@ -294,6 +307,7 @@ public class GroovyEngine implements ScriptEngine {
* @return the engine class loader
* @since 7.0.0
*/
+ @Incubating
public EngineClassLoader getClassLoader() {
return classLoader;
}
@@ -304,6 +318,7 @@ public class GroovyEngine implements ScriptEngine {
* @return the compiler configuration, never {@code null}
* @since 7.0.0
*/
+ @Incubating
public CompilerConfiguration getCompilerConfiguration() {
return compilerConfiguration;
}
@@ -1247,16 +1262,22 @@ public class GroovyEngine implements ScriptEngine {
* @param configuration compiler configuration, or {@code null} for the default
* @since 7.0.0
*/
+ @Incubating
public EngineClassLoader(CompilerConfiguration configuration) {
super(Thread.currentThread().getContextClassLoader(), configuration);
}
/**
- * Constructs an EngineClassLoader with the given parent class loader.
+ * Constructs an EngineClassLoader with the given parent class loader and
+ * {@link CompilerConfiguration#DEFAULT}. Use
+ * {@link #EngineClassLoader(ClassLoader, CompilerConfiguration)} to supply
+ * an engine's configuration, so that the engine adopts this loader rather
+ * than wrapping it.
*
* @param parent the parent class loader
* @since 7.0.0
*/
+ @Incubating
public EngineClassLoader(ClassLoader parent) {
super(parent);
}
@@ -1269,6 +1290,7 @@ public class GroovyEngine implements ScriptEngine {
* @param configuration compiler configuration, or {@code null} for the default
* @since 7.0.0
*/
+ @Incubating
public EngineClassLoader(ClassLoader parent, CompilerConfiguration configuration) {
super(parent, configuration);
}
diff --git a/subprojects/groovy-groovysh/src/spec/doc/groovysh.adoc b/subprojects/groovy-groovysh/src/spec/doc/groovysh.adoc
index 4e851c953f..235e3294cf 100644
--- a/subprojects/groovy-groovysh/src/spec/doc/groovysh.adoc
+++ b/subprojects/groovy-groovysh/src/spec/doc/groovysh.adoc
@@ -1462,7 +1462,11 @@ be prepended as snippets on every evaluation) and
`ASTTransformationCustomizer(ThreadInterrupt)` (so Ctrl+C can stop a
tight loop after `Main` interrupts the execute thread).
+[source,groovy]
+.Compile-time customizers on the engine
+----
include::../test/EmbeddingSpecTest.groovy[tags=embed_engine_config,indent=0]
+----
Subclasses that need a different `GroovyShell` can override
`protected GroovyShell createShell(ClassLoader, Binding, CompilerConfiguration)`.
@@ -1473,7 +1477,11 @@ that are assigned after `super(...)`.
class loader (the field is `protected`; Java callers cannot read it
without a getter).
+[source,groovy]
+.The engine class loader
+----
include::../test/EmbeddingSpecTest.groovy[tags=embed_classloader,indent=0]
+----
==== `GroovyshOptions`
@@ -1481,27 +1489,46 @@ include::../test/EmbeddingSpecTest.groovy[tags=embed_classloader,indent=0]
that does not call `System.exit`. The options object is built with
`GroovyshOptions.builder()` and is incubating in 7.0.
+Where a setting has an equivalent on JLine's `ShellBuilder`, it
+deliberately carries the same name and parameter type, so that a
+future move of groovysh onto `org.jline.shell` does not break this
+API.
+
Recognized hooks:
* `compilerConfiguration` / `engine` — compile-time customizers, or a
pre-built `GroovyEngine`. If both are set, the engine wins.
* `bindings` / `binding(name, value)` — variables installed on the
engine before the REPL starts.
-* `extraCommandRegistry` — additional JLine `CommandRegistry`
- instances, appended after groovysh's own registries.
+* `groups` — additional JLine `CommandGroup` instances
+ (`org.jline.shell`, the undeprecated successor to `CommandRegistry`;
+ groovysh adapts them internally). They are resolved *before*
+ groovysh's own commands, so a group may override a built-in
+ command name.
* `prompt` — `Supplier<String>` invoked on each REPL iteration
(default `{ 'groovy> ' }`).
-* `resultHandler` — how values are rendered (default:
- `console.println(result?.toString())`).
-* `errorHandler` — how execution failures are rendered (default:
- `SystemRegistry.trace`). `UserInterruptException` and
- `EndOfFileException` stay in `Main` as control flow.
+* `resultHandler` — how values are rendered, given the session
+ `Printer` (default: `printer.println(result?.toString())`).
+* `errorHandler` — how execution failures are rendered, given the
+ error and groovysh's own renderer to delegate to (default: the
+ latter). `UserInterruptException` and `EndOfFileException` stay in
+ `Main` as control flow.
* `showBanner` — set `false` to suppress groovysh's banner so the host
can print its own.
+* `rightPrompt` — optional right-hand prompt.
* `terminal` — optional JLine `Terminal`; when omitted, `Main` builds
one from the CLI flags.
+* `historyFile` — where to persist history; when omitted, groovysh's
+ own `groovysh_history`.
+* `onReaderReady` — a `Consumer<LineReader>` called once the reader
+ exists, for settings the builder does not model: the continuation
+ prompt (`SECONDARY_PROMPT_PATTERN`), key bindings, reader options.
-include::../test/EmbeddingSpecTest.groovy[tags=embed_options_help,indent=0]
+[source,groovy]
+.Embedding with `GroovyshOptions`
+----
+include::../test/EmbeddingSpecTest.groovy[tags=embed_options_hooks,indent=0]
+----
`Main.start(Map, String[])` remains the binding-only overload and
delegates to `GroovyshOptions`.
@@ -1510,7 +1537,10 @@ delegates to `GroovyshOptions`.
`/clear`, `/pwd`, `/cd`, `/ls`, `/cat`, `/grep`, `/head`, `/tail`,
`/wc`, `/sort`, `/date`, `/echo` and `/!` live in the public
-`ExtraConsoleCommands` class. `Main` still registers it by default.
+`ExtraConsoleCommands` class. It implements JLine's deprecated
+`org.jline.console.CommandRegistry`, as groovysh's own registries
+still do; prefer `GroovyshOptions.groups` and `org.jline.shell`
+for new embedder commands. `Main` still registers it by default.
Embedders that build their own `SystemRegistry` can construct it
directly. The former `Main.ExtraConsoleCommands` nested class remains
as a deprecated subclass for Groovy callers that compiled against it.
diff --git a/subprojects/groovy-groovysh/src/spec/test/EmbeddingSpecTest.groovy b/subprojects/groovy-groovysh/src/spec/test/EmbeddingSpecTest.groovy
index 28abbe86ee..a986a0d65e 100644
--- a/subprojects/groovy-groovysh/src/spec/test/EmbeddingSpecTest.groovy
+++ b/subprojects/groovy-groovysh/src/spec/test/EmbeddingSpecTest.groovy
@@ -23,8 +23,17 @@ import org.apache.groovy.groovysh.Main
import org.apache.groovy.groovysh.jline.GroovyEngine
import org.codehaus.groovy.control.CompilerConfiguration
import org.codehaus.groovy.control.customizers.ImportCustomizer
+import org.jline.reader.LineReader
+import org.jline.shell.CommandSession
+import org.jline.shell.impl.AbstractCommand
+import org.jline.shell.impl.SimpleCommandGroup
+import org.jline.terminal.Size
+import org.jline.terminal.impl.DumbTerminal
import org.junit.jupiter.api.Test
+import java.nio.charset.StandardCharsets
+import java.nio.file.Path
+
/**
* Executable examples for embedding groovysh. Included from
* {@code groovysh.adoc}.
@@ -45,11 +54,35 @@ class EmbeddingSpecTest {
}
@Test
- void optionsBuilderHelpPath() {
- // tag::embed_options_help[]
- int rc = Main.start(GroovyshOptions.builder().showBanner(false).build(), '--help')
- assert rc == 0
- // end::embed_options_help[]
+ void optionsBuilderHooks() {
+ def terminal = new DumbTerminal('embedded', 'dumb',
+ new ByteArrayInputStream(new byte[0]), new ByteArrayOutputStream(), StandardCharsets.UTF_8)
+ terminal.size = new Size(80, 24)
+ def results = []
+ try {
+ // tag::embed_options_hooks[]
+ int rc = Main.start(GroovyshOptions.builder()
+ .terminal(terminal) // host-supplied terminal
+ .showBanner(false) // the host prints its own
+ .prompt { 'gremlin> ' } // primary prompt
+ .onReaderReady { LineReader reader -> // continuation prompt, key bindings
+ reader.setVariable(LineReader.SECONDARY_PROMPT_PATTERN, '.......> ')
+ }
+ .historyFile(Path.of(System.getProperty('user.home'), '.myapp_history'))
+ .binding('answer', 42) // visible to evaluated code
+ .groups(new SimpleCommandGroup('MyApp', new AbstractCommand('/ping') {
+ @Override
+ Object execute(CommandSession session, String[] args) { 'pong' }
+ }))
+ .resultHandler { printer, result -> results << result } // render values your way
+ .errorHandler { error, defaultTrace -> defaultTrace.accept(error) }
+ .build(), '-e', 'answer')
+ assert rc == 0
+ assert 42 in results
+ // end::embed_options_hooks[]
+ } finally {
+ terminal.close()
+ }
}
@Test
diff --git a/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/ExtraConsoleCommandsTest.groovy b/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/ExtraConsoleCommandsTest.groovy
index ae63d52da6..1a031d3616 100644
--- a/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/ExtraConsoleCommandsTest.groovy
+++ b/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/ExtraConsoleCommandsTest.groovy
@@ -173,10 +173,29 @@ class ExtraConsoleCommandsTest {
}
@Test
- void commandInfoReturnsPosixCommandNames() {
- def info = extra.commandInfo('/pwd')
- assert info instanceof List
- assert !info.isEmpty()
+ void commandInfoDescribesTheCommandItIsAskedAbout() {
+ assert extra.commandInfo('/pwd') == ['print working directory']
+ assert extra.commandInfo('/clear') == ['clear terminal']
+ assert extra.commandInfo('/!') == ['execute shell command']
+ assert extra.commandInfo('/ls') == ['list files']
+ // every command gets its own description rather than a shared list
+ def described = extra.commandNames().collectEntries { [it, extra.commandInfo(it)] }
+ assert described.every { _, info -> info.size() == 1 && info[0] }
+ assert described.values().flatten().toSet().size() == described.size()
+ }
+
+ @Test
+ void commandInfoIsEmptyForAnUnknownCommand() {
+ assert extra.commandInfo('/nope') == []
+ }
+
+ @Test
+ void helpDescribesEachConsoleCommand() {
+ system.execute('/help')
+ def help = terminalOutput()
+ assert help.contains('clear terminal')
+ assert help.contains('print working directory')
+ assert help.contains('list files')
}
@Test
diff --git a/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/GroovyshEmbeddingTest.groovy b/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/GroovyshEmbeddingTest.groovy
index 66d56b5854..7419e95fbc 100644
--- a/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/GroovyshEmbeddingTest.groovy
+++ b/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/GroovyshEmbeddingTest.groovy
@@ -21,10 +21,10 @@ package org.apache.groovy.groovysh
import org.apache.groovy.groovysh.jline.GroovyEngine
import org.codehaus.groovy.control.CompilerConfiguration
import org.codehaus.groovy.control.customizers.ImportCustomizer
-import org.jline.console.CommandInput
-import org.jline.console.CommandMethods
-import org.jline.console.CommandRegistry
-import org.jline.console.impl.JlineCommandRegistry
+import org.jline.reader.LineReader
+import org.jline.shell.CommandSession
+import org.jline.shell.impl.AbstractCommand
+import org.jline.shell.impl.SimpleCommandGroup
import org.jline.terminal.Size
import org.jline.terminal.Terminal
import org.jline.terminal.impl.DumbTerminal
@@ -35,7 +35,6 @@ import org.junit.jupiter.api.io.TempDir
import java.nio.charset.StandardCharsets
import java.nio.file.Path
-import java.util.function.Function
/**
* End-to-end coverage of {@link Main#start(GroovyshOptions, String[])}
@@ -83,7 +82,7 @@ class GroovyshEmbeddingTest {
void resultHandlerSeesEvaluatedValue() {
def results = []
int rc = Main.start(options()
- .resultHandler { c, r -> results << r }
+ .resultHandler { p, r -> results << r }
.build(), '-e', '2 + 3')
assert rc == 0
assert 5 in results
@@ -94,7 +93,7 @@ class GroovyshEmbeddingTest {
def results = []
int rc = Main.start(options()
.binding('answer', 42)
- .resultHandler { c, r -> results << r }
+ .resultHandler { p, r -> results << r }
.build(), '-e', 'answer')
assert rc == 0
assert 42 in results
@@ -109,7 +108,7 @@ class GroovyshEmbeddingTest {
def results = []
int rc = Main.start(options()
.compilerConfiguration(config)
- .resultHandler { c, r -> results << r }
+ .resultHandler { p, r -> results << r }
.build(), '-e', 'new AtomicInteger(9).get()')
assert rc == 0
assert 9 in results
@@ -123,29 +122,80 @@ class GroovyshEmbeddingTest {
int rc = Main.start(options()
.engine(engine)
.compilerConfiguration(new CompilerConfiguration())
- .resultHandler { c, r -> results << r }
+ .resultHandler { p, r -> results << r }
.build(), '-e', 'marker')
assert rc == 0
assert 'from-engine' in results
}
@Test
- void extraCommandRegistryIsInvoked() {
- def ping = new PingRegistry()
+ void commandGroupIsInvoked() {
+ def hits = []
int rc = Main.start(options()
- .extraCommandRegistry(ping)
- .resultHandler { c, r -> }
+ .groups(group('/ping', hits))
+ .resultHandler { p, r -> }
.build(), '-e', '/ping')
assert rc == 0
- assert ping.hits == ['ping']
+ assert hits == ['/ping']
+ }
+
+ @Test
+ void aCommandGroupCanOverrideABuiltIn() {
+ def hits = []
+ int rc = Main.start(options()
+ .groups(group('/imports', hits))
+ .resultHandler { p, r -> }
+ .build(), '-e', '/imports')
+ assert rc == 0
+ assert hits == ['/imports'] // groovysh's own /imports did not run
+ }
+
+ @Test
+ void historyFileIsHonoured() {
+ // JLine only writes the file once a line is actually read, and -e short-circuits
+ // readLine, so assert the reader was configured with the embedder's path
+ def history = tempHome.resolve('embedder_history')
+ def configured = null
+ int rc = Main.start(options()
+ .historyFile(history)
+ .onReaderReady { LineReader r -> configured = r.getVariable(LineReader.HISTORY_FILE) }
+ .resultHandler { p, r -> }
+ .build(), '-e', '1 + 1')
+ assert rc == 0
+ assert configured == history
+ }
+
+ @Test
+ void historyFileDefaultsToGroovyshWhenUnset() {
+ def configured = null
+ int rc = Main.start(options()
+ .onReaderReady { LineReader r -> configured = r.getVariable(LineReader.HISTORY_FILE) }
+ .resultHandler { p, r -> }
+ .build(), '-e', '1 + 1')
+ assert rc == 0
+ assert (configured as Path).fileName.toString() == 'groovysh_history'
+ }
+
+ @Test
+ void onReaderReadyCanSetTheSecondaryPrompt() {
+ def seen = null
+ int rc = Main.start(options()
+ .onReaderReady { LineReader r ->
+ r.setVariable(LineReader.SECONDARY_PROMPT_PATTERN, 'gremlin...> ')
+ seen = r.getVariable(LineReader.SECONDARY_PROMPT_PATTERN)
+ }
+ .resultHandler { p, r -> }
+ .build(), '-e', '1')
+ assert rc == 0
+ assert seen == 'gremlin...> '
}
@Test
void errorHandlerReceivesThrownFailures() {
def errors = []
int rc = Main.start(options()
- .resultHandler { c, r -> }
- .errorHandler { r, t -> errors << t }
+ .resultHandler { p, r -> }
+ .errorHandler { t, trace -> errors << t }
.build(), '-e', 'throw new RuntimeException("boom")')
assert rc == 0
assert errors.any { containsMessage(it, 'boom') }
@@ -154,7 +204,7 @@ class GroovyshEmbeddingTest {
@Test
void bannerCanBeSuppressed() {
def captured = captureStdout {
- Main.start(options().resultHandler { c, r -> }.build(), '-e', '1')
+ Main.start(options().resultHandler { p, r -> }.build(), '-e', '1')
}
assert !captured.contains('Groovy Shell')
}
@@ -164,7 +214,7 @@ class GroovyshEmbeddingTest {
def captured = captureStdout {
Main.start(options()
.showBanner(true)
- .resultHandler { c, r -> }
+ .resultHandler { p, r -> }
.build(), '-e', '1')
}
assert captured.contains('Groovy Shell')
@@ -175,7 +225,7 @@ class GroovyshEmbeddingTest {
def captured = captureStdout {
Main.start(options()
.showBanner(true)
- .resultHandler { c, r -> }
+ .resultHandler { p, r -> }
.build(), '-q', '-e', '1')
}
assert captured.contains(GroovySystem.version)
@@ -197,7 +247,7 @@ class GroovyshEmbeddingTest {
prompts << 'gremlin> '
'gremlin> '
}
- .resultHandler { c, r -> }
+ .resultHandler { p, r -> }
.build())
assert rc == 0
assert prompts.contains('gremlin> ')
@@ -240,27 +290,16 @@ class GroovyshEmbeddingTest {
false
}
- private static class PingRegistry extends JlineCommandRegistry implements CommandRegistry {
- final List<String> hits = []
-
- PingRegistry() {
- registerCommands([
- '/ping': new CommandMethods((Function) this::ping, this::defaultCompleter)
- ])
- }
-
- @Override
- String name() {
- 'Ping'
- }
+ private static SimpleCommandGroup group(String name, List<String> hits) {
+ new SimpleCommandGroup('Embedder', new AbstractCommand(name) {
+ @Override
+ String description() { 'a command contributed by the embedder' }
- @Override
- List<String> commandInfo(String command) {
- ['ping the extra registry']
- }
-
- private void ping(CommandInput input) {
- hits << 'ping'
- }
+ @Override
+ Object execute(CommandSession session, String[] args) {
+ hits << name
+ null
+ }
+ })
}
}
diff --git a/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/GroovyshOptionsTest.groovy b/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/GroovyshOptionsTest.groovy
index 806a033012..2ea3a6c946 100644
--- a/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/GroovyshOptionsTest.groovy
+++ b/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/GroovyshOptionsTest.groovy
@@ -20,12 +20,15 @@ package org.apache.groovy.groovysh
import org.apache.groovy.groovysh.jline.GroovyEngine
import org.codehaus.groovy.control.CompilerConfiguration
-import org.jline.console.CommandRegistry
-import org.jline.console.impl.JlineCommandRegistry
+import org.jline.shell.CommandGroup
+import org.jline.shell.CommandSession
+import org.jline.shell.impl.AbstractCommand
+import org.jline.shell.impl.SimpleCommandGroup
import org.jline.terminal.impl.DumbTerminal
import org.junit.jupiter.api.Test
import java.nio.charset.StandardCharsets
+import java.nio.file.Path
import static groovy.test.GroovyAssert.shouldFail
@@ -42,8 +45,11 @@ class GroovyshOptionsTest {
assert options.compilerConfiguration == null
assert options.engine == null
assert options.bindings.isEmpty()
- assert options.extraCommandRegistries.isEmpty()
+ assert options.groups.isEmpty()
assert options.prompt == null
+ assert options.rightPrompt == null
+ assert options.historyFile == null
+ assert options.onReaderReady == null
assert options.resultHandler == null
assert options.errorHandler == null
assert options.showBanner
@@ -78,28 +84,26 @@ class GroovyshOptionsTest {
}
@Test
- void extraRegistriesAppend() {
- def first = new DummyRegistry('first')
- def second = new DummyRegistry('second')
+ void groupsAppend() {
+ def first = group('first')
+ def second = group('second')
def options = GroovyshOptions.builder()
- .extraCommandRegistry(first)
- .extraCommandRegistries([second])
+ .groups(first)
+ .groups([second])
.build()
- assert options.extraCommandRegistries == [first, second]
+ assert options.groups == [first, second]
}
@Test
- void extraCommandRegistriesNullIsIgnored() {
- def options = GroovyshOptions.builder()
- .extraCommandRegistries(null)
- .build()
- assert options.extraCommandRegistries.isEmpty()
+ void groupsNullIsIgnored() {
+ assert GroovyshOptions.builder().groups((Iterable) null).build().groups.isEmpty()
+ assert GroovyshOptions.builder().groups((CommandGroup[]) null).build().groups.isEmpty()
}
@Test
- void extraCommandRegistryRejectsNull() {
+ void groupsRejectNullEntries() {
shouldFail(NullPointerException) {
- GroovyshOptions.builder().extraCommandRegistry(null)
+ GroovyshOptions.builder().groups([null])
}
}
@@ -114,13 +118,13 @@ class GroovyshOptionsTest {
void mapsAndListsAreUnmodifiable() {
def options = GroovyshOptions.builder()
.binding('a', 1)
- .extraCommandRegistry(new DummyRegistry('d'))
+ .groups(group('d'))
.build()
shouldFail(UnsupportedOperationException) {
options.bindings.put('b', 2)
}
shouldFail(UnsupportedOperationException) {
- options.extraCommandRegistries.add(new DummyRegistry('x'))
+ options.groups.add(group('x'))
}
}
@@ -129,8 +133,8 @@ class GroovyshOptionsTest {
def config = new CompilerConfiguration()
def engine = new GroovyEngine()
def prompt = { 'gremlin> ' }
- GroovyshOptions.ResultHandler results = { c, r -> }
- GroovyshOptions.ErrorHandler errors = { r, t -> }
+ GroovyshOptions.ResultHandler results = { p, r -> }
+ GroovyshOptions.ErrorHandler errors = { t, trace -> }
def terminal = new DumbTerminal(
'groovysh-test', 'dumb',
new ByteArrayInputStream(new byte[0]),
@@ -141,6 +145,8 @@ class GroovyshOptionsTest {
.compilerConfiguration(config)
.engine(engine)
.prompt(prompt)
+ .rightPrompt('[rp]')
+ .historyFile(Path.of('history.txt'))
.resultHandler(results)
.errorHandler(errors)
.showBanner(false)
@@ -149,6 +155,8 @@ class GroovyshOptionsTest {
assert options.compilerConfiguration.is(config)
assert options.engine.is(engine)
assert options.prompt.get() == 'gremlin> '
+ assert options.rightPrompt.get() == '[rp]'
+ assert options.historyFile.fileName.toString() == 'history.txt'
assert options.resultHandler.is(results)
assert options.errorHandler.is(errors)
assert !options.showBanner
@@ -158,16 +166,10 @@ class GroovyshOptionsTest {
}
}
- private static class DummyRegistry extends JlineCommandRegistry implements CommandRegistry {
- private final String group
-
- DummyRegistry(String group) {
- this.group = group
- }
-
- @Override
- String name() {
- group
- }
+ private static CommandGroup group(String name) {
+ new SimpleCommandGroup(name, new AbstractCommand("/${name}") {
+ @Override
+ Object execute(CommandSession session, String[] args) { null }
+ })
}
}
diff --git a/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/jline/GroovyEngineTest.groovy b/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/jline/GroovyEngineTest.groovy
index 4ebf153bc3..39503e41ff 100644
--- a/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/jline/GroovyEngineTest.groovy
+++ b/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/jline/GroovyEngineTest.groovy
@@ -18,9 +18,6 @@
*/
package org.apache.groovy.groovysh.jline
-import groovy.lang.Binding
-import groovy.lang.GroovyClassLoader
-import groovy.lang.GroovyShell
import groovy.transform.ThreadInterrupt
import org.codehaus.groovy.control.CompilerConfiguration
import org.codehaus.groovy.control.customizers.ASTTransformationCustomizer
@@ -274,9 +271,11 @@ class GroovyEngineTest {
def thrown = new AtomicReference<Throwable>()
def started = new CountDownLatch(1)
engine.put('started', started)
- def thread = Thread.start {
+ // daemon, and bounded: if the interrupt is ever missed the loop must still end
+ // rather than spin a core for the rest of the forked JVM's life
+ def thread = Thread.startDaemon {
try {
- engine.execute('started.countDown(); def n = 0; while (true) { n++ }')
+ engine.execute('started.countDown(); def n = 0L; while (n < 100_000_000_000L) { n++ }')
} catch (Throwable t) {
thrown.set(t)
}