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/04 01:40:55 UTC

(groovy) branch master updated (41e2879c7b -> ab0b10afa8)

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

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


    from 41e2879c7b groovysh: record how far each vendored fork has been carried forward
     new 4edf93569b GROOVY-12349: groovysh: take JLine's echo instead of carrying our own
     new 8c4a687083 GROOVY-12349: groovysh: guard /grep's regex matching against backtracking
     new 011ab4e40a GROOVY-12349: groovysh: resolve glob matches against the shell's directory
     new e20c082d0f GROOVY-12349: groovysh: pad wc counts only when there are several
     new ab0b10afa8 GROOVY-12349: groovysh: hold only what tail is going to print

The 5 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 subprojects/groovy-groovysh/ARCHITECTURE.md        |  12 +-
 subprojects/groovy-groovysh/build.gradle           |   4 +
 .../groovy/org/apache/groovy/groovysh/Main.groovy  |  15 +--
 .../groovy/groovysh/jline/GroovyPosixCommands.java |  98 ++++++++------
 .../groovysh/jline/GroovyPosixCommandsTest.groovy  | 144 +++++++++++++++++++++
 5 files changed, 219 insertions(+), 54 deletions(-)


(groovy) 03/05: GROOVY-12349: groovysh: resolve glob matches against the shell's directory

