/
GroovyMain.java
655 lines (579 loc) · 23.2 KB
/
GroovyMain.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
/**
* 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 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 org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GroovyInternalPosixParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
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 java.io.*;
import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
/**
* A Command line to execute groovy.
*
* @author Jeremy Rayner
* @author Yuri Schimke
* @author Roshan Dawrani
* @version $Revision$
*/
public class GroovyMain {
// arguments to the script
private List args;
// is this a file on disk
private boolean isScriptFile;
// filename or content of script
private String script;
// process args as input files
private boolean processFiles;
// edit input files in place
private boolean editFiles;
// automatically output the result of each script
private boolean autoOutput;
// automatically split each line using the splitpattern
private boolean autoSplit;
// The pattern used to split the current line
private String splitPattern = " ";
// process sockets
private boolean processSockets;
// port to listen on when processing sockets
private int port;
// backup input files with extension
private String backupExtension;
// do you want full stack traces in script exceptions?
private boolean debug = false;
// Compiler configuration, used to set the encodings of the scripts/classes
private CompilerConfiguration conf = new CompilerConfiguration(System.getProperties());
/**
* Main CLI interface.
*
* @param args all command line args.
*/
public static void main(String args[]) {
processArgs(args, System.out);
}
// package-level visibility for testing purposes (just usage/errors at this stage)
// TODO: should we have an 'err' printstream too for ParseException?
static void processArgs(String[] args, final PrintStream out) {
Options options = buildOptions();
try {
CommandLine cmd = parseCommandLine(options, args);
if (cmd.hasOption('h')) {
printHelp(out, options);
} else if (cmd.hasOption('v')) {
String version = GroovySystem.getVersion();
out.println("Groovy Version: " + version + " JVM: " + System.getProperty("java.version") +
" Vendor: " + System.getProperty("java.vm.vendor") + " OS: " + System.getProperty("os.name"));
} else {
// If we fail, then exit with an error so scripting frameworks can catch it
// TODO: pass printstream(s) down through process
if (!process(cmd)) {
System.exit(1);
}
}
} catch (ParseException pe) {
out.println("error: " + pe.getMessage());
printHelp(out, options);
} catch (IOException ioe) {
out.println("error: " + ioe.getMessage());
}
}
private static void printHelp(PrintStream out, Options options) {
HelpFormatter formatter = new HelpFormatter();
PrintWriter pw = new PrintWriter(out);
formatter.printHelp(
pw,
80,
"groovy [options] [args]",
"options:",
options,
2,
4,
null, // footer
false);
pw.flush();
}
/**
* Parse the command line.
*
* @param options the options parser.
* @param args the command line args.
* @return parsed command line.
* @throws ParseException if there was a problem.
*/
private static CommandLine parseCommandLine(Options options, String[] args) throws ParseException {
CommandLineParser parser = new GroovyInternalPosixParser();
return parser.parse(options, args, true);
}
/**
* Build the options parser. Has to be synchronized because of the way Options are constructed.
*
* @return an options parser.
*/
@SuppressWarnings("static-access")
private static synchronized Options buildOptions() {
Options options = new Options();
options.addOption(OptionBuilder.hasArg().withArgName("path").withDescription("Specify where to find the class files - must be first argument").create("classpath"));
options.addOption(OptionBuilder.withLongOpt("classpath").hasArg().withArgName("path").withDescription("Aliases for '-classpath'").create("cp"));
options.addOption(
OptionBuilder.withLongOpt("define").
withDescription("define a system property").
hasArg(true).
withArgName("name=value").
create('D'));
options.addOption(
OptionBuilder.withLongOpt("disableopt").
withDescription("disables one or all optimization elements. " +
"optlist can be a comma separated list with the elements: " +
"all (disables all optimizations), " +
"int (disable any int based optimizations)").
hasArg(true).
withArgName("optlist").
create());
options.addOption(
OptionBuilder.hasArg(false)
.withDescription("usage information")
.withLongOpt("help")
.create('h'));
options.addOption(
OptionBuilder.hasArg(false)
.withDescription("debug mode will print out full stack traces")
.withLongOpt("debug")
.create('d'));
options.addOption(
OptionBuilder.hasArg(false)
.withDescription("display the Groovy and JVM versions")
.withLongOpt("version")
.create('v'));
options.addOption(
OptionBuilder.withArgName("charset")
.hasArg()
.withDescription("specify the encoding of the files")
.withLongOpt("encoding")
.create('c'));
options.addOption(
OptionBuilder.withArgName("script")
.hasArg()
.withDescription("specify a command line script")
.create('e'));
options.addOption(
OptionBuilder.withArgName("extension")
.hasOptionalArg()
.withDescription("modify files in place; create backup if extension is given (e.g. \'.bak\')")
.create('i'));
options.addOption(
OptionBuilder.hasArg(false)
.withDescription("process files line by line using implicit 'line' variable")
.create('n'));
options.addOption(
OptionBuilder.hasArg(false)
.withDescription("process files line by line and print result (see also -n)")
.create('p'));
options.addOption(
OptionBuilder.withArgName("port")
.hasOptionalArg()
.withDescription("listen on a port and process inbound lines (default: 1960)")
.create('l'));
options.addOption(
OptionBuilder.withArgName("splitPattern")
.hasOptionalArg()
.withDescription("split lines using splitPattern (default '\\s') using implicit 'split' variable")
.withLongOpt("autosplit")
.create('a'));
options.addOption(
OptionBuilder.withLongOpt("indy")
.withDescription("enables compilation using invokedynamic")
.create());
options.addOption(
OptionBuilder.withLongOpt("configscript")
.hasArg().withDescription("A script for tweaking the configuration options")
.create());
options.addOption(
OptionBuilder.withLongOpt("basescript")
.hasArg().withArgName("class").withDescription("Base class name for scripts (must derive from Script)")
.create('b'));
return options;
}
private static void setSystemPropertyFrom(final String nameValue) {
if(nameValue==null) throw new IllegalArgumentException("argument should not be null");
String name, value;
int i = nameValue.indexOf("=");
if (i == -1) {
name = nameValue;
value = Boolean.TRUE.toString();
}
else {
name = nameValue.substring(0, i);
value = nameValue.substring(i + 1, nameValue.length());
}
name = name.trim();
System.setProperty(name, value);
}
/**
* Process the users request.
*
* @param line the parsed command line.
* @throws ParseException if invalid options are chosen
*/
private static boolean process(CommandLine line) throws ParseException, IOException {
List args = line.getArgList();
if (line.hasOption('D')) {
String[] values = line.getOptionValues('D');
for (int i=0; i<values.length; i++) {
setSystemPropertyFrom(values[i]);
}
}
GroovyMain main = new GroovyMain();
// add the ability to parse scripts with a specified encoding
main.conf.setSourceEncoding(line.getOptionValue('c',main.conf.getSourceEncoding()));
main.isScriptFile = !line.hasOption('e');
main.debug = line.hasOption('d');
main.conf.setDebug(main.debug);
main.processFiles = line.hasOption('p') || line.hasOption('n');
main.autoOutput = line.hasOption('p');
main.editFiles = line.hasOption('i');
if (main.editFiles) {
main.backupExtension = line.getOptionValue('i');
}
main.autoSplit = line.hasOption('a');
String sp = line.getOptionValue('a');
if (sp != null)
main.splitPattern = sp;
if (main.isScriptFile) {
if (args.isEmpty())
throw new ParseException("neither -e or filename provided");
main.script = (String) args.remove(0);
if (main.script.endsWith(".java"))
throw new ParseException("error: cannot compile file with .java extension: " + main.script);
} else {
main.script = line.getOptionValue('e');
}
main.processSockets = line.hasOption('l');
if (main.processSockets) {
String p = line.getOptionValue('l', "1960"); // default port to listen to
main.port = Integer.parseInt(p);
}
// we use "," as default, because then split will create
// an empty array if no option is set
String disabled = line.getOptionValue("disableopt", ",");
String[] deopts = disabled.split(",");
for (String deopt_i : deopts) {
main.conf.getOptimizationOptions().put(deopt_i,false);
}
if (line.hasOption("indy")) {
CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", true);
main.conf.getOptimizationOptions().put("indy", true);
}
if (line.hasOption("basescript")) {
main.conf.setScriptBaseClass(line.getOptionValue("basescript"));
}
if (line.hasOption("configscript")) {
String path = line.getOptionValue("configscript");
File groovyConfigurator = new File(path);
Binding binding = new Binding();
binding.setVariable("configuration", main.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);
shell.evaluate(groovyConfigurator);
}
main.args = args;
return main.run();
}
/**
* Run the script.
*/
private boolean run() {
try {
if (processSockets) {
processSockets();
} else if (processFiles) {
processFiles();
} else {
processOnce();
}
return true;
} catch (CompilationFailedException e) {
System.err.println(e);
return false;
} catch (Throwable e) {
if (e instanceof InvokerInvocationException) {
InvokerInvocationException iie = (InvokerInvocationException) e;
e = iie.getCause();
}
System.err.println("Caught: " + e);
if (!debug) {
StackTraceUtils.deepSanitize(e);
}
e.printStackTrace();
return false;
}
}
/**
* Process Sockets.
*/
private void processSockets() throws CompilationFailedException, IOException, URISyntaxException {
GroovyShell groovy = new GroovyShell(conf);
new GroovySocketServer(groovy, getScriptSource(isScriptFile, script), autoOutput, port);
}
/**
* Get the text of the Groovy script at the given location.
* If the location is a file path and it does not exist as given,
* then {@link GroovyMain#huntForTheScriptFile(String)} is called to try
* with some Groovy extensions appended.
*
* This method is not used to process scripts and is retained for backward
* compatibility. If you want to modify how GroovyMain processes scripts
* then use {@link GroovyMain#getScriptSource(boolean, String)}.
*
* @param uriOrFilename
* @return the text content at the location
* @throws IOException
* @deprecated
*/
public String getText(String uriOrFilename) throws IOException {
if (uriPattern.matcher(uriOrFilename).matches()) {
try {
return ResourceGroovyMethods.getText(new URL(uriOrFilename));
} catch (Exception e) {
throw new GroovyRuntimeException("Unable to get script from URL: ", e);
}
}
return ResourceGroovyMethods.getText(huntForTheScriptFile(uriOrFilename));
}
/**
* Get a new GroovyCodeSource for a script which may be given as a location
* (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
* @return a new GroovyCodeSource for the given script
* @throws IOException
* @throws URISyntaxException
* @since 2.3.0
*/
protected GroovyCodeSource getScriptSource(boolean isScriptFile, String script) throws IOException, URISyntaxException {
//check the script is currently valid before starting a server against the script
if (isScriptFile) {
if (uriPattern.matcher(script).matches()) {
return new GroovyCodeSource(new URI(script));
} else {
return new GroovyCodeSource(huntForTheScriptFile(script));
}
} else {
return new GroovyCodeSource(script, "script_from_command_line", GroovyShell.DEFAULT_CODE_BASE);
}
}
// TODO remove duplication with GroovyClassLoader#uriPattern
// RFC2396
// scheme = alpha *( alpha | digit | "+" | "-" | "." )
// match URIs but not Windows filenames, e.g.: http://cnn.com but not C:\xxx\file.ext
private static final Pattern uriPattern = Pattern.compile("\\p{Alpha}[-+.\\p{Alnum}]*:[^\\\\]*");
/**
* Search for the script file, doesn't bother if it is named precisely.
*
* Tries in this order:
* - actual supplied name
* - name.groovy
* - name.gvy
* - name.gy
* - name.gsh
*
* @since 2.3.0
*/
public static File searchForGroovyScriptFile(String input) {
String scriptFileName = input.trim();
File scriptFile = new File(scriptFileName);
// TODO: Shouldn't these extensions be kept elsewhere? What about CompilerConfiguration?
// This method probably shouldn't be in GroovyMain either.
String[] standardExtensions = {".groovy",".gvy",".gy",".gsh"};
int i = 0;
while (i < standardExtensions.length && !scriptFile.exists()) {
scriptFile = new File(scriptFileName + standardExtensions[i]);
i++;
}
// if we still haven't found the file, point back to the originally specified filename
if (!scriptFile.exists()) {
scriptFile = new File(scriptFileName);
}
return scriptFile;
}
/**
* Hunt for the script file by calling searchForGroovyScriptFile(String).
*
* @see GroovyMain#searchForGroovyScriptFile(String)
*/
public File huntForTheScriptFile(String input) {
return GroovyMain.searchForGroovyScriptFile(input);
}
// GROOVY-6771
private static void setupContextClassLoader(GroovyShell shell) {
final Thread current = Thread.currentThread();
class DoSetContext implements PrivilegedAction {
ClassLoader classLoader;
public DoSetContext(ClassLoader loader) {
classLoader = loader;
}
public Object run() {
current.setContextClassLoader(classLoader);
return null;
}
}
AccessController.doPrivileged(new DoSetContext(shell.getClassLoader()));
}
/**
* Process the input files.
*/
private void processFiles() throws CompilationFailedException, IOException, URISyntaxException {
GroovyShell groovy = new GroovyShell(conf);
setupContextClassLoader(groovy);
Script s = groovy.parse(getScriptSource(isScriptFile, script));
if (args.isEmpty()) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(System.out);
try {
processReader(s, reader, writer);
} finally {
reader.close();
writer.close();
}
} else {
Iterator i = args.iterator();
while (i.hasNext()) {
String filename = (String) i.next();
//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);
processFile(s, file);
}
}
}
/**
* Process a single input file.
*
* @param s the script to execute.
* @param file the input file.
*/
private void processFile(Script s, File file) throws IOException {
if (!file.exists())
throw new FileNotFoundException(file.getName());
if (!editFiles) {
BufferedReader reader = new BufferedReader(new FileReader(file));
try {
PrintWriter writer = new PrintWriter(System.out);
processReader(s, reader, writer);
writer.flush();
} finally {
reader.close();
}
} else {
File backup;
if (backupExtension == null) {
backup = File.createTempFile("groovy_", ".tmp");
backup.deleteOnExit();
} else {
backup = new File(file.getPath() + backupExtension);
}
backup.delete();
if (!file.renameTo(backup))
throw new IOException("unable to rename " + file + " to " + backup);
BufferedReader reader = new BufferedReader(new FileReader(backup));
try {
PrintWriter writer = new PrintWriter(new FileWriter(file));
try {
processReader(s, reader, writer);
} finally {
writer.close();
}
} finally {
reader.close();
}
}
}
/**
* Process a script against a single input file.
*
* @param s script to execute.
* @param reader input file.
* @param pw output sink.
*/
private void processReader(Script s, BufferedReader reader, PrintWriter pw) throws IOException {
String line;
String lineCountName = "count";
s.setProperty(lineCountName, BigInteger.ZERO);
String autoSplitName = "split";
s.setProperty("out", pw);
try {
InvokerHelper.invokeMethod(s, "begin", null);
} catch (MissingMethodException mme) {
// ignore the missing method exception
// as it means no begin() method is present
}
while ((line = reader.readLine()) != null) {
s.setProperty("line", line);
s.setProperty(lineCountName, ((BigInteger)s.getProperty(lineCountName)).add(BigInteger.ONE));
if(autoSplit) {
s.setProperty(autoSplitName, line.split(splitPattern));
}
Object o = s.run();
if (autoOutput && o != null) {
pw.println(o);
}
}
try {
InvokerHelper.invokeMethod(s, "end", null);
} catch (MissingMethodException mme) {
// ignore the missing method exception
// as it means no end() method is present
}
}
/**
* Process the standard, single script with args.
*/
private void processOnce() throws CompilationFailedException, IOException, URISyntaxException {
GroovyShell groovy = new GroovyShell(conf);
setupContextClassLoader(groovy);
groovy.run(getScriptSource(isScriptFile, script), args);
}
}