arguments = Lists.newArrayList();
/**
* Users may specify JS inputs via the legacy {@code --js} option, as well
* as via additional arguments to the Closure Compiler. For example, it is
* convenient to leverage the additional arguments feature when using the
* Closure Compiler in combination with {@code find} and {@code xargs}:
*
* find MY_JS_SRC_DIR -name '*.js' \
* | xargs java -jar compiler.jar --manage_closure_dependencies
*
* The {@code find} command will produce a list of '*.js' source files in
* the {@code MY_JS_SRC_DIR} directory while {@code xargs} will convert them
* to a single, space-delimited set of arguments that are appended to the
* {@code java} command to run the Compiler.
*
* Note that it is important to use the
* {@code --manage_closure_dependencies} option in this case because the
* order produced by {@code find} is unlikely to be sorted correctly with
* respect to {@code goog.provide()} and {@code goog.requires()}.
*/
List getJsFiles() {
List allJsInputs = Lists.newArrayListWithCapacity(
js.size() + arguments.size());
allJsInputs.addAll(js);
allJsInputs.addAll(arguments);
return allJsInputs;
}
// Our own option parser to be backwards-compatible.
// It needs to be public because of the crazy reflection that args4j does.
public static class BooleanOptionHandler extends OptionHandler {
private static final Set TRUES =
Sets.newHashSet("true", "on", "yes", "1");
private static final Set FALSES =
Sets.newHashSet("false", "off", "no", "0");
public BooleanOptionHandler(
CmdLineParser parser, OptionDef option,
Setter super Boolean> setter) {
super(parser, option, setter);
}
@Override
public int parseArguments(Parameters params) throws CmdLineException {
String param = null;
try {
param = params.getParameter(0);
} catch (CmdLineException e) {}
if (param == null) {
setter.addValue(true);
return 0;
} else {
String lowerParam = param.toLowerCase();
if (TRUES.contains(lowerParam)) {
setter.addValue(true);
} else if (FALSES.contains(lowerParam)) {
setter.addValue(false);
} else {
setter.addValue(true);
return 0;
}
return 1;
}
}
@Override
public String getDefaultMetaVariable() {
return null;
}
}
// Our own parser for warning guards that preserves the original order
// of the flags.
public static class WarningGuardErrorOptionHandler
extends StringOptionHandler {
public WarningGuardErrorOptionHandler(
CmdLineParser parser, OptionDef option,
Setter super String> setter) {
super(parser, option, new WarningGuardSetter(setter, CheckLevel.ERROR));
}
}
public static class WarningGuardWarningOptionHandler
extends StringOptionHandler {
public WarningGuardWarningOptionHandler(
CmdLineParser parser, OptionDef option,
Setter super String> setter) {
super(parser, option,
new WarningGuardSetter(setter, CheckLevel.WARNING));
}
}
public static class WarningGuardOffOptionHandler
extends StringOptionHandler {
public WarningGuardOffOptionHandler(
CmdLineParser parser, OptionDef option,
Setter super String> setter) {
super(parser, option, new WarningGuardSetter(setter, CheckLevel.OFF));
}
}
private static class WarningGuardSetter implements Setter {
private final Setter super String> proxy;
private final CheckLevel level;
private WarningGuardSetter(
Setter super String> proxy, CheckLevel level) {
this.proxy = proxy;
this.level = level;
}
@Override public boolean isMultiValued() {
return proxy.isMultiValued();
}
@Override public Class getType() {
return (Class) proxy.getType();
}
@Override public void addValue(String value) throws CmdLineException {
proxy.addValue(value);
guardLevels.add(new GuardLevel(value, level));
}
@Override public FieldSetter asFieldSetter() {
return proxy.asFieldSetter();
}
@Override public AnnotatedElement asAnnotatedElement() {
return proxy.asAnnotatedElement();
}
}
public static WarningGuardSpec getWarningGuardSpec() {
WarningGuardSpec spec = new WarningGuardSpec();
for (GuardLevel guardLevel : guardLevels) {
spec.add(guardLevel.level, guardLevel.name);
}
return spec;
}
}
/**
* Set of options that can be used with the --formatting flag.
*/
private static enum FormattingOption {
PRETTY_PRINT,
PRINT_INPUT_DELIMITER,
SINGLE_QUOTES
;
private void applyToOptions(CompilerOptions options) {
switch (this) {
case PRETTY_PRINT:
options.prettyPrint = true;
break;
case PRINT_INPUT_DELIMITER:
options.printInputDelimiter = true;
break;
case SINGLE_QUOTES:
options.setPreferSingleQuotes(true);
break;
default:
throw new RuntimeException("Unknown formatting option: " + this);
}
}
}
private final Flags flags = new Flags();
private boolean isConfigValid = false;
/**
* Create a new command-line runner. You should only need to call
* the constructor if you're extending this class. Otherwise, the main
* method should instantiate it.
*/
protected CommandLineRunner(String[] args) {
super();
initConfigFromFlags(args, System.err);
}
protected CommandLineRunner(String[] args, PrintStream out, PrintStream err) {
super(out, err);
initConfigFromFlags(args, err);
}
/**
* Split strings into tokens delimited by whitespace, but treat quoted
* strings as single tokens. Non-whitespace characters adjacent to quoted
* strings will be returned as part of the token. For example, the string
* {@code "--js='/home/my project/app.js'"} would be returned as a single
* token.
*
* @param lines strings to tokenize
* @return a list of tokens
*/
private List tokenizeKeepingQuotedStrings(List lines) {
List tokens = Lists.newArrayList();
Pattern tokenPattern =
Pattern.compile("(?:[^ \t\f\\x0B'\"]|(?:'[^']*'|\"[^\"]*\"))+");
for (String line : lines) {
Matcher matcher = tokenPattern.matcher(line);
while (matcher.find()) {
tokens.add(matcher.group(0));
}
}
return tokens;
}
private List processArgs(String[] args) {
// Args4j has a different format that the old command-line parser.
// So we use some voodoo to get the args into the format that args4j
// expects.
Pattern argPattern = Pattern.compile("(--[a-zA-Z_]+)=(.*)");
Pattern quotesPattern = Pattern.compile("^['\"](.*)['\"]$");
List processedArgs = Lists.newArrayList();
for (String arg : args) {
Matcher matcher = argPattern.matcher(arg);
if (matcher.matches()) {
processedArgs.add(matcher.group(1));
String value = matcher.group(2);
Matcher quotesMatcher = quotesPattern.matcher(value);
if (quotesMatcher.matches()) {
processedArgs.add(quotesMatcher.group(1));
} else {
processedArgs.add(value);
}
} else {
processedArgs.add(arg);
}
}
return processedArgs;
}
private void processFlagFile(PrintStream err)
throws CmdLineException, IOException {
File flagFileInput = new File(flags.flag_file);
List argsInFile = tokenizeKeepingQuotedStrings(
Files.readLines(flagFileInput, Charset.defaultCharset()));
flags.flag_file = "";
List processedFileArgs
= processArgs(argsInFile.toArray(new String[] {}));
CmdLineParser parserFileArgs = new CmdLineParser(flags);
// Command-line warning levels should override flag file settings,
// which means they should go last.
List previous = Lists.newArrayList(Flags.guardLevels);
Flags.guardLevels.clear();
parserFileArgs.parseArgument(processedFileArgs.toArray(new String[] {}));
Flags.guardLevels.addAll(previous);
// Currently we are not supporting this (prevent direct/indirect loops)
if (!flags.flag_file.equals("")) {
err.println("ERROR - Arguments in the file cannot contain "
+ "--flagfile option.");
isConfigValid = false;
}
}
private void initConfigFromFlags(String[] args, PrintStream err) {
List processedArgs = processArgs(args);
CmdLineParser parser = new CmdLineParser(flags);
Flags.guardLevels.clear();
isConfigValid = true;
try {
parser.parseArgument(processedArgs.toArray(new String[] {}));
// For contains --flagfile flag
if (!flags.flag_file.equals("")) {
processFlagFile(err);
}
} catch (CmdLineException e) {
err.println(e.getMessage());
isConfigValid = false;
} catch (IOException ioErr) {
err.println("ERROR - " + flags.flag_file + " read error.");
isConfigValid = false;
}
if (flags.version) {
err.println(
"Closure Compiler (http://code.google.com/closure/compiler)\n" +
"Version: " + Compiler.getReleaseVersion() + "\n" +
"Built on: " + Compiler.getReleaseDate());
err.flush();
}
if (flags.process_common_js_modules) {
flags.process_closure_primitives = true;
flags.manage_closure_dependencies = true;
if (flags.common_js_entry_module == null) {
err.println("Please specify --common_js_entry_module.");
err.flush();
isConfigValid = false;
}
flags.closure_entry_point = Lists.newArrayList(
ProcessCommonJSModules.toModuleName(flags.common_js_entry_module));
}
if (!isConfigValid || flags.display_help) {
isConfigValid = false;
parser.printUsage(err);
} else {
CodingConvention conv;
if (flags.third_party) {
conv = CodingConventions.getDefault();
} else if (flags.process_jquery_primitives) {
conv = new JqueryCodingConvention();
} else {
conv = new ClosureCodingConvention();
}
getCommandLineConfig()
.setPrintTree(flags.print_tree)
.setPrintAst(flags.print_ast)
.setPrintPassGraph(flags.print_pass_graph)
.setJscompDevMode(flags.jscomp_dev_mode)
.setLoggingLevel(flags.logging_level)
.setExterns(flags.externs)
.setJs(flags.getJsFiles())
.setJsOutputFile(flags.js_output_file)
.setModule(flags.module)
.setVariableMapInputFile(flags.variable_map_input_file)
.setPropertyMapInputFile(flags.property_map_input_file)
.setVariableMapOutputFile(flags.variable_map_output_file)
.setCreateNameMapFiles(flags.create_name_map_files)
.setPropertyMapOutputFile(flags.property_map_output_file)
.setCodingConvention(conv)
.setSummaryDetailLevel(flags.summary_detail_level)
.setOutputWrapper(flags.output_wrapper)
.setModuleWrapper(flags.module_wrapper)
.setModuleOutputPathPrefix(flags.module_output_path_prefix)
.setCreateSourceMap(flags.create_source_map)
.setSourceMapFormat(flags.source_map_format)
.setWarningGuardSpec(Flags.getWarningGuardSpec())
.setDefine(flags.define)
.setCharset(flags.charset)
.setManageClosureDependencies(flags.manage_closure_dependencies)
.setOnlyClosureDependencies(flags.only_closure_dependencies)
.setClosureEntryPoints(flags.closure_entry_point)
.setOutputManifest(ImmutableList.of(flags.output_manifest))
.setOutputModuleDependencies(flags.output_module_dependencies)
.setAcceptConstKeyword(flags.accept_const_keyword)
.setLanguageIn(flags.language_in)
.setProcessCommonJSModules(flags.process_common_js_modules)
.setCommonJSModulePathPrefix(flags.common_js_path_prefix)
.setTransformAMDToCJSModules(flags.transform_amd_modules)
.setWarningsWhitelistFile(flags.warnings_whitelist_file);
}
}
@Override
protected CompilerOptions createOptions() {
CompilerOptions options = new CompilerOptions();
if (flags.process_jquery_primitives) {
options.setCodingConvention(new JqueryCodingConvention());
} else {
options.setCodingConvention(new ClosureCodingConvention());
}
options.setExtraAnnotationNames(flags.extra_annotation_name);
CompilationLevel level = flags.compilation_level;
level.setOptionsForCompilationLevel(options);
if (flags.debug) {
level.setDebugOptionsForCompilationLevel(options);
}
if (flags.use_types_for_optimization) {
level.setTypeBasedOptimizationOptions(options);
}
if (flags.generate_exports) {
options.setGenerateExports(flags.generate_exports);
}
WarningLevel wLevel = flags.warning_level;
wLevel.setOptionsForWarningLevel(options);
for (FormattingOption formattingOption : flags.formatting) {
formattingOption.applyToOptions(options);
}
options.closurePass = flags.process_closure_primitives;
options.jqueryPass = flags.process_jquery_primitives &&
CompilationLevel.ADVANCED_OPTIMIZATIONS == level;
options.angularPass = flags.angular_pass;
if (!flags.translationsFile.isEmpty()) {
try {
options.messageBundle = new XtbMessageBundle(
new FileInputStream(flags.translationsFile),
flags.translationsProject);
} catch (IOException e) {
throw new RuntimeException("Reading XTB file", e);
}
} else if (CompilationLevel.ADVANCED_OPTIMIZATIONS == level) {
// In SIMPLE or WHITESPACE mode, if the user hasn't specified a
// translations file, they might reasonably try to write their own
// implementation of goog.getMsg that makes the substitution at
// run-time.
//
// In ADVANCED mode, goog.getMsg is going to be renamed anyway,
// so we might as well inline it.
options.messageBundle = new EmptyMessageBundle();
}
return options;
}
@Override
protected Compiler createCompiler() {
return new Compiler(getErrorPrintStream());
}
@Override
protected List createExterns() throws FlagUsageException,
IOException {
List externs = super.createExterns();
if (flags.use_only_custom_externs || isInTestMode()) {
return externs;
} else {
List defaultExterns = getDefaultExterns();
defaultExterns.addAll(externs);
return defaultExterns;
}
}
// The externs expected in externs.zip, in sorted order.
private static final List DEFAULT_EXTERNS_NAMES = ImmutableList.of(
// JS externs
"es3.js",
"es5.js",
// Event APIs
"w3c_event.js",
"w3c_event3.js",
"gecko_event.js",
"ie_event.js",
"webkit_event.js",
// DOM apis
"w3c_dom1.js",
"w3c_dom2.js",
"w3c_dom3.js",
"gecko_dom.js",
"ie_dom.js",
"webkit_dom.js",
// CSS apis
"w3c_css.js",
"gecko_css.js",
"ie_css.js",
"webkit_css.js",
// Top-level namespaces
"google.js",
"deprecated.js",
"fileapi.js",
"flash.js",
"gears_symbols.js",
"gears_types.js",
"gecko_xml.js",
"html5.js",
"ie_vml.js",
"iphone.js",
"webstorage.js",
"w3c_anim_timing.js",
"w3c_css3d.js",
"w3c_elementtraversal.js",
"w3c_geolocation.js",
"w3c_indexeddb.js",
"w3c_navigation_timing.js",
"w3c_range.js",
"w3c_selectors.js",
"w3c_xml.js",
"window.js",
"webkit_notifications.js",
"webgl.js");
/**
* @return a mutable list
* @throws IOException
*/
public static List getDefaultExterns() throws IOException {
InputStream input = CommandLineRunner.class.getResourceAsStream(
"/externs.zip");
if (input == null) {
// In some environments, the externs.zip is relative to this class.
input = CommandLineRunner.class.getResourceAsStream("externs.zip");
}
Preconditions.checkNotNull(input);
ZipInputStream zip = new ZipInputStream(input);
Map externsMap = Maps.newHashMap();
for (ZipEntry entry = null; (entry = zip.getNextEntry()) != null; ) {
BufferedInputStream entryStream = new BufferedInputStream(
ByteStreams.limit(zip, entry.getSize()));
externsMap.put(entry.getName(),
SourceFile.fromInputStream(
// Give the files an odd prefix, so that they do not conflict
// with the user's files.
"externs.zip//" + entry.getName(),
entryStream));
}
Preconditions.checkState(
externsMap.keySet().equals(Sets.newHashSet(DEFAULT_EXTERNS_NAMES)),
"Externs zip must match our hard-coded list of externs.");
// Order matters, so the resources must be added to the result list
// in the expected order.
List externs = Lists.newArrayList();
for (String key : DEFAULT_EXTERNS_NAMES) {
externs.add(externsMap.get(key));
}
return externs;
}
/**
* @return Whether the configuration is valid.
*/
public boolean shouldRunCompiler() {
return this.isConfigValid;
}
/**
* Runs the Compiler. Exits cleanly in the event of an error.
*/
public static void main(String[] args) {
CommandLineRunner runner = new CommandLineRunner(args);
if (runner.shouldRunCompiler()) {
runner.run();
} else {
System.exit(-1);
}
}
}