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 2019/09/18 09:53:53 UTC
[groovy] 01/03: move to later spock version
This is an automated email from the ASF dual-hosted git repository.
paulk pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit ac1276434d423b1252cce0a6514d3a3ee22f6a0b
Author: Paul King <pa...@asert.com.au>
AuthorDate: Wed Sep 18 19:48:45 2019 +1000
move to later spock version
---
build.gradle | 2 +-
.../groovy/tools/shell/AnsiDetector.groovy | 34 -
.../groovy/tools/shell/BufferManager.groovy | 115 --
.../org/codehaus/groovy/tools/shell/Command.groovy | 48 -
.../groovy/tools/shell/CommandAlias.groovy | 87 --
.../groovy/tools/shell/CommandException.groovy | 47 -
.../groovy/tools/shell/CommandRegistry.groovy | 109 --
.../groovy/tools/shell/CommandSupport.groovy | 227 ----
.../tools/shell/ComplexCommandSupport.groovy | 101 --
.../groovy/tools/shell/ExitNotification.groovy | 34 -
.../codehaus/groovy/tools/shell/Groovysh.groovy | 672 ------------
.../tools/shell/InteractiveShellRunner.groovy | 217 ----
.../codehaus/groovy/tools/shell/Interpreter.groovy | 112 --
.../org/codehaus/groovy/tools/shell/Main.groovy | 260 -----
.../org/codehaus/groovy/tools/shell/Parser.groovy | 285 -----
.../org/codehaus/groovy/tools/shell/Shell.groovy | 128 ---
.../codehaus/groovy/tools/shell/ShellRunner.groovy | 102 --
.../tools/shell/commands/AliasCommand.groovy | 133 ---
.../tools/shell/commands/ClearCommand.groovy | 47 -
.../tools/shell/commands/DisplayCommand.groovy | 48 -
.../groovy/tools/shell/commands/DocCommand.groovy | 191 ----
.../groovy/tools/shell/commands/EditCommand.groovy | 104 --
.../groovy/tools/shell/commands/ExitCommand.groovy | 54 -
.../groovy/tools/shell/commands/GrabCommand.groovy | 69 --
.../groovy/tools/shell/commands/HelpCommand.groovy | 131 ---
.../tools/shell/commands/HistoryCommand.groovy | 154 ---
.../tools/shell/commands/ImportCommand.groovy | 264 -----
.../tools/shell/commands/InspectCommand.groovy | 130 ---
.../groovy/tools/shell/commands/LoadCommand.groovy | 88 --
.../tools/shell/commands/PurgeCommand.groovy | 85 --
.../tools/shell/commands/RecordCommand.groovy | 139 ---
.../tools/shell/commands/RegisterCommand.groovy | 80 --
.../groovy/tools/shell/commands/SaveCommand.groovy | 79 --
.../groovy/tools/shell/commands/SetCommand.groovy | 108 --
.../tools/shell/commands/ShadowCommand.groovy | 57 -
.../groovy/tools/shell/commands/ShowCommand.groovy | 105 --
.../completion/BackslashEscapeCompleter.groovy | 44 -
.../shell/completion/CommandNameCompleter.groovy | 53 -
.../completion/CustomClassSyntaxCompletor.groovy | 52 -
.../shell/completion/FileNameCompleter.groovy | 172 ---
.../shell/completion/GroovySyntaxCompletor.groovy | 375 -------
.../shell/completion/IdentifierCompletor.groovy | 39 -
.../shell/completion/ImportsSyntaxCompletor.groovy | 127 ---
.../completion/InfixKeywordSyntaxCompletor.groovy | 49 -
.../shell/completion/KeywordSyntaxCompletor.groovy | 127 ---
.../completion/NavigablePropertiesCompleter.groovy | 97 --
.../ReflectionCompletionCandidate.groovy | 79 --
.../shell/completion/ReflectionCompletor.groovy | 721 -------------
.../completion/StricterArgumentCompleter.groovy | 133 ---
.../completion/VariableSyntaxCompletor.groovy | 63 --
.../org/codehaus/groovy/tools/shell/package.html | 28 -
.../tools/shell/util/CommandArgumentParser.groovy | 123 ---
.../shell/util/CurlyCountingGroovyLexer.groovy | 69 --
.../shell/util/DefaultCommandsRegistrar.groovy | 89 --
.../tools/shell/util/NoExitSecurityManager.groovy | 64 --
.../groovy/tools/shell/util/PackageHelper.groovy | 30 -
.../tools/shell/util/PackageHelperImpl.groovy | 487 ---------
.../tools/shell/util/ScriptVariableAnalyzer.groovy | 123 ---
.../groovy/tools/shell/util/SimpleCompletor.groovy | 141 ---
.../tools/shell/util/WrappedInputStream.groovy | 110 --
.../tools/shell/util/XmlCommandRegistrar.groovy | 95 --
.../codehaus/groovy/tools/shell/util/package.html | 30 -
subprojects/groovy-nio/build.gradle | 8 +-
.../groovy/binding/AbstractFullBinding.java | 114 --
.../codehaus/groovy/binding/AggregateBinding.java | 83 --
.../java/org/codehaus/groovy/binding/BindPath.java | 238 ----
.../org/codehaus/groovy/binding/BindingProxy.java | 160 ---
.../codehaus/groovy/binding/BindingUpdatable.java | 58 -
.../groovy/binding/ClosureSourceBinding.java | 62 --
.../groovy/binding/ClosureTriggerBinding.java | 171 ---
.../groovy/binding/EventTriggerBinding.java | 88 --
.../org/codehaus/groovy/binding/FullBinding.java | 48 -
.../groovy/binding/MutualPropertyBinding.java | 199 ----
.../codehaus/groovy/binding/PropertyBinding.java | 368 -------
.../binding/PropertyChangeProxyTargetBinding.java | 42 -
.../groovy/binding/PropertyPathFullBinding.java | 79 --
.../org/codehaus/groovy/binding/SourceBinding.java | 29 -
.../groovy/binding/SwingTimerTriggerBinding.java | 183 ----
.../org/codehaus/groovy/binding/TargetBinding.java | 28 -
.../codehaus/groovy/binding/TriggerBinding.java | 29 -
.../java/org/codehaus/groovy/binding/package.html | 28 -
.../groovy/runtime/SwingGroovyMethods.java | 1134 --------------------
subprojects/groovy-templates/build.gradle | 6 +
83 files changed, 14 insertions(+), 11307 deletions(-)
diff --git a/build.gradle b/build.gradle
index 54efb16..6cf78e3 100644
--- a/build.gradle
+++ b/build.gradle
@@ -162,7 +162,7 @@ ext {
slf4jVersion = '1.7.25'
xmlunitVersion = '1.6'
xstreamVersion = '1.4.11.1'
- spockVersion = '1.2-groovy-2.4-SNAPSHOT' // supports 3.0
+ spockVersion = '1.3-groovy-2.5-SNAPSHOT' // supports up to 3.9.99
antlr4Version = '4.7.3'
spotbugsannotationsVersion = '3.1.11'
}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/AnsiDetector.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/AnsiDetector.groovy
deleted file mode 100644
index 8101591..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/AnsiDetector.groovy
+++ /dev/null
@@ -1,34 +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.codehaus.groovy.tools.shell
-
-import groovy.transform.CompileStatic
-import jline.TerminalFactory
-
-import java.util.concurrent.Callable
-
-@CompileStatic
-@Deprecated
-class AnsiDetector implements Callable<Boolean>
-{
- @Override
- Boolean call() throws Exception {
- return TerminalFactory.create().isAnsiSupported()
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/BufferManager.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/BufferManager.groovy
deleted file mode 100644
index 0fa9f79..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/BufferManager.groovy
+++ /dev/null
@@ -1,115 +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.codehaus.groovy.tools.shell
-
-import org.codehaus.groovy.tools.shell.util.Logger
-
-/**
- * Manages the shells buffers.
- */
-@Deprecated
-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/codehaus/groovy/tools/shell/Command.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/Command.groovy
deleted file mode 100644
index c10f03c..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/Command.groovy
+++ /dev/null
@@ -1,48 +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.codehaus.groovy.tools.shell
-
-import groovy.transform.CompileStatic
-import jline.console.completer.Completer
-
-/**
- * Provides the interface required for command extensions.
- */
-@CompileStatic
-@Deprecated
-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/codehaus/groovy/tools/shell/CommandAlias.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/CommandAlias.groovy
deleted file mode 100644
index a664bab..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/CommandAlias.groovy
+++ /dev/null
@@ -1,87 +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.codehaus.groovy.tools.shell
-
-import jline.console.completer.Completer
-
-
-/**
- * Provides simple command aliasing.
- */
-@Deprecated
-class CommandAlias
- extends CommandSupport
-{
- final String targetName
-
- CommandAlias(final Groovysh shell, final String name, final String shortcut, final String target) {
- super(shell, name, shortcut)
-
- assert target
-
- this.targetName = target
- }
-
- Command getTarget() {
- Command command = registry.find(targetName)
-
- assert command != null
-
- return command
- }
-
- @Override
- protected List<Completer> createCompleters() {
- try {
- // TODO: Use interface with createCompleters()
- if (target instanceof CommandSupport) {
- CommandSupport support = (CommandSupport) target
- return support.createCompleters()
- }
-
- } catch (MissingMethodException) {
- log.warn('Aliased Command without createCompleters Method')
- }
- }
-
- @Override
- String getDescription() {
- return messages.format('info.alias_to', targetName)
- }
-
- @Override
- String getUsage() {
- return target.usage
- }
-
- @Override
- String getHelp() {
- return target.help
- }
-
- @Override
- boolean getHidden() {
- return target.hidden
- }
-
- @Override
- Object execute(final List<String> args) {
- target.execute(args)
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/CommandException.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/CommandException.groovy
deleted file mode 100644
index e8b6a1f..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/CommandException.groovy
+++ /dev/null
@@ -1,47 +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.codehaus.groovy.tools.shell
-
-import groovy.transform.CompileStatic
-
-/**
- * Thrown to indicate a problem with command execution.
- */
-@CompileStatic
-@Deprecated
-class CommandException
- extends Exception
-{
-
- private final Command command
-
- 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/codehaus/groovy/tools/shell/CommandRegistry.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/CommandRegistry.groovy
deleted file mode 100644
index c627bd9..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/CommandRegistry.groovy
+++ /dev/null
@@ -1,109 +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.codehaus.groovy.tools.shell
-
-import org.codehaus.groovy.tools.shell.util.Logger
-
-/**
- * A registry of shell {@link Command} instances which may be executed.
- */
-@Deprecated
-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/codehaus/groovy/tools/shell/CommandSupport.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/CommandSupport.groovy
deleted file mode 100644
index e4f66ee..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/CommandSupport.groovy
+++ /dev/null
@@ -1,227 +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.codehaus.groovy.tools.shell
-
-import jline.console.completer.Completer
-import jline.console.completer.NullCompleter
-import jline.console.completer.StringsCompleter
-import jline.console.history.FileHistory
-import org.codehaus.groovy.tools.shell.completion.StricterArgumentCompleter
-import org.codehaus.groovy.tools.shell.util.Logger
-import org.codehaus.groovy.tools.shell.util.MessageSource
-
-/**
- * Support for {@link Command} instances.
- */
-@Deprecated
-abstract class CommandSupport
- implements Command
-{
- protected static final String NEWLINE = System.properties['line.separator']
-
- /** 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
-
- /** 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) {
- 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
-
- //
- // NOTE: Registry will be added once registered.
- //
- }
-
- @Override
- String getDescription() {
- try {
- return messages.getMessage('command.description')
- } catch (MissingResourceException) {
- return 'No 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 << new NullCompleter()
- }
- }
- } else {
- list << new NullCompleter()
- }
-
-
- return new StricterArgumentCompleter(list)
- }
-
- //
- // Helpers
- //
-
- protected void alias(final String name, final String shortcut) {
- aliases << new CommandAlias(shell, name, shortcut, this.name)
- }
-
- protected void fail(final String msg) {
- throw new CommandException(this, msg)
- }
-
- protected void fail(final String msg, final Throwable cause) {
- throw new CommandException(this, 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 FileHistory getHistory() {
- return shell.history
- }
-
- protected GroovyClassLoader getClassLoader() {
- return shell.interp.classLoader
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/ComplexCommandSupport.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/ComplexCommandSupport.groovy
deleted file mode 100644
index 84cdaed..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/ComplexCommandSupport.groovy
+++ /dev/null
@@ -1,101 +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.codehaus.groovy.tools.shell
-
-import jline.console.completer.Completer
-import org.codehaus.groovy.tools.shell.util.SimpleCompletor
-
-/**
- * Support for more complex commands.
- */
-@Deprecated
-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 SimpleCompletor()
- 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/codehaus/groovy/tools/shell/ExitNotification.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/ExitNotification.groovy
deleted file mode 100644
index 70b2cc9..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/ExitNotification.groovy
+++ /dev/null
@@ -1,34 +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.codehaus.groovy.tools.shell
-
-/**
- * Notification to signal the shell to exit.
- */
-@Deprecated
-class ExitNotification
- extends Error
-{
- /** 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/codehaus/groovy/tools/shell/Groovysh.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/Groovysh.groovy
deleted file mode 100644
index 72d0765..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/Groovysh.groovy
+++ /dev/null
@@ -1,672 +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.codehaus.groovy.tools.shell
-
-import antlr.TokenStreamException
-import groovy.transform.CompileStatic
-import jline.Terminal
-import jline.WindowsTerminal
-import jline.console.history.FileHistory
-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.InvokerHelper
-import org.codehaus.groovy.runtime.StackTraceUtils
-import org.codehaus.groovy.tools.shell.commands.LoadCommand
-import org.codehaus.groovy.tools.shell.commands.RecordCommand
-import org.codehaus.groovy.tools.shell.util.CurlyCountingGroovyLexer
-import org.codehaus.groovy.tools.shell.util.DefaultCommandsRegistrar
-import org.codehaus.groovy.tools.shell.util.MessageSource
-import org.codehaus.groovy.tools.shell.util.PackageHelper
-import org.codehaus.groovy.tools.shell.util.PackageHelperImpl
-import org.codehaus.groovy.tools.shell.util.Preferences
-import org.codehaus.groovy.tools.shell.util.ScriptVariableAnalyzer
-import org.codehaus.groovy.tools.shell.util.XmlCommandRegistrar
-import org.fusesource.jansi.AnsiRenderer
-
-import java.util.regex.Pattern
-
-/**
- * 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 {@link XmlCommandRegistrar}
- */
-@Deprecated
-class Groovysh extends Shell {
-
-
- private static final MessageSource messages = new MessageSource(Groovysh)
-
- 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'
-
-
- 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
-
- FileHistory 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
-
- Groovysh(final ClassLoader classLoader, final Binding binding, final IO io, final Closure registrar) {
- this(classLoader, binding, io, registrar, null)
- }
-
- Groovysh(final ClassLoader classLoader, final Binding binding, final IO io, final Closure registrar, CompilerConfiguration configuration) {
- this(classLoader, binding, io, registrar, configuration, new Interpreter(classLoader, binding, configuration))
- }
-
- Groovysh(final ClassLoader classLoader, final Binding binding, final IO io, final Closure registrar, CompilerConfiguration configuration, Interpreter interpreter) {
- super(io)
- assert classLoader
- assert binding
- def actualRegistrar = registrar ?: createDefaultRegistrar(classLoader)
- parser = new Parser()
- interp = interpreter
- actualRegistrar.call(this)
- this.packageHelper = new PackageHelperImpl(classLoader)
- }
-
- private static Closure createDefaultRegistrar(final ClassLoader classLoader) {
- return {Groovysh shell ->
- URL xmlCommandResource = getClass().getResource('commands.xml')
- if (xmlCommandResource != null) {
- def r = new XmlCommandRegistrar(shell, classLoader)
- r.register(xmlCommandResource)
- } else {
- new DefaultCommandsRegistrar(shell).register()
- }
- }
- }
-
- Groovysh(final ClassLoader classLoader, final Binding binding, final IO io) {
- this(classLoader, binding, io, null)
- }
-
- Groovysh(final Binding binding, final IO io) {
- this(Thread.currentThread().contextClassLoader, binding, io)
- }
-
- Groovysh(final IO io) {
- this(new Binding(), io)
- }
-
- Groovysh(final IO io, CompilerConfiguration configuration) {
- this(Thread.currentThread().contextClassLoader, new Binding(), io, null, configuration)
- }
-
- 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(final String line) {
- assert line != null
-
- // Ignore empty lines
- if (line.trim().size() == 0) {
- 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<String>(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
- setLastResult(result = interp.evaluate(buff))
- } else {
- // Evaluate Buffer wrapped with code storing bounded vars
- result = evaluateWithStoredBoundVars(importsSpec, current)
- }
-
- 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
- }
-
- /**
- * return true if the buffer can be recognized as a type declaration statement
- * @param strings
- * @return
- */
- @CompileStatic
- static boolean isTypeOrMethodDeclaration(final List<String> buffer) {
- final 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, final 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 + ['} finally {' + variableBlocks + '}']
- } else {
- buff = [importsSpec] + ['true'] + current
- }
- setLastResult(result = interp.evaluate(buff))
-
- if (variableBlocks) {
- Map<String, Object> boundVarValues = interp.context.getVariable(COLLECTED_BOUND_VARS_MAP_VARNAME)
- boundVarValues.each({ String name, Object value -> interp.context.setVariable(name, value) })
- }
-
- return result
- }
-
-
-
- protected Object executeCommand(final String line) {
- return super.execute(line)
- }
-
- /**
- * Display the given buffer.
- */
- void displayBuffer(final 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
- //
-
- private final AnsiRenderer prompt = new AnsiRenderer()
-
- /*
- Builds the command prompt name in 1 of 3 ways:
- 1. Checks the groovysh.prompt property passed into groovysh script. -Dgroovysh.prompt="hello"
- 2. Checks an environment variable called GROOVYSH_PROMPT. export GROOVYSH_PROMPT
- 3. If no value is defined returns the default groovy shell prompt.
-
- The code will always assume you want the line number in the prompt. To implement differently overhead the render
- prompt variable.
- */
- private String buildPrompt() {
- def lineNum = formatLineNumber(buffers.current().size())
-
- def groovyshellProperty = System.getProperty('groovysh.prompt')
- if (groovyshellProperty) {
- return "@|bold ${groovyshellProperty}:|@${lineNum}@|bold >|@ "
- }
- def groovyshellEnv = System.getenv('GROOVYSH_PROMPT')
- if (groovyshellEnv) {
- return "@|bold ${groovyshellEnv}:|@${lineNum}@|bold >|@ "
- }
- return "@|bold groovy:|@${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')
- }
-
- // not sure whether the same Lexer instance could be reused.
- def lexer = CurlyCountingGroovyLexer.createGroovyLexer(src.toString())
-
- // read all tokens
- try {
- while (lexer.nextToken().getType() != CurlyCountingGroovyLexer.EOF) {}
- } catch (TokenStreamException e) {
- // pass
- }
- int parenIndent = (lexer.getParenLevel()) * indentSize
-
- // dedent after closing brackets
- return ' ' * Math.max(parenIndent, 0)
- }
-
- public String renderPrompt() {
- return prompt.render( buildPrompt() )
- }
-
- /**
- * Format the given number suitable for rendering as a line number column.
- */
- protected String formatLineNumber(final 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
- * @param filename
- */
- protected void loadUserScript(final String filename) {
- assert filename
-
- File file = new File(getUserStateDirectory(), filename)
-
- if (file.exists()) {
- Command 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 {
- // Restore the result hook
- resultHook = previousHook
- }
- } else {
- log.error("Unable to load user-script, missing '$LoadCommand.COMMAND_NAME' command")
- }
- }
- }
-
- //
- // Recording
- //
-
- protected void maybeRecordInput(final String line) {
- RecordCommand record = registry[RecordCommand.COMMAND_NAME]
-
- if (record != null) {
- record.recordInput(line)
- }
- }
-
- protected void maybeRecordResult(final Object result) {
- RecordCommand record = registry[RecordCommand.COMMAND_NAME]
-
- if (record != null) {
- record.recordResult(result)
- }
- }
-
- protected void maybeRecordError(Throwable cause) {
- RecordCommand record = registry[RecordCommand.COMMAND_NAME]
-
- if (record != null) {
- if (getPreference(SANITIZE_PREFERENCE_KEY, 'false')) {
- cause = StackTraceUtils.deepSanitize(cause)
- }
- record.recordError(cause)
- }
- }
-
- //
- // 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("@|bold ===>|@ ${InvokerHelper.toString(result)}")
- }
- }
-
- Closure resultHook = defaultResultHook
-
- private void setLastResult(final 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("@|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<Message> msgIterator = collector.getErrors().iterator()
- while (msgIterator.hasNext()) {
- Message errorMsg = msgIterator.next()
- errorMsg.write(writer)
- if (msgIterator.hasNext()) {
- writer.println()
- }
- }
- io.err.println("@|bold,red ${data.toString()}|@")
- } else {
- io.err.println("@|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
- if (!io.verbose && sanitize) {
- cause = StackTraceUtils.deepSanitize(cause)
- }
-
- def trace = 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
- }
-
- buff << " @|bold at|@ ${e.className}.${e.methodName} (@|bold "
-
- buff << (e.nativeMethod ? 'Native Method' :
- (e.fileName != null && e.lineNumber != -1 ? "${e.fileName}:${e.lineNumber}" :
- (e.fileName != null ? e.fileName : 'Unknown Source')))
-
- buff << '|@)'
-
- io.err.println(buff)
-
- buff.setLength(0) // Reset the buffer
- if (doBreak) {
- io.err.println(' @|bold ...|@')
- break
- }
- }
- }
- }
- }
-
- // protected for mocking in tests
- protected String getPreference(final String key, final String theDefault) {
- return Preferences.get(key, theDefault)
- }
-
- Closure errorHook = defaultErrorHook
-
- private void displayError(final 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("@|bold,red Unknown property|@: " + cause.property)
- return
- }
- }
-
- errorHook.call(cause)
- }
-
- /**
- * Run Interactive Shell with optional initial script and files to load
- */
- int run(final String evalString, final List<String> filenames) {
- List<String> startCommands = []
-
- if (evalString != null && evalString.trim().size() > 0) {
- startCommands.add(evalString)
- }
- if (filenames != null && filenames.size() > 0) {
- startCommands.addAll(filenames.collect({String it -> "${LoadCommand.COMMAND_NAME} $it"}))
- }
- return run(startCommands.join('\n'))
- }
-
- /**
- * Run Interactive Shell with initial command
- */
- int run(final String commandLine) {
- def code
-
- try {
- loadUserScript('groovysh.profile')
- loadUserScript('groovysh.rc')
-
- // Setup the interactive runner
- runner = new InteractiveShellRunner(
- this,
- this.&renderPrompt as Closure)
-
- // if args were passed in, just execute as a command
- // (but cygwin gives an empty string, so ignore that)
- if (commandLine != null && commandLine.trim().size() > 0) {
- runner.wrappedInputStream.insert(commandLine + '\n')
- }
-
- // Setup the history
- File histFile = new File(userStateDirectory, 'groovysh.history')
- history = new FileHistory(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) {
- log.debug("Exiting w/code: ${n.code}")
-
- code = n.code
- }
- catch (Throwable t) {
- io.err.println(messages.format('info.fatal', t))
- t.printStackTrace(io.err)
-
- code = 1
- }
-
- assert code != null // This should never happen
-
- return code
- }
-
-
- /**
- * maybe displays log information and a welcome message
- * @param term
- */
- public 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(messages.format('startup_banner.0', GroovySystem.version, System.properties['java.version']))
- io.out.println(messages['startup_banner.1'])
- io.out.println('-' * (width - 1))
- }
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/InteractiveShellRunner.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/InteractiveShellRunner.groovy
deleted file mode 100644
index de73fde..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/InteractiveShellRunner.groovy
+++ /dev/null
@@ -1,217 +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.codehaus.groovy.tools.shell
-
-import jline.console.ConsoleReader
-import jline.console.completer.AggregateCompleter
-import jline.console.completer.CandidateListCompletionHandler
-import jline.console.completer.CompletionHandler
-import jline.console.history.FileHistory
-import org.codehaus.groovy.tools.shell.completion.CustomClassSyntaxCompletor
-import org.codehaus.groovy.tools.shell.completion.FileNameCompleter
-import org.codehaus.groovy.tools.shell.completion.GroovySyntaxCompletor
-import org.codehaus.groovy.tools.shell.completion.ImportsSyntaxCompletor
-import org.codehaus.groovy.tools.shell.completion.KeywordSyntaxCompletor
-import org.codehaus.groovy.tools.shell.completion.ReflectionCompletor
-import org.codehaus.groovy.tools.shell.completion.VariableSyntaxCompletor
-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.codehaus.groovy.tools.shell.util.WrappedInputStream
-
-/**
- * Support for running a {@link Shell} interactively using the JLine library.
- */
-@Deprecated
-class InteractiveShellRunner
- extends ShellRunner
- implements Runnable
-{
- ConsoleReader reader
-
- final Closure prompt
-
- final CommandsMultiCompleter completer
- WrappedInputStream wrappedInputStream
-
- InteractiveShellRunner(final Groovysh shell, final Closure prompt) {
- super(shell)
-
- this.prompt = prompt
- this.wrappedInputStream = new WrappedInputStream(shell.io.inputStream)
- this.reader = new ConsoleReader(wrappedInputStream, shell.io.outputStream)
-
- CompletionHandler currentCompletionHandler = this.reader.getCompletionHandler()
- if (currentCompletionHandler instanceof CandidateListCompletionHandler) {
- // have to downcast because methods not part of the interface
- ((CandidateListCompletionHandler) currentCompletionHandler).setStripAnsi(true)
- ((CandidateListCompletionHandler) currentCompletionHandler).setPrintSpaceAfterFullCompletion(false)
- }
-
-
- // expand events ia an advanced feature of JLine that clashes with Groovy syntax (e.g. invoke "2!=3")
- this.reader.expandEvents = false
-
-
- // complete groovysh commands, display, import, ... as first word in line
- this.completer = new CommandsMultiCompleter()
- reader.addCompleter(this.completer)
-
- CustomClassSyntaxCompletor classnameCompletor = new CustomClassSyntaxCompletor(shell)
-
- reader.addCompleter(new GroovySyntaxCompletor(shell,
- new ReflectionCompletor(shell),
- classnameCompletor,
- [new KeywordSyntaxCompletor(),
- new VariableSyntaxCompletor(shell),
- classnameCompletor,
- new ImportsSyntaxCompletor(shell)],
- new FileNameCompleter(false)))
- }
-
- @Override
- void run() {
- for (Command command in shell.registry.commands()) {
- completer.add(command)
- }
-
- // Force things to become clean
- completer.refresh()
-
- // And then actually run
- adjustHistory()
- super.run()
- }
-
- void setHistory(final 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")
- }
-
- @Override
- 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.call() as String)
- } 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 casesomeone 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.historyFull) {
- def first = history.first()
- if (first) {
- shell.evictedLine = first.value()
- }
- }
- }
- }
-
-}
-
-/**
- * Completer for interactive shells.
- */
-@Deprecated
-class CommandsMultiCompleter
- extends AggregateCompleter
-{
- protected final Logger log = Logger.create(this.class)
-
- List/*<Completer>*/ list = []
-
- private boolean dirty = false
-
- def add(final 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(final String buffer, final int pos, final 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/codehaus/groovy/tools/shell/Interpreter.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/Interpreter.groovy
deleted file mode 100644
index 5af886a..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/Interpreter.groovy
+++ /dev/null
@@ -1,112 +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.codehaus.groovy.tools.shell
-
-import org.codehaus.groovy.control.CompilerConfiguration
-import org.codehaus.groovy.runtime.InvokerHelper
-import org.codehaus.groovy.runtime.MethodClosure
-import org.codehaus.groovy.tools.shell.util.Logger
-
-import java.lang.reflect.Method
-
-/**
- * Helper to interpret a source buffer.
- */
-@Deprecated
-class Interpreter implements Evaluator
-{
- static final String SCRIPT_FILENAME = 'groovysh_evaluate'
-
- private final Logger log = Logger.create(this.class)
-
- private final GroovyShell shell
-
- Interpreter(final ClassLoader classLoader, final Binding binding) {
- this(classLoader, binding, null)
- }
-
- Interpreter(final ClassLoader classLoader, final Binding binding, CompilerConfiguration configuration) {
- assert classLoader
- assert binding
- if (configuration != null) {
- shell = new GroovyShell(classLoader, binding, configuration)
- } else {
- shell = new GroovyShell(classLoader, binding)
- }
- }
-
- Binding getContext() {
- return shell.context
- }
-
- GroovyClassLoader getClassLoader() {
- return shell.classLoader
- }
-
- GroovyShell getShell() {
- return shell
- }
-
- @Override
- def evaluate(final Collection<String> buffer) {
- assert buffer
-
- def source = buffer.join(Parser.NEWLINE)
-
- def result
-
- Class type
- try {
- Script script = shell.parse(source, SCRIPT_FILENAME)
- type = script.getClass()
-
- log.debug("Compiled script: $script")
-
- if (type.declaredMethods.any {Method it -> it.name == 'main' }) {
- result = script.run()
- }
-
- // Need to use String.valueOf() here to avoid icky exceptions causes by GString coercion
- log.debug("Evaluation result: ${InvokerHelper.toString(result)} (${result?.getClass()})")
-
- // Keep only the methods that have been defined in the script
- type.declaredMethods.each { Method m ->
- if (!(m.name in [ 'main', 'run' ] || m.name.startsWith('super$') || m.name.startsWith('class$') || m.name.startsWith('$'))) {
- log.debug("Saving method definition: $m.name")
-
- context["${m.name}"] = new MethodClosure(type.newInstance(), m.name)
- }
- }
- }
- finally {
- // Remove the script class generated
- classLoader.removeClassCacheEntry(type?.name)
-
- // Remove the inline closures from the cache as well
- classLoader.removeClassCacheEntry('$_run_closure')
- }
-
- return result
- }
-}
-
-@Deprecated
-interface Evaluator {
- def evaluate(final Collection<String> buffer)
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/Main.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/Main.groovy
deleted file mode 100644
index 6d8bd81..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/Main.groovy
+++ /dev/null
@@ -1,260 +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.codehaus.groovy.tools.shell
-
-import groovy.cli.internal.CliBuilderInternal
-import groovy.cli.internal.OptionAccessor
-import jline.TerminalFactory
-import jline.UnixTerminal
-import jline.UnsupportedTerminal
-import jline.WindowsTerminal
-import org.codehaus.groovy.control.CompilerConfiguration
-import org.codehaus.groovy.tools.shell.util.Logger
-import org.codehaus.groovy.tools.shell.util.MessageSource
-import org.codehaus.groovy.tools.shell.util.NoExitSecurityManager
-import org.fusesource.jansi.Ansi
-import org.fusesource.jansi.AnsiConsole
-
-import static org.apache.groovy.util.SystemUtil.setSystemPropertyFrom
-
-/**
- * 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>.
- */
-@Deprecated
-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.
- */
- static void main(final 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'])
- }
- OptionAccessor options = cli.parse(args)
-
- if (options == null) {
- // CliBuilder prints error, but does not exit
- System.exit(22) // Invalid Args
- }
-
- if (options.h) {
- cli.usage()
- System.exit(0)
- }
-
- if (options.V) {
- System.out.println(messages.format('cli.info.version', GroovySystem.version))
- System.exit(0)
- }
-
- 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
- }
- }
-
- 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
- }
-
- if (options.q) {
- io.verbosity = IO.Verbosity.QUIET
- }
-
- String evalString = null
- if (options.e) {
- evalString = options.getOptionValue('e')
- }
- def configuration = new CompilerConfiguration(System.getProperties())
- configuration.setParameters((boolean) options.hasOption("pa"))
-
- List<String> filenames = options.arguments()
- 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
-
- println('WARNING: Abnormal JVM shutdown detected')
- }
-
- if (shell.history) {
- shell.history.flush()
- }
- }
-
-
- SecurityManager psm = System.getSecurityManager()
- System.setSecurityManager(new NoExitSecurityManager())
-
- try {
- code = shell.run(evalString, filenames)
- }
- finally {
- System.setSecurityManager(psm)
- }
-
- // 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
-
- System.exit(code)
- }
-
- /**
- * @param type: one of 'auto', 'unix', ('win', 'windows'), ('false', 'off', 'none')
- * @param suppressColor only has effect when ansi is enabled
- */
- static void setTerminalType(String type, boolean suppressColor) {
- assert type != null
-
- 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")
- }
- if (enableAnsi) {
- installAnsi() // must be called before IO(), since it modifies System.in
- Ansi.enabled = !suppressColor
- } else {
- Ansi.enabled = false
- }
-
- if (type != null) {
- System.setProperty(TerminalFactory.JLINE_TERMINAL, type)
- }
- }
-
- 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(final String nameValue) {
- setSystemPropertyFrom(nameValue)
- }
-}
-
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/Parser.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/Parser.groovy
deleted file mode 100644
index 33b6add..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/Parser.groovy
+++ /dev/null
@@ -1,285 +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.codehaus.groovy.tools.shell
-
-import antlr.RecognitionException
-import antlr.TokenStreamException
-import antlr.collections.AST
-import org.codehaus.groovy.antlr.SourceBuffer
-import org.codehaus.groovy.antlr.UnicodeEscapingReader
-import org.codehaus.groovy.antlr.parser.GroovyLexer
-import org.codehaus.groovy.antlr.parser.GroovyRecognizer
-import org.codehaus.groovy.control.CompilationFailedException
-import org.codehaus.groovy.control.ParserPluginFactory
-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
-
-@Deprecated
-interface Parsing {
- ParseStatus parse(final Collection<String> buffer)
-}
-
-/**
- * Provides a facade over the parser to recognize valid Groovy syntax.
- */
-@Deprecated
-class Parser
-{
- static final String NEWLINE = System.getProperty('line.separator')
-
- 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 relaxed parser, which tends to allow more, but won't really catch valid syntax errors.
- */
-@Deprecated
-final class RelaxedParser implements Parsing {
- private final Logger log = Logger.create(this.class)
-
- private SourceBuffer sourceBuffer
-
- private String[] tokenNames
-
- @Override
- ParseStatus parse(final Collection<String> buffer) {
- assert buffer
-
- sourceBuffer = new SourceBuffer()
-
- def source = buffer.join(Parser.NEWLINE)
-
- log.debug("Parsing: $source")
-
- try {
- doParse(new UnicodeEscapingReader(new StringReader(source), sourceBuffer))
-
- log.debug('Parse complete')
-
- return new ParseStatus(ParseCode.COMPLETE)
- }
- catch (e) {
- switch (e.getClass()) {
- case TokenStreamException:
- case RecognitionException:
- log.debug("Parse incomplete: $e (${e.getClass().name})")
-
- return new ParseStatus(ParseCode.INCOMPLETE)
-
- default:
- log.debug("Parse error: $e (${e.getClass().name})")
-
- return new ParseStatus(e)
- }
- }
- }
-
- protected AST doParse(final UnicodeEscapingReader reader) throws Exception {
- GroovyLexer lexer = new GroovyLexer(reader)
- reader.setLexer(lexer)
-
- def parser = GroovyRecognizer.make(lexer)
- parser.setSourceBuffer(sourceBuffer)
- tokenNames = parser.tokenNames
-
- parser.compilationUnit()
- return parser.AST
- }
-}
-
-/**
- * A more rigid parser which catches more syntax errors, but also tends to barf on stuff that is really valid from time to time.
- */
-@Deprecated
-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.getConfiguration().setPluginFactory(ParserPluginFactory.antlr2()) // We have to stick to the old parser before GROOVY-8279 is fixed
- 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.
- */
-@Deprecated
-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.
- */
-@Deprecated
-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/codehaus/groovy/tools/shell/Shell.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/Shell.groovy
deleted file mode 100644
index 3cd034b..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/Shell.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.codehaus.groovy.tools.shell
-
-import org.codehaus.groovy.runtime.InvokerHelper
-import org.codehaus.groovy.tools.shell.util.CommandArgumentParser
-import org.codehaus.groovy.tools.shell.util.Logger
-import org.fusesource.jansi.Ansi
-
-import static org.fusesource.jansi.Ansi.ansi
-
-/**
- * A simple shell for invoking commands from a command-line.
- */
-@Deprecated
-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(ansi().a(Ansi.Attribute.INTENSITY_BOLD).fg(Ansi.Color.RED).a(e.message).reset())
- }
- log.debug("Result: ${InvokerHelper.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/codehaus/groovy/tools/shell/ShellRunner.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/ShellRunner.groovy
deleted file mode 100644
index 8c49d43..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/ShellRunner.groovy
+++ /dev/null
@@ -1,102 +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.codehaus.groovy.tools.shell
-
-import org.codehaus.groovy.tools.shell.util.Logger
-
-/**
- * Support for running a {@link Shell}.
- */
-@Deprecated
-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/codehaus/groovy/tools/shell/commands/AliasCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/AliasCommand.groovy
deleted file mode 100644
index 427b82f..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/AliasCommand.groovy
+++ /dev/null
@@ -1,133 +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.codehaus.groovy.tools.shell.commands
-
-import jline.console.completer.Completer
-import org.codehaus.groovy.tools.shell.Command
-import org.codehaus.groovy.tools.shell.CommandSupport
-import org.codehaus.groovy.tools.shell.Groovysh
-import org.codehaus.groovy.tools.shell.completion.CommandNameCompleter
-
-/**
- * The 'alias' command.
- */
-@Deprecated
-class AliasCommand
- extends CommandSupport
-{
- public static final String COMMAND_NAME = ':alias'
-
- AliasCommand(final Groovysh shell) {
- super(shell, COMMAND_NAME, ':a', )
- }
-
- @Override
- protected List<Completer> createCompleters() {
- return [
- new CommandNameCompleter(registry, true),
- null
- ]
- }
-
- @Override
- Object execute(final List<String> args) {
- assert args != null
-
- if (args.size() < 2) {
- fail("Command 'alias' requires at least 2 arguments") // TODO: i18n
- }
-
- String name = args[0]
- List target = args[1..-1]
-
- Command command = registry.find(name)
-
- if (command == null) {
- command = registry.find(name)
- }
- if (command != null) {
- if (command instanceof AliasTargetProxyCommand) {
- log.debug("Rebinding alias: $name")
-
- registry.remove(command)
- }
- else {
- fail("Can not rebind non-user aliased command: ${command.name}") // TODO: i18n
- }
- }
-
- log.debug("Creating alias '$name' to: $target")
-
- // Register the command
- command = shell << new AliasTargetProxyCommand(shell, name, target)
-
- //
- // TODO: Should this be here... or should this be in the Shell's impl?
- //
-
- // Try to install the completor
- if (shell.runner) {
- shell.runner.completer.add(command)
- }
- }
-}
-
-class AliasTargetProxyCommand
- extends CommandSupport implements Command
-{
- private static int counter = 0
-
- final List<String> args
-
- AliasTargetProxyCommand(final Groovysh shell, final String name, final List args) {
- super(shell, name, ':a' + counter++)
-
- assert args
-
- this.args = args
- }
-
- @Override
- String getDescription() {
- return "User defined alias to: @|bold ${args.join(' ')}|@"
- }
-
- @Override
- String getUsage() {
- return ''
- }
-
- @Override
- String getHelp() {
- return description
- }
-
- @Override
- Object execute(final List<String> args) {
- List<String> allArgs = this.args + args
-
- log.debug("Executing with args: $allArgs")
-
- //
- // FIXME: Should go back through shell.execute() to allow aliases to groovy snips too
- //
-
- return shell.executeCommand(allArgs.join(' '))
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/ClearCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/ClearCommand.groovy
deleted file mode 100644
index 5728842..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/ClearCommand.groovy
+++ /dev/null
@@ -1,47 +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.codehaus.groovy.tools.shell.commands
-
-import org.codehaus.groovy.tools.shell.CommandSupport
-import org.codehaus.groovy.tools.shell.Groovysh
-
-/**
- * The 'clear' command.
- */
-@Deprecated
-class ClearCommand
- extends CommandSupport
-{
- public static final String COMMAND_NAME = ':clear'
-
- ClearCommand(final Groovysh shell) {
- super(shell, COMMAND_NAME, ':c')
- }
-
- @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/codehaus/groovy/tools/shell/commands/DisplayCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/DisplayCommand.groovy
deleted file mode 100644
index f49c381..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/DisplayCommand.groovy
+++ /dev/null
@@ -1,48 +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.codehaus.groovy.tools.shell.commands
-
-import org.codehaus.groovy.tools.shell.CommandSupport
-import org.codehaus.groovy.tools.shell.Groovysh
-
-/**
- * The 'display' command. Displays the current buffer (e.g. while method declaration was not finished).
- */
-@Deprecated
-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/codehaus/groovy/tools/shell/commands/DocCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/DocCommand.groovy
deleted file mode 100644
index 7ebe503..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/DocCommand.groovy
+++ /dev/null
@@ -1,191 +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.codehaus.groovy.tools.shell.commands
-
-import jline.console.completer.Completer
-import org.codehaus.groovy.tools.shell.CommandSupport
-import org.codehaus.groovy.tools.shell.Groovysh
-
-/**
- * The 'doc' command.
- *
- * @since 2.2.0
- */
-@Deprecated
-class DocCommand extends CommandSupport {
-
- public static final String COMMAND_NAME = ':doc'
-
- private static final String ENV_BROWSER = 'BROWSER'
- private static final String ENV_BROWSER_GROOVYSH = 'GROOVYSH_BROWSER'
-
- private static final int TIMEOUT_CONN = 5 * 1000 // ms
- private static final int TIMEOUT_READ = 5 * 1000 // ms
-
- // indicates support for java.awt.Desktop#browse on the current platform
- private static boolean hasAWTDesktopPlatformSupport
- private static desktop
-
- /**
- * Check for java.awt.Desktop#browse platform support
- */
- static {
- try {
- def desktopClass = Class.forName('java.awt.Desktop')
- desktop = desktopClass.desktopSupported ? desktopClass.desktop : null
-
- hasAWTDesktopPlatformSupport =
- desktop != null &&
- desktop.isSupported(desktopClass.declaredClasses.find { it.simpleName == 'Action' }.BROWSE)
-
- } catch (Exception e) {
- hasAWTDesktopPlatformSupport = false
- desktop = null
- }
- }
-
- DocCommand(final Groovysh shell) {
- super(shell, COMMAND_NAME, ':D')
- }
-
- @Override
- protected List<Completer> createCompleters() {
- return [new ImportCompleter(shell.packageHelper, shell.interp, false),
- null]
- }
-
- @Override
- Object execute(final List<String> args) {
- if (args?.size() == 1) {
- doc(args[0])
- return
- }
- fail(messages.format('error.unexpected_args', args ? args.join(' ') : 'no arguments'))
- }
-
- void doc(String className) {
- def normalizedClassName = normalizeClassName(className)
- def urls = urlsFor(normalizedClassName)
- if (urls.empty) {
- fail("Documentation for \"${normalizedClassName}\" could not be found.")
- }
-
- // Print the URLs.
- // It is useful especially when the browsing fails.
- urls.each { url -> io.out.println url }
-
- browse(urls)
- }
-
- protected String normalizeClassName(String className) {
- className.replaceAll('"', '').replaceAll("'", '')
- }
-
- protected void browse(List urls) {
- def browser = browserEnvironmentVariable
-
- // fallback to java.awt.Desktop in case of missing env variable(s)
- if (browser) {
- browseWithNativeBrowser(browser, urls)
- } else if (hasAWTDesktopPlatformSupport) {
- browseWithAWT(urls)
- } else {
- fail 'Browser could not be opened due to missing platform support for "java.awt.Desktop". Please set ' +
- "a $ENV_BROWSER_GROOVYSH or $ENV_BROWSER environment variable referring to the browser binary to " +
- 'solve this issue.'
- }
- }
-
- protected String getBrowserEnvironmentVariable() {
- System.getenv(ENV_BROWSER_GROOVYSH) ?: System.getenv(ENV_BROWSER)
- }
-
- protected void browseWithAWT(List urls) {
- try {
- urls.each { url -> desktop.browse(url.toURI()) }
- } catch (Exception e) {
- fail "Browser could not be opened, an unexpected error occured (${e}). You can add a " +
- "$ENV_BROWSER_GROOVYSH or $ENV_BROWSER environment variable to explicitly specify a browser binary."
- }
- }
-
- protected void browseWithNativeBrowser(String browser, List urls) {
- try {
- "$browser ${urls.join(' ')}".execute()
- } catch (Exception e) {
- // we could be here caused by a IOException, SecurityException or NP Exception
- fail "Browser could not be opened (${e}). Please check the $ENV_BROWSER_GROOVYSH or $ENV_BROWSER " +
- "environment variable."
- }
- }
-
- protected List urlsFor(String className) {
- String groovyVersion = GroovySystem.version
- def path = className.replaceAll(/\./, '/') + '.html'
-
- def urls = []
- if (className.matches(/^(groovy|org\.codehaus\.groovy|)\..+/)) {
- def url = new URL("http://docs.groovy-lang.org/$groovyVersion/html/gapi/$path")
- if (sendHEADRequest(url)) {
- urls << url
- }
- } else {
- // Don't specify package names to not depend on a specific version of Java SE.
- // Java SE includes non-java(x) packages such as org.w3m.*, org.omg.*. org.xml.* for now
- // and new packages might be added in the future.
- def url = new URL("http://docs.oracle.com/javase/${simpleVersion()}/docs/api/$path")
- if (sendHEADRequest(url)) {
- urls << url
- url = new URL("http://docs.groovy-lang.org/$groovyVersion/html/groovy-jdk/$path")
- if (sendHEADRequest(url)) {
- urls << url
- }
- }
- }
-
- urls
- }
-
- private static simpleVersion() {
- String javaVersion = System.getProperty('java.version')
- if (javaVersion.startsWith('1.')) {
- javaVersion.split(/\./)[1]
- } else {
- // java 9 and above
- javaVersion.replaceAll(/-.*/, '').split(/\./)[0]
- }
- }
-
- protected boolean sendHEADRequest(URL url) {
- try {
- HttpURLConnection conn = url.openConnection() as HttpURLConnection
- conn.requestMethod = 'HEAD'
- conn.connectTimeout = TIMEOUT_CONN
- conn.readTimeout = TIMEOUT_READ
- conn.instanceFollowRedirects = true
-
- return conn.responseCode == 200
-
- } catch (IOException e) {
- fail "Sending a HEAD request to $url failed (${e}). Please check your network settings."
- }
- }
-
-}
-
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/EditCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/EditCommand.groovy
deleted file mode 100644
index 11ef470..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/EditCommand.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.codehaus.groovy.tools.shell.commands
-
-import org.codehaus.groovy.tools.shell.CommandSupport
-import org.codehaus.groovy.tools.shell.Groovysh
-import org.codehaus.groovy.tools.shell.util.Preferences
-
-/**
- * The 'edit' command. Opens Editor to write into the current Buffer.
- */
-@Deprecated
-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/codehaus/groovy/tools/shell/commands/ExitCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/ExitCommand.groovy
deleted file mode 100644
index 5d75c90..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/ExitCommand.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.codehaus.groovy.tools.shell.commands
-
-import org.codehaus.groovy.tools.shell.CommandSupport
-import org.codehaus.groovy.tools.shell.ExitNotification
-import org.codehaus.groovy.tools.shell.Groovysh
-
-/**
- * The 'exit' command.
- */
-@Deprecated
-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)
-
- //
- // TODO: Maybe support a single arg for the code?
- //
-
- if (io.verbose) {
- io.out.println(messages['info.bye'])
- }
-
- throw new ExitNotification(0)
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/GrabCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/GrabCommand.groovy
deleted file mode 100644
index 15c107a..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/GrabCommand.groovy
+++ /dev/null
@@ -1,69 +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.codehaus.groovy.tools.shell.commands
-
-import groovy.grape.Grape
-import jline.console.completer.Completer
-import org.codehaus.groovy.tools.GrapeUtil
-import org.codehaus.groovy.tools.shell.CommandSupport
-import org.codehaus.groovy.tools.shell.Groovysh
-
-/**
- * The 'grab' command.
- */
-@Deprecated
-class GrabCommand extends CommandSupport {
-
- public static final String COMMAND_NAME = ':grab'
-
- public GrabCommand(Groovysh shell) {
- super(shell, COMMAND_NAME, ':g')
- }
-
- @Override protected List<Completer> createCompleters() { [ null ] }
-
- @Override Object execute(List<String> args) {
- 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/codehaus/groovy/tools/shell/commands/HelpCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/HelpCommand.groovy
deleted file mode 100644
index 50100ff..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/HelpCommand.groovy
+++ /dev/null
@@ -1,131 +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.codehaus.groovy.tools.shell.commands
-
-import jline.console.completer.Completer
-import org.codehaus.groovy.tools.shell.Command
-import org.codehaus.groovy.tools.shell.CommandSupport
-import org.codehaus.groovy.tools.shell.Groovysh
-import org.codehaus.groovy.tools.shell.completion.CommandNameCompleter
-
-/**
- * The 'help' command.
- */
-@Deprecated
-class HelpCommand
- extends CommandSupport
-{
-
- 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") // TODO: i18n
- }
-
- io.out.println()
- io.out.println("usage: @|bold ${command.name}|@ $command.usage") // TODO: i18n
- 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
-
- 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('For information about @|green Groovy|@, visit:') // TODO: i18n
- io.out.println(' @|cyan http://groovy-lang.org|@ ') // FIXME: parsing freaks out if end tok is at the last char...
- io.out.println()
-
- // List the commands we know about
- io.out.println('Available commands:') // TODO: i18n
-
- for (Command command in registry.commands()) {
- if (command.hidden) {
- continue
- }
-
- def n = command.name.padRight(maxName, ' ')
- def s = command.shortcut.padRight(maxShortcut, ' ')
-
- //
- // TODO: Wrap description if needed
- //
-
- def d = command.description
-
- io.out.println(" @|bold ${n}|@ (@|bold ${s}|@) $d")
- }
-
- io.out.println()
- io.out.println('For help on a specific command type:') // TODO: i18n
- io.out.println(' :help @|bold command|@ ')
- io.out.println()
- }
-}
-
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/HistoryCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/HistoryCommand.groovy
deleted file mode 100644
index 0592034..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/HistoryCommand.groovy
+++ /dev/null
@@ -1,154 +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.codehaus.groovy.tools.shell.commands
-
-import jline.console.history.History
-import org.codehaus.groovy.tools.shell.ComplexCommandSupport
-import org.codehaus.groovy.tools.shell.Groovysh
-import org.codehaus.groovy.tools.shell.util.SimpleCompletor
-
-/**
- * The 'history' command.
- */
-@Deprecated
-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
- }
-
- SimpleCompletor subCommandsCompletor = new SimpleCompletor(loader)
- subCommandsCompletor.setWithBlank(false)
- return [
- subCommandsCompletor,
- 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
- }
-
- def do_show = {
- Iterator<History.Entry> histIt = history.iterator()
- while (histIt.hasNext()) {
- History.Entry next = histIt.next()
- if (next) {
- io.out.println(" @|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 show shows a list of indexes and past commands. recall serves to rerun one of those by their index.
- * There is is 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 identifer')
- }
-
- 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/codehaus/groovy/tools/shell/commands/ImportCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/ImportCommand.groovy
deleted file mode 100644
index a9bb41e..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/ImportCommand.groovy
+++ /dev/null
@@ -1,264 +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.codehaus.groovy.tools.shell.commands
-
-import groovy.transform.CompileStatic
-import jline.console.completer.AggregateCompleter
-import jline.console.completer.Completer
-import jline.console.completer.NullCompleter
-import jline.console.completer.StringsCompleter
-import org.codehaus.groovy.control.CompilationFailedException
-import org.codehaus.groovy.control.ResolveVisitor
-import org.codehaus.groovy.tools.shell.CommandSupport
-import org.codehaus.groovy.tools.shell.Evaluator
-import org.codehaus.groovy.tools.shell.Groovysh
-import org.codehaus.groovy.tools.shell.Interpreter
-import org.codehaus.groovy.tools.shell.completion.ReflectionCompletionCandidate
-import org.codehaus.groovy.tools.shell.completion.ReflectionCompletor
-import org.codehaus.groovy.tools.shell.completion.StricterArgumentCompleter
-import org.codehaus.groovy.tools.shell.util.Logger
-import org.codehaus.groovy.tools.shell.util.PackageHelper
-
-import java.util.regex.Pattern
-
-/**
- * The 'import' command.
- */
-@Deprecated
-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 = new NullCompleter()
- 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)
-
- }
-
- Object execute(final List<String> args) {
- assert args != null
-
- if (args.isEmpty()) {
- fail('Command \'import\' requires one or more arguments') // TODO: i18n
- }
-
- 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}'" // TODO: i18n
- log.debug(msg)
- fail(msg)
- }
- // remove last semicolon
- importSpec = importSpec.replaceAll(';', '')
-
- def buff = [ 'import ' + args.join(' ') ]
- buff << 'def dummp = false'
-
- def type
- try {
- type = classLoader.parseClass(buff.join(NEWLINE))
-
- // No need to keep duplicates, but order may be important so remove the previous def, since
- // the last defined import will win anyways
-
- if (imports.remove(importSpec)) {
- log.debug('Removed duplicate import from list')
- }
-
- 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
- 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 Classnames 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, packagenames or fully qualified classNames
- private static final Pattern PACK_OR_CLASSNAME_PATTERN = ~/^([a-z_]{1}[a-z0-9_]*(\.[a-z0-9_]*)*(\.[A-Z][^.]*)?)?$/
- // matches empty, packagenames or fully qualified classNames 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, packagenames or fully qualified classNames 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
- int complete(final String buffer, final int cursor, final List<CharSequence> result) {
- String currentImportExpression = buffer ? buffer.substring(0, cursor) : ''
- if (staticImport) {
- if (! (currentImportExpression.matches(PACK_OR_CLASS_OR_METHODNAME_PATTERN))) {
- return -1
- }
- } else {
- if (! (currentImportExpression.matches(PACK_OR_SIMPLE_CLASSNAME_PATTERN))) {
- return -1
- }
- }
- if (currentImportExpression.contains('..')) {
- return -1
- }
-
- 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) {
- result.addAll(classnames.collect({ String it -> it + '.'}))
- } else {
- result.addAll(classnames.collect({ String it -> addDotOrBlank(it) }))
- }
- }
- if (! staticImport) {
- result.add('* ')
- }
- 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 = ReflectionCompletor.getPublicFieldsAndMethods(clazz, '')
- result.addAll(members.collect({ ReflectionCompletionCandidate it -> it.value.replace('(', '').replace(')', '') + ' ' }))
- }
- result.add('* ')
- return currentImportExpression.length()
- }
- return -1
- } // 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) {
- result.addAll(standards)
- return 0
- }
- return -1
- }
-
- log.debug(prefix)
- Collection<String> matches = candidates.findAll({ String it -> it.startsWith(prefix) })
- if (matches) {
- result.addAll(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 = ReflectionCompletor.getPublicFieldsAndMethods(clazz, prefix)
- if (members) {
- result.addAll(members.collect({ ReflectionCompletionCandidate it -> it.value.replace('(', '').replace(')', '') + ' ' }))
- return lastDot <= 0 ? 0 : lastDot + 1
- }
- }
- }
- return -1
- }
-
- 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/codehaus/groovy/tools/shell/commands/InspectCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/InspectCommand.groovy
deleted file mode 100644
index 7242308..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/InspectCommand.groovy
+++ /dev/null
@@ -1,130 +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.codehaus.groovy.tools.shell.commands
-
-import groovy.inspect.swingui.ObjectBrowser
-import jline.console.completer.Completer
-import org.codehaus.groovy.tools.shell.CommandSupport
-import org.codehaus.groovy.tools.shell.Groovysh
-import org.codehaus.groovy.tools.shell.util.SimpleCompletor
-
-import javax.swing.*
-import java.awt.*
-import java.util.List
-
-/**
- * The 'inspect' command.
- */
-@Deprecated
-class InspectCommand
- extends CommandSupport
-{
- public static final String COMMAND_NAME = ':inspect'
-
- InspectCommand(final Groovysh shell) {
- super(shell, COMMAND_NAME, ':n')
- }
-
- def lafInitialized = false
- def headless
-
- @Override
- protected List<Completer> createCompleters() {
- return [
- new InspectCommandCompletor(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("@|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)
- }
- }
-}
-
-/**
- * Completor for the 'inspect' command.
- */
-class InspectCommandCompletor
- extends SimpleCompletor
-{
- private final Binding binding
-
- InspectCommandCompletor(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/codehaus/groovy/tools/shell/commands/LoadCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/LoadCommand.groovy
deleted file mode 100644
index 0eb6ceb..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/LoadCommand.groovy
+++ /dev/null
@@ -1,88 +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.codehaus.groovy.tools.shell.commands
-
-import jline.console.completer.Completer
-import jline.internal.Configuration
-import org.codehaus.groovy.tools.shell.CommandSupport
-import org.codehaus.groovy.tools.shell.Groovysh
-import org.codehaus.groovy.tools.shell.completion.FileNameCompleter
-
-/**
- * The 'load' command.
- */
-@Deprecated
-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/codehaus/groovy/tools/shell/commands/PurgeCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/PurgeCommand.groovy
deleted file mode 100644
index 7d87772..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/PurgeCommand.groovy
+++ /dev/null
@@ -1,85 +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.codehaus.groovy.tools.shell.commands
-
-import org.codehaus.groovy.tools.shell.ComplexCommandSupport
-import org.codehaus.groovy.tools.shell.Groovysh
-import org.codehaus.groovy.tools.shell.util.Preferences
-
-/**
- * The 'purge' command.
- */
-@Deprecated
-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/codehaus/groovy/tools/shell/commands/RecordCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/RecordCommand.groovy
deleted file mode 100644
index 4da47c4..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/RecordCommand.groovy
+++ /dev/null
@@ -1,139 +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.codehaus.groovy.tools.shell.commands
-
-import org.codehaus.groovy.runtime.InvokerHelper
-import org.codehaus.groovy.tools.shell.ComplexCommandSupport
-import org.codehaus.groovy.tools.shell.Groovysh
-
-/**
- * The 'record' command.
- */
-@Deprecated
-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: ${InvokerHelper.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/codehaus/groovy/tools/shell/commands/RegisterCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/RegisterCommand.groovy
deleted file mode 100644
index fc0de96..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/RegisterCommand.groovy
+++ /dev/null
@@ -1,80 +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.codehaus.groovy.tools.shell.commands
-
-import org.codehaus.groovy.tools.shell.Command
-import org.codehaus.groovy.tools.shell.CommandSupport
-import org.codehaus.groovy.tools.shell.Groovysh
-
-/**
- * The 'register' command.
- * Registers a class as a new groovysh command.
- * Requires the command to have matching constructors (shell) or (shell, name, alias).
- */
-@Deprecated
-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 completor
- command = type.newInstance(shell, args.get(1), null) as Command
- }
- else if (args.size() == 3) { // pass name, alias to completor
- 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/codehaus/groovy/tools/shell/commands/SaveCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/SaveCommand.groovy
deleted file mode 100644
index f7ed5ca..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/SaveCommand.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.codehaus.groovy.tools.shell.commands
-
-import jline.console.completer.Completer
-import jline.console.completer.FileNameCompleter
-import org.codehaus.groovy.tools.shell.CommandSupport
-import org.codehaus.groovy.tools.shell.Groovysh
-
-/**
- * The 'save' command.
- */
-@Deprecated
-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 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/codehaus/groovy/tools/shell/commands/SetCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/SetCommand.groovy
deleted file mode 100644
index b031c3a..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/SetCommand.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.codehaus.groovy.tools.shell.commands
-
-import jline.console.completer.Completer
-import org.codehaus.groovy.tools.shell.CommandSupport
-import org.codehaus.groovy.tools.shell.Groovysh
-import org.codehaus.groovy.tools.shell.util.PackageHelper
-import org.codehaus.groovy.tools.shell.util.Preferences
-import org.codehaus.groovy.tools.shell.util.SimpleCompletor
-
-/**
- * The 'set' command, used to set preferences.
- */
-@Deprecated
-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 SimpleCompletor(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/codehaus/groovy/tools/shell/commands/ShadowCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/ShadowCommand.groovy
deleted file mode 100644
index ee9505b..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/ShadowCommand.groovy
+++ /dev/null
@@ -1,57 +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.codehaus.groovy.tools.shell.commands
-
-import org.codehaus.groovy.tools.shell.ComplexCommandSupport
-import org.codehaus.groovy.tools.shell.Groovysh
-import org.codehaus.groovy.tools.shell.IO
-import org.codehaus.groovy.tools.shell.util.Preferences
-
-/**
- * The 'shadow' command.
- */
-@Deprecated
-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/codehaus/groovy/tools/shell/commands/ShowCommand.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/ShowCommand.groovy
deleted file mode 100644
index d3362b6..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/commands/ShowCommand.groovy
+++ /dev/null
@@ -1,105 +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.codehaus.groovy.tools.shell.commands
-
-import org.codehaus.groovy.runtime.InvokerHelper
-import org.codehaus.groovy.runtime.MethodClosure
-import org.codehaus.groovy.tools.shell.ComplexCommandSupport
-import org.codehaus.groovy.tools.shell.Groovysh
-import org.codehaus.groovy.tools.shell.util.Preferences
-
-/**
- * The 'show' command.
- */
-@Deprecated
-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 = ${InvokerHelper.toString(value)}")
- }
- }
- }
-
- 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/codehaus/groovy/tools/shell/completion/BackslashEscapeCompleter.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/BackslashEscapeCompleter.groovy
deleted file mode 100644
index 6b5a55e..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/BackslashEscapeCompleter.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.codehaus.groovy.tools.shell.completion
-
-import jline.console.completer.Completer
-
-import static jline.internal.Preconditions.checkNotNull
-
-/**
- * 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
- */
-@Deprecated
-class BackslashEscapeCompleter implements Completer {
- private static final List<String> VALID_ESCAPEES = ['r (return)', 'n (newline)', 't (tab)',
- '\\ (backslash)', "' (single quote)", '" (double quote)',
- 'b (backspace)', 'f (formfeed)', 'uXXXX (unicode)']
-
- @Override
- int complete(String buffer, final int cursor, final List<CharSequence> candidates) {
- checkNotNull(candidates)
- candidates.addAll(VALID_ESCAPEES)
- return cursor
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/CommandNameCompleter.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/CommandNameCompleter.groovy
deleted file mode 100644
index 92a92cd..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/CommandNameCompleter.groovy
+++ /dev/null
@@ -1,53 +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.codehaus.groovy.tools.shell.completion
-
-import org.codehaus.groovy.tools.shell.Command
-import org.codehaus.groovy.tools.shell.CommandRegistry
-import org.codehaus.groovy.tools.shell.util.SimpleCompletor
-
-/**
- * Completor for the command.names
- */
-@Deprecated
-class CommandNameCompleter extends SimpleCompletor {
- 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/codehaus/groovy/tools/shell/completion/CustomClassSyntaxCompletor.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/CustomClassSyntaxCompletor.groovy
deleted file mode 100644
index 26c7292..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/CustomClassSyntaxCompletor.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.codehaus.groovy.tools.shell.completion
-
-import org.codehaus.groovy.antlr.GroovySourceToken
-import org.codehaus.groovy.tools.shell.Groovysh
-
-/**
- * Completor completingclasses defined in the shell
- */
-@Deprecated
-class CustomClassSyntaxCompletor implements IdentifierCompletor {
-
- private final Groovysh shell
-
- CustomClassSyntaxCompletor(final Groovysh shell) {
- this.shell = shell
- }
-
- @Override
- boolean complete(final List<GroovySourceToken> 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/codehaus/groovy/tools/shell/completion/FileNameCompleter.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/FileNameCompleter.groovy
deleted file mode 100644
index 79178b4..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/FileNameCompleter.groovy
+++ /dev/null
@@ -1,172 +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.codehaus.groovy.tools.shell.completion
-
-import groovy.transform.PackageScope
-import jline.internal.Configuration
-
-import static jline.internal.Preconditions.checkNotNull
-
-/**
- * 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
- */
-@Deprecated
-class FileNameCompleter extends jline.console.completer.FileNameCompleter {
- private static final boolean OS_IS_WINDOWS = 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
- int complete(String buffer, final int cursor, final List<CharSequence> 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()
-
- return 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/codehaus/groovy/tools/shell/completion/GroovySyntaxCompletor.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/GroovySyntaxCompletor.groovy
deleted file mode 100644
index 5ba3104..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/GroovySyntaxCompletor.groovy
+++ /dev/null
@@ -1,375 +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.codehaus.groovy.tools.shell.completion
-
-import antlr.TokenStreamException
-import groovy.transform.TupleConstructor
-import jline.console.completer.Completer
-import jline.internal.Configuration
-import org.codehaus.groovy.antlr.GroovySourceToken
-import org.codehaus.groovy.antlr.SourceBuffer
-import org.codehaus.groovy.antlr.UnicodeEscapingReader
-import org.codehaus.groovy.antlr.parser.GroovyLexer
-import org.codehaus.groovy.tools.shell.CommandRegistry
-import org.codehaus.groovy.tools.shell.Groovysh
-import org.codehaus.groovy.tools.shell.util.Logger
-
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.DOT
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.EOF
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.IDENT
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LITERAL_as
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LITERAL_boolean
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LITERAL_byte
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LITERAL_catch
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LITERAL_char
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LITERAL_class
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LITERAL_def
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LITERAL_double
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LITERAL_enum
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LITERAL_false
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LITERAL_finally
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LITERAL_float
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LITERAL_import
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LITERAL_instanceof
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LITERAL_int
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LITERAL_interface
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LITERAL_long
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LITERAL_package
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LITERAL_short
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LITERAL_this
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LITERAL_true
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LITERAL_try
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LITERAL_void
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.OPTIONAL_DOT
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.SPREAD_DOT
-
-/**
- * Implements the Completor interface to provide competions for
- * GroovyShell by tokenizing the buffer and invoking other classes depending on the tokens found.
- */
-@Deprecated
-class GroovySyntaxCompletor implements Completer {
-
- protected final static Logger LOG = Logger.create(GroovySyntaxCompletor)
-
- private final Groovysh shell
- private final List<IdentifierCompletor> identifierCompletors
- private final IdentifierCompletor classnameCompletor
- private final ReflectionCompletor reflectionCompletor
- private final InfixKeywordSyntaxCompletor infixCompletor
- private final Completer defaultFilenameCompletor
- private final Completer windowsFilenameCompletor
- private final Completer instringFilenameCompletor
- private final Completer backslashCompletor
- private static final boolean isWin = 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
- }
-
- GroovySyntaxCompletor(final Groovysh shell,
- final ReflectionCompletor reflectionCompletor,
- IdentifierCompletor classnameCompletor,
- final List<IdentifierCompletor> identifierCompletors,
- final Completer filenameCompletor) {
- this.shell = shell
- this.classnameCompletor = classnameCompletor
- this.identifierCompletors = identifierCompletors
- infixCompletor = new InfixKeywordSyntaxCompletor()
- backslashCompletor = new BackslashEscapeCompleter()
- this.reflectionCompletor = reflectionCompletor
- defaultFilenameCompletor = filenameCompletor
- windowsFilenameCompletor = new FileNameCompleter(false, true, false)
- instringFilenameCompletor = new FileNameCompleter(false, false, false)
- }
-
- @Override
- int complete(final String bufferLine, final int cursor, final List<CharSequence> candidates) {
- if (!bufferLine) {
- return -1
- }
- if (isCommand(bufferLine, shell.registry)) {
- return -1
- }
- // complete given the context of the whole buffer, not just last line
- // Build a single string for the lexer
- List<GroovySourceToken> tokens = []
- try {
- if (!tokenizeBuffer(bufferLine.substring(0, cursor), shell.buffers.current(), tokens)) {
- return -1
- }
- } catch (InStringException ise) {
- int completionStart = ise.column + ise.openDelim.size()
- def remainder = bufferLine.substring(completionStart)
- def completer = instringFilenameCompletor
- if (['"', "'", '"""', "'''"].contains(ise.openDelim)) {
- if (isWin) {
- completer = windowsFilenameCompletor
- }
- // 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 backslashCompletor.complete(remainder, cursor, candidates)
- } catch (Exception ex2) {
- }
- }
- }
- }
- int completionResult = completer.complete(remainder, 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 (infixCompletor.complete(tokens, candidates)) {
- return tokens.last().column - 1
- }
- return -1
- }
- if (completionCase == CompletionCase.INSTANCEOF) {
- if (classnameCompletor.complete(tokens, candidates)) {
- return tokens.last().column - 1
- }
- 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 = reflectionCompletor.complete(tokens, candidates)
- break
- default:
- // bug
- throw new RuntimeException("Unknown Completion case: $completionCase")
-
- }
- return result
- }
-
- static CompletionCase getCompletionCase(final List<GroovySourceToken> tokens) {
- GroovySourceToken currentToken = tokens[-1]
-
- // now look at last 2 tokens to decide whether we are in a completion situation at all
- if (currentToken.type == IDENT) {
- // cursor is on identifier, use it as prefix and check whether it follows a dot
-
- if (tokens.size() == 1) {
- return CompletionCase.NO_DOT_PREFIX
- }
- GroovySourceToken previousToken = tokens[-2]
- if (previousToken.type == DOT || previousToken.type == OPTIONAL_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) {
- // 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 completor
- case LITERAL_import:
- case LITERAL_class:
- case LITERAL_interface:
- case LITERAL_enum:
- case LITERAL_def:
- case LITERAL_void:
- case LITERAL_boolean:
- case LITERAL_byte:
- case LITERAL_char:
- case LITERAL_short:
- case LITERAL_int:
- case LITERAL_float:
- case LITERAL_long:
- case LITERAL_double:
- case LITERAL_package:
- case LITERAL_true:
- case LITERAL_false:
- case LITERAL_as:
- case LITERAL_this:
- case LITERAL_try:
- case LITERAL_finally:
- case LITERAL_catch:
- return CompletionCase.NO_COMPLETION
- case IDENT:
- // 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 == OPTIONAL_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) {
- // 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 == LITERAL_instanceof) {
- return CompletionCase.INSTANCEOF
- } else {
- LOG.debug('Untreated toke type: ' + currentToken.type)
- }
- return CompletionCase.NO_COMPLETION
- }
-
- int completeIdentifier(final List<GroovySourceToken> tokens, final List<CharSequence> candidates) {
- boolean foundMatches = false
- for (IdentifierCompletor completor : identifierCompletors) {
- foundMatches |= completor.complete(tokens, candidates)
- }
- if (foundMatches) {
- return tokens.last().column - 1
- }
- 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 GroovyLexer createGroovyLexer(final String src) {
- Reader unicodeReader = new UnicodeEscapingReader(new StringReader(src), new SourceBuffer())
- GroovyLexer lexer = new GroovyLexer(unicodeReader)
- unicodeReader.setLexer(lexer)
- return lexer
- }
-
- @TupleConstructor
- static class InStringException extends Exception {
- int column
- String openDelim
-
- @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<GroovySourceToken> result) {
- GroovyLexer groovyLexer
- if (previousLines.size() > 0) {
- StringBuilder src = new StringBuilder()
- for (String line : previousLines) {
- src.append(line).append('\n')
- }
- src.append(bufferLine)
- groovyLexer = createGroovyLexer(src.toString())
- } else {
- groovyLexer = createGroovyLexer(bufferLine)
- }
- // Build a list of tokens using a GroovyLexer
- GroovySourceToken nextToken
- GroovySourceToken lastToken
- while (true) {
- try {
- nextToken = groovyLexer.nextToken() as GroovySourceToken
- 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 (TokenStreamException e) {
- // 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)
- //System.err.println "|" + remainder + "|"
- // 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
- return false
- }
- }
- return !result.empty
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/IdentifierCompletor.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/IdentifierCompletor.groovy
deleted file mode 100644
index 9192356..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/IdentifierCompletor.groovy
+++ /dev/null
@@ -1,39 +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.codehaus.groovy.tools.shell.completion
-
-import org.codehaus.groovy.antlr.GroovySourceToken
-
-/**
- * Interface for classes that complete identifier tokens within a groovy Statement
- * (Class, variable, keyword, method, ...)
- * Similar to JLine Completor, but adapted for usage in GroovySyntaxCompletor
- */
-@Deprecated
-interface IdentifierCompletor {
-
- /**
- *
- * @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<GroovySourceToken> tokens, List<CharSequence> candidates)
-
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/ImportsSyntaxCompletor.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/ImportsSyntaxCompletor.groovy
deleted file mode 100644
index e8c35e1..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/ImportsSyntaxCompletor.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.codehaus.groovy.tools.shell.completion
-
-import org.codehaus.groovy.antlr.GroovySourceToken
-import org.codehaus.groovy.control.ResolveVisitor
-import org.codehaus.groovy.tools.shell.Groovysh
-
-/**
- * Completor completing imported classnames
- */
-@Deprecated
-class ImportsSyntaxCompletor implements IdentifierCompletor {
-
- 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
- }
-
- ImportsSyntaxCompletor(final Groovysh shell) {
- this.shell = shell
- }
-
- @Override
- boolean complete(final List<GroovySourceToken> 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 = ReflectionCompletor.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/codehaus/groovy/tools/shell/completion/InfixKeywordSyntaxCompletor.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/InfixKeywordSyntaxCompletor.groovy
deleted file mode 100644
index 266c92e..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/InfixKeywordSyntaxCompletor.groovy
+++ /dev/null
@@ -1,49 +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.codehaus.groovy.tools.shell.completion
-
-import org.codehaus.groovy.antlr.GroovySourceToken
-
-/**
- * Completor completing groovy keywords that appear after identifiers
- */
-@Deprecated
-class InfixKeywordSyntaxCompletor implements IdentifierCompletor {
-
- // INFIX keywords can only occur after identifiers
- private static final String[] INFIX_KEYWORDS = [
- 'in',
- 'instanceof',
- 'extends',
- 'implements',
- ]
-
- @Override
- boolean complete(final List<GroovySourceToken> 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/codehaus/groovy/tools/shell/completion/KeywordSyntaxCompletor.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/KeywordSyntaxCompletor.groovy
deleted file mode 100644
index be3e179..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/KeywordSyntaxCompletor.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.codehaus.groovy.tools.shell.completion
-
-import org.codehaus.groovy.antlr.GroovySourceToken
-
-/**
- * Completor completing Groovy keywords and special functions
- */
-@Deprecated
-class KeywordSyntaxCompletor implements IdentifierCompletor {
-
- 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
- '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<GroovySourceToken> 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/codehaus/groovy/tools/shell/completion/NavigablePropertiesCompleter.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/NavigablePropertiesCompleter.groovy
deleted file mode 100644
index 5cbee7f..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/NavigablePropertiesCompleter.groovy
+++ /dev/null
@@ -1,97 +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.codehaus.groovy.tools.shell.completion
-
-import java.util.regex.Pattern
-
-@Deprecated
-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/codehaus/groovy/tools/shell/completion/ReflectionCompletionCandidate.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/ReflectionCompletionCandidate.groovy
deleted file mode 100644
index a11d3cf..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/ReflectionCompletionCandidate.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.codehaus.groovy.tools.shell.completion
-
-import groovy.transform.CompileStatic
-
-/**
- * A candidate as String with additional jansi formatting codes
- */
-@CompileStatic
-@Deprecated
-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/codehaus/groovy/tools/shell/completion/ReflectionCompletor.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/ReflectionCompletor.groovy
deleted file mode 100644
index 682bbe1..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/ReflectionCompletor.groovy
+++ /dev/null
@@ -1,721 +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.codehaus.groovy.tools.shell.completion
-
-import org.codehaus.groovy.antlr.GroovySourceToken
-import org.codehaus.groovy.control.MultipleCompilationErrorsException
-import org.codehaus.groovy.runtime.InvokerHelper
-import org.codehaus.groovy.tools.shell.Groovysh
-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.codehaus.groovy.antlr.parser.GroovyTokenTypes.ASSIGN
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.BAND
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.BAND_ASSIGN
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.BNOT
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.BOR
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.BOR_ASSIGN
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.BXOR
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.BXOR_ASSIGN
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.COLON
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.COMMA
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.COMPARE_TO
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.DIV
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.DIV_ASSIGN
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.DOT
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.EQUAL
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.GE
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.GT
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.IDENT
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LAND
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LBRACK
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LCURLY
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LE
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LITERAL_false
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LITERAL_in
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LITERAL_instanceof
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LITERAL_true
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LNOT
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LOR
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LPAREN
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.LT
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.MEMBER_POINTER
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.MINUS
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.MINUS_ASSIGN
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.NOT_EQUAL
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.NUM_BIG_DECIMAL
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.NUM_BIG_INT
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.NUM_DOUBLE
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.NUM_FLOAT
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.NUM_INT
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.NUM_LONG
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.OPTIONAL_DOT
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.PLUS
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.PLUS_ASSIGN
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.RANGE_EXCLUSIVE
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.RANGE_INCLUSIVE
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.RBRACK
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.RPAREN
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.SEMI
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.SPREAD_DOT
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.STAR
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.STAR_ASSIGN
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.STRING_CTOR_START
-import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.STRING_LITERAL
-
-/**
- * Completes fields and methods of Classes or instances.
- * Does not quite respect the contract of IdentifierCompletor, as last Token may be a dot or not,
- * thus also returns as int the cursor position.
- */
-@Deprecated
-class ReflectionCompletor {
-
- 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
- */
- ReflectionCompletor(final Groovysh shell) {
- this.shell = shell
- }
-
- int complete(final List<GroovySourceToken> tokens, final List<CharSequence> candidates) {
- GroovySourceToken currentElementToken = null
- GroovySourceToken dotToken
- List<GroovySourceToken> previousTokens
- if (tokens.size() < 2) {
- throw new IllegalArgumentException('must be invoked with at least 2 tokens, one of which is dot' + tokens*.text)
- }
- if (tokens.last().type == DOT || tokens.last().type == OPTIONAL_DOT || tokens.last().type == SPREAD_DOT) {
- dotToken = tokens.last()
- previousTokens = tokens[0..-2]
- } else {
- if (tokens[-2].type != DOT && tokens[-2].type != OPTIONAL_DOT && tokens[-2].type != SPREAD_DOT) {
- throw new IllegalArgumentException('must be invoked with token list with dot 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 GroovySourceToken currentElementToken,
- final GroovySourceToken dotToken) {
- // look for public methods/fields that match the prefix
- Collection<ReflectionCompletionCandidate> myCandidates = getPublicFieldsAndMethods(instanceOrClass, identifierPrefix)
-
- 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 (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.column - 1
- } else {
- // Spread-dot has length 2!
- lastDot = dotToken.column +(dotToken.getText().length() - 1)
- }
- 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<GroovySourceToken> groovySourceTokens) {
- if (!groovySourceTokens
- || groovySourceTokens.last().type == DOT
- || groovySourceTokens.last().type == OPTIONAL_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<GroovySourceToken> 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 groovySourceTokens
- * @return
- */
- static List<GroovySourceToken> getInvokerTokens(final List<GroovySourceToken> groovySourceTokens) {
- int validIndex = groovySourceTokens.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>()
- GroovySourceToken lastToken = null
- outerloop:
- for (GroovySourceToken loopToken in groovySourceTokens.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 STRING_LITERAL:
- // 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 COMPARE_TO:
- case EQUAL:
- case NOT_EQUAL:
- case ASSIGN:
- case GT:
- case LT:
- case GE:
- case LE:
- case PLUS:
- case PLUS_ASSIGN:
- case MINUS:
- case MINUS_ASSIGN:
- case STAR:
- case STAR_ASSIGN:
- case DIV:
- case DIV_ASSIGN:
- case BOR:
- case BOR_ASSIGN:
- case BAND:
- case BAND_ASSIGN:
- case BXOR:
- case BXOR_ASSIGN:
- case BNOT:
- case LOR:
- case LAND:
- case LNOT:
- case LITERAL_in:
- case LITERAL_instanceof:
- if (expectedOpeners.empty()) {
- break outerloop
- }
- break
- // tokens which indicate we have reached the beginning of a statement
- case LCURLY:
- case SEMI:
- case STRING_CTOR_START:
- break outerloop
- // tokens we accept
- case IDENT:
- if (lastToken) {
- if (lastToken.type == LPAREN) {
- //Method invocation,must be avoided
- return []
- }
- if (lastToken.type == IDENT) {
- // 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:
- case COLON:
- case COMMA:
- if (expectedOpeners.empty()) {
- break outerloop
- }
- // harmless literals
- case LITERAL_true:
- case LITERAL_false:
- case NUM_INT:
- case NUM_FLOAT:
- case NUM_LONG:
- case NUM_DOUBLE:
- case NUM_BIG_INT:
- case NUM_BIG_DECIMAL:
- case MEMBER_POINTER:
- case DOT:
- case OPTIONAL_DOT:
- break
- default:
- return null
- } // end switch
- validIndex --
- lastToken = loopToken
- } // end for
- return groovySourceTokens[(validIndex)..-1]
- }
-
- static String tokenListToEvalString(final List<GroovySourceToken> groovySourceTokens) {
- StringBuilder builder = new StringBuilder()
- for (GroovySourceToken token: groovySourceTokens) {
- if (token.type == STRING_LITERAL) {
- 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) {
- 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 || (prefix.length() >= Integer.valueOf(Preferences.get(Groovysh.METACLASS_COMPLETION_PREFIX_LENGTH_PREFERENCE_KEY, '3')))
- while (loopclazz != null && loopclazz != Object && loopclazz != GroovyObject) {
- addClassFieldsAndMethods(loopclazz, showStatic, !isClass, prefix, rv, renderBold)
- renderBold = false
- loopclazz = loopclazz.superclass
- }
- if (clazz.isArray() && !isClass) {
- // 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 (!isClass) {
- 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/codehaus/groovy/tools/shell/completion/StricterArgumentCompleter.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/StricterArgumentCompleter.groovy
deleted file mode 100644
index 010ef70..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/StricterArgumentCompleter.groovy
+++ /dev/null
@@ -1,133 +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.codehaus.groovy.tools.shell.completion
-
-import groovy.transform.CompileStatic
-import jline.console.completer.ArgumentCompleter
-import jline.console.completer.ArgumentCompleter.ArgumentDelimiter
-import jline.console.completer.ArgumentCompleter.ArgumentList
-import jline.console.completer.Completer
-import jline.internal.Log
-
-import static jline.internal.Preconditions.checkNotNull
-
-/**
- * This fixes strict jline 2.12 ArgumentCompleter
- * See https://github.com/jline/jline2/pull/202
- */
-@CompileStatic
-@Deprecated
-class StricterArgumentCompleter extends ArgumentCompleter {
-
- /**
- * Create a new completer with the default
- * {@link jline.console.completer.ArgumentCompleter.WhitespaceArgumentDelimiter}.
- *
- * @param completers The embedded completers
- */
- StricterArgumentCompleter(List<Completer> completers) {
- super(completers)
- }
-
- int complete(final String buffer, final int cursor, final List<CharSequence> candidates) {
- // buffer can be null
- checkNotNull(candidates)
-
- ArgumentDelimiter delim = delimiter
- ArgumentList list = delim.delimit(buffer, cursor)
- int argpos = list.argumentPosition
- int argIndex = list.cursorArgumentIndex
-
- if (argIndex < 0) {
- return -1
- }
-
- 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.getArguments()
- String arg = (args == null || i >= args.length) ? "" : args[i]
-
- List<CharSequence> subCandidates = new LinkedList<CharSequence>()
- int offset = sub.complete(arg, arg.length(), subCandidates)
- if (offset == -1) {
- return -1
- }
-
- // 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 (CharSequence 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 -1
- }
- }
-
- int ret = completer.complete(list.getCursorArgument(), argpos, candidates)
-
- if (ret == -1) {
- return -1
- }
-
- 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/codehaus/groovy/tools/shell/completion/VariableSyntaxCompletor.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/VariableSyntaxCompletor.groovy
deleted file mode 100644
index b063c4e..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/completion/VariableSyntaxCompletor.groovy
+++ /dev/null
@@ -1,63 +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.codehaus.groovy.tools.shell.completion
-
-import org.codehaus.groovy.antlr.GroovySourceToken
-import org.codehaus.groovy.runtime.MethodClosure
-import org.codehaus.groovy.tools.shell.Groovysh
-
-/**
- * Completor completing variable and method names from known variables in the shell
- */
-@Deprecated
-class VariableSyntaxCompletor implements IdentifierCompletor {
-
- final Groovysh shell
-
- VariableSyntaxCompletor(final Groovysh shell) {
- this.shell = shell
- }
-
- @Override
- boolean complete(final List<GroovySourceToken> 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/codehaus/groovy/tools/shell/package.html b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/package.html
deleted file mode 100644
index 7ab22a2..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/package.html
+++ /dev/null
@@ -1,28 +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.
-
--->
-<html>
- <body>
- <p>
- Provides support for the Groovy Shell (aka. <tt>groovysh</tt>).
- </p>
- </body>
-</html>
-
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/CommandArgumentParser.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/CommandArgumentParser.groovy
deleted file mode 100644
index a25a00b..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/CommandArgumentParser.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.codehaus.groovy.tools.shell.util
-
-import groovy.transform.CompileStatic
-
-@CompileStatic
-@Deprecated
-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/codehaus/groovy/tools/shell/util/CurlyCountingGroovyLexer.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/CurlyCountingGroovyLexer.groovy
deleted file mode 100644
index ab87996..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/CurlyCountingGroovyLexer.groovy
+++ /dev/null
@@ -1,69 +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.codehaus.groovy.tools.shell.util
-
-import org.codehaus.groovy.antlr.GroovySourceToken
-import org.codehaus.groovy.antlr.SourceBuffer
-import org.codehaus.groovy.antlr.UnicodeEscapingReader
-import org.codehaus.groovy.antlr.parser.GroovyLexer
-import org.codehaus.groovy.antlr.parser.GroovyTokenTypes
-
-/**
- * patching GroovyLexer to get access to Paren level
- */
-@Deprecated
-class CurlyCountingGroovyLexer extends GroovyLexer {
-
- private endReached = false
-
- protected CurlyCountingGroovyLexer(Reader reader) {
- super(reader)
- }
-
- static CurlyCountingGroovyLexer createGroovyLexer(String src) {
- Reader unicodeReader = new UnicodeEscapingReader(new StringReader(src.toString()), new SourceBuffer())
- CurlyCountingGroovyLexer lexer = new CurlyCountingGroovyLexer(unicodeReader)
- unicodeReader.setLexer(lexer)
- return lexer
- }
-
- int getParenLevel() {
- return parenLevelStack.size()
- }
-
- // called by nextToken()
- @Override
- void uponEOF() {
- super.uponEOF()
- endReached = true
- }
-
- List<GroovySourceToken> toList() {
- List<GroovySourceToken> tokens = []
- GroovySourceToken token
- while (! endReached) {
- token = nextToken() as GroovySourceToken
- tokens.add(token)
- if (token.type == GroovyTokenTypes.EOF) {
- break
- }
- }
- return tokens
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/DefaultCommandsRegistrar.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/DefaultCommandsRegistrar.groovy
deleted file mode 100644
index 5ad8ec9..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/DefaultCommandsRegistrar.groovy
+++ /dev/null
@@ -1,89 +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.codehaus.groovy.tools.shell.util
-
-import org.codehaus.groovy.tools.shell.Command
-import org.codehaus.groovy.tools.shell.Shell
-import org.codehaus.groovy.tools.shell.commands.AliasCommand
-import org.codehaus.groovy.tools.shell.commands.ClearCommand
-import org.codehaus.groovy.tools.shell.commands.DisplayCommand
-import org.codehaus.groovy.tools.shell.commands.DocCommand
-import org.codehaus.groovy.tools.shell.commands.EditCommand
-import org.codehaus.groovy.tools.shell.commands.ExitCommand
-import org.codehaus.groovy.tools.shell.commands.GrabCommand
-import org.codehaus.groovy.tools.shell.commands.HelpCommand
-import org.codehaus.groovy.tools.shell.commands.HistoryCommand
-import org.codehaus.groovy.tools.shell.commands.ImportCommand
-import org.codehaus.groovy.tools.shell.commands.InspectCommand
-import org.codehaus.groovy.tools.shell.commands.LoadCommand
-import org.codehaus.groovy.tools.shell.commands.PurgeCommand
-import org.codehaus.groovy.tools.shell.commands.RecordCommand
-import org.codehaus.groovy.tools.shell.commands.RegisterCommand
-import org.codehaus.groovy.tools.shell.commands.SaveCommand
-import org.codehaus.groovy.tools.shell.commands.SetCommand
-import org.codehaus.groovy.tools.shell.commands.ShowCommand
-
-/**
- * Registers {@link Command} classes from an XML file like:
- * <commands>
- * <command>org.codehaus.groovy.tools.shell.commands.HelpCommand</command>
- * ...
- * </commands>
- */
-@Deprecated
-class DefaultCommandsRegistrar
-{
-
- private final Shell shell
-
- DefaultCommandsRegistrar(final Shell shell) {
- assert shell != null
-
- this.shell = shell
- }
-
- void register() {
-
- for (Command classname in [
- new HelpCommand(shell),
- new ExitCommand(shell),
- new ImportCommand(shell),
- new DisplayCommand(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 AliasCommand(shell),
- new SetCommand(shell),
- new GrabCommand(shell),
- // does not do anything
- //new ShadowCommand(shell),
- new RegisterCommand(shell),
- new DocCommand(shell)
- ]) {
- shell.register(classname)
- }
-
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/NoExitSecurityManager.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/NoExitSecurityManager.groovy
deleted file mode 100644
index ec8d142..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/NoExitSecurityManager.groovy
+++ /dev/null
@@ -1,64 +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.codehaus.groovy.tools.shell.util
-
-import java.security.Permission
-
-/**
- * Custom security manager to {@link System#exit} (and related) from being used.
- */
-@Deprecated
-public class NoExitSecurityManager
- extends SecurityManager
-{
- private final SecurityManager parent
-
- public NoExitSecurityManager(final SecurityManager parent) {
- this.parent = parent
- }
-
- public NoExitSecurityManager() {
- this(System.getSecurityManager())
- }
-
- @Override
- public void checkPermission(final Permission perm) {
- if (parent != null) {
- parent.checkPermission(perm)
- }
- }
-
- /**
- * Always throws {@link SecurityException}.
- */
- @Override
- public void checkExit(final int code) {
- throw new SecurityException('Use of System.exit() is forbidden!')
- }
-
- /*
- public void checkPermission(final Permission perm) {
- assert perm != null
-
- if (perm.getName().equals("exitVM")) {
- System.out.println("exitVM")
- }
- }
- */
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/PackageHelper.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/PackageHelper.groovy
deleted file mode 100644
index 42d75a3..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/PackageHelper.groovy
+++ /dev/null
@@ -1,30 +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.codehaus.groovy.tools.shell.util
-
-@Deprecated
-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/codehaus/groovy/tools/shell/util/PackageHelperImpl.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/PackageHelperImpl.groovy
deleted file mode 100644
index 5a6556d..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/PackageHelperImpl.groovy
+++ /dev/null
@@ -1,487 +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.codehaus.groovy.tools.shell.util
-
-import groovy.transform.CompileDynamic
-import groovy.transform.CompileStatic
-
-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
-import java.util.zip.ZipException
-
-/**
- * Helper class that crawls all items of the classpath for packages.
- * Retrieves from those sources the list of subpackages and classes on demand.
- */
-@CompileStatic
-@Deprecated
-class PackageHelperImpl implements PreferenceChangeListener, PackageHelper {
-
- // Pattern for regular Classnames
- public static final Pattern NAME_PATTERN = ~('^[A-Z][^.\$_]+\$')
-
- private static final String CLASS_SUFFIX = '.class'
- protected static final Logger LOG = Logger.create(PackageHelperImpl)
-
- Map<String, CachedPackage> rootPackages = null
- final ClassLoader groovyClassLoader
-
- PackageHelperImpl(final ClassLoader groovyClassLoader=null) {
- this.groovyClassLoader = groovyClassLoader
- initializePackages()
- Preferences.addChangeListener(this)
- }
-
- void reset() {
- initializePackages()
- }
-
- private void initializePackages() {
- if (! Boolean.valueOf(Preferences.get(IMPORT_COMPLETION_PREFERENCE_KEY))) {
- rootPackages = getPackages(this.groovyClassLoader)
- }
- }
-
- @Override
- void preferenceChange(final 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(final ClassLoader groovyClassLoader) throws IOException {
- Map<String, CachedPackage> rootPackages = new HashMap()
- Set<URL> urls = new HashSet<URL>()
-
- // 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'
- 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
- }
- }
-
- /**
- * This method 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)
- * @return
- */
- 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(final Collection<String> packageNames, final URL url,
- final 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 packagenames found at URL, accepts jar files and folders
- * @param url
- * @return
- */
- static Collection<String> getPackageNames(final URL url) {
- //log.debug(url)
- String path = URLDecoder.decode(url.getFile(), 'UTF-8')
- File urlfile = new File(path)
- if (urlfile.isDirectory()) {
- Set<String> packnames = new HashSet<String>()
- collectPackageNamesFromFolderRecursive(urlfile, '', packnames)
- return packnames
- }
-
- if (urlfile.path.endsWith('.jar')) {
- try {
- JarFile jf = new JarFile(urlfile)
- return getPackageNamesFromJar(jf)
- } catch(ZipException ze) {
- if (LOG.debugEnabled) {
- ze.printStackTrace()
- }
- LOG.debug("Error opening zipfile : '${url.getFile()}', ${ze.toString()}")
- } catch (FileNotFoundException fnfe) {
- LOG.debug("Error opening file : '${url.getFile()}', ${fnfe.toString()}")
- }
- }
- return []
- }
-
- /**
- * Crawls a folder, iterates over subfolders, looking for class files.
- * @param directory
- * @param prefix
- * @param packnames
- * @return
- */
- static Collection<String> collectPackageNamesFromFolderRecursive(final File directory, final String prefix,
- final Set<String> packnames) {
- //log.debug(directory)
- 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(final JarFile jf) {
- Set<String> packnames = new HashSet<String>()
- 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
- }
-
- // following block does not work, because URLClassLoader.packages only ever returns SystemPackages
- /*static Collection<String> getPackageNames(URL url) {
- URLClassLoader urlLoader = new URLClassLoader([url] as URL[])
- //log.debug(urlLoader.packages.getClass())
-
- urlLoader.getPackages().collect {Package pack ->
- pack.name
- }
- }*/
-
- /**
- * returns the names of Classes and direct subpackages contained in a package
- * @param packagename
- * @return
- */
- @CompileStatic
- Set<String> getContents(final 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, '.')
- CachedPackage cp = rootPackages.get(tokenizer.nextToken())
- while (cp != null && tokenizer.hasMoreTokens()) {
- String token = tokenizer.nextToken()
- if (cp.childPackages == null) {
- // no match for taken,no subpackages known
- return [] as Set
- }
- cp = cp.childPackages.get(token) as CachedPackage
- }
- if (cp == null) {
- return [] as Set
- }
- // TreeSet for ordering
- Set<String> children = new TreeSet()
- if (cp.childPackages) {
- children.addAll(cp.childPackages.collect { String key, CachedPackage v -> key })
- }
- if (cp.checked && !cp.containsClasses) {
- return children
- }
-
- Set<String> classnames = getClassnames(cp.sources, sanitizedPackageName)
-
- cp.checked = true
- if (classnames) {
- cp.containsClasses = true
- children.addAll(classnames)
- }
- return children
- }
-
- /**
- * Copied from JLine 1.0 ClassNameCompletor
- * @param urls
- * @param packagename
- * @return
- */
- static Set<String> getClassnames(final Set<URL> urls, final String packagename) {
- Set<String> classes = new TreeSet<String>()
- // normal slash even in Windows
- String pathname = packagename.replace('.', '/')
- for (Iterator<URL> it = urls.iterator(); it.hasNext();) {
- URL url = it.next()
- if (url.protocol == 'jrt') {
- getPackagesAndClassesFromJigsaw(url) { boolean isPackage, String name ->
- !isPackage && name.startsWith(packagename)
- }.collect(classes) { it - "${packagename}." }
- } else {
- File file = new File(URLDecoder.decode(url.getFile(), 'UTF-8'))
- if (file == null) {
- continue
- }
- if (file.isDirectory()) {
- File packFolder = new File(file, pathname)
- if (!packFolder.isDirectory()) {
- continue
- }
- File[] files = packFolder.listFiles()
- for (int i = 0; (files != null) && (i < files.length); i++) {
- if (files[i].isFile()) {
- String filename = files[i].name
- if (filename.endsWith(CLASS_SUFFIX)) {
- String name = filename.substring(0, filename.length() - CLASS_SUFFIX.length())
- if (!name.matches(NAME_PATTERN)) {
- continue
- }
- classes.add(name)
- }
- }
- }
- continue
- }
-
- if (!file.toString().endsWith('.jar')) {
- continue
- }
-
- JarFile jf = new JarFile(file)
-
- try {
- for (Enumeration e = jf.entries(); e.hasMoreElements();) {
- JarEntry entry = (JarEntry) e.nextElement()
-
- if (entry == null) {
- continue
- }
-
- String name = entry.name
-
- // only use class files
- if (!name.endsWith(CLASS_SUFFIX)) {
- continue
- }
- // normal slash inside jars even on windows
- int lastslash = name.lastIndexOf('/')
- if (lastslash == -1 || name.substring(0, lastslash) != pathname) {
- continue
- }
- name = name.substring(lastslash + 1, name.length() - CLASS_SUFFIX.length())
- if (!name.matches(NAME_PATTERN)) {
- continue
- }
- classes.add(name)
- }
- } finally {
- jf.close()
- }
- }
- }
-
-
- return classes
- }
-}
-
-@CompileStatic
-@Deprecated
-class CachedPackage {
- String name
- boolean containsClasses
- boolean checked
- Map<String, CachedPackage> childPackages
- Set<URL> sources
-
- CachedPackage(String name, Set<URL> sources) {
- this.sources = sources
- this.name = name
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/ScriptVariableAnalyzer.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/ScriptVariableAnalyzer.groovy
deleted file mode 100644
index 28a0ba1..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/ScriptVariableAnalyzer.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.codehaus.groovy.tools.shell.util
-
-import groovy.transform.TypeChecked
-import org.codehaus.groovy.ast.ClassCodeVisitorSupport
-import org.codehaus.groovy.ast.ClassNode
-import org.codehaus.groovy.ast.DynamicVariable
-import org.codehaus.groovy.ast.GroovyClassVisitor
-import org.codehaus.groovy.ast.expr.VariableExpression
-import org.codehaus.groovy.classgen.GeneratorContext
-import org.codehaus.groovy.control.CompilationFailedException
-import org.codehaus.groovy.control.CompilationUnit
-import org.codehaus.groovy.control.CompilerConfiguration
-import org.codehaus.groovy.control.Phases
-import org.codehaus.groovy.control.SourceUnit
-
-import java.security.CodeSource
-
-/**
- * Class to Class parsing a script to detect all bound and unbound variables.
- * Based on http://glaforge.appspot.com/article/knowing-which-variables-are-bound-or-not-in-a-groovy-script
- */
-@TypeChecked
-@Deprecated
-class ScriptVariableAnalyzer {
-
- /**
- * define a visitor that visits all variable expressions
- */
- @Deprecated
- static class VariableVisitor extends ClassCodeVisitorSupport implements GroovyClassVisitor {
- Set<String> bound = new HashSet<String>()
- Set<String> unbound = new HashSet<String>()
-
- @Override
- void visitVariableExpression(VariableExpression expression) {
- // we're not interested in some special implicit variables
- if (!(expression.variable in ['args', 'context', 'this', 'super'])) {
- // thanks to this instanceof
- // we know if the variable is bound or not
- if (expression.accessedVariable instanceof DynamicVariable) {
- unbound << expression.variable
- } else {
- bound << expression.variable
- }
- }
- super.visitVariableExpression(expression)
- }
-
- @Override
- protected SourceUnit getSourceUnit() {
- return null
- }
- }
-
- /**
- * custom PrimaryClassNodeOperation
- * to be able to hook our code visitor
- */
- @Deprecated
- static class VisitorSourceOperation extends CompilationUnit.PrimaryClassNodeOperation {
-
- final GroovyClassVisitor visitor
-
- VisitorSourceOperation(final GroovyClassVisitor visitor) {
- this.visitor = visitor
- }
-
- @Override
- void call(final SourceUnit source, final GeneratorContext context, final ClassNode classNode)
- throws CompilationFailedException {
- classNode.visitContents(visitor)
- }
- }
-
- /**
- * class loader to add our phase operation
- */
- @Deprecated
- static class VisitorClassLoader extends GroovyClassLoader {
- final GroovyClassVisitor visitor
-
- VisitorClassLoader(final GroovyClassVisitor visitor, ClassLoader parent) {
- super(parent == null ? Thread.currentThread().getContextClassLoader() : parent)
- this.visitor = visitor
- }
-
- @Override
- protected CompilationUnit createCompilationUnit(final CompilerConfiguration config, final CodeSource source) {
- CompilationUnit cu = super.createCompilationUnit(config, source)
- cu.addPhaseOperation(new VisitorSourceOperation(visitor), Phases.CLASS_GENERATION)
- return cu
- }
- }
-
- static Set<String> getBoundVars(final String scriptText, ClassLoader parent) {
- assert scriptText != null
- GroovyClassVisitor visitor = new VariableVisitor()
- VisitorClassLoader myCL = new VisitorClassLoader(visitor, parent)
- // simply by parsing the script with our classloader
- // our visitor will be called and will visit all the variables
- myCL.parseClass(scriptText)
- return visitor.bound
- }
-
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/SimpleCompletor.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/SimpleCompletor.groovy
deleted file mode 100644
index cf2bb4e..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/SimpleCompletor.groovy
+++ /dev/null
@@ -1,141 +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.codehaus.groovy.tools.shell.util
-
-import jline.console.completer.Completer
-import org.codehaus.groovy.runtime.InvokerHelper
-
-/**
- * Support for simple completors.
- */
-@Deprecated
-class SimpleCompletor implements Completer {
-
- SortedSet<String> candidates
-
- /**
- * A delimiter to use to qualify completions.
- */
- protected String delimiter
-
- boolean withBlank = true
-
-
- SimpleCompletor(final String[] candidates) {
- setCandidateStrings(candidates)
- }
-
- SimpleCompletor() {
- this(new String[0])
- }
-
- SimpleCompletor(final Closure loader) {
- this()
-
- assert loader != null
-
- Object obj = loader.call()
-
- List list = null
-
- if (obj instanceof List) {
- list = (List) obj
- }
-
- //
- // TODO: Maybe handle arrays too?
- //
-
- if (list == null) {
- throw new IllegalStateException('The loader closure did not return a list of candidates; found: ' + obj)
- }
-
- Iterator iter = list.iterator()
-
- while (iter.hasNext()) {
- add(InvokerHelper.toString(iter.next()))
- }
- }
-
- void setWithBlank(boolean withBlank) {
- this.withBlank = withBlank
- }
-
- void add(final String candidate) {
- addCandidateString(candidate)
- }
-
- Object leftShift(final String s) {
- add(s)
-
- return null
- }
-
- @Override
- int complete(final String buffer, final int cursor, final List<CharSequence> clist) {
- String start = (buffer == null) ? '' : buffer
-
- SortedSet<String> matches = getCandidates().tailSet(start)
-
- for (Iterator i = matches.iterator(); i.hasNext();) {
- String can = (String) i.next()
-
- if (!(can.startsWith(start))) {
- break
- }
-
- String delim = delimiter
-
- if (delim != null) {
- int index = can.indexOf(delim, cursor)
-
- if (index != -1) {
- can = can.substring(0, index + 1)
- }
- }
-
- if (withBlank) {
- can += ' '
- }
-
- clist.add(can)
- }
-
- // the index of the completion is always from the beginning of the buffer.
- return (clist.size() == 0) ? (-1) : 0
- }
-
- void setCandidates(final SortedSet<String> candidates) {
- this.candidates = candidates
- }
-
- SortedSet<String> getCandidates() {
- return Collections.unmodifiableSortedSet(this.candidates)
- }
-
- void setCandidateStrings(final String[] strings) {
- setCandidates(new TreeSet(Arrays.asList(strings)))
- }
-
- void addCandidateString(final String string) {
- if (string != null) {
- candidates.add(string)
- }
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/WrappedInputStream.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/WrappedInputStream.groovy
deleted file mode 100644
index 8a91f14..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/WrappedInputStream.groovy
+++ /dev/null
@@ -1,110 +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.codehaus.groovy.tools.shell.util
-
-/**
- * In order to modify JLine Behavior, we need to wrap the IO streams so we can hack into them
- * This allows autoindent and redisplaying the chars typed so far after exceptions during completion
- */
-@Deprecated
-class WrappedInputStream extends InputStream implements Closeable {
-
- final InputStream wrapped
- // observed sometimes ClassNotFoundException when not qualifying with java.io
- java.io.ByteArrayInputStream inserted = new java.io.ByteArrayInputStream()
-
-
- /**
- * Construct a new IO container using system streams.
- */
- WrappedInputStream(final InputStream wrapped) {
- super()
- this.wrapped = wrapped
- }
-
- @Override
- int read() throws java.io.IOException {
- if (inserted != null && inserted.available() > 0) {
- return inserted.read()
- }
- return wrapped.read()
- }
-
- void insert(String chars) {
- inserted.close()
- inserted = new java.io.ByteArrayInputStream(chars.getBytes('UTF-8'))
- }
-
- @Override
- int read(byte[] b) throws java.io.IOException {
- def insertb = inserted.read(b)
- if (insertb > 0) {
- return insertb
- }
- return wrapped.read(b)
- }
-
- @Override
- int read(byte[] b, int off, int len) throws java.io.IOException {
- def insertb = inserted.read(b, off, len)
- if (insertb > 0) {
- return insertb
- }
- return wrapped.read(b, off, len)
- }
-
- @Override
- long skip(long n) throws java.io.IOException {
- def skipb = inserted.skip(n)
- if (skipb > 0) {
- return skipb
- }
- return wrapped.skip(n)
- }
-
- @Override
- int available() throws java.io.IOException {
- int x = inserted.available()
- if (x > 0) {
- return x
- }
- return wrapped.available()
- }
-
- @Override
- void close() throws java.io.IOException {
- wrapped.close()
- inserted.close()
- }
-
- @Override
- synchronized void mark(int readlimit) {
- throw new UnsupportedOperationException()
- }
-
- @Override
- synchronized void reset() throws java.io.IOException {
- throw new UnsupportedOperationException()
- }
-
- @Override
- boolean markSupported() {
- return false
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/XmlCommandRegistrar.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/XmlCommandRegistrar.groovy
deleted file mode 100644
index 30de139..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/XmlCommandRegistrar.groovy
+++ /dev/null
@@ -1,95 +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.codehaus.groovy.tools.shell.util
-
-import org.codehaus.groovy.tools.shell.Command
-import org.codehaus.groovy.tools.shell.Shell
-
-/**
- * Registers {@link Command} classes from an XML file like:
- *
- * <pre>
- {@literal
- <commands>
- <!-- default commands -->
- <command>org.codehaus.groovy.tools.shell.commands.HelpCommand</command>
- <command>org.codehaus.groovy.tools.shell.commands.ExitCommand</command>
- <command>org.codehaus.groovy.tools.shell.commands.ImportCommand</command>
- <command>org.codehaus.groovy.tools.shell.commands.DisplayCommand</command>
- <command>org.codehaus.groovy.tools.shell.commands.ClearCommand</command>
- <command>org.codehaus.groovy.tools.shell.commands.ShowCommand</command>
- <command>org.codehaus.groovy.tools.shell.commands.InspectCommand</command>
- <command>org.codehaus.groovy.tools.shell.commands.PurgeCommand</command>
- <command>org.codehaus.groovy.tools.shell.commands.EditCommand</command>
- <command>org.codehaus.groovy.tools.shell.commands.LoadCommand</command>
- <command>org.codehaus.groovy.tools.shell.commands.SaveCommand</command>
- <command>org.codehaus.groovy.tools.shell.commands.RecordCommand</command>
- <command>org.codehaus.groovy.tools.shell.commands.HistoryCommand</command>
- <command>org.codehaus.groovy.tools.shell.commands.AliasCommand</command>
- <command>org.codehaus.groovy.tools.shell.commands.SetCommand</command>
- <command>org.codehaus.groovy.tools.shell.commands.ShadowCommand</command>
- <command>org.codehaus.groovy.tools.shell.commands.RegisterCommand</command>
- <command>org.codehaus.groovy.tools.shell.commands.DocCommand</command>
- <!-- custom commands -->
- </commands>
- * }
- * <pre>
- */
-@Deprecated
-class XmlCommandRegistrar {
- private final Logger log = Logger.create(this.class)
-
- private final Shell shell
-
- private final ClassLoader classLoader
-
- XmlCommandRegistrar(final Shell shell, final ClassLoader classLoader) {
- assert shell != null
- assert classLoader != null
-
- this.shell = shell
- this.classLoader = classLoader
- }
-
- void register(final URL url) {
- assert url
-
- if (log.debugEnabled) {
- log.debug("Registering commands from: $url")
- }
-
- url.withReader {Reader reader ->
- groovy.util.Node doc = new groovy.util.XmlParser().parse(reader)
-
- doc.children().each {groovy.util.Node element ->
- String classname = element.text()
-
- Class type = classLoader.loadClass(classname)
-
- Command command = type.newInstance(shell) as Command
-
- if (log.debugEnabled) {
- log.debug("Created command '${command.name}': $command")
- }
-
- shell << command
- }
- }
- }
-}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/package.html b/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/package.html
deleted file mode 100644
index c9ec0d5..0000000
--- a/subprojects/groovy-groovysh/src/main/groovy/org/codehaus/groovy/tools/shell/util/package.html
+++ /dev/null
@@ -1,30 +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.
-
--->
-<!-- $Id: package.html 7254 2007-08-15 22:26:39Z user57 $ -->
-
-<html>
- <body>
- <p>
- Utility classes related to the Groovy Shell (aka. <tt>groovysh</tt>).
- </p>
- </body>
-</html>
-
diff --git a/subprojects/groovy-nio/build.gradle b/subprojects/groovy-nio/build.gradle
index d12c4f9..d164141 100644
--- a/subprojects/groovy-nio/build.gradle
+++ b/subprojects/groovy-nio/build.gradle
@@ -10,12 +10,18 @@
* 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
+ * software distributed under the License is distributed oHistoryRecordGetTextToRunTestsn 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.
*/
+repositories {
+ maven {
+ url 'https://oss.sonatype.org/content/repositories/snapshots'
+ }
+}
+
dependencies {
compile rootProject
testCompile project(':groovy-test')
diff --git a/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/AbstractFullBinding.java b/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/AbstractFullBinding.java
deleted file mode 100644
index b534116..0000000
--- a/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/AbstractFullBinding.java
+++ /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.codehaus.groovy.binding;
-
-import groovy.lang.Closure;
-
-/**
- * @since Groovy 1.1
- */
-@Deprecated
-public abstract class AbstractFullBinding implements FullBinding {
-
- protected SourceBinding sourceBinding;
- protected TargetBinding targetBinding;
- protected Closure validator;
- protected Closure converter;
- protected Closure reverseConverter;
-
- private void fireBinding() {
- if ((sourceBinding == null) || (targetBinding == null)) {
- // should we throw invalid binding exception? or fail quietly?
- return;
- }
- Object result = sourceBinding.getSourceValue();
- if (getValidator() != null) {
- Object validation = getValidator().call(result);
- if ((validation == null)
- || ((validation instanceof Boolean) && !(Boolean) validation))
- {
- // should we throw a validation failed exception? or fail quietly?
- return;
- }
- }
- if (getConverter() != null) {
- result = getConverter().call(result);
- }
- targetBinding.updateTargetValue(result);
- }
-
- public void update() {
- fireBinding();
- }
-
- private void fireReverseBinding() {
- if (!(sourceBinding instanceof TargetBinding) || !(targetBinding instanceof SourceBinding)) {
- throw new RuntimeException("Binding Instance is not reversable");
- }
- Object result = ((SourceBinding)targetBinding).getSourceValue();
- if (getReverseConverter() != null) {
- result = getReverseConverter().call(result);
- }
- ((TargetBinding)sourceBinding).updateTargetValue(result);
- }
-
- public void reverseUpdate() {
- fireReverseBinding();
- }
-
- public SourceBinding getSourceBinding() {
- return sourceBinding;
- }
-
- public void setSourceBinding(SourceBinding sourceBinding) {
- this.sourceBinding = sourceBinding;
- }
-
- public TargetBinding getTargetBinding() {
- return targetBinding;
- }
-
- public void setTargetBinding(TargetBinding targetBinding) {
- this.targetBinding = targetBinding;
- }
-
- public Closure getValidator() {
- return validator;
- }
-
- public void setValidator(Closure validator) {
- this.validator = validator;
- }
-
- public Closure getConverter() {
- return converter;
- }
-
- public void setConverter(Closure converter) {
- this.converter = converter;
- }
-
- public Closure getReverseConverter() {
- return reverseConverter;
- }
-
- public void setReverseConverter(Closure reverseConverter) {
- this.reverseConverter = reverseConverter;
- }
-}
diff --git a/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/AggregateBinding.java b/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/AggregateBinding.java
deleted file mode 100644
index 3b85d53..0000000
--- a/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/AggregateBinding.java
+++ /dev/null
@@ -1,83 +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.codehaus.groovy.binding;
-
-import java.util.LinkedHashSet;
-import java.util.Set;
-
-/**
- * An aggregation of multiple bindings
- *
- * @since Groovy 1.6
- */
-@Deprecated
-public class AggregateBinding implements BindingUpdatable {
-
- protected boolean bound;
-
- // use linked hash set so order is preserved
- protected Set<BindingUpdatable> bindings = new LinkedHashSet<BindingUpdatable>();
-
- public void addBinding(BindingUpdatable binding) {
- if (binding == null || bindings.contains(binding)) return;
- if (bound) binding.bind(); // bind is idempotent, so no state checking
- bindings.add(binding);
- }
-
- public void removeBinding(BindingUpdatable binding) {
- bindings.remove(binding);
- }
-
- public void bind() {
- if (!bound) {
- bound = true;
- for (BindingUpdatable binding : bindings) {
- binding.bind();
- }
- }
- }
-
- public void unbind() {
- if (bound) {
- for (BindingUpdatable binding : bindings) {
- binding.unbind();
- }
- bound = false;
- }
- }
-
- public void rebind() {
- if (bound) {
- unbind();
- bind();
- }
- }
-
- public void update() {
- for (BindingUpdatable binding : bindings) {
- binding.update();
- }
- }
-
- public void reverseUpdate() {
- for (BindingUpdatable binding : bindings) {
- binding.reverseUpdate();
- }
- }
-}
diff --git a/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/BindPath.java b/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/BindPath.java
deleted file mode 100644
index f0cdbe8..0000000
--- a/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/BindPath.java
+++ /dev/null
@@ -1,238 +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.codehaus.groovy.binding;
-
-import groovy.lang.MetaClass;
-import groovy.lang.MissingPropertyException;
-import groovy.lang.Reference;
-import org.codehaus.groovy.runtime.InvokerHelper;
-
-import java.beans.PropertyChangeListener;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-
-/**
- * The bind path object. This class represents one "step" in the bind path.
- */
-@SuppressWarnings({"unchecked"}) // all are of type Object, so generics are useless
-@Deprecated
-public class BindPath {
-
- /**
- * The local lookup for synthetic properties, like JTextField#text
- */
- Map<String, TriggerBinding> localSynthetics;
-
- /**
- * The object we think we are bound to
- */
- Object currentObject;
-
- /**
- * The property we are interested in
- */
- String propertyName;
-
- PropertyChangeListener localListener;
- PropertyChangeListener globalListener;
- BindingUpdatable syntheticFullBinding;
-
- /**
- * The steps further down the path from us
- */
- BindPath[] children;
-
- /**
- * Called when we detect a change somewhere down our path.
- * First, check to see if our object is changing. If so remove our old listener
- * Next, update the reference object the children have and recurse
- * Finally, add listeners if we have a different object
- *
- * @param listener This listener to attach.
- * @param newObject The object we should read our property off of.
- * @param updateSet The list of objects we have added listeners to
- */
- public synchronized void updatePath(PropertyChangeListener listener, Object newObject, Set updateSet) {
- if (currentObject != newObject) {
- removeListeners();
- }
- if ((children != null) && (children.length > 0)) {
- try {
- Object newValue = null;
- if (newObject != null) {
- updateSet.add(newObject);
- newValue = extractNewValue(newObject);
- }
- for (BindPath child : children) {
- child.updatePath(listener, newValue, updateSet);
- }
- } catch (Exception e) {
- //LOGME
- // do we ignore it, or fail?
- }
- }
- if (currentObject != newObject) {
- addListeners(listener, newObject, updateSet);
- }
- }
-
- /**
- * Adds all the listeners to the objects in the bind path.
- * This assumes that we are not added as listeners to any of them, hence
- * it is not idempotent.
- *
- * @param listener This listener to attach.
- * @param newObject The object we should read our property off of.
- * @param updateSet The list of objects we have added listeners to
- */
- public void addAllListeners(PropertyChangeListener listener, Object newObject, Set updateSet) {
- addListeners(listener, newObject, updateSet);
- if ((children != null) && (children.length > 0)) {
- try {
- Object newValue = null;
- if (newObject != null) {
- updateSet.add(newObject);
- newValue = extractNewValue(newObject);
- }
- for (BindPath child : children) {
- child.addAllListeners(listener, newValue, updateSet);
- }
- } catch (Exception e) {
- e.printStackTrace(System.out);
- //LOGME
- // do we ignore it, or fail?
- }
- }
- }
-
- private Object extractNewValue(Object newObject) {
- Object newValue;
- try {
- newValue = InvokerHelper.getProperty(newObject, propertyName);
-
- } catch (MissingPropertyException mpe) {
- //todo we should flag this when the path is created that this is a field not a prop...
- // try direct method...
- try {
- newValue = InvokerHelper.getAttribute(newObject, propertyName);
- if (newValue instanceof Reference) {
- newValue = ((Reference) newValue).get();
- }
- } catch (Exception e) {
- //LOGME?
- newValue = null;
- }
- }
- return newValue;
- }
-
- static final Class[] NAME_PARAMS = {String.class, PropertyChangeListener.class};
- static final Class[] GLOBAL_PARAMS = {PropertyChangeListener.class};
-
- /**
- * Add listeners to a specific object. Updates the bould flags and update set
- *
- * @param listener This listener to attach.
- * @param newObject The object we should read our property off of.
- * @param updateSet The list of objects we have added listeners to
- */
- public void addListeners(PropertyChangeListener listener, Object newObject, Set updateSet) {
- removeListeners();
- if (newObject != null) {
- // check for local synthetics
- TriggerBinding syntheticTrigger = getSyntheticTriggerBinding(newObject);
- MetaClass mc = InvokerHelper.getMetaClass(newObject);
- if (syntheticTrigger != null) {
- PropertyBinding psb = new PropertyBinding(newObject, propertyName);
- PropertyChangeProxyTargetBinding proxytb = new PropertyChangeProxyTargetBinding(newObject, propertyName, listener);
-
- syntheticFullBinding = syntheticTrigger.createBinding(psb, proxytb);
- syntheticFullBinding.bind();
- updateSet.add(newObject);
- } else if (!mc.respondsTo(newObject, "addPropertyChangeListener", NAME_PARAMS).isEmpty()) {
- InvokerHelper.invokeMethod(newObject, "addPropertyChangeListener", new Object[] {propertyName, listener});
- localListener = listener;
- updateSet.add(newObject);
- } else if (!mc.respondsTo(newObject, "addPropertyChangeListener", GLOBAL_PARAMS).isEmpty()) {
- InvokerHelper.invokeMethod(newObject, "addPropertyChangeListener", listener);
- globalListener = listener;
- updateSet.add(newObject);
- }
- }
- currentObject = newObject;
- }
-
- /**
- * Remove listeners, believing that our bould flags are accurate and it removes
- * only as declared.
- */
- public void removeListeners() {
- if (globalListener != null) {
- try {
- InvokerHelper.invokeMethod(currentObject, "removePropertyChangeListener", globalListener);
- } catch (Exception e) {
- //LOGME ignore the failure
- }
- globalListener = null;
- }
- if (localListener != null) {
- try {
- InvokerHelper.invokeMethod(currentObject, "removePropertyChangeListener", new Object[] {propertyName, localListener});
- } catch (Exception e) {
- //LOGME ignore the failure
- }
- localListener = null;
- }
- if (syntheticFullBinding != null) {
- syntheticFullBinding.unbind();
- }
- }
-
- public synchronized void updateLocalSyntheticProperties(Map<String, TriggerBinding> synthetics) {
- localSynthetics = null;
- String endName = "#" + propertyName;
- for (Map.Entry<String, TriggerBinding> syntheticEntry : synthetics.entrySet()) {
- if (syntheticEntry.getKey().endsWith(endName)) {
- if (localSynthetics == null) {
- localSynthetics = new TreeMap();
- }
- localSynthetics.put(syntheticEntry.getKey(), syntheticEntry.getValue());
- }
- }
- }
-
- public TriggerBinding getSyntheticTriggerBinding(Object newObject) {
- if (localSynthetics == null) {
- return null;
- }
- Class currentClass = newObject.getClass();
- while (currentClass != null) {
- // should we check interfaces as well? if so at what level?
- TriggerBinding trigger =
- localSynthetics.get(currentClass.getName() + "#" + propertyName);
- if (trigger != null) {
- return trigger;
- }
- currentClass = currentClass.getSuperclass();
- }
- return null;
- }
-
-}
diff --git a/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/BindingProxy.java b/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/BindingProxy.java
deleted file mode 100644
index 0815018..0000000
--- a/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/BindingProxy.java
+++ /dev/null
@@ -1,160 +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.codehaus.groovy.binding;
-
-import groovy.lang.GroovyObjectSupport;
-import groovy.lang.ReadOnlyPropertyException;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * This class returns half bound {@link org.codehaus.groovy.binding.FullBinding}s on the source half to the model
- * object for every property reference (and I do mean every, valid or not, queried before or not). These returned
- * half bindings are stored strongly in a list when generated.
- *
- * Changing the model will keep all existing bindings but change the source on all of the bininfs
- *
- * Formerly Known as Model Binding.
- *
- * @since Groovy 1.5
- */
-@Deprecated
-public class BindingProxy extends GroovyObjectSupport implements BindingUpdatable {
-
- Object model;
- boolean bound;
-
- final Map<String, PropertyBinding> propertyBindings = new HashMap<String, PropertyBinding>();
- final List<FullBinding> generatedBindings = new ArrayList<FullBinding>();
-
- public BindingProxy(Object model) {
- this.model = model;
- }
-
- public Object getModel() {
- return model;
- }
-
- public synchronized void setModel(Object model) {
- // should we use a finer grained lock than this?
-
- boolean bindAgain = bound;
- this.model = model;
-
- unbind();
- for (PropertyBinding propertyBinding : propertyBindings.values()) {
- (propertyBinding).setBean(model);
- }
-
- if (bindAgain) {
- bind();
- update();
- }
- }
-
- public Object getProperty(String property) {
- PropertyBinding pb;
- synchronized (propertyBindings) {
- // should we verify the property is valid?
- pb = propertyBindings.get(property);
- if (pb == null) {
- pb = new ModelBindingPropertyBinding(model, property);
- propertyBindings.put(property, pb);
- }
- }
- FullBinding fb = pb.createBinding(pb, null);
- if (bound) {
- fb.bind();
- }
- return fb;
- }
-
- public void setProperty(String property, Object value) {
- throw new ReadOnlyPropertyException(property, model.getClass());
- }
-
- public void bind() {
- synchronized (generatedBindings) {
- if (!bound) {
- bound = true;
- for (FullBinding generatedBinding : generatedBindings) {
- (generatedBinding).bind();
- // should we trap exceptions and do an each?
- }
- }
- }
- }
-
- public void unbind() {
- synchronized (generatedBindings) {
- if (bound) {
- bound = false;
- for (FullBinding generatedBinding : generatedBindings) {
- (generatedBinding).unbind();
- // should we trap exceptions and do an each?
- }
- }
- }
- }
-
- public void rebind() {
- synchronized (generatedBindings) {
- if (bound) {
- for (FullBinding generatedBinding : generatedBindings) {
- (generatedBinding).rebind();
- // should we trap exceptions and do an each?
- }
- }
- }
- }
-
- public void update() {
- synchronized (generatedBindings) {
- for (FullBinding generatedBinding : generatedBindings) {
- (generatedBinding).update();
- // should we trap exceptions and do an each?
- }
- }
- }
-
- public void reverseUpdate() {
- synchronized (generatedBindings) {
- for (FullBinding generatedBinding : generatedBindings) {
- (generatedBinding).reverseUpdate();
- // should we trap exceptions and do an each?
- }
- }
- }
-
- class ModelBindingPropertyBinding extends PropertyBinding {
- public ModelBindingPropertyBinding(Object bean, String propertyName) {
- super(bean, propertyName);
- }
-
- public FullBinding createBinding(SourceBinding source, TargetBinding target) {
- FullBinding fb = super.createBinding(source, target);
- generatedBindings.add(fb);
- return fb;
- }
- }
-
-}
diff --git a/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/BindingUpdatable.java b/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/BindingUpdatable.java
deleted file mode 100644
index d822567..0000000
--- a/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/BindingUpdatable.java
+++ /dev/null
@@ -1,58 +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.codehaus.groovy.binding;
-
-/**
- * @since Groovy 1.1
- */
-@Deprecated
-public interface BindingUpdatable {
-
- /**
- * Causes automatic updating of bound values to be turned on.
- * This is idempotent between calls to unbind and rebind; i.e. multiple calls
- * to bind will have only the effect of the first call.
- */
- void bind();
-
- /**
- * Causes automatic updating of bound values to be turned off.
- * This is idempotent between calls to bind and rebind; i.e. multiple calls
- * to unbind will have only the effect of the first call.
- */
- void unbind();
-
- /**
- * Causes the current bindings to be reset.
- * If the binding is not bound, it is a no-op.
- * If the binding is bound, it will be turned off, then turned on against current values.
- */
- void rebind();
-
- /**
- * Causes the values to be propagated from the source to the target
- */
- void update();
-
- /**
- * If supported, Causes the values to be propagated from the target to the source,
- * If not supported, an exception may be thrown
- */
- void reverseUpdate();
-}
diff --git a/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/ClosureSourceBinding.java b/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/ClosureSourceBinding.java
deleted file mode 100644
index c9f6e2b..0000000
--- a/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/ClosureSourceBinding.java
+++ /dev/null
@@ -1,62 +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.codehaus.groovy.binding;
-
-import groovy.lang.Closure;
-
-/**
- * @since Groovy 1.1
- */
-@Deprecated
-public class ClosureSourceBinding implements SourceBinding {
-
- private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];
-
- Closure closure;
- Object[] arguments;
-
- public ClosureSourceBinding(Closure closure) {
- this(closure, EMPTY_OBJECT_ARRAY);
- }
-
- public ClosureSourceBinding(Closure closure, Object[] arguments) { //TODO in Groovy 2.0 use varargs?
- this.closure = closure;
- this.arguments = arguments;
- }
-
- public Closure getClosure() {
- return closure;
- }
-
- public void setClosure(Closure closure) {
- this.closure = closure;
- }
-
- public Object getSourceValue() {
- return closure.call(arguments);
- }
-
- public void setClosureArguments(Object[] arguments) {
- this.arguments = arguments;
- }
-
- public void setClosureArgument(Object argument) {
- this.arguments = new Object[] {argument};
- }
-}
diff --git a/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/ClosureTriggerBinding.java b/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/ClosureTriggerBinding.java
deleted file mode 100644
index 11a85f2..0000000
--- a/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/ClosureTriggerBinding.java
+++ /dev/null
@@ -1,171 +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.codehaus.groovy.binding;
-
-import groovy.lang.Closure;
-import groovy.lang.GroovyObjectSupport;
-import groovy.lang.Reference;
-import org.codehaus.groovy.reflection.ReflectionUtils;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Field;
-import java.security.PrivilegedAction;
-import java.util.ArrayList;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-
-@Deprecated
-public class ClosureTriggerBinding implements TriggerBinding, SourceBinding {
- private static final BindPath[] EMPTY_BINDPATH_ARRAY = new BindPath[0];
- Map<String, TriggerBinding> syntheticBindings;
- Closure closure;
-
- public ClosureTriggerBinding(Map<String, TriggerBinding> syntheticBindings) {
- this.syntheticBindings = syntheticBindings;
- }
-
- public Closure getClosure() {
- return closure;
- }
-
- public void setClosure(Closure closure) {
- this.closure = closure;
- }
-
- private BindPath createBindPath(String propertyName, BindPathSnooper snooper) {
- BindPath bp = new BindPath();
- bp.propertyName = propertyName;
- bp.updateLocalSyntheticProperties(syntheticBindings);
- List<BindPath> childPaths = new ArrayList<BindPath>();
- for (Map.Entry<String, BindPathSnooper> entry : snooper.fields.entrySet()) {
- childPaths.add(createBindPath(entry.getKey(), entry.getValue()));
- }
- bp.children = childPaths.toArray(EMPTY_BINDPATH_ARRAY);
- return bp;
- }
-
- public FullBinding createBinding(SourceBinding source, TargetBinding target) {
- if (source != this) {
- throw new RuntimeException("Source binding must the Trigger Binding as well");
- }
- final BindPathSnooper delegate = new BindPathSnooper();
- try {
- // create our own local copy of the closure
- final Class closureClass = closure.getClass();
-
- // do in privileged block since we may be looking at private stuff
- Closure closureLocalCopy = java.security.AccessController.doPrivileged(new PrivilegedAction<Closure>() {
- public Closure run() {
- // assume closures have only 1 constructor, of the form (Object, Reference*)
- Constructor constructor = closureClass.getConstructors()[0];
- int paramCount = constructor.getParameterTypes().length;
- Object[] args = new Object[paramCount];
- args[0] = delegate;
- for (int i = 1; i < paramCount; i++) {
- args[i] = new Reference(new BindPathSnooper());
- }
- try {
- boolean acc = constructor.isAccessible();
- ReflectionUtils.trySetAccessible(constructor);
- Closure localCopy = (Closure) constructor.newInstance(args);
- if (!acc) { constructor.setAccessible(false); }
- localCopy.setResolveStrategy(Closure.DELEGATE_ONLY);
- for (Field f:closureClass.getDeclaredFields()) {
- acc = f.isAccessible();
- ReflectionUtils.trySetAccessible(f);
- if (f.getType() == Reference.class) {
- delegate.fields.put(f.getName(),
- (BindPathSnooper) ((Reference) f.get(localCopy)).get());
- }
- if (!acc) { f.setAccessible(false); }
- }
- return localCopy;
- } catch (Exception e) {
- throw new RuntimeException("Error snooping closure", e);
- }
- }
- });
- try {
- closureLocalCopy.call();
- } catch (DeadEndException e) {
- // we want this exception exposed.
- throw e;
- } catch (Exception e) {
- //LOGME
- // ignore it, likely failing because we are faking out properties
- // such as a call to Math.min(int, BindPathSnooper)
- }
- } catch (Exception e) {
- e.printStackTrace(System.out);
- throw new RuntimeException("A closure expression binding could not be created because of " + e.getClass().getName() + ":\n\t" + e.getMessage());
- }
- List<BindPath> rootPaths = new ArrayList<BindPath>();
- for (Map.Entry<String, BindPathSnooper> entry : delegate.fields.entrySet()) {
- BindPath bp =createBindPath(entry.getKey(), entry.getValue());
- bp.currentObject = closure;
- rootPaths.add(bp);
- }
- PropertyPathFullBinding fb = new PropertyPathFullBinding();
- fb.setSourceBinding(new ClosureSourceBinding(closure));
- fb.setTargetBinding(target);
- fb.bindPaths = rootPaths.toArray(EMPTY_BINDPATH_ARRAY);
- return fb;
- }
-
- public Object getSourceValue() {
- return closure.call();
- }
-}
-
-@Deprecated
-class DeadEndException extends RuntimeException {
- DeadEndException(String message) { super(message); }
-}
-
-@Deprecated
-class DeadEndObject {
- public Object getProperty(String property) {
- throw new DeadEndException("Cannot bind to a property on the return value of a method call");
- }
- public Object invokeMethod(String name, Object args) {
- return this;
- }
-}
-
-@Deprecated
-class BindPathSnooper extends GroovyObjectSupport {
- static final DeadEndObject DEAD_END = new DeadEndObject();
-
- Map<String, BindPathSnooper> fields = new LinkedHashMap<String, BindPathSnooper>();
-
- public Object getProperty(String property) {
- if (fields.containsKey(property)) {
- return fields.get(property);
- } else {
- BindPathSnooper snooper = new BindPathSnooper();
- fields.put(property, snooper);
- return snooper;
- }
- }
-
- public Object invokeMethod(String name, Object args) {
- return DEAD_END;
- }
-}
diff --git a/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/EventTriggerBinding.java b/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/EventTriggerBinding.java
deleted file mode 100644
index b7b503d..0000000
--- a/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/EventTriggerBinding.java
+++ /dev/null
@@ -1,88 +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.codehaus.groovy.binding;
-
-import groovy.lang.Closure;
-import org.codehaus.groovy.runtime.InvokerHelper;
-
-/**
- * @since Groovy 1.1
- */
-@Deprecated
-public class EventTriggerBinding implements TriggerBinding {
-
- Object triggerBean;
- String eventName;
-
- public EventTriggerBinding(Object triggerBean, String eventName) {
- this.triggerBean = triggerBean;
- this.eventName = eventName;
- }
-
- public FullBinding createBinding(final SourceBinding sourceBinding, final TargetBinding targetBinding) {
- return new EventTriggerFullBinding(sourceBinding, targetBinding);
- }
-
- public Object getTriggerBean() {
- return triggerBean;
- }
-
- public void setTriggerBean(Object triggerBean) {
- this.triggerBean = triggerBean;
- }
-
- public String getEventName() {
- return eventName;
- }
-
- public void setEventName(String eventName) {
- this.eventName = eventName;
- }
-
- private class EventTriggerFullBinding extends AbstractFullBinding {
-
- Closure handler;
-
- public EventTriggerFullBinding(final SourceBinding sourceBinding, TargetBinding targetBinding) {
- setSourceBinding(sourceBinding);
- setTargetBinding(targetBinding);
- handler = new Closure(triggerBean) {
- public Object call(Object... params) {
- if (sourceBinding instanceof ClosureSourceBinding) {
- ((ClosureSourceBinding)sourceBinding).setClosureArguments(params);
- }
- update();
- return null;
- }
- };
- }
-
- public void bind() {
- InvokerHelper.setProperty(triggerBean, eventName, handler);
- }
-
- public void unbind() {
- throw new UnsupportedOperationException();
- }
-
- public void rebind() {
- throw new UnsupportedOperationException();
- }
- }
-}
\ No newline at end of file
diff --git a/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/FullBinding.java b/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/FullBinding.java
deleted file mode 100644
index ebe7d2c..0000000
--- a/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/FullBinding.java
+++ /dev/null
@@ -1,48 +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.codehaus.groovy.binding;
-
-import groovy.lang.Closure;
-
-/**
- * @since Groovy 1.1
- */
-@Deprecated
-public interface FullBinding extends BindingUpdatable {
-
- SourceBinding getSourceBinding();
-
- TargetBinding getTargetBinding();
-
- void setSourceBinding(SourceBinding source);
-
- void setTargetBinding(TargetBinding target);
-
- void setValidator(Closure validator);
-
- Closure getValidator();
-
- void setConverter(Closure converter);
-
- Closure getConverter();
-
- void setReverseConverter(Closure reverseConverter);
-
- Closure getReverseConverter();
-}
diff --git a/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/MutualPropertyBinding.java b/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/MutualPropertyBinding.java
deleted file mode 100644
index 41f3b63..0000000
--- a/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/MutualPropertyBinding.java
+++ /dev/null
@@ -1,199 +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.codehaus.groovy.binding;
-
-import groovy.lang.Closure;
-
-/**
- * @since Groovy 1.6
- */
-
-@Deprecated
-public class MutualPropertyBinding implements FullBinding {
-
- boolean bound;
-
- PropertyBinding sourceBinding;
- PropertyBinding targetBinding;
- Closure validator;
- Closure converter;
- Closure reverseConverter;
-
- Closure triggerFactory;
-
- TriggerBinding forwardTriggerBinding;
- FullBinding forwardBinding;
- TriggerBinding reverseTriggerBinding;
- FullBinding reverseBinding;
-
- MutualPropertyBinding(TriggerBinding forwardTrigger, PropertyBinding source, PropertyBinding target, Closure triggerFactory) {
- // order matters here!
- this.triggerFactory = triggerFactory;
- sourceBinding = source;
- forwardTriggerBinding = forwardTrigger;
- setTargetBinding(target);
- rebuildBindings();
- }
-
- public SourceBinding getSourceBinding() {
- return sourceBinding;
- }
-
- public TargetBinding getTargetBinding() {
- return targetBinding;
- }
-
- public void setSourceBinding(SourceBinding sourceBinding) {
- try {
- if (sourceBinding == null) {
- forwardTriggerBinding = null;
- } else {
- forwardTriggerBinding = (TriggerBinding) triggerFactory.call(sourceBinding);
- }
- this.sourceBinding = (PropertyBinding) sourceBinding;
- } catch (RuntimeException re) {
- throw new UnsupportedOperationException("Mutual Bindings may only change source bindings to other PropertyBindings");
- }
- rebuildBindings();
- }
-
- public void setTargetBinding(TargetBinding targetBinding) {
- try {
- if (targetBinding == null) {
- reverseTriggerBinding = null;
- } else {
- reverseTriggerBinding = (TriggerBinding) triggerFactory.call(targetBinding);
- }
- this.targetBinding = (PropertyBinding) targetBinding;
- } catch (RuntimeException re) {
- throw new UnsupportedOperationException("Mutual Bindings may only change target bindings to other PropertyBindings");
- }
- rebuildBindings();
- }
-
- public void setValidator(Closure validator) {
- this.validator = validator;
- rebuildBindings();
- }
-
- public Closure getValidator() {
- return validator;
- }
-
- public void setConverter(Closure converter) {
- this.converter = converter;
- rebuildBindings();
- }
-
- public Closure getConverter() {
- return converter;
- }
-
- public void setReverseConverter(Closure reverseConverter) {
- this.reverseConverter = reverseConverter;
- rebuildBindings();
- }
-
- public Closure getReverseConverter() {
- return reverseConverter;
- }
-
- protected void rebuildBindings() {
- // tear stuff down, even if we are half built
- if (bound) {
- if (forwardBinding != null) {
- forwardBinding.unbind();
- }
- if (reverseBinding != null) {
- reverseBinding.unbind();
- }
- }
-
- // check for all pieces, if we don't have the triad quit silently
- if (forwardTriggerBinding == null || sourceBinding == null || reverseTriggerBinding == null || targetBinding == null) {
- return;
- }
-
- // build the pieces
- forwardBinding = forwardTriggerBinding.createBinding(sourceBinding, targetBinding);
- reverseBinding = reverseTriggerBinding.createBinding(targetBinding, sourceBinding);
-
- // add the ancillary pieces
- if ((converter != null) && (reverseConverter != null)) {
- forwardBinding.setConverter(converter);
- reverseBinding.setConverter(reverseConverter);
- }
- if (validator != null) {
- forwardBinding.setValidator(validator);
- }
-
- // rebind if we were bound
- if (bound) {
- forwardBinding.bind();
- reverseBinding.bind();
- }
-
- }
-
- public void bind() {
- if (!bound) {
- bound = true;
- //guard checks
-
- // both converter and reverseConverter must be set or not
- if ((converter == null) != (reverseConverter == null)) {
- throw new RuntimeException("Both converter or reverseConverter must be set or unset to bind. Only "
- + ((converter != null) ? "converter": "reverseConverter") + " is set.");
- }
- // don't bind if we are half set up, quietly stop
- if (forwardBinding == null || reverseBinding == null) {
- // don't worry about the bind state, if the binding
- // is completed we will bind in rebuild
- return;
- }
-
- forwardBinding.bind();
- reverseBinding.bind();
- }
- }
-
- public void unbind() {
- if (bound) {
- forwardBinding.unbind();
- reverseBinding.unbind();
- bound = false;
- }
- }
-
- public void rebind() {
- if (bound) {
- unbind();
- bind();
- }
- }
-
- public void update() {
- forwardBinding.update();
- }
-
- public void reverseUpdate() {
- reverseBinding.update();
- }
-}
-
diff --git a/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/PropertyBinding.java b/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/PropertyBinding.java
deleted file mode 100644
index dbc9a89..0000000
--- a/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/binding/PropertyBinding.java
+++ /dev/null
@@ -1,368 +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.codehaus.groovy.binding;
-
-import groovy.beans.DefaultPropertyAccessor;
-import groovy.beans.PropertyAccessor;
-import groovy.lang.GroovyRuntimeException;
-import groovy.lang.MissingMethodException;
-import org.codehaus.groovy.runtime.InvokerHelper;
-import org.codehaus.groovy.runtime.InvokerInvocationException;
-import org.codehaus.groovy.runtime.ResourceGroovyMethods;
-import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation;
-
-import javax.swing.*;
-import java.awt.*;
-import java.beans.PropertyChangeEvent;
-import java.beans.PropertyChangeListener;
-import java.beans.PropertyVetoException;
-import java.io.IOException;
-import java.lang.reflect.InvocationTargetException;
-import java.net.URL;
-import java.util.Enumeration;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-
-/**
- * @since Groovy 1.1
- */
-@Deprecated
-public class PropertyBinding implements SourceBinding, TargetBinding, TriggerBinding {
... 1934 lines suppressed ...