You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by su...@apache.org on 2019/08/21 10:07:44 UTC
[groovy] 01/04: trivial refactoring: GroovyMain & FileSystemCompiler
This is an automated email from the ASF dual-hosted git repository.
sunlan pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit e21543c5b42a81d789b8e70829c9f8e153ee33de
Author: Davyd Kohut <ex...@gmail.com>
AuthorDate: Thu Aug 15 13:26:09 2019 +0300
trivial refactoring: GroovyMain & FileSystemCompiler
---
src/main/java/groovy/ui/GroovyMain.java | 82 +++++++-------
.../codehaus/groovy/tools/FileSystemCompiler.java | 125 +++++++++++----------
2 files changed, 105 insertions(+), 102 deletions(-)
diff --git a/src/main/java/groovy/ui/GroovyMain.java b/src/main/java/groovy/ui/GroovyMain.java
index 314c640..4f43a6a 100644
--- a/src/main/java/groovy/ui/GroovyMain.java
+++ b/src/main/java/groovy/ui/GroovyMain.java
@@ -18,38 +18,15 @@
*/
package groovy.ui;
-import groovy.lang.Binding;
-import groovy.lang.GroovyCodeSource;
-import groovy.lang.GroovyRuntimeException;
-import groovy.lang.GroovyShell;
-import groovy.lang.GroovySystem;
-import groovy.lang.MissingMethodException;
-import groovy.lang.Script;
+import groovy.lang.*;
import org.codehaus.groovy.control.CompilationFailedException;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.customizers.ImportCustomizer;
-import org.codehaus.groovy.runtime.InvokerHelper;
-import org.codehaus.groovy.runtime.InvokerInvocationException;
-import org.codehaus.groovy.runtime.ResourceGroovyMethods;
-import org.codehaus.groovy.runtime.StackTraceUtils;
-import org.codehaus.groovy.runtime.StringGroovyMethods;
+import org.codehaus.groovy.runtime.*;
import picocli.CommandLine;
-import picocli.CommandLine.Command;
-import picocli.CommandLine.Help;
-import picocli.CommandLine.IVersionProvider;
-import picocli.CommandLine.Option;
-import picocli.CommandLine.ParameterException;
-import picocli.CommandLine.Unmatched;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.PrintStream;
-import java.io.PrintWriter;
+import picocli.CommandLine.*;
+
+import java.io.*;
import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
@@ -57,7 +34,6 @@ import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
-import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -69,7 +45,7 @@ import java.util.regex.Pattern;
public class GroovyMain {
// arguments to the script
- private List args;
+ private List<String> args;
// is this a file on disk
private boolean isScriptFile;
@@ -112,7 +88,7 @@ public class GroovyMain {
*
* @param args all command line args.
*/
- public static void main(String args[]) {
+ public static void main(String[] args) {
processArgs(args, System.out, System.err);
}
@@ -121,15 +97,23 @@ public class GroovyMain {
static void processArgs(String[] args, final PrintStream out) {
processArgs(args, out, out);
}
+
// package-level visibility for testing purposes (just usage/errors at this stage)
static void processArgs(String[] args, final PrintStream out, final PrintStream err) {
GroovyCommand groovyCommand = new GroovyCommand();
- CommandLine parser = new CommandLine(groovyCommand).setUnmatchedArgumentsAllowed(true).setStopAtUnmatched(true);
+
+ CommandLine parser = new CommandLine(groovyCommand)
+ .setOut(new PrintWriter(out))
+ .setErr(new PrintWriter(err))
+ .setUnmatchedArgumentsAllowed(true)
+ .setStopAtUnmatched(true);
+
try {
- List<CommandLine> result = parser.parse(args);
- if (CommandLine.printHelpIfRequested(result, out, err, Help.Ansi.AUTO)) {
+ ParseResult result = parser.parseArgs(args);
+
+ if (CommandLine.executeHelpRequest(result) != null)
return;
- }
+
// TODO: pass printstream(s) down through process
if (!groovyCommand.process(parser)) {
// If we fail, then exit with an error so scripting frameworks can catch it.
@@ -224,7 +208,7 @@ public class GroovyMain {
private boolean versionRequested;
@Unmatched
- List<String> arguments = new ArrayList<String>();
+ List<String> arguments = new ArrayList<>();
/**
* Process the users request.
@@ -236,7 +220,8 @@ public class GroovyMain {
for (Map.Entry<String, String> entry : systemProperties.entrySet()) {
System.setProperty(entry.getKey(), entry.getValue());
}
- GroovyMain main = new GroovyMain();
+
+ final GroovyMain main = new GroovyMain();
// add the ability to parse scripts with a specified encoding
main.conf.setSourceEncoding(encoding);
@@ -292,31 +277,42 @@ public class GroovyMain {
processConfigScripts(getConfigScripts(), main.conf);
main.args = arguments;
+
return main.run();
}
private List<String> getConfigScripts() {
List<String> scripts = new ArrayList<String>();
+
if (this.configscript != null) {
scripts.add(this.configscript);
}
+
String configScripts = System.getProperty("groovy.starter.configscripts", null);
+
if (configScripts != null && !configScripts.isEmpty()) {
- scripts.addAll(StringGroovyMethods.tokenize((CharSequence) configScripts, ','));
+ scripts.addAll(StringGroovyMethods.tokenize(configScripts, ','));
}
+
return scripts;
}
}
public static void processConfigScripts(List<String> scripts, CompilerConfiguration conf) throws IOException {
if (scripts.isEmpty()) return;
+
Binding binding = new Binding();
binding.setVariable("configuration", conf);
+
CompilerConfiguration configuratorConfig = new CompilerConfiguration();
ImportCustomizer customizer = new ImportCustomizer();
+
customizer.addStaticStars("org.codehaus.groovy.control.customizers.builder.CompilerCustomizationBuilder");
+
configuratorConfig.addCompilationCustomizers(customizer);
+
GroovyShell shell = new GroovyShell(binding, configuratorConfig);
+
for (String script : scripts) {
shell.evaluate(new File(script));
}
@@ -393,7 +389,7 @@ public class GroovyMain {
* (isScript is true) or as text (isScript is false).
*
* @param isScriptFile indicates whether the script parameter is a location or content
- * @param script the location or context of the script
+ * @param script the location or context of the script
* @return a new GroovyCodeSource for the given script
* @throws IOException
* @throws URISyntaxException
@@ -407,7 +403,7 @@ public class GroovyMain {
if (!scriptFile.exists() && URI_PATTERN.matcher(script).matches()) {
return new GroovyCodeSource(new URI(script));
}
- return new GroovyCodeSource( scriptFile );
+ return new GroovyCodeSource(scriptFile);
}
return new GroovyCodeSource(script, "script_from_command_line", GroovyShell.DEFAULT_CODE_BASE);
}
@@ -459,7 +455,7 @@ public class GroovyMain {
// GROOVY-6771
private static void setupContextClassLoader(GroovyShell shell) {
final Thread current = Thread.currentThread();
- class DoSetContext implements PrivilegedAction {
+ class DoSetContext implements PrivilegedAction<Object> {
ClassLoader classLoader;
public DoSetContext(ClassLoader loader) {
@@ -491,9 +487,7 @@ public class GroovyMain {
writer.flush();
}
} else {
- Iterator i = args.iterator();
- while (i.hasNext()) {
- String filename = (String) i.next();
+ for (String filename : args) {
//TODO: These are the arguments for -p and -i. Why are we searching using Groovy script extensions?
// Where is this documented?
File file = huntForTheScriptFile(filename);
diff --git a/src/main/java/org/codehaus/groovy/tools/FileSystemCompiler.java b/src/main/java/org/codehaus/groovy/tools/FileSystemCompiler.java
index a1f26c5..829172a 100644
--- a/src/main/java/org/codehaus/groovy/tools/FileSystemCompiler.java
+++ b/src/main/java/org/codehaus/groovy/tools/FileSystemCompiler.java
@@ -27,17 +27,9 @@ import org.codehaus.groovy.runtime.DefaultGroovyStaticMethods;
import org.codehaus.groovy.runtime.StringGroovyMethods;
import org.codehaus.groovy.tools.javac.JavaAwareCompilationUnit;
import picocli.CommandLine;
-import picocli.CommandLine.Command;
-import picocli.CommandLine.IVersionProvider;
-import picocli.CommandLine.Option;
-import picocli.CommandLine.Parameters;
-import picocli.CommandLine.ParseResult;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.PrintWriter;
+import picocli.CommandLine.*;
+
+import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
@@ -51,6 +43,8 @@ import static groovy.ui.GroovyMain.processConfigScripts;
* Command-line compiler (aka. <tt>groovyc</tt>).
*/
public class FileSystemCompiler {
+
+ private static boolean displayStackTraceOnError = false;
private final CompilationUnit unit;
public FileSystemCompiler(CompilerConfiguration configuration) throws ConfigurationException {
@@ -67,37 +61,39 @@ public class FileSystemCompiler {
}
}
- public void compile(String[] paths) throws Exception {
- unit.addSources(paths);
- unit.compile();
- }
-
- public void compile(File[] files) throws Exception {
- unit.addSources(files);
- unit.compile();
- }
-
- /** Prints the usage help message for {@link CompilationOptions} to stderr.
+ /**
+ * Prints the usage help message for {@link CompilationOptions} to stderr.
+ *
* @see #displayHelp(PrintWriter)
- * @since 2.5 */
+ * @since 2.5
+ */
public static void displayHelp() {
displayHelp(new PrintWriter(System.err, true));
}
- /** Prints the usage help message for the {@link CompilationOptions} to the specified PrintWriter.
- * @since 2.5 */
+ /**
+ * Prints the usage help message for the {@link CompilationOptions} to the specified PrintWriter.
+ *
+ * @since 2.5
+ */
public static void displayHelp(final PrintWriter writer) {
configureParser(new CompilationOptions()).usage(writer);
}
- /** Prints version information to stderr.
- * @see #displayVersion(PrintWriter) */
+ /**
+ * Prints version information to stderr.
+ *
+ * @see #displayVersion(PrintWriter)
+ */
public static void displayVersion() {
displayVersion(new PrintWriter(System.err, true));
}
- /** Prints version information to the specified PrintWriter.
- * @since 2.5 */
+ /**
+ * Prints version information to the specified PrintWriter.
+ *
+ * @since 2.5
+ */
public static void displayVersion(final PrintWriter writer) {
for (String line : new VersionProvider().getVersion()) {
writer.println(line);
@@ -125,8 +121,6 @@ public class FileSystemCompiler {
return checkFiles(filenames) == 0;
}
- private static boolean displayStackTraceOnError = false;
-
/**
* Same as main(args) except that exceptions are thrown out instead of causing
* the VM to exit.
@@ -216,12 +210,13 @@ public class FileSystemCompiler {
// if there are any joint compilation options set stubDir if not set
try {
if ((configuration.getJointCompilationOptions() != null)
- && !configuration.getJointCompilationOptions().containsKey("stubDir"))
- {
+ && !configuration.getJointCompilationOptions().containsKey("stubDir")) {
tmpDir = DefaultGroovyStaticMethods.createTempDir(null, "groovy-generated-", "-java-source");
configuration.getJointCompilationOptions().put("stubDir", tmpDir);
}
+
FileSystemCompiler compiler = new FileSystemCompiler(configuration, unit);
+
if (lookupUnnamedFiles) {
for (String filename : filenames) {
File file = new File(filename);
@@ -231,11 +226,8 @@ public class FileSystemCompiler {
}
}
} else {
- compiler.unit.getClassLoader().setResourceLoader(new GroovyResourceLoader() {
- public URL loadGroovySource(String filename) throws MalformedURLException {
- return null;
- }
- });
+ compiler.unit.getClassLoader()
+ .setResourceLoader(filename -> null);
}
compiler.compile(filenames);
} finally {
@@ -251,12 +243,16 @@ public class FileSystemCompiler {
if (filenames == null) {
return new String[0];
}
- List<String> fileList = new ArrayList<String>(filenames.size());
+
+ List<String> fileList = new ArrayList<>(filenames.size());
+
boolean errors = false;
+
for (String filename : filenames) {
if (filename.startsWith("@")) {
String fn = filename.substring(1);
BufferedReader br = null;
+
try {
br = new BufferedReader(new FileReader(fn));
for (String file; (file = br.readLine()) != null; ) {
@@ -279,6 +275,7 @@ public class FileSystemCompiler {
fileList.add(filename);
}
}
+
if (errors) {
return null;
} else {
@@ -286,12 +283,38 @@ public class FileSystemCompiler {
}
}
+ public static void deleteRecursive(File file) {
+ if (!file.exists()) {
+ return;
+ }
+ if (file.isFile()) {
+ file.delete();
+ } else if (file.isDirectory()) {
+ File[] files = file.listFiles();
+ for (int i = 0; i < files.length; i++) {
+ deleteRecursive(files[i]);
+ }
+ file.delete();
+ }
+ }
+
+ public void compile(String[] paths) throws Exception {
+ unit.addSources(paths);
+ unit.compile();
+ }
+
+ public void compile(File[] files) throws Exception {
+ unit.addSources(files);
+ unit.compile();
+ }
+
/**
- * @since 2.5 */
+ * @since 2.5
+ */
static class VersionProvider implements IVersionProvider {
@Override
public String[] getVersion() {
- return new String[] {
+ return new String[]{
"Groovy compiler version " + GroovySystem.getVersion(),
"Copyright 2003-2019 The Apache Software Foundation. http://groovy-lang.org/",
"",
@@ -300,7 +323,8 @@ public class FileSystemCompiler {
}
/**
- * @since 2.5 */
+ * @since 2.5
+ */
@Command(name = "groovyc",
customSynopsis = "groovyc [options] <source-files>",
sortOptions = false,
@@ -359,7 +383,7 @@ public class FileSystemCompiler {
private boolean versionRequested;
@Parameters(description = "The groovy source files to compile, or @-files containing a list of source files to compile",
- paramLabel = "<source-files>")
+ paramLabel = "<source-files>")
private List<String> files;
public CompilerConfiguration toCompilerConfiguration() throws IOException {
@@ -433,19 +457,4 @@ public class FileSystemCompiler {
return flags.toArray(new String[0]);
}
}
-
- public static void deleteRecursive(File file) {
- if (!file.exists()) {
- return;
- }
- if (file.isFile()) {
- file.delete();
- } else if (file.isDirectory()) {
- File[] files = file.listFiles();
- for (int i = 0; i < files.length; i++) {
- deleteRecursive(files[i]);
- }
- file.delete();
- }
- }
}