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 06:26:58 UTC

(groovy) 04/04: GROOVY-12403: let an embedder contribute completion

This is an automated email from the ASF dual-hosted git repository.

paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git

commit a24cdf7796b2c72a0953ff9f1ce07438a82af242
Author: Paul King <pa...@asert.com.au>
AuthorDate: Mon Sep 14 14:20:08 2026 +1000

    GROOVY-12403: let an embedder contribute completion
    
    groups(CommandGroup) already carries per-command completers into the
    registry, but the slot SystemRegistryImpl.completer() reserves for
    whole-line completion - what addCompleter feeds, and where groovysh
    puts its own identifier and import completer - had no hook. A host
    console could complete the arguments of its own commands but not its
    domain language.
    
    onReaderReady gains the BiConsumer<LineReader, GroovySystemRegistry>
    overload JLine's ShellBuilder uses for the same purpose, and now fires
    once the reader and the registry are both wired rather than straight
    after the reader is built. Firing late is what makes completion
    reachable, since Main assigns reader.completer from the registry, and
    it matches ShellBuilder, which holds a single BiConsumer and calls it
    last. The Consumer overload wraps into it, as ShellBuilder's does.
    
    An embedder supplements groovysh's completion with
    
        reader.completer = new AggregateCompleter(registry.completer(), mine)
    
    or replaces it by assigning its own. Nothing between the reader being
    built and the callback now needs the embedder's reader settings, so
    moving the callback later costs nothing.
---
 .../apache/groovy/groovysh/GroovyshOptions.java    | 42 +++++++++++++++++-----
 .../groovy/org/apache/groovy/groovysh/Main.groovy  |  4 ++-
 .../groovy-groovysh/src/spec/doc/groovysh.adoc     | 22 ++++++++++--
 .../groovy/groovysh/GroovyshEmbeddingTest.groovy   | 40 +++++++++++++++++++++
 4 files changed, 96 insertions(+), 12 deletions(-)

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 37122ef5a0..aa472321a5 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
@@ -19,6 +19,7 @@
 package org.apache.groovy.groovysh;
 
 import org.apache.groovy.groovysh.jline.GroovyEngine;
+import org.apache.groovy.groovysh.jline.GroovySystemRegistry;
 import org.apache.groovy.lang.annotation.Incubating;
 import org.codehaus.groovy.control.CompilerConfiguration;
 import org.jline.console.Printer;
@@ -34,6 +35,7 @@ import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
+import java.util.function.BiConsumer;
 import java.util.function.Consumer;
 import java.util.function.Supplier;
 
