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