Debian Codegraph @

src/com/google/javascript/jscomp/CommandLineRunner.java

raw symbols ◀ ▶ SCIP
2 Debian patches touch this file
1 /*
2 * Copyright 2009 The Closure Compiler Authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.javascript.jscomp;
18
19 import com.google.common.base.Preconditions;
20 import com.google.common.collect.ImmutableList;
21 import com.google.common.collect.Lists;
22 import com.google.common.collect.Maps;
23 import com.google.common.collect.Sets;
24 import com.google.common.io.Files;
•25 import com.google.common.io.ByteStreams;
26
27 import org.kohsuke.args4j.Argument;
28 import org.kohsuke.args4j.CmdLineException;
29 import org.kohsuke.args4j.CmdLineParser;
30 import org.kohsuke.args4j.Option;
31 import org.kohsuke.args4j.OptionDef;
•32 import org.kohsuke.args4j.spi.FieldSetter;
33 import org.kohsuke.args4j.spi.OptionHandler;
34 import org.kohsuke.args4j.spi.Parameters;
35 import org.kohsuke.args4j.spi.Setter;
36 import org.kohsuke.args4j.spi.StringOptionHandler;
37
38 import java.io.BufferedInputStream;
39 import java.io.File;
40 import java.io.FileInputStream;
41 import java.io.IOException;
42 import java.io.InputStream;
43 import java.io.PrintStream;
•44 import java.lang.reflect.AnnotatedElement;
45 import java.nio.charset.Charset;
46 import java.util.List;
47 import java.util.Map;
48 import java.util.Set;
49 import java.util.logging.Level;
50 import java.util.regex.Matcher;
51 import java.util.regex.Pattern;
52 import java.util.zip.ZipEntry;
53 import java.util.zip.ZipInputStream;
54
55 /**
56 * CommandLineRunner translates flags into Java API calls on the Compiler.
57 *
58 * This class may be extended and used to create other Java classes
59 * that behave the same as running the Compiler from the command line. If you
60 * want to run the compiler in-process in Java, you should look at this class
61 * for hints on what API calls to make, but you should not use this class
62 * directly.
63 *
64 * Example:
65 * <pre>
66 * class MyCommandLineRunner extends CommandLineRunner {
67 * MyCommandLineRunner(String[] args) {
68 * super(args);
69 * }
70 *
71 * {@code @Override} protected CompilerOptions createOptions() {
72 * CompilerOptions options = super.createOptions();
73 * addMyCrazyCompilerPassThatOutputsAnExtraFile(options);
74 * return options;
75 * }
76 *
77 * public static void main(String[] args) {
78 * MyCommandLineRunner runner = new MyCommandLineRunner(args);
79 * if (runner.shouldRunCompiler()) {
80 * runner.run();
81 * } else {
82 * System.exit(-1);
83 * }
84 * }
85 * }
86 * </pre>
87 *
88 * This class is totally not thread-safe.
89 *
90 * @author [email protected] (Michael Bolin)
91 */
92 public class CommandLineRunner extends
93 AbstractCommandLineRunner<Compiler, CompilerOptions> {
94 private static class GuardLevel {
95 final String name;
96 final CheckLevel level;
97 GuardLevel(String name, CheckLevel level) {
98 this.name = name;
99 this.level = level;
100 }
101 }
102
103 // I don't really care about unchecked warnings in this class.
104 @SuppressWarnings("unchecked")
105 private static class Flags {
106 private static List<GuardLevel> guardLevels = Lists.newArrayList();
107
108 @Option(name = "--help",
109 handler = BooleanOptionHandler.class,
110 usage = "Displays this message")
111 private boolean display_help = false;
112
113 @Option(name = "--print_tree",
114 handler = BooleanOptionHandler.class,
115 usage = "Prints out the parse tree and exits")
116 private boolean print_tree = false;
117
118 @Option(name = "--print_ast",
119 handler = BooleanOptionHandler.class,
120 usage = "Prints a dot file describing the internal abstract syntax"
121 + " tree and exits")
122 private boolean print_ast = false;
123
124 @Option(name = "--print_pass_graph",
125 handler = BooleanOptionHandler.class,
126 usage = "Prints a dot file describing the passes that will get run"
127 + " and exits")
128 private boolean print_pass_graph = false;
129
130 // Turn on (very slow) extra sanity checks for use when modifying the
131 // compiler.
132 @Option(name = "--jscomp_dev_mode",
133 // hidden, no usage
134 aliases = {"--dev_mode"})
135 private CompilerOptions.DevMode jscomp_dev_mode =
136 CompilerOptions.DevMode.OFF;
137
138 @Option(name = "--logging_level",
139 usage = "The logging level (standard java.util.logging.Level"
140 + " values) for Compiler progress. Does not control errors or"
141 + " warnings for the JavaScript code under compilation")
142 private String logging_level = Level.WARNING.getName();
143
144 @Option(name = "--externs",
145 usage = "The file containing JavaScript externs. You may specify"
146 + " multiple")
147 private List<String> externs = Lists.newArrayList();
148
149 @Option(name = "--js",
150 usage = "The JavaScript filename. You may specify multiple")
151 private List<String> js = Lists.newArrayList();
152
153 @Option(name = "--js_output_file",
154 usage = "Primary output filename. If not specified, output is " +
155 "written to stdout")
156 private String js_output_file = "";
157
158 @Option(name = "--module",
159 usage = "A JavaScript module specification. The format is "
160 + "<name>:<num-js-files>[:[<dep>,...][:]]]. Module names must be "
161 + "unique. Each dep is the name of a module that this module "
162 + "depends on. Modules must be listed in dependency order, and JS "
163 + "source files must be listed in the corresponding order. Where "
164 + "--module flags occur in relation to --js flags is unimportant. "
165 + "Provide the value 'auto' to trigger module creation from CommonJS"
166 + "modules.")
167 private List<String> module = Lists.newArrayList();
168
169 @Option(name = "--variable_map_input_file",
170 usage = "File containing the serialized version of the variable "
171 + "renaming map produced by a previous compilation")
172 private String variable_map_input_file = "";
173
174 @Option(name = "--property_map_input_file",
175 usage = "File containing the serialized version of the property "
176 + "renaming map produced by a previous compilation")
177 private String property_map_input_file = "";
178
179 @Option(name = "--variable_map_output_file",
180 usage = "File where the serialized version of the variable "
181 + "renaming map produced should be saved")
182 private String variable_map_output_file = "";
183
184 @Option(name = "--create_name_map_files",
185 handler = BooleanOptionHandler.class,
186 usage = "If true, variable renaming and property renaming map "
187 + "files will be produced as {binary name}_vars_map.out and "
188 + "{binary name}_props_map.out. Note that this flag cannot be used "
189 + "in conjunction with either variable_map_output_file or "
190 + "property_map_output_file")
191 private boolean create_name_map_files = false;
192
193 @Option(name = "--property_map_output_file",
194 usage = "File where the serialized version of the property "
195 + "renaming map produced should be saved")
196 private String property_map_output_file = "";
197
198 @Option(name = "--third_party",
199 handler = BooleanOptionHandler.class,
200 usage = "Check source validity but do not enforce Closure style "
201 + "rules and conventions")
202 private boolean third_party = false;
203
204 @Option(name = "--summary_detail_level",
205 usage = "Controls how detailed the compilation summary is. Values:"
206 + " 0 (never print summary), 1 (print summary only if there are "
207 + "errors or warnings), 2 (print summary if the 'checkTypes' "
208 + "diagnostic group is enabled, see --jscomp_warning), "
209 + "3 (always print summary). The default level is 1")
210 private int summary_detail_level = 1;
211
212 @Option(name = "--output_wrapper",
213 usage = "Interpolate output into this string at the place denoted"
214 + " by the marker token %output%. Use marker token %output|jsstring%"
215 + " to do js string escaping on the output.")
216 private String output_wrapper = "";
217
218 @Option(name = "--module_wrapper",
219 usage = "An output wrapper for a JavaScript module (optional). "
220 + "The format is <name>:<wrapper>. The module name must correspond "
221 + "with a module specified using --module. The wrapper must "
222 + "contain %s as the code placeholder. The %basename% placeholder can "
223 + "also be used to substitute the base name of the module output file.")
224 private List<String> module_wrapper = Lists.newArrayList();
225
226 @Option(name = "--module_output_path_prefix",
227 usage = "Prefix for filenames of compiled JS modules. "
228 + "<module-name>.js will be appended to this prefix. Directories "
229 + "will be created as needed. Use with --module")
230 private String module_output_path_prefix = "./";
231
232 @Option(name = "--create_source_map",
233 usage = "If specified, a source map file mapping the generated " +
234 "source files back to the original source file will be " +
235 "output to the specified path. The %outname% placeholder will " +
236 "expand to the name of the output file that the source map " +
237 "corresponds to.")
238 private String create_source_map = "";
239
240 @Option(name = "--source_map_format",
241 usage = "The source map format to produce. " +
242 "Options: V1, V2, V3, DEFAULT. DEFAULT produces V2.")
243 private SourceMap.Format source_map_format = SourceMap.Format.DEFAULT;
244
245 // Used to define the flag, values are stored by the handler.
246 @SuppressWarnings("unused")
247 @Option(name = "--jscomp_error",
248 handler = WarningGuardErrorOptionHandler.class,
249 usage = "Make the named class of warnings an error. Options:" +
250 DiagnosticGroups.DIAGNOSTIC_GROUP_NAMES)
251 private List<String> jscomp_error = Lists.newArrayList();
252
253 // Used to define the flag, values are stored by the handler.
254 @SuppressWarnings("unused")
255 @Option(name = "--jscomp_warning",
256 handler = WarningGuardWarningOptionHandler.class,
257 usage = "Make the named class of warnings a normal warning. " +
258 "Options:" + DiagnosticGroups.DIAGNOSTIC_GROUP_NAMES)
259 private List<String> jscomp_warning = Lists.newArrayList();
260
261 // Used to define the flag, values are stored by the handler.
262 @SuppressWarnings("unused")
263 @Option(name = "--jscomp_off",
264 handler = WarningGuardOffOptionHandler.class,
265 usage = "Turn off the named class of warnings. Options:" +
266 DiagnosticGroups.DIAGNOSTIC_GROUP_NAMES)
267 private List<String> jscomp_off = Lists.newArrayList();
268
269 @Option(name = "--define",
270 aliases = {"--D", "-D"},
271 usage = "Override the value of a variable annotated @define. " +
272 "The format is <name>[=<val>], where <name> is the name of a @define " +
273 "variable and <val> is a boolean, number, or a single-quoted string " +
274 "that contains no single quotes. If [=<val>] is omitted, " +
275 "the variable is marked true")
276 private List<String> define = Lists.newArrayList();
277
278 @Option(name = "--charset",
279 usage = "Input and output charset for all files. By default, we " +
280 "accept UTF-8 as input and output US_ASCII")
281 private String charset = "";
282
283 @Option(name = "--compilation_level",
284 usage = "Specifies the compilation level to use. Options: " +
285 "WHITESPACE_ONLY, SIMPLE_OPTIMIZATIONS, ADVANCED_OPTIMIZATIONS")
286 private CompilationLevel compilation_level =
287 CompilationLevel.SIMPLE_OPTIMIZATIONS;
288
289 @Option(name = "--use_types_for_optimization",
290 usage = "Experimental: perform additional optimizations " +
291 "based on available information. Inaccurate type annotations " +
292 "may result in incorrect results.")
293 private boolean use_types_for_optimization = false;
294
295 @Option(name = "--warning_level",
296 usage = "Specifies the warning level to use. Options: " +
297 "QUIET, DEFAULT, VERBOSE")
298 private WarningLevel warning_level = WarningLevel.DEFAULT;
299
300 @Option(name = "--use_only_custom_externs",
301 handler = BooleanOptionHandler.class,
302 usage = "Specifies whether the default externs should be excluded")
303 private boolean use_only_custom_externs = false;
304
305 @Option(name = "--debug",
306 handler = BooleanOptionHandler.class,
307 usage = "Enable debugging options")
308 private boolean debug = false;
309
310 @Option(name = "--generate_exports",
311 handler = BooleanOptionHandler.class,
312 usage = "Generates export code for those marked with @export")
313 private boolean generate_exports = false;
314
315 @Option(name = "--formatting",
316 usage = "Specifies which formatting options, if any, should be "
317 + "applied to the output JS. Options: "
318 + "PRETTY_PRINT, PRINT_INPUT_DELIMITER, SINGLE_QUOTES")
319 private List<FormattingOption> formatting = Lists.newArrayList();
320
321 @Option(name = "--process_common_js_modules",
322 usage = "Process CommonJS modules to a concatenable form.")
323 private boolean process_common_js_modules = false;
324
325 @Option(name = "--common_js_module_path_prefix",
326 usage = "Path prefix to be removed from CommonJS module names.")
327 private String common_js_path_prefix =
328 ProcessCommonJSModules.DEFAULT_FILENAME_PREFIX;
329
330 @Option(name = "--common_js_entry_module",
331 usage = "Root of your common JS dependency hierarchy. "+
332 "Your main script.")
333 private String common_js_entry_module;
334
335 @Option(name = "--transform_amd_modules",
336 usage = "Transform AMD to CommonJS modules.")
337 private boolean transform_amd_modules = false;
338
339 @Option(name = "--process_closure_primitives",
340 handler = BooleanOptionHandler.class,
341 usage = "Processes built-ins from the Closure library, such as "
342 + "goog.require(), goog.provide(), and goog.exportSymbol()")
343 private boolean process_closure_primitives = true;
344
345 @Option(name = "--manage_closure_dependencies",
346 handler = BooleanOptionHandler.class,
347 usage = "Automatically sort dependencies so that a file that "
348 + "goog.provides symbol X will always come before a file that "
349 + "goog.requires symbol X. If an input provides symbols, and "
350 + "those symbols are never required, then that input will not "
351 + "be included in the compilation.")
352 private boolean manage_closure_dependencies = false;
353
354 @Option(name = "--only_closure_dependencies",
355 handler = BooleanOptionHandler.class,
356 usage = "Only include files in the transitive dependency of the "
357 + "entry points (specified by closure_entry_point). Files that do "
358 + "not provide dependencies will be removed. This supersedes"
359 + "manage_closure_dependencies")
360 private boolean only_closure_dependencies = false;
361
362 @Option(name = "--closure_entry_point",
363 usage = "Entry points to the program. Must be goog.provide'd "
364 + "symbols. Any goog.provide'd symbols that are not a transitive "
365 + "dependency of the entry points will be removed. Files without "
366 + "goog.provides, and their dependencies, will always be left in. "
367 + "If any entry points are specified, then the "
368 + "manage_closure_dependencies option will be set to true and "
369 + "all files will be sorted in dependency order.")
370 private List<String> closure_entry_point = Lists.newArrayList();
371
372 @Option(name = "--process_jquery_primitives",
373 handler = BooleanOptionHandler.class,
374 usage = "Processes built-ins from the Jquery library, such as "
375 + "jQuery.fn and jQuery.extend()")
376 private boolean process_jquery_primitives = false;
377
378 @Option(name = "--angular_pass",
379 handler = BooleanOptionHandler.class,
380 usage = "Generate $inject properties for AngularJS for functions "
381 + "annotated with @ngInject")
382 private boolean angular_pass = false;
383
384 @Option(name = "--output_manifest",
385 usage = "Prints out a list of all the files in the compilation. "
386 + "If --manage_closure_dependencies is on, this will not include "
387 + "files that got dropped because they were not required. "
388 + "The %outname% placeholder expands to the JS output file. "
389 + "If you're using modularization, using %outname% will create "
390 + "a manifest for each module.")
391 private String output_manifest = "";
392
393 @Option(name = "--output_module_dependencies",
394 usage = "Prints out a JSON file of dependencies between modules.")
395 private String output_module_dependencies = "";
396
397 @Option(name = "--accept_const_keyword",
398 usage = "Allows usage of const keyword.")
399 private boolean accept_const_keyword = false;
400
401 @Option(name = "--language_in",
402 usage = "Sets what language spec that input sources conform. "
403 + "Options: ECMASCRIPT3 (default), ECMASCRIPT5, ECMASCRIPT5_STRICT")
404 private String language_in = "ECMASCRIPT3";
405
406 @Option(name = "--version",
407 handler = BooleanOptionHandler.class,
408 usage = "Prints the compiler version to stderr.")
409 private boolean version = false;
410
411 @Option(name = "--translations_file",
412 usage = "Source of translated messages. Currently only supports XTB.")
413 private String translationsFile = "";
414
415 @Option(name = "--translations_project",
416 usage = "Scopes all translations to the specified project." +
417 "When specified, we will use different message ids so that messages " +
418 "in different projects can have different translations.")
419 private String translationsProject = null;
420
421 @Option(name = "--flagfile",
422 usage = "A file containing additional command-line options.")
423 private String flag_file = "";
424
425 @Option(name = "--warnings_whitelist_file",
426 usage = "A file containing warnings to suppress. Each line should be " +
427 "of the form\n" +
428 "<file-name>:<line-number>? <warning-description>")
429 private String warnings_whitelist_file = "";
430
431 @Option(name = "--extra_annotation_name",
432 usage = "A whitelist of tag names in JSDoc. You may specify multiple")
433 private List<String> extra_annotation_name = Lists.newArrayList();
434
435 @Argument
436 private List<String> arguments = Lists.newArrayList();
437
438 /**
439 * Users may specify JS inputs via the legacy {@code --js} option, as well
440 * as via additional arguments to the Closure Compiler. For example, it is
441 * convenient to leverage the additional arguments feature when using the
442 * Closure Compiler in combination with {@code find} and {@code xargs}:
443 * <pre>
444 * find MY_JS_SRC_DIR -name '*.js' \
445 * | xargs java -jar compiler.jar --manage_closure_dependencies
446 * </pre>
447 * The {@code find} command will produce a list of '*.js' source files in
448 * the {@code MY_JS_SRC_DIR} directory while {@code xargs} will convert them
449 * to a single, space-delimited set of arguments that are appended to the
450 * {@code java} command to run the Compiler.
451 * <p>
452 * Note that it is important to use the
453 * {@code --manage_closure_dependencies} option in this case because the
454 * order produced by {@code find} is unlikely to be sorted correctly with
455 * respect to {@code goog.provide()} and {@code goog.requires()}.
456 */
457 List<String> getJsFiles() {
458 List<String> allJsInputs = Lists.newArrayListWithCapacity(
459 js.size() + arguments.size());
460 allJsInputs.addAll(js);
461 allJsInputs.addAll(arguments);
462 return allJsInputs;
463 }
464
465 // Our own option parser to be backwards-compatible.
466 // It needs to be public because of the crazy reflection that args4j does.
467 public static class BooleanOptionHandler extends OptionHandler<Boolean> {
468 private static final Set<String> TRUES =
469 Sets.newHashSet("true", "on", "yes", "1");
470 private static final Set<String> FALSES =
471 Sets.newHashSet("false", "off", "no", "0");
472
473 public BooleanOptionHandler(
474 CmdLineParser parser, OptionDef option,
475 Setter<? super Boolean> setter) {
476 super(parser, option, setter);
477 }
478
479 @Override
480 public int parseArguments(Parameters params) throws CmdLineException {
481 String param = null;
482 try {
483 param = params.getParameter(0);
484 } catch (CmdLineException e) {}
485
486 if (param == null) {
487 setter.addValue(true);
488 return 0;
489 } else {
490 String lowerParam = param.toLowerCase();
491 if (TRUES.contains(lowerParam)) {
492 setter.addValue(true);
493 } else if (FALSES.contains(lowerParam)) {
494 setter.addValue(false);
495 } else {
496 setter.addValue(true);
497 return 0;
498 }
499 return 1;
500 }
501 }
502
503 @Override
504 public String getDefaultMetaVariable() {
505 return null;
506 }
507 }
508
509 // Our own parser for warning guards that preserves the original order
510 // of the flags.
511 public static class WarningGuardErrorOptionHandler
512 extends StringOptionHandler {
513 public WarningGuardErrorOptionHandler(
514 CmdLineParser parser, OptionDef option,
515 Setter<? super String> setter) {
516 super(parser, option, new WarningGuardSetter(setter, CheckLevel.ERROR));
517 }
518 }
519
520 public static class WarningGuardWarningOptionHandler
521 extends StringOptionHandler {
522 public WarningGuardWarningOptionHandler(
523 CmdLineParser parser, OptionDef option,
524 Setter<? super String> setter) {
525 super(parser, option,
526 new WarningGuardSetter(setter, CheckLevel.WARNING));
527 }
528 }
529
530 public static class WarningGuardOffOptionHandler
531 extends StringOptionHandler {
532 public WarningGuardOffOptionHandler(
533 CmdLineParser parser, OptionDef option,
534 Setter<? super String> setter) {
535 super(parser, option, new WarningGuardSetter(setter, CheckLevel.OFF));
536 }
537 }
538
539 private static class WarningGuardSetter implements Setter<String> {
540 private final Setter<? super String> proxy;
541 private final CheckLevel level;
542
543 private WarningGuardSetter(
544 Setter<? super String> proxy, CheckLevel level) {
545 this.proxy = proxy;
546 this.level = level;
547 }
548
549 @Override public boolean isMultiValued() {
550 return proxy.isMultiValued();
551 }
552
553 @Override public Class<String> getType() {
554 return (Class<String>) proxy.getType();
555 }
556
557 @Override public void addValue(String value) throws CmdLineException {
558 proxy.addValue(value);
559 guardLevels.add(new GuardLevel(value, level));
560 }
•561
562 @Override public FieldSetter asFieldSetter() {
563 return proxy.asFieldSetter();
564 }
565
566 @Override public AnnotatedElement asAnnotatedElement() {
567 return proxy.asAnnotatedElement();
568 }
569 }
570
571 public static WarningGuardSpec getWarningGuardSpec() {
572 WarningGuardSpec spec = new WarningGuardSpec();
573 for (GuardLevel guardLevel : guardLevels) {
574 spec.add(guardLevel.level, guardLevel.name);
575 }
576 return spec;
577 }
578 }
579
580 /**
581 * Set of options that can be used with the --formatting flag.
582 */
583 private static enum FormattingOption {
584 PRETTY_PRINT,
585 PRINT_INPUT_DELIMITER,
586 SINGLE_QUOTES
587 ;
588
589 private void applyToOptions(CompilerOptions options) {
590 switch (this) {
591 case PRETTY_PRINT:
592 options.prettyPrint = true;
593 break;
594 case PRINT_INPUT_DELIMITER:
595 options.printInputDelimiter = true;
596 break;
597 case SINGLE_QUOTES:
598 options.setPreferSingleQuotes(true);
599 break;
600 default:
601 throw new RuntimeException("Unknown formatting option: " + this);
602 }
603 }
604 }
605
606 private final Flags flags = new Flags();
607
608 private boolean isConfigValid = false;
609
610 /**
611 * Create a new command-line runner. You should only need to call
612 * the constructor if you're extending this class. Otherwise, the main
613 * method should instantiate it.
614 */
615 protected CommandLineRunner(String[] args) {
616 super();
617 initConfigFromFlags(args, System.err);
618 }
619
620 protected CommandLineRunner(String[] args, PrintStream out, PrintStream err) {
621 super(out, err);
622 initConfigFromFlags(args, err);
623 }
624
625 /**
626 * Split strings into tokens delimited by whitespace, but treat quoted
627 * strings as single tokens. Non-whitespace characters adjacent to quoted
628 * strings will be returned as part of the token. For example, the string
629 * {@code "--js='/home/my project/app.js'"} would be returned as a single
630 * token.
631 *
632 * @param lines strings to tokenize
633 * @return a list of tokens
634 */
635 private List<String> tokenizeKeepingQuotedStrings(List<String> lines) {
636 List<String> tokens = Lists.newArrayList();
637 Pattern tokenPattern =
638 Pattern.compile("(?:[^ \t\f\\x0B'\"]|(?:'[^']*'|\"[^\"]*\"))+");
639
640 for (String line : lines) {
641 Matcher matcher = tokenPattern.matcher(line);
642 while (matcher.find()) {
643 tokens.add(matcher.group(0));
644 }
645 }
646 return tokens;
647 }
648
649 private List<String> processArgs(String[] args) {
650 // Args4j has a different format that the old command-line parser.
651 // So we use some voodoo to get the args into the format that args4j
652 // expects.
653 Pattern argPattern = Pattern.compile("(--[a-zA-Z_]+)=(.*)");
654 Pattern quotesPattern = Pattern.compile("^['\"](.*)['\"]$");
655 List<String> processedArgs = Lists.newArrayList();
656
657 for (String arg : args) {
658 Matcher matcher = argPattern.matcher(arg);
659 if (matcher.matches()) {
660 processedArgs.add(matcher.group(1));
661
662 String value = matcher.group(2);
663 Matcher quotesMatcher = quotesPattern.matcher(value);
664 if (quotesMatcher.matches()) {
665 processedArgs.add(quotesMatcher.group(1));
666 } else {
667 processedArgs.add(value);
668 }
669 } else {
670 processedArgs.add(arg);
671 }
672 }
673
674 return processedArgs;
675 }
676
677 private void processFlagFile(PrintStream err)
678 throws CmdLineException, IOException {
679 File flagFileInput = new File(flags.flag_file);
680 List<String> argsInFile = tokenizeKeepingQuotedStrings(
681 Files.readLines(flagFileInput, Charset.defaultCharset()));
682
683 flags.flag_file = "";
684 List<String> processedFileArgs
685 = processArgs(argsInFile.toArray(new String[] {}));
686 CmdLineParser parserFileArgs = new CmdLineParser(flags);
687 // Command-line warning levels should override flag file settings,
688 // which means they should go last.
689 List<GuardLevel> previous = Lists.newArrayList(Flags.guardLevels);
690 Flags.guardLevels.clear();
691 parserFileArgs.parseArgument(processedFileArgs.toArray(new String[] {}));
692 Flags.guardLevels.addAll(previous);
693
694 // Currently we are not supporting this (prevent direct/indirect loops)
695 if (!flags.flag_file.equals("")) {
696 err.println("ERROR - Arguments in the file cannot contain "
697 + "--flagfile option.");
698 isConfigValid = false;
699 }
700 }
701
702 private void initConfigFromFlags(String[] args, PrintStream err) {
703
704 List<String> processedArgs = processArgs(args);
705
706 CmdLineParser parser = new CmdLineParser(flags);
707 Flags.guardLevels.clear();
708 isConfigValid = true;
709 try {
710 parser.parseArgument(processedArgs.toArray(new String[] {}));
711 // For contains --flagfile flag
712 if (!flags.flag_file.equals("")) {
713 processFlagFile(err);
714 }
715 } catch (CmdLineException e) {
716 err.println(e.getMessage());
717 isConfigValid = false;
718 } catch (IOException ioErr) {
719 err.println("ERROR - " + flags.flag_file + " read error.");
720 isConfigValid = false;
721 }
722
723 if (flags.version) {
724 err.println(
725 "Closure Compiler (http://code.google.com/closure/compiler)\n" +
726 "Version: " + Compiler.getReleaseVersion() + "\n" +
727 "Built on: " + Compiler.getReleaseDate());
728 err.flush();
729 }
730
731 if (flags.process_common_js_modules) {
732 flags.process_closure_primitives = true;
733 flags.manage_closure_dependencies = true;
734 if (flags.common_js_entry_module == null) {
735 err.println("Please specify --common_js_entry_module.");
736 err.flush();
737 isConfigValid = false;
738 }
739 flags.closure_entry_point = Lists.newArrayList(
740 ProcessCommonJSModules.toModuleName(flags.common_js_entry_module));
741 }
742
743 if (!isConfigValid || flags.display_help) {
744 isConfigValid = false;
745 parser.printUsage(err);
746 } else {
747 CodingConvention conv;
748 if (flags.third_party) {
749 conv = CodingConventions.getDefault();
750 } else if (flags.process_jquery_primitives) {
751 conv = new JqueryCodingConvention();
752 } else {
753 conv = new ClosureCodingConvention();
754 }
755
756 getCommandLineConfig()
757 .setPrintTree(flags.print_tree)
758 .setPrintAst(flags.print_ast)
759 .setPrintPassGraph(flags.print_pass_graph)
760 .setJscompDevMode(flags.jscomp_dev_mode)
761 .setLoggingLevel(flags.logging_level)
762 .setExterns(flags.externs)
763 .setJs(flags.getJsFiles())
764 .setJsOutputFile(flags.js_output_file)
765 .setModule(flags.module)
766 .setVariableMapInputFile(flags.variable_map_input_file)
767 .setPropertyMapInputFile(flags.property_map_input_file)
768 .setVariableMapOutputFile(flags.variable_map_output_file)
769 .setCreateNameMapFiles(flags.create_name_map_files)
770 .setPropertyMapOutputFile(flags.property_map_output_file)
771 .setCodingConvention(conv)
772 .setSummaryDetailLevel(flags.summary_detail_level)
773 .setOutputWrapper(flags.output_wrapper)
774 .setModuleWrapper(flags.module_wrapper)
775 .setModuleOutputPathPrefix(flags.module_output_path_prefix)
776 .setCreateSourceMap(flags.create_source_map)
777 .setSourceMapFormat(flags.source_map_format)
778 .setWarningGuardSpec(Flags.getWarningGuardSpec())
779 .setDefine(flags.define)
780 .setCharset(flags.charset)
781 .setManageClosureDependencies(flags.manage_closure_dependencies)
782 .setOnlyClosureDependencies(flags.only_closure_dependencies)
783 .setClosureEntryPoints(flags.closure_entry_point)
784 .setOutputManifest(ImmutableList.of(flags.output_manifest))
785 .setOutputModuleDependencies(flags.output_module_dependencies)
786 .setAcceptConstKeyword(flags.accept_const_keyword)
787 .setLanguageIn(flags.language_in)
788 .setProcessCommonJSModules(flags.process_common_js_modules)
789 .setCommonJSModulePathPrefix(flags.common_js_path_prefix)
790 .setTransformAMDToCJSModules(flags.transform_amd_modules)
791 .setWarningsWhitelistFile(flags.warnings_whitelist_file);
792 }
793 }
794
795 @Override
796 protected CompilerOptions createOptions() {
797 CompilerOptions options = new CompilerOptions();
798 if (flags.process_jquery_primitives) {
799 options.setCodingConvention(new JqueryCodingConvention());
800 } else {
801 options.setCodingConvention(new ClosureCodingConvention());
802 }
803
804 options.setExtraAnnotationNames(flags.extra_annotation_name);
805
806 CompilationLevel level = flags.compilation_level;
807 level.setOptionsForCompilationLevel(options);
808
809 if (flags.debug) {
810 level.setDebugOptionsForCompilationLevel(options);
811 }
812
813 if (flags.use_types_for_optimization) {
814 level.setTypeBasedOptimizationOptions(options);
815 }
816
817 if (flags.generate_exports) {
818 options.setGenerateExports(flags.generate_exports);
819 }
820
821 WarningLevel wLevel = flags.warning_level;
822 wLevel.setOptionsForWarningLevel(options);
823 for (FormattingOption formattingOption : flags.formatting) {
824 formattingOption.applyToOptions(options);
825 }
826
827 options.closurePass = flags.process_closure_primitives;
828
829 options.jqueryPass = flags.process_jquery_primitives &&
830 CompilationLevel.ADVANCED_OPTIMIZATIONS == level;
831
832 options.angularPass = flags.angular_pass;
833
834 if (!flags.translationsFile.isEmpty()) {
835 try {
836 options.messageBundle = new XtbMessageBundle(
837 new FileInputStream(flags.translationsFile),
838 flags.translationsProject);
839 } catch (IOException e) {
840 throw new RuntimeException("Reading XTB file", e);
841 }
842 } else if (CompilationLevel.ADVANCED_OPTIMIZATIONS == level) {
843 // In SIMPLE or WHITESPACE mode, if the user hasn't specified a
844 // translations file, they might reasonably try to write their own
845 // implementation of goog.getMsg that makes the substitution at
846 // run-time.
847 //
848 // In ADVANCED mode, goog.getMsg is going to be renamed anyway,
849 // so we might as well inline it.
850 options.messageBundle = new EmptyMessageBundle();
851 }
852
853 return options;
854 }
855
856 @Override
857 protected Compiler createCompiler() {
858 return new Compiler(getErrorPrintStream());
859 }
860
861 @Override
862 protected List<SourceFile> createExterns() throws FlagUsageException,
863 IOException {
864 List<SourceFile> externs = super.createExterns();
865 if (flags.use_only_custom_externs || isInTestMode()) {
866 return externs;
867 } else {
868 List<SourceFile> defaultExterns = getDefaultExterns();
869 defaultExterns.addAll(externs);
870 return defaultExterns;
871 }
872 }
873
874 // The externs expected in externs.zip, in sorted order.
875 private static final List<String> DEFAULT_EXTERNS_NAMES = ImmutableList.of(
876 // JS externs
877 "es3.js",
878 "es5.js",
879
880 // Event APIs
881 "w3c_event.js",
882 "w3c_event3.js",
883 "gecko_event.js",
884 "ie_event.js",
885 "webkit_event.js",
886
887 // DOM apis
888 "w3c_dom1.js",
889 "w3c_dom2.js",
890 "w3c_dom3.js",
891 "gecko_dom.js",
892 "ie_dom.js",
893 "webkit_dom.js",
894
895 // CSS apis
896 "w3c_css.js",
897 "gecko_css.js",
898 "ie_css.js",
899 "webkit_css.js",
900
901 // Top-level namespaces
902 "google.js",
903
904 "deprecated.js",
905 "fileapi.js",
906 "flash.js",
907 "gears_symbols.js",
908 "gears_types.js",
909 "gecko_xml.js",
910 "html5.js",
911 "ie_vml.js",
912 "iphone.js",
913 "webstorage.js",
914 "w3c_anim_timing.js",
915 "w3c_css3d.js",
916 "w3c_elementtraversal.js",
917 "w3c_geolocation.js",
918 "w3c_indexeddb.js",
919 "w3c_navigation_timing.js",
920 "w3c_range.js",
921 "w3c_selectors.js",
922 "w3c_xml.js",
923 "window.js",
924 "webkit_notifications.js",
925 "webgl.js");
926
927 /**
928 * @return a mutable list
929 * @throws IOException
930 */
931 public static List<SourceFile> getDefaultExterns() throws IOException {
932 InputStream input = CommandLineRunner.class.getResourceAsStream(
933 "/externs.zip");
934 if (input == null) {
935 // In some environments, the externs.zip is relative to this class.
936 input = CommandLineRunner.class.getResourceAsStream("externs.zip");
937 }
938 Preconditions.checkNotNull(input);
939
940 ZipInputStream zip = new ZipInputStream(input);
941 Map<String, SourceFile> externsMap = Maps.newHashMap();
942 for (ZipEntry entry = null; (entry = zip.getNextEntry()) != null; ) {
943 BufferedInputStream entryStream = new BufferedInputStream(
•944 ByteStreams.limit(zip, entry.getSize()));
945 externsMap.put(entry.getName(),
946 SourceFile.fromInputStream(
947 // Give the files an odd prefix, so that they do not conflict
948 // with the user's files.
949 "externs.zip//" + entry.getName(),
950 entryStream));
951 }
952
953 Preconditions.checkState(
954 externsMap.keySet().equals(Sets.newHashSet(DEFAULT_EXTERNS_NAMES)),
955 "Externs zip must match our hard-coded list of externs.");
956
957 // Order matters, so the resources must be added to the result list
958 // in the expected order.
959 List<SourceFile> externs = Lists.newArrayList();
960 for (String key : DEFAULT_EXTERNS_NAMES) {
961 externs.add(externsMap.get(key));
962 }
963
964 return externs;
965 }
966
967 /**
968 * @return Whether the configuration is valid.
969 */
970 public boolean shouldRunCompiler() {
971 return this.isConfigValid;
972 }
973
974 /**
975 * Runs the Compiler. Exits cleanly in the event of an error.
976 */
977 public static void main(String[] args) {
978 CommandLineRunner runner = new CommandLineRunner(args);
979 if (runner.shouldRunCompiler()) {
980 runner.run();
981 } else {
982 System.exit(-1);
983 }
984 }
985 }