@@ -101,7 +103,7 @@ public final class GroovyshOptions {
     private final boolean showBanner;
     private final Terminal terminal;
     private final Path historyFile;
-    private final Consumer<LineReader> onReaderReady;
+    private final BiConsumer<LineReader, GroovySystemRegistry> onReaderReady;
 
     private GroovyshOptions(Builder builder) {
         this.compilerConfiguration = builder.compilerConfiguration;
@@ -232,13 +234,14 @@ public final class GroovyshOptions {
     }
 
     /**
-     * Callback invoked once the {@link LineReader} has been built, for settings
-     * this class does not model — the secondary prompt pattern, key bindings,
-     * reader options.
+     * Callback invoked once the reader and the command registry are both wired,
+     * immediately before the REPL starts, for settings this class does not
+     * model — the secondary prompt pattern, key bindings, reader options, and
+     * the completer.
      *
      * @return the callback, or {@code null}
      */
-    public Consumer<LineReader> getOnReaderReady() {
+    public BiConsumer<LineReader, GroovySystemRegistry> getOnReaderReady() {
         return onReaderReady;
     }
 
@@ -260,7 +263,7 @@ public final class GroovyshOptions {
         private boolean showBanner = true;
         private Terminal terminal;
         private Path historyFile;
-        private Consumer<LineReader> onReaderReady;
+        private BiConsumer<LineReader, GroovySystemRegistry> onReaderReady;
 
         private Builder() {
         }
@@ -451,13 +454,36 @@ public final class GroovyshOptions {
         }
 
         /**
-         * Registers a callback invoked once the {@link LineReader} is built.
-         * Mirrors {@code ShellBuilder.onReaderReady(Consumer)}.
+         * Registers a callback invoked once the reader is wired, immediately
+         * before the REPL starts. 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 == null ? null
+                    : (reader, registry) -> onReaderReady.accept(reader);
+            return this;
+        }
+
+        /**
+         * Registers a callback invoked once the reader and the command registry
+         * are both wired, immediately before the REPL starts. Mirrors
+         * {@code ShellBuilder.onReaderReady(BiConsumer)}.
+         * <p>
+         * This is the hook for completion. groovysh has already assigned
+         * {@code reader.setCompleter(registry.completer())} by the time the
+         * callback runs, so an embedder contributing its own completion wraps
+         * that, for example
+         * {@code reader.setCompleter(new AggregateCompleter(registry.completer(), mine))}.
+         * Candidates from an {@code AggregateCompleter} are merged, so a
+         * completer added this way supplements groovysh's rather than replacing
+         * it; assign a completer of your own to replace it outright.
+         *
+         * @param onReaderReady the callback, or {@code null} for none
+         * @return this builder
+         */
+        public Builder onReaderReady(BiConsumer<LineReader, GroovySystemRegistry> onReaderReady) {
             this.onReaderReady = onReaderReady;
             return this;
         }
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 8300dc6f77..cc2836b06e 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
@@ -347,7 +347,6 @@ 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
@@ -397,6 +396,9 @@ class Main {
             KeyMap<Binding> keyMap = reader.keyMaps.get("main")
             keyMap.bind(new Reference(Widgets.TAILTIP_TOGGLE), KeyMap.alt("s"))
             keyMap.bind(new Reference(Widgets.AUTOSUGGEST_TOGGLE), KeyMap.alt("v"))
+            // last, so an embedder sees the reader fully wired — completer included
+            groovyshOptions.onReaderReady?.accept(reader, systemRegistry)
+
             def init = configPath.getUserConfig('groovysh_init.groovy')
             if (init) {
                 systemRegistry.initialize(init.toFile())
diff --git a/subprojects/groovy-groovysh/src/spec/doc/groovysh.adoc b/subprojects/groovy-groovysh/src/spec/doc/groovysh.adoc
index 235e3294cf..51085b77a0 100644
--- a/subprojects/groovy-groovysh/src/spec/doc/groovysh.adoc
+++ b/subprojects/groovy-groovysh/src/spec/doc/groovysh.adoc
@@ -1520,9 +1520,25 @@ Recognized hooks:
   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.
+* `onReaderReady` — called once the reader and the command registry
+  are both wired, immediately before the REPL starts, for settings the
+  builder does not model: the continuation prompt
+  (`SECONDARY_PROMPT_PATTERN`), key bindings, reader options, and
+  completion. Takes a `Consumer<LineReader>`, or a
+  `BiConsumer<LineReader, GroovySystemRegistry>` when the registry is
+  needed too. groovysh has already assigned
+  `reader.completer = registry.completer()` by then, so an embedder
+  contributing domain completion wraps it:
++
+[source,groovy]
+----
+reader.completer = new AggregateCompleter(registry.completer(), myCompleter)
+----
++
+`AggregateCompleter` merges candidates, so a completer added that way
+supplements groovysh's rather than replacing it. Assigning a completer
+of your own replaces it outright. Per-command completion needs none of
+this — it comes from `Command.completer()` on a contributed `group`.
 
 [source,groovy]
 .Embedding with `GroovyshOptions`
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 7419e95fbc..1745eff57c 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,7 +21,11 @@ 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.reader.Candidate
 import org.jline.reader.LineReader
+import org.jline.reader.Parser
+import org.jline.reader.impl.completer.AggregateCompleter
+import org.jline.reader.impl.completer.StringsCompleter
 import org.jline.shell.CommandSession
 import org.jline.shell.impl.AbstractCommand
 import org.jline.shell.impl.SimpleCommandGroup
@@ -253,6 +257,42 @@ class GroovyshEmbeddingTest {
         assert prompts.contains('gremlin> ')
     }
 
+    @Test
+    void onReaderReadyCanContributeAGlobalCompleter() {
+        LineReader captured = null
+        int rc = Main.start(options()
+            .onReaderReady { LineReader reader, registry ->
+                captured = reader
+                // groovysh has already assigned its own completer; supplement it
+                reader.completer = new AggregateCompleter(registry.completer(),
+                    new StringsCompleter('gremlinStep'))
+            }
+            .resultHandler { p, r -> }
+            .build(), '-e', '1')
+        assert rc == 0
+        assert captured != null
+
+        def candidates = new ArrayList<Candidate>()
+        def line = captured.parser.parse('gremlinSt', 'gremlinSt'.length(), Parser.ParseContext.COMPLETE)
+        captured.completer.complete(captured, line, candidates)
+        assert candidates*.value().contains('gremlinStep')
+    }
+
+    @Test
+    void onReaderReadyRunsAfterTheRegistryIsWired() {
+        def order = []
+        int rc = Main.start(options()
+            .groups(group('/ping', []))
+            .onReaderReady { LineReader reader, registry ->
+                order << (registry.hasCommand('/ping') ? 'registry-ready' : 'registry-incomplete')
+                order << (reader.completer != null ? 'completer-set' : 'completer-missing')
+            }
+            .resultHandler { p, r -> }
+            .build(), '-e', '1')
+        assert rc == 0
+        assert order == ['registry-ready', 'completer-set']
+    }
+
     @Test
     void startRejectsNullOptions() {
         def thrown = false