You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tinkerpop.apache.org by sp...@apache.org on 2016/05/02 20:10:11 UTC

[02/10] incubator-tinkerpop git commit: Implemented more options for Gremlin Console startup.

Implemented more options for Gremlin Console startup.

Added -i for interactive mode and made -e execute in the Console rather than ScriptExecutor. Added switches to show/hide output and added a switch for "help". The existing method for -i still works as in "bin/gremlin.sh init.groovy"


Project: http://git-wip-us.apache.org/repos/asf/incubator-tinkerpop/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-tinkerpop/commit/b6853f05
Tree: http://git-wip-us.apache.org/repos/asf/incubator-tinkerpop/tree/b6853f05
Diff: http://git-wip-us.apache.org/repos/asf/incubator-tinkerpop/diff/b6853f05

Branch: refs/heads/master
Commit: b6853f052fc2efcf76f9d8e30bf95e6a22349fcc
Parents: b1493b5
Author: Stephen Mallette <sp...@genoprime.com>
Authored: Thu Apr 28 13:46:02 2016 -0400
Committer: Stephen Mallette <sp...@genoprime.com>
Committed: Thu Apr 28 13:46:02 2016 -0400

----------------------------------------------------------------------
 gremlin-console/pom.xml                         |   5 +
 gremlin-console/src/main/bin/gremlin.bat        |  41 +----
 gremlin-console/src/main/bin/gremlin.sh         |  19 +--
 .../tinkerpop/gremlin/console/Console.groovy    | 157 +++++++++++++++----
 4 files changed, 136 insertions(+), 86 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-tinkerpop/blob/b6853f05/gremlin-console/pom.xml
----------------------------------------------------------------------
diff --git a/gremlin-console/pom.xml b/gremlin-console/pom.xml
index 1620bc5..98cccb0 100644
--- a/gremlin-console/pom.xml
+++ b/gremlin-console/pom.xml
@@ -42,6 +42,11 @@ limitations under the License.
             <version>4.5.1</version>
         </dependency>
         <dependency>
+            <groupId>commons-cli</groupId>
+            <artifactId>commons-cli</artifactId>
+            <version>1.2</version>
+        </dependency>
+        <dependency>
             <groupId>org.apache.tinkerpop</groupId>
             <artifactId>gremlin-driver</artifactId>
             <version>${project.version}</version>

http://git-wip-us.apache.org/repos/asf/incubator-tinkerpop/blob/b6853f05/gremlin-console/src/main/bin/gremlin.bat
----------------------------------------------------------------------
diff --git a/gremlin-console/src/main/bin/gremlin.bat b/gremlin-console/src/main/bin/gremlin.bat
index 481d5ac..1d5e9bd 100644
--- a/gremlin-console/src/main/bin/gremlin.bat
+++ b/gremlin-console/src/main/bin/gremlin.bat
@@ -39,45 +39,6 @@ set JAVA_OPTIONS=-Xms32m -Xmx512m -Djline.terminal=none
 
 :: Launch the application
 
