Debian Codegraph @

src/com/google/javascript/jscomp/ant/CompileTask.java

raw symbols SCIP
1 /*
2 * Copyright 2010 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.ant;
18
19 import com.google.common.base.Strings;
20 import com.google.common.collect.Lists;
21 import com.google.javascript.jscomp.CheckLevel;
22 import com.google.javascript.jscomp.CommandLineRunner;
23 import com.google.javascript.jscomp.CompilationLevel;
24 import com.google.javascript.jscomp.Compiler;
25 import com.google.javascript.jscomp.CompilerOptions;
26 import com.google.javascript.jscomp.DiagnosticGroup;
27 import com.google.javascript.jscomp.DiagnosticGroups;
28 import com.google.javascript.jscomp.MessageFormatter;
29 import com.google.javascript.jscomp.Result;
30 import com.google.javascript.jscomp.SourceFile;
31 import com.google.javascript.jscomp.SourceMap;
32 import com.google.javascript.jscomp.SourceMap.Format;
33 import com.google.javascript.jscomp.WarningLevel;
34
35 import org.apache.tools.ant.BuildException;
36 import org.apache.tools.ant.Project;
37 import org.apache.tools.ant.Task;
38 import org.apache.tools.ant.types.FileList;
39 import org.apache.tools.ant.types.Parameter;
40 import org.apache.tools.ant.types.Path;
41
42 import java.io.File;
43 import java.io.FileOutputStream;
44 import java.io.FileWriter;
45 import java.io.IOException;
46 import java.io.OutputStreamWriter;
47 import java.nio.charset.Charset;
48 import java.util.Date;
49 import java.util.List;
50 import java.util.Map;
51 import java.util.logging.Level;
52
53 /**
54 * This class implements a simple Ant task to do almost the same as
55 * CommandLineRunner.
56 *
57 * Most of the public methods of this class are entry points for the
58 * Ant code to hook into.
59 *
60 */
61 public final class CompileTask
62 extends Task {
63 private CompilerOptions.LanguageMode languageIn;
64 private WarningLevel warningLevel;
65 private boolean debugOptions;
66 private String encoding = "UTF-8";
67 private String outputEncoding = "UTF-8";
68 private CompilationLevel compilationLevel;
69 private boolean customExternsOnly;
70 private boolean manageDependencies;
71 private boolean prettyPrint;
72 private boolean printInputDelimiter;
73 private boolean generateExports;
74 private boolean replaceProperties;
75 private boolean forceRecompile;
76 private String replacePropertiesPrefix;
77 private File outputFile;
78 private final List<Parameter> defineParams;
79 private final List<FileList> externFileLists;
80 private final List<FileList> sourceFileLists;
81 private final List<Path> sourcePaths;
82 private final List<Warning> warnings;
83 private String sourceMapFormat;
84 private File sourceMapOutputFile;
85
86 public CompileTask() {
87 this.languageIn = CompilerOptions.LanguageMode.ECMASCRIPT3;
88 this.warningLevel = WarningLevel.DEFAULT;
89 this.debugOptions = false;
90 this.compilationLevel = CompilationLevel.SIMPLE_OPTIMIZATIONS;
91 this.customExternsOnly = false;
92 this.manageDependencies = false;
93 this.prettyPrint = false;
94 this.printInputDelimiter = false;
95 this.generateExports = false;
96 this.replaceProperties = false;
97 this.forceRecompile = false;
98 this.replacePropertiesPrefix = "closure.define.";
99 this.defineParams = Lists.newLinkedList();
100 this.externFileLists = Lists.newLinkedList();
101 this.sourceFileLists = Lists.newLinkedList();
102 this.sourcePaths = Lists.newLinkedList();
103 this.warnings = Lists.newLinkedList();
104 }
105
106 /**
107 * Set the language to which input sources conform.
108 * @param value The name of the language.
109 * (ECMASCRIPT3, ECMASCRIPT5, ECMASCRIPT5_STRICT).
110 */
111 public void setLanguageIn(String value) {
112 if (value.equals("ECMASCRIPT5_STRICT") || value.equals("ES5_STRICT")) {
113 this.languageIn = CompilerOptions.LanguageMode.ECMASCRIPT5_STRICT;
114 } else if (value.equals("ECMASCRIPT5") || value.equals("ES5")) {
115 this.languageIn = CompilerOptions.LanguageMode.ECMASCRIPT5;
116 } else if (value.equals("ECMASCRIPT3") || value.equals("ES3")) {
117 this.languageIn = CompilerOptions.LanguageMode.ECMASCRIPT3;
118 } else {
119 throw new BuildException(
120 "Unrecognized 'languageIn' option value (" + value + ")");
121 }
122 }
123
124 /**
125 * Set the warning level.
126 * @param value The warning level by string name. (default, quiet, verbose).
127 */
128 public void setWarning(String value) {
129 if ("default".equalsIgnoreCase(value)) {
130 this.warningLevel = WarningLevel.DEFAULT;
131 } else if ("quiet".equalsIgnoreCase(value)) {
132 this.warningLevel = WarningLevel.QUIET;
133 } else if ("verbose".equalsIgnoreCase(value)) {
134 this.warningLevel = WarningLevel.VERBOSE;
135 } else {
136 throw new BuildException(
137 "Unrecognized 'warning' option value (" + value + ")");
138 }
139 }
140
141 /**
142 * Enable debugging options.
143 * @param value True if debug mode is enabled.
144 */
145 public void setDebug(boolean value) {
146 this.debugOptions = value;
147 }
148
149 /**
150 * Set the compilation level.
151 * @param value The optimization level by string name.
152 * (whitespace, simple, advanced).
153 */
154 public void setCompilationLevel(String value) {
155 if ("simple".equalsIgnoreCase(value)) {
156 this.compilationLevel = CompilationLevel.SIMPLE_OPTIMIZATIONS;
157 } else if ("advanced".equalsIgnoreCase(value)) {
158 this.compilationLevel = CompilationLevel.ADVANCED_OPTIMIZATIONS;
159 } else if ("whitespace".equalsIgnoreCase(value)) {
160 this.compilationLevel = CompilationLevel.WHITESPACE_ONLY;
161 } else {
162 throw new BuildException(
163 "Unrecognized 'compilation' option value (" + value + ")");
164 }
165 }
166
167 public void setManageDependencies(boolean value) {
168 this.manageDependencies = value;
169 }
170
171 /**
172 * Use only custom externs.
173 */
174 public void setCustomExternsOnly(boolean value) {
175 this.customExternsOnly = value;
176 }
177
178 /**
179 * Set output file.
180 */
181 public void setOutput(File value) {
182 this.outputFile = value;
183 }
184
185 /**
186 * Set the replacement property prefix.
187 */
188 public void setReplacePropertiesPrefix(String value) {
189 this.replacePropertiesPrefix = value;
190 }
191
192 /**
193 * Whether to replace {@code @define} lines with properties
194 */
195 public void setReplaceProperties(boolean value) {
196 this.replaceProperties = value;
197 }
198
199 /**
200 * Set input file encoding
201 */
202 public void setEncoding(String encoding) {
203 this.encoding = encoding;
204 }
205
206 /**
207 * Set output file encoding
208 */
209 public void setOutputEncoding(String outputEncoding) {
210 this.outputEncoding = outputEncoding;
211 }
212
213 /**
214 * Set pretty print formatting option
215 */
216 public void setPrettyPrint(boolean pretty) {
217 this.prettyPrint = pretty;
218 }
219
220 /**
221 * Set print input delimiter formatting option
222 */
223 public void setPrintInputDelimiter(boolean print) {
224 this.printInputDelimiter = print;
225 }
226
227 /**
228 * Set force recompile option
229 */
230 public void setForceRecompile(boolean forceRecompile) {
231 this.forceRecompile = forceRecompile;
232 }
233
234 /**
235 * Set generateExports option
236 */
237 public void setGenerateExports(boolean generateExports) {
238 this.generateExports = generateExports;
239 }
240
241 /**
242 * Sets the externs file.
243 */
244 public void addExterns(FileList list) {
245 this.externFileLists.add(list);
246 }
247
248 /**
249 * Adds a <warning/> entry
250 *
251 * Each warning entry must have two attributes, group and level. Group must
252 * contain one of the constants from DiagnosticGroups (e.g.,
253 * "ACCESS_CONTROLS"), while level must contain one of the CheckLevel
254 * constants ("ERROR", "WARNING" or "OFF").
255 */
256 public void addWarning(Warning warning) {
257 this.warnings.add(warning);
258 }
259
260 /**
261 * Sets the source files.
262 */
263 public void addSources(FileList list) {
264 this.sourceFileLists.add(list);
265 }
266
267 /**
268 * Adds a <path/> entry.
269 */
270 public void addPath(Path list) {
271 this.sourcePaths.add(list);
272 }
273
274 @Override
275 public void execute() {
276 if (this.outputFile == null) {
277 throw new BuildException("outputFile attribute must be set");
278 }
279
280 Compiler.setLoggingLevel(Level.OFF);
281
282 CompilerOptions options = createCompilerOptions();
283 Compiler compiler = createCompiler(options);
284
285 List<SourceFile> externs = findExternFiles();
286 List<SourceFile> sources = findSourceFiles();
287
288 if (isStale() || forceRecompile) {
289 log("Compiling " + sources.size() + " file(s) with " +
290 externs.size() + " extern(s)");
291
292 Result result = compiler.compile(externs, sources, options);
293 if (result.success) {
294 StringBuilder source = new StringBuilder(compiler.toSource());
295 if (result.sourceMap != null) {
296 flushSourceMap(result.sourceMap);
297 source.append(System.getProperty("line.separator"));
298 source.append("//@ sourceMappingURL=" + sourceMapOutputFile.getName());
299 }
300 writeResult(source.toString());
301 } else {
302 throw new BuildException("Compilation failed.");
303 }
304 } else {
305 log("None of the files changed. Compilation skipped.");
306 }
307 }
308
309 private void flushSourceMap(SourceMap sourceMap) {
310 try {
311 FileWriter out = new FileWriter(sourceMapOutputFile);
312 sourceMap.appendTo(out, sourceMapOutputFile.getName());
313 out.close();
314 } catch (IOException e) {
315 throw new BuildException("Cannot write sourcemap to file.", e);
316 }
317 }
318
319 private CompilerOptions createCompilerOptions() {
320 CompilerOptions options = new CompilerOptions();
321
322 this.compilationLevel.setOptionsForCompilationLevel(options);
323 if (this.debugOptions) {
324 this.compilationLevel.setDebugOptionsForCompilationLevel(options);
325 }
326
327 options.prettyPrint = this.prettyPrint;
328 options.printInputDelimiter = this.printInputDelimiter;
329 options.generateExports = this.generateExports;
330
331 options.setLanguageIn(this.languageIn);
332
333 this.warningLevel.setOptionsForWarningLevel(options);
334 options.setManageClosureDependencies(manageDependencies);
335
336 if (replaceProperties) {
337 convertPropertiesMap(options);
338 }
339
340 convertDefineParameters(options);
341
342 for (Warning warning : warnings) {
343 CheckLevel level = warning.getLevel();
344 String groupName = warning.getGroup();
345 DiagnosticGroup group = new DiagnosticGroups().forName(groupName);
346 if (group == null) {
347 throw new BuildException(
348 "Unrecognized 'warning' option value (" + groupName + ")");
349 }
350 options.setWarningLevel(group, level);
351 }
352
353 if (!Strings.isNullOrEmpty(sourceMapFormat)) {
354 options.sourceMapFormat = Format.valueOf(sourceMapFormat);
355 }
356
357 if (sourceMapOutputFile != null) {
358 File parentFile = sourceMapOutputFile.getParentFile();
359 if (parentFile.mkdirs()) {
360 log("Created missing parent directory " + parentFile, Project.MSG_DEBUG);
361 }
362 options.sourceMapOutputPath = parentFile.getAbsolutePath();
363 }
364 return options;
365 }
366
367 /**
368 * Creates a new {@code <define/>} nested element. Supports name and value
369 * attributes.
370 */
371 public Parameter createDefine() {
372 Parameter param = new Parameter();
373 defineParams.add(param);
374 return param;
375 }
376
377 /**
378 * Converts {@code <define/>} nested elements into Compiler {@code @define}
379 * replacements. Note: unlike project properties, {@code <define/>} elements
380 * do not need to be named starting with the replacement prefix.
381 */
382 private void convertDefineParameters(CompilerOptions options) {
383 for (Parameter p : defineParams) {
384 String key = p.getName();
385 Object value = p.getValue();
386
387 if (!setDefine(options, key, value)) {
388 log("Unexpected @define value for name=" + key + "; value=" + value);
389 }
390 }
391 }
392
393 /**
394 * Converts project properties beginning with the replacement prefix
395 * into Compiler {@code @define} replacements.
396 *
397 * @param options
398 */
399 private void convertPropertiesMap(CompilerOptions options) {
400 @SuppressWarnings("unchecked")
401 Map<String, Object> props = getProject().getProperties();
402 for (Map.Entry<String, Object> entry : props.entrySet()) {
403 String key = entry.getKey();
404 Object value = entry.getValue();
405
406 if (key.startsWith(replacePropertiesPrefix)) {
407 key = key.substring(replacePropertiesPrefix.length());
408
409 if (!setDefine(options, key, value)) {
410 log("Unexpected property value for key=" + key + "; value=" + value);
411 }
412 }
413 }
414 }
415
416 /**
417 * Maps Ant-style values (e.g., from Properties) into expected
418 * Closure {@code @define} literals
419 *
420 * @return True if the {@code @define} replacement succeeded, false if
421 * the variable's value could not be mapped properly.
422 */
423 private boolean setDefine(CompilerOptions options,
424 String key, Object value) {
425 boolean success = false;
426
427 if (value instanceof String) {
428 final boolean isTrue = "true".equals(value);
429 final boolean isFalse = "false".equals(value);
430
431 if (isTrue || isFalse) {
432 options.setDefineToBooleanLiteral(key, isTrue);
433 } else {
434 try {
435 double dblTemp = Double.parseDouble((String) value);
436 options.setDefineToDoubleLiteral(key, dblTemp);
437 } catch (NumberFormatException nfe) {
438 // Not a number, assume string
439 options.setDefineToStringLiteral(key, (String) value);
440 }
441 }
442
443 success = true;
444 } else if (value instanceof Boolean) {
445 options.setDefineToBooleanLiteral(key, (Boolean) value);
446 success = true;
447 } else if (value instanceof Integer) {
448 options.setDefineToNumberLiteral(key, (Integer) value);
449 success = true;
450 } else if (value instanceof Double) {
451 options.setDefineToDoubleLiteral(key, (Double) value);
452 success = true;
453 }
454
455 return success;
456 }
457
458 private Compiler createCompiler(CompilerOptions options) {
459 Compiler compiler = new Compiler();
460 MessageFormatter formatter =
461 options.errorFormat.toFormatter(compiler, false);
462 AntErrorManager errorManager = new AntErrorManager(formatter, this);
463 compiler.setErrorManager(errorManager);
464 return compiler;
465 }
466
467 private List<SourceFile> findExternFiles() {
468 List<SourceFile> files = Lists.newLinkedList();
469 if (!this.customExternsOnly) {
470 files.addAll(getDefaultExterns());
471 }
472
473 for (FileList list : this.externFileLists) {
474 files.addAll(findJavaScriptFiles(list));
475 }
476
477 return files;
478 }
479
480 private List<SourceFile> findSourceFiles() {
481 List<SourceFile> files = Lists.newLinkedList();
482
483 for (FileList list : this.sourceFileLists) {
484 files.addAll(findJavaScriptFiles(list));
485 }
486
487 for (Path list : this.sourcePaths) {
488 files.addAll(findJavaScriptFiles(list));
489 }
490
491 return files;
492 }
493
494 /**
495 * Translates an Ant file list into the file format that the compiler
496 * expects.
497 */
498 private List<SourceFile> findJavaScriptFiles(FileList fileList) {
499 List<SourceFile> files = Lists.newLinkedList();
500 File baseDir = fileList.getDir(getProject());
501
502 for (String included : fileList.getFiles(getProject())) {
503 files.add(SourceFile.fromFile(new File(baseDir, included),
504 Charset.forName(encoding)));
505 }
506
507 return files;
508 }
509
510 /**
511 * Translates an Ant Path into the file list format that the compiler
512 * expects.
513 */
514 private List<SourceFile> findJavaScriptFiles(Path path) {
515 List<SourceFile> files = Lists.newArrayList();
516
517 for (String included : path.list()) {
518 files.add(SourceFile.fromFile(new File(included),
519 Charset.forName(encoding)));
520 }
521
522 return files;
523 }
524
525 /**
526 * Gets the default externs set.
527 *
528 * Adapted from {@link CommandLineRunner}.
529 */
530 private List<SourceFile> getDefaultExterns() {
531 try {
532 return CommandLineRunner.getDefaultExterns();
533 } catch (IOException e) {
534 throw new BuildException(e);
535 }
536 }
537
538 private void writeResult(String source) {
539 if (this.outputFile.getParentFile().mkdirs()) {
540 log("Created missing parent directory " +
541 this.outputFile.getParentFile(), Project.MSG_DEBUG);
542 }
543
544 try {
545 OutputStreamWriter out = new OutputStreamWriter(
546 new FileOutputStream(this.outputFile), outputEncoding);
547 out.append(source);
548 out.flush();
549 out.close();
550 } catch (IOException e) {
551 throw new BuildException(e);
552 }
553
554 log("Compiled JavaScript written to " + this.outputFile.getAbsolutePath(),
555 Project.MSG_DEBUG);
556 }
557
558 /**
559 * Determine if compilation must actually happen, i.e. if any input file
560 * (extern or source) has changed after the outputFile was last modified.
561 *
562 * @return true if compilation should happen
563 */
564 private boolean isStale() {
565 long lastRun = outputFile.lastModified();
566 long sourcesLastModified = Math.max(
567 getLastModifiedTime(this.sourceFileLists),
568 getLastModifiedTime(this.sourcePaths));
569 long externsLastModified = getLastModifiedTime(this.externFileLists);
570
571 return lastRun <= sourcesLastModified || lastRun <= externsLastModified;
572 }
573
574 /**
575 * Returns the most recent modified timestamp of the file collection.
576 *
577 * Note: this must be combined into one method to account for both
578 * Path and FileList erasure types.
579 *
580 * @param fileLists Collection of FileList or Path
581 * @return Most recent modified timestamp
582 */
583 private long getLastModifiedTime(List<?> fileLists) {
584 long lastModified = 0;
585
586 for (Object entry : fileLists) {
587 if (entry instanceof FileList) {
588 FileList list = (FileList) entry;
589
590 for (String fileName : list.getFiles(this.getProject())) {
591 File path = list.getDir(this.getProject());
592 File file = new File(path, fileName);
593 lastModified = Math.max(getLastModifiedTime(file), lastModified);
594 }
595 } else if (entry instanceof Path) {
596 Path path = (Path) entry;
597 for (String src : path.list()) {
598 File file = new File(src);
599 lastModified = Math.max(getLastModifiedTime(file), lastModified);
600 }
601 }
602 }
603
604 return lastModified;
605 }
606
607 /**
608 * Returns the last modified timestamp of the given File.
609 */
610 private long getLastModifiedTime(File file) {
611 long fileLastModified = file.lastModified();
612 // If the file is absent, we don't know if it changed (maybe was deleted),
613 // so assume it has just changed.
614 if (fileLastModified == 0) {
615 fileLastModified = new Date().getTime();
616 }
617 return fileLastModified;
618 }
619
620 public void setSourceMapFormat(String format) {
621 this.sourceMapFormat = format;
622 }
623
624 public void setSourceMapOutputFile(File sourceMapOutputFile) {
625 this.sourceMapOutputFile = sourceMapOutputFile;
626 }
627 }