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 2025/07/12 02:28:11 UTC
(groovy) 01/01: support records and interfaces amd static imports
This is an automated email from the ASF dual-hosted git repository.
paulk pushed a commit to branch jline3
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit 59c9088a16ec9d270c055ca36a25d8d1c89b02fb
Author: Paul King <pa...@asert.com.au>
AuthorDate: Sat Jul 12 11:49:48 2025 +1000
support records and interfaces amd static imports
---
LICENSE | 18 +
gradle/licenses.gradle | 3 +
gradle/verification-metadata.xml | 120 ++++
licenses/LICENSE-BINZIP | 17 +-
licenses/LICENSE-SDK | 17 +-
licenses/jline2-BINZIP.txt | 4 -
licenses/jline3-BINZIP-SRC.txt | 15 +
.../{jline2-license.txt => jline3-license.txt} | 0
src/bin/groovysh2 | 46 --
LICENSE => subprojects/groovy-groovysh/LICENSE | 46 +-
subprojects/groovy-groovysh/build.gradle | 9 +-
.../apache/groovy/groovysh/BufferManager.groovy | 114 ----
.../org/apache/groovy/groovysh/Command.groovy | 46 --
.../apache/groovy/groovysh/CommandException.groovy | 45 --
.../apache/groovy/groovysh/CommandRegistry.groovy | 108 ---
.../apache/groovy/groovysh/CommandSupport.groovy | 231 -------
.../groovy/groovysh/ComplexCommandSupport.groovy | 100 ---
.../apache/groovy/groovysh/ExitNotification.groovy | 33 -
.../org/apache/groovy/groovysh/Groovysh.groovy | 661 ------------------
.../groovy/groovysh/InteractiveShellRunner.groovy | 294 --------
.../org/apache/groovy/groovysh/Interpreter.groovy | 108 ---
.../groovy/org/apache/groovy/groovysh/Main.groovy | 481 ++++++++------
.../groovy/org/apache/groovy/groovysh/Main2.groovy | 387 -----------
.../org/apache/groovy/groovysh/Parser.groovy | 215 ------
.../groovy/org/apache/groovy/groovysh/Shell.groovy | 125 ----
.../org/apache/groovy/groovysh/ShellRunner.groovy | 99 ---
.../groovy/groovysh/antlr4/RelaxedParser.groovy | 66 --
.../groovy/groovysh/commands/BrowseCommand.groovy | 127 ----
.../groovy/groovysh/commands/DisplayCommand.groovy | 44 --
.../groovy/groovysh/commands/EditCommand.groovy | 103 ---
.../groovy/groovysh/commands/ExitCommand.groovy | 46 --
.../groovy/groovysh/commands/GrabCommand.groovy | 79 ---
.../groovy/groovysh/commands/HelpCommand.groovy | 123 ----
.../groovy/groovysh/commands/HistoryCommand.groovy | 156 -----
.../groovy/groovysh/commands/ImportCommand.groovy | 307 ---------
.../groovy/groovysh/commands/InspectCommand.groovy | 182 -----
.../groovy/groovysh/commands/LoadCommand.groovy | 86 ---
.../groovy/groovysh/commands/PurgeCommand.groovy | 82 ---
.../groovy/groovysh/commands/RecordCommand.groovy | 136 ----
.../groovysh/commands/RegisterCommand.groovy | 77 ---
.../groovy/groovysh/commands/ResetCommand.groovy | 42 --
.../groovy/groovysh/commands/SaveCommand.groovy | 76 ---
.../groovy/groovysh/commands/SetCommand.groovy | 104 ---
.../groovy/groovysh/commands/ShadowCommand.groovy | 54 --
.../groovy/groovysh/commands/ShowCommand.groovy | 98 ---
.../completion/BackslashEscapeCompleter.groovy | 52 --
.../completion/CommandNameCompleter.groovy | 52 --
.../groovysh/completion/FileNameCompleter.groovy | 173 -----
.../completion/NavigablePropertiesCompleter.groovy | 96 ---
.../ReflectionCompletionCandidate.groovy | 78 ---
.../completion/StricterArgumentCompleter.groovy | 128 ----
.../antlr4/CustomClassSyntaxCompleter.groovy | 51 --
.../completion/antlr4/GroovySyntaxCompleter.groovy | 385 -----------
.../completion/antlr4/IdentifierCompleter.groovy | 38 --
.../antlr4/ImportsSyntaxCompleter.groovy | 126 ----
.../antlr4/InfixKeywordSyntaxCompleter.groovy | 50 --
.../antlr4/KeywordSyntaxCompleter.groovy | 126 ----
.../completion/antlr4/ReflectionCompleter.groovy | 737 ---------------------
.../antlr4/VariableSyntaxCompleter.groovy | 61 --
.../groovy/groovysh/jline/GroovyBuiltins.groovy | 55 +-
.../groovy/groovysh/jline/GroovyCommands.groovy | 491 ++++++++++++--
.../apache/groovy/groovysh/jline/GroovyEngine.java | 345 ++++++----
.../groovysh/jline/GroovySystemRegistry.groovy | 18 +
.../groovysh/util/CommandArgumentParser.groovy | 122 ----
.../groovysh/util/DefaultCommandsRegistrar.groovy | 82 ---
.../groovy/groovysh/util/PackageHelper.groovy | 29 -
.../groovy/groovysh/util/PackageHelperImpl.groovy | 461 -------------
.../groovysh/util/ScriptVariableAnalyzer.groovy | 119 ----
.../groovy/groovysh/util/SimpleCompleter.groovy | 144 ----
.../groovy/groovysh/util/WrappedInputStream.groovy | 109 ---
.../groovysh/util/XmlCommandRegistrar.groovy | 95 ---
.../util/antlr4/CurlyCountingGroovyLexer.groovy | 77 ---
.../org/apache/groovy/groovysh/util/package.html | 28 -
.../src/main/resources/nanorc/dark.nanorctheme | 35 +-
.../src/main/resources/nanorc/light.nanorctheme | 13 +-
.../org/apache/groovy/groovysh/Groovysh.properties | 34 -
.../org/apache/groovy/groovysh/Main.properties | 33 +-
.../groovy-groovysh/src/spec/doc/groovysh.adoc | 2 -
.../groovy/groovysh/AllCompletersTest.groovy | 173 -----
.../groovy/groovysh/CommandCompleterTest.groovy | 148 -----
.../groovy/groovysh/CompleterTestSupport.groovy | 58 --
.../apache/groovy/groovysh/ErrorDisplayTest.groovy | 60 --
.../groovy/groovysh/GroovyshParsersTest.groovy | 51 --
.../org/apache/groovy/groovysh/GroovyshTest.groovy | 590 -----------------
.../groovy/groovysh/ImportCompleterTest.groovy | 123 ----
.../groovy/groovysh/ImportCompleterUnitTest.groovy | 259 --------
.../groovy/groovysh/MockPackageHelper.groovy | 39 --
.../apache/groovy/groovysh/ShellRunnerTest.groovy | 129 ----
.../groovy/groovysh/ShellRunnerTestSupport.groovy | 69 --
.../org/apache/groovy/groovysh/ShellTest.groovy | 47 --
.../groovy/groovysh/commands/AliasTest.groovy | 1 +
.../groovysh/commands/ClassloaderTest.groovy | 35 -
.../groovysh/commands/CommandTestSupport.groovy | 52 --
.../commands/ComplexCommandSupportTest.groovy | 160 -----
.../groovysh/commands/ConsoleTestSupport.groovy | 8 +-
.../groovysh/commands/DisplayCommandTest.groovy | 32 -
.../groovysh/commands/EchoCommand.properties | 22 -
.../groovysh/commands/EditCommandTest.groovy | 76 ---
.../groovysh/commands/ExitCommandTest.groovy | 36 -
.../groovysh/commands/GrabCommandTest.groovy | 12 +-
.../commands/GroovyCommandTestSupport.groovy | 2 +-
.../groovysh/commands/HelpCommandTest.groovy | 8 +-
.../groovysh/commands/HistoryCommandTest.groovy | 140 ----
.../groovy/groovysh/commands/ImportTest.groovy | 8 +-
.../groovysh/commands/InspectCommandTest.groovy | 28 -
.../groovysh/commands/LoadCommandTest.groovy | 34 -
.../groovysh/commands/RecordCommandTest.groovy | 52 --
.../groovysh/commands/RegisterCommandTest.groovy | 59 --
.../groovysh/commands/SaveCommandTest.groovy | 28 -
.../groovy/groovysh/commands/SetCommandTest.groovy | 49 --
.../completion/CustomClassCompleterTest.groovy | 40 --
.../completion/FileNameCompleterTest.groovy | 76 ---
.../completion/GroovySyntaxCompleterTest.groovy | 263 --------
.../completion/ImportsSyntaxCompleterTest.groovy | 226 -------
.../groovysh/completion/InvokerParsingTest.groovy | 87 ---
.../completion/KeywordCompleterTest.groovy | 75 ---
.../NavigablePropertiesCompleterTest.groovy | 104 ---
.../completion/ReflectionCompleterTest.groovy | 230 -------
.../groovysh/completion/TokenUtilTest.groovy | 57 --
.../completion/VariableCompleterTest.groovy | 61 --
.../expr/ClassWithPrivateConstructor.groovy | 31 -
.../groovy/groovysh/expr/ExprTestSupport.groovy | 46 --
.../apache/groovy/groovysh/expr/TimeItTest.groovy | 42 --
.../groovysh/util/CommandArgumentParserTest.groovy | 62 --
.../util/CurlyCountingGroovyLexerTest.groovy | 62 --
.../groovy/groovysh/util/MessageSourceTest.groovy | 49 --
.../groovysh/util/PackageHelperImplTest.groovy | 127 ----
.../util/ScriptVariableAnalyzerTest.groovy | 68 --
.../groovysh/util/WrappedInputStreamTest.groovy | 77 ---
129 files changed, 1236 insertions(+), 12910 deletions(-)
diff --git a/LICENSE b/LICENSE
index a515d411d4..503d6ed6de 100644
--- a/LICENSE
+++ b/LICENSE
@@ -211,6 +211,24 @@ For details, see licenses/asciidoc-style-license.txt.
------------------------------------------------------------------------
+JLine3 License
+
+The following source files within this product:
+
+ org/apache/groovy/groovysh/jline/GroovyEngine.java
+ org/apache/groovy/groovysh/jline/ObjectInspector.groovy
+ org/apache/groovy/groovysh/jline/Utils.groovy
+ org/apache/groovy/groovysh/jline/JrtJavaBasePackages.java
+ org/apache/groovy/groovysh/jline/PackageHelper.java
+
+were derived from similarly named files in the JLine3 source repository which
+have a BSD-style license. Details can be found in: licenses/jline3-license.txt
+
+This product bundles several JLine3 jars (optional dependency used with groovysh),
+which are available under a BSD License. For details, see licenses/jline3-license.txt.
+
+------------------------------------------------------------------------
+
JQuery License
The following file is used within documentation:
diff --git a/gradle/licenses.gradle b/gradle/licenses.gradle
index d05bc8e97a..4a66d3b358 100644
--- a/gradle/licenses.gradle
+++ b/gradle/licenses.gradle
@@ -26,6 +26,7 @@ tasks.register('updateLicenses') {
ext.licenseDocGeneratorFile = "${projectDir}/subprojects/groovy-docgenerator/LICENSE"
ext.licenseGroovyDocFile = "${projectDir}/subprojects/groovy-groovydoc/LICENSE"
ext.licenseJsr223File = "${projectDir}/subprojects/groovy-jsr223/LICENSE"
+ ext.licenseJLine3File = "${projectDir}/subprojects/groovy-groovysh/LICENSE"
ext.licenseBinZipFile = "${licensesDir}/LICENSE-BINZIP"
ext.licenseDocFile = "${licensesDir}/LICENSE-DOC"
ext.licenseJarJarFile = "${licensesDir}/LICENSE-JARJAR"
@@ -45,6 +46,7 @@ tasks.register('updateLicenses') {
def docgeneratorFiles = fileTree(licensesDir).include('normalize-stylesheet-groovy-docgenerator.txt')
def groovydocFiles = fileTree(licensesDir).include('normalize-stylesheet-groovy-groovydoc.txt')
def jsr223Files = fileTree(licensesDir).include('jsr223-BINZIP-SRC.txt')
+ def jline3Files = fileTree(licensesDir).include('jline3-BINZIP-SRC.txt')
def licenseHdr = '\n\n------------------------------------------------------------------------\n\n'
[
(licenseBinZipFile) : binzipFiles,
@@ -54,6 +56,7 @@ tasks.register('updateLicenses') {
(licenseDocGeneratorFile): docgeneratorFiles,
(licenseGroovyDocFile) : groovydocFiles,
(licenseJsr223File) : jsr223Files,
+ (licenseJLine3File) : jline3Files,
].each { outFile, inFiles ->
file(outFile).withWriter('utf-8') { writer ->
writer << ([file(licenseBaseFile)] + inFiles).collect {
diff --git a/gradle/verification-metadata.xml b/gradle/verification-metadata.xml
index 9650721bdb..55ef6492ed 100644
--- a/gradle/verification-metadata.xml
+++ b/gradle/verification-metadata.xml
@@ -115,6 +115,7 @@
<ignored-key id="FE66BCA17E67AE6F" reason="Key couldn't be downloaded from any key server"/>
</ignored-keys>
<trusted-keys>
+ <trusted-key id="0181A4828FA27B6BE6F1F5A68611CD28F472E006" group="org.jline"/>
<trusted-key id="019082BC00E0324E2AEF4CF00D3B328562A119A7" group="org.openjdk.jmh"/>
<trusted-key id="0191E61ACBBE76323AC15C83B5AD94BDD6BDB924" group="me.champeau.openbeans" name="openbeans" version="1.0.2"/>
<trusted-key id="04543577D6A9CC626239C50C7ECBD740FF06AEB5">
@@ -383,6 +384,7 @@
<component group="com.google.code.findbugs" name="jsr305" version="3.0.2">
<artifact name="jsr305-3.0.2.jar">
<pgp value="7616EB882DAF57A11477AAF559A252FB1199D873"/>
+ <sha512 value="bb09db62919a50fa5b55906013be6ca4fc7acb2e87455fac5eaf9ede2e41ce8bbafc0e5a385a561264ea4cd71bbbd3ef5a45e02d63277a201d06a0ae1636f804" origin="Generated by Gradle" reason="Artifact is not signed"/>
</artifact>
</component>
<component group="com.google.code.gson" name="gson" version="2.11.0">
@@ -416,6 +418,11 @@
<pgp value="694621A7227D8D5289699830ABE9F3126BB741C1"/>
</artifact>
</component>
+ <component group="com.google.guava" name="listenablefuture" version="9999.0-empty-to-avoid-conflict-with-guava">
+ <artifact name="listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar">
+ <sha512 value="c5987a979174cbacae2e78b319f080420cc71bcdbcf7893745731eeb93c23ed13bff8d4599441f373f3a246023d33df03e882de3015ee932a74a774afdd0782f" origin="Generated by Gradle" reason="Artifact is not signed"/>
+ </artifact>
+ </component>
<component group="com.google.inject" name="guice" version="4.2.1">
<artifact name="guice-4.2.1-no_aop.jar">
<pgp value="1616273079FE63E31C938F10F0DF21D1D0A3C384"/>
@@ -444,6 +451,7 @@
<component group="com.google.j2objc" name="j2objc-annotations" version="3.0.0">
<artifact name="j2objc-annotations-3.0.0.jar">
<pgp value="BDB5FA4FE719D787FB3D3197F6D4A1D411E9D1AE"/>
+ <sha512 value="1406b1aa53b19f8269129d96ce8b64bf36f215eacf7d8f1e0adadee31614e53bb3f7acf4ff97418c5bfc75677a6f3cd637c3d9889d1e85117b6fa12467c91e9f" origin="Generated by Gradle" reason="Artifact is not signed"/>
</artifact>
</component>
<component group="com.gradle" name="build-scan-plugin" version="1.10.1">
@@ -592,6 +600,7 @@
<component group="commons-collections" name="commons-collections" version="3.2.2">
<artifact name="commons-collections-3.2.2.jar">
<pgp value="0CC641C3A62453AB390066C4A41F13C999945293"/>
+ <sha512 value="51c72f9aca7726f3c387095e66be85a6df97c74b00a25434b89188c1b8eab6e2b55accf7b9bd412430d22bd09324dec076e300b3d1fa39fccad471f0f2a3da16" origin="Generated by Gradle" reason="Artifact is not signed"/>
</artifact>
</component>
<component group="commons-io" name="commons-io" version="2.11.0">
@@ -634,6 +643,7 @@
<component group="io.github.x-stream" name="mxparser" version="1.2.2">
<artifact name="mxparser-1.2.2.jar">
<pgp value="050A37A2E0577F4BAA095B52602EC18D20C4661C"/>
+ <sha512 value="c6578e6d5356b9ff6f80ce2fada028387f78b57099e85eba49b4e80f057fd124c338df2193190072e65b71d4f10d749e3890fae11738e5d7350bf44125fb7d7e" origin="Generated by Gradle" reason="Artifact is not signed"/>
</artifact>
</component>
<component group="jakarta.activation" name="jakarta.activation-api" version="1.2.1">
@@ -704,6 +714,7 @@
<component group="junit" name="junit" version="4.13.2">
<artifact name="junit-4.13.2.jar">
<pgp value="FF6E2C001948C5F2F38B0CC385911F425EC61B51"/>
+ <sha512 value="a31b9950f929a7e5a600d89787ef40e42a8a8e2392e210d0c0f45b3572937670a18a524f1815508cd1152cd1eaa7275cb7430ba45c053be365c83c231bccd3f0" origin="Generated by Gradle" reason="Artifact is not signed"/>
</artifact>
</component>
<component group="log4j" name="log4j" version="1.2.17">
@@ -758,6 +769,12 @@
<pgp value="A7892505CF1A58076453E52D7999BEFBA1039E8B"/>
</artifact>
</component>
+ <component group="net.java.dev.jna" name="jna" version="5.17.0">
+ <artifact name="jna-5.17.0.jar">
+ <pgp value="FA7929F83AD44C4590F6CC6815C71C0A4E0B8EDD"/>
+ <sha512 value="33f352528fc70a07ffc9184ff80647b02c51ea26ceb11ce70eea4adbd9419a6f811bc11746dc73ddf40ff2a21daedbeaabd349e901f30ec5e841a1f5fc6f1b52" origin="Generated by Gradle" reason="Artifact is not signed"/>
+ </artifact>
+ </component>
<component group="net.javacrumbs.json-unit" name="json-unit" version="2.38.0">
<artifact name="json-unit-2.38.0.jar">
<sha512 value="aca6573e4e2a2ec3b123d3ad7e8f4c9c6fb4fd33b2d01266566a2d37d96ab5cd03e8b01ce977f006be19f02c34e8795ddd14d9278a8974fe795c2f8a37b930c0" origin="Generated by Gradle" reason="A key couldn't be downloaded"/>
@@ -797,6 +814,7 @@
<component group="org.abego.treelayout" name="org.abego.treelayout.core" version="1.0.3">
<artifact name="org.abego.treelayout.core-1.0.3.jar">
<pgp value="D790F72EA8FD39551012B62DCF9F3090CE4CB752"/>
+ <sha512 value="d12d44cd9dde470035ce72785f1a8af741ca0055b0da174064931d830bd0efdc887f1b3fa6abe452498fbb48ea820b0a842ba55ab6a52a4a1cc914330e655b1d" origin="Generated by Gradle" reason="Artifact is not signed"/>
</artifact>
</component>
<component group="org.antlr" name="ST4" version="4.3.4">
@@ -849,11 +867,51 @@
<pgp value="2DB4F1EF0FA761ECC4EA935C86FDC7E2A11262CB"/>
</artifact>
</component>
+ <component group="org.apache.commons" name="commons-lang3" version="3.17.0">
+ <artifact name="commons-lang3-3.17.0.jar">
+ <sha512 value="dfd5ff7fe7f852b9caabc81e5a00e20616f98405085f059b64dc2121feb5fa6cb327e11a3d2f954c079811c31f6fd484e90f932d45078796fbfa7dbf1f1eb5aa" origin="Generated by Gradle" reason="Artifact is not signed"/>
+ </artifact>
+ </component>
+ <component group="org.apache.commons" name="commons-lang3" version="3.8.1">
+ <artifact name="commons-lang3-3.8.1.jar">
+ <sha512 value="fb0fe98385496a565678a000c26a3245082abfbf879cc29a35112b4bf18c966697a7a63bb1fd2fae4a42512cd3de5a2e6dc9d1df4a4058332a6ddeae06cdf667" origin="Generated by Gradle" reason="Artifact is not signed"/>
+ </artifact>
+ </component>
<component group="org.apache.commons" name="commons-math3" version="3.6.1">
<artifact name="commons-math3-3.6.1.jar">
<pgp value="41A1A08C62FCA78B79D3081164A16FAAEC16A4BE"/>
</artifact>
</component>
+ <component group="org.apache.commons" name="commons-text" version="1.3">
+ <artifact name="commons-text-1.3.jar">
+ <sha512 value="697af1320d949b0e03d29cc097143c4f8724e26ec944b936c201b983b88117dd7037f843f099b0fd955f1f5355c4d5fc2f12ca7c2b8aea3ce16d9b01b83fbcb5" origin="Generated by Gradle" reason="Artifact is not signed"/>
+ </artifact>
+ </component>
+ <component group="org.apache.httpcomponents" name="httpclient" version="4.5.13">
+ <artifact name="httpclient-4.5.13.jar">
+ <sha512 value="3567739186e551f84cad3e4b6b270c5b8b19aba297675a96bcdff3663ff7d20d188611d21f675fe5ff1bfd7d8ca31362070910d7b92ab1b699872a120aa6f089" origin="Generated by Gradle" reason="Artifact is not signed"/>
+ </artifact>
+ </component>
+ <component group="org.apache.httpcomponents" name="httpcore" version="4.4.14">
+ <artifact name="httpcore-4.4.14.jar">
+ <sha512 value="f16a652f4a7b87dbf7cb16f8590d54a3f719c4c7b2f8883ce59db2d73be4701b64f2ca8a2c45aca6a5dbeaddeedff0c280a03722f70c076e239b645faa54eff9" origin="Generated by Gradle" reason="Artifact is not signed"/>
+ </artifact>
+ </component>
+ <component group="org.apache.httpcomponents.client5" name="httpclient5" version="5.1.3">
+ <artifact name="httpclient5-5.1.3.jar">
+ <sha512 value="4fb38b6bf164103e68320ce430776915a6831923eb3e0b6e6f29ff57647e6bd29efc07d46b107aec23bf9004cfd959fbda8153740ba0060260a54d67ccf8a093" origin="Generated by Gradle" reason="Artifact is not signed"/>
+ </artifact>
+ </component>
+ <component group="org.apache.httpcomponents.core5" name="httpcore5" version="5.1.3">
+ <artifact name="httpcore5-5.1.3.jar">
+ <sha512 value="c9b439da0fb0124f37676686c69f8fdb824a30e0d6a3b9ebc0ebca5555727ae18cc5a146d8874b4cfe6fa966d5eb6083a44c379a76017ec79863596a23c571b3" origin="Generated by Gradle" reason="Artifact is not signed"/>
+ </artifact>
+ </component>
+ <component group="org.apache.httpcomponents.core5" name="httpcore5-h2" version="5.1.3">
+ <artifact name="httpcore5-h2-5.1.3.jar">
+ <sha512 value="76a22785285a3c12a98db24d678f1fd695cb4941be438fd80a7c41b4fbf804452694f93947579aba3bcee652671e362ae6d76bfb60a8db75518e52aba4ddad36" origin="Generated by Gradle" reason="Artifact is not signed"/>
+ </artifact>
+ </component>
<component group="org.apache.ivy" name="ivy" version="2.5.2">
<artifact name="ivy-2.5.2.jar">
<pgp value="CE8075A251547BEE249BC151A2115AE15F6B8B72"/>
@@ -862,6 +920,7 @@
<component group="org.apache.ivy" name="ivy" version="2.5.3">
<artifact name="ivy-2.5.3.jar">
<pgp value="9C60C6B3A5A9DF8FEDD299D65BE0BA8CB80602AE"/>
+ <sha512 value="be291ddf612703fd3657a72820199430d053a8e06f7631e78477b428ba343631bc36b16bde8c25df544b64b420be84568d3898921f8db63fe676fb590586355b" origin="Generated by Gradle" reason="Artifact is not signed"/>
</artifact>
</component>
<component group="org.apache.logging.log4j" name="log4j-api" version="2.24.3">
@@ -1203,6 +1262,11 @@
<sha512 value="a99e92782658ed20e1d01b0ae426882d481a4ba91de3f6c058a24aa54ebded654f4b16dc26adccafd61f27ce22329a1ae1db935c4b49ee31734bcb775e6c7fd7" origin="Generated by Gradle" reason="A key couldn't be downloaded"/>
</artifact>
</component>
+ <component group="org.codehaus.plexus" name="plexus-component-annotations" version="2.1.0">
+ <artifact name="plexus-component-annotations-2.1.0.jar">
+ <sha512 value="cc534fda54272f074fe9edd581a6c3e1ea98127340c7f852c4b4953a44dad048ace22dfa10f30d6adcdfc15efd319dac778a03ebbe20de7779fd1df640506e88" origin="Generated by Gradle" reason="Artifact is not signed"/>
+ </artifact>
+ </component>
<component group="org.codehaus.plexus" name="plexus-component-annotations" version="2.2.0">
<artifact name="plexus-component-annotations-2.2.0.jar">
<pgp value="BA926F64CA647B6D853A38672E2010F8A7FF4A41"/>
@@ -1327,6 +1391,7 @@
<component group="org.hamcrest" name="hamcrest-core" version="1.3">
<artifact name="hamcrest-core-1.3.jar">
<pgp value="4DB1A49729B053CAF015CEE9A6ADFC93EF34893E"/>
+ <sha512 value="e237ae735aac4fa5a7253ec693191f42ef7ddce384c11d29fbf605981c0be077d086757409acad53cb5b9e53d86a07cc428d459ff0f5b00d32a8cbbca390be49" origin="Generated by Gradle" reason="Artifact is not signed"/>
</artifact>
</component>
<component group="org.hsqldb" name="hsqldb" version="2.7.4">
@@ -1473,6 +1538,11 @@
<sha512 value="397c3257c5448c26304b312212f6da1649ad15e52ce0419c5ba647f8a68864707a0c8071fa9860c28aa9d626d66c8faf2d5f576e693f9d01b0f71eeeb84b57fb" origin="Generated by Gradle" reason="Artifact is not signed"/>
</artifact>
</component>
+ <component group="org.opentest4j" name="opentest4j" version="1.3.0">
+ <artifact name="opentest4j-1.3.0.jar">
+ <sha512 value="78fc698a7871bb50305e3657893c10500595f043348d875f57bc39ca4a6a51eda3967b7c8c8a7ec3e8f85f2171bca4aa98823e912e416e87e81c6ba5b70a37c3" origin="Generated by Gradle" reason="Artifact is not signed"/>
+ </artifact>
+ </component>
<component group="org.osgi" name="org.osgi.dto" version="1.0.0">
<artifact name="org.osgi.dto-1.0.0.jar">
<sha512 value="6c2e82be9a502b05817ce276a807ec0f72e4847ad1712b9c36afd2bac6989e88873c271ae87fd2d867f56016686b9e3b1a6b39c5e5bed76d6e52fb8e2569b615" origin="Generated by Gradle" reason="A key couldn't be downloaded"/>
@@ -1523,6 +1593,56 @@
<sha512 value="5dbdf60bace26f9dbe2610d3de178e729fae77d65f57cb8238a828d020aaf1b4cc3d3d804bbdcf4a385c141b14fbf92ff689d9caa1f9e86542b5c47b0b1e9288" origin="Generated by Gradle" reason="A key couldn't be downloaded"/>
</artifact>
</component>
+ <component group="org.ow2.asm" name="asm" version="9.7.1">
+ <artifact name="asm-9.7.1.jar">
+ <sha512 value="4767b01603dad5c79cc1e2b5f3722f72b1059d928f184f446ba11badeb1b381b3a3a9a801cc43d25d396df950b09d19597c73173c411b1da890de808b94f1f50" origin="Generated by Gradle" reason="Artifact is not signed"/>
+ </artifact>
+ </component>
+ <component group="org.ow2.asm" name="asm" version="9.8">
+ <artifact name="asm-9.8.jar">
+ <sha512 value="cbd250b9c698a48a835e655f5f5262952cc6dd1a434ec0bc3429a9de41f2ce08fcd3c4f569daa7d50321ca6ad1d32e131e4199aa4fe54bce9e9691b37e45060e" origin="Generated by Gradle" reason="Artifact is not signed"/>
+ </artifact>
+ </component>
+ <component group="org.ow2.asm" name="asm-analysis" version="9.7.1">
+ <artifact name="asm-analysis-9.7.1.jar">
+ <sha512 value="a8bd265c81d9bb4371cafd3f5d18f96ad79aec65031457d518c54599144d199d9feddf13b8dc822b2598b8b504a88edbd81d1f2c52991a70a6b343d8f5bb6fe5" origin="Generated by Gradle" reason="Artifact is not signed"/>
+ </artifact>
+ </component>
+ <component group="org.ow2.asm" name="asm-analysis" version="9.8">
+ <artifact name="asm-analysis-9.8.jar">
+ <sha512 value="0268e6dc2cc4965180ca1b62372e3c5fc280d6dc09cfeace2ac4e43468025e8a78813e4e93beafc0352e67498c70616cb4368313aaab532025fa98146c736117" origin="Generated by Gradle" reason="Artifact is not signed"/>
+ </artifact>
+ </component>
+ <component group="org.ow2.asm" name="asm-commons" version="9.7.1">
+ <artifact name="asm-commons-9.7.1.jar">
+ <sha512 value="81daf5765e387e6aeec5d45c4b9e4e1b471fb4f350931e5a214845c7c657a2142768f6902765e49c0ce2c595962e5d008883cba2e4a40c4bdce8f2e92518d2db" origin="Generated by Gradle" reason="Artifact is not signed"/>
+ </artifact>
+ </component>
+ <component group="org.ow2.asm" name="asm-commons" version="9.8">
+ <artifact name="asm-commons-9.8.jar">
+ <sha512 value="d2add10e25416b701bd84651b42161e090df2f32940de5e06e0e2a41c6106734db2fe5136f661d8a8af55e80dc958bc7b385a1004f0ebe550828dfa1e9d70d41" origin="Generated by Gradle" reason="Artifact is not signed"/>
+ </artifact>
+ </component>
+ <component group="org.ow2.asm" name="asm-tree" version="9.7.1">
+ <artifact name="asm-tree-9.7.1.jar">
+ <sha512 value="e55008c392fdd35e95d3404766b12dd4b46e13d5c362fcd0ab42a65751a82737eaf0ebc857691d1916190d34407adfde4437615d69c278785416fd911e00978d" origin="Generated by Gradle" reason="Artifact is not signed"/>
+ </artifact>
+ </component>
+ <component group="org.ow2.asm" name="asm-tree" version="9.8">
+ <artifact name="asm-tree-9.8.jar">
+ <sha512 value="4493f573d9f0cfc8837db9be25a8b61a825a06aafc0e02f0363875584ff184a5a14600e53793c09866300859e44f153faffd0e050de4a7fba1a63b5fb010a9a7" origin="Generated by Gradle" reason="Artifact is not signed"/>
+ </artifact>
+ </component>
+ <component group="org.ow2.asm" name="asm-util" version="9.7.1">
+ <artifact name="asm-util-9.7.1.jar">
+ <sha512 value="522d793d15a2c5ea6504a50222cf0750f1eab7b881cf289675042539b1aba8b3868197b1bebe729de728dd10020eb028ae16252dcd5d84fdcbf7f925832bc269" origin="Generated by Gradle" reason="Artifact is not signed"/>
+ </artifact>
+ </component>
+ <component group="org.ow2.asm" name="asm-util" version="9.8">
+ <artifact name="asm-util-9.8.jar">
+ <sha512 value="b68048e199c49d2f90b2990c6993f1fcddccd34fb9d91154ef327d874aa5ff8609db5fbd63e23141020cdeda8fb753e97a61c2152e1b4e8f20003a5390e7e1d9" origin="Generated by Gradle" reason="Artifact is not signed"/>
+ </artifact>
+ </component>
<component group="org.reflections" name="reflections" version="0.10.2">
<artifact name="reflections-0.10.2.jar">
<pgp value="3F2A008A91D11A7FAC4A0786F13D3E721D56BD54"/>
diff --git a/licenses/LICENSE-BINZIP b/licenses/LICENSE-BINZIP
index cba7e5136e..1b50bfd779 100644
--- a/licenses/LICENSE-BINZIP
+++ b/licenses/LICENSE-BINZIP
@@ -223,10 +223,21 @@ BSD license. For details, see licenses/hamcrest-license.txt.
------------------------------------------------------------------------
-JLine2 License (optional dependency used with groovysh)
+JLine3 License
-This product bundles the JLine2 jar, which is available under a
-BSD License. For details, see licenses/jline2-license.txt.
+The following source files within this product:
+
+ org/apache/groovy/groovysh/jline/GroovyEngine.java
+ org/apache/groovy/groovysh/jline/ObjectInspector.groovy
+ org/apache/groovy/groovysh/jline/Utils.groovy
+ org/apache/groovy/groovysh/jline/JrtJavaBasePackages.java
+ org/apache/groovy/groovysh/jline/PackageHelper.java
+
+were derived from similarly named files in the JLine3 source repository which
+have a BSD-style license. Details can be found in: licenses/jline3-license.txt
+
+This product bundles several JLine3 jars (optional dependency used with groovysh),
+which are available under a BSD License. For details, see licenses/jline3-license.txt.
------------------------------------------------------------------------
diff --git a/licenses/LICENSE-SDK b/licenses/LICENSE-SDK
index f912246438..e355010831 100644
--- a/licenses/LICENSE-SDK
+++ b/licenses/LICENSE-SDK
@@ -223,10 +223,21 @@ BSD license. For details, see licenses/hamcrest-license.txt.
------------------------------------------------------------------------
-JLine2 License (optional dependency used with groovysh)
+JLine3 License
-This product bundles the JLine2 jar, which is available under a
-BSD License. For details, see licenses/jline2-license.txt.
+The following source files within this product:
+
+ org/apache/groovy/groovysh/jline/GroovyEngine.java
+ org/apache/groovy/groovysh/jline/ObjectInspector.groovy
+ org/apache/groovy/groovysh/jline/Utils.groovy
+ org/apache/groovy/groovysh/jline/JrtJavaBasePackages.java
+ org/apache/groovy/groovysh/jline/PackageHelper.java
+
+were derived from similarly named files in the JLine3 source repository which
+have a BSD-style license. Details can be found in: licenses/jline3-license.txt
+
+This product bundles several JLine3 jars (optional dependency used with groovysh),
+which are available under a BSD License. For details, see licenses/jline3-license.txt.
------------------------------------------------------------------------
diff --git a/licenses/jline2-BINZIP.txt b/licenses/jline2-BINZIP.txt
deleted file mode 100644
index dd3b3ab42a..0000000000
--- a/licenses/jline2-BINZIP.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-JLine2 License (optional dependency used with groovysh)
-
-This product bundles the JLine2 jar, which is available under a
-BSD License. For details, see licenses/jline2-license.txt.
diff --git a/licenses/jline3-BINZIP-SRC.txt b/licenses/jline3-BINZIP-SRC.txt
new file mode 100644
index 0000000000..f97727d66f
--- /dev/null
+++ b/licenses/jline3-BINZIP-SRC.txt
@@ -0,0 +1,15 @@
+JLine3 License
+
+The following source files within this product:
+
+ org/apache/groovy/groovysh/jline/GroovyEngine.java
+ org/apache/groovy/groovysh/jline/ObjectInspector.groovy
+ org/apache/groovy/groovysh/jline/Utils.groovy
+ org/apache/groovy/groovysh/jline/JrtJavaBasePackages.java
+ org/apache/groovy/groovysh/jline/PackageHelper.java
+
+were derived from similarly named files in the JLine3 source repository which
+have a BSD-style license. Details can be found in: licenses/jline3-license.txt
+
+This product bundles several JLine3 jars (optional dependency used with groovysh),
+which are available under a BSD License. For details, see licenses/jline3-license.txt.
diff --git a/licenses/jline2-license.txt b/licenses/jline3-license.txt
similarity index 100%
rename from licenses/jline2-license.txt
rename to licenses/jline3-license.txt
diff --git a/src/bin/groovysh2 b/src/bin/groovysh2
deleted file mode 100644
index cb91378df7..0000000000
--- a/src/bin/groovysh2
+++ /dev/null
@@ -1,46 +0,0 @@
-#!/usr/bin/env sh
-# ----------------------------------------------------------------------------
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-# ----------------------------------------------------------------------------
-
-##############################################################################
-## ##
-## Groovy Shell script for UN*X ##
-## ##
-##############################################################################
-
-export GROOVY_APP_NAME=GroovyShell
-
-# resolve links - $0 may be a soft-link
-PRG="$0"
-
-while [ -h "$PRG" ] ; do
- ls="$(ls -ld "$PRG")"
- link="$(expr "$ls" : '.*-> \(.*\)$')"
- if expr "$link" : '/.*' > /dev/null; then
- PRG="$link"
- else
- PRG="$(dirname "$PRG")"/"$link"
- fi
-done
-
-DIRNAME="$(dirname "$PRG")"
-
-. "$DIRNAME/startGroovy"
-
-startGroovy org.apache.groovy.groovysh.Main2 "$@"
diff --git a/LICENSE b/subprojects/groovy-groovysh/LICENSE
similarity index 89%
copy from LICENSE
copy to subprojects/groovy-groovysh/LICENSE
index a515d411d4..c36fe585b2 100644
--- a/LICENSE
+++ b/subprojects/groovy-groovysh/LICENSE
@@ -203,42 +203,18 @@
------------------------------------------------------------------------
-Asciidoc License
+JLine3 License
-This product uses the style.css from asciidoctor.org within
-documentation. The file is available under the MIT License.
-For details, see licenses/asciidoc-style-license.txt.
+The following source files within this product:
-------------------------------------------------------------------------
-
-JQuery License
-
-The following file is used within documentation:
-
- src/spec/assets/css/jquery-2.1.1.min.js
-
-This file is made available under the following MIT license:
-licenses/jquery-js-license.txt
-
-------------------------------------------------------------------------
-
-JSR223 License
-
-The following classes within this product:
-
- org.codehaus.groovy.jsr223.GroovyCompiledScript
- org.codehaus.groovy.jsr223.GroovyScriptEngineFactory
- org.codehaus.groovy.jsr223.GroovyScriptEngineImpl
-
-were derived from reference implementation files developed by Sun in
-collaboration with the Groovy community. The reference implementation
-has a BSD-style license. Details can be found in: licenses/jsr223-license.txt
-
-------------------------------------------------------------------------
+ org/apache/groovy/groovysh/jline/GroovyEngine.java
+ org/apache/groovy/groovysh/jline/ObjectInspector.groovy
+ org/apache/groovy/groovysh/jline/Utils.groovy
+ org/apache/groovy/groovysh/jline/JrtJavaBasePackages.java
+ org/apache/groovy/groovysh/jline/PackageHelper.java
-normalize.css License
+were derived from similarly named files in the JLine3 source repository which
+have a BSD-style license. Details can be found in: licenses/jline3-license.txt
-The stylesheet.css file (originally normalize.css) is used by the
-groovydoc and docgenerator components for groovy-jdk/gapi documentation.
-It is made available under a MIT License:
-licenses/normalize-stylesheet-license.txt
+This product bundles several JLine3 jars (optional dependency used with groovysh),
+which are available under a BSD License. For details, see licenses/jline3-license.txt.
diff --git a/subprojects/groovy-groovysh/build.gradle b/subprojects/groovy-groovysh/build.gradle
index 9bd910cafa..d3cc2c9f5f 100644
--- a/subprojects/groovy-groovysh/build.gradle
+++ b/subprojects/groovy-groovysh/build.gradle
@@ -36,7 +36,6 @@ dependencies {
implementation "org.jline:jansi:${versions.jline}"
implementation "org.jline:jline-reader:${versions.jline}"
implementation "org.jline:jline-console:${versions.jline}"
-// implementation "org.jline:jline-console:3.30.5-SNAPSHOT"
implementation "org.jline:jline-terminal-jni:${versions.jline}"
implementation "org.jline:jline-terminal-jansi:${versions.jline}"
implementation "org.jline:jline-terminal-jna:${versions.jline}"
@@ -50,3 +49,11 @@ plugins.withId('eclipse') {
entries.removeAll { entry -> entry.path in ['/groovy-xml', '/groovy-swing', '/groovy-templates'] }
}
}
+
+tasks.named('rat') {
+ excludes << '**/jline/GroovyEngine.java' // BSD license as per NOTICE/LICENSE files
+ excludes << '**/jline/ObjectInspector.groovy' // BSD license as per NOTICE/LICENSE files
+ excludes << '**/jline/Utils.groovy' // BSD license as per NOTICE/LICENSE files
+ excludes << '**/jline/JrtJavaBasePackages.java' // BSD license as per NOTICE/LICENSE files
+ excludes << '**/jline/PackageHelper.java' // BSD license as per NOTICE/LICENSE files
+}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/BufferManager.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/BufferManager.groovy
deleted file mode 100644
index 7e73a304d1..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/BufferManager.groovy
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh
-
-import org.codehaus.groovy.tools.shell.util.Logger
-
-/**
- * Manages the shells buffers.
- */
-class BufferManager
-{
- protected final Logger log = Logger.create(this.class)
-
- final List<List<String>> buffers = []
-
- int selected
-
- BufferManager() {
- reset()
- }
-
- void reset() {
- buffers.clear()
-
- create(true)
-
- log.debug('Buffers reset')
- }
-
- List<String> current() {
- assert !buffers.isEmpty()
-
- return buffers[selected]
- }
-
- void select(final int index) {
- assert index >= 0 && index < buffers.size()
-
- selected = index
- }
-
- int create(final boolean select) {
- buffers << []
-
- def i = buffers.size() - 1
-
- if (select) {
- this.select(i)
- }
-
- if (log.debugEnabled) {
- log.debug("Created new buffer with index: $i")
- }
-
- return i
- }
-
- void delete(final int index) {
- assert index >= 0 && index < buffers.size()
-
- buffers.remove(index)
-
- if (log.debugEnabled) {
- log.debug("Deleted buffer with index: $index")
- }
- }
-
- int size() {
- return buffers.size()
- }
-
- //
- // Selected operators
- //
-
- void deleteSelected() {
- delete(selected)
-
- def i = selected - 1
-
- if (i < 0) {
- select(0)
- }
- else {
- select(i)
- }
- }
-
- void clearSelected() {
- current().clear()
- }
-
- void updateSelected(final List buffer) {
- assert buffer != null
-
- buffers[selected] = buffer
- }
-}
\ No newline at end of file
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/Command.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/Command.groovy
deleted file mode 100644
index d9b171d988..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/Command.groovy
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh
-
-import groovy.transform.CompileStatic
-import org.jline.reader.Completer
-
-/**
- * Provides the interface required for command extensions.
- */
-@CompileStatic
-interface Command {
- String getName()
-
- String getShortcut()
-
- Completer getCompleter()
-
- String getDescription()
-
- String getUsage()
-
- String getHelp()
-
- List/*<CommandAlias>*/ getAliases()
-
- Object execute(final List<String> args)
-
- boolean getHidden()
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/CommandException.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/CommandException.groovy
deleted file mode 100644
index 5181a2db51..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/CommandException.groovy
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh
-
-import groovy.transform.CompileStatic
-
-/**
- * Thrown to indicate a problem with command execution.
- */
-@CompileStatic
-class CommandException extends Exception {
-
- private final Command command
- private static final long serialVersionUID = 3904423461953446923L;
-
- CommandException(final Command command, final String msg) {
- super(msg)
- this.command = command
- }
-
- CommandException(final Command command, final String msg, final Throwable cause) {
- super(msg, cause)
- this.command = command
- }
-
- Command getCommand() {
- return command
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/CommandRegistry.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/CommandRegistry.groovy
deleted file mode 100644
index e691864382..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/CommandRegistry.groovy
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh
-
-import org.codehaus.groovy.tools.shell.util.Logger
-
-/**
- * A registry of shell {@link Command} instances which may be executed.
- */
-class CommandRegistry
-{
- protected final Logger log = Logger.create(CommandRegistry)
-
- //
- // TODO: Hook up support so one can for (command in registry) { }
- //
-
- /** A list of all of the registered commands. */
- final List<Command> commandList = []
-
- /** A set of all of the command names and shortcuts to ensure they are unique. */
- private final Set<String> names = new TreeSet<String>()
-
- Command register(final Command command) {
- assert command
-
- // Make sure that the command name and shortcut are unique
- assert !names.contains(command.name) : "Duplicate command name: $command.name"
- names << command.name
-
- assert !names.contains(command.shortcut) : "Duplicate command shortcut: $command.shortcut"
- names << command.shortcut
-
- // Hold on to the command in order
- commandList << command
-
- // Hookup context for alias commands
- if (command instanceof CommandSupport) {
- ((CommandSupport) command).registry = this
- }
-
- // Add any standard aliases for the command if any
- command.aliases?.each {Command it -> this.register(it) }
-
- if (log.debugEnabled) {
- log.debug("Registered command: $command.name")
- }
-
- return command
- }
-
- Command find(final String name) {
- assert name
-
- for (c in commandList) {
- if (name in [ c.name, c.shortcut ]) {
- return c
- }
- // also allow :import
- if (!c.name.startsWith(':') && name.equals(':' + c.name)) {
- return c
- }
- }
-
- return null
- }
-
- void remove(final Command command) {
- assert command
-
- commandList.remove(command)
-
- names.remove(command.name)
- names.remove(command.shortcut)
-
- if (log.debugEnabled) {
- log.debug("Removed command: $command.name")
- }
- }
-
- List<Command> commands() {
- return commandList
- }
-
- Command getProperty(final String name) {
- return find(name)
- }
-
- Iterator iterator() {
- return commands().iterator()
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/CommandSupport.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/CommandSupport.groovy
deleted file mode 100644
index 2eed51c5a1..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/CommandSupport.groovy
+++ /dev/null
@@ -1,231 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh
-
-import org.jline.reader.Completer
-import org.jline.reader.impl.completer.NullCompleter
-import org.jline.reader.impl.completer.StringsCompleter
-import org.jline.reader.History
-import org.apache.groovy.groovysh.completion.StricterArgumentCompleter
-import org.codehaus.groovy.tools.shell.IO
-import org.codehaus.groovy.tools.shell.util.Logger
-import org.codehaus.groovy.tools.shell.util.MessageSource
-
-import static org.jline.jansi.AnsiRenderer.render
-
-/**
- * Support for {@link Command} instances.
- */
-abstract class CommandSupport implements Command {
- protected static final String NEWLINE = System.lineSeparator()
-
- /** Instance logger for the command, initialized late to include the command name. */
- protected final Logger log
-
- /** i18n message source for the command. */
- protected final MessageSource messages = new MessageSource(this.class, CommandSupport)
-
- /** The name of the command. */
- final String name
-
- /** The shortcut switch */
- final String shortcut
-
- /** A description */
- private String description
-
- /** The owning shell. */
- protected final Groovysh shell
-
- /** The I/O container for the command to spit stuff out. */
- protected final IO io
-
- /** Provides the command instance with the registry, for aliasing support. */
- protected CommandRegistry registry
-
- /** Standard aliases for the command. */
- final List/*<CommandAlias>*/ aliases = []
-
- /** Flag to indicate if the command should be hidden or not. */
- boolean hidden = false
-
- protected CommandSupport(final Groovysh shell, final String name, final String shortcut, final String description = null) {
- assert shell != null
- assert name
- assert shortcut
-
- this.log = Logger.create(this.class, name)
- this.shell = shell
- this.io = shell.io
- this.name = name
- this.shortcut = shortcut
- this.description = description
-
- //
- // NOTE: Registry will be added once registered.
- //
- }
-
- @Override
- String getDescription() {
- if (!this.description) {
-
- }
- try {
- this.description = messages.getMessage('command.description')
- } catch (MissingResourceException) {
- this.description = 'No description'
- }
- description
- }
-
- @Override
- String getUsage() {
- try {
- return messages.getMessage('command.usage')
- } catch (MissingResourceException) {
- return 'No usage description'
- }
- }
-
- @Override
- String getHelp() {
- try {
- return messages.getMessage('command.help')
- } catch (MissingResourceException) {
- return 'No help'
- }
- }
-
- @Override
- boolean getHidden() {
- return hidden
- }
-
- @Override
- List getAliases() {
- return aliases
- }
-
- @Override
- String getShortcut() {
- return shortcut
- }
-
- @Override
- String getName() {
- return name
- }
-/**
- * Override to provide custom completion semantics for the command.
- */
- protected List<Completer> createCompleters() {
- return []
- }
-
- /**
- * Setup the Completer for the command.
- */
- @Override
- Completer getCompleter() {
- if (hidden) {
- return null
- }
-
- List<Completer> list = new ArrayList<Completer>()
- List<Completer> completers = createCompleters()
-
- StringsCompleter stringCompleter
- if (completers) {
- stringCompleter = new StringsCompleter(name + ' ', shortcut + ' ')
- } else {
- stringCompleter = new StringsCompleter(name, shortcut)
- }
-
- list << stringCompleter
-
- if (completers) {
- // replace null/empty with NullCompleter
- completers.each {Completer it ->
- if (it) {
- list << it
- } else {
- list << NullCompleter.INSTANCE
- }
- }
- } else {
- list << NullCompleter.INSTANCE
- }
-
-
- return new StricterArgumentCompleter(list)
- }
-
- //
- // Helpers
- //
-
- protected void fail(final String msg) {
- throw new CommandException(this, render(msg))
- }
-
- protected void fail(final String msg, final Throwable cause) {
- throw new CommandException(this, render(msg), cause)
- }
-
- protected void assertNoArguments(final List<String> args) {
- assert args != null
-
- if (args.size() > 0) {
- fail(messages.format('error.unexpected_args', args.join(' ')))
- }
- }
-
- //
- // Shell access helpers
- //
-
- protected BufferManager getBuffers() {
- return shell.buffers
- }
-
- protected List<String> getBuffer() {
- return shell.buffers.current()
- }
-
- protected List<String> getImports() {
- return shell.imports
- }
-
- protected Binding getBinding() {
- return shell.interp.context
- }
-
- protected Map getVariables() {
- return binding.variables
- }
-
- protected History getHistory() {
- return shell.history
- }
-
- protected GroovyClassLoader getClassLoader() {
- return shell.interp.classLoader
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/ComplexCommandSupport.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/ComplexCommandSupport.groovy
deleted file mode 100644
index 6595ed26de..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/ComplexCommandSupport.groovy
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh
-
-import org.apache.groovy.groovysh.util.SimpleCompleter
-import org.jline.reader.Completer
-
-/**
- * Support for more complex commands.
- */
-abstract class ComplexCommandSupport
- extends CommandSupport
-{
-
- protected final List<String> functions
-
- protected final String defaultFunction
-
- protected ComplexCommandSupport(final Groovysh shell, final String name, final String shortcut, final List<String> comFunctions) {
- this(shell, name, shortcut, comFunctions, null)
- }
-
- protected ComplexCommandSupport(final Groovysh shell, final String name, final String shortcut,
- final List<String> comFunctions, final String defaultFunction) {
- super(shell, name, shortcut)
- this.functions = comFunctions
- this.defaultFunction = defaultFunction
- assert(defaultFunction == null || defaultFunction in functions)
- }
-
- @Override
- protected List<Completer> createCompleters() {
- def c = new SimpleCompleter()
- c.setWithBlank(false)
- functions.each { String it -> c.add(it) }
-
- return [ c, null ]
- }
-
- @Override
- Object execute(List<String> args) {
- assert args != null
-
- if (args.size() == 0) {
- if (defaultFunction) {
- args = [ defaultFunction ]
- } else {
- fail("Command '$name' requires at least one argument of ${functions}")
- }
- }
-
- return executeFunction(args[0], args.tail())
- }
-
- protected executeFunction(final String fname, final List<String> args) {
- assert args != null
-
- List<String> myFunctions = functions
-
- if (fname in myFunctions) {
- Closure func = loadFunction(fname)
-
- log.debug("Invoking function '$fname' w/args: $args")
-
- return func.call(args)
- }
- fail("Unknown function name: '$fname'. Valid arguments: $myFunctions")
- }
-
- protected Closure loadFunction(final String name) {
- assert name
-
- try {
- return this."do_${name}"
- } catch (MissingPropertyException e) {
- fail("Failed to load delegate function: $e")
- }
- }
-
- def do_all = {
- functions.findAll {it != 'all'}.collect {executeFunction(it, [])}
- }
-}
-
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/ExitNotification.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/ExitNotification.groovy
deleted file mode 100644
index 76f3259715..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/ExitNotification.groovy
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh
-
-/**
- * Notification to signal the shell to exit.
- */
-class ExitNotification extends Error {
- private static final long serialVersionUID = 6530248218832943112L;
-
- /** The exit code. */
- final int code
-
- ExitNotification(final int code) {
- this.code = code
- }
-}
\ No newline at end of file
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/Groovysh.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/Groovysh.groovy
deleted file mode 100644
index 5edc815780..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/Groovysh.groovy
+++ /dev/null
@@ -1,661 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh
-
-import groovy.transform.AutoFinal
-import groovy.transform.CompileDynamic
-import groovy.transform.CompileStatic
-import groovy.transform.stc.ClosureParams
-import groovy.transform.stc.SimpleType
-import org.apache.groovy.groovysh.commands.LoadCommand
-import org.apache.groovy.groovysh.commands.RecordCommand
-import org.apache.groovy.groovysh.util.DefaultCommandsRegistrar
-import org.apache.groovy.groovysh.util.PackageHelper
-import org.apache.groovy.groovysh.util.PackageHelperImpl
-import org.apache.groovy.groovysh.util.ScriptVariableAnalyzer
-import org.apache.groovy.groovysh.util.XmlCommandRegistrar
-import org.apache.groovy.groovysh.util.antlr4.CurlyCountingGroovyLexer
-import org.codehaus.groovy.control.CompilationFailedException
-import org.codehaus.groovy.control.CompilerConfiguration
-import org.codehaus.groovy.control.ErrorCollector
-import org.codehaus.groovy.control.MultipleCompilationErrorsException
-import org.codehaus.groovy.control.messages.Message
-import org.codehaus.groovy.runtime.FormatHelper
-import org.codehaus.groovy.runtime.StackTraceUtils
-import org.codehaus.groovy.tools.shell.IO
-import org.codehaus.groovy.tools.shell.util.MessageSource
-import org.codehaus.groovy.tools.shell.util.Preferences
-import org.jline.reader.History
-import org.jline.reader.impl.history.DefaultHistory
-import org.jline.terminal.Terminal
-
-import java.util.regex.Pattern
-
-import static org.codehaus.groovy.control.CompilerConfiguration.DEFAULT
-import static org.jline.jansi.AnsiRenderer.render
-
-/**
- * An interactive shell for evaluating Groovy code from the command-line (aka. groovysh).
- *
- * The set of available commands can be modified by placing a file in the classpath named
- * <code>org/codehaus/groovy/tools/shell/commands.xml</code>
- *
- * @see XmlCommandRegistrar
- */
-@AutoFinal @CompileStatic
-class Groovysh extends Shell {
-
- private static final Pattern TYPEDEF_PATTERN = ~'^\\s*((?:public|protected|private|static|abstract|final)\\s+)*(?:class|enum|interface).*'
- private static final Pattern METHODDEF_PATTERN = ~'^\\s*((?:public|protected|private|static|abstract|final|synchronized)\\s+)*[a-zA-Z_.]+[a-zA-Z_.<>]+\\s+[a-zA-Z_]+\\(.*'
-
- public static final String COLLECTED_BOUND_VARS_MAP_VARNAME = 'groovysh_collected_boundvars'
-
- public static final String INTERPRETER_MODE_PREFERENCE_KEY = 'interpreterMode'
- public static final String AUTOINDENT_PREFERENCE_KEY = 'autoindent'
- public static final String COLORS_PREFERENCE_KEY = 'colors'
- public static final String SANITIZE_PREFERENCE_KEY = 'sanitizeStackTrace'
- public static final String SHOW_LAST_RESULT_PREFERENCE_KEY = 'showLastResult'
-
- // after how many prefix characters we start displaying all metaclass methods
- public static final String METACLASS_COMPLETION_PREFIX_LENGTH_PREFERENCE_KEY = 'meta-completion-prefix-length'
-
- private static final MessageSource messages = new MessageSource(Groovysh)
-
- //
-
- final BufferManager buffers = new BufferManager()
-
- final Parser parser
-
- final Interpreter interp
-
- // individual imports are stored without leading 'import ' or trailing ';'
- final List<String> imports = []
-
- int indentSize = 2
-
- InteractiveShellRunner runner
-
- History history
-
- boolean historyFull // used as a workaround for GROOVY-2177
-
- String evictedLine // remembers the command which will get evicted if history is full
-
- PackageHelper packageHelper
-
- private CompilerConfiguration configuration
-
- private static Closure createDefaultRegistrar(ClassLoader classLoader) {
- return { Groovysh groovysh ->
- URL xmlCommandResource = groovysh.getClass().getResource('commands.xml')
- if (xmlCommandResource != null) {
- def registrar = new XmlCommandRegistrar(groovysh, classLoader)
- registrar.register(xmlCommandResource)
- } else {
- def registrar = new DefaultCommandsRegistrar(groovysh)
- registrar.register()
- }
- }
- }
-
- //--------------------------------------------------------------------------
-
- Groovysh(ClassLoader classLoader, Binding binding, IO io, @ClosureParams(value=SimpleType, options='org.apache.groovy.groovysh.Groovysh') Closure registrar, CompilerConfiguration configuration, Interpreter interpreter) {
- super(io)
- assert classLoader
- assert binding
- def theRegistrar = registrar ?: createDefaultRegistrar(classLoader)
- interp = interpreter
- parser = new Parser()
- theRegistrar.call(this)
- packageHelper = new PackageHelperImpl(classLoader)
- this.configuration = configuration
- }
-
- Groovysh(ClassLoader classLoader, Binding binding, IO io, @ClosureParams(value=SimpleType, options='org.apache.groovy.groovysh.Groovysh') Closure registrar = null, CompilerConfiguration configuration = DEFAULT) {
- this(classLoader, binding, io, registrar, configuration, new Interpreter(classLoader, binding, configuration))
- }
-
- // ClassLoader,Binding,IO variants (drop left-to-right)
-
- Groovysh(Binding binding, IO io) {
- this(Thread.currentThread().getContextClassLoader(), binding, io)
- }
-
- Groovysh(IO io, CompilerConfiguration cc) {
- this(Thread.currentThread().getContextClassLoader(), new Binding(), io, null, cc)
- }
-
- Groovysh(IO io) {
- this(new Binding(), io)
- }
-
- Groovysh() {
- this(new IO())
- }
-
- //
- // Execution
- //
-
- /**
- * Execute a single line, where the line may be a command or Groovy code (complete or incomplete).
- */
- @Override
- Object execute(String line) {
- assert line != null
-
- // Ignore empty lines
- if (line.trim().isEmpty()) {
- return null
- }
-
- maybeRecordInput(line)
-
- Object result
-
- // First try normal command execution
- if (isExecutable(line)) {
- result = executeCommand(line)
-
- // For commands, only set the last result when its non-null
- if (result != null) {
- setLastResult(result)
- }
-
- return result
- }
-
- // Otherwise treat the line as Groovy
- List<String> current = new ArrayList<>(buffers.current())
-
- // Append the line to the current buffer
- current << line
-
- String importsSpec = this.getImportStatements()
-
- // Attempt to parse the current buffer
- def status = parser.parse([importsSpec] + current)
-
- switch (status.code) {
- case ParseCode.COMPLETE:
- log.debug('Evaluating buffer...')
-
- if (io.verbose) {
- displayBuffer(current)
- }
-
- if (!Boolean.valueOf(getPreference(INTERPRETER_MODE_PREFERENCE_KEY, 'false')) || isTypeOrMethodDeclaration(current)) {
- // Evaluate the current buffer w/imports and dummy statement
- List buff = [importsSpec] + [ 'true' ] + current
- try {
- setLastResult(result = interp.evaluate(buff))
- } catch(MultipleCompilationErrorsException t) {
- if (isIncompleteCaseOfAntlr4(t)) {
- // treat like INCOMPLETE case
- buffers.updateSelected(current)
- break
- }
- throw t
- }
- } else {
- // Evaluate Buffer wrapped with code storing bounded vars
- try {
- result = evaluateWithStoredBoundVars(importsSpec, current)
- } catch(MultipleCompilationErrorsException t) {
- if (isIncompleteCaseOfAntlr4(t)) {
- // treat like INCOMPLETE case
- buffers.updateSelected(current)
- break
- }
- throw t
- }
- }
-
- buffers.clearSelected()
- break
-
- case ParseCode.INCOMPLETE:
- // Save the current buffer so user can build up complex multi-line code blocks
- buffers.updateSelected(current)
- break
-
- case ParseCode.ERROR:
- throw status.cause
-
- default:
- // Should never happen
- throw new Error("Invalid parse status: $status.code")
- }
-
- return result
- }
-
- private boolean isIncompleteCaseOfAntlr4(MultipleCompilationErrorsException t) {
- // TODO antlr4 parser errors pop out here - can we rework to be like antlr2?
- (
- (t.message.contains('Unexpected input: ') || t.message.contains('Unexpected character: ')) && !(
- t.message.contains("Unexpected input: '}'")
- || t.message.contains("Unexpected input: ')'")
- || t.message.contains("Unexpected input: ']'")
- )
- )
- }
-
- /**
- * return true if the buffer can be recognized as a type declaration statement
- * @param strings
- * @return
- */
- static boolean isTypeOrMethodDeclaration(List<String> buffer) {
- String joined = buffer.join('')
- return joined.matches(TYPEDEF_PATTERN) || joined.matches(METHODDEF_PATTERN)
- }
-/*
- * to simulate an interpreter mode, this method wraps the statements into a try/finally block that
- * stores bound variables like unbound variables
- */
- private Object evaluateWithStoredBoundVars(String importsSpec, List<String> current) {
- Object result
- String variableBlocks = null
- // To make groovysh behave more like an interpreter, we need to retrieve all bound
- // vars at the end of script execution, and then update them into the groovysh Binding context.
- Set<String> boundVars = ScriptVariableAnalyzer.getBoundVars(importsSpec + Parser.NEWLINE + current.join(Parser.NEWLINE), interp.classLoader)
- if (boundVars) {
- variableBlocks = "$COLLECTED_BOUND_VARS_MAP_VARNAME = new HashMap();"
- boundVars.each({ String varname ->
- // bound vars can be in global or some local scope.
- // We discard locally scoped vars by ignoring MissingPropertyException
- variableBlocks += """
-try {$COLLECTED_BOUND_VARS_MAP_VARNAME[\"$varname\"] = $varname;
-} catch (MissingPropertyException e){}"""
- })
- }
- // Evaluate the current buffer w/imports and dummy statement
- List<String> buff
- if (variableBlocks) {
- buff = [importsSpec] + ['try {', 'true'] + current + [variableBlocks, '} finally {' + variableBlocks + '}']
- } else {
- buff = [importsSpec] + ['true'] + current
- }
- setLastResult(result = interp.evaluate(buff))
-
- if (variableBlocks) {
- def boundVarValues = (Map<String, Object>) interp.context.getVariable(COLLECTED_BOUND_VARS_MAP_VARNAME)
- boundVarValues.each({ String name, Object value -> interp.context.setVariable(name, value) })
- }
-
- return result
- }
-
- protected Object executeCommand(String line) {
- return super.execute(line)
- }
-
- /**
- * Display the given buffer.
- */
- void displayBuffer(List buffer) {
- assert buffer
-
- buffer.eachWithIndex { line, index ->
- def lineNum = formatLineNumber(index)
-
- io.out.println(" ${lineNum}@|bold >|@ $line")
- }
- }
-
- String getImportStatements() {
- return this.imports.collect({String it -> "import $it;"}).join('')
- }
-
- //
- // Prompt
- //
-
- /**
- * Builds the command prompt name in 1 of 3 ways:
- * <ol>
- * <li>Checks the groovysh.prompt property passed into groovysh script: {@code -Dgroovysh.prompt="hello"}
- * <li>Checks an environment variable called GROOVYSH_PROMPT: {@code export GROOVYSH_PROMPT}
- * <li>If no value is defined returns the default groovy shell prompt.
- * </ol>
- * The code will always assume you want the line number in the prompt. To
- * implement differently overhead the render prompt variable.
- */
- private String renderPrompt() {
- def lineNum = formatLineNumber(buffers.current().size())
- def prompt = System.getProperty('groovysh.prompt') ?: System.getenv('GROOVYSH_PROMPT') ?: 'groovy'
- render("@|bold $prompt:|@$lineNum@|bold >|@ ")
- }
-
- /**
- * Calculate probably desired indentation based on parenthesis balance and last char,
- * as well as what the user used last as indentation.
- * @return a string to indent the next line in the buffer
- */
- String getIndentPrefix() {
- List<String> buffer = this.buffers.current()
- if (buffer.size() < 1) {
- return ''
- }
- StringBuilder src = new StringBuilder()
- for (String line: buffer) {
- src.append(line).append('\n')
- }
-
- def lexer = CurlyCountingGroovyLexer.createGroovyLexer(src.toString())
- int curlyIndent = lexer.countCurlyLevel() * indentSize
-
- // dedent after closing brackets
- return ' ' * Math.max(curlyIndent, 0)
- }
-
- /**
- * Format the given number suitable for rendering as a line number column.
- */
- protected String formatLineNumber(int num) {
- assert num >= 0
- // Make a %03d-like string for the line number
- return num.toString().padLeft(3, '0')
- }
-
- //
- // User Profile Scripts
- //
-
- File getUserStateDirectory() {
- def userHome = new File(System.getProperty('user.home'))
- def dir = new File(userHome, '.groovy')
- return dir.canonicalFile
- }
-
- /**
- * Loads file from within user groovy state directory.
- */
- @CompileDynamic
- protected void loadUserScript(String filename) {
- assert filename
-
- def file = new File(getUserStateDirectory(), filename)
- if (file.exists()) {
- def command = registry[LoadCommand.COMMAND_NAME] as Command
- if (command) {
- log.debug("Loading user-script: $file")
-
- // Disable the result hook for profile scripts
- def previousHook = resultHook
- resultHook = { result -> /* nothing */}
- try {
- command.load(file.toURI().toURL())
- }
- finally {
- resultHook = previousHook
- }
- } else {
- log.error("Unable to load user-script, missing '$LoadCommand.COMMAND_NAME' command")
- }
- }
- }
-
- //
- // Recording
- //
-
- protected void maybeRecordInput(String line) {
- def record = (RecordCommand) registry[RecordCommand.COMMAND_NAME]
- if (record != null) {
- record.recordInput(line)
- }
- }
-
- protected void maybeRecordResult(Object result) {
- def record = (RecordCommand) registry[RecordCommand.COMMAND_NAME]
- if (record != null) {
- record.recordResult(result)
- }
- }
-
- protected void maybeRecordError(Throwable cause) {
- def record = (RecordCommand) registry[RecordCommand.COMMAND_NAME]
- if (record != null) {
- Throwable error
- if (getPreference(SANITIZE_PREFERENCE_KEY, 'false')) {
- error = StackTraceUtils.deepSanitize(cause)
- } else {
- error = cause
- }
- record.recordError(error)
- }
- }
-
- //
- // Hooks
- //
-
- final Closure defaultResultHook = { Object result ->
- boolean showLastResult = !io.quiet && (io.verbose || getPreference(SHOW_LAST_RESULT_PREFERENCE_KEY, 'false'))
- if (showLastResult) {
- // avoid String.valueOf here because it bypasses pretty-printing of Collections,
- // e.g. String.valueOf( ['a': 42] ) != ['a': 42].toString()
- io.out.println(render("@|bold ===>|@ ${FormatHelper.toString(result)}"))
- }
- }
-
- Closure resultHook = defaultResultHook
-
- private void setLastResult(Object result) {
- if (resultHook == null) {
- throw new IllegalStateException('Result hook is not set')
- }
-
- resultHook.call((Object)result)
-
- interp.context['_'] = result
-
- maybeRecordResult(result)
- }
-
- final Closure defaultErrorHook = { Throwable cause ->
- assert cause != null
-
- if (log.debug || ! (cause instanceof CompilationFailedException)) {
- // For CompilationErrors, the Exception Class is usually not useful to the user
- io.err.println(render("@|bold,red ERROR|@ ${cause.getClass().name}:"))
- }
-
- if (cause instanceof MultipleCompilationErrorsException) {
- Writer data = new org.apache.groovy.io.StringBuilderWriter()
- PrintWriter writer = new PrintWriter(data)
- ErrorCollector collector = ((MultipleCompilationErrorsException) cause).getErrorCollector()
- Iterator<? extends Message> msgIterator = collector.getErrors().iterator()
- while (msgIterator.hasNext()) {
- Message errorMsg = msgIterator.next()
- errorMsg.write(writer)
- if (msgIterator.hasNext()) {
- writer.println()
- }
- }
- io.err.println(render("@|bold,red ${data.toString()}|@"))
- } else {
- io.err.println(render("@|bold,red ${cause.message}|@"))
-
- maybeRecordError(cause)
-
- if (log.debug) {
- // If we have debug enabled then skip the fancy bits below
- log.debug(cause)
- }
- else {
- boolean sanitize = getPreference(SANITIZE_PREFERENCE_KEY, 'false')
- // Sanitize the stack trace unless we are in verbose mode, or the user has request otherwise
- def trace = (sanitize && !io.verbose ? StackTraceUtils.deepSanitize(cause) : cause).stackTrace
-
- def buff = new StringBuilder()
-
- boolean doBreak = false
-
- for (e in trace) {
- // Stop the trace once we find the root of the evaluated script
- if (e.className == Interpreter.SCRIPT_FILENAME && e.methodName == 'run') {
- if (io.verbosity != IO.Verbosity.DEBUG && io.verbosity != IO.Verbosity.VERBOSE) {
- break
- }
- doBreak = true
- }
-
- def target = (e.nativeMethod ? 'Native Method' :
- (e.fileName != null && e.lineNumber != -1 ? "${e.fileName}:${e.lineNumber}" :
- (e.fileName != null ? e.fileName : 'Unknown Source')))
-
- buff << render(" @|bold at|@ ${e.className}.${e.methodName}(@|bold $target|@)")
- io.err.println(buff)
-
- buff.setLength(0) // Reset the buffer
- if (doBreak) {
- io.err.println(render(' @|bold ...|@'))
- break
- }
- }
- }
- }
- }
-
- // protected for mocking in tests
- protected String getPreference(String key, String theDefault) {
- return Preferences.get(key, theDefault)
- }
-
- Closure errorHook = defaultErrorHook
-
- private void displayError(Throwable cause) {
- if (errorHook == null) {
- throw new IllegalStateException('Error hook is not set')
- }
- if (cause instanceof MissingPropertyException) {
- if (cause.type && cause.type.canonicalName == Interpreter.SCRIPT_FILENAME) {
- io.err.println(render("@|bold,red Unknown property|@: " + cause.property))
- return
- }
- }
-
- errorHook.call(cause)
- }
-
- /**
- * Run the Interactive Shell with optional initial script and files to load.
- */
- int run(String evalString, List<String> filenames) {
- List<String> startCommands = []
- if (evalString?.trim()) {
- startCommands.add(evalString)
- }
- if (filenames) {
- filenames.each {
- startCommands.add("${LoadCommand.COMMAND_NAME} $it".toString())
- }
- }
- return run(startCommands.join('\n'))
- }
-
- /**
- * Run the Interactive Shell with initial command.
- */
- int run(String commandLine) {
- def code
- try {
- loadUserScript('groovysh.profile')
- loadUserScript('groovysh.rc')
-
- // Setup the interactive runner
- runner = new InteractiveShellRunner(this, this.&renderPrompt)
-
- // if args were passed in, just execute as a command
- // (but cygwin gives an empty string, so ignore that)
- if (commandLine?.trim()) {
- runner.wrappedInputStream.insert(commandLine + '\n')
- }
-
- // Setup the history
- File histFile = new File(userStateDirectory, 'groovysh.history')
- history = new DefaultHistory(/*histFile*/)
-// runner.setHistory(history)
-
- // Setup the error handler
- runner.errorHandler = this.&displayError
-
- displayWelcomeBanner(runner)
-
- // And let 'er rip... :-)
- runner.run()
-
- code = 0
- } catch (ExitNotification n) {
- code = n.code
- log.debug("Exiting w/code: $code")
- } catch (Throwable t) {
- code = 1
- io.err.println(messages.format('info.fatal', t))
- t.printStackTrace(io.err)
- }
-
- assert code != null // This should never happen
-
- return code
- }
-
- /**
- * maybe displays log information and a welcome message
- * @param term
- */
- void displayWelcomeBanner(InteractiveShellRunner runner) {
- if (!log.debug && io.quiet) {
- // nothing to do here
- return
- }
- Terminal term = runner.reader.terminal
- if (log.debug) {
- log.debug("Terminal ($term)")
-// log.debug(" Supported: $term.supported")
-// log.debug(" ECHO: (enabled: $term.echoEnabled)")
- log.debug(" H x W: ${term.getHeight()} x ${term.getWidth()}")
-// log.debug(" ANSI: ${term.isAnsiSupported()}")
-
-// if (term instanceof WindowsTerminal) {
-// WindowsTerminal winterm = (WindowsTerminal) term
-// log.debug(" Direct: ${winterm.directConsole}")
-// }
- }
-
- // Display the welcome banner
- if (!io.quiet) {
- int width = term.getWidth()
-
- // If we can't tell, or have something bogus then use a reasonable default
- if (width < 1) {
- width = 80
- }
-
- io.out.println(render(messages.format('startup_banner.0', GroovySystem.version, System.properties['java.version'])))
- io.out.println(render(messages['startup_banner.1'].toString()))
- io.out.println('-' * (width - 1))
- }
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/InteractiveShellRunner.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/InteractiveShellRunner.groovy
deleted file mode 100644
index 4d54e7ad5f..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/InteractiveShellRunner.groovy
+++ /dev/null
@@ -1,294 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh
-
-import groovy.transform.AutoFinal
-import groovy.transform.CompileDynamic
-import groovy.transform.CompileStatic
-import org.apache.groovy.groovysh.completion.FileNameCompleter
-import org.apache.groovy.groovysh.completion.antlr4.CustomClassSyntaxCompleter
-import org.apache.groovy.groovysh.completion.antlr4.GroovySyntaxCompleter
-import org.apache.groovy.groovysh.completion.antlr4.IdentifierCompleter
-import org.apache.groovy.groovysh.completion.antlr4.ImportsSyntaxCompleter
-import org.apache.groovy.groovysh.completion.antlr4.KeywordSyntaxCompleter
-
-//import jline.console.completer.AggregateCompleter
-//import jline.console.completer.CandidateListCompletionHandler
-//import jline.console.completer.Completer
-//import jline.console.completer.CompletionHandler
-//import jline.console.history.FileHistory
-import org.apache.groovy.groovysh.completion.antlr4.ReflectionCompleter
-import org.apache.groovy.groovysh.completion.antlr4.VariableSyntaxCompleter
-import org.apache.groovy.groovysh.util.WrappedInputStream
-import org.codehaus.groovy.tools.shell.IO
-//import org.codehaus.groovy.tools.shell.util.Logger
-import org.codehaus.groovy.tools.shell.util.Preferences
-import org.jline.builtins.Completers
-import org.jline.builtins.ConfigurationPath
-import org.jline.builtins.SyntaxHighlighter
-import org.jline.console.impl.SystemHighlighter
-import org.jline.reader.History
-import org.jline.reader.LineReader
-import org.jline.reader.LineReaderBuilder
-import org.jline.reader.impl.DefaultHighlighter
-import org.jline.reader.impl.history.DefaultHistory
-import org.jline.terminal.Terminal
-import org.jline.terminal.TerminalBuilder
-import org.jline.utils.OSUtils
-
-import javax.swing.JRootPane
-import java.nio.file.Path
-import java.nio.file.Paths
-
-import static org.jline.builtins.SyntaxHighlighter.DEFAULT_NANORC_FILE
-import static org.jline.console.ConsoleEngine.VAR_NANORC
-
-
-/**
- * Support for running a {@link Shell} interactively using the JLine library.
- */
-@AutoFinal @CompileStatic
-class InteractiveShellRunner extends ShellRunner implements Runnable {
-
- LineReader reader
- private final Terminal terminal
- private History history
- final Closure prompt
-// final CommandsMultiCompleter completer
- WrappedInputStream wrappedInputStream
- private static final String DEFAULT_NANORC_VALUE = "classpath:/nanorc/groovy.nanorc";
-
- @CompileDynamic
- InteractiveShellRunner(Groovysh shell, Closure prompt) {
- super(shell)
- this.history = new DefaultHistory()
- this.prompt = prompt
- this.wrappedInputStream = new WrappedInputStream(shell.io.inputStream)
- this.terminal = TerminalBuilder.builder()
- .system(true)
- .name("Groovysh")
- .build()
-// this.reader = new ConsoleReader(wrappedInputStream, shell.io.outputStream)
-
-// CompletionHandler currentCompletionHandler = reader.getCompletionHandler()
-// if (currentCompletionHandler instanceof CandidateListCompletionHandler) {
-// currentCompletionHandler.setStripAnsi(true)
-// currentCompletionHandler.setPrintSpaceAfterFullCompletion(false)
-// }
-
- def reflectionCompleter = new ReflectionCompleter(shell)
-
- def classnameCompleter = new CustomClassSyntaxCompleter(shell)
-
- List<IdentifierCompleter> identifierCompleters = [
- new KeywordSyntaxCompleter(),
- new VariableSyntaxCompleter(shell),
- classnameCompleter,
- new ImportsSyntaxCompleter(shell)
- ]
-
- String jnanorcName = 'jnanorc'
- String root = '/Users/paulk/Projects/groovy/subprojects/groovy-groovysh/build/resources/main/nanorc/'
- println "root = $root"
-// File file = new File(InteractiveShellRunner.protectionDomain.codeSource.location.toURI().path)
-// String root = file.canonicalPath.replace('classes', '').normalize()
- ConfigurationPath configPath = new ConfigurationPath(Paths.get(root), Paths.get(root))
- Path jnanorc = configPath.getConfig(jnanorcName)
-// String root = base.canonicalPath.replace('classes', '').normalize()
-// println "root = $root"
-// ConfigurationPath configPath = new ConfigurationPath(Paths.get(root), Paths.get(root))
-// Path nanorc = configPath.getConfig('nanorc')
-// println "nanorc = $nanorc"
-// scriptEngine.put(VAR_NANORC, nanorc.toString())
- SyntaxHighlighter commandHighlighter = SyntaxHighlighter.build(jnanorc, "command")
- println "commandHighlighter = ${commandHighlighter.properties}"
- SyntaxHighlighter argsHighlighter = SyntaxHighlighter.build(jnanorc, "args")
- println "argsHighlighter = ${argsHighlighter.properties}"
- SyntaxHighlighter groovyHighlighter = SyntaxHighlighter.build(jnanorc, 'groovy')
- println "groovyHighlighter = ${groovyHighlighter.properties}"
- SystemHighlighter highlighter = new SystemHighlighter(commandHighlighter, argsHighlighter, groovyHighlighter)
-// if (!OSUtils.IS_WINDOWS) {
-// highlighter.setSpecificHighlighter("!", SyntaxHighlighter.build(nanorc, "SH-REPL"))
-// }
-// highlighter.addFileHighlight("nano", "less", "slurp")
-// highlighter.addFileHighlight("groovy", "classloader", Arrays.asList("-a", "--add"))
-// highlighter.addExternalHighlighterRefresh(printer::refresh)
-// highlighter.addExternalHighlighterRefresh(scriptEngine::refresh)
-// def filenameCompleter = new Completers.FileNameCompleter()
- def filenameCompleter = new FileNameCompleter()
- def groovyCompleter = new GroovySyntaxCompleter(shell, reflectionCompleter, classnameCompleter, identifierCompleters, filenameCompleter)
-
- this.reader = LineReaderBuilder.builder()
- .terminal(this.terminal)
- .highlighter(highlighter)
-// .parser(parser)
- .history(this.history)
-// .completer(new MyGroovyCompleterJLine3Adapter(/* pass necessary GroovySH context */))
- // .highlighter(new MyGroovyHighlighter()) // Optional
- // .variable(LineReader.HISTORY_FILE, historyFile) // Another way to set history file
- .option(LineReader.Option.HISTORY_IGNORE_DUPS, true)
- .option(LineReader.Option.HISTORY_IGNORE_SPACE, true)
- .completer(groovyCompleter)
- .build()
-
- // expand events ia an advanced feature of JLine that clashes with Groovy syntax (e.g. invoke "2!=3")
-// reader.expandEvents = false
-
- // complete groovysh commands, display, import, ... as first word in line
-
-// completer = new CommandsMultiCompleter()
-
-
-
-// reader.addCompleter(completer)
-// reader.addCompleter(new GroovySyntaxCompleter(
-// shell, reflectionCompleter, classnameCompleter, identifierCompleters, filenameCompleter))
-
- }
-
- @Override
- void run() {
-/* for (command in shell.registry.commands()) {
- completer.add(command)
- }
-
- // Force things to become clean
- completer.refresh()
-
- // And then actually run
- adjustHistory()*/
- super.run()
- }
-
- @Override @CompileDynamic
- protected String readLine() {
- try {
- if (Boolean.valueOf(Preferences.get(Groovysh.AUTOINDENT_PREFERENCE_KEY))) {
- // prevent auto-indent when pasting code blocks
- if (shell.io.inputStream.available() == 0) {
- wrappedInputStream.insert(((Groovysh) shell).indentPrefix)
- }
- }
- return reader.readLine(prompt())
- } catch (StringIndexOutOfBoundsException e) {
- log.debug('HACK: Try and work around GROOVY-2152 for now', e)
- reader.println()
- return ''
- } catch (Throwable t) {
- if (shell.io.verbosity == IO.Verbosity.DEBUG) {
- throw t
- }
- reader.println()
- return ''
- }
- }
-
- @Override
- protected boolean work() {
- boolean result = super.work()
- adjustHistory()
-
- result
- }
-
- private void adjustHistory() {
- // we save the evicted line in case someone wants to use it with history recall
-/* if (shell instanceof Groovysh) {
- def history = shell.history
- shell.historyFull = history != null && history.size() >= history.maxSize
- if (shell.isHistoryFull()) {
- def first = history.first()
- if (first) {
- shell.evictedLine = first.value()
- }
- }
- }*/
- }
-
-/* void setHistory(FileHistory history) {
- reader.history = history
- def dir = history.file.parentFile
-
- if (!dir.exists()) {
- dir.mkdirs()
-
- log.debug("Created base directory for history file: $dir")
- }
-
- log.debug("Using history file: $history.file")
- }*/
-}
-
-/**
- * Completer for interactive shells.
- */
-/*
-@AutoFinal @CompileStatic
-class CommandsMultiCompleter extends AggregateCompleter {
-
- protected final Logger log = Logger.create(getClass())
-
- List<Completer> list = []
-
- private boolean dirty
-
- def add(Command command) {
- assert command
-
- //
- // FIXME: Need to handle completer removal when things like aliases are rebound
- //
-
- def c = command.completer
-
- if (c) {
- list << c
-
- log.debug("Added completer[${list.size()}] for command: $command.name")
-
- dirty = true
- }
- }
-
- void refresh() {
- log.debug('Refreshing the completer list')
-
- completers.clear()
- completers.addAll(list)
- dirty = false
- }
-
- @Override
- int complete(String buffer, int pos, List cand) {
- assert buffer != null
-
- //
- // FIXME: This is a bit of a hack, I'm too lazy to rewrite a more efficient
- // completer impl that is more dynamic than the jline.MultiCompleter version
- // so just re-use it and reset the list as needed
- //
-
- if (dirty) {
- refresh()
- }
-
- return super.complete(buffer, pos, cand)
- }
-}
-*/
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/Interpreter.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/Interpreter.groovy
deleted file mode 100644
index ac3cc4a430..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/Interpreter.groovy
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh
-
-import groovy.transform.AutoFinal
-import groovy.transform.CompileDynamic
-import groovy.transform.CompileStatic
-import org.codehaus.groovy.control.CompilerConfiguration
-import org.codehaus.groovy.runtime.FormatHelper
-import org.codehaus.groovy.runtime.InvokerHelper
-import org.codehaus.groovy.runtime.MethodClosure
-import org.codehaus.groovy.tools.shell.util.Logger
-
-interface Evaluator {
- Object evaluate(Collection<String> strings)
-}
-
-/**
- * Helper to interpret a source buffer.
- */
-@AutoFinal @CompileStatic
-class Interpreter implements Evaluator {
-
- protected static final String SCRIPT_FILENAME = 'groovysh_evaluate'
-
- private final Logger log = Logger.create(getClass())
-
- private final GroovyShell shell
-
- Interpreter(ClassLoader classLoader, Binding binding, CompilerConfiguration configuration = CompilerConfiguration.DEFAULT) {
- assert classLoader
- assert binding
- shell = new GroovyShell(classLoader, binding, configuration)
- }
-
- GroovyClassLoader getClassLoader() {
- return shell.getClassLoader()
- }
-
- Binding getContext() {
- // GROOVY-9584: leave as call to getter not property access to avoid potential context variable in binding
- return shell.getContext()
- }
-
- GroovyShell getShell() {
- return shell
- }
-
- //--------------------------------------------------------------------------
-
- @Override @CompileDynamic
- Object evaluate(Collection<String> buffer) {
- assert buffer
-
- String source = buffer.join(Parser.NEWLINE)
-
- Object result = null
-
- Class type = null
- try {
- type = shell.parseClass(new GroovyCodeSource(source, SCRIPT_FILENAME, GroovyShell.DEFAULT_CODE_BASE))
- Script script = InvokerHelper.createScript(type, context)
- log.debug("Compiled script: $script")
-
- if (type.getDeclaredMethods().any { it.name == 'main' }) {
- result = script.run()
- }
-
- // Need to use String.valueOf() here to avoid icky exceptions causes by GString coercion
- log.debug("Evaluation result: ${FormatHelper.toString(result)} (${result?.getClass()})")
-
- // Keep only the methods that have been defined in the script
- type.getDeclaredMethods().each { m ->
- String name = m.name
- if (!(name == 'main' || name == 'run' || name.startsWith('super$') || name.startsWith('class$') || name.startsWith('$'))) {
- log.debug("Saving script method definition: $name")
- context[name] = new MethodClosure(script, name)
- }
- }
- } finally {
- // Remove the generated script class
- if (type?.name) {
- classLoader.removeClassCacheEntry(type.name)
- }
-
- // Remove the inline closures as well
- classLoader.removeClassCacheEntry('$_run_closure')
- }
-
- return result
- }
-}
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 0b7ef4d398..99398478b3 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,245 +18,314 @@
*/
package org.apache.groovy.groovysh
-import groovy.cli.internal.CliBuilderInternal
-import groovy.cli.internal.OptionAccessor
-import groovy.transform.AutoFinal
-import groovy.transform.CompileDynamic
-import groovy.transform.CompileStatic
-//import jline.TerminalFactory
-//import jline.UnixTerminal
-//import jline.UnsupportedTerminal
-//import jline.WindowsTerminal
-import org.codehaus.groovy.control.CompilerConfiguration
-import org.codehaus.groovy.tools.shell.IO
-import org.codehaus.groovy.tools.shell.util.Logger
+import org.apache.groovy.groovysh.jline.GroovyBuiltins
+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.GroovySystemRegistry
+import org.apache.groovy.groovysh.util.DocFinder
import org.codehaus.groovy.tools.shell.util.MessageSource
-//import org.fusesource.jansi.Ansi
-//import org.fusesource.jansi.AnsiConsole
-
-import static org.apache.groovy.util.SystemUtil.setSystemPropertyFrom
+import org.jline.builtins.ClasspathResourceUtil
+import org.jline.builtins.ConfigurationPath
+import org.jline.builtins.Options
+import org.jline.builtins.SyntaxHighlighter
+import org.jline.console.CommandInput
+import org.jline.console.CommandMethods
+import org.jline.console.CommandRegistry
+import org.jline.console.ConsoleEngine
+import org.jline.console.Printer
+import org.jline.console.impl.DefaultPrinter
+import org.jline.console.impl.JlineCommandRegistry
+import org.jline.console.impl.SystemHighlighter
+import org.jline.keymap.KeyMap
+import org.jline.reader.Binding
+import org.jline.reader.EndOfFileException
+import org.jline.reader.LineReader
+import org.jline.reader.LineReader.Option
+import org.jline.reader.LineReaderBuilder
+import org.jline.reader.Reference
+import org.jline.reader.UserInterruptException
+import org.jline.reader.impl.DefaultParser
+import org.jline.reader.impl.DefaultParser.Bracket
+import org.jline.terminal.Size
+import org.jline.terminal.Terminal
+import org.jline.terminal.Terminal.Signal
+import org.jline.terminal.TerminalBuilder
+import org.jline.utils.InfoCmp.Capability
+import org.jline.utils.OSUtils
+import org.jline.widget.TailTipWidgets
+import org.jline.widget.TailTipWidgets.TipType
+import org.jline.widget.Widgets
+
+import java.nio.file.Path
+import java.nio.file.Paths
+import java.util.function.Function
+import java.util.function.Supplier
+
+import static org.jline.jansi.AnsiRenderer.render
/**
- * A Main instance has a Groovysh member representing the shell,
- * and a startGroovysh() method to run an interactive shell.
- * Subclasses should preferably extend createIO() or configure the shell
- * via getShell prior to invoking startGroovysh.
- * Clients may use configureAndStartGroovysh to provide the same CLI params
- * but a different Groovysh implementation (implementing getIO() and run()).
- *
- * The class also has static utility methods to manipulate the
- * static ansi state using the jAnsi library.
- *
- * Main CLI entry-point for <tt>groovysh</tt>.
+ * Groovy Repo modelled on JLine3 Groovy Repl demo
*/
-@AutoFinal @CompileStatic
class Main {
- final Groovysh groovysh
-
- /**
- * @param io: may just be new IO(), which is the default
- */
- Main(IO io) {
- Logger.io = io
- groovysh = new Groovysh(io)
- }
-
- /**
- * @param io: may just be new IO(), which is the default
- */
- Main(IO io, CompilerConfiguration configuration) {
- Logger.io = io
- groovysh = new Groovysh(io, configuration)
- }
-
- /**
- * create a Main instance, configures it according to CLI arguments, and starts the shell.
- * @param main must have a Groovysh member that has an IO member.
- */
- @CompileDynamic
- static void main(String[] args) {
- MessageSource messages = new MessageSource(Main)
- def cli = new CliBuilderInternal(usage: 'groovysh [options] [...]', stopAtNonOption: false,
- header: messages['cli.option.header'])
- cli.with {
- _(names: ['-cp', '-classpath', '--classpath'], messages['cli.option.classpath.description'])
- h(longOpt: 'help', messages['cli.option.help.description'])
- V(longOpt: 'version', messages['cli.option.version.description'])
- v(longOpt: 'verbose', messages['cli.option.verbose.description'])
- q(longOpt: 'quiet', messages['cli.option.quiet.description'])
- d(longOpt: 'debug', messages['cli.option.debug.description'])
- e(longOpt: 'evaluate', args: 1, argName: 'CODE', optionalArg: false, messages['cli.option.evaluate.description'])
- C(longOpt: 'color', args: 1, argName: 'FLAG', optionalArg: true, messages['cli.option.color.description'])
- D(longOpt: 'define', type: Map, argName: 'name=value', messages['cli.option.define.description'])
- T(longOpt: 'terminal', args: 1, argName: 'TYPE', messages['cli.option.terminal.description'])
- pa(longOpt: 'parameters', messages['cli.option.parameters.description'])
- pr(longOpt: 'enable-preview', messages['cli.option.enable.preview.description'])
+ private static final MessageSource messages = new MessageSource(Main)
+
+ @SuppressWarnings("resource")
+ protected static class ExtraConsoleCommands extends JlineCommandRegistry implements CommandRegistry {
+ private LineReader reader
+ private final Supplier<Path> workDir
+
+ ExtraConsoleCommands(Supplier<Path> workDir) {
+ super()
+ this.workDir = workDir
+ registerCommands([
+ '/clear': new CommandMethods((Function) this::clear, this::defaultCompleter),
+ '/echo' : new CommandMethods((Function) this::echo, this::defaultCompleter),
+ "/!" : new CommandMethods((Function) this::shell, this::defaultCompleter)
+ ])
}
- OptionAccessor options = cli.parse(args)
- if (options == null) {
- // CliBuilder prints error, but does not exit
- System.exit(22) // Invalid Args
+ @Override
+ String name() {
+ 'Console Commands'
}
- if (options.h) {
- cli.usage()
- System.exit(0)
+ void setLineReader(LineReader reader) {
+ this.reader = reader
}
- if (options.V) {
- System.out.println(messages.format('cli.info.version', GroovySystem.version))
- System.exit(0)
+ private Terminal terminal() {
+ return reader.terminal
}
- boolean suppressColor = false
- if (options.hasOption('C')) {
- def value = options.getOptionValue('C')
- if (value != null) {
- suppressColor = !Boolean.valueOf(value).booleanValue() // For JDK 1.4 compat
+ private void clear(CommandInput input) {
+ final String[] usage = [
+ "/clear - clear terminal",
+ "Usage: /clear",
+ " -? --help Displays command help"
+ ]
+ try {
+ parseOptions(usage, input.args())
+ terminal().puts(Capability.clear_screen)
+ terminal().flush()
+ } catch (Exception e) {
+ saveException(e)
}
}
- String type = ''//TerminalFactory.AUTO
- if (options.hasOption('T')) {
- type = options.getOptionValue('T')
- }
- try {
- setTerminalType(type, suppressColor)
- } catch (IllegalArgumentException e) {
- System.err.println(e.getMessage())
- cli.usage()
- System.exit(22) // Invalid Args
- }
-
- // IO must be constructed AFTER calling setTerminalType()/AnsiConsole.systemInstall(),
- // else wrapped System.out does not work on Windows.
- IO io = new IO()
-
- if (options.hasOption('D')) {
- options.Ds.each { k, v -> System.setProperty(k, v) }
- }
-
- if (options.v) {
- io.verbosity = IO.Verbosity.VERBOSE
- }
-
- if (options.d) {
- io.verbosity = IO.Verbosity.DEBUG
+ 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)
+ }
}
- if (options.q) {
- io.verbosity = IO.Verbosity.QUIET
+ private static void executeCommand(List<String> args) throws Exception {
+ def sout = new StringBuilder(), serr = new StringBuilder()
+ def command = OSUtils.IS_WINDOWS ? ['cmd.exe', '/c'] : ['sh', '-c']
+ def proc = new ProcessBuilder().command(command + args.join(' ')).start()
+ proc.consumeProcessOutput(sout, serr)
+ int exitCode = proc.waitFor()
+ if (sout.size()) print sout
+ if (exitCode != 0) {
+ if (serr.size()) print serr
+ throw new Exception("Error occurred in shell!")
+ }
}
- String evalString = null
- if (options.e) {
- evalString = options.getOptionValue('e')
+ 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())
+ } catch (Exception e) {
+ saveException(e)
+ }
+ } else {
+ List<String> argv = input.args().toList()
+ if (!argv.isEmpty()) {
+ try {
+ executeCommand(argv)
+ } catch (Exception e) {
+ saveException(e)
+ }
+ }
+ }
}
- start(io, evalString, options.arguments(), options.hasOption('pa'))
}
- private static void start(IO io, String evalString, List<String> filenames, boolean parameters) {
- def configuration = new CompilerConfiguration(System.getProperties())
- configuration.setParameters(parameters)
- Main main = new Main(io, configuration)
- main.startGroovysh(evalString, filenames)
- }
-
- /**
- * @param evalString commands that will be executed at startup after loading files given with filenames param
- * @param filenames files that will be loaded at startup
- */
- protected void startGroovysh(String evalString, List<String> filenames) {
- int code
- Groovysh shell = getGroovysh()
-
- // Add a hook to display some status when shutting down...
- addShutdownHook {
- //
- // FIXME: We need to configure JLine to catch CTRL-C for us... Use gshell-io's InputPipe
- //
- if (code == null) {
- // Give the user a warning when the JVM shutdown abnormally, normal shutdown
- // will set an exit code through the proper channels
+ static String getUserStateDirectory() {
+ def userHome = new File(System.getProperty('user.home'))
+ new File(userHome, '.groovy').canonicalPath
+ }
- println('WARNING: Abnormal JVM shutdown detected')
+ static void main(String[] args) {
+ try {
+ Supplier<Path> workDir = () -> Paths.get(System.getProperty('user.dir'))
+ DefaultParser parser = new DefaultParser(
+ regexCommand: /\/?[a-zA-Z!]+\S*/,
+ eofOnUnclosedQuote: true
+ )
+ parser.blockCommentDelims(new DefaultParser.BlockCommentDelims('/*', '*/'))
+ .lineCommentDelims(new String[]{'//'})
+ .setEofOnUnclosedBracket(Bracket.CURLY, Bracket.ROUND, Bracket.SQUARE)
+ Terminal terminal = TerminalBuilder.builder().build()
+ if (terminal.width == 0 || terminal.height == 0) {
+ terminal.size = new Size(120, 40) // hard-coded terminal size when redirecting
}
-
- if (shell.history) {
- shell.history.save()
+ Thread executeThread = Thread.currentThread()
+ terminal.handle(Signal.INT, signal -> executeThread.interrupt())
+
+ def rootURL = Main.getResource('/nanorc')
+ Path root = ClasspathResourceUtil.getResourcePath(rootURL)
+ ConfigurationPath configPath = new ConfigurationPath(root, Path.of(userStateDirectory))
+
+ // ScriptEngine and command registries
+ GroovyEngine scriptEngine = new GroovyEngine()
+ scriptEngine.put('ROOT', rootURL.toString())
+ scriptEngine.put('CONSOLE_OPTIONS', [:])
+ Printer printer = new DefaultPrinter(scriptEngine, configPath)
+ ConsoleEngine consoleEngine = new GroovyConsoleEngine(scriptEngine, printer, workDir, configPath)
+ consoleEngine.setConsoleOption('docs', new DocFinder())
+
+ CommandRegistry builtins = new GroovyBuiltins(scriptEngine, workDir, configPath, (String fun) ->
+ new ConsoleEngine.WidgetCreator(consoleEngine, fun)
+ )
+ def extra = new ExtraConsoleCommands(workDir)
+
+ // Command line highlighter
+ scriptEngine.put(GroovyEngine.NANORC_VALUE, rootURL.toString())
+ Path jnanorc = root.resolve('jnanorc')
+ def commandHighlighter = SyntaxHighlighter.build(jnanorc, "COMMAND")
+ def argsHighlighter = SyntaxHighlighter.build(jnanorc, "ARGS")
+ def groovyHighlighter = SyntaxHighlighter.build(jnanorc, "Groovy")
+
+ CommandRegistry groovy = new GroovyCommands(scriptEngine, workDir, printer, groovyHighlighter)
+ GroovySystemRegistry systemRegistry = new GroovySystemRegistry(parser, terminal, workDir, configPath).tap {
+ groupCommandsInHelp(false)
+ setCommandRegistries(extra, consoleEngine, builtins, groovy)
+ addCompleter(scriptEngine.scriptCompleter)
+ setScriptDescription(scriptEngine::scriptDescription)
+ // sys registry doesn't support rename/alias, so for now invoke as user alias
+/*
+ renameLocal 'exit', '/exit'
+ renameLocal 'help', '/help'
+ invoke '/alias', '/x', '/exit'
+ invoke '/alias', '/q', '/exit'
+ invoke '/alias', '/h', '/help'
+*/
+ invoke '/alias', '/exit', 'exit'
+ invoke '/alias', '/help', 'help'
+ invoke '/alias', '/x', 'exit'
+ invoke '/alias', '/q', 'exit'
+ invoke '/alias', '/h', 'help'
}
- }
- //SecurityManagerUtil sm = new SecurityManagerUtil()
-
- try {
- code = shell.run(evalString, filenames)
- }
- finally {
-// sm.close()
- }
-
- // Force the JVM to exit at this point, since shell could have created threads or
- // popped up Swing components that will cause the JVM to linger after we have been
- // asked to shutdown
+ def highlighter = new SystemHighlighter(commandHighlighter, argsHighlighter, groovyHighlighter).tap {
+ if (!OSUtils.IS_WINDOWS) {
+ setSpecificHighlighter("/!", SyntaxHighlighter.build(jnanorc, "SH-REPL"))
+ }
+ addFileHighlight('/nano', '/less', 'slurp', '/load', '/save')
+ addFileHighlight('/classloader', null, ['-a', '--add'])
+ addExternalHighlighterRefresh(printer::refresh)
+ addExternalHighlighterRefresh(scriptEngine::refresh)
+ }
- System.exit(code)
- }
+ // LineReader
+ LineReader reader = LineReaderBuilder.builder()
+ .terminal(terminal)
+ .completer(systemRegistry.completer())
+ .parser(parser)
+ .highlighter(highlighter)
+ .variable(LineReader.SECONDARY_PROMPT_PATTERN, "%M%P > ")
+ .variable(LineReader.INDENTATION, 2)
+ .variable(LineReader.LIST_MAX, 100)
+ .variable(LineReader.HISTORY_FILE, configPath.getUserConfig('groovysh_history', true))
+ .option(Option.INSERT_BRACKET, true)
+ .option(Option.EMPTY_WORD_OPTIONS, false)
+ .option(Option.USE_FORWARD_SLASH, true)
+ .option(Option.DISABLE_EVENT_EXPANSION, true)
+ .build()
+ if (OSUtils.IS_WINDOWS) {
+ reader.setVariable(
+ LineReader.BLINK_MATCHING_PAREN, 0) // if enabled cursor remains in begin parenthesis (gitbash)
+ }
- /**
- * @param type: one of 'auto', 'unix', ('win', 'windows'), ('false', 'off', 'none')
- * @param suppressColor only has effect when ansi is enabled
- */
- @AutoFinal(enabled=false)
- static void setTerminalType(String type, boolean suppressColor) {
- assert type != null
+ // complete command registries
+ consoleEngine.setLineReader(reader)
+ builtins.setLineReader(reader)
+ extra.setLineReader(reader)
+
+ // widgets and console initialization
+ new TailTipWidgets(reader, systemRegistry::commandDescription, 5, TipType.COMPLETER)
+ KeyMap<Binding> keyMap = reader.keyMaps.get("main")
+ keyMap.bind(new Reference(Widgets.TAILTIP_TOGGLE), KeyMap.alt("s"))
+ def init = configPath.getUserConfig('groovysh_init')
+ if (init) {
+ systemRegistry.initialize(configPath.getUserConfig('groovysh_init').toFile())
+ }
- type = type.toLowerCase()
- boolean enableAnsi = true
-/* switch (type) {
- case TerminalFactory.AUTO:
- type = null
- break
- case TerminalFactory.UNIX:
- type = UnixTerminal.canonicalName
- break
- case TerminalFactory.WIN:
- case TerminalFactory.WINDOWS:
- type = WindowsTerminal.canonicalName
- break
- case TerminalFactory.FALSE:
- case TerminalFactory.OFF:
- case TerminalFactory.NONE:
- type = UnsupportedTerminal.canonicalName
- // Disable ANSI, for some reason UnsupportedTerminal reports ANSI as enabled, when it shouldn't
- enableAnsi = false
- break
- default:
- // Should never happen
- throw new IllegalArgumentException("Invalid Terminal type: $type")
- }*/
+ println render(messages.format('startup_banner.0', GroovySystem.version, System.properties['java.version'], terminal.type))
+ println render(messages['startup_banner.1'])
+ println '-' * (terminal.width - 1)
+ def index = 0
+ def lines = ['def boo() { 6/3 }', 'boo()']
+
+ // REPL-loop
+ while (true) {
+ try {
+ systemRegistry.cleanUp() // delete temporary variables and reset output streams
+ String line = reader.readLine("groovy> ")
+// String line = 'trait U{}\ntrait T{}\ntrait'
+// String line = lines[index++]
+ line = parser.getCommand(line).startsWith("/!") ? line.replaceFirst("/!", "/! ") : line
+ if (line.startsWith(':')) {
+ def maybeCmd = line.split()[0].replaceFirst(':', '/')
+ if (systemRegistry.hasCommand(maybeCmd) || systemRegistry.isCommandAlias(maybeCmd)) {
+ line = line.replaceFirst(':', '/')
+ }
+ }
+ Object result = systemRegistry.execute(line)
+ consoleEngine.println(result)
+ } catch (UserInterruptException e) {
+ // Ignore
+ } catch (EndOfFileException e) {
+ String pl = e.getPartialLine()
+ if (pl != null) { // execute last line from redirected file (required for Windows)
+ try {
+ consoleEngine.println(systemRegistry.execute(pl))
+ } catch (Exception e2) {
+ systemRegistry.trace(e2)
+ }
+ }
+ break
+ } catch (Exception | Error e) {
+ systemRegistry.trace(e) // print exception and save it to console variable
+ }
+ }
+ systemRegistry.close() // persist pipeline completer names etc
- if (type != null) {
-// System.setProperty(TerminalFactory.JLINE_TERMINAL, type)
+ boolean groovyRunning = Thread.getAllStackTraces().keySet().any { it.name.startsWith("AWT-Shut") }
+ if (groovyRunning) {
+ consoleEngine.println("Please, close Groovy Consoles/Object Browsers!")
+ }
+ } catch (Throwable t) {
+ t.printStackTrace()
}
}
-
- static void installAnsi() {
- // Install the system adapters, replaces System.out and System.err
- // Must be called before using IO(), because IO stores refs to System.out and System.err
-// AnsiConsole.systemInstall()
-
- // Register jline ansi detector
-// Ansi.setDetector(new AnsiDetector())
- }
-
- @Deprecated
- static void setSystemProperty(String nameValue) {
- setSystemPropertyFrom(nameValue)
- }
-
- private static final java.util.logging.Logger LOGGER = java.util.logging.Logger.getLogger(Main.class.getName());
}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/Main2.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/Main2.groovy
deleted file mode 100644
index 9ab7126c92..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/Main2.groovy
+++ /dev/null
@@ -1,387 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh
-
-import org.apache.groovy.groovysh.jline.GroovyBuiltins
-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.GroovySystemRegistry
-import org.apache.groovy.groovysh.util.DocFinder
-import org.codehaus.groovy.tools.shell.util.MessageSource
-import org.jline.builtins.ClasspathResourceUtil
-import org.jline.builtins.ConfigurationPath
-import org.jline.builtins.Options
-import org.jline.builtins.SyntaxHighlighter
-import org.jline.console.CommandInput
-import org.jline.console.CommandMethods
-import org.jline.console.CommandRegistry
-import org.jline.console.ConsoleEngine
-import org.jline.console.Printer
-import org.jline.console.impl.DefaultPrinter
-import org.jline.console.impl.JlineCommandRegistry
-import org.jline.console.impl.SystemHighlighter
-import org.jline.keymap.KeyMap
-import org.jline.reader.Binding
-import org.jline.reader.EndOfFileException
-import org.jline.reader.LineReader
-import org.jline.reader.LineReader.Option
-import org.jline.reader.LineReaderBuilder
-import org.jline.reader.Reference
-import org.jline.reader.UserInterruptException
-import org.jline.reader.impl.DefaultParser
-import org.jline.reader.impl.DefaultParser.Bracket
-import org.jline.terminal.Size
-import org.jline.terminal.Terminal
-import org.jline.terminal.Terminal.Signal
-import org.jline.terminal.TerminalBuilder
-import org.jline.utils.InfoCmp.Capability
-import org.jline.utils.OSUtils
-import org.jline.widget.TailTipWidgets
-import org.jline.widget.TailTipWidgets.TipType
-import org.jline.widget.Widgets
-
-import java.nio.file.Path
-import java.nio.file.Paths
-import java.util.function.Function
-import java.util.function.Supplier
-
-import static org.jline.jansi.AnsiRenderer.render
-
-/**
- * Groovy Repo modelled on JLine3 Groovy Repl demo
- */
-class Main2 {
- private static final MessageSource messages = new MessageSource(Groovysh)
-
- @SuppressWarnings("resource")
- protected static class ExtraConsoleCommands extends JlineCommandRegistry implements CommandRegistry {
- private LineReader reader
- private final Supplier<Path> workDir
-
- ExtraConsoleCommands(Supplier<Path> workDir) {
- super()
- this.workDir = workDir
- registerCommands([
- '/clear': new CommandMethods((Function) this::clear, this::defaultCompleter),
- '/echo' : new CommandMethods((Function) this::echo, this::defaultCompleter),
- "/!" : new CommandMethods((Function) this::shell, this::defaultCompleter)
- ])
- }
-
- @Override
- String name() {
- 'Console Commands'
- }
-
- void setLineReader(LineReader reader) {
- this.reader = reader
- }
-
- private Terminal terminal() {
- return reader.terminal
- }
-
-/* private void tput(CommandInput input) {
- final String[] usage = {
- "tput - put terminal capability",
- "Usage: tput [CAPABILITY]",
- " -? --help Displays command help"
- };
- try {
- Options opt = parseOptions(usage, input.xargs());
- List<String> argv = opt.args();
- if (!argv.isEmpty()) {
- Capability vcap = Capability.byName(argv.get(0));
- if (vcap != null) {
- terminal()
- .puts(
- vcap,
- opt.argObjects().subList(1, argv.size()).toArray(new Object[0]));
- } else {
- terminal().writer().println("Unknown capability");
- }
- } else {
- terminal().writer().println("Usage: tput [CAPABILITY]");
- }
- } catch (Exception e) {
- saveException(e);
- }
- }*/
-
-/* private void testkey(CommandInput input) {
- final String[] usage = {
- "testkey - display the key events",
- "Usage: testkey",
- " -? --help Displays command help"
- };
- try {
- parseOptions(usage, input.args());
- terminal().writer().write("Input the key event(Enter to complete): ");
- terminal().writer().flush();
- StringBuilder sb = new StringBuilder();
- while (true) {
- int c = ((LineReaderImpl) reader).readCharacter();
- if (c == 10 || c == 13) break;
- sb.append(new String(Character.toChars(c)));
- }
- terminal().writer().println(KeyMap.display(sb.toString()));
- terminal().writer().flush();
- } catch (Exception e) {
- saveException(e);
- }
- }*/
-
- private void clear(CommandInput input) {
- final String[] usage = [
- "/clear - clear terminal",
- "Usage: /clear",
- " -? --help Displays command help"
- ]
- try {
- parseOptions(usage, input.args())
- terminal().puts(Capability.clear_screen)
- terminal().flush()
- } catch (Exception e) {
- saveException(e)
- }
- }
-
- 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)
- }
- }
-
- private static void executeCommand(List<String> args) throws Exception {
- def sout = new StringBuilder(), serr = new StringBuilder()
- def command = OSUtils.IS_WINDOWS ? ['cmd.exe', '/c'] : ['sh', '-c']
- def proc = new ProcessBuilder().command(command + args.join(' ')).start()
- proc.consumeProcessOutput(sout, serr)
- int exitCode = proc.waitFor()
- if (sout.size()) print sout
- if (exitCode != 0) {
- if (serr.size()) print serr
- throw new Exception("Error occurred in shell!")
- }
- }
-
- 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())
- } catch (Exception e) {
- saveException(e)
- }
- } else {
- List<String> argv = input.args().toList()
- if (!argv.isEmpty()) {
- try {
- executeCommand(argv)
- } catch (Exception e) {
- saveException(e)
- }
- }
- }
- }
-
-// private Set<String> capabilities() {
-// return InfoCmp.getCapabilitiesByName().keySet();
-// }
-
-// private List<Completer> tputCompleter(String command) {
-// List<Completer> completers = new ArrayList<>();
-// completers.add(new ArgumentCompleter(
-// NullCompleter.INSTANCE,
-// new OptionCompleter(new StringsCompleter(this::capabilities), this::commandOptions, 1)));
-// return completers;
-// }
- }
-
-
- static String getUserStateDirectory() {
- def userHome = new File(System.getProperty('user.home'))
- new File(userHome, '.groovy').canonicalPath
- }
-
- static void main(String[] args) {
- try {
- Supplier<Path> workDir = () -> Paths.get(System.getProperty("user.dir"))
- DefaultParser parser = new DefaultParser(
- regexCommand: /\/?[a-zA-Z!]+\S*/,
- eofOnUnclosedQuote: true
- )
- parser.blockCommentDelims(new DefaultParser.BlockCommentDelims("/*", "*/"))
- .lineCommentDelims(new String[]{"//"})
- .setEofOnUnclosedBracket(Bracket.CURLY, Bracket.ROUND, Bracket.SQUARE)
- Terminal terminal = TerminalBuilder.builder().build()
- if (terminal.getWidth() == 0 || terminal.getHeight() == 0) {
- terminal.setSize(new Size(120, 40)) // hard coded terminal size when redirecting
- }
- Thread executeThread = Thread.currentThread()
- terminal.handle(Signal.INT, signal -> executeThread.interrupt())
-
- def rootURL = Main2.getResource('/nanorc')
- Path root = ClasspathResourceUtil.getResourcePath(rootURL)
- ConfigurationPath configPath = new ConfigurationPath(root, Path.of(userStateDirectory))
-
- // ScriptEngine and command registries
- GroovyEngine scriptEngine = new GroovyEngine()
- scriptEngine.put("ROOT", rootURL.toString())
- scriptEngine.put('CONSOLE_OPTIONS', [:])
- Printer printer = new DefaultPrinter(scriptEngine, configPath)
- ConsoleEngine consoleEngine = new GroovyConsoleEngine(scriptEngine, printer, workDir, configPath)
- consoleEngine.setConsoleOption('docs', new DocFinder())
-
- CommandRegistry builtins = new GroovyBuiltins(workDir, configPath, (String fun) ->
- new ConsoleEngine.WidgetCreator(consoleEngine, fun)
- )
- def extra = new ExtraConsoleCommands(workDir)
- CommandRegistry groovy = new GroovyCommands(scriptEngine, printer)
- GroovySystemRegistry systemRegistry = new GroovySystemRegistry(parser, terminal, workDir, configPath).tap {
- groupCommandsInHelp(false)
- setCommandRegistries(extra, consoleEngine, builtins, groovy)
- addCompleter(scriptEngine.scriptCompleter)
- setScriptDescription(scriptEngine::scriptDescription)
- // sys registry doesn't support rename/alias, so for now invoke as user alias
-/*
- renameLocal 'exit', '/exit'
- renameLocal 'help', '/help'
- invoke '/alias', '/x', '/exit'
- invoke '/alias', '/q', '/exit'
- invoke '/alias', '/h', '/help'
-*/
- invoke '/alias', '/exit', 'exit'
- invoke '/alias', '/help', 'help'
- invoke '/alias', '/x', 'exit'
- invoke '/alias', '/q', 'exit'
- invoke '/alias', '/h', 'help'
- }
-
- // Command line highlighter
- scriptEngine.put(GroovyEngine.NANORC_VALUE, rootURL.toString())
- Path jnanorc = root.resolve('jnanorc')
- def commandHighlighter = SyntaxHighlighter.build(jnanorc, "COMMAND")
- def argsHighlighter = SyntaxHighlighter.build(jnanorc, "ARGS")
- def groovyHighlighter = SyntaxHighlighter.build(jnanorc, "Groovy")
- def highlighter = new SystemHighlighter(commandHighlighter, argsHighlighter, groovyHighlighter).tap {
- if (!OSUtils.IS_WINDOWS) {
- setSpecificHighlighter("/!", SyntaxHighlighter.build(jnanorc, "SH-REPL"))
- }
- addFileHighlight("/nano", "/less", "slurp")
- addFileHighlight("/classloader", null, Arrays.asList("-a", "--add"))
- addExternalHighlighterRefresh(printer::refresh)
- addExternalHighlighterRefresh(scriptEngine::refresh)
- }
-
- // LineReader
- LineReader reader = LineReaderBuilder.builder()
- .terminal(terminal)
- .completer(systemRegistry.completer())
- .parser(parser)
- .highlighter(highlighter)
- .variable(LineReader.SECONDARY_PROMPT_PATTERN, "%M%P > ")
- .variable(LineReader.INDENTATION, 2)
- .variable(LineReader.LIST_MAX, 100)
- .variable(LineReader.HISTORY_FILE, configPath.getUserConfig('groovysh_history', true))
- .option(Option.INSERT_BRACKET, true)
- .option(Option.EMPTY_WORD_OPTIONS, false)
- .option(Option.USE_FORWARD_SLASH, true)
- .option(Option.DISABLE_EVENT_EXPANSION, true)
- .build()
- if (OSUtils.IS_WINDOWS) {
- reader.setVariable(
- LineReader.BLINK_MATCHING_PAREN, 0) // if enabled cursor remains in begin parenthesis (gitbash)
- }
-
- // complete command registries
- consoleEngine.setLineReader(reader)
- builtins.setLineReader(reader)
- extra.setLineReader(reader)
-
- // widgets and console initialization
- new TailTipWidgets(reader, systemRegistry::commandDescription, 5, TipType.COMPLETER)
- KeyMap<Binding> keyMap = reader.keyMaps.get("main")
- keyMap.bind(new Reference(Widgets.TAILTIP_TOGGLE), KeyMap.alt("s"))
- def init = configPath.getUserConfig('groovysh_init')
- if (init) {
- systemRegistry.initialize(configPath.getUserConfig('groovysh_init').toFile())
- }
-
- println render(messages.format('startup_banner.0', GroovySystem.version, System.properties['java.version'], terminal.type))
- println render(messages['startup_banner.1'])
- println '-' * (terminal.width - 1)
-
- // REPL-loop
- while (true) {
- try {
- systemRegistry.cleanUp() // delete temporary variables and reset output streams
- String line = reader.readLine("groovy> ")
-// String line = '/grab \t'
- line = parser.getCommand(line).startsWith("/!") ? line.replaceFirst("/!", "/! ") : line
- if (line.startsWith(':')) {
- def maybeCmd = line.split()[0].replaceFirst(':', '/')
- if (systemRegistry.hasCommand(maybeCmd) || systemRegistry.isCommandAlias(maybeCmd)) {
- line = line.replaceFirst(':', '/')
- }
- }
- Object result = systemRegistry.execute(line)
- consoleEngine.println(result)
- } catch (UserInterruptException e) {
- // Ignore
- } catch (EndOfFileException e) {
- String pl = e.getPartialLine()
- if (pl != null) { // execute last line from redirected file (required for Windows)
- try {
- consoleEngine.println(systemRegistry.execute(pl))
- } catch (Exception e2) {
- systemRegistry.trace(e2)
- }
- }
- break
- } catch (Exception | Error e) {
- systemRegistry.trace(e) // print exception and save it to console variable
- }
- }
- systemRegistry.close() // persist pipeline completer names etc
-
- boolean groovyRunning = Thread.getAllStackTraces().keySet().any { it.name.startsWith("AWT-Shut") }
- if (groovyRunning) {
- consoleEngine.println("Please, close Groovy Consoles/Object Browsers!")
- }
- } catch (Throwable t) {
- t.printStackTrace()
- }
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/Parser.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/Parser.groovy
deleted file mode 100644
index 857ef847ce..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/Parser.groovy
+++ /dev/null
@@ -1,215 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh
-
-import org.apache.groovy.groovysh.antlr4.RelaxedParser
-import org.codehaus.groovy.control.CompilationFailedException
-import org.codehaus.groovy.control.SourceUnit
-import org.codehaus.groovy.tools.shell.util.Logger
-import org.codehaus.groovy.tools.shell.util.Preferences
-
-import java.util.regex.Pattern
-
-interface Parsing {
- ParseStatus parse(final Collection<String> buffer)
-}
-
-/**
- * Provides a facade over the parser to recognize valid Groovy syntax.
- */
-class Parser {
- static final String NEWLINE = System.lineSeparator()
-
- private static final Logger log = Logger.create(Parser)
-
- private final Parsing delegate
-
- Parser() {
- String flavor = Preferences.getParserFlavor()
-
- log.debug("Using parser flavor: $flavor")
-
- switch (flavor) {
- case Preferences.PARSER_RELAXED:
- delegate = new RelaxedParser()
- break
-
- case Preferences.PARSER_RIGID:
- delegate = new RigidParser()
- break
-
- default:
- log.error("Invalid parser flavor: $flavor; using default: $Preferences.PARSER_RIGID")
- delegate = new RigidParser()
- break
- }
- }
-
- ParseStatus parse(final Collection<String> buffer) {
- return delegate.parse(buffer)
- }
-}
-
-
-/**
- * A more rigid parser which catches more syntax errors, but also tends to barf on stuff that is really valid from time to time.
- */
-final class RigidParser implements Parsing {
- private static final Pattern ANNOTATION_PATTERN = Pattern.compile('^@[a-zA-Z_][a-zA-Z_0-9]*(.*)$')
- static final String SCRIPT_FILENAME = 'groovysh_parse'
-
- private final Logger log = Logger.create(this.class)
-
- @Override
- ParseStatus parse(final Collection<String> buffer) {
- assert buffer
-
- String source = buffer.join(Parser.NEWLINE)
-
- log.debug("Parsing: $source")
-
- SourceUnit parser
- Throwable error
-
- try {
- parser = SourceUnit.create(SCRIPT_FILENAME, source, /*tolerance*/ 1)
- parser.parse()
-
- log.debug('Parse complete')
-
- return new ParseStatus(ParseCode.COMPLETE)
- }
- catch (CompilationFailedException e) {
- // During a shell session often a user will hit enter without having completed a class definition
- // for the parser this means it will raise some kind of compilation exception.
- // The following code has to attempt to hide away all such exceptions that are due to the code being
- // incomplete, but show all exceptions due to the code being incorrect.
- // Unexpected EOF is most common for incomplete code, however there are several other situations
- // where the code is incomplete, but the Exception is raised without failedWithUnexpectedEOF().
-
- // FIXME: Seems like failedWithUnexpectedEOF() is not always set as expected, as in:
- //
- // class a { <--- is true here
- // def b() { <--- is false here :-(
- //
-
- if (parser.errorCollector.errorCount > 1 || !parser.failedWithUnexpectedEOF()) {
-
- // HACK: Super insane hack... we detect a syntax error, but might still ignore
- // it depending on the line ending
- if (ignoreSyntaxErrorForLineEnding(buffer[-1].trim()) ||
- isAnnotationExpression(e, buffer[-1].trim()) ||
- hasUnmatchedOpenBracketOrParen(source)) {
- log.debug("Ignoring parse failure; might be valid: $e")
- } else {
- error = e
- }
- }
- }
- catch (Throwable e) {
- error = e
- }
-
- if (error) {
- log.debug("Parse error: $error")
-
- return new ParseStatus(error)
- }
- log.debug('Parse incomplete')
- return new ParseStatus(ParseCode.INCOMPLETE)
- }
-
- static boolean ignoreSyntaxErrorForLineEnding(String line) {
- def final lineEndings = ['{', '[', '(', ',', '.', '-', '+', '/', '*', '%', '&', '|', '?', '<', '>', '=', ':', "'''", '"""', '\\']
- for (String lineEnding in lineEndings) {
- if (line.endsWith(lineEnding)) {
- return true
- }
- }
- return false
- }
-
- static boolean hasUnmatchedOpenBracketOrParen(String source) {
- if (!source) {
- return false
- }
- int parens = 0
- int brackets = 0
- for (ch in source) {
- switch (ch) {
- case '[': ++brackets; break;
- case ']': --brackets; break;
- case '(': ++parens; break;
- case ')': --parens; break;
- default:
- break
- }
- }
- return (brackets > 0 || parens > 0)
- }
-
- static boolean isAnnotationExpression(CompilationFailedException e, String line) {
- return e.getMessage().contains('unexpected token: @') && ANNOTATION_PATTERN.matcher(line).find()
- }
-}
-
-/**
- * Container for the parse code.
- */
-final class ParseCode {
- static final ParseCode COMPLETE = new ParseCode(0)
-
- static final ParseCode INCOMPLETE = new ParseCode(1)
-
- static final ParseCode ERROR = new ParseCode(2)
-
- final int code
-
- private ParseCode(int code) {
- this.code = code
- }
-
- @Override
- String toString() {
- return code
- }
-}
-
-/**
- * Container for parse status details.
- */
-final class ParseStatus {
- final ParseCode code
-
- final Throwable cause
-
- ParseStatus(final ParseCode code, final Throwable cause) {
- this.code = code
- this.cause = cause
- }
-
- ParseStatus(final ParseCode code) {
- this(code, null)
- }
-
- ParseStatus(final Throwable cause) {
- this(ParseCode.ERROR, cause)
- }
-}
-
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/Shell.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/Shell.groovy
deleted file mode 100644
index 61e0b721d7..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/Shell.groovy
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh
-
-import org.codehaus.groovy.runtime.FormatHelper
-import org.apache.groovy.groovysh.util.CommandArgumentParser
-import org.codehaus.groovy.tools.shell.IO
-import org.codehaus.groovy.tools.shell.util.Logger
-
-import static org.jline.jansi.AnsiRenderer.render
-
-/**
- * A simple shell for invoking commands from a command-line.
- */
-class Shell
-{
- protected final Logger log = Logger.create(this.class)
-
- final CommandRegistry registry = new CommandRegistry()
-
- final IO io
-
- Shell(final IO io) {
- assert(io != null)
-
- this.io = io
- }
-
- Shell() {
- this(new IO())
- }
-
- /**
- * @param line the line to parse
- * @param parsedArgs accumulate the rest of the line after the command
- */
- Command findCommand(final String line, List<String> parsedArgs = null) {
- assert line
-
- //
- // TODO: Introduce something like 'boolean Command.accepts(String)' to ask
- // commands if they can take the line?
- //
- // Would like to get '!66' to invoke the 'history recall' bits, but currently has
- // to be '! 66' for it to work with an alias like:
- //
- // alias ! history recall
- //
- // Or maybe allow commands to register specific syntax hacks into the registry?
- // then ask the registry for the command for a given line?
- //
-
- // command id is first word, unless empty
- Command command = null;
- List<String> linetokens = line.trim().tokenize()
- assert linetokens.size() > 0
-
- if (linetokens[0].length() > 0) {
- command = registry.find(linetokens[0])
- if (command != null && linetokens.size() > 1 && parsedArgs != null) {
- List<String> args = CommandArgumentParser.parseLine(line, parsedArgs == null ? 1 : -1)
- parsedArgs.addAll(args[1..-1])
- }
- }
- return command
- }
-
- boolean isExecutable(final String line) {
- return findCommand(line) != null
- }
-
- Object execute(final String line) {
- assert line
-
- List<String> args = []
- Command command = findCommand(line, args)
-
- def result = null
-
- if (command) {
-
- log.debug("Executing command($command.name): $command; w/args: $args")
- try {
- result = command.execute(args)
- } catch (CommandException e) {
- io.err.println(render("'@|bold,red $e.message|@"))
- }
- log.debug("Result: ${FormatHelper.toString(result)}")
- }
-
- return result
- }
-
- Command register(final Command command) {
- return registry.register(command)
- }
-
- /**
- * this should probably be deprecated
- */
- def leftShift(final String line) {
- return execute(line)
- }
-
-
- Command leftShift(final Command command) {
- return register(command)
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/ShellRunner.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/ShellRunner.groovy
deleted file mode 100644
index 3faa4fc3ea..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/ShellRunner.groovy
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh
-
-import org.codehaus.groovy.tools.shell.util.Logger
-
-/**
- * Support for running a {@link Shell}.
- */
-abstract class ShellRunner implements Runnable {
- protected final Logger log = Logger.create(this.class)
-
- final Shell shell
-
- boolean running = false
-
- boolean breakOnNull = true
-
- Closure errorHandler = { e ->
- log.debug(e)
-
- running = false
- }
-
- protected ShellRunner(final Shell shell) {
- assert(shell != null)
-
- this.shell = shell
- }
-
- @Override
- void run() {
- log.debug('Running')
-
- running = true
-
- while (running) {
- try {
- running = work()
- }
- catch (ExitNotification n) {
- throw n
- }
- catch (Throwable t) {
- log.debug("Work failed: $t", t)
-
- if (errorHandler) {
- try {
- errorHandler.call(t)
- } catch (Throwable t2) {
- errorHandler(new IllegalArgumentException("Error when handling error: $t.message"))
- errorHandler.call(t2)
- }
- }
- }
- }
-
- log.debug('Finished')
- }
-
- protected boolean work() {
- def line = readLine()
-
- if (log.debugEnabled) {
- log.debug("Read line: $line")
- }
-
- // Stop on null (maybe)
- if (line == null && breakOnNull) {
- return false // stop the loop
- }
-
- // Ignore empty lines
- if (line.trim().size() > 0) {
- shell << line
- }
-
- return true
- }
-
- protected abstract String readLine()
-}
-
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/antlr4/RelaxedParser.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/antlr4/RelaxedParser.groovy
deleted file mode 100644
index 112c663e74..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/antlr4/RelaxedParser.groovy
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.antlr4
-
-import org.antlr.v4.runtime.CharStream
-import org.antlr.v4.runtime.CharStreams
-import org.antlr.v4.runtime.CommonTokenStream
-import org.antlr.v4.runtime.ConsoleErrorListener
-import org.apache.groovy.groovysh.ParseCode
-import org.apache.groovy.groovysh.ParseStatus
-import org.apache.groovy.groovysh.Parser
-import org.apache.groovy.groovysh.Parsing
-import org.apache.groovy.parser.antlr4.GroovyLangLexer
-import org.apache.groovy.parser.antlr4.GroovySyntaxError
-import org.codehaus.groovy.tools.shell.util.Logger
-
-/**
- * A relaxed parser, which tends to allow more, but won't really catch valid syntax errors.
- */
-final class RelaxedParser implements Parsing {
- private final Logger log = Logger.create(this.class)
-
- @Override
- ParseStatus parse(final Collection<String> buffer) {
- assert buffer
- def source = buffer.join(Parser.NEWLINE)
-
- log.debug("Parsing: $source")
-
- try {
- CharStream charStream = CharStreams.fromReader(new StringReader(source))
- GroovyLangLexer lexer = new GroovyLangLexer(charStream)
- lexer.removeErrorListener(ConsoleErrorListener.INSTANCE)
- def tokenStream = new CommonTokenStream(lexer)
- tokenStream.fill()
-
- log.debug('Parse complete')
- return new ParseStatus(ParseCode.COMPLETE)
- } catch (GroovySyntaxError e) {
- if ((e.message.contains('Unexpected input: ') || e.message.contains('Unexpected character: ')) && !(
- e.message.contains("Unexpected input: '}'")
- || e.message.contains("Unexpected input: ')'")
- || e.message.contains("Unexpected input: ']'")))
- return new ParseStatus(ParseCode.INCOMPLETE)
- } catch (Exception e) {
- log.debug("Parse error: $e (${e.getClass().name})")
- return new ParseStatus(e)
- }
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/BrowseCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/BrowseCommand.groovy
deleted file mode 100644
index b62ad16565..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/BrowseCommand.groovy
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.commands
-
-import groovy.console.ui.ObjectBrowser
-import org.apache.groovy.groovysh.CommandSupport
-import org.apache.groovy.groovysh.Groovysh
-import org.apache.groovy.groovysh.util.SimpleCompleter
-import org.jline.reader.Completer
-
-import javax.swing.*
-import java.awt.*
-import java.util.List
-
-import static org.jline.jansi.AnsiRenderer.render
-
-/**
- * The 'browse' command.
- */
-class BrowseCommand extends CommandSupport {
- public static final String COMMAND_NAME = ':inspect'
-
- BrowseCommand(final Groovysh shell) {
- super(shell, COMMAND_NAME, ':n')
- }
-
- def lafInitialized = false
- def headless
-
- @Override
- protected List<Completer> createCompleters() {
- return [
- new BrowseCommandCompleter(binding),
- null
- ]
- }
-
- @Override
- Object execute(final List<String> args) {
- assert args != null
-
- log.debug("Inspecting w/args: $args")
-
- if (args.size() > 1) {
- fail(messages.format('error.unexpected_args', args.join(' ')))
- }
-
- def subject
-
- if (args.size() == 1) {
- subject = binding.variables[args[0]]
- } else {
- subject = binding.variables['_']
- }
-
- if (!subject) {
- io.out.println('Subject is null, false or empty; nothing to inspect') // TODO: i18n
- } else {
- // Only set LAF once.
- if (!lafInitialized) {
- lafInitialized = true
- try {
- UIManager.setLookAndFeel(UIManager.systemLookAndFeelClassName)
-
- // The setLAF doesn't throw a HeadlessException on Mac.
- // So try really creating a frame.
- new java.awt.Frame().dispose()
-
- headless = false
- } catch (HeadlessException he) {
- headless = true
- }
- }
-
- if (headless) {
- io.err.println(render("@|red ERROR:|@ Running in AWT Headless mode, 'inspect' is not available."))
- return
- }
-
- if (io.verbose) {
- io.out.println("Launching object browser to inspect: $subject") // TODO: i18n
- }
-
- ObjectBrowser.inspect(subject)
- }
- }
-}
-
-/**
- * Completer for the 'browse' command.
- */
-class BrowseCommandCompleter extends SimpleCompleter {
- private final Binding binding
-
- BrowseCommandCompleter(final Binding binding) {
- assert binding
- this.setWithBlank(false)
- this.binding = binding
- }
-
- @Override
- SortedSet<String> getCandidates() {
- SortedSet<String> set = new TreeSet<String>()
-
- binding.variables.keySet().each {
- set << it
- }
-
- return set
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/DisplayCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/DisplayCommand.groovy
deleted file mode 100644
index b7ea312d0d..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/DisplayCommand.groovy
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.commands
-
-import org.apache.groovy.groovysh.CommandSupport
-import org.apache.groovy.groovysh.Groovysh
-
-/**
- * The 'display' command. Displays the current buffer (e.g. while method declaration was not finished).
- */
-class DisplayCommand extends CommandSupport {
- public static final String COMMAND_NAME = ':display'
-
- DisplayCommand(final Groovysh shell) {
- super(shell, COMMAND_NAME, ':d')
- }
-
- @Override
- Object execute(final List<String> args) {
- assertNoArguments(args)
-
- if (buffer.isEmpty()) {
- io.out.println('Buffer is empty') // TODO: i18n
- } else {
- shell.displayBuffer(buffer)
- }
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/EditCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/EditCommand.groovy
deleted file mode 100644
index 1cce2dd58b..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/EditCommand.groovy
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.commands
-
-import org.apache.groovy.groovysh.CommandSupport
-import org.apache.groovy.groovysh.Groovysh
-import org.codehaus.groovy.tools.shell.util.Preferences
-
-/**
- * The 'edit' command. Opens Editor to write into the current Buffer.
- */
-class EditCommand
- extends CommandSupport
-{
- public static final String COMMAND_NAME = ':edit'
-
- EditCommand(final Groovysh shell) {
- super(shell, COMMAND_NAME, ':e')
- }
-
- ProcessBuilder getEditorProcessBuilder(final String editCommand, final String tempFilename) {
- def pb = new ProcessBuilder(editCommand, tempFilename)
-
- // GROOVY-6201: Editor should inherit I/O from the current process.
- // Fixed only for java >= 1.7 using new ProcessBuilder api
- pb.redirectErrorStream(true)
- def javaVer = Double.valueOf(System.getProperty('java.specification.version'))
- if (javaVer >= 1.7) {
- pb.redirectInput(ProcessBuilder.Redirect.INHERIT)
- pb.redirectOutput(ProcessBuilder.Redirect.INHERIT)
- }
-
- return pb
- }
-
- private String getEditorCommand() {
- def editor = Preferences.editor
-
- log.debug("Using editor: $editor")
-
- if (!editor) {
- fail("Unable to determine which editor to use; check \$EDITOR") // TODO: i18n
- }
-
- return editor
- }
-
- @Override
- Object execute(final List<String> args) {
- assertNoArguments(args)
-
- File file = File.createTempFile('groovysh-buffer', '.groovy')
- file.deleteOnExit()
-
- try {
- // Write the current buffer to a tmp file
- file.write(buffer.join(NEWLINE))
-
- //Try to launch the editor.
- log.debug("Executing: $editorCommand $file")
- def pb = getEditorProcessBuilder("$editorCommand", "$file")
- def p = pb.start()
-
- // Wait for it to finish
- log.debug("Waiting for process: $p")
- p.waitFor()
-
- log.debug("Editor contents: ${file.text}")
-
- replaceCurrentBuffer(file.readLines())
- }
- finally {
- file.delete()
- }
- }
-
- void replaceCurrentBuffer(List<String> contents) {
- // clear current buffer contents
- shell.buffers.clearSelected()
-
- // load editor contents into current buffer
- for (String line : contents) {
- shell.execute(line)
- }
- }
-
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/ExitCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/ExitCommand.groovy
deleted file mode 100644
index 4b34ce8de5..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/ExitCommand.groovy
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.commands
-
-import org.apache.groovy.groovysh.CommandSupport
-import org.apache.groovy.groovysh.ExitNotification
-import org.apache.groovy.groovysh.Groovysh
-
-/**
- * The 'exit' command.
- */
-class ExitCommand extends CommandSupport {
- public static final String COMMAND_NAME = ':exit'
-
- ExitCommand(final Groovysh shell) {
- super(shell, COMMAND_NAME, ':x')
-// alias(':quit', ':q')
- }
-
- @Override
- Object execute(final List<String> args) {
- assertNoArguments(args)
-
- if (io.verbose) {
- io.out.println(messages['info.bye'])
- }
-
- throw new ExitNotification(0)
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/GrabCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/GrabCommand.groovy
deleted file mode 100644
index 73966b47d8..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/GrabCommand.groovy
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.commands
-
-import groovy.grape.Grape
-import org.jline.reader.Completer
-import org.codehaus.groovy.tools.GrapeUtil
-import org.apache.groovy.groovysh.CommandSupport
-import org.apache.groovy.groovysh.Groovysh
-
-/**
- * The 'grab' command.
- */
-class GrabCommand extends CommandSupport {
-
- public static final String COMMAND_NAME = ':grab'
- //private Printer printer
-
- GrabCommand(Groovysh shell) {
- super(shell, COMMAND_NAME, ':g')
- }
-
- @Override protected List<Completer> createCompleters() { [ null ] }
-
- @Override Object execute(List<String> args) {
- if (args.size() == 1 && args[0] in ['-l', '--list']) {
- // TODO use printer
- Grape.instance.enumerateGrapes().each { group, nv ->
- shell.runner.reader.terminal.println group
- nv.each {name, versions ->
- shell.runner.reader.terminal.println " $name:${versions[0]}"
- }
- }
- return
- }
- validate(args)
- grab(dependency(args))
- shell.packageHelper.reset()
- }
-
- private void validate(List<String> args) {
- if ( args?.size() != 1 ||
- !( args[0] ==~ /^(\w|\.|-)+:(\w|\.|-)+(\w|\.|-)(:+(\w|\.|-|\*)+){0,2}$/ ) ) {
- fail("usage: @|bold ${COMMAND_NAME}|@ ${usage}")
- }
- }
-
- private String dependency(List<String> args) {
- validate(args)
- args[0]
- }
-
- private Map<String, Object> dependencyMap(String dependency) {
- GrapeUtil.getIvyParts(dependency)
- }
-
- private void grab(String dependency) {
- Grape.grab([classLoader: shell.interp.classLoader.parent,
- refObject: shell.interp],
- dependencyMap(dependency))
- }
-
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/HelpCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/HelpCommand.groovy
deleted file mode 100644
index d754ee828f..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/HelpCommand.groovy
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.commands
-
-import org.jline.reader.Completer
-import org.apache.groovy.groovysh.Command
-import org.apache.groovy.groovysh.CommandSupport
-import org.apache.groovy.groovysh.Groovysh
-import org.apache.groovy.groovysh.completion.CommandNameCompleter
-
-import static org.jline.jansi.AnsiRenderer.render
-
-/**
- * The 'help' command.
- */
-class HelpCommand extends CommandSupport { // TODO for this file: further i18n
-
- public static final String COMMAND_NAME = ':help'
-
- HelpCommand(final Groovysh shell) {
- super(shell, COMMAND_NAME, ':h')
-
-// alias('?', ':?')
- }
-
- protected List<Completer> createCompleters() {
- return [
- new CommandNameCompleter(registry, false),
- null
- ]
- }
-
- @Override
- Object execute(final List<String> args) {
- assert args != null
-
- if (args.size() > 1) {
- fail(messages.format('error.unexpected_args', args.join(' ')))
- }
-
- if (args.size() == 1) {
- help(args[0])
- }
- else {
- list()
- }
- }
-
- private void help(final String name) {
- assert name
-
- Command command = registry.find(name)
- if (!command) {
- fail("No such command: $name")
- }
-
- io.out.println()
- io.out.println(render("usage: @|bold ${command.name}|@ $command.usage"))
- io.out.println()
- io.out.println(command.help)
- io.out.println()
- }
-
- private void list() {
- // Figure out the max command name and shortcut length dynamically
- int maxName = 0
- int maxShortcut = 0
-
- for (Command command in registry.commands()) {
- if (command.hidden) {
- continue
- }
-
- if (command.name.size() > maxName) {
- maxName = command.name.size()
- }
-
- if (command.shortcut.size() > maxShortcut) {
- maxShortcut = command.shortcut.size()
- }
- }
-
- io.out.println()
- io.out.println(render('For information about @|green Groovy|@, visit:'))
- io.out.println(render(' @|cyan http://groovy-lang.org|@'))
- io.out.println()
-
- io.out.println('Available commands:')
-
- for (Command command in registry.commands()) {
- if (command.hidden) {
- continue
- }
-
- def n = command.name.padRight(maxName, ' ')
- def s = command.shortcut.padRight(maxShortcut, ' ')
- def d = command.description
-
- io.out.println(render(" @|bold ${n}|@ (@|bold ${s}|@) $d"))
- }
-
- io.out.println()
- io.out.println('For help on a specific command type:')
- io.out.println(render(' :help @|bold command|@ '))
- io.out.println()
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/HistoryCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/HistoryCommand.groovy
deleted file mode 100644
index 7d4dcc464d..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/HistoryCommand.groovy
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.commands
-
-import org.jline.reader.History
-import org.apache.groovy.groovysh.ComplexCommandSupport
-import org.apache.groovy.groovysh.Groovysh
-import org.apache.groovy.groovysh.util.SimpleCompleter
-
-import static org.jline.jansi.AnsiRenderer.render
-
-/**
- * The 'history' command.
- */
-class HistoryCommand extends ComplexCommandSupport {
-
- public static final String COMMAND_NAME = ':history'
-
- HistoryCommand(final Groovysh shell) {
- super(shell, COMMAND_NAME, ':H', [ 'show', 'clear', 'flush', 'recall' ], 'show')
- }
-
- @Override
- protected List createCompleters() {
- def loader = {
- def list = []
- list.addAll(functions)
-
- return list
- }
-
- SimpleCompleter subCommandsCompleter = new SimpleCompleter(loader)
- subCommandsCompleter.setWithBlank(false)
- return [
- subCommandsCompleter,
- null
- ]
- }
-
- @Override
- Object execute(List<String> args) {
- if (!history) {
- fail('Shell does not appear to be interactive; Can not query history')
- }
-
- super.execute(args)
-
- // Don't return anything
- return null
- }
-
- /**
- * history show - shows a list of indexes and past commands
- */
- def do_show = {
- Iterator<History.Entry> histIt = history.iterator()
- while (histIt.hasNext()) {
- History.Entry next = histIt.next()
- if (next) {
- io.out.println(render(" @|bold ${next.index().toString().padLeft(3, ' ')}|@ ${next.value()}"))
- }
- }
- }
-
- def do_clear = {
- history.clear()
-
- if (io.verbose) {
- io.out.println('History cleared')
- }
- }
-
- def do_flush = {
- history.flush()
-
- if (io.verbose) {
- io.out.println('History flushed')
- }
- }
-
- /**
- * history recall - serves to rerun a command from the history by its index.
- * There is a moving window of indexes, so the first valid index will usually be greater than zero.
- */
- def do_recall = {args ->
- String line
-
- if (!args || ((List)args).size() != 1) {
- fail('History recall requires a single history identifier')
- }
-
- String ids = ((List<String>)args)[0]
-
- //
- // FIXME: This won't work as desired because the history shifts when we run recall and could internally shift more from alias redirection
- //
-
- try {
- int id = Integer.parseInt(ids)
- if (shell.historyFull) {
- // if history was full before execution of the command, then the recall command itself
- // has been added to history before it actually gets executed
- // so we need to shift by one
- id--
- }
-
- Iterator<History.Entry> listEntryIt = history.iterator()
- if (listEntryIt.hasNext()) {
- History.Entry next = listEntryIt.next()
- if (id < next.index() -1) {
- // not using id on purpose, as might be decremented
- fail("Unknown index: $ids")
- } else if (id == next.index() -1) {
- line = shell.evictedLine
- } else if (next.index() == id) {
- line = next.value()
- } else {
- while (listEntryIt.hasNext()) {
- next = listEntryIt.next()
- if (next.index() == id) {
- line = next.value()
- break
- }
- }
- }
- }
-
-
- } catch (NumberFormatException e) {
- fail("Invalid history identifier: $ids", e)
- }
-
- log.debug("Recalling history item #$ids: $line")
-
- if (line) {
- return shell.execute(line)
- }
- }
-
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/ImportCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/ImportCommand.groovy
deleted file mode 100644
index ff74f71654..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/ImportCommand.groovy
+++ /dev/null
@@ -1,307 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.commands
-
-import groovy.transform.CompileStatic
-import org.jline.reader.Candidate
-import org.jline.reader.Completer
-import org.jline.reader.LineReader
-import org.jline.reader.ParsedLine
-import org.jline.reader.impl.completer.AggregateCompleter
-import org.jline.reader.impl.completer.NullCompleter
-import org.jline.reader.impl.completer.StringsCompleter
-import org.apache.groovy.groovysh.CommandSupport
-import org.apache.groovy.groovysh.Evaluator
-import org.apache.groovy.groovysh.Groovysh
-import org.apache.groovy.groovysh.Interpreter
-import org.apache.groovy.groovysh.completion.antlr4.ReflectionCompleter
-import org.apache.groovy.groovysh.completion.ReflectionCompletionCandidate
-import org.apache.groovy.groovysh.completion.StricterArgumentCompleter
-import org.apache.groovy.groovysh.util.PackageHelper
-import org.codehaus.groovy.control.CompilationFailedException
-import org.codehaus.groovy.control.ResolveVisitor
-import org.codehaus.groovy.tools.shell.util.Logger
-
-import java.util.regex.Pattern
-
-/**
- * The 'import' command.
- */
-class ImportCommand extends CommandSupport {
-
- /**
- * pattern used to validate the arguments to the import command,
- * which proxies the Groovy import statement
- * chars, digits, underscore, dot, star
- */
- private static final Pattern IMPORTED_ITEM_PATTERN = ~'[a-zA-Z0-9_. *]+;?$'
-
- ImportCommand(final Groovysh shell) {
- super(shell, 'import', ':i')
- }
-
- @Override
- Completer getCompleter() {
- // need a different completer setup due to static import
- Completer impCompleter = new StringsCompleter(name + ' ', shortcut + ' ')
- Completer asCompleter = new StringsCompleter('as ')
- Completer nullCompleter = NullCompleter.INSTANCE
- PackageHelper packageHelper = shell.packageHelper
- Interpreter interp = shell.interp
- Completer nonStaticCompleter = new StricterArgumentCompleter([
- impCompleter,
- new ImportCompleter(packageHelper, interp, false),
- asCompleter,
- nullCompleter])
- Completer staticCompleter = new StricterArgumentCompleter([
- impCompleter,
- new StringsCompleter('static '),
- new ImportCompleter(packageHelper, interp, true),
- asCompleter,
- nullCompleter])
- Collection<Completer> argCompleters = [
- nonStaticCompleter,
- staticCompleter]
- return new AggregateCompleter(argCompleters)
-
- }
-
- String simpleName(String importSpec) {
- int index = importSpec.lastIndexOf(' as ')
- if (index >= 0)
- return importSpec.substring(index + 4)
- index = importSpec.lastIndexOf('.')
- if (index >= 0)
- return importSpec.substring(index + 1)
- importSpec
- }
-
- Object execute(final List<String> args) {
- assert args != null
-
- if (args.isEmpty()) {
- fail("@|red Invalid arguments.|@ Command @|cyan 'import'|@ requires one or more arguments. Use @|magenta :show imports|@ to show existing imports.")
- }
-
- def importSpec = args.join(' ')
-
- // technically java conventions don't allow numerics at the start of package/class names so the regex below
- // is a bit lacking. this approach works reasonably well ->
- // "(\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*\\.)+((\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart})|\\*)+;?$"
- // but there's something preventing it from working when class names end in a "d" or "D" like
- // "java.awt.TextField" so it is not implemented as such here. Perhaps this could be made to be more
- // intelligent if someone could figure out why that is happening or could write a nicer batch of regex to
- // solve the problem
- if (!(importSpec.matches(IMPORTED_ITEM_PATTERN))) {
- def msg = "Invalid import definition: '${importSpec}'"
- log.debug(msg)
- fail(msg)
- }
- // remove last semicolon
- importSpec = importSpec.replace(';', '')
-
- def buff = ['import ' + importSpec]
- buff << 'def dummy = false'
-
- def type
- try {
- type = classLoader.parseClass(buff.join(NEWLINE))
-
- def sn = simpleName(importSpec)
-
- if (sn == '*') {
- if (imports.remove(importSpec)) {
- log.debug('Removed duplicate import from list')
- }
- } else {
- // remove duplicates
- imports.removeAll{
- def dup = simpleName(it) == sn
- if (dup) {
- log.debug("Removed duplicate import: $it")
- }
- dup
- }
-
- // avoid class clashes
- def classNames = classLoader.loadedClasses*.simpleName
-
- if (classNames.contains(sn)) {
- def msg = "Invalid import definition: '${importSpec}'; conflicts with existing class: $sn" // TODO: i18n
- log.debug(msg)
- fail(msg)
- }
- }
-
- log.debug("Adding import: $importSpec")
-
- imports.add(importSpec)
- return imports.join(', ')
- }
- catch (CompilationFailedException e) {
- def msg = "Invalid import definition: '${importSpec}'; reason: $e.message" // TODO: i18n
- log.debug(msg, e)
- fail(msg)
- }
- finally {
- // Remove the class generated while testing the import syntax
- if (type?.name) {
- classLoader.removeClassCacheEntry(type.name)
- }
- }
- }
-}
-
-class ImportCompleter implements Completer {
-
- protected final Logger log = Logger.create(ImportCompleter)
-
- PackageHelper packageHelper
- Groovysh shell
-
- /*
- * The following rules do not need to work for all thinkable situations, just for all reasonable situations.
- * In particular the underscore and dollar signs in Class or method names usually indicate something internal,
- * which we intentionally want to hide in tab completion
- */
- // matches fully qualified class names with dot at the end
- private static final Pattern QUALIFIED_CLASS_DOT_PATTERN = ~/^[a-z_]{1}[a-z0-9_]*(\.[a-z0-9_]*)*\.[A-Z][^.]*\.$/
- // matches empty, package names or fully qualified class names
- private static final Pattern PACK_OR_CLASSNAME_PATTERN = ~/^([a-z_]{1}[a-z0-9_]*(\.[a-z0-9_]*)*(\.[A-Z][^.]*)?)?$/
- // matches empty, package names or fully qualified class names without special symbols
- private static final Pattern PACK_OR_SIMPLE_CLASSNAME_PATTERN = ~'^([a-z_]{1}[a-z0-9_]*(\\.[a-z0-9_]*)*(\\.[A-Z][^.\$_]*)?)?\$'
- // matches empty, package names or fully qualified class names or fully qualified method names
- private static final Pattern PACK_OR_CLASS_OR_METHODNAME_PATTERN = ~'^([a-z_]{1}[a-z0-9.]*(\\.[a-z0-9_]*)*(\\.[A-Z][^.\$_]*(\\.[a-zA-Z0-9_]*)?)?)?\$'
- private static final Pattern LOWERCASE_IMPORT_ITEM_PATTERN = ~/^[a-z0-9.]+$/
-
- final boolean staticImport
- final Evaluator interpreter
-
-
- ImportCompleter(final PackageHelper packageHelper, final Evaluator interp, final boolean staticImport) {
- this.packageHelper = packageHelper
- this.staticImport = staticImport
- this.interpreter = interp
- this.shell = shell
- }
-
- @Override
- @CompileStatic
- void complete(LineReader reader, ParsedLine line, List<Candidate> result) {
- def buffer = reader.buffer
- def cursor = line.cursor()
- String currentImportExpression = buffer ? buffer.substring(0, cursor) : ''
- if (staticImport) {
- if (!(currentImportExpression.matches(PACK_OR_CLASS_OR_METHODNAME_PATTERN))) {
- return
- }
- } else {
- if (!(currentImportExpression.matches(PACK_OR_SIMPLE_CLASSNAME_PATTERN))) {
- return
- }
- }
- if (currentImportExpression.contains('..')) {
- return
- }
-
- if (currentImportExpression.endsWith('.')) {
- // no upper case?
- if (currentImportExpression.matches(LOWERCASE_IMPORT_ITEM_PATTERN)) {
- Set<String> classnames = packageHelper.getContents(currentImportExpression[0..-2])
- if (classnames) {
- if (staticImport) {
- addAll(result, classnames.collect{ String it -> it + '.' })
- } else {
- addAll(result, classnames.collect({ String it -> addDotOrBlank(it) }))
- }
- }
- if (!staticImport) {
- add(result, '* ')
- }
- return //currentImportExpression.length()
- } else if (staticImport && currentImportExpression.matches(QUALIFIED_CLASS_DOT_PATTERN)) {
- Class clazz = interpreter.evaluate([currentImportExpression[0..-2]]) as Class
- if (clazz != null) {
- Collection<ReflectionCompletionCandidate> members = ReflectionCompleter.getPublicFieldsAndMethods(clazz, '')
- addAll(result, members.collect({ ReflectionCompletionCandidate it -> it.value.replace('(', '').replace(')', '') + ' ' }))
- }
- add(result, '* ')
- return //currentImportExpression.length()
- }
- return
- } // endif startswith '.', we have a prefix
-
- String prefix
- int lastDot = currentImportExpression.lastIndexOf('.')
- if (lastDot == -1) {
- prefix = currentImportExpression
- } else {
- prefix = currentImportExpression.substring(lastDot + 1)
- }
- String baseString = currentImportExpression.substring(0, Math.max(lastDot, 0))
-
- // expression could be for Classname, or for static methodname
- if (currentImportExpression.matches(PACK_OR_CLASSNAME_PATTERN)) {
- Set<String> candidates = packageHelper.getContents(baseString)
- if (candidates == null || candidates.size() == 0) {
- // At least give standard package completion, else static keyword is highly annoying
- Collection<String> standards = ResolveVisitor.DEFAULT_IMPORTS.findAll({ String it -> it.startsWith(currentImportExpression) })
- if (standards) {
- addAll(result, standards)
- return //0
- }
- return
- }
-
- log.debug(prefix)
- Collection<String> matches = candidates.findAll({ String it -> it.startsWith(prefix) })
- if (matches) {
- addAll(result, matches.collect({ String it -> addDotOrBlank(it) }))
- return //lastDot <= 0 ? 0 : lastDot + 1
- }
- } else if (staticImport) {
- Class clazz = interpreter.evaluate([baseString]) as Class
- if (clazz != null) {
- Collection<ReflectionCompletionCandidate> members = ReflectionCompleter.getPublicFieldsAndMethods(clazz, prefix)
- if (members) {
- addAll(result, members.collect({ ReflectionCompletionCandidate it -> it.value.replace('(', '').replace(')', '') + ' ' }))
- return //lastDot <= 0 ? 0 : lastDot + 1
- }
- }
- }
- return
- }
-
- private static void addAll(List<Candidate> result, List<String> strings) {
- for (String s : strings) {
- result.add(new Candidate(s))
- }
- }
-
- private static void add(List<Candidate> result, String s) {
- result.add(new Candidate(s))
- }
-
- private static String addDotOrBlank(final String it) {
- if (it[0] in 'A'..'Z') {
- return it + ' '
- }
- return it + '.'
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/InspectCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/InspectCommand.groovy
deleted file mode 100644
index 649c9c1aee..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/InspectCommand.groovy
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.commands
-
-import groovy.console.ui.ObjectBrowser
-import org.apache.groovy.groovysh.jline.GroovyEngine
-import org.apache.groovy.groovysh.jline.ObjectInspector
-import org.jline.builtins.Completers.OptDesc
-import org.jline.builtins.Completers.OptionCompleter
-import org.jline.console.CmdDesc
-import org.jline.console.CommandInput
-import org.jline.console.CommandMethods
-import org.jline.console.Printer
-import org.jline.reader.Completer
-import org.jline.reader.impl.completer.ArgumentCompleter
-import org.jline.reader.impl.completer.NullCompleter
-import org.jline.reader.impl.completer.StringsCompleter
-import org.jline.utils.AttributedString
-
-class InspectCommand {
- private static final String DEFAULT_NANORC_VALUE = "classpath:/nanorc/gron.nanorc"
- private final GroovyEngine engine
- private final Printer printer
- private boolean consoleUi
-
- InspectCommand(GroovyEngine engine, Printer printer) {
- this.engine = engine
- this.printer = printer
- try {
- Class.forName("groovy.console.ui.ObjectBrowser")
- consoleUi = true
- } catch (Exception e) {
- // ignore
- }
-
- commandExecute.put(Command.INSPECT, new CommandMethods(this::inspect, this::inspectCompleter));
- commandExecute.put(Command.CONSOLE, new CommandMethods(this::console, this::defaultCompleter));
- commandExecute.put(Command.GRAB, new CommandMethods(this::grab, this::defaultCompleter));
- commandExecute.put(Command.CLASSLOADER, new CommandMethods(this::classLoader, this::classloaderCompleter));
- registerCommands(commandName, commandExecute);
- commandDescs.put(Command.INSPECT, inspectCmdDesc());
- commandDescs.put(Command.CONSOLE, consoleCmdDesc());
- commandDescs.put(Command.GRAB, grabCmdDesc());
- commandDescs.put(Command.CLASSLOADER, classLoaderCmdDesc());
- }
-
- Object inspect(CommandInput input) {
- if (input.xargs().length == 0) {
- return null;
- }
- if (input.args().length > 2) {
- throw new IllegalArgumentException("Wrong number of command parameters: " + input.args().length);
- }
- int idx = optionIdx(input.args())
- String option = idx < 0 ? "--info" : input.args()[idx]
- if (option.equals("-?") || option.equals("--help")) {
- printer.println(helpDesc(Command.INSPECT))
- return null
- }
- int id = 0;
- if (idx >= 0) {
- id = idx == 0 ? 1 : 0
- }
- if (input.args().length < id + 1) {
- throw new IllegalArgumentException("Wrong number of command parameters: " + input.args().length)
- }
- try {
- Object obj = input.xargs()[id]
- ObjectInspector inspector = new ObjectInspector(obj)
- Object out = null
- Map<String, Object> options = new HashMap<>()
- if (option.equals("-m") || option.equals("--methods")) {
- out = inspector.methods()
- options.put(Printer.COLUMNS, ObjectInspector.METHOD_COLUMNS)
- } else if (option.equals("-n") || option.equals("--metaMethods")) {
- out = inspector.metaMethods()
- options.put(Printer.COLUMNS, ObjectInspector.METHOD_COLUMNS)
- } else if (option.equals("-i") || option.equals("--info")) {
- out = inspector.properties()
- options.put(Printer.VALUE_STYLE, engine.groovyOption(GroovyEngine.NANORC_VALUE, DEFAULT_NANORC_VALUE))
- } else if (consoleUi && (option.equals("-g") || option.equals("--gui"))) {
- ObjectBrowser.inspect(obj)
- } else {
- throw new IllegalArgumentException("Unknown option: " + option)
- }
- options.put(Printer.SKIP_DEFAULT_OPTIONS, true)
- options.put(Printer.MAX_DEPTH, 1)
- options.put(Printer.INDENTION, 4)
- printer.println(options, out)
- } catch (Exception e) {
- saveException(e)
- }
- return null
- }
-
- private CmdDesc inspectCmdDesc() {
- def optDescs = [:]
- optDescs.put("-? --help", doDescription("Displays command help"))
- if (consoleUi) {
- optDescs.put("-g --gui", doDescription("Launch object browser"))
- }
- optDescs.put("-i --info", doDescription("Object class info"))
- optDescs.put("-m --methods", doDescription("List object methods"))
- optDescs.put("-n --metaMethods", doDescription("List object metaMethods"))
- CmdDesc out = new CmdDesc(new ArrayList<>(), optDescs)
- List<AttributedString> mainDesc = new ArrayList<>()
- List<String> info = new ArrayList<>()
- info.add("Display object info on terminal/in browser")
- commandInfos.put(Command.INSPECT, info)
- mainDesc.add(new AttributedString("inspect [OPTION] OBJECT"))
- out.setMainDesc(mainDesc)
- out.setHighlighted(false)
- return out
- }
-
- private List<AttributedString> doDescription(String description) {
- [new AttributedString(description)]
- }
-
- private int optionIdx(String[] args) {
- int out = 0
- for (String a : args) {
- if (a.startsWith("-")) {
- return out
- }
- out++
- }
- return -1
- }
-
- private List<String> variables() {
- engine.find(null).keySet().collect{'$' + it }
- }
-
- private List<OptDesc> compileOptDescs(String command) {
- List<OptDesc> out = new ArrayList<>()
-// Command cmd = Command.valueOf(command.toUpperCase());
- for (Map.Entry<String, List<AttributedString>> entry :
- commandDescs.get(cmd).getOptsDesc().entrySet()) {
- String[] option = entry.getKey().split("\\s+");
- String desc = entry.getValue().get(0).toString();
- if (option.length == 2) {
- out.add(new OptDesc(option[0], option[1], desc));
- } else if (option[0].charAt(1) == '-') {
- out.add(new OptDesc(null, option[0], desc));
- } else {
- out.add(new OptDesc(option[0], null, desc));
- }
- }
- return out;
- }
-
- private List<Completer> inspectCompleter(String command) {
- [new ArgumentCompleter(
- NullCompleter.INSTANCE,
- new OptionCompleter(
- Arrays.asList(new StringsCompleter(this::variables), NullCompleter.INSTANCE),
- this::compileOptDescs,
- 1))]
- }
-
- private List<Completer> defaultCompleter(String command) {
- [new ArgumentCompleter(
- NullCompleter.INSTANCE, new OptionCompleter(NullCompleter.INSTANCE, this::compileOptDescs, 1))]
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/LoadCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/LoadCommand.groovy
deleted file mode 100644
index cca596cbf4..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/LoadCommand.groovy
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.commands
-
-import org.jline.reader.Completer
-import org.apache.groovy.groovysh.CommandSupport
-import org.apache.groovy.groovysh.Groovysh
-import org.apache.groovy.groovysh.completion.FileNameCompleter
-
-/**
- * The 'load' command.
- */
-class LoadCommand extends CommandSupport {
- public static final String COMMAND_NAME = ':load'
-// private static final boolean isWin = Configuration.isWindows()
-
- LoadCommand(final Groovysh shell) {
- super(shell, COMMAND_NAME, ':l')
-// alias('.', ':.')
- }
-
- @Override
- protected List<Completer> createCompleters() {
- return [new FileNameCompleter(true, true, true)]
- }
-
- @Override
- Object execute(final List<String> args) {
- assert args != null
-
- if (args.size() == 0) {
- fail("Command '$COMMAND_NAME' requires at least one argument") // TODO: i18n
- }
-
- for (source in args) {
- URL url
-// if (isWin) {
-// source = source.replaceAll('\\\\ ', ' ')
-// }
- log.debug("Attempting to load: \"$source\"")
- try {
- url = new URL("$source")
- }
- catch (MalformedURLException e) {
- def file = new File("$source")
- if (!file.exists()) {
- fail("File not found: \"$file\"") // TODO: i18n
- }
- url = file.toURI().toURL()
- }
-
- load(url)
- }
- }
-
- void load(final URL url) {
- assert url != null
-
- if (io.verbose) {
- io.out.println("Loading: $url")
- }
-
- url.eachLine { String it, int lineNumber ->
- if (lineNumber == 1 && it.startsWith('#!')) {
- return
- }
- shell << it as String
- }
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/PurgeCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/PurgeCommand.groovy
deleted file mode 100644
index 54b94109ab..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/PurgeCommand.groovy
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.commands
-
-import org.apache.groovy.groovysh.ComplexCommandSupport
-import org.apache.groovy.groovysh.Groovysh
-import org.codehaus.groovy.tools.shell.util.Preferences
-
-/**
- * The 'purge' command.
- */
-class PurgeCommand extends ComplexCommandSupport {
- public static final String COMMAND_NAME = ':purge'
-
- PurgeCommand(final Groovysh shell) {
- super(shell, COMMAND_NAME, ':p', [ 'variables', 'classes', 'imports', 'preferences', 'all' ])
- }
-
- def do_variables = {
- if (variables.isEmpty()) {
- io.out.println('No variables defined') // TODO: i18n
- }
- else {
- variables.clear()
-
- if (io.verbose) {
- io.out.println('Custom variables purged') // TODO: i18n
- }
- }
- }
-
- def do_classes = {
- if (classLoader.loadedClasses.size() == 0) {
- io.out.println('No classes have been loaded') // TODO: i18n
- }
- else {
- classLoader.clearCache()
-
- if (io.verbose) {
- io.out.println('Loaded classes purged') // TODO: i18n
- }
- }
- }
-
- def do_imports = {
- if (imports.isEmpty()) {
- io.out.println('No custom imports have been defined') // TODO: i18n
- }
- else {
- imports.clear()
-
- if (io.verbose) {
- io.out.println('Custom imports purged') // TODO: i18n
- }
- }
- }
-
- def do_preferences = {
- Preferences.clear()
-
- if (io.verbose) {
- io.out.println('Preferences purged') // TODO: i18n
- }
- }
-}
-
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/RecordCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/RecordCommand.groovy
deleted file mode 100644
index ac80286d9b..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/RecordCommand.groovy
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.commands
-
-import org.codehaus.groovy.runtime.FormatHelper
-import org.apache.groovy.groovysh.ComplexCommandSupport
-import org.apache.groovy.groovysh.Groovysh
-
-/**
- * The 'record' command.
- */
-class RecordCommand extends ComplexCommandSupport {
- public static final String COMMAND_NAME = ':record'
-
- RecordCommand(final Groovysh shell) {
- super(shell, COMMAND_NAME, ':r', [ 'start', 'stop', 'status' ], 'status')
-
- addShutdownHook {
- if (isRecording()) {
- this.do_stop()
- }
- }
- }
-
- private File file
-
- private PrintWriter writer
-
- boolean isRecording() {
- return file != null
- }
-
- def recordInput(final String line) {
- assert line != null
-
- if (isRecording()) {
- writer.println(line)
- writer.flush()
- }
- }
-
- def recordResult(final Object result) {
- // result maybe null
-
- if (isRecording()) {
- writer.println("// RESULT: ${FormatHelper.toString(result)}")
- writer.flush()
- }
- }
-
- def recordError(final Throwable cause) {
- assert cause != null
-
- if (isRecording()) {
- writer.println("// ERROR: $cause")
-
- cause.stackTrace.each {
- writer.println("// $it")
- }
-
- writer.flush()
- }
- }
-
- def do_start = {List<String> args ->
- if (isRecording()) {
- fail("Already recording to: \"$file\"")
- }
-
- if (args.size() == 0) {
- file = File.createTempFile('groovysh-', '.txt')
- } else if (args.size() == 1) {
- file = new File(args[0] as String)
- } else {
- fail('Too many arguments. Usage: record start [filename]')
- }
-
- if (file.parentFile) file.parentFile.mkdirs()
-
- writer = file.newPrintWriter()
- writer.println('// OPENED: ' + new Date())
- writer.flush()
-
- io.out.println("Recording session to: \"$file\"")
-
- return file
- }
-
- def do_stop = {
- if (!isRecording()) {
- fail('Not recording')
- }
-
- writer.println('// CLOSED: ' + new Date())
- writer.flush()
-
- writer.close()
- writer = null
-
- io.out.println("Recording stopped; session saved as: \"$file\" (${file.length()} bytes)")
-
- def tmp = file
- file = null
-
- return tmp
- }
-
- def do_status = {
- if (!isRecording()) {
- io.out.println('Not recording')
-
- return null
- }
-
- io.out.println("Recording to file: \"$file\" (${file.length()} bytes)")
-
- return file
- }
-}
-
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/RegisterCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/RegisterCommand.groovy
deleted file mode 100644
index 53f5ac0042..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/RegisterCommand.groovy
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.commands
-
-import org.apache.groovy.groovysh.Command
-import org.apache.groovy.groovysh.CommandSupport
-import org.apache.groovy.groovysh.Groovysh
-
-/**
- * The 'register' command.
- * Registers a class as a new groovysh command.
- * Requires the command to have matching constructors (shell) or (shell, name, alias).
- */
-class RegisterCommand extends CommandSupport {
- static final String COMMAND_NAME = ':register'
-
- RegisterCommand(final Groovysh shell) {
- super(shell, COMMAND_NAME, ':rc')
- }
-
- @Override
- Object execute(final List<String> args) {
- assert args != null
-
- if (args.size() < 1) {
- fail("Command '$COMMAND_NAME' requires at least 1 arguments") // TODO: i18n
- }
-
- String classname = args.get(0)
-
- Class type = classLoader.loadClass(classname)
-
- Command command = null
-
- if (args.size() == 1) { // use default name
- command = type.newInstance(shell) as Command
- }
- else if (args.size() == 2) { // pass name to completer
- command = type.newInstance(shell, args.get(1), null) as Command
- }
- else if (args.size() == 3) { // pass name, alias to completer
- command = type.newInstance(shell, args.get(1), args.get(2)) as Command
- }
-
- def oldcommand = registry[command.name] // let's prevent collisions
-
- if (oldcommand) {
- fail("Can not rebind command: ${command.name}") // TODO: i18n
- }
-
- if (log.debugEnabled) {
- log.debug("Created command '${command.name}': $command")
- }
-
- command = shell << command
-
- if (shell.runner) {
- shell.runner.completer.add(command)
- }
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/ResetCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/ResetCommand.groovy
deleted file mode 100644
index 19139ea605..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/ResetCommand.groovy
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.commands
-
-import org.apache.groovy.groovysh.CommandSupport
-import org.apache.groovy.groovysh.Groovysh
-
-/**
- * The 'reset' command.
- */
-class ResetCommand extends CommandSupport {
- public static final String COMMAND_NAME = ':reset'
-
- ResetCommand(final Groovysh shell) {
- super(shell, COMMAND_NAME, ':R')
- }
-
- @Override
- Object execute(final List<String> args) {
- assertNoArguments(args)
- buffer.clear()
- if (io.verbose) {
- io.out.println('Buffer cleared') // TODO: i18n
- }
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/SaveCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/SaveCommand.groovy
deleted file mode 100644
index 99fbba3880..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/SaveCommand.groovy
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.commands
-
-import org.apache.groovy.groovysh.CommandSupport
-import org.apache.groovy.groovysh.Groovysh
-import org.jline.builtins.Completers
-import org.jline.reader.Completer
-
-/**
- * The 'save' command.
- */
-class SaveCommand extends CommandSupport {
- public static final String COMMAND_NAME = ':save'
-
- SaveCommand(final Groovysh shell) {
- super(shell, COMMAND_NAME, ':s')
- }
-
- @Override
- protected List<Completer> createCompleters() {
- return [
- new Completers.FileNameCompleter(),
- null
- ]
- }
-
- @Override
- Object execute(final List<String> args) {
- assert args != null
-
- if (args.size() != 1) {
- fail("Command '$COMMAND_NAME' requires a single file argument") // TODO: i18n
- }
-
- if (buffer.isEmpty()) {
- io.out.println('Buffer is empty') // TODO: i18n
- return
- }
-
- //
- // TODO: Support special '-' file to simply dump text to io.out
- //
-
- def file = new File("${args[0]}")
-
- if (io.verbose) {
- io.out.println("Saving current buffer to file: \"$file\"") // TODO: i18n
- }
-
- def dir = file.parentFile
- if (dir && !dir.exists()) {
- log.debug("Creating parent directory path: \"$dir\"")
-
- dir.mkdirs()
- }
-
- file.write(buffer.join(NEWLINE))
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/SetCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/SetCommand.groovy
deleted file mode 100644
index 9fada227d4..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/SetCommand.groovy
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.commands
-
-import org.apache.groovy.groovysh.CommandSupport
-import org.apache.groovy.groovysh.Groovysh
-import org.apache.groovy.groovysh.util.PackageHelper
-import org.apache.groovy.groovysh.util.SimpleCompleter
-import org.codehaus.groovy.tools.shell.util.Preferences
-import org.jline.reader.Completer
-
-/**
- * The 'set' command, used to set preferences.
- */
-class SetCommand extends CommandSupport {
- public static final String COMMAND_NAME = ':set'
-
- SetCommand(final Groovysh shell) {
- super(shell, COMMAND_NAME, ':=')
- }
-
- @Override
- protected List<Completer> createCompleters() {
- def loader = {
- Set<String> set = [] as Set<String>
-
- String[] keys = Preferences.keys()
-
- keys.each { String key -> set.add(key) }
-
- set << Preferences.VERBOSITY_KEY
- set << Preferences.EDITOR_KEY
- set << Preferences.PARSER_FLAVOR_KEY
- set << Preferences.SANITIZE_STACK_TRACE_KEY
- set << Preferences.SHOW_LAST_RESULT_KEY
- set << Groovysh.INTERPRETER_MODE_PREFERENCE_KEY
- set << Groovysh.AUTOINDENT_PREFERENCE_KEY
- set << Groovysh.COLORS_PREFERENCE_KEY
- set << Groovysh.METACLASS_COMPLETION_PREFIX_LENGTH_PREFERENCE_KEY
- set << PackageHelper.IMPORT_COMPLETION_PREFERENCE_KEY
-
- return set.toList()
- }
-
- return [
- new SimpleCompleter(loader),
- null
- ]
- }
-
- @Override
- Object execute(final List<String> args) {
- assert args != null
-
- if (args.size() == 0) {
- def keys = Preferences.keys()
-
- if (keys.size() == 0) {
- io.out.println('No preferences are set')
- return
- }
-
- io.out.println('Preferences:')
- keys.each { String key ->
- def keyvalue = Preferences.get(key, null)
- io.out.println(" $key=$keyvalue")
- }
- return
- }
-
- if (args.size() > 2) {
- fail("Command '$name' requires arguments: <name> [<value>]")
- }
-
- String name = args[0]
- def value
-
- if (args.size() == 1) {
- value = true
- } else {
- value = args[1]
- }
-
- log.debug("Setting preference: $name=$value")
-
- Preferences.put(name, String.valueOf(value))
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/ShadowCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/ShadowCommand.groovy
deleted file mode 100644
index 57aafc2d12..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/ShadowCommand.groovy
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.commands
-
-import org.apache.groovy.groovysh.ComplexCommandSupport
-import org.apache.groovy.groovysh.Groovysh
-import org.codehaus.groovy.tools.shell.IO
-import org.codehaus.groovy.tools.shell.util.Preferences
-
-/**
- * The 'shadow' command.
- */
-class ShadowCommand extends ComplexCommandSupport {
- public static final String COMMAND_NAME = ':shadow'
-
- ShadowCommand(final Groovysh shell) {
- super(shell, COMMAND_NAME, ':&', [ 'debug', 'verbose', 'info', 'this' ])
-
- this.hidden = true
- }
-
- def do_debug = {
- Preferences.verbosity = IO.Verbosity.DEBUG
- }
-
- def do_verbose = {
- Preferences.verbosity = IO.Verbosity.VERBOSE
- }
-
- def do_info = {
- Preferences.verbosity = IO.Verbosity.INFO
- }
-
- def do_this = {
- return this
- }
-}
-
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/ShowCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/ShowCommand.groovy
deleted file mode 100644
index aded00fae3..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/commands/ShowCommand.groovy
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.commands
-
-import org.apache.groovy.groovysh.ComplexCommandSupport
-import org.apache.groovy.groovysh.Groovysh
-import org.codehaus.groovy.runtime.FormatHelper
-import org.codehaus.groovy.runtime.MethodClosure
-import org.codehaus.groovy.tools.shell.util.Preferences
-
-/**
- * The 'show' command.
- */
-class ShowCommand extends ComplexCommandSupport {
- public static final String COMMAND_NAME = ':show'
-
- ShowCommand(final Groovysh shell) {
- super(shell, COMMAND_NAME, ':S', ['variables', 'classes', 'imports', 'preferences', 'all'])
- }
-
- def do_variables = {
- if (variables.isEmpty()) {
- io.out.println('No variables defined') // TODO: i18n
- } else {
- io.out.println('Variables:') // TODO: i18n
-
- variables.each { key, value ->
- // Special handling for defined methods, just show the sig
- if (value instanceof MethodClosure) {
- //
- // TODO: Would be nice to show the argument types it will accept...
- //
- value = "method ${value.method}()"
- }
-
- io.out.println(" $key = ${FormatHelper.toString(safe: true, maxSize: 2000, value)}")
- }.collectEntries { k, v -> [k, k == '_' ? k : v] }
- }
- }
-
- def do_classes = {
- Class[] classes = classLoader.loadedClasses
-
- if (classes.size() == 0) {
- io.out.println('No classes have been loaded') // TODO: i18n
- } else {
- io.out.println('Classes:') // TODO: i18n
-
- classes.each { Class classIt ->
- io.out.println(" $classIt")
- }
- }
- }
-
- def do_imports = {
- if (imports.isEmpty()) {
- io.out.println('No custom imports have been defined') // TODO: i18n
- } else {
- io.out.println('Custom imports:') // TODO: i18n
-
- imports.each { String importIt ->
- io.out.println(" $importIt")
- }
- }
- }
-
- def do_preferences = {
- String[] keys = Preferences.keys()
-
- if (keys.size() == 0) {
- io.out.println('No preferences are set')
- return
- }
-
- io.out.println('Preferences:')
- keys.each { String key ->
- def value = Preferences.get(key, null)
- io.out.println(" $key=$value")
- }
- return
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/BackslashEscapeCompleter.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/BackslashEscapeCompleter.groovy
deleted file mode 100644
index f55f71543c..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/BackslashEscapeCompleter.groovy
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.completion
-
-import org.jline.reader.Candidate
-import org.jline.reader.Completer
-import org.jline.reader.LineReader
-import org.jline.reader.ParsedLine
-
-/**
- * A completer within compatible strings (single/double quotes, single/double triple quotes)
- * showing informational alternatives that can occur after the backslash escape character.
- * No completion occurs and the cursor remains where it is.
- *
- * @since 2.4.13
- */
-class BackslashEscapeCompleter implements Completer {
- private static final Map<String, String> VALID_ESCAPEES = [
- r: 'return', n: 'newline', t: 'tab',
- '\\': 'backslash', "'": 'single quote', '"': 'double quote',
- b: 'backspace', f: 'formfeed']
- private static final GROUP = 'Escape Sequences'
-
- @Override
- void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) {
- String buffer = line.line().substring(0, line.cursor())
- if (!buffer.endsWith('\\')) {
- return
- }
-
- VALID_ESCAPEES.each { k, v ->
- candidates.add(new Candidate(k, "$k ($v)", GROUP, null, null, null, true))
- }
- candidates.add(new Candidate('u', "$uXXXX (unicode)", GROUP, 'Complete with a 4-digit hex code', null, null, false))
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/CommandNameCompleter.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/CommandNameCompleter.groovy
deleted file mode 100644
index 34212ea451..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/CommandNameCompleter.groovy
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.completion
-
-import org.apache.groovy.groovysh.Command
-import org.apache.groovy.groovysh.CommandRegistry
-import org.apache.groovy.groovysh.util.SimpleCompleter
-
-/**
- * Completer for the command.names
- */
-class CommandNameCompleter extends SimpleCompleter {
- private final CommandRegistry registry
-
- CommandNameCompleter(final CommandRegistry registry, boolean withBlank) {
- assert registry
- setWithBlank(withBlank)
- this.registry = registry
- }
-
- @Override
- SortedSet<String> getCandidates() {
- SortedSet<String> set = new TreeSet<String>()
-
- for (Command command in registry.commands()) {
- if (command.hidden) {
- continue
- }
-
- set << command.name
- set << command.shortcut
- }
-
- return set
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/FileNameCompleter.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/FileNameCompleter.groovy
deleted file mode 100644
index b51d652258..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/FileNameCompleter.groovy
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.completion
-
-import groovy.transform.PackageScope
-import org.jline.reader.Candidate
-import org.jline.reader.Completer
-import org.jline.reader.LineReader
-import org.jline.reader.ParsedLine
-
-/**
- * A file name completer takes the buffer and issues a list of
- * potential completions.
- * <p/>
- * This completer tries to behave as similar as possible to
- * <i>bash</i>'s file name completion (using GNU readline)
- * with the following exceptions:
- * <p/>
- * <ul>
- * <li>Candidates that are directories will end with "File.separator"</li>
- * <li>Wildcard regular expressions are not evaluated or replaced</li>
- * <li>The "~" character can be used to represent the user's home directory.
- * It cannot fully complete to other users' homes in all operating systems, since java does
- * not provide any way of determining that easily, but it will attempt a simplistic approach.</li>
- * </ul>
- *
- * @since 2.3
- */
-class FileNameCompleter implements Completer/*extends jline.console.completer.FileNameCompleter*/ {
- private static final boolean OS_IS_WINDOWS = false//Configuration.isWindows()
- private final GroovyShell gs = new GroovyShell()
-
- FileNameCompleter(boolean printSpaceAfterFullCompletion = true, boolean escapeBackslash = false,
- boolean escapeSpaces = true) {
- this.printSpaceAfterFullCompletion = printSpaceAfterFullCompletion
- this.escapeBackslash = escapeBackslash
- if (OS_IS_WINDOWS) separator = escapeBackslash ? "\\\\" : "\\"
- this.escapeSpaces = escapeSpaces
- }
-
- private static boolean isWindowsSubsystemForLinux() {
- System.getProperty("os.name").contains('Linux') && System.getProperty('os.version').contains('Microsoft')
- }
-
- /**
- * True for say, a command-line arg, false for instance inside a String.
- */
- boolean printSpaceAfterFullCompletion
-
- /**
- * If the filename will be placed inside a single/double quoted String we must escape backslash when on e.g. Windows.
- */
- boolean escapeBackslash
-
- /**
- * Set false if e.g. the filename will be inside a String. Should not be true if quoteFilenamesWithSpaces is true.
- */
- boolean escapeSpaces
-
- private String separator
-
- @Override
- void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) {
-/*// checkNotNull(candidates)
-
- buffer = buffer ?: ""
- String translated = buffer
- int adjustment = 0
- if (escapeBackslash) {
- translated = gs.evaluate("'$translated'")
- adjustment = buffer.size() - translated.size()
- }
-
- // Special character: ~ maps to the user's home directory in most OSs
- if (translated.startsWith("~")) {
- File homeDir = getUserHome()
- if ((OS_IS_WINDOWS || isWindowsSubsystemForLinux()) && (translated.equals("~" + separator()) || translated.equals("~/"))) {
- // for windows ~ isn't recognized at the file system level so replace
- def adjustSize = translated.size()
- String result
- String temp = (homeDir.path + translated.substring(separator().size())).toString().replace('"', '\\"').replace('\'', '\\\'')
- if (escapeBackslash) {
- temp = temp.replace('\\', '\\\\')
- }
- result = escapeSpaces ? temp.replace(' ', '\\ ') : temp
- candidates << result
- return cursor - adjustSize - adjustment
- } else if (translated.startsWith("~/")) {
- translated = homeDir.path + translated.substring(2)
- } else {
- translated = homeDir.parentFile.absolutePath + separator() + translated.substring(1)
- }
- } else if (!(new File(translated).canonicalFile.exists()) && !(new File(translated).canonicalFile.parentFile?.exists())) {
- String cwd = getUserDir().absolutePath
- translated = cwd + separator() + translated
- }
-
- File file = new File(translated)
- final File dir
-
- if ((OS_IS_WINDOWS && translated.endsWith(separator())) || translated.endsWith('/')) {
- dir = file
- } else {
- dir = file.parentFile
- }
-
- File[] entries = (dir == null) ? new File[0] : dir.listFiles()
-
- matchFiles(buffer, translated, entries, candidates)
- */
- }
-
- private static String canonicalForm(String raw) {
- String result = raw.replace('\\', '/')
- OS_IS_WINDOWS ? result.toLowerCase() : result
- }
-
- protected int matchFiles(final String buffer, final String translated, final File[] files,
- final List<CharSequence> candidates) {
- if (files == null) return -1
- for (File file : files) {
- if (canonicalForm(file.getAbsolutePath()).startsWith(canonicalForm(translated))) {
- CharSequence name = file.name
- String renderedName = render(name).toString()
- if (file.isDirectory()) {
- renderedName += separator
- } else {
- if (printSpaceAfterFullCompletion) {
- renderedName += ' '
- }
- }
- candidates.add(renderedName)
- }
- }
-
- int index = -1
- int sizeAdjust = 0
- if (separator) {
- index = buffer.lastIndexOf(separator)
- sizeAdjust = separator.size()
- }
- int slashIndex = buffer.lastIndexOf('/')
- if (slashIndex >= 0 && slashIndex > index) {
- index = slashIndex
- sizeAdjust = 1
- }
- return index + sizeAdjust
- }
-
- @PackageScope CharSequence render(CharSequence name) {
- String temp = name.toString().replace('"', '\\"').replace('\'', '\\\'')
- if (escapeBackslash) {
- temp = temp.replace('\\', '\\\\')
- }
- escapeSpaces ? temp.replace(' ', '\\ ') : temp
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/NavigablePropertiesCompleter.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/NavigablePropertiesCompleter.groovy
deleted file mode 100644
index 390f7c2a89..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/NavigablePropertiesCompleter.groovy
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.completion
-
-import java.util.regex.Pattern
-
-class NavigablePropertiesCompleter {
-
- private static final Pattern NO_CONTROL_CHARS_PATTERN = ~'^[^\\p{Cntrl}]+$'
-
- // pattern describing particle that must not occur within a string for the string to be a possible identifier
- private static final Pattern INVALID_CHAR_FOR_IDENTIFIER_PATTERN = ~'[ @#%^&§()+\\-={}\\[\\]~`´<>,."\'/!?:;|\\\\]'
-
- /**
- * Adds navigable properties to the list of candidates if they match the prefix
- */
- void addCompletions(final Object instance, final String prefix, final Set<CharSequence> candidates) {
- if (instance == null) {
- return
- }
- this.addIndirectObjectMembers(instance, prefix, candidates)
- }
-
-
- void addIndirectObjectMembers(final Object instance, final String prefix, final Set<CharSequence> candidates) {
- if (instance instanceof Map) {
- Map map = (Map) instance
- addMapProperties(map, prefix, candidates)
- }
- if (instance instanceof Node) {
- Node node = (Node) instance
- addNodeChildren(node, prefix, candidates)
- }
- if (instance instanceof NodeList) {
- NodeList nodeList = (NodeList) instance
- addNodeListEntries(nodeList, prefix, candidates)
- }
- }
-
- static void addMapProperties(final Map instance, final String prefix, final Set<CharSequence> candidates) {
- // key can be any Object but only Strings will be completed
- for (String key in instance.keySet().findAll {it instanceof String}) {
- // if key has no Control characters
- if (key.matches(NO_CONTROL_CHARS_PATTERN) && key.startsWith(prefix)) {
- // if key cannot be parsed used as identifier name, (contains invalid char or ends with $)
- if (key.find(INVALID_CHAR_FOR_IDENTIFIER_PATTERN) || key.endsWith('$')) {
- key = key.replace('\\', '\\\\').replace('\'', '\\\'')
- key = '\'' + key + '\''
- }
- candidates.add(key)
- }
- }
- }
-
- void addNodeListEntries(final NodeList instance, final String prefix, final Set<CharSequence> candidates) {
- for (Object member : instance) {
- addIndirectObjectMembers(member, prefix, candidates)
- }
- }
-
- void addNodeChildren(final Node instance, final String prefix, final Set<CharSequence> candidates) {
- for (Object child in instance.children()) {
- String member = ''
- if (child instanceof String) {
- member = (String) child
- } else if (child instanceof Node) {
- member = ((Node) child).name()
- } else if (child instanceof NodeList) {
- for (Object node : ((NodeList) child)) {
- addNodeChildren((Node) node, prefix, candidates)
- }
- } else {
- continue
- }
- if (member.startsWith(prefix)) {
- candidates.add(member)
- }
- }
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/ReflectionCompletionCandidate.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/ReflectionCompletionCandidate.groovy
deleted file mode 100644
index d0b53f022f..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/ReflectionCompletionCandidate.groovy
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.completion
-
-import groovy.transform.CompileStatic
-
-/**
- * A candidate as String with additional jansi formatting codes
- */
-@CompileStatic
-class ReflectionCompletionCandidate implements Comparable<ReflectionCompletionCandidate> {
-
- private final String value
- private final List<String> jAnsiCodes
-
- ReflectionCompletionCandidate(final String value, final String... jAnsiCodes) {
- this.value = value
- this.jAnsiCodes = new ArrayList<>(Arrays.asList(jAnsiCodes))
- }
-
- String getValue() {
- return value
- }
-
- List<String> getjAnsiCodes() {
- return jAnsiCodes
- }
-
- @Override
- int compareTo(ReflectionCompletionCandidate o) {
- boolean hasBracket = this.value.contains('(')
- boolean otherBracket = o.value.contains('(')
- if (hasBracket == otherBracket) {
- this.value.compareTo(o.value)
- } else if (hasBracket && ! otherBracket) {
- return -1
- } else {
- return 1
- }
-
- }
-
- @Override
- String toString() {
- return value
- }
-
- @Override
- int hashCode() {
- return value.hashCode()
- }
-
- @Override
- boolean equals(o) {
- if (this.is(o)) return true
- if (getClass() != o.class) return false
-
- ReflectionCompletionCandidate that = (ReflectionCompletionCandidate) o
-
- return value == that.value
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/StricterArgumentCompleter.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/StricterArgumentCompleter.groovy
deleted file mode 100644
index 330504396b..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/StricterArgumentCompleter.groovy
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.completion
-
-import groovy.transform.CompileStatic
-import org.jline.reader.Candidate
-import org.jline.reader.Completer
-import org.jline.reader.LineReader
-import org.jline.reader.ParsedLine
-
-import org.jline.reader.impl.completer.ArgumentCompleter
-//import org.jline.reader.impl.completer.ArgumentCompleter.WhitespaceArgumentDelimiter
-
-/**
- * This fixes strict jline 2.12 ArgumentCompleter
- * See https://github.com/jline/jline2/pull/202
- */
-@CompileStatic
-class StricterArgumentCompleter extends ArgumentCompleter {
-/**
- * Create a new completer with the default
- * {@link org.jline.reader.impl.completer.ArgumentCompleter.WhitespaceArgumentDelimiter}.
- *
- * @param completers The embedded completers
- */
- StricterArgumentCompleter(List<Completer> completers) {
- super(completers)
- }
-
- @Override
- void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) {
- // buffer can be null
-// checkNotNull(candidates)
-
- def list = line.words()
- int argpos = line.wordCursor()
- int argIndex = line.cursor()
-
- if (argIndex < 0) {
- return
- }
-
- List<Completer> completers = getCompleters()
- Completer completer
-
- // if we are beyond the end of the completers, just use the last one
- if (argIndex >= completers.size()) {
- completer = completers.get(completers.size() - 1)
- } else {
- completer = completers.get(argIndex)
- }
-
- // ensure that all the previous completers are successful before allowing this completer to pass (only if strict).
- for (int i = 0; isStrict() && (i < argIndex); i++) {
- Completer sub = completers.get(i >= completers.size() ? (completers.size() - 1) : i)
- String[] args = list.toArray(new String[0])
- String arg = (args == null || i >= args.length) ? "" : args[i]
-
- List<Candidate> subCandidates = new LinkedList<Candidate>()
- sub.complete(reader, line, subCandidates as List<Candidate>)
-
- // for strict matching, one of the candidates must equal the current argument "arg",
- // starting from offset within arg, but the suitable candidate may actually also have a
- // delimiter at the end.
- boolean candidateMatches = false
- for (Candidate subCandidate : subCandidates) {
-/* // each Subcandidate may end with the delimiter.
- // That it contains the delimiter is possible, but not likely.
- String[] candidateDelimList = delim.delimit(subCandidate, 0).arguments
- if (candidateDelimList.length == 0) {
- continue
- }
- String trimmedCand = candidateDelimList[0]
- if (trimmedCand.equals(arg.substring(offset))) {
- candidateMatches = true
- break
- }*/
- }
- if (!candidateMatches) {
- return
- }
- }
-
-/* int ret = completer.complete(list.getCursorArgument(), argpos, candidates)
-
- if (ret == -1) {
- return
- }
-
- int pos = ret + list.bufferPosition - argpos*/
-
- // Special case: when completing in the middle of a line, and the area under the cursor is a delimiter,
- // then trim any delimiters from the candidates, since we do not need to have an extra delimiter.
- //
- // E.g., if we have a completion for "foo", and we enter "f bar" into the buffer, and move to after the "f"
- // and hit TAB, we want "foo bar" instead of "foo bar".
-
-/* if ((cursor != buffer.length()) && delim.isDelimiter(buffer, cursor)) {
- for (int i = 0; i < candidates.size(); i++) {
- CharSequence val = candidates.get(i)
- while (val.length() > 0 && delim.isDelimiter(val, val.length() - 1)) {
- val = val.subSequence(0, val.length() - 1)
- }
- candidates.set(i, val)
- }
- }*/
-
-// Log.trace("Completing ", buffer, " (pos=", cursor, ") with: ", candidates, ": offset=", pos)
-
-// return pos
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/antlr4/CustomClassSyntaxCompleter.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/antlr4/CustomClassSyntaxCompleter.groovy
deleted file mode 100644
index 4577b9c36a..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/antlr4/CustomClassSyntaxCompleter.groovy
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.completion.antlr4
-
-import org.antlr.v4.runtime.Token
-import org.apache.groovy.groovysh.Groovysh
-
-/**
- * Completer completing classes defined in the shell
- */
-class CustomClassSyntaxCompleter implements IdentifierCompleter {
-
- private final Groovysh shell
-
- CustomClassSyntaxCompleter(final Groovysh shell) {
- this.shell = shell
- }
-
- @Override
- boolean complete(final List<Token> tokens, final List<CharSequence> candidates) {
- String prefix = tokens.last().text
- boolean foundMatch = false
- Class[] classes = shell.interp.classLoader.loadedClasses
- if (classes.size() > 0) {
- List<String> classnames = classes*.name
- for (String varName in classnames) {
- if (varName.startsWith(prefix)) {
- candidates << varName
- foundMatch = true
- }
- }
- }
- return foundMatch
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/antlr4/GroovySyntaxCompleter.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/antlr4/GroovySyntaxCompleter.groovy
deleted file mode 100644
index 200114f2ef..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/antlr4/GroovySyntaxCompleter.groovy
+++ /dev/null
@@ -1,385 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.completion.antlr4
-
-import groovy.transform.TupleConstructor
-import org.antlr.v4.runtime.CharStream
-import org.antlr.v4.runtime.CharStreams
-import org.antlr.v4.runtime.CommonTokenStream
-import org.antlr.v4.runtime.ConsoleErrorListener
-import org.antlr.v4.runtime.Token
-import org.apache.groovy.groovysh.CommandRegistry
-import org.apache.groovy.groovysh.Groovysh
-import org.apache.groovy.groovysh.completion.BackslashEscapeCompleter
-import org.apache.groovy.groovysh.completion.FileNameCompleter
-import org.apache.groovy.parser.antlr4.GroovyLangLexer
-import org.codehaus.groovy.tools.shell.util.Logger
-import org.jline.reader.Candidate
-import org.jline.reader.Completer
-import org.jline.reader.LineReader
-import org.jline.reader.ParsedLine
-
-import static org.apache.groovy.parser.antlr4.GroovyLexer.AS
-import static org.apache.groovy.parser.antlr4.GroovyLexer.BooleanLiteral
-import static org.apache.groovy.parser.antlr4.GroovyLexer.BuiltInPrimitiveType
-import static org.apache.groovy.parser.antlr4.GroovyLexer.CATCH
-import static org.apache.groovy.parser.antlr4.GroovyLexer.CLASS
-import static org.apache.groovy.parser.antlr4.GroovyLexer.CapitalizedIdentifier
-import static org.apache.groovy.parser.antlr4.GroovyLexer.DEF
-import static org.apache.groovy.parser.antlr4.GroovyLexer.DOT
-import static org.apache.groovy.parser.antlr4.GroovyLexer.ENUM
-import static org.apache.groovy.parser.antlr4.GroovyLexer.EOF
-import static org.apache.groovy.parser.antlr4.GroovyLexer.FINALLY
-import static org.apache.groovy.parser.antlr4.GroovyLexer.IMPORT
-import static org.apache.groovy.parser.antlr4.GroovyLexer.INSTANCEOF
-import static org.apache.groovy.parser.antlr4.GroovyLexer.INTERFACE
-import static org.apache.groovy.parser.antlr4.GroovyLexer.Identifier
-import static org.apache.groovy.parser.antlr4.GroovyLexer.METHOD_POINTER
-import static org.apache.groovy.parser.antlr4.GroovyLexer.METHOD_REFERENCE
-import static org.apache.groovy.parser.antlr4.GroovyLexer.NOT
-import static org.apache.groovy.parser.antlr4.GroovyLexer.NOT_INSTANCEOF
-import static org.apache.groovy.parser.antlr4.GroovyLexer.PACKAGE
-import static org.apache.groovy.parser.antlr4.GroovyLexer.SAFE_DOT
-import static org.apache.groovy.parser.antlr4.GroovyLexer.SPREAD_DOT
-import static org.apache.groovy.parser.antlr4.GroovyLexer.THIS
-import static org.apache.groovy.parser.antlr4.GroovyLexer.TRY
-import static org.apache.groovy.parser.antlr4.GroovyLexer.VOID
-
-/**
- * Implements the Completer interface to provide completions for
- * GroovyShell by tokenizing the buffer and invoking other classes depending on the tokens found.
- */
-class GroovySyntaxCompleter implements Completer {
-
- protected final static Logger LOG = Logger.create(GroovySyntaxCompleter)
-
- private final Groovysh shell
- private final List<IdentifierCompleter> identifierCompleters
- private final IdentifierCompleter classnameCompleter
- private final ReflectionCompleter reflectionCompleter
- private final InfixKeywordSyntaxCompleter infixCompleter
- private final Completer defaultFilenameCompleter
- private final Completer windowsFilenameCompleter
- private final Completer instringFilenameCompleter
- private final Completer backslashCompleter
- private static final boolean isWin = false//Configuration.isWindows()
- private final GroovyShell gs = new GroovyShell()
-
- static enum CompletionCase {
- SECOND_IDENT,
- NO_COMPLETION,
- DOT_LAST,
- SPREAD_DOT_LAST,
- PREFIX_AFTER_DOT,
- PREFIX_AFTER_SPREAD_DOT,
- NO_DOT_PREFIX,
- INSTANCEOF
- }
-
- GroovySyntaxCompleter(final Groovysh shell,
- final ReflectionCompleter reflectionCompleter,
- IdentifierCompleter classnameCompleter,
- final List<IdentifierCompleter> identifierCompleters,
- final Completer filenameCompleter) {
- this.shell = shell
- this.classnameCompleter = classnameCompleter
- this.identifierCompleters = identifierCompleters
- infixCompleter = new InfixKeywordSyntaxCompleter()
- backslashCompleter = new BackslashEscapeCompleter()
- this.reflectionCompleter = reflectionCompleter
- defaultFilenameCompleter = filenameCompleter
- windowsFilenameCompleter = new FileNameCompleter(false, true, false)
- instringFilenameCompleter = new FileNameCompleter(false, false, false)
- }
-
- @Override
- void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) {
- String bufferLine = line.line().substring(0, line.cursor())
-// int complete(final String bufferLine, final int cursor, final List<CharSequence> candidates) {
- if (!bufferLine) {
- return
- }
- if (isCommand(bufferLine, shell.registry)) {
- return
- }
- // complete given the context of the whole buffer, not just last line
- // Build a single string for the lexer
- List<Token> tokens = []
- try {
- if (!tokenizeBuffer(bufferLine.substring(0, line.cursor()), shell.buffers.current(), tokens)) {
- //return -1
- }
- } catch (InStringException ise) {
- int completionStart = ise.column + ise.openDelim.size()
- def remainder = bufferLine.substring(completionStart)
- def completer = instringFilenameCompleter
- if (['"', "'", '"""', "'''"].contains(ise.openDelim)) {
- if (isWin) {
- completer = windowsFilenameCompleter
- }
- // perhaps a backslash
- if (remainder.contains("\\")) {
- try {
- gs.evaluate("'$remainder'")
- } catch (Exception ex1) {
- try {
- gs.evaluate("'${remainder.substring(0, remainder.size() - 1)}'")
- // only get here if there is an unescaped backslash at the end of the buffer
- // ignore the result since it is only informational
- //return backslashCompleter.complete(remainder, cursor, candidates)
- } catch (Exception ex2) {
- }
- }
- }
- }
- int completionResult = completer.complete(remainder, line.cursor() - completionStart, candidates)
- if (completionResult >= 0) {
- //return completionStart + completionResult
- }
- //return completionResult
- }
-
- CompletionCase completionCase = getCompletionCase(tokens)
- if (completionCase == CompletionCase.NO_COMPLETION) {
- //return -1
- }
- if (completionCase == CompletionCase.SECOND_IDENT) {
- if (infixCompleter.complete(tokens, candidates)) {
- //return tokens.last().startIndex
- }
- // return -1
- }
- if (completionCase == CompletionCase.INSTANCEOF) {
- if (classnameCompleter.complete(tokens, candidates)) {
- //return tokens.last().startIndex
- }
- //return -1
- }
-
-
- int result
- switch (completionCase) {
- case CompletionCase.NO_DOT_PREFIX:
- result = completeIdentifier(tokens, candidates)
- break
- case CompletionCase.DOT_LAST:
- case CompletionCase.PREFIX_AFTER_DOT:
- case CompletionCase.SPREAD_DOT_LAST:
- case CompletionCase.PREFIX_AFTER_SPREAD_DOT:
- result = reflectionCompleter.complete(tokens, candidates)
- break
- default:
- // bug
- throw new RuntimeException("Unknown Completion case: $completionCase")
-
- }
- //return result
- }
-
- static CompletionCase getCompletionCase(final List<Token> tokens) {
- Token currentToken = tokens[-1]
-
- // now look at last 2 tokens to decide whether we are in a completion situation at all
- if (currentToken.type == Identifier || currentToken.type == CapitalizedIdentifier) {
- // cursor is on identifier, use it as prefix and check whether it follows a dot
-
- if (tokens.size() == 1) {
- return CompletionCase.NO_DOT_PREFIX
- }
- Token previousToken = tokens[-2]
- if (previousToken.type == DOT || previousToken.type == SAFE_DOT) {
- // we have a dot, so need to evaluate the statement up to the dot for completion
- if (tokens.size() < 3) {
- return CompletionCase.NO_COMPLETION
- }
- return CompletionCase.PREFIX_AFTER_DOT
- } else if (previousToken.type == SPREAD_DOT || previousToken.type == METHOD_POINTER || previousToken.type == METHOD_REFERENCE) {
- // we have a dot, so need to evaluate the statement up to the dot for completion
- if (tokens.size() < 3) {
- return CompletionCase.NO_COMPLETION
- }
- return CompletionCase.PREFIX_AFTER_SPREAD_DOT
- } else {
- // no dot, so we complete a varname, classname, or similar
- switch (previousToken.type) {
- // if any of these is before, no useful completion possible in this completer
- case IMPORT:
- case CLASS:
- case INTERFACE:
- case ENUM:
- case DEF:
- case VOID:
- case BuiltInPrimitiveType:
-// case LITERAL_byte:
-// case LITERAL_char:
-// case LITERAL_short:
-// case LITERAL_int:
-// case LITERAL_float:
-// case LITERAL_long:
-// case LITERAL_double:
- case PACKAGE:
- case BooleanLiteral:
-// case LITERAL_true:
-// case LITERAL_false:
- case AS:
- case THIS:
- case TRY:
- case FINALLY:
- case CATCH:
- return CompletionCase.NO_COMPLETION
- case NOT: // just for !in and !instanceof; maybe needs special case
- case CapitalizedIdentifier:
- case Identifier:
- // identifiers following each other could mean Declaration (no completion) or closure invocation
- // closure invocation too complex for now to complete
- return CompletionCase.SECOND_IDENT
- default:
- return CompletionCase.NO_DOT_PREFIX
- }
- }
-
- } else if (currentToken.type == DOT || currentToken.type == SAFE_DOT) {
- // cursor is on dot, so need to evaluate the statement up to the dot for completion
- if (tokens.size() == 1) {
- return CompletionCase.NO_COMPLETION
- }
- return CompletionCase.DOT_LAST
- } else if (currentToken.type == SPREAD_DOT || currentToken.type == METHOD_REFERENCE || currentToken.type == METHOD_POINTER) {
- // cursor is on spread-dot, so need to evaluate the statement up to the dot for completion
- if (tokens.size() == 1) {
- return CompletionCase.NO_COMPLETION
- }
- return CompletionCase.SPREAD_DOT_LAST
- } else if (currentToken.type == INSTANCEOF || currentToken.type == NOT_INSTANCEOF) {
- return CompletionCase.INSTANCEOF
- } else {
- LOG.debug('Unhandled token type: ' + currentToken.type)
- }
- return CompletionCase.NO_COMPLETION
- }
-
- int completeIdentifier(final List<Token> tokens, final List<CharSequence> candidates) {
- boolean foundMatches = false
- for (IdentifierCompleter completer : identifierCompleters) {
- foundMatches |= completer.complete(tokens, candidates)
- }
- if (foundMatches) {
- return tokens.last().startIndex
- }
- return -1
- }
-
- static boolean isCommand(final String bufferLine, final CommandRegistry registry) {
- // for shell commands, don't complete
- int commandEnd = bufferLine.indexOf(' ')
- if (commandEnd != -1) {
- String commandTokenText = bufferLine.substring(0, commandEnd)
- for (command in registry.commands()) {
- if (commandTokenText == command.name || commandTokenText in command.aliases) {
- return true
- }
- }
- }
- return false
- }
-
- static createTokenStream(String text) {
- CharStream charStream = CharStreams.fromReader(new StringReader(text))
- GroovyLangLexer lexer = new GroovyLangLexer(charStream)
- lexer.removeErrorListener(ConsoleErrorListener.INSTANCE)
- def tokenStream = new CommonTokenStream(lexer)
- tokenStream.fill()
- return tokenStream
- }
-
- @TupleConstructor
- static class InStringException extends Exception {
- int column
- String openDelim
- private static final long serialVersionUID = -2554041223576762580L;
-
- @Override
- String toString() {
- super.toString() + "[column=$column, openDelim=$openDelim]"
- }
- }
-
- private static final STRING_STARTERS = [/"""/, /'''/, /"/, /'/, '$/', '/']
-
- /**
- * Adds to result the identified tokens for the bufferLines
- * @param bufferLine
- * @param previousLines
- * @param result
- * @return true if lexing was successful
- */
- static boolean tokenizeBuffer(final String bufferLine,
- final List<String> previousLines,
- final List<Token> result) {
- def tokenStream
- if (previousLines.size() > 0) {
- StringBuilder src = new StringBuilder()
- for (String line : previousLines) {
- src.append(line).append('\n')
- }
- src.append(bufferLine)
- tokenStream = createTokenStream(src.toString()).getTokens().iterator()
- } else {
- tokenStream = createTokenStream(bufferLine).getTokens().iterator()
- }
- // Build a list of tokens
- Token nextToken
- Token lastToken
- while (true) {
- try {
- nextToken = tokenStream.next() as Token
- if (nextToken.type == EOF) {
- if (!result.isEmpty() && nextToken.line > result.last().line) {
- // no completion if EOF line has no tokens
- return false
- }
- break
- }
- result << nextToken
- lastToken = nextToken
- } catch (Exception e) {
- // TODO this whole section needs a rework for antlr4
- // getting the next token failed, possibly due to unclosed quotes; investigate rest of the line to confirm
- if (lastToken != null) {
- String restline = bufferLine.substring(lastToken.columnLast - 1)
- int leadingBlanks = restline.find('^[ ]*').length()
- if (restline) {
- String remainder = restline.substring(leadingBlanks)
- // Exception with following quote either means we're in String or at end of GString.
- String openDelim = STRING_STARTERS.find { remainder.startsWith(it) }
- if (openDelim && previousLines.size() + 1 == lastToken.line) {
- throw new InStringException(lastToken.columnLast + leadingBlanks - 1, openDelim)
- }
- }
- }
- return false
-// } catch (NullPointerException e) {
-// // this can happen when e.g. a string as not closed
-// new File('/tmp/groovysh_log.txt') << e.message << '\n'
-// return false
- }
- }
- return !result.empty
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/antlr4/IdentifierCompleter.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/antlr4/IdentifierCompleter.groovy
deleted file mode 100644
index 96a97bc75a..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/antlr4/IdentifierCompleter.groovy
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.completion.antlr4
-
-import org.antlr.v4.runtime.Token
-
-/**
- * Interface for classes that complete identifier tokens within a groovy Statement
- * (Class, variable, keyword, method, ...)
- * Similar to JLine Completer, but adapted for usage in GroovySyntaxCompleter
- */
-interface IdentifierCompleter {
-
- /**
- *
- * @param tokens List of tokens, non empty, last token is an identifier token, previous token is not a dot
- * @param candidates
- * @return
- */
- boolean complete(List<Token> tokens, List<CharSequence> candidates)
-
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/antlr4/ImportsSyntaxCompleter.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/antlr4/ImportsSyntaxCompleter.groovy
deleted file mode 100644
index 3ac6376e51..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/antlr4/ImportsSyntaxCompleter.groovy
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.completion.antlr4
-
-import org.antlr.v4.runtime.Token
-import org.apache.groovy.groovysh.Groovysh
-import org.codehaus.groovy.control.ResolveVisitor
-
-/**
- * Completer completing imported classnames
- */
-class ImportsSyntaxCompleter implements IdentifierCompleter {
-
- final Groovysh shell
- // cache for all preimported classes
- List<String> preimportedClassNames
- // cache for all manually imported classes
- final Map<String, Collection<String>> cachedImports = new HashMap<String, Collection<String>>().withDefault { String key ->
- Collection<String> matchingImports = new TreeSet<String>()
- collectImportedSymbols(key, matchingImports)
- matchingImports
- }
-
- ImportsSyntaxCompleter(final Groovysh shell) {
- this.shell = shell
- }
-
- @Override
- boolean complete(final List<Token> tokens, final List<CharSequence> candidates) {
- String prefix = tokens.last().getText()
- boolean foundMatch = findMatchingPreImportedClasses(prefix, candidates)
- for (String importSpec in shell.imports) {
- foundMatch |= findMatchingImportedClassesCached(prefix, importSpec, candidates)
- }
- return foundMatch
- }
-
- boolean findMatchingImportedClassesCached(final String prefix, final String importSpec, final List<String> candidates) {
- candidates.addAll(cachedImports
- .get(importSpec)
- .findAll({ String it -> it.startsWith(prefix) }))
- }
-
- boolean findMatchingPreImportedClasses(final String prefix, final Collection<String> matches) {
- boolean foundMatch = false
- if (preimportedClassNames == null) {
- preimportedClassNames = []
- for (packname in ResolveVisitor.DEFAULT_IMPORTS) {
- Set<String> packnames = shell.packageHelper.getContents(packname[0..-2])
- if (packnames) {
- preimportedClassNames.addAll(packnames.findAll({ String it -> it[0] in 'A'..'Z' }))
- }
- }
- preimportedClassNames.add('BigInteger')
- preimportedClassNames.add('BigDecimal')
- }
- // preimported names
- for (String preImpClassname in preimportedClassNames) {
- if (preImpClassname.startsWith(prefix)) {
- matches.add(preImpClassname)
- foundMatch = true
- }
- }
- return foundMatch
- }
-
- private static final String STATIC_IMPORT_PATTERN = ~/^static ([a-zA-Z_][a-zA-Z_0-9]*\.)+([a-zA-Z_][a-zA-Z_0-9]*|\*)$/
-
- /**
- * finds matching imported classes or static methods
- * @param importSpec an import statement without the leading 'import ' or trailing semicolon
- * @param matches all names matching the importSpec will be added to this Collection
- */
- void collectImportedSymbols(final String importSpec, final Collection<String> matches) {
- String asKeyword = ' as '
- int asIndex = importSpec.indexOf(asKeyword)
- if (asIndex > -1) {
- String alias = importSpec.substring(asIndex + asKeyword.length())
- matches << alias
- return
- }
- int lastDotIndex = importSpec.lastIndexOf('.')
- String symbolName = importSpec.substring(lastDotIndex + 1)
- String staticPrefix = 'static '
- if (importSpec.startsWith(staticPrefix)) {
- // make sure pattern is safe, though shell should have done anyway
- if (importSpec.matches(STATIC_IMPORT_PATTERN)) {
- String className = importSpec.substring(staticPrefix.length(), lastDotIndex)
- Class clazz = shell.interp.evaluate([className]) as Class
- if (clazz != null) {
- Set<String> clazzSymbols = ReflectionCompleter.getPublicFieldsAndMethods(clazz, '')*.value
- Collection<String> importedSymbols
- if (symbolName == '*') {
- importedSymbols = clazzSymbols
- } else {
- Set<String> acceptableMatches = [symbolName, symbolName + '(', symbolName + '()']
- importedSymbols = acceptableMatches.intersect(clazzSymbols)
- }
- matches.addAll(importedSymbols)
- }
- }
- } else {
- if (symbolName == '*') {
- matches.addAll(shell.packageHelper.getContents(importSpec))
- } else {
- matches << symbolName
- }
- }
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/antlr4/InfixKeywordSyntaxCompleter.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/antlr4/InfixKeywordSyntaxCompleter.groovy
deleted file mode 100644
index 4b016b44c6..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/antlr4/InfixKeywordSyntaxCompleter.groovy
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.completion.antlr4
-
-import org.antlr.v4.runtime.Token
-
-/**
- * Completer completing groovy keywords that appear after identifiers
- */
-class InfixKeywordSyntaxCompleter implements IdentifierCompleter {
-
- // INFIX keywords can only occur after identifiers
- private static final String[] INFIX_KEYWORDS = [
- 'in',
- 'instanceof',
- '!in',
- '!instanceof',
- 'extends',
- 'implements',
- ]
-
- @Override
- boolean complete(final List<Token> tokens, final List<CharSequence> candidates) {
- String prefix = tokens.last().text
- boolean foundMatch = false
- for (String varName in INFIX_KEYWORDS) {
- if (varName.startsWith(prefix)) {
- candidates << varName
- foundMatch = true
- }
- }
- return foundMatch
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/antlr4/KeywordSyntaxCompleter.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/antlr4/KeywordSyntaxCompleter.groovy
deleted file mode 100644
index 294b265d24..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/antlr4/KeywordSyntaxCompleter.groovy
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.completion.antlr4
-
-import org.antlr.v4.runtime.Token
-
-/**
- * Completer completing Groovy keywords and special functions
- */
-class KeywordSyntaxCompleter implements IdentifierCompleter {
-
- private static final String[] KEYWORDS = [
- 'abstract',
- 'assert', 'boolean', 'break', 'byte',
- 'case',
- // 'catch (', // special
- 'char', 'class', 'continue',
- 'def', // short, but keep, else 'default' completes, annoyingly
- 'default',
- 'do',
- 'double',
- 'else', 'enum',
-
- //'false',// value
- 'final',
- //'finally {', // special
- 'float',
- //'for (', // special
- //'if (', // special
- //'import', // command anyway
-
- 'int', // short, but keeping for consistency, all primitives
- 'interface',
- 'long',
- //'native',
- 'new',
- //'null', // value
- 'private', 'protected', 'public',
- 'return', 'short',
- 'static',
- //'super',// value
- //'switch (', // special
- 'synchronized',
- //'this', // value
- //threadsafe,
- 'throw', 'throws',
- 'transient',
- //'true', // value
- //'try {', //special
- 'var', 'void', 'volatile'
- //'while (' // special
- ]
-
- // VALUE_KEYWORDS and SPECIAL_FUNCTIONS completed without added blank
- private static final String[] VALUE_KEYWORDS = [
- 'true',
- 'false',
- 'this',
- 'super',
- 'null']
-
- private static final String[] SPECIAL_FUNCTIONS = [
- 'catch (',
- 'finally {',
- 'for (',
- 'if (',
- 'switch (',
- 'try {',
- 'while (']
-
- private static final String[] DEFAULT_METHODS = [
- 'use (',
- 'print ',
- 'println ',
- 'printf ',
- 'sprintf ',
- ]
-
- @Override
- boolean complete(final List<Token> tokens, final List<CharSequence> candidates) {
- String prefix = tokens.last().text
- boolean foundMatch = false
- for (String varName in KEYWORDS) {
- if (varName.startsWith(prefix)) {
- candidates << varName + ' '
- foundMatch = true
- }
- }
- for (String varName in VALUE_KEYWORDS) {
- if (varName.startsWith(prefix)) {
- candidates << varName
- foundMatch = true
- }
- }
- for (String varName in SPECIAL_FUNCTIONS) {
- if (varName.startsWith(prefix)) {
- candidates << varName
- foundMatch = true
- }
- }
- for (String varName in DEFAULT_METHODS) {
- if (varName.startsWith(prefix)) {
- candidates << varName
- foundMatch = true
- }
- }
-
- return foundMatch
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/antlr4/ReflectionCompleter.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/antlr4/ReflectionCompleter.groovy
deleted file mode 100644
index 00a6011774..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/antlr4/ReflectionCompleter.groovy
+++ /dev/null
@@ -1,737 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.completion.antlr4
-
-import org.antlr.v4.runtime.Token
-import org.apache.groovy.groovysh.Groovysh
-import org.apache.groovy.groovysh.completion.NavigablePropertiesCompleter
-import org.apache.groovy.groovysh.completion.ReflectionCompletionCandidate
-import org.codehaus.groovy.control.MultipleCompilationErrorsException
-import org.codehaus.groovy.runtime.InvokerHelper
-import org.codehaus.groovy.tools.shell.util.Preferences
-//import org.fusesource.jansi.Ansi
-//import org.fusesource.jansi.AnsiRenderer
-
-import java.lang.reflect.Field
-import java.lang.reflect.Method
-import java.lang.reflect.Modifier
-import java.util.regex.Pattern
-
-import static org.apache.groovy.parser.antlr4.GroovyLexer.ADD
-import static org.apache.groovy.parser.antlr4.GroovyLexer.ADD_ASSIGN
-import static org.apache.groovy.parser.antlr4.GroovyLexer.AND
-import static org.apache.groovy.parser.antlr4.GroovyLexer.AND_ASSIGN
-import static org.apache.groovy.parser.antlr4.GroovyLexer.ASSIGN
-import static org.apache.groovy.parser.antlr4.GroovyLexer.BITAND
-import static org.apache.groovy.parser.antlr4.GroovyLexer.BITNOT
-import static org.apache.groovy.parser.antlr4.GroovyLexer.BITOR
-import static org.apache.groovy.parser.antlr4.GroovyLexer.BooleanLiteral
-import static org.apache.groovy.parser.antlr4.GroovyLexer.BuiltInPrimitiveType
-import static org.apache.groovy.parser.antlr4.GroovyLexer.COLON
-import static org.apache.groovy.parser.antlr4.GroovyLexer.COMMA
-import static org.apache.groovy.parser.antlr4.GroovyLexer.CapitalizedIdentifier
-import static org.apache.groovy.parser.antlr4.GroovyLexer.DIV
-import static org.apache.groovy.parser.antlr4.GroovyLexer.DIV_ASSIGN
-import static org.apache.groovy.parser.antlr4.GroovyLexer.DOT
-import static org.apache.groovy.parser.antlr4.GroovyLexer.EQUAL
-import static org.apache.groovy.parser.antlr4.GroovyLexer.GE
-import static org.apache.groovy.parser.antlr4.GroovyLexer.GStringBegin
-import static org.apache.groovy.parser.antlr4.GroovyLexer.GT
-import static org.apache.groovy.parser.antlr4.GroovyLexer.Identifier
-import static org.apache.groovy.parser.antlr4.GroovyLexer.IN
-import static org.apache.groovy.parser.antlr4.GroovyLexer.INSTANCEOF
-import static org.apache.groovy.parser.antlr4.GroovyLexer.LBRACE
-import static org.apache.groovy.parser.antlr4.GroovyLexer.LBRACK
-import static org.apache.groovy.parser.antlr4.GroovyLexer.LPAREN
-import static org.apache.groovy.parser.antlr4.GroovyLexer.LE
-import static org.apache.groovy.parser.antlr4.GroovyLexer.LT
-import static org.apache.groovy.parser.antlr4.GroovyLexer.METHOD_POINTER
-import static org.apache.groovy.parser.antlr4.GroovyLexer.METHOD_REFERENCE
-import static org.apache.groovy.parser.antlr4.GroovyLexer.MUL
-import static org.apache.groovy.parser.antlr4.GroovyLexer.MUL_ASSIGN
-import static org.apache.groovy.parser.antlr4.GroovyLexer.NOT
-import static org.apache.groovy.parser.antlr4.GroovyLexer.NOTEQUAL
-import static org.apache.groovy.parser.antlr4.GroovyLexer.OR
-import static org.apache.groovy.parser.antlr4.GroovyLexer.OR_ASSIGN
-import static org.apache.groovy.parser.antlr4.GroovyLexer.RANGE_EXCLUSIVE_FULL
-import static org.apache.groovy.parser.antlr4.GroovyLexer.RANGE_EXCLUSIVE_LEFT
-import static org.apache.groovy.parser.antlr4.GroovyLexer.RANGE_EXCLUSIVE_RIGHT
-import static org.apache.groovy.parser.antlr4.GroovyLexer.RANGE_INCLUSIVE
-import static org.apache.groovy.parser.antlr4.GroovyLexer.RBRACK
-import static org.apache.groovy.parser.antlr4.GroovyLexer.RPAREN
-import static org.apache.groovy.parser.antlr4.GroovyLexer.SAFE_DOT
-import static org.apache.groovy.parser.antlr4.GroovyLexer.SEMI
-import static org.apache.groovy.parser.antlr4.GroovyLexer.SPACESHIP
-import static org.apache.groovy.parser.antlr4.GroovyLexer.SPREAD_DOT
-import static org.apache.groovy.parser.antlr4.GroovyLexer.StringLiteral
-import static org.apache.groovy.parser.antlr4.GroovyLexer.SUB
-import static org.apache.groovy.parser.antlr4.GroovyLexer.SUB_ASSIGN
-import static org.apache.groovy.parser.antlr4.GroovyLexer.XOR
-import static org.apache.groovy.parser.antlr4.GroovyLexer.XOR_ASSIGN
-
-/**
- * Completes fields and methods of Classes or instances.
- * Does not quite respect the contract of IdentifierCompleter, as last Token may be a dot or not,
- * thus also returns as int the cursor position.
- */
-class ReflectionCompleter {
-
- private static final NavigablePropertiesCompleter PROPERTIES_COMPLETER = new NavigablePropertiesCompleter()
- private static final Pattern BEAN_ACCESSOR_PATTERN = ~'^(get|set|is)[A-Z].*'
-
- final Groovysh shell
-
- /**
- *
- * @param shell
- * @param metaclass_completion_prefix_length how long the prefix must be to display candidates from metaclass
- */
- ReflectionCompleter(final Groovysh shell) {
- this.shell = shell
- }
-
- int complete(final List<Token> tokens, final List<CharSequence> candidates) {
- Token currentElementToken = null
- Token dotToken
- List<Token> previousTokens
- if (tokens.size() < 2) {
- throw new IllegalArgumentException('Must be invoked with at least 2 tokens, one of which is a dot-like operator: ' + tokens*.text)
- }
- if (tokens.last().type == DOT || tokens.last().type == SAFE_DOT || tokens.last().type == SPREAD_DOT || tokens.last().type == METHOD_POINTER || tokens.last().type == METHOD_REFERENCE) {
- dotToken = tokens.last()
- previousTokens = tokens[0..-2]
- } else {
- if (tokens[-2].type != DOT && tokens[-2].type != SAFE_DOT && tokens[-2].type != SPREAD_DOT && tokens[-2].type != METHOD_POINTER && tokens[-2].type != METHOD_REFERENCE) {
- throw new IllegalArgumentException('Must be invoked with token list with dot-like operator at last position or one position before: ' + tokens*.text)
- }
- currentElementToken = tokens.last()
- dotToken = tokens[-2]
- previousTokens = tokens[0..-3]
- }
-
- Object instanceOrClass = getInvokerClassOrInstance(previousTokens)
- if (instanceOrClass == null) {
- return -1
- }
- if (dotToken.type == SPREAD_DOT) {
- /**
- * for aggregate types, find an arbitrary collection-member
- * element within the instance. This may cause invalid completion candidates when the collection is not
- * homogeneous, but still better than no completion at all. Alternatively the union or intersection of
- * candidate completions could be built. For non-aggregate types, we assume that whatever find()
- * returns is useful for *. completion as well.
- */
- instanceOrClass = instanceOrClass.find()
- if (instanceOrClass == null) {
- return -1
- }
- }
-
- String identifierPrefix
- if (currentElementToken) {
- identifierPrefix = currentElementToken.text
- } else {
- identifierPrefix = ''
- }
-
- return completeInstanceMembers(instanceOrClass, identifierPrefix, candidates, currentElementToken, dotToken)
- }
-
- private int completeInstanceMembers(final Object instanceOrClass,
- final String identifierPrefix,
- final List<CharSequence> candidates,
- final Token currentElementToken,
- final Token dotToken) {
- // look for public methods/fields that match the prefix
- def methodRef = dotToken.type == METHOD_POINTER || dotToken.type == METHOD_REFERENCE
- Collection<ReflectionCompletionCandidate> myCandidates = getPublicFieldsAndMethods(instanceOrClass, identifierPrefix, methodRef)
-
- boolean showAllMethods = (identifierPrefix.length() >= Integer.valueOf(Preferences.get(Groovysh.METACLASS_COMPLETION_PREFIX_LENGTH_PREFERENCE_KEY, '3')))
- // Also add metaclass methods if prefix is long enough (user would usually not care about those)
- myCandidates.addAll(getMetaclassMethods(
- instanceOrClass,
- identifierPrefix,
- showAllMethods).collect({ String it -> new ReflectionCompletionCandidate(it) }))
-
- if (!showAllMethods) {
- // user probably does not care to see default Object / GroovyObject Methods,
- // they obfuscate the business logic
- removeStandardMethods(myCandidates)
- }
-
- // specific DefaultGroovyMethods only suggested for suitable instances
- myCandidates.addAll(getDefaultMethods(instanceOrClass,
- identifierPrefix).collect({ String it -> new ReflectionCompletionCandidate(it, AnsiRenderer.Code.BLUE.name()) }))
-
- if (myCandidates.size() > 0) {
- myCandidates = myCandidates.sort()
- if (methodRef) {
- // strip braces for :: and .& operators
- myCandidates = myCandidates.collect { cand ->
- def val = cand.value
- val = val.endsWith('()') ? val[0..-3] :
- (val.endsWith('(') ? val[0..-2] : val)
- new ReflectionCompletionCandidate(val, *cand.jAnsiCodes)
- }
- }
- if (Boolean.valueOf(Preferences.get(Groovysh.COLORS_PREFERENCE_KEY, 'true'))) {
- candidates.addAll(myCandidates.collect(
- { ReflectionCompletionCandidate it ->
- AnsiRenderer.render(it.value,
- it.jAnsiCodes.toArray(new String[it.jAnsiCodes.size()]))
- }))
- } else {
- candidates.addAll(myCandidates*.value)
- }
-
- int lastDot
- // dot could be on previous line
- if (currentElementToken && dotToken.line != currentElementToken.line) {
- lastDot = currentElementToken.startIndex
- } else {
- // Spread-dot/Method-ref/Method-pointer have length 2!
- lastDot = dotToken.startIndex + dotToken.text.size()
- }
- return lastDot
- }
-
- // no candidates
- return -1
- }
-
- /**
- * Takes the last ? tokens of the list that form a simple expression,
- * evaluates it and returns a result. "Simple" means evaluation is known to be
- * side-effect free.
- */
- Object getInvokerClassOrInstance(final List<Token> groovySourceTokens) {
- if (!groovySourceTokens
- || groovySourceTokens.last().type == DOT
- || groovySourceTokens.last().type == SAFE_DOT) {
- // we expect the list of tokens before a dot.
- return null
- }
- // first, try to detect a sequence of token before the dot that can safely be evaluated.
- List<Token> invokerTokens = getInvokerTokens(groovySourceTokens)
- if (invokerTokens) {
- try {
- String instanceRefExpression = tokenListToEvalString(invokerTokens)
- instanceRefExpression = instanceRefExpression.replace('\n', '')
- Object instance = shell.interp.evaluate([shell.getImportStatements()] + ['true'] + [instanceRefExpression])
- return instance
- } catch (MissingPropertyException |
- MissingMethodException |
- MissingFieldException |
- MultipleCompilationErrorsException e) {
-
- }
- }
- return null
- }
-
- /**
- * return the last tokens of a list that form an expression to be completed after the next dot, or null if
- * expression cannot be detected. This discards Expressions that could easily have side effects or be long
- * in evaluation. However it assumes that operators can be evaluated without side-effect or long running
- * operation. Users who use operators for which this does not hold should not use tab completion.
- * @param tokens
- * @return
- */
- static List<Token> getInvokerTokens(final List<Token> tokens) {
- int validIndex = tokens.size()
- if (validIndex == 0) {
- return []
- }
- // implementation goes backwards on token list, adding strings
- // to be evaluated later
- // need to collect using Strings, to support evaluation of string literals
- Stack<Integer> expectedOpeners = new Stack<Integer>()
- Token lastToken = null
- outerloop:
- for (Token loopToken in tokens.reverse()) {
- switch (loopToken.type) {
- // a combination of any of these can be evaluated without side effects
- // this just avoids any parentheses,
- // could maybe be extended further if harmless parentheses can be detected .
- // This allows already a lot of powerful simple completions, like [foo: Baz.bar]['foo'].
- case StringLiteral:
- // must escape String for evaluation, need the original string e.g. for mapping key
- break
- case LPAREN:
- if (expectedOpeners.empty()) {
- break outerloop
- }
- if (expectedOpeners.pop() != LPAREN) {
- return []
- }
- break
- case LBRACK:
- if (expectedOpeners.empty()) {
- break outerloop
- }
- if (expectedOpeners.pop() != LBRACK) {
- return []
- }
- break
- case RBRACK:
- expectedOpeners.push(LBRACK)
- break
- case RPAREN:
- expectedOpeners.push(LPAREN)
- break
- // tokens which indicate we have reached the beginning of a statement
- // operator tokens (must not be evaluated, as they can have side effects via evil overriding
- case SPACESHIP:
- case EQUAL:
- case NOTEQUAL:
- case ASSIGN:
- case GT:
- case LT:
- case GE:
- case LE:
- case ADD:
- case ADD_ASSIGN:
- case SUB:
- case SUB_ASSIGN:
- case MUL:
- case MUL_ASSIGN:
- case DIV:
- case DIV_ASSIGN:
- case BITOR:
- case OR_ASSIGN:
- case BITAND:
- case AND_ASSIGN:
- case XOR:
- case XOR_ASSIGN:
- case BITNOT:
- case OR:
- case AND:
- case NOT:
- case IN:
- case INSTANCEOF:
- if (expectedOpeners.empty()) {
- break outerloop
- }
- break
- // tokens which indicate we have reached the beginning of a statement
- case LBRACE:
- case SEMI:
-// case STRING_CTOR_START:
- case GStringBegin:
- break outerloop
- // tokens we accept
- case Identifier:
- case CapitalizedIdentifier:
- if (lastToken) {
- if (lastToken.type == LPAREN) {
- //Method invocation,must be avoided
- return []
- }
- if (lastToken.type == Identifier || lastToken.type == CapitalizedIdentifier) {
- // could be attempt to invoke closure like 'foo.each bar.baz'
- return []
- }
- }
- break
- // may begin expression when outside brackets (from back)
- case RANGE_INCLUSIVE:
- case RANGE_EXCLUSIVE_LEFT:
- case RANGE_EXCLUSIVE_RIGHT:
- case RANGE_EXCLUSIVE_FULL:
- case COLON:
- case COMMA:
- if (expectedOpeners.empty()) {
- break outerloop
- }
- // harmless literals
- case BooleanLiteral:
-// case LITERAL_true:
-// case LITERAL_false:
- case BuiltInPrimitiveType:
-// case NUM_INT:
-// case NUM_FLOAT:
-// case NUM_LONG:
-// case NUM_DOUBLE:
-// case NUM_BIG_INT:
-// case NUM_BIG_DECIMAL:
- case METHOD_POINTER:
- case DOT:
- case SAFE_DOT:
- break
- default:
- return null
- } // end switch
- validIndex--
- lastToken = loopToken
- } // end for
- return tokens[(validIndex)..-1]
- }
-
- static String tokenListToEvalString(final List<Token> groovySourceTokens) {
- StringBuilder builder = new StringBuilder()
- for (Token token : groovySourceTokens) {
- if (token.type == StringLiteral) {
- builder.append('\'').append(token.text).append('\'')
- } else {
- builder.append(token.text)
- }
- }
- return builder.toString()
- }
-
- static boolean acceptName(final String name, final String prefix) {
- return (!prefix || name.startsWith(prefix)) &&
- (!(name.contains('$')) && !(name.startsWith('_')))
- }
-
- static Collection<String> getMetaclassMethods(final Object instance, final String prefix, final boolean includeMetaClassImplMethods) {
- Set<String> rv = new HashSet<String>()
- MetaClass metaclass = InvokerHelper.getMetaClass(instance)
- if (includeMetaClassImplMethods || !(metaclass instanceof MetaClassImpl)) {
- metaclass.metaMethods.each { MetaMethod mmit ->
- if (acceptName(mmit.name, prefix)) {
- rv << mmit.getName() + (mmit.parameterTypes.length == 0 ? '()' : '(')
- }
- }
- }
- return rv.sort()
- }
-
- /**
- * Build a list of public fields and methods for an object
- * that match a given prefix.
- * @param instance the object
- * @param prefix the prefix that must be matched
- * @return the list of public methods and fields that begin with the prefix
- */
- static Collection<ReflectionCompletionCandidate> getPublicFieldsAndMethods(final Object instance, final String prefix, final boolean all = false) {
- Set<ReflectionCompletionCandidate> rv = new HashSet<ReflectionCompletionCandidate>()
- Class clazz = instance.getClass()
- if (clazz == null) {
- return rv
- }
-
- boolean isClass = (clazz == Class)
- if (isClass) {
- clazz = instance as Class
- }
-
- Class loopclazz = clazz
- // render immediate class members bold when completing an instance
- boolean renderBold = !isClass
- // hide static members for instances unless user typed a prefix
- boolean showStatic = isClass || all || (prefix.length() >= Integer.valueOf(Preferences.get(Groovysh.METACLASS_COMPLETION_PREFIX_LENGTH_PREFERENCE_KEY, '3')))
- boolean showInstance = !isClass || all
- while (loopclazz != null && loopclazz != Object && loopclazz != GroovyObject) {
- addClassFieldsAndMethods(loopclazz, showStatic, showInstance, prefix, rv, renderBold)
- renderBold = false
- loopclazz = loopclazz.superclass
- }
- if (clazz.isArray() && showInstance) {
- // Arrays are special, these public members cannot be found via Reflection
- for (String member : ['length', 'clone()']) {
- if (member.startsWith(prefix)) {
- rv.add(new ReflectionCompletionCandidate(member/*, Ansi.Attribute.INTENSITY_BOLD.name()*/))
- }
- }
- }
-
- // other completions that are commonly possible with properties
- if (showInstance) {
- Set<String> candidates = new HashSet<String>()
- PROPERTIES_COMPLETER.addCompletions(instance, prefix, candidates)
- rv.addAll(candidates.collect({ String it -> new ReflectionCompletionCandidate(it/*, AnsiRenderer.Code.MAGENTA.name()*/) }))
- }
-
- return rv.sort()
- }
-
- /**
- * removes candidates that, most of the times, a programmer does not want to see in completion
- * @param candidates
- */
- static removeStandardMethods(final Collection<ReflectionCompletionCandidate> candidates) {
- for (String defaultMethod : [
- 'clone()', 'finalize()', 'getClass()',
- 'getMetaClass()', 'getProperty(', 'invokeMethod(', 'setMetaClass(', 'setProperty(',
- 'equals(', 'hashCode()', 'toString()',
- 'notify()', 'notifyAll()', 'wait(', 'wait()']) {
- for (ReflectionCompletionCandidate candidate : candidates) {
- if (defaultMethod.equals(candidate.value)) {
- candidates.remove(candidate)
- break
- }
- }
- }
- }
-
- /**
- * Offering all DefaultGroovyMethods on any object is too verbose, hiding all
- * removes user-friendliness. So here util methods will be added to candidates
- * if the instance is of a suitable type.
- * This does not need to be strictly complete, only the most useful functions may appear.
- */
- static List<String> getDefaultMethods(final Object instance, final String prefix) {
- List<String> candidates = []
- if (instance instanceof Iterable) {
- [
- 'any()', 'any(',
- 'collect()', 'collect(',
- 'combinations()',
- 'count(',
- 'countBy(',
- 'drop(', 'dropRight(', 'dropWhile(',
- 'each()', 'each(',
- 'eachPermutation(',
- 'every()', 'every(',
- 'find(', 'findResult(', 'findResults(',
- 'flatten()',
- 'init()',
- 'inject(',
- 'intersect(',
- 'join(',
- 'max()', 'min()',
- 'reverse()',
- 'size()',
- 'sort()',
- 'split(',
- 'take(', 'takeRight(', 'takeWhile(',
- 'toSet()',
- 'retainAll(', 'removeAll(',
- 'unique()', 'unique('
- ].findAll({ it.startsWith(prefix) }).each({ candidates.add(it) })
- if (instance instanceof Collection) {
- [
- 'grep('
- ].findAll({ it.startsWith(prefix) }).each({ candidates.add(it) })
- }
- if (instance instanceof List) {
- [
- 'collate(',
- 'execute()', 'execute(',
- 'pop()',
- 'transpose()'
- ].findAll({ it.startsWith(prefix) }).each({ candidates.add(it) })
- }
- }
- if (instance instanceof Map) {
- [
- 'any(',
- 'collect(',
- 'collectEntries(',
- 'collectMany(',
- 'count(',
- 'drop(',
- 'each(',
- 'every(',
- 'find(', 'findAll(', 'findResult(', 'findResults(',
- 'groupEntriesBy(', 'groupBy(',
- 'inject(', 'intersect(',
- 'max(', 'min(',
- 'sort(',
- 'spread()',
- 'subMap(',
- 'take(', 'takeWhile('
- ].findAll({ it.startsWith(prefix) }).each({ candidates.add(it) })
- }
- if (instance instanceof File) {
- [
- 'append(',
- 'createTempDir()', 'createTempDir(',
- 'deleteDir()', 'directorySize()',
- 'eachByte(', 'eachDir(', 'eachDirMatch(', 'eachDirRecurse(', 'eachFile(', 'eachFileMatch(', 'eachFileRecurse(', 'eachLine(',
- 'filterLine(',
- 'getBytes()', 'getText()', 'getText(',
- 'newInputStream()', 'newOutputStream()', 'newPrintWriter()', 'newPrintWriter(', 'newReader()', 'newReader(', 'newWriter()', 'newWriter(',
- 'readBytes()', 'readLines(',
- 'setBytes(', 'setText(', 'size()', 'splitEachLine(',
- 'traverse(',
- 'withInputStream(', 'withOutputStream(', 'withPrintWriter(', 'withReader(', 'withWriter(', 'withWriterAppend(', 'write('
- ].findAll({ it.startsWith(prefix) }).each({ candidates.add(it) })
- }
- if (instance instanceof String) {
- [
- 'capitalize()', 'center(', 'collectReplacements(', 'count(',
- 'decodeBase64()', 'decodeHex()', 'denormalize()',
- 'eachLine(', 'eachMatch(', 'execute()', 'execute(',
- 'find(', 'findAll(',
- 'isAllWhitespace()', 'isBigDecimal()', 'isBigInteger()', 'isDouble()', 'isFloat()', 'isInteger()', 'isLong()', 'isNumber()',
- 'normalize()',
- 'padLeft(', 'padRight(',
- 'readLines()', 'reverse()',
- 'size()', 'splitEachLine(', 'stripIndent(', 'stripMargin(',
- 'toBigDecimal()', 'toBigInteger()', 'toBoolean()', 'toCharacter()', 'toDouble()', 'toFloat()', 'toInteger()',
- 'toList()', 'toLong()', 'toSet()', 'toShort()', 'toURI()', 'toURL()',
- 'tokenize(', 'tr('
- ].findAll({ it.startsWith(prefix) }).each({ candidates.add(it) })
- }
- if (instance instanceof URL) {
- [
- 'eachLine(',
- 'filterLine(',
- 'getBytes()', 'getBytes(', 'getText()', 'getText(',
- 'newInputStream()', 'newInputStream(', 'newReader()', 'newReader(',
- 'readLines()', 'readLines(',
- 'splitEachLine(',
- 'withInputStream(', 'withReader('
- ].findAll({ it.startsWith(prefix) }).each({ candidates.add(it) })
- }
- if (instance instanceof InputStream) {
- [
- 'eachLine(',
- 'filterLine(',
- 'getBytes()', 'getText()', 'getText(',
- 'newReader()', 'newReader(',
- 'readLines()', 'readLines(',
- 'splitEachLine(',
- 'withReader(', 'withStream('
- ].findAll({ it.startsWith(prefix) }).each({ candidates.add(it) })
- }
- if (instance instanceof OutputStream) {
- [
- 'newPrintWriter()', 'newWriter()', 'newWriter(',
- 'setBytes(',
- 'withPrintWriter(', 'withStream(', 'withWriter('
- ].findAll({ it.startsWith(prefix) }).each({ candidates.add(it) })
- }
- if (instance instanceof Number) {
- [
- 'abs()',
- 'downto(',
- 'times(',
- 'power(',
- 'upto('
- ].findAll({ it.startsWith(prefix) }).each({ candidates.add(it) })
- }
- Class clazz = instance.getClass()
- if (clazz != null && clazz != Class && clazz.isArray()) {
- [
- 'any()', 'any(',
- 'collect()', 'collect(',
- 'count(',
- 'countBy(',
- 'drop(', 'dropRight(', 'dropWhile(',
- 'each()', 'each(',
- 'every()', 'every(',
- 'find(', 'findResult(',
- 'flatten()',
- 'init()',
- 'inject(',
- 'join(',
- 'max()', 'min()',
- 'reverse()',
- 'size()',
- 'sort()',
- 'split(',
- 'take(', 'takeRight(', 'takeWhile('
- ].findAll({ it.startsWith(prefix) }).each({ candidates.add(it) })
- }
- return candidates
- }
-
- private static Collection<ReflectionCompletionCandidate> addClassFieldsAndMethods(final Class clazz,
- final boolean includeStatic,
- final boolean includeNonStatic,
- final String prefix,
- final Collection<ReflectionCompletionCandidate> rv,
- final boolean renderBold) {
-
- Field[] fields = (includeStatic && !includeNonStatic) ? clazz.fields : clazz.getDeclaredFields()
- fields.each { Field fit ->
- if (acceptName(fit.name, prefix)) {
- int modifiers = fit.getModifiers()
- if (Modifier.isPublic(modifiers) && (Modifier.isStatic(modifiers) ? includeStatic : includeNonStatic)) {
- if (!clazz.isEnum()
- || !(!includeStatic && Modifier.isPublic(modifiers) && Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers) && fit.type == clazz)) {
- ReflectionCompletionCandidate candidate = new ReflectionCompletionCandidate(fit.name)
- if (!Modifier.isStatic(modifiers)) {
- if (renderBold) {
- candidate.jAnsiCodes.add(Ansi.Attribute.INTENSITY_BOLD.name())
- }
- }
- rv << candidate
- }
- }
- }
- }
- Method[] methods = (includeStatic && !includeNonStatic) ? clazz.methods : clazz.getDeclaredMethods()
- for (Method methIt : methods) {
- String name = methIt.getName()
- if (name.startsWith("super\$")) {
- name = name.substring(name.find("^super\\\$.*\\\$").length())
- }
- int modifiers = methIt.getModifiers()
- if (Modifier.isPublic(modifiers) && (Modifier.isStatic(modifiers) ? includeStatic : includeNonStatic)) {
- boolean fieldnameSuggested = false
- // bean fieldname can be used instead of accessor, tidies up completion candidates
- // the same goes for static fields // accessors
- if (name.matches(BEAN_ACCESSOR_PATTERN)) {
- String fieldname = getFieldnameForAccessor(name, methIt.parameterTypes.length)
- if (fieldname != null && fieldname != 'metaClass' && fieldname != 'property') {
- if (acceptName(fieldname, prefix)) {
- fieldnameSuggested = true
- ReflectionCompletionCandidate fieldCandidate = new ReflectionCompletionCandidate(fieldname)
- if (!rv.contains(fieldCandidate)) {
- if (!Modifier.isStatic(modifiers) && renderBold) {
-// fieldCandidate.jAnsiCodes.add(Ansi.Attribute.INTENSITY_BOLD.name())
- }
-
- rv.add(fieldCandidate)
- }
- }
- }
- }
- if (!fieldnameSuggested && acceptName(name, prefix)) {
- ReflectionCompletionCandidate candidate = new ReflectionCompletionCandidate(name + (methIt.parameterTypes.length == 0 ? '()' : '('))
- if (!Modifier.isStatic(modifiers) && renderBold) {
-// candidate.jAnsiCodes.add(Ansi.Attribute.INTENSITY_BOLD.name())
- }
- rv.add(candidate)
- }
- }
- }
-
- for (Class interface_ : clazz.getInterfaces()) {
- addClassFieldsAndMethods(interface_, includeStatic, includeNonStatic, prefix, rv, false)
- }
- }
-
- static CharSequence getFieldnameForAccessor(String accessor, int parameterLength) {
- String fieldname = null
- if (accessor.startsWith('get')) {
- if (parameterLength == 0) {
- fieldname = accessor.substring(3)
- }
- } else if (accessor.startsWith('set')) {
- if (parameterLength == 1) {
- fieldname = accessor.substring(3)
- }
- } else if (accessor.startsWith('is')) {
- if (parameterLength == 0) {
- fieldname = accessor.substring(2)
- }
- } else {
- throw new IllegalStateException('getFieldnameForAccessor called with invalid accessor : ' + accessor)
- }
- if (fieldname == null) {
- return null
- }
- return fieldname[0].toLowerCase() + fieldname.substring(1)
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/antlr4/VariableSyntaxCompleter.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/antlr4/VariableSyntaxCompleter.groovy
deleted file mode 100644
index d0939f298f..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/completion/antlr4/VariableSyntaxCompleter.groovy
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.completion.antlr4
-
-import org.antlr.v4.runtime.Token
-import org.apache.groovy.groovysh.Groovysh
-import org.codehaus.groovy.runtime.MethodClosure
-
-/**
- * Completer completing variable and method names from known variables in the shell
- */
-class VariableSyntaxCompleter implements IdentifierCompleter {
-
- final Groovysh shell
-
- VariableSyntaxCompleter(final Groovysh shell) {
- this.shell = shell
- }
-
- @Override
- boolean complete(final List<Token> tokens, final List<CharSequence> candidates) {
- String prefix = tokens.last().text
- Map vars = shell.interp.context.variables
- boolean foundMatch = false
- for (String varName in vars.keySet()) {
- if (acceptName(varName, prefix)) {
- if (vars.get(varName) instanceof MethodClosure) {
- if (((MethodClosure) vars.get(varName)).getMaximumNumberOfParameters() > 0) {
- varName += '('
- } else {
- varName += '()'
- }
- }
- foundMatch = true
- candidates << varName
- }
- }
- return foundMatch
- }
-
- private static boolean acceptName(String name, String prefix) {
- return (!prefix || name.startsWith(prefix)) &&
- (!(name.contains('$')) && !(name.startsWith('_')))
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyBuiltins.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyBuiltins.groovy
index e7e5ae47c5..ebea00ab99 100644
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyBuiltins.groovy
+++ b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyBuiltins.groovy
@@ -18,7 +18,10 @@
*/
package org.apache.groovy.groovysh.jline
+import org.jline.builtins.Commands
import org.jline.builtins.ConfigurationPath
+import org.jline.console.CommandInput
+import org.jline.console.CommandMethods
import org.jline.console.impl.Builtins
import org.jline.reader.Widget
@@ -27,10 +30,56 @@ import java.util.function.Function
import java.util.function.Supplier
class GroovyBuiltins extends Builtins {
- GroovyBuiltins(Supplier<Path> workDir, ConfigurationPath configPath, Function<String, Widget> widgetCreator) {
+ private final ConfigurationPath configPath
+ private final Supplier<Path> workDir
+ private final GroovyEngine engine
+
+ GroovyBuiltins(GroovyEngine engine, Supplier<Path> workDir, ConfigurationPath configPath, Function<String, Widget> widgetCreator) {
super(workDir, configPath, widgetCreator)
- commandNames().each{ name ->
- rename(Command."${name.toUpperCase()}", "/$name")
+ this.workDir = workDir
+ this.configPath = configPath
+ this.engine = engine
+ // Builtins doesn't have the extension points we want, so duplicate its command registration here
+ def commandExecute = commandNames().collectEntries { name ->
+ def methods = getCommandMethods(name)
+ if (name in ['nano', 'less']) {
+ methods = new CommandMethods((Function)this::"$name", methods.compileCompleter())
+ }
+ [Command."${name.toUpperCase()}", methods]
+ }
+ def commandName = commandNames().collectEntries{ name ->
+ [Command."${name.toUpperCase()}", '/' + name]
+ }
+ registerCommands(commandName, commandExecute)
+ }
+
+ private void less(CommandInput input) {
+ boolean usingBuffer = input.xargs().size() == 0
+ if (usingBuffer) {
+ def temp = File.createTempFile('groovysh', '.groovy')
+ temp.text = engine.buffer
+ input = new CommandInput(input.command(), [temp.absolutePath] as String[], input.terminal(), input.in(), input.out(), input.err())
+ }
+ try {
+ Commands.less(input.terminal(), input.in(), input.out(), input.err(), workDir.get(), input.xargs(), configPath)
+ } catch (Exception e) {
+ saveException(e)
+ }
+ }
+
+ private void nano(CommandInput input) {
+ boolean usingBuffer = input.args().size() == 0
+ def temp = null
+ if (usingBuffer) {
+ temp = File.createTempFile('groovysh', '.groovy')
+ temp.text = engine.buffer
+ input = new CommandInput(input.command(), [temp.absolutePath] as String[], input.terminal(), input.in(), input.out(), input.err())
+ }
+ try {
+ Commands.nano(input.terminal(), input.out(), input.err(), workDir.get(), input.args(), configPath)
+ if (temp) GroovyCommands.loadFile(engine, temp)
+ } catch (Exception e) {
+ saveException(e)
}
}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyCommands.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyCommands.groovy
index 3d21981d64..38da02b46e 100644
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyCommands.groovy
+++ b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovyCommands.groovy
@@ -23,6 +23,7 @@ import groovy.console.ui.ObjectBrowser
import org.jline.builtins.Completers
import org.jline.builtins.Completers.OptDesc
import org.jline.builtins.Completers.OptionCompleter
+import org.jline.builtins.SyntaxHighlighter
import org.jline.console.CmdDesc
import org.jline.console.CommandInput
import org.jline.console.CommandMethods
@@ -35,6 +36,7 @@ import org.jline.reader.impl.completer.NullCompleter
import org.jline.reader.impl.completer.StringsCompleter
import org.jline.utils.AttributedString
+import java.awt.event.ActionListener
import java.nio.file.FileSystems
import java.nio.file.Files
import java.nio.file.Path
@@ -44,24 +46,32 @@ import java.util.function.Function
import java.util.function.Supplier
import java.util.stream.Stream
-import static org.jline.builtins.Completers.TreeCompleter.node
-
class GroovyCommands extends JlineCommandRegistry implements CommandRegistry {
private static final String DEFAULT_NANORC_VALUE = 'gron'
private final GroovyEngine engine
private final Printer printer
+ private final SyntaxHighlighter highlighter
private final Map<String, Tuple4<Function, Function, Function, List<String>>> commands = [
- '/inspect' : new Tuple4<>(this::inspect, this::inspectCompleter, this::inspectCmdDesc, ['Display/browse object info on terminal/object browser']),
- '/console' : new Tuple4<>(this::console, this::defCompleter, this::consoleCmdDesc, ['Launch Groovy console']),
- '/grab' : new Tuple4<>(this::grab, this::grabCompleter, this::grabCmdDesc, ['Add maven repository dependencies to classpath']),
- '/classloader' : new Tuple4<>(this::classLoader, this::classloaderCompleter, this::classLoaderCmdDesc, ['Display and manage Groovy classLoader data'])
+ '/inspect' : new Tuple4<>(this::inspect, this::inspectCompleter, this::inspectCmdDesc, ['display/browse object info on terminal/object browser']),
+ '/console' : new Tuple4<>(this::console, this::defCompleter, this::defCmdDesc, ['launch Groovy console']),
+ '/grab' : new Tuple4<>(this::grab, this::grabCompleter, this::grabCmdDesc, ['add maven repository dependencies to classpath']),
+ '/classloader' : new Tuple4<>(this::classLoader, this::classloaderCompleter, this::classLoaderCmdDesc, ['display/manage Groovy classLoader data']),
+ '/imports' : new Tuple4<>(this::importsCommand, this::importsCompleter, this::nameDeleteCmdDesc, ['show/delete import statements']),
+ '/reset' : new Tuple4<>(this::reset, this::defCompleter, this::defCmdDesc, ['clear the buffer']),
+ '/load' : new Tuple4<>(this::load, this::loadCompleter, this::loadCmdDesc, ['load a file into the buffer']),
+ '/save' : new Tuple4<>(this::save, this::saveCompleter, this::defCmdDesc, ['save the buffer to a file']),
+ '/types' : new Tuple4<>(this::typesCommand, this::typesCompleter, this::nameDeleteCmdDesc, ['show/delete types']),
+ '/methods' : new Tuple4<>(this::methodsCommand, this::methodsCompleter, this::nameDeleteCmdDesc, ['show/delete methods'])
]
private boolean consoleUi
private boolean ivy
+ private Supplier<Path> workDir
- GroovyCommands(GroovyEngine engine, Printer printer) {
+ GroovyCommands(GroovyEngine engine, Supplier<Path> workDir, Printer printer, SyntaxHighlighter highlighter) {
this.engine = engine
this.printer = printer
+ this.workDir = workDir
+ this.highlighter = highlighter
try {
Class.forName('groovy.console.ui.ObjectBrowser')
consoleUi = true
@@ -107,15 +117,12 @@ class GroovyCommands extends JlineCommandRegistry implements CommandRegistry {
if (!input.xargs()) {
return null
}
- if (input.args().length > 2) {
- throw new IllegalArgumentException('Wrong number of command parameters: ' + input.args().length)
- }
+ checkArgCount(input, [0, 1, 2])
+ if (maybePrintHelp(input, '/grab')) return
try {
String arg = input.args()[0]
- if (arg == '-?' || arg == '--help') {
- printer.println(helpDesc('/grab'))
- } else if (arg == '-l' || arg == '--list') {
- Object resp = engine.execute('groovy.grape.Grape.getInstance().enumerateGrapes()')
+ if (arg == '-l' || arg == '--list') {
+ Object resp = engine.execute('groovy.grape.Grape.instance.enumerateGrapes()')
printer.println([
(Printer.VALUE_STYLE) : engine.groovyOption(GroovyEngine.NANORC_VALUE, DEFAULT_NANORC_VALUE),
(Printer.INDENTION) : 4,
@@ -160,20 +167,157 @@ class GroovyCommands extends JlineCommandRegistry implements CommandRegistry {
return null
}
- void console(CommandInput input) {
- if (input.args().length > 1) {
- throw new IllegalArgumentException('Wrong number of command parameters: ' + input.args().length)
+ void reset(CommandInput input) {
+ checkArgCount(input, [0, 1])
+ if (maybePrintHelp(input, '/reset')) return
+ engine.reset()
+ }
+
+ void save(CommandInput input) {
+ checkArgCount(input, [1, 2])
+ if (maybePrintHelp(input, '/save')) return
+ boolean overwrite = false
+ String arg = input.args()[0]
+ if (arg == '-o' || arg == '--overwrite') {
+ overwrite = true
+ arg = input.args()[1]
}
- if (input.args().length == 1) {
- String arg = input.args()[0]
- if (arg == '-?' || arg == '--help') {
- printer.println(helpDesc('/console'))
- return
- } else {
- throw new IllegalArgumentException('Unknown command parameter: ' + input.args()[0])
+ saveFile(engine, new File(arg), overwrite)
+ }
+
+ static void saveFile(GroovyEngine engine, File file, boolean overwrite = false) {
+ if (!file && overwrite) {
+ throw new IllegalArgumentException('File to overwrite not found: ' + file.path)
+ }
+ if (file && !overwrite) {
+ throw new IllegalArgumentException("Can't overwrite existing file: " + file.path)
+ }
+ file.text = engine.buffer
+ println "Saved: " + file.path
+ }
+
+ void load(CommandInput input) {
+ checkArgCount(input, [1, 2])
+ if (maybePrintHelp(input, '/load')) return
+ boolean merge = false
+ String arg = input.args()[0]
+ if (arg == '-m' || arg == '--merge') {
+ merge = true
+ arg = input.args()[1]
+ }
+ loadFile(engine, new File(arg), merge)
+ }
+
+ static void loadFile(GroovyEngine engine, File file, boolean merge = false) {
+ if (!file) {
+ throw new IllegalArgumentException('File not found: ' + file.path)
+ }
+ if (!merge) {
+ engine.reset()
+ }
+ def unprocessed = []
+ file.readLines().each { line ->
+ try {
+ unprocessed << line
+ engine.execute(unprocessed.join('\n'))
+ unprocessed.clear()
+ } catch (Exception ignore) {
+ // ignore
+ }
+ }
+ println "Loaded: " + file.path
+ }
+
+ private highlight(Collection<String> lines) {
+ highlighter.highlight(lines.collect{ ' \b' + it }.join('\n\n')).toAnsi()
+ }
+
+ boolean maybePrintHelp(CommandInput input, String name) {
+ if (!input.args()) return false
+ String arg = input.args()[0]
+ if (arg == '-?' || arg == '--help') {
+ printer.println(helpDesc(name))
+ return true
+ }
+ return false
+ }
+
+ boolean maybeRemoveItem(CommandInput input, String name, Map<String, String> aggregate, Closure remove) {
+ if (input.args().length == 2) {
+ if (input.args()[0] == '-d' || input.args()[0] == '--delete') {
+ def toRemove = []
+ if (name == '*') {
+ toRemove.addAll(aggregate.keySet())
+ } else if (name.endsWith('*')) {
+ String prefix = name[0..-2]
+ toRemove.addAll(aggregate.keySet().findAll { key -> key.startsWith(prefix) })
+ } else if (name.startsWith('*')) {
+ String suffix = name[1..-1]
+ toRemove.addAll(aggregate.keySet().findAll { key -> key.endsWith(suffix) })
+ } else {
+ toRemove.add(name)
+ }
+ toRemove.each{ remove(it) }
+ return true
}
}
+ return false
+ }
+
+ private static void checkArgCount(CommandInput input, Collection<Integer> nums) {
+ if (input.args().length !in nums) {
+ throw new IllegalArgumentException('Wrong number of command parameters: ' + input.args().length)
+ }
+ }
+
+ void importsCommand(CommandInput input) {
+ checkArgCount(input, [0, 1, 2])
+ if (maybePrintHelp(input, '/imports')) return
+ if (!input.args()) printer.println(highlight(engine.imports.values()))
+ else {
+ String name = input.args()[-1]
+ if (maybeRemoveItem(input, name, engine.imports, engine::removeImport)) return
+ String source = engine.imports.get(name)
+ if (source) printer.println(highlight([source]))
+ }
+ }
+
+ void typesCommand(CommandInput input) {
+ checkArgCount(input, [0, 1, 2])
+ if (maybePrintHelp(input, '/types')) return
+ if (!input.args()) printer.println(highlight(engine.types.values()))
+ else {
+ String name = input.args()[-1]
+ if (maybeRemoveItem(input, name, engine.types, engine::removeType)) return
+ String source = engine.types.get(name)
+ if (source) printer.println(highlight([source]))
+ }
+ }
+
+ void methodsCommand(CommandInput input) {
+ checkArgCount(input, [0, 1, 2])
+ if (maybePrintHelp(input, '/methods')) return
+ if (!input.args()) printer.println(highlight(engine.methods.values()))
+ else {
+ String name = input.args()[-1]
+ if (maybeRemoveItem(input, name, engine.methods, engine::removeMethod)) return
+ List<String> sources = engine.methods.entrySet().findAll{ e -> e.key.startsWith("$name(") }*.value
+ if (sources) printer.println(highlight(sources))
+ }
+ }
+
+ void console(CommandInput input) {
+ checkArgCount(input, [0, 1])
+ if (maybePrintHelp(input, '/console')) return
Console c = new Console(engine.sharedData)
+ def poller = new javax.swing.Timer(100, null)
+ poller.addActionListener({ e ->
+ if (c.inputArea != null) {
+ poller.stop()
+ c.inputArea.text = engine.buffer
+ }
+ } as ActionListener)
+ poller.start()
c.run()
}
@@ -204,21 +348,21 @@ class GroovyCommands extends JlineCommandRegistry implements CommandRegistry {
Map<String, Object> options = [:]
if (option == '-m' || option == '--methods') {
out = inspector.methods()
- options.put(Printer.COLUMNS, ObjectInspector.METHOD_COLUMNS)
+ options[Printer.COLUMNS] = ObjectInspector.METHOD_COLUMNS
} else if (option == '-n' || option == '--metaMethods') {
out = inspector.metaMethods()
- options.put(Printer.COLUMNS, ObjectInspector.METHOD_COLUMNS)
+ options[Printer.COLUMNS] = ObjectInspector.METHOD_COLUMNS
} else if (option == '-i' || option == '--info') {
out = inspector.properties()
- options.put(Printer.VALUE_STYLE, engine.groovyOption(GroovyEngine.NANORC_VALUE, DEFAULT_NANORC_VALUE))
+ options[Printer.VALUE_STYLE] = engine.groovyOption(GroovyEngine.NANORC_VALUE, DEFAULT_NANORC_VALUE)
} else if (consoleUi && (option == '-g' || option == '--gui')) {
ObjectBrowser.inspect(obj)
} else {
throw new IllegalArgumentException('Unknown option: ' + option)
}
- options.put(Printer.SKIP_DEFAULT_OPTIONS, true)
- options.put(Printer.MAX_DEPTH, 1)
- options.put(Printer.INDENTION, 4)
+ options[Printer.SKIP_DEFAULT_OPTIONS] = true
+ options[Printer.MAX_DEPTH] = 1
+ options[Printer.INDENTION] = 4
printer.println(options, out)
} catch (Exception e) {
saveException(e)
@@ -227,9 +371,7 @@ class GroovyCommands extends JlineCommandRegistry implements CommandRegistry {
}
private classLoader(CommandInput input) {
- if (input.args().length > 2) {
- throw new IllegalArgumentException('Wrong number of command parameters: ' + input.args().length)
- }
+ checkArgCount(input, [0, 1])
String option = '--view'
String arg = null
if (input.args().length) {
@@ -302,30 +444,48 @@ class GroovyCommands extends JlineCommandRegistry implements CommandRegistry {
}
private CmdDesc grabCmdDesc(String name) {
- new CmdDesc([], [
+ new CmdDesc([
+ new AttributedString("$name [OPTIONS] <group>:<artifact>:<version>"),
+ new AttributedString("$name --list")
+ ], [], [
'-? --help' : doDescription('Displays command help'),
'-l --list' : doDescription('List the modules in the cache'),
'-v --verbose' : doDescription('Report downloads')
- ]).tap {
- mainDesc = [
- new AttributedString("$name [OPTIONS] <group>:<artifact>:<version>"),
- new AttributedString("$name --list")
- ]
- highlighted = false
- }
+ ])
+ }
+
+ private CmdDesc defCmdDesc(String name) {
+ new CmdDesc([
+ new AttributedString(name),
+ ], [], [
+ '-? --help' : doDescription('Displays command help')
+ ])
}
- private CmdDesc consoleCmdDesc(String name) {
- new CmdDesc([], [
+ private CmdDesc nameCmdDesc(String name) {
+ new CmdDesc([
+ new AttributedString("$name [name]"),
+ ], [], [
'-? --help' : doDescription('Displays command help'),
- '-l --list' : doDescription('List the modules in the cache'),
- '-v --verbose' : doDescription('Report downloads')
- ]).tap {
- mainDesc = [
- new AttributedString(name),
- ]
- highlighted = false
- }
+ ])
+ }
+
+ private CmdDesc nameDeleteCmdDesc(String name) {
+ new CmdDesc([
+ new AttributedString("$name [options] [name]"),
+ ], [], [
+ '-? --help' : doDescription('Displays command help'),
+ '-d --delete' : doDescription('Delete the named item'),
+ ])
+ }
+
+ private CmdDesc loadCmdDesc(String name) {
+ new CmdDesc([
+ new AttributedString("$name filename"),
+ ], [], [
+ '-? --help' : doDescription('Displays command help'),
+ '-m --merge' : doDescription('Merge into existing buffer')
+ ])
}
private CmdDesc inspectCmdDesc(String name) {
@@ -338,26 +498,20 @@ class GroovyCommands extends JlineCommandRegistry implements CommandRegistry {
if (consoleUi) {
optDescs['-g --gui'] = doDescription('Launch object browser')
}
- new CmdDesc([], optDescs).tap {
- mainDesc = [
- new AttributedString("$name [OPTION] OBJECT"),
- ]
- highlighted = false
- }
+ new CmdDesc([
+ new AttributedString("$name [OPTION] OBJECT"),
+ ], [], optDescs)
}
private CmdDesc classLoaderCmdDesc(String name) {
- new CmdDesc([], [
+ new CmdDesc([
+ new AttributedString(name),
+ ], [], [
'-? --help' : doDescription('Displays command help'),
'-v --view' : doDescription('View class loader info'),
'-d --delete [REGEX]' : doDescription('Delete loaded classes'),
'-a --add PATH' : doDescription('Add classpath PATH - a jar file or a directory')
- ]).tap {
- mainDesc = [
- new AttributedString(name),
- ]
- highlighted = false
- }
+ ])
}
private List<AttributedString> doDescription(String description) {
@@ -382,7 +536,6 @@ class GroovyCommands extends JlineCommandRegistry implements CommandRegistry {
private List<OptDesc> compileOptDescs(String command) {
def tuple = commands[command]
List<OptDesc> out = []
-
for (Map.Entry<String, List<AttributedString>> entry : tuple.v3(command).optsDesc.entrySet() ) {
String[] option = entry.getKey().split(/\s+/)
String desc = entry.value.get(0).toString()
@@ -406,6 +559,63 @@ class GroovyCommands extends JlineCommandRegistry implements CommandRegistry {
new OptDesc('-v', '--view', NullCompleter.INSTANCE)]
[new ArgumentCompleter(NullCompleter.INSTANCE, new OptionCompleter(argsCompleters, options, 1))]
}
+/*
+ Completer getCompleter() {
+ // need a different completer setup due to static import
+ Completer impCompleter = new StringsCompleter(name + ' ', shortcut + ' ')
+ Completer asCompleter = new StringsCompleter('as ')
+ Completer nullCompleter = NullCompleter.INSTANCE
+ org.apache.groovy.groovysh.util.PackageHelper packageHelper = shell.packageHelper
+ Interpreter interp = shell.interp
+ Completer nonStaticCompleter = new StricterArgumentCompleter([
+ impCompleter,
+ new ImportCompleter(packageHelper, interp, false),
+ asCompleter,
+ nullCompleter])
+ Completer staticCompleter = new StricterArgumentCompleter([
+ impCompleter,
+ new StringsCompleter('static '),
+ new ImportCompleter(packageHelper, interp, true),
+ asCompleter,
+ nullCompleter])
+ Collection<Completer> argCompleters = [
+ nonStaticCompleter,
+ staticCompleter]
+ return new AggregateCompleter(argCompleters)
+
+ }
+*/
+ private List<Completer> loadCompleter(String command) {
+ [new ArgumentCompleter(NullCompleter.INSTANCE, new OptionCompleter(new Completers.FilesCompleter(workDir), this::compileOptDescs, 1))]
+ }
+
+ private List<Completer> saveCompleter(String command) {
+ [new ArgumentCompleter(NullCompleter.INSTANCE, new OptionCompleter(new Completers.FilesCompleter(workDir), this::compileOptDescs, 1))]
+ }
+
+ private List<Completer> importsCompleter(String command) {
+ [new ArgumentCompleter(NullCompleter.INSTANCE,
+ new OptionCompleter([new StringsCompleter((Supplier)() -> engine.imports.keySet()), NullCompleter.INSTANCE], this::compileOptDescs, 1))]
+/* Completer impCompleter = new StringsCompleter('/import ')
+ Completer asCompleter = new StringsCompleter('as ')
+ Completer nullCompleter = NullCompleter.INSTANCE
+// org.apache.groovy.groovysh.util.PackageHelper packageHelper = shell.packageHelper
+// Interpreter interp = shell.interp
+ [
+ new StricterArgumentCompleter([
+ impCompleter,
+ new ImportCompleter(packageHelper, interp, false),
+ asCompleter,
+ nullCompleter]),
+ new StricterArgumentCompleter([
+ impCompleter,
+ new StringsCompleter('static '),
+ new ImportCompleter(packageHelper, interp, true),
+ asCompleter,
+ nullCompleter])
+ ]
+*/
+ }
private List<Completer> inspectCompleter(String command) {
[new ArgumentCompleter(NullCompleter.INSTANCE,
@@ -419,9 +629,160 @@ class GroovyCommands extends JlineCommandRegistry implements CommandRegistry {
this::compileOptDescs, 1))]
}
+ private List<Completer> typesCompleter(String command) {
+ [new ArgumentCompleter(NullCompleter.INSTANCE,
+ new OptionCompleter([new StringsCompleter((Supplier)() -> engine.types.keySet()), NullCompleter.INSTANCE],
+ this::compileOptDescs, 1))]
+ }
+
+ private List<Completer> methodsCompleter(String command) {
+ [new ArgumentCompleter(NullCompleter.INSTANCE,
+ new OptionCompleter([new StringsCompleter((Supplier)() -> engine.methodNames), NullCompleter.INSTANCE],
+ this::compileOptDescs, 1))]
+ }
+
private List<Completer> defCompleter(String command) {
[new ArgumentCompleter(NullCompleter.INSTANCE,
new OptionCompleter(NullCompleter.INSTANCE,
this::compileOptDescs, 1)).tap{strict = false }]
}
+/*
+ static class ImportCompleter implements Completer {
+
+ protected final Logger log = Logger.create(ImportCompleter)
+
+ org.apache.groovy.groovysh.util.PackageHelper packageHelper
+ //Groovysh shell
+
+ / *
+ * The following rules do not need to work for all thinkable situations, just for all reasonable situations.
+ * In particular the underscore and dollar signs in Class or method names usually indicate something internal,
+ * which we intentionally want to hide in tab completion
+ * /
+ // matches fully qualified class names with dot at the end
+ private static final Pattern QUALIFIED_CLASS_DOT_PATTERN = ~/^[a-z_]{1}[a-z0-9_]*(\.[a-z0-9_]*)*\.[A-Z][^.]*\.$/
+ // matches empty, package names or fully qualified class names
+ private static final Pattern PACK_OR_CLASSNAME_PATTERN = ~/^([a-z_]{1}[a-z0-9_]*(\.[a-z0-9_]*)*(\.[A-Z][^.]*)?)?$/
+ // matches empty, package names or fully qualified class names without special symbols
+ private static final Pattern PACK_OR_SIMPLE_CLASSNAME_PATTERN = ~'^([a-z_]{1}[a-z0-9_]*(\\.[a-z0-9_]*)*(\\.[A-Z][^.\$_]*)?)?\$'
+ // matches empty, package names or fully qualified class names or fully qualified method names
+ private static final Pattern PACK_OR_CLASS_OR_METHODNAME_PATTERN = ~'^([a-z_]{1}[a-z0-9.]*(\\.[a-z0-9_]*)*(\\.[A-Z][^.\$_]*(\\.[a-zA-Z0-9_]*)?)?)?\$'
+ private static final Pattern LOWERCASE_IMPORT_ITEM_PATTERN = ~/^[a-z0-9.]+$/
+
+ final boolean staticImport
+ final Evaluator interpreter
+
+
+ ImportCompleter(final org.apache.groovy.groovysh.util.PackageHelper packageHelper, final Evaluator interp, final boolean staticImport) {
+ this.packageHelper = packageHelper
+ this.staticImport = staticImport
+ this.interpreter = interp
+ this.shell = shell
+ }
+
+ @Override
+ @CompileStatic
+ void complete(LineReader reader, ParsedLine line, List<Candidate> result) {
+ def buffer = reader.buffer
+ def cursor = line.cursor()
+ String currentImportExpression = buffer ? buffer.substring(0, cursor) : ''
+ if (staticImport) {
+ if (!(currentImportExpression.matches(PACK_OR_CLASS_OR_METHODNAME_PATTERN))) {
+ return
+ }
+ } else {
+ if (!(currentImportExpression.matches(PACK_OR_SIMPLE_CLASSNAME_PATTERN))) {
+ return
+ }
+ }
+ if (currentImportExpression.contains('..')) {
+ return
+ }
+
+ if (currentImportExpression.endsWith('.')) {
+ // no upper case?
+ if (currentImportExpression.matches(LOWERCASE_IMPORT_ITEM_PATTERN)) {
+ Set<String> classnames = packageHelper.getContents(currentImportExpression[0..-2])
+ if (classnames) {
+ if (staticImport) {
+ addAll(result, classnames.collect{ String it -> it + '.' })
+ } else {
+ addAll(result, classnames.collect({ String it -> addDotOrBlank(it) }))
+ }
+ }
+ if (!staticImport) {
+ add(result, '* ')
+ }
+ return //currentImportExpression.length()
+ } else if (staticImport && currentImportExpression.matches(QUALIFIED_CLASS_DOT_PATTERN)) {
+ Class clazz = interpreter.evaluate([currentImportExpression[0..-2]]) as Class
+ if (clazz != null) {
+ Collection<ReflectionCompletionCandidate> members = ReflectionCompleter.getPublicFieldsAndMethods(clazz, '')
+ addAll(result, members.collect({ ReflectionCompletionCandidate it -> it.value.replace('(', '').replace(')', '') + ' ' }))
+ }
+ add(result, '* ')
+ return //currentImportExpression.length()
+ }
+ return
+ } // endif startswith '.', we have a prefix
+
+ String prefix
+ int lastDot = currentImportExpression.lastIndexOf('.')
+ if (lastDot == -1) {
+ prefix = currentImportExpression
+ } else {
+ prefix = currentImportExpression.substring(lastDot + 1)
+ }
+ String baseString = currentImportExpression.substring(0, Math.max(lastDot, 0))
+
+ // expression could be for Classname, or for static methodname
+ if (currentImportExpression.matches(PACK_OR_CLASSNAME_PATTERN)) {
+ Set<String> candidates = packageHelper.getContents(baseString)
+ if (candidates == null || candidates.size() == 0) {
+ // At least give standard package completion, else static keyword is highly annoying
+ Collection<String> standards = ResolveVisitor.DEFAULT_IMPORTS.findAll({ String it -> it.startsWith(currentImportExpression) })
+ if (standards) {
+ addAll(result, standards)
+ return //0
+ }
+ return
+ }
+
+ log.debug(prefix)
+ Collection<String> matches = candidates.findAll({ String it -> it.startsWith(prefix) })
+ if (matches) {
+ addAll(result, matches.collect({ String it -> addDotOrBlank(it) }))
+ return //lastDot <= 0 ? 0 : lastDot + 1
+ }
+ } else if (staticImport) {
+ Class clazz = interpreter.evaluate([baseString]) as Class
+ if (clazz != null) {
+ Collection<ReflectionCompletionCandidate> members = ReflectionCompleter.getPublicFieldsAndMethods(clazz, prefix)
+ if (members) {
+ addAll(result, members.collect({ ReflectionCompletionCandidate it -> it.value.replace('(', '').replace(')', '') + ' ' }))
+ return //lastDot <= 0 ? 0 : lastDot + 1
+ }
+ }
+ }
+ return
+ }
+
+ private static void addAll(List<Candidate> result, List<String> strings) {
+ for (String s : strings) {
+ result.add(new Candidate(s))
+ }
+ }
+
+ private static void add(List<Candidate> result, String s) {
+ result.add(new Candidate(s))
+ }
+
+ private static String addDotOrBlank(final String it) {
+ if (it[0] in 'A'..'Z') {
+ return it + ' '
+ }
+ return it + '.'
+ }
+ }*/
+
}
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 895d5085d9..42155ad8b5 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
@@ -1,10 +1,14 @@
/*
+ * This file was originally on the file of the same name from the jline-groovy module from JLine3
+ * which has the following license:
+ *
* Copyright (c) 2002-2022, the original author(s).
*
* This software is distributable under the BSD license. See the terms of the
* BSD license in the documentation provided with this software.
*
- * https://opensource.org/licenses/BSD-3-Clause
+ * Subsequent modifications to this file were made by the Apache Groovy team
+ * and are under the Apache 2 License.
*/
package org.apache.groovy.groovysh.jline;
@@ -18,6 +22,7 @@ import groovy.lang.MissingPropertyException;
import groovy.lang.Script;
import org.apache.groovy.ast.tools.ImmutablePropertyUtils;
import org.codehaus.groovy.control.messages.SyntaxErrorMessage;
+import org.codehaus.groovy.runtime.DefaultGroovyMethods;
import org.codehaus.groovy.runtime.metaclass.MissingMethodExceptionNoStack;
import org.codehaus.groovy.syntax.SyntaxException;
import org.jline.builtins.Styles;
@@ -76,8 +81,6 @@ import static org.jline.console.ConsoleEngine.VAR_NANORC;
* Implements Groovy ScriptEngine.
* You must be very careful when using GroovyEngine in a multithreaded environment. The Binding instance is not
* thread safe, and it is shared by all scripts.
- *
- * @author <a href="mailto:matti.rintanikkola@gmail.com">Matti Rinta-Nikkola</a>
*/
public class GroovyEngine implements ScriptEngine {
public enum Format {
@@ -103,25 +106,22 @@ public class GroovyEngine implements ScriptEngine {
private static final String VAR_GROOVY_OPTIONS = "GROOVY_OPTIONS";
private static final String DEFAULT_NANORC_SYNTAX = "classpath:/nanorc/jnanorc";
private static final String REGEX_SYSTEM_VAR = "[A-Z]+[A-Z_]*";
- private static final String REGEX_VAR = "[a-zA-Z_]+[a-zA-Z0-9_]*";
- private static final Pattern PATTERN_FUNCTION_DEF = Pattern.compile(
- "^def\\s+(" + REGEX_VAR + ")\\s*\\(([a-zA-Z0-9_ ,]*)\\)\\s*\\{(.*)?}(|\n)$", Pattern.DOTALL);
- private static final Pattern PATTERN_CLASSLIKE_DEF =
- Pattern.compile("^(class|record|interface|trait)\\s+(" + REGEX_VAR + ")\\s*(.*?\\{.*?})(|\n)$", Pattern.DOTALL);
- private static final Pattern PATTERN_CLASS_DEF =
- Pattern.compile("^class\\s+(" + REGEX_VAR + ")\\s*(.*?\\{.*?})(|\n)$", Pattern.DOTALL);
- private static final Pattern PATTERN_TRAIT_DEF =
- Pattern.compile("^trait\\s+(" + REGEX_VAR + ")\\s*(.*?\\{.*?})(|\n)$", Pattern.DOTALL);
- private static final Pattern PATTERN_INTERFACE_DEF =
- Pattern.compile("^interface\\s+(" + REGEX_VAR + ")\\s*(.*?\\{.*?})(|\n)$", Pattern.DOTALL);
- private static final Pattern PATTERN_RECORD_DEF =
- Pattern.compile("^record\\s+(" + REGEX_VAR + ")\\s*(.*?\\{.*?})(|\n)$", Pattern.DOTALL);
+ private static final String BASE_REGEX_VAR = "[\\p{L}_$][\\p{L}\\p{N}_$]*";
+ private static final String REGEX_VAR = "(" + BASE_REGEX_VAR + ")";
+ private static final String METHOD_REGEX_VAR = "(" + BASE_REGEX_VAR + "|\"(?:[^\"\\\\]|\\\\.)*\")";
+ private static final String ANNOTATIONS = "^\\s*(?:@(?!interface)(?:[\\p{L}_$][\\p{L}\\p{N}_$]*\\.)*[\\p{L}_$][\\p{L}\\p{N}_$]*(?:\\([^)]*\\))?\\s*)*";
+ private static final String MODIFIERS = "(?:(?:public|protected|private|abstract|final|static|sealed|non-sealed|strictfp)\\s+)*";
+ private static final String BODY = "\\s*(.*?\\{.*?})(|;|\n)$";
+ private static final Pattern PATTERN_METHOD_DEF = Pattern.compile(
+ "(?ms)" + ANNOTATIONS + MODIFIERS + REGEX_VAR + "\\s+(" + METHOD_REGEX_VAR + "\\s*\\(([a-zA-Z0-9_ ,]*)\\))" + BODY);
+ private static final Pattern PATTERN_TYPE_DEF =
+ Pattern.compile("(?ms)" + ANNOTATIONS + MODIFIERS + "(\\bclass|@?\\binterface|\\benum|\\btrait|\\brecord)\\s+" + REGEX_VAR + BODY);
private static final String REGEX_CLASS = "(.*?)\\.([A-Z_].*)";
private static final Pattern PATTERN_CLASS = Pattern.compile(REGEX_CLASS);
private static final String REGEX_PACKAGE = "([a-z][a-z_0-9]*\\.)*";
private static final String REGEX_CLASS_NAME = "[A-Z_](\\w)*";
private static final Pattern PATTERN_LOAD_CLASS = Pattern.compile(
- "(import\\s+|new\\s+|\\s*)?(" + REGEX_PACKAGE + ")(" + REGEX_CLASS_NAME + ")(\\..*|\\(.*)?");
+ "(import\\s+(static\\s+)|new\\s+|\\s*)?(" + REGEX_PACKAGE + ")(" + REGEX_CLASS_NAME + ")(\\..*|\\(.*)?");
private static final List<String> DEFAULT_IMPORTS = Arrays.asList(
"java.lang.*",
"java.util.*",
@@ -137,10 +137,8 @@ public class GroovyEngine implements ScriptEngine {
protected Binding sharedData;
private final Map<String, String> imports = new HashMap<>();
private final Map<String, String> methods = new HashMap<>();
- private final Map<String, String> classes = new HashMap<>();
- private final Map<String, String> interfaces = new HashMap<>();
- private final Map<String, String> traits = new HashMap<>();
- private final Map<String, String> records = new HashMap<>();
+ private final Set<String> methodNames = new HashSet<>();
+ private final Map<String, String> types = new HashMap<>();
private final Map<String, Class<?>> nameClass;
private Cloner objectCloner = new ObjectCloner();
protected final EngineClassLoader classLoader;
@@ -165,6 +163,22 @@ public class GroovyEngine implements ScriptEngine {
nameClass = new HashMap<>(defaultNameClass);
}
+ public Map<String, String> getTypes() {
+ return DefaultGroovyMethods.asUnmodifiable(types);
+ }
+
+ public Map<String, String> getMethods() {
+ return DefaultGroovyMethods.asUnmodifiable(methods);
+ }
+
+ public Set<String> getMethodNames() {
+ return DefaultGroovyMethods.asUnmodifiable(methodNames);
+ }
+
+ public Map<String, String> getImports() {
+ return DefaultGroovyMethods.asUnmodifiable(imports);
+ }
+
@Override
public Completer getScriptCompleter() {
return compileCompleter();
@@ -340,81 +354,66 @@ public class GroovyEngine implements ScriptEngine {
}
}
+ public String getBuffer() {
+ List<String> parts = new ArrayList<>();
+ parts.add(String.join("\n", imports.values()));
+ parts.addAll(types.values());
+ parts.addAll(methods.values());
+ return String.join("\n\n", parts);
+ }
+
@Override
public Object execute(String statement) throws Exception {
Object out = null;
- if (statement.matches("import\\s+(static\\s+)?(([^;\\s])+)\\s*(;)?")) {
+ if (statement.matches("import\\s+(static\\s+)?(([^;\\s])+)(?:\\s+as\\s+(" + BASE_REGEX_VAR + "))?\\s*(;)?")) {
String[] p = statement.split("\\s+");
int classIdx = 1;
boolean isStatic = p[1].equals("static");
if (isStatic) {
classIdx++;
}
- String classname = p[classIdx].replaceAll(";", "");
- addToNameClass(classname);
- if (isStatic) {
- classname = "static " + classname;
+ String classname = null;
+ if (classIdx < p.length) {
+ classname = p[classIdx].replaceAll(";", "");
+ addToNameClass(classname);
+ if (isStatic) {
+ classname = "static " + classname;
+ }
+ // check for alias
+ if (p.length > 3) {
+ classname = p[p.length - 1].replaceAll(";", "");
+ }
}
executeStatement(shell, imports, statement);
- imports.put(classname, statement);
- } else if (statement.equals("import")) {
- List<String> allImports = new ArrayList<>(imports.keySet());
- allImports.addAll(DEFAULT_IMPORTS);
- out = allImports;
- } else if (functionDef(statement)) {
- // do nothing
- } else if (statement.equals("def")) {
- out = methods;
- } else if (statement.equals("class")) {
- out = classes;
- } else if (statement.equals("record")) {
- out = records;
- } else if (statement.equals("trait")) {
- out = traits;
- } else if (statement.equals("interface")) {
- out = interfaces;
- } else if (statement.matches("(def|class|trait|interface|record)\\s+" + REGEX_VAR)) {
- String name = statement.split("\\s+")[1];
- if (statement.startsWith("def") && methods.containsKey(name)) {
- out = "def " + name + methods.get(name);
- } else if (statement.startsWith("class") && classes.containsKey(name)) {
- out = "class " + name + " " + classes.get(name);
- } else if (statement.startsWith("trait") && traits.containsKey(name)) {
- out = "trait " + name + " " + traits.get(name);
- } else if (statement.startsWith("record") && records.containsKey(name)) {
- out = "record " + name + " " + records.get(name);
- } else if (statement.startsWith("interface") && interfaces.containsKey(name)) {
- out = "interface " + name + " " + interfaces.get(name);
+ if (classname != null) {
+ imports.put(classname, statement);
}
+ } else if (methodDef(statement)) {
+ // do nothing
} else {
- out = executeStatement(shell, imports, statement);
+ out = executeStatement(shell, imports, methods, statement);
classLoader.purgeClassCache();
- if (PATTERN_CLASS_DEF.matcher(statement).matches()) {
- Matcher matcher = PATTERN_CLASS_DEF.matcher(statement);
- matcher.matches();
- classes.put(matcher.group(1), matcher.group(2));
- addToNameClass(matcher.group(1));
- } else if (PATTERN_TRAIT_DEF.matcher(statement).matches()) {
- Matcher matcher = PATTERN_TRAIT_DEF.matcher(statement);
- matcher.matches();
- traits.put(matcher.group(1), matcher.group(2));
- addToNameClass(matcher.group(1));
- } else if (PATTERN_INTERFACE_DEF.matcher(statement).matches()) {
- Matcher matcher = PATTERN_INTERFACE_DEF.matcher(statement);
- matcher.matches();
- interfaces.put(matcher.group(1), matcher.group(2));
- addToNameClass(matcher.group(1));
- } else if (PATTERN_RECORD_DEF.matcher(statement).matches()) {
- Matcher matcher = PATTERN_RECORD_DEF.matcher(statement);
- matcher.matches();
- records.put(matcher.group(1), matcher.group(2));
- addToNameClass(matcher.group(1));
+ Matcher matcher = PATTERN_TYPE_DEF.matcher(statement);
+ if (matcher.matches()) {
+ types.put(matcher.group(2), removeTrailingSemi(matcher.group(0)));
+ addToNameClass(matcher.group(2));
}
}
return out;
}
- private static Object executeStatement(GroovyShell shell, Map<String, String> imports, String statement)
+ private static String removeTrailingSemi(String statement) {
+ if (statement.endsWith(";")) {
+ return statement.substring(0, statement.length() - 1).trim();
+ }
+ return statement;
+ }
+
+ private static Object executeStatement(GroovyShell shell, Map<String, String> imports, String statement) throws IOException {
+ return executeStatement(shell, imports, new HashMap<>(), statement);
+ }
+
+ private static Object executeStatement(GroovyShell shell, Map<String, String> imports, Map<String, String> methods, String statement)
throws IOException {
int idx = statement.indexOf("=") + 1;
Matcher matcher = PATTERN_LOAD_CLASS.matcher(statement.substring(idx));
@@ -449,12 +448,15 @@ public class GroovyEngine implements ScriptEngine {
}
}
StringBuilder e = new StringBuilder();
- for (Map.Entry<String, String> entry : imports.entrySet()) {
- e.append(entry.getValue()).append("\n");
+ for (String importVal : imports.values()) {
+ e.append(importVal).append("\n");
+ }
+ for (String methodVal : methods.values()) {
+ e.append(methodVal).append("\n");
}
e.append(statement);
- if (classLikeDef(statement)) {
- e.append("; null");
+ if (typeDef(statement)) {
+ e.append("\nnull");
}
return shell.evaluate(e.toString());
}
@@ -495,19 +497,20 @@ public class GroovyEngine implements ScriptEngine {
return out;
}
- private boolean functionDef(String statement) throws Exception {
+ private boolean methodDef(String statement) throws Exception {
boolean out = false;
- Matcher m = PATTERN_FUNCTION_DEF.matcher(statement);
+ Matcher m = PATTERN_METHOD_DEF.matcher(statement);
if (m.matches()) {
out = true;
- put(m.group(1), execute("{" + m.group(2) + "->" + m.group(3) + "}"));
- methods.put(m.group(1), "(" + m.group(2) + ")" + "{" + m.group(3) + "}");
+ String code = removeTrailingSemi(m.group(0));
+ methodNames.add(m.group(3));
+ methods.put(m.group(2), code);
}
return out;
}
- private static boolean classLikeDef(String statement) {
- return PATTERN_CLASSLIKE_DEF.matcher(statement).matches();
+ private static boolean typeDef(String statement) {
+ return PATTERN_TYPE_DEF.matcher(statement).matches();
}
private void refreshNameClass() {
@@ -516,48 +519,67 @@ public class GroovyEngine implements ScriptEngine {
for (String name : imports.keySet()) {
addToNameClass(name);
}
- for (String name : classes.keySet()) {
+ for (String name : types.keySet()) {
addToNameClass(name);
}
}
+ public void reset() {
+ types.clear();
+ methods.clear();
+ methodNames.clear();
+ classLoader.purgeClassCache();
+ refreshNameClass();
+ }
+
private void del(String var) {
if (var == null) {
return;
}
if (imports.containsKey(var)) {
- imports.remove(var);
- if (var.endsWith(".*")) {
- refreshNameClass();
- } else {
- classLoader.purgeClassCache(var + "(\\$.*)?");
- nameClass.remove(var.substring(var.lastIndexOf('.') + 1));
- }
+ removeImport(var);
+ } else if (methods.containsKey(var)) {
+ removeMethod(var);
} else if (sharedData.hasVariable(var)) {
sharedData.getVariables().remove(var);
- methods.remove(var);
- } else if (classes.containsKey(var)) {
- classes.remove(var);
- classLoader.purgeClassCache(var + "(\\$.*)?");
- } else if (interfaces.containsKey(var)) {
- interfaces.remove(var);
- classLoader.purgeClassCache(var + "(\\$.*)?");
- } else if (records.containsKey(var)) {
- records.remove(var);
- classLoader.purgeClassCache(var + "(\\$.*)?");
- } else if (traits.containsKey(var)) {
- traits.remove(var);
- classLoader.purgeClassCache(var + "(\\$.*)?");
+ } else if (types.containsKey(var)) {
+ removeType(var);
} else if (!var.contains(".") && var.contains("*")) {
for (String v : internalFind(var)) {
if (sharedData.hasVariable(v) && !v.equals("_") && !v.matches(REGEX_SYSTEM_VAR)) {
sharedData.getVariables().remove(v);
- methods.remove(v);
}
}
}
}
+ public void removeMethod(String name) {
+ if (name.contains("(")) {
+ methods.remove(name);
+ String prefix = name.substring(0, name.indexOf('('));
+ methodNames.remove(prefix);
+ } else {
+ methodNames.remove(name);
+ methods.keySet().removeIf(k -> k.startsWith(name + "("));
+ }
+ }
+
+ public void removeImport(String name) {
+ imports.remove(name);
+ if (name.endsWith(".*")) {
+ refreshNameClass();
+ } else {
+ classLoader.purgeClassCache(name + "(\\$.*)?");
+ nameClass.remove(name.substring(name.lastIndexOf('.') + 1));
+ }
+ }
+
+ public void removeType(String name) {
+ types.remove(name);
+ classLoader.purgeClassCache(name + "(\\$.*)?");
+ nameClass.remove(name);
+ }
+
@Override
public void del(String... vars) {
if (vars == null) {
@@ -643,23 +665,27 @@ public class GroovyEngine implements ScriptEngine {
}
private Completer compileCompleter() {
- List<Completer> completers = new ArrayList<>();
- completers.add(new ArgumentCompleter(
- new StringsCompleter("def"), new StringsCompleter(methods::keySet), NullCompleter.INSTANCE));
- completers.add(new ArgumentCompleter(
- new StringsCompleter("class"), new StringsCompleter(classes::keySet), NullCompleter.INSTANCE));
- completers.add(new ArgumentCompleter(
- new StringsCompleter("trait"), new StringsCompleter(traits::keySet), NullCompleter.INSTANCE));
- completers.add(new ArgumentCompleter(
- new StringsCompleter("interface"), new StringsCompleter(interfaces::keySet), NullCompleter.INSTANCE));
- completers.add(new ArgumentCompleter(
- new StringsCompleter("record"), new StringsCompleter(records::keySet), NullCompleter.INSTANCE));
- completers.add(new ArgumentCompleter(
- new StringsCompleter("import"),
- new PackageCompleter(CandidateType.PACKAGE, this),
- NullCompleter.INSTANCE));
- completers.add(new MethodCompleter(this));
- return new AggregateCompleter(completers);
+ Completer importCompleter = new StringsCompleter("import");
+ Completer asCompleter = new AsCompleter();
+
+ Completer normalImportCompleter = new ArgumentCompleter(
+ importCompleter,
+ new ImportCompleter(this, false),
+ asCompleter,
+ NullCompleter.INSTANCE);
+
+ Completer staticImportCompleter = new ArgumentCompleter(
+ importCompleter,
+ new StringsCompleter("static"),
+ new ImportCompleter(this, true),
+ asCompleter,
+ NullCompleter.INSTANCE);
+
+ return new AggregateCompleter(Arrays.asList(
+ normalImportCompleter,
+ staticImportCompleter,
+ new MethodCompleter(this)
+ ));
}
private enum CandidateType {
@@ -1114,6 +1140,63 @@ public class GroovyEngine implements ScriptEngine {
}
}
+ private static class AsCompleter implements Completer {
+ private final Completer delegate = new StringsCompleter("as");
+
+ @Override
+ public void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) {
+ String buffer = line.word().substring(0, line.wordCursor());
+ if (buffer.trim().endsWith("*")) return;
+ delegate.complete(reader, line, candidates);
+ }
+ }
+
+ private static class ImportCompleter implements Completer {
+ private final GroovyEngine groovyEngine;
+ private final boolean isStatic;
+
+ public ImportCompleter(GroovyEngine groovyEngine, boolean isStatic) {
+ this.groovyEngine = groovyEngine;
+ this.isStatic = isStatic;
+ }
+
+ @Override
+ public void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) {
+ assert line != null;
+ assert candidates != null;
+ String buffer = line.word().substring(0, line.wordCursor());
+ String curBuf = "";
+ int lastDelim = buffer.lastIndexOf('.');
+ if (lastDelim > -1) {
+ curBuf = buffer.substring(0, lastDelim + 1);
+ }
+ if (isStatic && curBuf.endsWith(".")) {
+ try {
+ Class cls = (Class) groovyEngine.shell.evaluate(curBuf.substring(0, lastDelim));
+ String prefix = buffer.substring(lastDelim + 1);
+ for (Field f : cls.getFields()) {
+ if (Modifier.isStatic(f.getModifiers()) && f.getName().startsWith(prefix)) {
+ candidates.add(new Candidate(curBuf + f.getName(), f.getName(), "Fields",null, null, null, true, 0));
+ }
+ }
+ for (Method m : cls.getMethods()) {
+ if (Modifier.isStatic(m.getModifiers()) && m.getName().startsWith(prefix)) {
+ candidates.add(new Candidate(curBuf + m.getName(), m.getName(), "Methods",null, null, null, true, 0));
+ }
+ }
+ if (!candidates.isEmpty()) return;
+ } catch(Exception ignore) {
+ }
+ }
+
+ Helpers.doCandidates(
+ candidates,
+ Helpers.nextDomain(curBuf, new AccessRules(groovyEngine.groovyOptions()), CandidateType.PACKAGE, groovyEngine.shell),
+ curBuf,
+ CandidateType.PACKAGE);
+ }
+ }
+
private static class PackageCompleter implements Completer {
private final CandidateType type;
private final GroovyEngine groovyEngine;
@@ -1124,10 +1207,10 @@ public class GroovyEngine implements ScriptEngine {
}
@Override
- public void complete(LineReader reader, ParsedLine commandLine, List<Candidate> candidates) {
- assert commandLine != null;
+ public void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) {
+ assert line != null;
assert candidates != null;
- String buffer = commandLine.word().substring(0, commandLine.wordCursor());
+ String buffer = line.word().substring(0, line.wordCursor());
String curBuf = "";
int lastDelim = buffer.lastIndexOf('.');
if (lastDelim > -1) {
@@ -1251,7 +1334,7 @@ public class GroovyEngine implements ScriptEngine {
clazz = inspector.evaluateClass(wordbuffer.substring(eqsep + 1, varsep));
involvedObject = inspector.getInvolvedObject();
}
- Helpers.doCandidates(candidates, retrieveDecleredClasses(clazz), curBuf, CandidateType.CLASSES);
+ Helpers.doCandidates(candidates, retrieveDeclaredClasses(clazz), curBuf, CandidateType.CLASSES);
doMethodCandidates(candidates, involvedObject, clazz, curBuf);
} else if (inspector.hasVariable(var)) {
if (firstMethod) {
@@ -1459,7 +1542,7 @@ public class GroovyEngine implements ScriptEngine {
return out;
}
- private Set<String> retrieveDecleredClasses(Class<?> clazz) {
+ private Set<String> retrieveDeclaredClasses(Class<?> clazz) {
Set<String> out = new HashSet<>();
if (clazz != null && !clazz.isEnum()) {
int nameLength = clazz.getCanonicalName().length();
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovySystemRegistry.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovySystemRegistry.groovy
index 06ea558204..250d19c5e1 100644
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovySystemRegistry.groovy
+++ b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/jline/GroovySystemRegistry.groovy
@@ -1,3 +1,21 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
package org.apache.groovy.groovysh.jline
import org.jline.builtins.ConfigurationPath
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/util/CommandArgumentParser.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/util/CommandArgumentParser.groovy
deleted file mode 100644
index 909621447d..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/util/CommandArgumentParser.groovy
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.util
-
-import groovy.transform.CompileStatic
-
-@CompileStatic
-class CommandArgumentParser {
-
- /**
- * takes a String and tokenizes it according to posix-shell-like rules, meaning
- * arguments are separated by non-escaped blanks or hyphens, and hyphens wrap tokens regardless
- * of blanks, other hyphens or escaped hyphens within the wrapping hyphens.
- *
- * Example: "foo bar 123'456' 'abc\'def\\' ''" has 6 tokens:
- * ["foo", "bar", "123", "456", "abc'def\", ""]
- *
- * @param untrimmedLine
- * @param numTokensToCollect stop processing after so many tokens, negative means unlimited
- * @return
- */
- static List<String> parseLine(final String untrimmedLine, final int numTokensToCollect = -1) {
- assert untrimmedLine != null
-
- final String line = untrimmedLine.trim()
- List<String> tokens = []
- String currentToken = ''
- // state machine being either in neutral state, in singleHyphenOpen state, or in doubleHyphenOpen State.
- boolean singleHyphenOpen = false
- boolean doubleHyphenOpen = false
- int index = 0
- for (; index < line.length(); index++) {
- if (tokens.size() == numTokensToCollect) {
- break
- }
- String ch = line.charAt(index)
- // escaped char? -> maybe unescape
- if (ch == '\\') {
- if (index >= line.length() - 1) {
- // end reached
- currentToken += ch
- continue
- }
- if (singleHyphenOpen || doubleHyphenOpen) {
- // add escaped, no other parsing action
- currentToken += ch
- index++
- currentToken += line.charAt(index)
- continue
- } else {
- // unescape, only add char after, no parsing action
- index++
- currentToken += line.charAt(index)
- continue
- }
- }
-
- if (ch == '"' && !singleHyphenOpen) {
- if (doubleHyphenOpen) {
- tokens.add(currentToken)
- currentToken = ''
- doubleHyphenOpen = false
- } else {
- if (currentToken.size() > 0) {
- tokens.add(currentToken)
- currentToken = ''
- }
- doubleHyphenOpen = true
- }
- continue
- }
- if (ch == '\'' && !doubleHyphenOpen) {
- if (singleHyphenOpen) {
- tokens.add(currentToken)
- currentToken = ''
- singleHyphenOpen = false
- } else {
- if (currentToken.size() > 0) {
- tokens.add(currentToken)
- currentToken = ''
- }
- singleHyphenOpen = true
- }
- continue
- }
- if (ch == ' ' && !doubleHyphenOpen && !singleHyphenOpen) {
- if (currentToken.size() > 0) {
- tokens.add(currentToken)
- currentToken = ''
- }
- continue
- }
- currentToken += ch
- } // end for char in line
- if (index == line.length() && doubleHyphenOpen) {
- throw new IllegalArgumentException('Missing closing " in ' + line + ' -- ' + tokens)
- }
- if (index == line.length() && singleHyphenOpen) {
- throw new IllegalArgumentException('Missing closing \' in ' + line + ' -- ' + tokens)
- }
- if (currentToken.size() > 0) {
- tokens.add(currentToken)
- }
- return tokens
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/util/DefaultCommandsRegistrar.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/util/DefaultCommandsRegistrar.groovy
deleted file mode 100644
index 31eaf20ea3..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/util/DefaultCommandsRegistrar.groovy
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.util
-
-import org.apache.groovy.groovysh.Command
-import org.apache.groovy.groovysh.Shell
-
-import org.apache.groovy.groovysh.commands.DisplayCommand
-import org.apache.groovy.groovysh.commands.EditCommand
-import org.apache.groovy.groovysh.commands.ExitCommand
-import org.apache.groovy.groovysh.commands.GrabCommand
-import org.apache.groovy.groovysh.commands.HelpCommand
-import org.apache.groovy.groovysh.commands.HistoryCommand
-import org.apache.groovy.groovysh.commands.ImportCommand
-import org.apache.groovy.groovysh.commands.InspectCommand
-import org.apache.groovy.groovysh.commands.LoadCommand
-import org.apache.groovy.groovysh.commands.PurgeCommand
-import org.apache.groovy.groovysh.commands.RecordCommand
-import org.apache.groovy.groovysh.commands.RegisterCommand
-import org.apache.groovy.groovysh.commands.ResetCommand
-import org.apache.groovy.groovysh.commands.SaveCommand
-import org.apache.groovy.groovysh.commands.SetCommand
-import org.apache.groovy.groovysh.commands.ShowCommand
-
-/**
- * Registers default {@link Command} instances.
- */
-class DefaultCommandsRegistrar {
-
- private final Shell shell
-
- DefaultCommandsRegistrar(final Shell shell) {
- assert shell != null
- this.shell = shell
- }
-
- void register() {
- List<Command> commands = [
- new HelpCommand(shell),
- new ExitCommand(shell),
- new ImportCommand(shell),
- new DisplayCommand(shell),
- new ResetCommand(shell),
-// new ClearCommand(shell),
-// new ShowCommand(shell),
-// new InspectCommand(shell),
- new PurgeCommand(shell),
- new EditCommand(shell),
- new LoadCommand(shell),
- new SaveCommand(shell),
- new RecordCommand(shell),
- new HistoryCommand(shell),
- new SetCommand(shell),
- new GrabCommand(shell),
- new RegisterCommand(shell),
- ]
-
-// if (!Boolean.getBoolean('groovysh.disableDocCommand')) {
-// commands.add(new DocCommand(shell))
-// }
-
- for (command in commands) {
- shell.register(command)
- }
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/util/PackageHelper.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/util/PackageHelper.groovy
deleted file mode 100644
index a6468a1fee..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/util/PackageHelper.groovy
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.util
-
-interface PackageHelper {
-
- public static final String IMPORT_COMPLETION_PREFERENCE_KEY = 'disable-import-completion'
-
- Set<String> getContents(final String packagename)
-
- void reset()
-
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/util/PackageHelperImpl.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/util/PackageHelperImpl.groovy
deleted file mode 100644
index 6a98b8f518..0000000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/util/PackageHelperImpl.groovy
+++ /dev/null
@@ -1,461 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.groovy.groovysh.util
-
-import groovy.transform.AutoFinal
-import groovy.transform.CompileDynamic
-import groovy.transform.CompileStatic
-import org.codehaus.groovy.tools.shell.util.Logger
-import org.codehaus.groovy.tools.shell.util.Preferences
-
-import java.nio.file.InvalidPathException
-import java.nio.file.Paths
-import java.util.jar.JarEntry
-import java.util.jar.JarFile
-import java.util.prefs.PreferenceChangeEvent
-import java.util.prefs.PreferenceChangeListener
-import java.util.regex.Pattern
-
-/**
- * Helper class that crawls all items of the classpath for packages.
- * Retrieves from those sources the list of subpackages and classes on demand.
- */
-@AutoFinal @CompileStatic
-class PackageHelperImpl implements PreferenceChangeListener, PackageHelper {
-
- protected static final Logger LOG = Logger.create(PackageHelperImpl)
-
- /** Pattern for regular class names. */
- public static final Pattern NAME_PATTERN = ~('^[A-Z][^.\$_]+\$')
-
- private static final String CLASS_SUFFIX = '.class'
-
- Map<String, CachedPackage> rootPackages
- final ClassLoader groovyClassLoader
-
- PackageHelperImpl(ClassLoader groovyClassLoader = null) {
- this.groovyClassLoader = groovyClassLoader
- initializePackages()
- Preferences.addChangeListener(this)
- }
-
- @Override
- void reset() {
- initializePackages()
- }
-
- private void initializePackages() {
- if (!Boolean.valueOf(Preferences.get(IMPORT_COMPLETION_PREFERENCE_KEY))) {
- rootPackages = getPackages(this.groovyClassLoader)
- }
- }
-
- @Override
- void preferenceChange(PreferenceChangeEvent evt) {
- if (evt.key == IMPORT_COMPLETION_PREFERENCE_KEY) {
- if (Boolean.valueOf(evt.getNewValue())) {
- rootPackages = null
- } else if (rootPackages == null) {
- initializePackages()
- }
- }
- }
-
- private static Map<String, CachedPackage> getPackages(ClassLoader groovyClassLoader) throws IOException {
- Map<String, CachedPackage> rootPackages = new HashMap()
- Set<URL> urls = new HashSet<>()
-
- // classes in CLASSPATH
- for (ClassLoader loader = groovyClassLoader; loader != null; loader = loader.parent) {
- if (!(loader instanceof URLClassLoader)) {
- LOG.debug('Ignoring classloader for completion: ' + loader)
- continue
- }
-
- urls.addAll(((URLClassLoader)loader).URLs)
- }
-
- // System classes
- Class<?>[] systemClasses = [String, javax.swing.JFrame, GroovyObject] as Class[]
- boolean jigsaw = false
- systemClasses.each { Class systemClass ->
- // normal slash even in Windows
- String classfileName = systemClass.name.replace('.', '/') + CLASS_SUFFIX
- URL classURL = systemClass.getResource(classfileName)
- if (classURL == null) {
- // this seems to work on Windows better than the earlier approach
- classURL = Thread.currentThread().contextClassLoader.getResource(classfileName)
- }
- if (classURL != null) {
- URLConnection uc = classURL.openConnection()
- if (uc instanceof JarURLConnection) {
- urls.add(((JarURLConnection) uc).getJarFileURL())
- } else if (uc.getClass().getSimpleName().equals("JavaRuntimeURLConnection")) {
- // Java 9 Jigsaw detected
- jigsaw = true
- } else {
- String filepath = classURL.toExternalForm()
- String rootFolder = filepath.substring(0, filepath.length() - classfileName.length() - 1)
- urls.add(new URL(rootFolder))
- }
- }
- }
-
- for (URL url : urls) {
- Collection<String> packageNames = getPackageNames(url)
- if (packageNames) {
- mergeNewPackages(packageNames, url, rootPackages)
- }
- }
- if (jigsaw || isModularRuntime()) {
- URL jigsawURL = URI.create("jrt:/").toURL()
- Set<String> jigsawPackages = getPackagesAndClassesFromJigsaw(jigsawURL) { isPackage, name -> isPackage && name }
- mergeNewPackages(jigsawPackages, jigsawURL, rootPackages)
- }
- return rootPackages
- }
-
- // TODO: review after jdk9 is released
- @CompileDynamic
- private static boolean isModularRuntime() {
- try {
- return this.classLoader.loadClass('java.lang.reflect.Module', false) != null
- } catch (e) {
- return false
- }
- }
-
- /**
- * Returns packages or classes listed from Jigsaw modules. It makes use of a
- * GroovyShell in order to avoid a hard dependency to JDK 7+ when building
- * the Groovysh module (uses nio2).
- */
- private static Set<String> getPackagesAndClassesFromJigsaw(URL jigsawURL, Closure<Boolean> predicate) {
- def shell = new GroovyShell()
- shell.setProperty('predicate', predicate)
- String jigsawURLString = jigsawURL.toString()
- shell.setProperty('jigsawURLString', jigsawURLString)
- shell.evaluate '''import java.nio.file.*
-
-def fs = FileSystems.newFileSystem(URI.create(jigsawURLString), [:])
-
-result = [] as Set
-
-def filterPackageName(Path path) {
- def elems = "$path".split('/')
-
- if (elems && elems.length > 2) {
- // remove e.g. 'modules/java.base/
- elems = elems[2..<elems.length]
-
- def name = elems.join('.')
- if (predicate(true, name)) {
- result << name
- }
- }
-}
-
-def filterClassName(Path path) {
- def elems = "$path".split('/')
-
- if (elems && elems.length > 2) {
- // remove e.g. 'modules/java.base/
- elems = elems[2..<elems.length]
-
- def name = elems.join('.')
- if (name.endsWith('.class')) {
- name = name.substring(0, name.lastIndexOf('.'))
- if (predicate(false, name)) {
- result << name
- }
- }
- }
-}
-
-class GroovyFileVisitor extends SimpleFileVisitor {}
-
-// walk each file and directory, possibly storing directories as packages, and files as classes
-Files.walkFileTree(fs.getPath('modules'),
- [preVisitDirectory: { dir, attrs -> filterPackageName(dir); FileVisitResult.CONTINUE },
- visitFile: { file, attrs -> filterClassName(file); FileVisitResult.CONTINUE}
- ]
- as GroovyFileVisitor)
-'''
-
- Set<String> jigsawPackages = (Set<String>) shell.getProperty('result')
-
- jigsawPackages
- }
-
- static mergeNewPackages(Collection<String> packageNames, URL url, Map<String, CachedPackage> rootPackages) {
- StringTokenizer tokenizer
- packageNames.each { String packname ->
- tokenizer = new StringTokenizer(packname, '.')
- if (!tokenizer.hasMoreTokens()) {
- return
- }
- String rootname = tokenizer.nextToken()
- CachedPackage cp
- CachedPackage childp
- cp = rootPackages.get(rootname, null) as CachedPackage
- if (cp == null) {
- cp = new CachedPackage(rootname, [url] as Set)
- rootPackages.put(rootname, cp)
- }
-
- while(tokenizer.hasMoreTokens()) {
- String packbasename = tokenizer.nextToken()
- if (cp.childPackages == null) {
- // small initial size, to save memory
- cp.childPackages = new HashMap<String, CachedPackage>(1)
- }
- childp = cp.childPackages.get(packbasename, null) as CachedPackage
- if (childp == null) {
- // start with small arraylist, to save memory
- Set<URL> urllist = new HashSet<URL>(1)
- urllist.add(url)
- childp = new CachedPackage(packbasename, urllist)
- cp.childPackages.put(packbasename, childp)
- } else {
- childp.sources.add(url)
- }
- cp = childp
- }
- }
- }
-
- /**
- * Returns all package names found at URL; accepts jar files and folders.
- */
- static Collection<String> getPackageNames(URL url) {
- File urlFile = Paths.get(url.toURI()).toFile()
-
- if (urlFile.isDirectory()) {
- return new HashSet<String>().tap {
- collectPackageNamesFromFolderRecursive(urlFile, '', it)
- }
- }
-
- if (urlFile.path.endsWith('.jar')) {
- try {
- JarFile jarFile = new JarFile(urlFile)
- return getPackageNamesFromJar(jarFile)
- } catch (IOException | InvalidPathException e) {
- if (LOG.isDebugEnabled()) e.printStackTrace()
- LOG.warn("Error opening jar file : '${url.file}' : ${e.toString()}")
- }
- }
-
- return []
- }
-
- /**
- * Crawls a folder, iterates over subfolders, looking for class files.
- */
- static Collection<String> collectPackageNamesFromFolderRecursive(File directory, String prefix, Set<String> packnames) {
- File[] files = directory.listFiles()
- boolean packageAdded = false
-
- for (int i = 0; (files != null) && (i < files.length); i++) {
- if (files[i].isDirectory()) {
- if (files[i].name.startsWith('.')) {
- return
- }
- String optionalDot = prefix ? '.' : ''
- collectPackageNamesFromFolderRecursive(files[i], prefix + optionalDot + files[i].name, packnames)
- } else if (! packageAdded) {
- if (files[i].name.endsWith(CLASS_SUFFIX)) {
- packageAdded = true
- if (prefix) {
- packnames.add(prefix)
- }
- }
- }
- }
- }
-
- static Collection<String> getPackageNamesFromJar(JarFile jf) {
- Set<String> packnames = new HashSet<>()
- for (Enumeration e = jf.entries(); e.hasMoreElements();) {
- JarEntry entry = (JarEntry) e.nextElement()
-
- if (entry == null) {
- continue
- }
-
- String name = entry.name
-
- if (!name.endsWith(CLASS_SUFFIX)) {
- // only use class files
- continue
- }
- // normal slashes also on Windows
- String fullname = name.replace('/', '.').substring(0, name.length() - CLASS_SUFFIX.length())
- // Discard classes in the default package
- if (fullname.lastIndexOf('.') > -1) {
- packnames.add(fullname.substring(0, fullname.lastIndexOf('.')))
- }
- }
- return packnames
- }
-
- /**
- * Returns the names of Classes and direct subpackages contained in a package.
- */
- @Override
- Set<String> getContents(String packagename) {
- if (!rootPackages) {
- return [] as Set
- }
- if (!packagename) {
- return rootPackages.collect { String key, CachedPackage v -> key } as Set
- }
- String sanitizedPackageName
- if (packagename.endsWith('.*')) {
- sanitizedPackageName = packagename[0..-3]
- } else {
- sanitizedPackageName = packagename
- }
-
- StringTokenizer tokenizer = new StringTokenizer(sanitizedPackageName, '.')
... 5647 lines suppressed ...