-if "%1" == "" goto console
-if "%1" == "-e" goto script
-if "%1" == "-v" goto version
-
-:console
-
 java %JAVA_OPTIONS% %JAVA_ARGS% -cp %LIBDIR%/*;%EXTDIR%; org.apache.tinkerpop.gremlin.console.Console %*
 
-set CLASSPATH=%OLD_CLASSPATH%
-goto :eof
-
-:script
-
-set strg=
-
-FOR %%X IN (%*) DO (
-CALL :concat %%X %1 %2
-)
-
-java %JAVA_OPTIONS% %JAVA_ARGS% -cp %LIBDIR%/*;%EXTDIR%; org.apache.tinkerpop.gremlin.groovy.jsr223.ScriptExecutor %strg%
-goto :eof
-
-:version
-java %JAVA_OPTIONS% %JAVA_ARGS% -cp %LIBDIR%/*;%EXTDIR%; org.apache.tinkerpop.gremlin.util.Gremlin
-
-goto :eof
-
-:concat
-
-if %1 == %2 goto skip
-
-SET strg=%strg% %1
-
-:concatsep
-
-if "%CP%" == "" (
-set CP=%LIBDIR%\%1
-)else (
-set CP=%CP%;%LIBDIR%\%1
-)
-
-:skip
+set CLASSPATH=%OLD_CLASSPATH%
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-tinkerpop/blob/b6853f05/gremlin-console/src/main/bin/gremlin.sh
----------------------------------------------------------------------
diff --git a/gremlin-console/src/main/bin/gremlin.sh b/gremlin-console/src/main/bin/gremlin.sh
index 84ba8179..6ff0254 100755
--- a/gremlin-console/src/main/bin/gremlin.sh
+++ b/gremlin-console/src/main/bin/gremlin.sh
@@ -76,15 +76,8 @@ if [ -z "${SCRIPT_DEBUG:-}" ]; then
 fi
 
 # Process options
-MAIN_CLASS=org.apache.tinkerpop.gremlin.console.Console
-while getopts "elv" opt; do
+while getopts ":l" opt; do
     case "$opt" in
-    e) MAIN_CLASS=org.apache.tinkerpop.gremlin.groovy.jsr223.ScriptExecutor
-       # For compatibility with behavior pre-Titan-0.5.0, stop
-       # processing gremlin.sh arguments as soon as the -e switch is
-       # seen; everything following -e becomes arguments to the
-       # ScriptExecutor main class
-       break;;
     l) eval GREMLIN_LOG_LEVEL=\$$OPTIND
        OPTIND="$(( $OPTIND + 1 ))"
        if [ "$GREMLIN_LOG_LEVEL" = "TRACE" -o \
@@ -92,22 +85,18 @@ while getopts "elv" opt; do
 	   SCRIPT_DEBUG=y
        fi
        ;;
-    v) MAIN_CLASS=org.apache.tinkerpop.gremlin.util.Gremlin
     esac
 done
 
-# Remove processed options from $@. Anything after -e is preserved by the break;; in the case
-shift $(( $OPTIND - 1 ))
-
 JAVA_OPTIONS="${JAVA_OPTIONS} -Dtinkerpop.ext=${USER_EXT_DIR:-${SYSTEM_EXT_DIR}} -Dlog4j.configuration=conf/log4j-console.properties -Dgremlin.log4j.level=$GREMLIN_LOG_LEVEL"
 JAVA_OPTIONS=$(awk -v RS=' ' '!/^$/ {if (!x[$0]++) print}' <<< "${JAVA_OPTIONS}" | grep -v '^$' | paste -sd ' ' -)
 
 if [ -n "$SCRIPT_DEBUG" ]; then
+    # in debug mode enable debugging of :install command
+    JAVA_OPTIONS="${JAVA_OPTIONS} -Divy.message.logger.level=4 -Dgroovy.grape.report.downloads=true"
     echo "CLASSPATH: $CLASSPATH"
     set -x
 fi
 
-# include the following in $JAVA_OPTIONS "-Divy.message.logger.level=4 -Dgroovy.grape.report.downloads=true" to debug :install
-
 # Start the JVM, execute the application, and return its exit code
-exec $JAVA $JAVA_OPTIONS $MAIN_CLASS "$@"
+exec $JAVA $JAVA_OPTIONS org.apache.tinkerpop.gremlin.console.Console "$@"

http://git-wip-us.apache.org/repos/asf/incubator-tinkerpop/blob/b6853f05/gremlin-console/src/main/groovy/org/apache/tinkerpop/gremlin/console/Console.groovy
----------------------------------------------------------------------
diff --git a/gremlin-console/src/main/groovy/org/apache/tinkerpop/gremlin/console/Console.groovy b/gremlin-console/src/main/groovy/org/apache/tinkerpop/gremlin/console/Console.groovy
index a13e785..a35c44a 100644
--- a/gremlin-console/src/main/groovy/org/apache/tinkerpop/gremlin/console/Console.groovy
+++ b/gremlin-console/src/main/groovy/org/apache/tinkerpop/gremlin/console/Console.groovy
@@ -18,11 +18,18 @@
  */
 package org.apache.tinkerpop.gremlin.console
 
-import org.apache.tinkerpop.gremlin.console.commands.*
+import org.apache.commons.cli.Option
+import org.apache.tinkerpop.gremlin.console.commands.GremlinSetCommand
+import org.apache.tinkerpop.gremlin.console.commands.InstallCommand
+import org.apache.tinkerpop.gremlin.console.commands.PluginCommand
+import org.apache.tinkerpop.gremlin.console.commands.RemoteCommand
+import org.apache.tinkerpop.gremlin.console.commands.SubmitCommand
+import org.apache.tinkerpop.gremlin.console.commands.UninstallCommand
 import org.apache.tinkerpop.gremlin.console.plugin.PluggedIn
 import org.apache.tinkerpop.gremlin.groovy.loaders.GremlinLoader
 import org.apache.tinkerpop.gremlin.groovy.plugin.GremlinPlugin
 import jline.console.history.FileHistory