Posted by pa...@apache.org.
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 011ab4e40afaf91097220a7773b2819fd7f16c3e
Author: Paul King <pa...@asert.com.au>
AuthorDate: Fri Sep 4 10:25:41 2026 +1000

    GROOVY-12349: groovysh: resolve glob matches against the shell's directory
    
    Glob expansion asks Ant's DirectoryScanner for matches, which reports them
    relative to the base directory it was given. That base is the shell's
    working directory, but the results were turned into paths without being
    resolved against it, so they were read relative to the JVM's directory
    instead. The two agree only until the first /cd, after which every glob
    fails:
    
        groovy> /cd globtest
        groovy> /ls *.txt
        RuntimeException: java.nio.file.NoSuchFileException: top.txt
    
    Both the file and directory results are now resolved against the shell's
    directory.
    
    The path had no tests, which is how this survived. Ant stays out of the
    module's dependencies, since expansion falls back when it is absent and
    the distribution supplies it, but it is now a testRuntimeOnly dependency
    so the scanner path is exercised — as groovy-test already does. That
    matters more than it sounds: without it even a plain *.txt test passes
    through the fallback and never reaches the code at fault.
    
    Found while assessing JLine c0fdc697, which reworks the same area
    upstream. That fix is not ported: it teaches the built-in matcher POSIX **
    semantics and directory prefixes, which Ant already handles, so with Ant
    present our expansion is the more capable of the two. Without Ant the
    fallback matches names within a single directory, so a pattern spanning
    directories quietly finds nothing; porting it would close that gap.
    
    Unrelated but worth knowing: an unquoted /ls **/*.txt never reaches the
    command, because the line contains /* and the shell reads it as an
    unterminated block comment. Quoting the pattern avoids it.
---
 subprojects/groovy-groovysh/build.gradle           |  4 +++
 .../groovy/groovysh/jline/GroovyPosixCommands.java |  6 ++--
 .../groovysh/jline/GroovyPosixCommandsTest.groovy  | 32 ++++++++++++++++++++++
 3 files changed, 40 insertions(+), 2 deletions(-)

diff --git a/subprojects/groovy-groovysh/build.gradle b/subprojects/groovy-groovysh/build.gradle
index 441e5f94e6..7abbc203d1 100644
--- a/subprojects/groovy-groovysh/build.gradle
+++ b/subprojects/groovy-groovysh/build.gradle
@@ -37,6 +37,10 @@ dependencies {
     testImplementation projects.groovyCsv         // for /slurp .csv default coverage
     testImplementation projects.groovyMarkdown    // for /slurp .md default coverage
     testImplementation projects.groovyTestJunit6  // for @ForkedJvm in CSV fallback tests
+    // glob expansion uses Ant's DirectoryScanner when it is on the classpath, which the
+    // distribution supplies but this module deliberately does not depend on; supply it to
+    // the tests so that path is exercised rather than skipped
+    testRuntimeOnly "org.apache.ant:ant:${versions.ant}"
     implementation "net.java.dev.jna:jna:${versions.jna}"
     implementation "org.jline:jansi:${versions.jline}"
     implementation "org.jline:jline-builtins:${versions.jline}"
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommands.java b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommands.java
index b69683d13b..dfdb49fe4e 100644
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommands.java
+++ b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommands.java
@@ -1309,14 +1309,16 @@ public class GroovyPosixCommands {
             String[] includedFiles = (String[]) getIncludedFilesMethod.invoke(scanner);
 
             for (String file : includedFiles) {
-                result.add(Path.of(file));
+                // the scanner reports matches relative to its base directory, which is the
+                // shell's working directory and not necessarily the JVM's
+                result.add(context.currentDir().resolve(file));
             }
 
             Method getIncludedDirsMethod = directoryScannerClass.getMethod("getIncludedDirectories");
             String[] includedDirs = (String[]) getIncludedDirsMethod.invoke(scanner);
 
             for (String dir : includedDirs) {
-                result.add(Path.of(dir));
+                result.add(context.currentDir().resolve(dir));
             }
             return result;
         } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InstantiationException |
diff --git a/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommandsTest.groovy b/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommandsTest.groovy
index acf1d8dbb9..bb0fd3adc3 100644
--- a/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommandsTest.groovy
+++ b/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommandsTest.groovy
@@ -149,6 +149,38 @@ class GroovyPosixCommandsTest {
         assert plainStdout().readLines() == ['gamma']
     }
 
+    // GROOVY-12349: the directory scanner reports matches relative to its base directory,
+    // which is the shell's working directory rather than the JVM's. Leaving them relative
+    // made every glob fail once the two differed, which is to say after any /cd. The
+    // context here uses tempDir, so these exercise exactly that difference.
+    @Test
+    void globResolvesAgainstTheShellWorkingDirectory() {
+        Files.writeString(tempDir.resolve('top.txt'), 'x\n')
+        GroovyPosixCommands.ls(context(), ['ls', '*.txt'] as Object[])
+        assert plainStdout().contains('top.txt')
+    }
+
+    @Test
+    void globMatchesAcrossNestedDirectories() {
+        Files.createDirectories(tempDir.resolve('a/b'))
+        Files.writeString(tempDir.resolve('top.txt'), 'x\n')
+        Files.writeString(tempDir.resolve('a/mid.txt'), 'x\n')
+        Files.writeString(tempDir.resolve('a/b/deep.txt'), 'x\n')
+        GroovyPosixCommands.ls(context(), ['ls', '**/*.txt'] as Object[])
+        String shown = plainStdout()
+        assert shown.contains('deep.txt') && shown.contains('mid.txt') && shown.contains('top.txt')
+    }
+
+    @Test
+    void globWithADirectoryPrefixMatchesOnlyThere() {
+        Files.createDirectories(tempDir.resolve('a'))
+        Files.writeString(tempDir.resolve('top.txt'), 'x\n')
+        Files.writeString(tempDir.resolve('a/mid.txt'), 'x\n')
+        GroovyPosixCommands.ls(context(), ['ls', 'a/*.txt'] as Object[])
+        String shown = plainStdout()
+        assert shown.contains('mid.txt') && !shown.contains('top.txt')
+    }
+
     // GROOVY-12341
     @Test
     void lsStripsControlCharactersFromFileNames() {


(groovy) 01/05: GROOVY-12349: groovysh: take JLine's echo instead of carrying our own

Posted by pa...@apache.org.
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 4edf93569b0403add216eb61642d0c6f6eeeb0ad
Author: Paul King <pa...@asert.com.au>
AuthorDate: Fri Sep 4 09:38:34 2026 +1000

    GROOVY-12349: groovysh: take JLine's echo instead of carrying our own
    
    /echo was a local implementation that joined its arguments with spaces
    and printed them. JLine's builtin does the same and also honours -n and
    backslash escape sequences, and upstream has since fixed how it treats a
    backslash before an unrecognised escape (jline#1901), which we would
    otherwise have had to port.
    
    /pwd, /cd and /date already delegate to org.jline.builtins.PosixCommands
    through the posix() helper, so /echo now does the same and the local
    implementation goes. adjustUsage rewrites the scraped usage from echo to
    /echo as it does for the others, and the registry gains the /echo alias.
    
    This is not the vendored fork: GroovyPosixCommands backs /ls, /wc,
    /sort, /head, /tail, /cat and /grep, and echo is not among them, so
    there is nothing to keep in sync here — the command now follows the
    dependency.
    
    Behaviour changes for anyone relying on the old command: escape
    sequences in an argument are now interpreted rather than printed
    literally, -n suppresses the trailing newline, and /echo with no
    arguments prints an empty line rather than nothing.
    
    Tests pin the three semantics the delegation now advertises, so a JLine
    bump that changed them would fail rather than pass silently.
---
 .../groovy/org/apache/groovy/groovysh/Main.groovy  | 15 ++-------------
 .../groovysh/jline/GroovyPosixCommandsTest.groovy  | 22 ++++++++++++++++++++++
 2 files changed, 24 insertions(+), 13 deletions(-)

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 9096431190..1a630d2f1d 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
@@ -145,6 +145,7 @@ class Main {
             posix.register('/cd', PosixCommands::cd)
             posix.register('/pwd', PosixCommands::pwd)
             posix.register('/date', PosixCommands::date)
+            posix.register('/echo', PosixCommands::echo)
             registerCommands(cmds)
         }
 
@@ -253,19 +254,7 @@ class Main {
         }
 
         private void echo(CommandInput input) {
-            final String[] usage = [
-                "/echo - echos a value",
-                "Usage:  /echo [-h] <args>",
-                "  -? --help                        Displays command help",
-            ]
-            try {
-                Options opt = parseOptions(usage, input.args())
-                if (!opt.args().isEmpty()) {
-                    terminal().writer().println(String.join(" ", opt.args()))
-                }
-            } catch (Exception e) {
-                saveException(e)
-            }
+            posix(adjustUsage('echo', '/echo'), input)
         }
 
         private static void executeCommand(List<String> args) throws Exception {
diff --git a/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommandsTest.groovy b/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommandsTest.groovy
index 6a91f2065c..1a348d89bb 100644
--- a/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommandsTest.groovy
+++ b/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommandsTest.groovy
@@ -18,6 +18,7 @@
  */
 package org.apache.groovy.groovysh.jline
 
+import org.jline.builtins.PosixCommands
 import org.jline.terminal.Terminal
 import org.jline.terminal.TerminalBuilder
 import org.junit.jupiter.api.AfterEach
@@ -93,6 +94,27 @@ class GroovyPosixCommandsTest {
      */
     private static final String NEUTRALISED_NAME = 'ok[2Ktrap.txt'
 
+    // GROOVY-12349: /echo delegates to JLine's PosixCommands.echo instead of the local
+    // implementation it used to carry, so these pin the semantics that delegation now
+    // advertises — and would fail if a bump changed them under us.
+    @Test
+    void echoInterpretsEscapeSequences() {
+        PosixCommands.echo(context(), ['echo', 'tab\\there'] as Object[])
+        assert stdout() == "tab\there\n"
+    }
+
+    @Test
+    void echoSuppressesTrailingNewlineForMinusN() {
+        PosixCommands.echo(context(), ['echo', '-n', 'no-newline'] as Object[])
+        assert stdout() == 'no-newline'
+    }
+
+    @Test
+    void echoJoinsArgumentsWithSingleSpaces() {
+        PosixCommands.echo(context(), ['echo', 'hello', 'world'] as Object[])
+        assert stdout() == 'hello world\n'
+    }
+
     // GROOVY-12341
     @Test
     void lsStripsControlCharactersFromFileNames() {


(groovy) 02/05: GROOVY-12349: groovysh: guard /grep's regex matching against backtracking

Posted by pa...@apache.org.
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 8c4a687083babd105464d2d55b34f2cd1f22e6d3
Author: Paul King <pa...@asert.com.au>
AuthorDate: Fri Sep 4 09:59:50 2026 +1000

    GROOVY-12349: groovysh: guard /grep's regex matching against backtracking
    
    Ported from JLine 1d5fc309, which our fork of PosixCommands predates. The
    upstream commit cites GHSA-r2xf-8xr9-62gw, GHSA-2v9w-34q6-wpqx,
    GHSA-ph9c-7hw9-vhhw and GHSA-5q95-hrpc-m3w3, and the fork carried the
    shape those describe.
    
    grep built its pattern as ".*" + pattern + ".*" and matched that against
    the whole line. Both halves of that are wrong: the intent is to find the
    pattern in the line, which find() says directly, and the wrapping gives a
    backtracking engine more to explore for no gain. The wrapping goes, -x
    keeps the anchored form and matches(), and everything else finds.
    
    Both matchers now run through SafeRegex, which wraps the input in a
    CharSequence that checks a deadline as the engine reads it, so a pattern
    that would otherwise run away gives up after 1.5s. The highlighting
    matcher catches the timeout and emits the rest of the line unhighlighted,
    as upstream does, rather than losing the line. SafeRegex comes from
    jline-terminal, which groovysh already depends on directly, so this takes
    upstream's implementation rather than adding our own.
    
    Tests pin the two matching paths that separate here, find() and the
    anchored matches(), and invert alongside them. They read output with the
    SGR sequences stripped rather than with colouring off, so the highlighting
    path, which is the one holding the new try/catch, stays covered.
    
    Not demonstrated: a pattern that actually trips the deadline. Several
    classic catastrophic patterns, including (a+)+b and (a|aa)+$, complete
    immediately on JDK 17 whether wrapped or not, so the guard is defensive
    here rather than shown to fire.
---
 .../groovy/groovysh/jline/GroovyPosixCommands.java | 29 ++++++++++--------
 .../groovysh/jline/GroovyPosixCommandsTest.groovy  | 34 ++++++++++++++++++++++
 2 files changed, 51 insertions(+), 12 deletions(-)

diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommands.java b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommands.java
index 1b5ba82ad8..b69683d13b 100644
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommands.java
+++ b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommands.java
@@ -36,6 +36,8 @@ import org.jline.utils.AttributedString;
 import org.jline.utils.AttributedStringBuilder;
 import org.jline.utils.InputStreamReader;
 import org.jline.utils.OSUtils;
+import org.jline.utils.RegexTimeoutException;
+import org.jline.utils.SafeRegex;
 
 import static org.jline.builtins.PosixCommands.*;
 
@@ -826,10 +828,9 @@ public class GroovyPosixCommands {
         if (opt.isSet("word-regexp")) {
             regexp = "\\b" + regexp + "\\b";
         }
-        if (opt.isSet("line-regexp")) {
+        boolean lineRegexp = opt.isSet("line-regexp");
+        if (lineRegexp) {
             regexp = "^" + regexp + "$";
-        } else {
-            regexp = ".*" + regexp + ".*";
         }
         Pattern p;
         Pattern p2;
@@ -886,7 +887,7 @@ public class GroovyPosixCommands {
                     int lineno = 1;
                     int lineMatch = 0;
                     while ((line = r.readLine()) != null) {
-                        boolean matches = p.matcher(line).matches();
+                        boolean matches = lineRegexp ? SafeRegex.matches(p, line) : SafeRegex.find(p, line);
                         if (invert) {
                             matches = !matches;
                         }
@@ -915,15 +916,19 @@ public class GroovyPosixCommands {
                                     sbl.append(":");
                                 }
                                 if (colored) {
-                                    Matcher matcher2 = p2.matcher(line);
+                                    Matcher matcher2 = SafeRegex.matcher(p2, line);
                                     int cur = 0;
-                                    while (matcher2.find()) {
-                                        applyStyle(sbl, colors, "se");
-                                        sbl.append(line, cur, matcher2.start());
-                                        applyStyle(sbl, colors, "ms");
-                                        sbl.append(line, matcher2.start(), matcher2.end());
-                                        applyStyle(sbl, colors, "se");
-                                        cur = matcher2.end();
+                                    try {
+                                        while (matcher2.find()) {
+                                            applyStyle(sbl, colors, "se");
+                                            sbl.append(line, cur, matcher2.start());
+                                            applyStyle(sbl, colors, "ms");
+                                            sbl.append(line, matcher2.start(), matcher2.end());
+                                            applyStyle(sbl, colors, "se");
+                                            cur = matcher2.end();
+                                        }
+                                    } catch (RegexTimeoutException e) {
+                                        // append the remainder without highlighting
                                     }
                                     sbl.append(line, cur, line.length());
                                 } else {
diff --git a/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommandsTest.groovy b/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommandsTest.groovy
index 1a348d89bb..acf1d8dbb9 100644
--- a/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommandsTest.groovy
+++ b/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommandsTest.groovy
@@ -83,6 +83,15 @@ class GroovyPosixCommandsTest {
         new String(out.toByteArray(), StandardCharsets.UTF_8).normalize()
     }
 
+    /**
+     * Standard output with SGR sequences removed. grep highlights matches when colouring is
+     * on, and that highlighting is the path through {@code SafeRegex.matcher}, so the tests
+     * leave it enabled and strip the rendering rather than turning it off.
+     */
+    private String plainStdout() {
+        stdout().replaceAll('\u001B\\[[0-9;]*m', '')
+    }
+
     /** A name carrying an escape sequence the terminal would otherwise act on. */
     private static final String HOSTILE_NAME = "ok\u001B[2Ktrap.txt"
 
@@ -115,6 +124,31 @@ class GroovyPosixCommandsTest {
         assert stdout() == 'hello world\n'
     }
 
+    // GROOVY-12349: grep wrapped the pattern as ".*" + p + ".*" and matched it against the
+    // whole line. Upstream dropped the wrapping for find(), because the wrapping both
+    // misstates the intent and gives a backtracking engine more to chew on. These pin the
+    // two paths that split apart as a result.
+    @Test
+    void grepFindsAPatternAnywhereInTheLine() {
+        Path f = Files.writeString(tempDir.resolve('g.txt'), 'alpha beta\ngamma\n')
+        GroovyPosixCommands.grep(context(), ['grep', 'beta', f.toString()] as Object[])
+        assert plainStdout().readLines() == ['alpha beta']
+    }
+
+    @Test
+    void grepWithLineRegexpMatchesWholeLinesOnly() {
+        Path f = Files.writeString(tempDir.resolve('g.txt'), 'alpha beta\nbeta\n')
+        GroovyPosixCommands.grep(context(), ['grep', '-x', 'beta', f.toString()] as Object[])
+        assert plainStdout().readLines() == ['beta']
+    }
+
+    @Test
+    void grepInvertStillSelectsNonMatchingLines() {
+        Path f = Files.writeString(tempDir.resolve('g.txt'), 'alpha beta\ngamma\n')
+        GroovyPosixCommands.grep(context(), ['grep', '-v', 'beta', f.toString()] as Object[])
+        assert plainStdout().readLines() == ['gamma']
+    }
+
     // GROOVY-12341
     @Test
     void lsStripsControlCharactersFromFileNames() {


(groovy) 04/05: GROOVY-12349: groovysh: pad wc counts only when there are several

Posted by pa...@apache.org.
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 e20c082d0f6a3016d81325e2238caf0a2692d5cd
Author: Paul King <pa...@asert.com.au>
AuthorDate: Fri Sep 4 10:32:52 2026 +1000

    GROOVY-12349: groovysh: pad wc counts only when there are several
    
    wc padded every count to eight columns, so asking for one of them
    indented the number away from the name that follows it:
    
        groovy> /wc -l wctest.txt
               3 /tmp/claude-501/wctest.txt
    
    Padding exists to line counts up with each other, so it now applies only
    when more than one is shown, matching wc. Several counts still align as
    before.
    
    Ported from JLine 28e0be76, which is titled for ls formatting but also
    carries this. The ls half of that commit is already here, having come
    across in the 2025-09-21 sync, and the rest of it moves PosixCommands
    onto JLine's Source abstraction, which this fork does not use: it reads
    through NamedInputStream so that a Groovy variable can be a source. The
    same commit also right-aligns the file name into eight columns, which
    this does not take, since a name is not a quantity and long ones read
    worse for it.
    
    ARCHITECTURE gains a correction found while assessing this. That sync
    took from upstream master rather than from a release tag, so recording
    it as 3.30.6 understated it, and comparing a tag against a tag counts
    commits already present. It counts commits that originated here as well,
    which is a third of them. The note now says to check the author and the
    code before treating a commit as outstanding.
---
 subprojects/groovy-groovysh/ARCHITECTURE.md        | 12 ++++++++----
 .../groovy/groovysh/jline/GroovyPosixCommands.java | 22 ++++++++++++++--------
 .../groovysh/jline/GroovyPosixCommandsTest.groovy  | 16 ++++++++++++++++
 3 files changed, 38 insertions(+), 12 deletions(-)

diff --git a/subprojects/groovy-groovysh/ARCHITECTURE.md b/subprojects/groovy-groovysh/ARCHITECTURE.md
index 45877a97df..a4f04fe581 100644
--- a/subprojects/groovy-groovysh/ARCHITECTURE.md
+++ b/subprojects/groovy-groovysh/ARCHITECTURE.md
@@ -57,7 +57,7 @@ taken from, and how far it has since been carried forward.
 | File(s) | Forked | Last synced |
 |---|---|---|
 | `GroovyEngine`, `PackageHelper`, `JrtJavaBasePackages`, `ObjectInspector`, `Utils` | `ed73546ad9` (2025-06-23) against **3.30.4** | never |
-| `GroovyPosixCommands` | `4cc59b2ba1` (2025-08-19) against **3.30.5** | `b90ebb9923` (2025-09-21) against **3.30.6**, plus one fix ported in `b2561621f1` at 4.4.1 |
+| `GroovyPosixCommands` | `4cc59b2ba1` (2025-08-19) against **3.30.5** | `b90ebb9923` (2025-09-21) against upstream **master** of that date, which was ahead of 3.30.6; plus one fix ported in `b2561621f1` at 4.4.1 |
 
 Record both here whenever a file is added, re-derived or synced,
 because the procedure below cannot be carried out without them,
@@ -72,9 +72,13 @@ untouched. Re-check when the base moves rather than repeating that
 comparison.
 
 `GroovyPosixCommands` is the one that drifts, because it is the one
-in use: upstream has moved by roughly 800 lines over 21 commits
-since 3.30.6, of which only the control-character fix has been
-taken.
+in use. Measuring that drift needs care, and a plain
+`git log <tag>..<tag>` overstates it twice over. A third of the
+commits it lists originated here and went upstream, so they are
+already present; and the 2025-09-21 sync took from master rather
+than from a tag, so it holds changes no release tag of that era
+contains. Check the author and check the code before treating a
+commit as outstanding.
 
 These are kept in-tree because the upstream artefact
 (`org.jline:jline-groovy`) depends on `org.apache.groovy:groovy`,
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommands.java b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommands.java
index dfdb49fe4e..f2eeac0803 100644
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommands.java
+++ b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommands.java
@@ -196,6 +196,12 @@ public class GroovyPosixCommands {
             showLines = showWords = showBytes = true;
         }
 
+        // a lone count needs no column to line up with, and padding it to eight just
+        // indents the number away from the name, which is not what wc does
+        boolean severalCounts =
+            (showLines ? 1 : 0) + (showWords ? 1 : 0) + (showChars ? 1 : 0) + (showBytes ? 1 : 0) > 1;
+        String countFormat = severalCounts ? "%8d" : "%d";
+
         long totalLines = 0, totalWords = 0, totalChars = 0, totalBytes = 0;
 
         for (NamedInputStream source : sources) {
@@ -226,10 +232,10 @@ public class GroovyPosixCommands {
             if (only) continue;
             // Print results for this file
             StringBuilder result = new StringBuilder();
-            if (showLines) result.append(String.format("%8d", lines));
-            if (showWords) result.append(String.format("%8d", words));
-            if (showChars) result.append(String.format("%8d", chars));
-            if (showBytes) result.append(String.format("%8d", bytes));
+            if (showLines) result.append(String.format(countFormat, lines));
+            if (showWords) result.append(String.format(countFormat, words));
+            if (showChars) result.append(String.format(countFormat, chars));
+            if (showBytes) result.append(String.format(countFormat, bytes));
             result.append(" ").append(stripControlChars(source.getName()));
 
             context.out().println(result);
@@ -239,10 +245,10 @@ public class GroovyPosixCommands {
         // Print totals if multiple files
         if (total) {
             StringBuilder result = new StringBuilder();
-            if (showLines) result.append(String.format("%8d", totalLines));
-            if (showWords) result.append(String.format("%8d", totalWords));
-            if (showChars) result.append(String.format("%8d", totalChars));
-            if (showBytes) result.append(String.format("%8d", totalBytes));
+            if (showLines) result.append(String.format(countFormat, totalLines));
+            if (showWords) result.append(String.format(countFormat, totalWords));
+            if (showChars) result.append(String.format(countFormat, totalChars));
+            if (showBytes) result.append(String.format(countFormat, totalBytes));
             result.append(" total");
 
             context.out().println(result);
diff --git a/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommandsTest.groovy b/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommandsTest.groovy
index bb0fd3adc3..2dea99343f 100644
--- a/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommandsTest.groovy
+++ b/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommandsTest.groovy
@@ -181,6 +181,22 @@ class GroovyPosixCommandsTest {
         assert shown.contains('mid.txt') && !shown.contains('top.txt')
     }
 
+    // GROOVY-12349: a lone count was padded to eight as though it had a column to line up
+    // with, which just indents it away from the name. Ported from JLine 28e0be76.
+    @Test
+    void wcPadsCountsOnlyWhenThereAreSeveral() {
+        Path f = Files.writeString(tempDir.resolve('w.txt'), 'one\ntwo\nthree\n')
+        GroovyPosixCommands.wc(context(), ['wc', '-l', f.toString()] as Object[])
+        assert plainStdout().startsWith('3 ')
+    }
+
+    @Test
+    void wcKeepsColumnsAlignedForSeveralCounts() {
+        Path f = Files.writeString(tempDir.resolve('w.txt'), 'one\ntwo\nthree\n')
+        GroovyPosixCommands.wc(context(), ['wc', f.toString()] as Object[])
+        assert plainStdout() =~ /^ {7}3 {7}3 {6}14 /
+    }
+
     // GROOVY-12341
     @Test
     void lsStripsControlCharactersFromFileNames() {


(groovy) 05/05: GROOVY-12349: groovysh: hold only what tail is going to print

Posted by pa...@apache.org.
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 ab0b10afa86b043488ade34c6c993669098256c4
Author: Paul King <pa...@asert.com.au>
AuthorDate: Fri Sep 4 10:51:04 2026 +1000

    GROOVY-12349: groovysh: hold only what tail is going to print
    
    tail read its whole input and then took the end of it, so asking for the
    last two lines of a log cost the size of the log. On a 195MB file under a
    96MB heap it did not answer at all:
    
        groovy> /tail -n 2 big.log
        class            java.lang.OutOfMemoryError
        message          Java heap space
    
    Lines now go through a deque trimmed to the requested count, and bytes
    through a window of the requested size carried across reads. The same
    file answers under a 32MB heap. The input is still read from the front,
    so this bounds what is held rather than what is read; that is the half
    that was failing.
    
    JLine bounds its own tail the same way, so this goes when the fork does,
    but that waits on the getSources hook that would let the fork be deleted
    and there is no reason to keep failing until then.
    
    Tests cover both branches, including a final line with no newline, asking
    for more than exists, and a byte window spanning several reads, which is
    where a window carried between reads goes wrong if it is going to.
---
 .../groovy/groovysh/jline/GroovyPosixCommands.java | 41 ++++++++++++++--------
 .../groovysh/jline/GroovyPosixCommandsTest.groovy  | 40 +++++++++++++++++++++
 2 files changed, 66 insertions(+), 15 deletions(-)

diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommands.java b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommands.java
index f2eeac0803..9fd2d2b115 100644
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommands.java
+++ b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommands.java
@@ -43,7 +43,6 @@ import static org.jline.builtins.PosixCommands.*;
 
 import java.io.BufferedReader;
 import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
 import java.io.Closeable;
 import java.io.File;
 import java.io.IOException;
@@ -66,9 +65,11 @@ import java.time.Instant;
 import java.time.ZoneId;
 import java.time.ZonedDateTime;
 import java.time.format.DateTimeFormatter;
+import java.util.ArrayDeque;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
+import java.util.Deque;
 import java.util.EnumSet;
 import java.util.HashSet;
 import java.util.List;
@@ -388,29 +389,39 @@ public class GroovyPosixCommands {
     }
 
     private static void tailInputStream(Context context, InputStream is, int lines, int bytes) throws IOException {
+        // Both branches keep only what is going to be printed. Reading the input into memory
+        // first and taking the end of it costs the size of the input, which for the logs this
+        // is pointed at is the whole point of asking for the last few lines of them.
         if (bytes > 0) {
-            // Read all and keep last bytes
-            ByteArrayOutputStream baos = new ByteArrayOutputStream();
-            byte[] buffer = new byte[8192];
+            byte[] window = new byte[bytes];
+            int held = 0;
+            byte[] chunk = new byte[8192];
             int n;
-            while ((n = is.read(buffer)) != -1) {
-                baos.write(buffer, 0, n);
+            while ((n = is.read(chunk)) != -1) {
+                if (n >= bytes) {
+                    System.arraycopy(chunk, n - bytes, window, 0, bytes);
+                    held = bytes;
+                } else {
+                    int kept = Math.min(held, bytes - n);
+                    System.arraycopy(window, held - kept, window, 0, kept);
+                    System.arraycopy(chunk, 0, window, kept, n);
+                    held = kept + n;
+                }
             }
-            byte[] data = baos.toByteArray();
-            int start = Math.max(0, data.length - bytes);
-            context.out().write(data, start, data.length - start);
+            context.out().write(window, 0, held);
         } else {
-            // Read all and keep last lines
-            List<String> allLines = new ArrayList<>();
+            Deque<String> tail = new ArrayDeque<>();
             try (BufferedReader reader = new BufferedReader(new java.io.InputStreamReader(is))) {
                 String line;
                 while ((line = reader.readLine()) != null) {
-                    allLines.add(line);
+                    tail.addLast(line);
+                    if (tail.size() > lines) {
+                        tail.removeFirst();
+                    }
                 }
             }
-            int start = Math.max(0, allLines.size() - lines);
-            for (int i = start; i < allLines.size(); i++) {
-                context.out().println(allLines.get(i));
+            for (String line : tail) {
+                context.out().println(line);
             }
         }
     }
diff --git a/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommandsTest.groovy b/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommandsTest.groovy
index 2dea99343f..afb0903832 100644
--- a/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommandsTest.groovy
+++ b/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/jline/GroovyPosixCommandsTest.groovy
@@ -197,6 +197,46 @@ class GroovyPosixCommandsTest {
         assert plainStdout() =~ /^ {7}3 {7}3 {6}14 /
     }
 
+    // GROOVY-12349: tail read its whole input before taking the end of it, so asking for the
+    // last two lines of a large log cost the size of the log. Both branches now hold only
+    // what they are going to print.
+    @Test
+    void tailKeepsOnlyTheRequestedLines() {
+        Path f = tempDir.resolve('t.txt')
+        Files.writeString(f, (1..5000).collect { "line $it" }.join('\n') + '\n')
+        GroovyPosixCommands.tail(context(), ['tail', '-n', '2', f.toString()] as Object[])
+        assert plainStdout().readLines() == ['line 4999', 'line 5000']
+    }
+
+    @Test
+    void tailCountsAFinalLineWithoutANewline() {
+        Path f = Files.writeString(tempDir.resolve('t.txt'), 'one\ntwo\nthree')
+        GroovyPosixCommands.tail(context(), ['tail', '-n', '2', f.toString()] as Object[])
+        assert plainStdout().readLines() == ['two', 'three']
+    }
+
+    @Test
+    void tailAsksForMoreLinesThanExist() {
+        Path f = Files.writeString(tempDir.resolve('t.txt'), 'one\ntwo\n')
+        GroovyPosixCommands.tail(context(), ['tail', '-n', '99', f.toString()] as Object[])
+        assert plainStdout().readLines() == ['one', 'two']
+    }
+
+    @Test
+    void tailByBytesTakesTheEndOfTheInput() {
+        // spans several read chunks, so the window has to carry bytes between them
+        Path f = Files.writeString(tempDir.resolve('t.txt'), 'x' * 30000 + 'TAIL')
+        GroovyPosixCommands.tail(context(), ['tail', '-c', '4', f.toString()] as Object[])
+        assert plainStdout() == 'TAIL'
+    }
+
+    @Test
+    void tailByBytesAsksForMoreThanExist() {
+        Path f = Files.writeString(tempDir.resolve('t.txt'), 'abc')
+        GroovyPosixCommands.tail(context(), ['tail', '-c', '99', f.toString()] as Object[])
+        assert plainStdout() == 'abc'
+    }
+
     // GROOVY-12341
     @Test
     void lsStripsControlCharactersFromFileNames() {