-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
AbstractCommandLineRunner.java
2866 lines (2492 loc) · 92.5 KB
/
AbstractCommandLineRunner.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2009 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import static java.nio.charset.StandardCharsets.US_ASCII;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.io.ByteStreams;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.google.javascript.jscomp.CompilerOptions.JsonStreamMode;
import com.google.javascript.jscomp.CompilerOptions.OutputJs;
import com.google.javascript.jscomp.CompilerOptions.TweakProcessing;
import com.google.javascript.jscomp.deps.ClosureBundler;
import com.google.javascript.jscomp.deps.ModuleLoader;
import com.google.javascript.jscomp.deps.SourceCodeEscapers;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.TokenStream;
import com.google.protobuf.CodedOutputStream;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.Flushable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.annotation.Nullable;
/**
* Implementations of AbstractCommandLineRunner translate flags into Java
* API calls on the Compiler. AbstractCompiler contains common flags and logic
* to make that happen.
*
* This class may be extended and used to create other Java classes
* that behave the same as running the Compiler from the command line. Example:
*
* <pre>
* class MyCommandLineRunner extends
* AbstractCommandLineRunner<MyCompiler, MyOptions> {
* MyCommandLineRunner(String[] args) {
* super(args);
* }
*
* @Override
* protected MyOptions createOptions() {
* MyOptions options = new MyOptions();
* CompilerFlagTranslator.setOptionsFromFlags(options);
* addMyCrazyCompilerPassThatOutputsAnExtraFile(options);
* return options;
* }
*
* @Override
* protected MyCompiler createCompiler() {
* return new MyCompiler();
* }
*
* public static void main(String[] args) {
* (new MyCommandLineRunner(args)).run();
* }
* }
* </pre>
*
* @author bolinfest@google.com (Michael Bolin)
*/
@GwtIncompatible("Unnecessary")
public abstract class AbstractCommandLineRunner<A extends Compiler,
B extends CompilerOptions> {
static final DiagnosticType OUTPUT_SAME_AS_INPUT_ERROR = DiagnosticType.error(
"JSC_OUTPUT_SAME_AS_INPUT_ERROR",
"Bad output file (already listed as input file): {0}");
static final DiagnosticType COULD_NOT_SERIALIZE_AST = DiagnosticType.error(
"JSC_COULD_NOT_SERIALIZE_AST",
"Could not serialize ast to: {0}");
static final DiagnosticType COULD_NOT_DESERIALIZE_AST = DiagnosticType.error(
"JSC_COULD_NOT_DESERIALIZE_AST",
"Could not deserialize ast from: {0}");
static final DiagnosticType NO_TREE_GENERATED_ERROR = DiagnosticType.error(
"JSC_NO_TREE_GENERATED_ERROR",
"Code contains errors. No tree was generated.");
static final DiagnosticType INVALID_MODULE_SOURCEMAP_PATTERN =
DiagnosticType.error(
"JSC_INVALID_MODULE_SOURCEMAP_PATTERN",
"When using --module flags, the --create_source_map flag must contain "
+ "%outname% in the value.");
static final DiagnosticType CONFLICTING_DUPLICATE_ZIP_CONTENTS = DiagnosticType.error(
"JSC_CONFLICTING_DUPLICATE_ZIP_CONTENTS",
"Two zip entries containing conflicting contents with the same relative path.\n"
+ "Entry 1: {0}\n"
+ "Entry 2: {1}");
static final String WAITING_FOR_INPUT_WARNING =
"The compiler is waiting for input via stdin.";
private final CommandLineConfig config;
private final InputStream in;
private final PrintStream defaultJsOutput;
private final PrintStream err;
private A compiler;
private Charset inputCharset;
// NOTE(nicksantos): JSCompiler has always used ASCII as the default
// output charset. This was done to solve legacy problems with
// bad proxies, etc. We are not sure if these issues are still problems,
// and changing the encoding would require a big obnoxious migration plan.
//
// New outputs should use outputCharset2, which is how I would have
// designed this if I had a time machine.
private Charset outputCharset2;
private Charset legacyOutputCharset;
private boolean testMode = false;
private Supplier<List<SourceFile>> externsSupplierForTesting = null;
private Supplier<List<SourceFile>> inputsSupplierForTesting = null;
private Supplier<List<JSModule>> modulesSupplierForTesting = null;
private Function<Integer, Void> exitCodeReceiver = SystemExitCodeReceiver.INSTANCE;
private Map<String, String> rootRelativePathsMap = null;
private Map<String, String> parsedModuleWrappers = null;
private final Gson gson;
static final String OUTPUT_MARKER = "%output%";
private static final String OUTPUT_MARKER_JS_STRING = "%output|jsstring%";
private final List<JsonFileSpec> filesToStreamOut = new ArrayList<>();
AbstractCommandLineRunner() {
this(System.in, System.out, System.err);
}
AbstractCommandLineRunner(PrintStream out, PrintStream err) {
this(System.in, out, err);
}
AbstractCommandLineRunner(InputStream in, PrintStream out, PrintStream err) {
this.config = new CommandLineConfig();
this.in = Preconditions.checkNotNull(in);
this.defaultJsOutput = Preconditions.checkNotNull(out);
this.err = Preconditions.checkNotNull(err);
this.gson = new Gson();
}
/**
* Put the command line runner into test mode. In test mode,
* all outputs will be blackholed.
* @param externsSupplier A provider for externs.
* @param inputsSupplier A provider for source inputs.
* @param modulesSupplier A provider for modules. Only one of inputsSupplier
* and modulesSupplier may be non-null.
* @param exitCodeReceiver A receiver for the status code that would
* have been passed to System.exit in non-test mode.
*/
@VisibleForTesting
void enableTestMode(
Supplier<List<SourceFile>> externsSupplier,
Supplier<List<SourceFile>> inputsSupplier,
Supplier<List<JSModule>> modulesSupplier,
Function<Integer, Void> exitCodeReceiver) {
Preconditions.checkArgument(
inputsSupplier == null ^ modulesSupplier == null);
testMode = true;
this.externsSupplierForTesting = externsSupplier;
this.inputsSupplierForTesting = inputsSupplier;
this.modulesSupplierForTesting = modulesSupplier;
this.exitCodeReceiver = exitCodeReceiver;
}
/**
* @param newExitCodeReceiver receives a non-zero integer to indicate a
* problem during execution or 0i to indicate success.
*/
public void setExitCodeReceiver(Function<Integer, Void> newExitCodeReceiver) {
this.exitCodeReceiver = Preconditions.checkNotNull(newExitCodeReceiver);
}
/**
* Returns whether we're in test mode.
*/
protected boolean isInTestMode() {
return testMode;
}
/**
* Returns whether output should be a JSON stream.
*/
private boolean isOutputInJson() {
return config.jsonStreamMode == JsonStreamMode.OUT
|| config.jsonStreamMode == JsonStreamMode.BOTH;
}
/**
* Get the command line config, so that it can be initialized.
*/
protected CommandLineConfig getCommandLineConfig() {
return config;
}
/**
* Returns the instance of the Compiler to use when {@link #run()} is
* called.
*/
protected abstract A createCompiler();
/**
* Returns the instance of the Options to use when {@link #run()} is called.
* createCompiler() is called before createOptions(), so getCompiler()
* will not return null when createOptions() is called.
*/
protected abstract B createOptions();
/**
* The warning classes that are available from the command-line.
*/
protected DiagnosticGroups getDiagnosticGroups() {
if (compiler == null) {
return new DiagnosticGroups();
}
return compiler.getDiagnosticGroups();
}
/**
* A helper function for creating the dependency options object.
*/
static DependencyOptions createDependencyOptions(
CompilerOptions.DependencyMode dependencyMode,
List<ModuleIdentifier> entryPoints) {
if (dependencyMode == CompilerOptions.DependencyMode.STRICT) {
if (entryPoints.isEmpty()) {
throw new FlagUsageException(
"When dependency_mode=STRICT, you must " + "specify at least one entry_point");
}
return new DependencyOptions()
.setDependencyPruning(true)
.setDependencySorting(true)
.setMoocherDropping(true)
.setEntryPoints(entryPoints);
} else if (dependencyMode == CompilerOptions.DependencyMode.LOOSE || !entryPoints.isEmpty()) {
return new DependencyOptions()
.setDependencyPruning(true)
.setDependencySorting(true)
.setMoocherDropping(false)
.setEntryPoints(entryPoints);
}
return null;
}
protected abstract void addWhitelistWarningsGuard(
CompilerOptions options, File whitelistFile);
protected static void setWarningGuardOptions(
CompilerOptions options,
ArrayList<FlagEntry<CheckLevel>> warningGuards,
DiagnosticGroups diagnosticGroups) {
if (warningGuards != null) {
for (FlagEntry<CheckLevel> entry : warningGuards) {
if ("*".equals(entry.value)) {
Set<String> groupNames = diagnosticGroups.getRegisteredGroups().keySet();
for (String groupName : groupNames) {
if (!DiagnosticGroups.wildcardExcludedGroups.contains(groupName)) {
diagnosticGroups.setWarningLevel(options, groupName, entry.flag);
}
}
} else {
diagnosticGroups.setWarningLevel(options, entry.value, entry.flag);
}
}
}
}
/**
* Sets options based on the configurations set flags API.
* Called during the run() run() method.
* If you want to ignore the flags API, or interpret flags your own way,
* then you should override this method.
*/
protected void setRunOptions(CompilerOptions options) throws IOException {
DiagnosticGroups diagnosticGroups = getDiagnosticGroups();
setWarningGuardOptions(options, config.warningGuards, diagnosticGroups);
if (!config.warningsWhitelistFile.isEmpty()) {
addWhitelistWarningsGuard(options, new File(config.warningsWhitelistFile));
}
if (!config.hideWarningsFor.isEmpty()) {
options.addWarningsGuard(new ShowByPathWarningsGuard(
config.hideWarningsFor.toArray(new String[] {}),
ShowByPathWarningsGuard.ShowType.EXCLUDE));
}
createDefineOrTweakReplacements(config.define, options, false);
options.setTweakProcessing(config.tweakProcessing);
createDefineOrTweakReplacements(config.tweak, options, true);
DependencyOptions depOptions =
createDependencyOptions(config.dependencyMode, config.entryPoints);
if (depOptions != null) {
options.setDependencyOptions(depOptions);
}
options.devMode = config.jscompDevMode;
options.setCodingConvention(config.codingConvention);
options.setSummaryDetailLevel(config.summaryDetailLevel);
options.setTrustedStrings(true);
legacyOutputCharset = options.outputCharset = getLegacyOutputCharset();
outputCharset2 = getOutputCharset2();
inputCharset = getInputCharset();
if (config.jsOutputFile.length() > 0) {
if (config.skipNormalOutputs) {
throw new FlagUsageException("skip_normal_outputs and js_output_file"
+ " cannot be used together.");
}
}
if (config.skipNormalOutputs && config.printAst) {
throw new FlagUsageException("skip_normal_outputs and print_ast cannot"
+ " be used together.");
}
if (config.skipNormalOutputs && config.printTree) {
throw new FlagUsageException("skip_normal_outputs and print_tree cannot"
+ " be used together.");
}
if (config.createSourceMap.length() > 0) {
options.sourceMapOutputPath = config.createSourceMap;
} else if (isOutputInJson()) {
options.sourceMapOutputPath = "%outname%";
}
options.sourceMapDetailLevel = config.sourceMapDetailLevel;
options.sourceMapFormat = config.sourceMapFormat;
options.sourceMapLocationMappings = config.sourceMapLocationMappings;
options.parseInlineSourceMaps = config.parseInlineSourceMaps;
options.applyInputSourceMaps = config.applyInputSourceMaps;
ImmutableMap.Builder<String, SourceMapInput> inputSourceMaps
= new ImmutableMap.Builder<>();
for (Map.Entry<String, String> files :
config.sourceMapInputFiles.entrySet()) {
SourceFile sourceMap = SourceFile.fromFile(files.getValue());
inputSourceMaps.put(
files.getKey(), new SourceMapInput(sourceMap));
}
options.inputSourceMaps = inputSourceMaps.build();
if (!config.variableMapInputFile.isEmpty()) {
options.inputVariableMap =
VariableMap.load(config.variableMapInputFile);
}
if (!config.propertyMapInputFile.isEmpty()) {
options.inputPropertyMap =
VariableMap.load(config.propertyMapInputFile);
}
if (!config.outputManifests.isEmpty()) {
Set<String> uniqueNames = new HashSet<>();
for (String filename : config.outputManifests) {
if (!uniqueNames.add(filename)) {
throw new FlagUsageException("output_manifest flags specify " +
"duplicate file names: " + filename);
}
}
}
if (!config.outputBundles.isEmpty()) {
Set<String> uniqueNames = new HashSet<>();
for (String filename : config.outputBundles) {
if (!uniqueNames.add(filename)) {
throw new FlagUsageException("output_bundle flags specify " +
"duplicate file names: " + filename);
}
}
}
options.transformAMDToCJSModules = config.transformAMDToCJSModules;
options.processCommonJSModules = config.processCommonJSModules;
options.moduleRoots = config.moduleRoots;
options.angularPass = config.angularPass;
options.setNewTypeInference(config.useNewTypeInference);
options.instrumentationTemplateFile = config.instrumentationTemplateFile;
}
protected final A getCompiler() {
return compiler;
}
/**
* @return a mutable list
* @throws IOException
*/
public static List<SourceFile> getBuiltinExterns(CompilerOptions.Environment env)
throws IOException {
InputStream input = AbstractCommandLineRunner.class.getResourceAsStream(
"/externs.zip");
if (input == null) {
// In some environments, the externs.zip is relative to this class.
input = AbstractCommandLineRunner.class.getResourceAsStream("externs.zip");
}
Preconditions.checkNotNull(input);
ZipInputStream zip = new ZipInputStream(input);
String envPrefix = env.toString().toLowerCase() + "/";
Map<String, SourceFile> mapFromExternsZip = new HashMap<>();
for (ZipEntry entry = null; (entry = zip.getNextEntry()) != null; ) {
String filename = entry.getName();
// Always load externs in the root folder.
// If the non-core-JS externs are organized in subfolders, only load
// the ones in a subfolder matching the specified environment. Strip the subfolder.
if (filename.contains("/")) {
if (!filename.startsWith(envPrefix)) {
continue;
}
filename = filename.substring(envPrefix.length()); // remove envPrefix, including '/'
}
BufferedInputStream entryStream = new BufferedInputStream(
ByteStreams.limit(zip, entry.getSize()));
mapFromExternsZip.put(filename,
SourceFile.fromInputStream(
// Give the files an odd prefix, so that they do not conflict
// with the user's files.
"externs.zip//" + filename,
entryStream,
UTF_8));
}
return DefaultExterns.prepareExterns(env, mapFromExternsZip);
}
/**
* Runs the Compiler and calls System.exit() with the exit status of the
* compiler.
*/
public final void run() {
int result = 0;
int runs = 1;
try {
for (int i = 0; i < runs && result == 0; i++) {
result = doRun();
}
} catch (AbstractCommandLineRunner.FlagUsageException e) {
err.println(e.getMessage());
result = -1;
} catch (Throwable t) {
t.printStackTrace(err);
result = -2;
}
exitCodeReceiver.apply(result);
}
/**
* Returns the PrintStream for writing errors associated with this
* AbstractCommandLineRunner.
*/
protected final PrintStream getErrorPrintStream() {
return err;
}
/**
* An exception thrown when command-line flags are used incorrectly.
*/
public static class FlagUsageException extends RuntimeException {
private static final long serialVersionUID = 1L;
public FlagUsageException(String message) {
super(message);
}
}
public List<JsonFileSpec> parseJsonFilesFromInputStream() throws IOException {
List<JsonFileSpec> jsonFiles = new ArrayList<>();
try (JsonReader reader = new JsonReader(new InputStreamReader(this.in, inputCharset))) {
reader.beginArray();
while (reader.hasNext()) {
JsonFileSpec jsonFile = gson.fromJson(reader, JsonFileSpec.class);
jsonFiles.add(jsonFile);
}
reader.endArray();
}
return jsonFiles;
}
/**
* Creates inputs from a list of files.
*
* Can be overridden by subclasses who want to pull files from different
* places.
*
* @param files A list of flag entries indicates js and zip file names.
* @param allowStdIn Whether '-' is allowed appear as a filename to represent
* stdin. If true, '-' is only allowed to appear once.
* @param jsModuleSpecs A list js module specs.
* @return An array of inputs
*/
protected List<SourceFile> createInputs(
List<FlagEntry<JsSourceType>> files, boolean allowStdIn, List<JsModuleSpec> jsModuleSpecs)
throws IOException {
return createInputs(files, null /* jsonFiles */, allowStdIn, jsModuleSpecs);
}
/**
* Creates inputs from a list of source files and json files.
*
* Can be overridden by subclasses who want to pull files from different
* places.
*
* @param files A list of flag entries indicates js and zip file names.
* @param jsonFiles A list of json encoded files.
* @param jsModuleSpecs A list js module specs.
* @return An array of inputs
*/
protected List<SourceFile> createInputs(
List<FlagEntry<JsSourceType>> files,
List<JsonFileSpec> jsonFiles,
List<JsModuleSpec> jsModuleSpecs)
throws IOException {
return createInputs(files, jsonFiles, false, jsModuleSpecs);
}
/**
* Check that relative paths inside zip files are unique, since multiple files
* with the same path inside different zips are considered duplicate inputs.
* Parameter {@code sourceFiles} may be modified if duplicates are removed.
*/
public static List<JSError> removeDuplicateZipEntries(
List<SourceFile> sourceFiles, List<JsModuleSpec> jsModuleSpecs) throws IOException {
ImmutableList.Builder<JSError> errors = ImmutableList.builder();
Map<String, SourceFile> sourceFilesByName = new HashMap<>();
Iterator<SourceFile> fileIterator = sourceFiles.iterator();
int currentFileIndex = 0;
Iterator<JsModuleSpec> moduleIterator = jsModuleSpecs.iterator();
// Tracks the total number of js files for current module and all the previous modules.
int cumulatedJsFileNum = 0;
JsModuleSpec currentModule = null;
while (fileIterator.hasNext()) {
SourceFile sourceFile = fileIterator.next();
currentFileIndex++;
// Check whether we reached the next module.
if (moduleIterator.hasNext() && currentFileIndex > cumulatedJsFileNum) {
currentModule = moduleIterator.next();
cumulatedJsFileNum += currentModule.numJsFiles;
}
String fullPath = sourceFile.getName();
if (!fullPath.contains("!/")) {
// Not a zip file
continue;
}
String relativePath = fullPath.split("!")[1];
if (!sourceFilesByName.containsKey(relativePath)) {
sourceFilesByName.put(relativePath, sourceFile);
} else {
SourceFile firstSourceFile = sourceFilesByName.get(relativePath);
if (firstSourceFile.getCode().equals(sourceFile.getCode())) {
errors.add(JSError.make(
SourceFile.DUPLICATE_ZIP_CONTENTS, firstSourceFile.getName(), sourceFile.getName()));
fileIterator.remove();
if (currentModule != null) {
currentModule.numJsFiles--;
}
} else {
errors.add(JSError.make(
CONFLICTING_DUPLICATE_ZIP_CONTENTS, firstSourceFile.getName(), sourceFile.getName()));
}
}
}
return errors.build();
}
/**
* Creates inputs from a list of source files, zips and json files.
*
* Can be overridden by subclasses who want to pull files from different
* places.
*
* @param files A list of flag entries indicates js and zip file names
* @param jsonFiles A list of json encoded files.
* @param allowStdIn Whether '-' is allowed appear as a filename to represent
* stdin. If true, '-' is only allowed to appear once.
* @param jsModuleSpecs A list js module specs.
* @return An array of inputs
*/
protected List<SourceFile> createInputs(
List<FlagEntry<JsSourceType>> files,
List<JsonFileSpec> jsonFiles,
boolean allowStdIn,
List<JsModuleSpec> jsModuleSpecs)
throws IOException {
List<SourceFile> inputs = new ArrayList<>(files.size());
boolean usingStdin = false;
int jsModuleIndex = 0;
JsModuleSpec jsModuleSpec = Iterables.getFirst(jsModuleSpecs, null);
int cumulatedInputFilesExpected =
jsModuleSpec == null ? Integer.MAX_VALUE : jsModuleSpec.numInputs;
for (int i = 0; i < files.size(); i++) {
FlagEntry<JsSourceType> file = files.get(i);
String filename = file.value;
if (file.flag == JsSourceType.JS_ZIP) {
if (!"-".equals(filename)) {
List<SourceFile> newFiles = SourceFile.fromZipFile(filename, inputCharset);
// Update the manifest maps for new zip entries.
if (rootRelativePathsMap.containsKey(filename)) {
String rootFilename = rootRelativePathsMap.get(filename);
for (SourceFile zipEntry : newFiles) {
String zipEntryName = zipEntry.getName();
Preconditions.checkState(zipEntryName.contains(filename));
String zipmap = zipEntryName.replace(filename, rootFilename);
rootRelativePathsMap.put(zipEntryName, zipmap);
}
}
inputs.addAll(newFiles);
if (jsModuleSpec != null) {
jsModuleSpec.numJsFiles += newFiles.size() - 1;
}
}
} else if (!"-".equals(filename)) {
SourceFile newFile = SourceFile.fromFile(filename, inputCharset);
inputs.add(newFile);
} else {
if (!allowStdIn) {
throw new FlagUsageException("Can't specify stdin.");
}
if (usingStdin) {
throw new FlagUsageException("Can't specify stdin twice.");
}
if (!config.outputManifests.isEmpty()) {
throw new FlagUsageException("Manifest files cannot be generated " +
"when the input is from stdin.");
}
if (!config.outputBundles.isEmpty()) {
throw new FlagUsageException("Bundle files cannot be generated " +
"when the input is from stdin.");
}
this.err.println(WAITING_FOR_INPUT_WARNING);
inputs.add(SourceFile.fromInputStream("stdin", this.in, inputCharset));
usingStdin = true;
}
if (i >= cumulatedInputFilesExpected - 1) {
jsModuleIndex++;
if (jsModuleIndex < jsModuleSpecs.size()) {
jsModuleSpec = jsModuleSpecs.get(jsModuleIndex);
cumulatedInputFilesExpected += jsModuleSpec.numInputs;
}
}
}
if (jsonFiles != null) {
for (JsonFileSpec jsonFile : jsonFiles) {
inputs.add(SourceFile.fromCode(jsonFile.getPath(), jsonFile.getSrc()));
}
}
for (JSError error : removeDuplicateZipEntries(inputs, jsModuleSpecs)) {
compiler.report(error);
}
return inputs;
}
/**
* Creates JS source code inputs from a list of files.
*/
private List<SourceFile> createSourceInputs(
List<JsModuleSpec> jsModuleSpecs,
List<FlagEntry<JsSourceType>> files,
List<JsonFileSpec> jsonFiles)
throws IOException {
if (isInTestMode()) {
return inputsSupplierForTesting != null ? inputsSupplierForTesting.get()
: null;
}
if (files.isEmpty() && jsonFiles == null) {
// Request to read from stdin.
files = Collections.singletonList(
new FlagEntry<JsSourceType>(JsSourceType.JS, "-"));
}
try {
if (jsonFiles != null) {
return createInputs(files, jsonFiles, jsModuleSpecs);
} else {
return createInputs(files, true, jsModuleSpecs);
}
} catch (FlagUsageException e) {
throw new FlagUsageException("Bad --js flag. " + e.getMessage());
}
}
/**
* Creates JS extern inputs from a list of files.
*/
private List<SourceFile> createExternInputs(List<String> files) throws IOException {
if (files.isEmpty()) {
return ImmutableList.of(SourceFile.fromCode("/dev/null", ""));
}
List<FlagEntry<JsSourceType>> externFiles = new ArrayList<>();
for (String file : files) {
externFiles.add(new FlagEntry<JsSourceType>(JsSourceType.EXTERN, file));
}
try {
return createInputs(externFiles, false, new ArrayList<JsModuleSpec>());
} catch (FlagUsageException e) {
throw new FlagUsageException("Bad --externs flag. " + e.getMessage());
}
}
/**
* Creates module objects from a list of js module specifications.
*
* @param specs A list of js module specifications, not null or empty.
* @param inputs A list of JS file paths, not null
* @return An array of module objects
*/
List<JSModule> createJsModules(List<JsModuleSpec> specs, List<SourceFile> inputs)
throws IOException {
if (isInTestMode()) {
return modulesSupplierForTesting.get();
}
Preconditions.checkState(specs != null);
Preconditions.checkState(!specs.isEmpty());
Preconditions.checkState(inputs != null);
List<String> moduleNames = new ArrayList<>(specs.size());
Map<String, JSModule> modulesByName = new LinkedHashMap<>();
Map<String, Integer> modulesFileCountMap = new LinkedHashMap<>();
int numJsFilesExpected = 0;
int minJsFilesRequired = 0;
for (JsModuleSpec spec : specs) {
checkModuleName(spec.name);
if (modulesByName.containsKey(spec.name)) {
throw new FlagUsageException("Duplicate module name: " + spec.name);
}
JSModule module = new JSModule(spec.name);
for (String dep : spec.deps) {
JSModule other = modulesByName.get(dep);
if (other == null) {
throw new FlagUsageException("Module '" + spec.name
+ "' depends on unknown module '" + dep
+ "'. Be sure to list modules in dependency order.");
}
module.addDependency(other);
}
// We will allow modules of zero input.
if (spec.numJsFiles < 0) {
numJsFilesExpected = -1;
} else {
minJsFilesRequired += spec.numJsFiles;
}
if (numJsFilesExpected >= 0) {
numJsFilesExpected += spec.numJsFiles;
}
// Add modules in reverse order so that source files are allocated to
// modules in reverse order. This allows the first module
// (presumably the base module) to have a size of 'auto'
moduleNames.add(0, spec.name);
modulesFileCountMap.put(spec.name, spec.numJsFiles);
modulesByName.put(spec.name, module);
}
final int totalNumJsFiles = inputs.size();
if (numJsFilesExpected >= 0 || minJsFilesRequired > totalNumJsFiles) {
if (minJsFilesRequired > totalNumJsFiles) {
numJsFilesExpected = minJsFilesRequired;
}
if (numJsFilesExpected > totalNumJsFiles) {
throw new FlagUsageException("Not enough JS files specified. Expected "
+ numJsFilesExpected + " but found " + totalNumJsFiles);
} else if (numJsFilesExpected < totalNumJsFiles) {
throw new FlagUsageException("Too many JS files specified. Expected "
+ numJsFilesExpected + " but found " + totalNumJsFiles);
}
}
int numJsFilesLeft = totalNumJsFiles;
int moduleIndex = 0;
for (String moduleName : moduleNames) {
// Parse module inputs.
int numJsFiles = modulesFileCountMap.get(moduleName);
JSModule module = modulesByName.get(moduleName);
// Check if the first js module specified 'auto' for the number of files
if (moduleIndex == moduleNames.size() - 1 && numJsFiles == -1) {
numJsFiles = numJsFilesLeft;
}
List<SourceFile> moduleFiles =
inputs.subList(numJsFilesLeft - numJsFiles, numJsFilesLeft);
for (SourceFile input : moduleFiles) {
module.add(input);
}
numJsFilesLeft -= numJsFiles;
moduleIndex++;
}
return new ArrayList<>(modulesByName.values());
}
/**
* Validates the module name. Can be overridden by subclasses.
* @param name The module name
*/
protected void checkModuleName(String name) {
if (!TokenStream.isJSIdentifier(name)) {
throw new FlagUsageException("Invalid module name: '" + name + "'");
}
}
/**
* Parses module wrapper specifications.
*
* @param specs A list of module wrapper specifications, not null. The spec
* format is: <code>name:wrapper</code>. Wrappers.
* @param modules The JS modules whose wrappers are specified
* @return A map from module name to module wrapper. Modules with no wrapper
* will have the empty string as their value in this map.
*/
static Map<String, String> parseModuleWrappers(List<String> specs, List<JSModule> modules) {
Preconditions.checkState(specs != null);
Map<String, String> wrappers = Maps.newHashMapWithExpectedSize(modules.size());
// Prepopulate the map with module names.
for (JSModule m : modules) {
wrappers.put(m.getName(), "");
}
for (String spec : specs) {
// Format is "<name>:<wrapper>".
int pos = spec.indexOf(':');
if (pos == -1) {
throw new FlagUsageException("Expected module wrapper to have "
+ "<name>:<wrapper> format: " + spec);
}
// Parse module name.
String name = spec.substring(0, pos);
if (!wrappers.containsKey(name)) {
throw new FlagUsageException("Unknown module: '" + name + "'");
}
String wrapper = spec.substring(pos + 1);
if (!wrapper.contains("%s")) {
throw new FlagUsageException("No %s placeholder in module wrapper: '"
+ wrapper + "'");
}
wrappers.put(name, wrapper);
}
return wrappers;
}
private String getModuleOutputFileName(JSModule m) {
return config.moduleOutputPathPrefix + m.getName() + ".js";
}
@VisibleForTesting
void writeModuleOutput(Appendable out, JSModule m) throws IOException {
if (parsedModuleWrappers == null) {
parsedModuleWrappers = parseModuleWrappers(
config.moduleWrapper,
ImmutableList.copyOf(
compiler.getDegenerateModuleGraph().getAllModules()));
}
String fileName = getModuleOutputFileName(m);
String baseName = new File(fileName).getName();
writeOutput(out, compiler, m,
parsedModuleWrappers.get(m.getName()).replace("%basename%", baseName),
"%s", null);
}
/**
* Writes code to an output stream, optionally wrapping it in an arbitrary
* wrapper that contains a placeholder where the code should be inserted.
* @param module Which module to write. If this is null, write the entire AST.
*/
static void writeOutput(Appendable out, Compiler compiler, @Nullable JSModule module,
String wrapper, String codePlaceholder,
@Nullable Function<String, String> escaper)
throws IOException {
if (compiler.getOptions().outputJs == OutputJs.SENTINEL) {
out.append("// No JS output because the compiler was run in checks-only mode.\n");
return;
}
Preconditions.checkState(compiler.getOptions().outputJs == OutputJs.NORMAL);
String code = module == null ? compiler.toSource() : compiler.toSource(module);
writeOutput(out, compiler, code, wrapper, codePlaceholder, escaper);
}
/**
* Writes code to an output stream, optionally wrapping it in an arbitrary
* wrapper that contains a placeholder where the code should be inserted.
*/
static void writeOutput(Appendable out, Compiler compiler, String code,
String wrapper, String codePlaceholder,
@Nullable Function<String, String> escaper)
throws IOException {
int pos = wrapper.indexOf(codePlaceholder);
if (pos != -1) {
String prefix = "";
if (pos > 0) {
prefix = wrapper.substring(0, pos);
out.append(prefix);
}
out.append(escaper == null ? code : escaper.apply(code));
int suffixStart = pos + codePlaceholder.length();
if (suffixStart != wrapper.length()) {
// Something after placeholder?
out.append(wrapper.substring(suffixStart));
}
// Make sure we always end output with a line feed.
out.append('\n');
// If we have a source map, adjust its offsets to match
// the code WITHIN the wrapper.
if (compiler != null && compiler.getSourceMap() != null) {
compiler.getSourceMap().setWrapperPrefix(prefix);
}
} else {
out.append(code);
out.append('\n');
}
}
/**
* Creates any directories necessary to write a file that will have a given
* path prefix.
*/