+import org.apache.tinkerpop.gremlin.util.Gremlin
 import org.apache.tinkerpop.gremlin.util.iterator.ArrayIterator
 import org.codehaus.groovy.tools.shell.AnsiDetector
 import org.codehaus.groovy.tools.shell.ExitNotification
@@ -30,6 +37,7 @@ import org.codehaus.groovy.tools.shell.Groovysh
 import org.codehaus.groovy.tools.shell.IO
 import org.codehaus.groovy.tools.shell.InteractiveShellRunner
 import org.codehaus.groovy.tools.shell.commands.SetCommand
+import org.codehaus.groovy.tools.shell.util.HelpFormatter
 import org.codehaus.groovy.tools.shell.util.Preferences
 import org.fusesource.jansi.Ansi
 import org.fusesource.jansi.AnsiConsole
@@ -67,15 +75,28 @@ class Console {
 
     private Iterator tempIterator = Collections.emptyIterator()
 
-    private final IO io = new IO(System.in, System.out, System.err)
+    private final IO io
     private final Groovysh groovy
+    private final boolean interactive
 
-
+    /**
+     * @deprecated As of release 3.2.1-incubating.
+     */
+    @Deprecated
     public Console(final String initScriptFile) {
-        io.out.println()
-        io.out.println("         \\,,,/")
-        io.out.println("         (o o)")
-        io.out.println("-----oOOo-(3)-oOOo-----")
+        this(new IO(System.in, System.out, System.err), initScriptFile.size() != null ? [initScriptFile] : null, true)
+    }
+
+    public Console(final IO io, final List<String> scriptAndArgs, final boolean interactive) {
+        this.io = io
+        this.interactive = interactive
+
+        if (!io.quiet) {
+            io.out.println()
+            io.out.println("         \\,,,/")
+            io.out.println("         (o o)")
+            io.out.println("-----oOOo-(3)-oOOo-----")
+        }
 
         maxIteration = Integer.parseInt(Preferences.get(PREFERENCE_ITERATION_MAX, Integer.toString(DEFAULT_ITERATION_MAX)))
         Preferences.addChangeListener(new PreferenceChangeListener() {
@@ -128,7 +149,9 @@ class Console {
 
                 if (activePlugins.contains(plugin.class.name)) {
                     pluggedIn.activate()
-                    io.out.println("plugin activated: " + plugin.getName())
+
+                    if (!io.quiet)
+                        io.out.println("plugin activated: " + plugin.getName())
                 }
             }
         }
@@ -137,13 +160,14 @@ class Console {
         // deactivated, and are thus hanging about
         mediator.writePluginState()
 
-        // start iterating results to show as output
-        showShellEvaluationOutput(true)
-
         try {
             // if the init script contains :x command it will throw an ExitNotification so init script execution
             // needs to appear in the try/catch
-            if (initScriptFile != null) initializeShellWithScript(initScriptFile)
+            if (scriptAndArgs != null && scriptAndArgs.size() > 0) executeInShell(scriptAndArgs)
+
+            // start iterating results to show as output
+            showShellEvaluationOutput(true)
+
             runner.run()
         } catch (ExitNotification ignored) {
             // occurs on exit
@@ -167,7 +191,7 @@ class Console {
             groovy.setResultHook(handleResultShowNothing)
     }
 
-    private def handlePrompt = { STANDARD_INPUT_PROMPT }
+    private def handlePrompt = { interactive ? STANDARD_INPUT_PROMPT : "" }
 
     private def handleResultShowNothing = { args -> null }
 
@@ -252,21 +276,28 @@ class Console {
                     io.err.println(e)
                 }
 
-                io.err.print("Display stack trace? [yN] ")
-                io.err.flush()
-                String line = new BufferedReader(io.in).readLine()
-                if (null == line)
-                    line = ""
-                io.err.print(line.trim())
-                io.err.println()
-                if (line.trim().equals("y") || line.trim().equals("Y")) {
+                if (interactive) {
+                    io.err.print("Display stack trace? [yN] ")
+                    io.err.flush()
+                    String line = new BufferedReader(io.in).readLine()
+                    if (null == line)
+                        line = ""
+                    io.err.print(line.trim())
+                    io.err.println()
+                    if (line.trim().equals("y") || line.trim().equals("Y")) {
+                        e.printStackTrace(io.err)
+                    }
+                } else {
                     e.printStackTrace(io.err)
+                    System.exit(1)
                 }
             } catch (Exception ignored) {
                 io.err.println("An undefined error has occurred: " + err)
+                if (!interactive) System.exit(1)
             }
         } else {
             io.err.println("An undefined error has occurred: " + err.toString())
+            if (!interactive) System.exit(1)
         }
 
         return null
@@ -284,27 +315,91 @@ class Console {
         return STANDARD_RESULT_PROMPT
     }
 
-    private void initializeShellWithScript(final String initScriptFile) {
+    private void executeInShell(final List<String> scriptAndArgs) {
+        final String scriptFile = scriptAndArgs[0]
         try {
-            final File file = new File(initScriptFile)
-            file.eachLine { line ->
+            // check if this script comes with arguments. if so then set them up in an "args" bundle
+            if (scriptAndArgs.size() > 1) {
+                List<String> args = scriptAndArgs.subList(1, scriptAndArgs.size())
+                groovy.execute("args = [\"" + args.join('\",\"') + "\"]")
+            }
+
+            final File file = new File(scriptFile)
+            int lineNumber = 0
+            def lines = file.readLines()
+            for (String line : lines) {
                 try {
+                    lineNumber++
                     groovy.execute(line)
                 } catch (Exception ex) {
-                    io.err.println("Bad line in Gremlin initialization file at [$line] - ${ex.message}")
-                    System.exit(1)
+                    io.err.println("Invalid line in $scriptFile at [$lineNumber: $line] - ${ex.message}")
+                    if (interactive)
+                        break
+                    else
+                        System.exit(1)
                 }
             }
+
+            if (!interactive) System.exit(0)
         } catch (FileNotFoundException ignored) {
-            io.err.println("Gremlin initialization file not found at [$initScriptFile].")
-            System.exit(1)
+            io.err.println("Gremlin file not found at [$scriptFile].")
+            if (!interactive) System.exit(1)
         } catch (Exception ex) {
-            io.err.println("Error starting Gremlin with initialization script at [$initScriptFile] - ${ex.message}")
-            System.exit(1)
+            io.err.println("Failure processing Gremlin script [$scriptFile] - ${ex.message}")
+            if (!interactive) System.exit(1)
         }
     }
 
     public static void main(final String[] args) {
-        new Console(args.length == 1 ? args[0] : null)
+        // need to do some up front processing to try to support "bin/gremlin.sh init.groovy" until this deprecated
+        // feature can be removed. ultimately this should be removed when a breaking change can go in
+        IO io = new IO(System.in, System.out, System.err)
+        if (args.length == 1 && !args[0].startsWith("-"))
+            new Console(io, [args[0]], true)
+
+        final CliBuilder cli = new CliBuilder(usage: 'gremlin.sh [options] [...]', formatter: new HelpFormatter(), stopAtNonOption: false)
+
+        // note that the inclusion of -l is really a setting handled by gremlin.sh and not by Console class itself.
+        // it is mainly listed here for informational purposes when the user starts things up with -h
+        cli.with {
+            h(longOpt: 'help', "Display this help message")
+            v(longOpt: 'version', "Display the version")
+            l("Set the logging level of components that use standard logging output independent of the Console")
+            V(longOpt: 'verbose', "Enable verbose Console output")
+            Q(longOpt: 'quiet', "Suppress superfluous Console output")
+            D(longOpt: 'debug', "Enabled debug Console output")
+            i(longOpt: 'interactive', argName: "SCRIPT ARG1 ARG2 ...", args: Option.UNLIMITED_VALUES, valueSeparator: ' ' as char, "Execute the specified script and leave the console open on completion")
+            e(longOpt: 'execute', argName: "SCRIPT ARG1 ARG2 ...", args: Option.UNLIMITED_VALUES, valueSeparator: ' ' as char, "Execute the specified script (SCRIPT ARG1 ARG2 ...) and close the console on completion")
+        }
+        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) {
+            println("gremlin " + Gremlin.version())
+            System.exit(0)
+        }
+
+        if (options.V) io.verbosity = IO.Verbosity.VERBOSE
+        if (options.D) io.verbosity = IO.Verbosity.DEBUG
+        if (options.Q) io.verbosity = IO.Verbosity.QUIET
+
+        if (options.i && options.e) {
+            println("-i and -e options are mutually exclusive - provide one or the other")
+            System.exit(0)
+        }
+
+        List<String> scriptAndArgs = options.e ?
+                (options.es != null && options.es ? options.es : null) :
+                (options.is != null && options.is ? options.is : null)
+        new Console(io, scriptAndArgs, !options.e)
     }
 }