-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
CommandLineRunner.java
1841 lines (1599 loc) · 66.5 KB
/
CommandLineRunner.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.UTF_8;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Ascii;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multimap;
import com.google.common.io.Files;
import com.google.javascript.jscomp.CompilerOptions.IsolationMode;
import com.google.javascript.jscomp.SourceMap.LocationMapping;
import com.google.javascript.jscomp.deps.ModuleLoader;
import com.google.javascript.rhino.TokenStream;
import com.google.protobuf.TextFormat;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.lang.reflect.AnnotatedElement;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.NamedOptionDef;
import org.kohsuke.args4j.Option;
import org.kohsuke.args4j.OptionDef;
import org.kohsuke.args4j.OptionHandlerFilter;
import org.kohsuke.args4j.spi.FieldSetter;
import org.kohsuke.args4j.spi.OptionHandler;
import org.kohsuke.args4j.spi.Parameters;
import org.kohsuke.args4j.spi.Setter;
import org.kohsuke.args4j.spi.StringOptionHandler;
/**
* CommandLineRunner translates flags into Java API calls on the Compiler.
*
* This class may be extended and used to create other Java classes
* that behave the same as running the Compiler from the command line. If you
* want to run the compiler in-process in Java, you should look at this class
* for hints on what API calls to make, but you should not use this class
* directly.
*
* Example:
* <pre>
* class MyCommandLineRunner extends CommandLineRunner {
* MyCommandLineRunner(String[] args) {
* super(args);
* }
*
* {@code @Override} protected CompilerOptions createOptions() {
* CompilerOptions options = super.createOptions();
* addMyCrazyCompilerPassThatOutputsAnExtraFile(options);
* return options;
* }
*
* public static void main(String[] args) {
* MyCommandLineRunner runner = new MyCommandLineRunner(args);
* if (runner.shouldRunCompiler()) {
* runner.run();
* }
* if (runner.hasErrors()) {
* System.exit(-1);
* }
* }
* }
* </pre>
*
* This class is totally not thread-safe.
*
* @author bolinfest@google.com (Michael Bolin)
*/
@GwtIncompatible("Unnecessary")
public class CommandLineRunner extends
AbstractCommandLineRunner<Compiler, CompilerOptions> {
public static final String OUTPUT_MARKER =
AbstractCommandLineRunner.OUTPUT_MARKER;
// UTF-8 BOM is 0xEF, 0xBB, 0xBF, of which character code is 65279.
public static final int UTF8_BOM_CODE = 65279;
// Allowable module name characters that aren't valid in a JS identifier
private static final Pattern extraModuleNameChars = Pattern.compile("[-.]+");
// I don't really care about unchecked warnings in this class.
@SuppressWarnings("unchecked")
private static class Flags {
// Some clients run a few copies of the compiler through CommandLineRunner
// on parallel threads (thankfully, with the same flags),
// so the access to these lists should be synchronized.
private static List<FlagEntry<CheckLevel>> guardLevels =
Collections.synchronizedList(new ArrayList<FlagEntry<CheckLevel>>());
private static List<FlagEntry<JsSourceType>> mixedJsSources =
Collections.synchronizedList(new ArrayList<FlagEntry<JsSourceType>>());
@Option(
name = "--help",
handler = BooleanOptionHandler.class,
usage = "Displays this message on stdout and exit"
)
private boolean displayHelp = false;
@Option(name = "--print_tree",
hidden = true,
handler = BooleanOptionHandler.class,
usage = "Prints out the parse tree and exits")
private boolean printTree = false;
@Option(name = "--print_ast",
hidden = true,
handler = BooleanOptionHandler.class,
usage = "Prints a dot file describing the internal abstract syntax"
+ " tree and exits")
private boolean printAst = false;
@Option(name = "--print_pass_graph",
hidden = true,
handler = BooleanOptionHandler.class,
usage = "Prints a dot file describing the passes that will get run"
+ " and exits")
private boolean printPassGraph = false;
@Option(
name = "--emit_use_strict",
handler = BooleanOptionHandler.class,
usage = "Start output with \"'use strict';\"."
)
private boolean emitUseStrict = true;
@Option(
name = "--strict_mode_input",
handler = BooleanOptionHandler.class,
usage = "Assume input sources are to run in strict mode."
+ " Ignored for language modes earlier than ECMASCRIPT7.")
private boolean strictModeInput = true;
// Turn on (very slow) extra sanity checks for use when modifying the
// compiler.
@Option(
name = "--jscomp_dev_mode",
hidden = true,
//no usage
aliases = {"--dev_mode"}
)
private CompilerOptions.DevMode jscompDevMode = CompilerOptions.DevMode.OFF;
@Option(name = "--logging_level",
hidden = true,
usage = "The logging level (standard java.util.logging.Level"
+ " values) for Compiler progress. Does not control errors or"
+ " warnings for the JavaScript code under compilation")
private String loggingLevel = Level.WARNING.getName();
@Option(name = "--externs",
usage = "The file containing JavaScript externs. You may specify"
+ " multiple")
private List<String> externs = new ArrayList<>();
@Option(name = "--js",
handler = JsOptionHandler.class,
usage = "The JavaScript filename. You may specify multiple. "
+ "The flag name is optional, because args are interpreted as files by default. "
+ "You may also use minimatch-style glob patterns. For example, use "
+ "--js='**.js' --js='!**_test.js' to recursively include all "
+ "js files that do not end in _test.js")
private List<String> js = new ArrayList<>();
@Option(name = "--jszip",
hidden = true,
handler = JsZipOptionHandler.class,
usage = "The JavaScript zip filename. You may specify multiple.")
private List<String> jszip = new ArrayList<>();
@Option(name = "--js_output_file",
usage = "Primary output filename. If not specified, output is "
+ "written to stdout")
private String jsOutputFile = "";
@Option(name = "--module",
usage = "A JavaScript module specification. The format is "
+ "<name>:<num-js-files>[:[<dep>,...][:]]]. Module names must be "
+ "unique. Each dep is the name of a module that this module "
+ "depends on. Modules must be listed in dependency order, and JS "
+ "source files must be listed in the corresponding order. Where "
+ "--module flags occur in relation to --js flags is unimportant. "
+ "<num-js-files> may be set to 'auto' for the first module if it "
+ "has no dependencies. "
+ "Provide the value 'auto' to trigger module creation from CommonJS"
+ "modules.")
private List<String> module = new ArrayList<>();
@Option(name = "--variable_renaming_report",
usage = "File where the serialized version of the variable "
+ "renaming map produced should be saved")
private String variableMapOutputFile = "";
@Option(name = "--create_renaming_reports",
hidden = true,
handler = BooleanOptionHandler.class,
usage = "If true, variable renaming and property renaming report "
+ "files will be produced as {binary name}_vars_renaming_report.out "
+ "and {binary name}_props_renaming_report.out. Note that this flag "
+ "cannot be used in conjunction with either variable_renaming_report "
+ "or property_renaming_report")
private boolean createNameMapFiles = false;
@Option(name = "--property_renaming_report",
usage = "File where the serialized version of the property "
+ "renaming map produced should be saved")
private String propertyMapOutputFile = "";
@Option(name = "--third_party",
handler = BooleanOptionHandler.class,
usage = "Check source validity but do not enforce Closure style "
+ "rules and conventions")
private boolean thirdParty = false;
@Option(name = "--summary_detail_level",
hidden = true,
usage = "Controls how detailed the compilation summary is. Values:"
+ " 0 (never print summary), 1 (print summary only if there are "
+ "errors or warnings), 2 (print summary if the 'checkTypes' "
+ "diagnostic group is enabled, see --jscomp_warning), "
+ "3 (always print summary). The default level is 1")
private int summaryDetailLevel = 1;
@Option(name = "--isolation_mode",
usage = "If set to IIFE the compiler output will follow the form:\n"
+ " (function(){%output%)).call(this);\n"
+ "Options: NONE, IIFE")
private IsolationMode isolationMode = IsolationMode.NONE;
@Option(name = "--output_wrapper",
usage = "Interpolate output into this string at the place denoted"
+ " by the marker token %output%. Use marker token %output|jsstring%"
+ " to do js string escaping on the output.")
private String outputWrapper = "";
@Option(name = "--output_wrapper_file",
usage = "Loads the specified file and passes the file contents to the --output_wrapper"
+ " flag, replacing the value if it exists. This is useful if you want special characters"
+ " like newline in the wrapper.")
private String outputWrapperFile = "";
@Option(name = "--module_wrapper",
usage = "An output wrapper for a JavaScript module (optional). "
+ "The format is <name>:<wrapper>. The module name must correspond "
+ "with a module specified using --module. The wrapper must "
+ "contain %s as the code placeholder. The %basename% placeholder can "
+ "also be used to substitute the base name of the module output file.")
private List<String> moduleWrapper = new ArrayList<>();
@Option(name = "--module_output_path_prefix",
usage = "Prefix for filenames of compiled JS modules. "
+ "<module-name>.js will be appended to this prefix. Directories "
+ "will be created as needed. Use with --module")
private String moduleOutputPathPrefix = "./";
@Option(name = "--create_source_map",
usage = "If specified, a source map file mapping the generated "
+ "source files back to the original source file will be "
+ "output to the specified path. The %outname% placeholder will "
+ "expand to the name of the output file that the source map "
+ "corresponds to.")
private String createSourceMap = "";
@Option(name = "--source_map_format",
hidden = true,
usage = "The source map format to produce. "
+ "Options are V3 and DEFAULT, which are equivalent.")
private SourceMap.Format sourceMapFormat = SourceMap.Format.DEFAULT;
@Option(name = "--source_map_location_mapping",
usage = "Source map location mapping separated by a '|' "
+ "(i.e. filesystem-path|webserver-path)")
private List<String> sourceMapLocationMapping = new ArrayList<>();
@Option(
name = "--source_map_input",
hidden = false,
usage =
"Source map locations for input files, separated by a '|', "
+ "(i.e. input-file-path|input-source-map)"
)
private List<String> sourceMapInputs = new ArrayList<>();
@Option(name = "--parse_inline_source_maps",
handler = BooleanOptionHandler.class,
hidden = true,
usage = "Parse inline source maps (//# sourceMappingURL=data:...)")
private Boolean parseInlineSourceMaps = true;
@Option(name = "--apply_input_source_maps",
handler = BooleanOptionHandler.class,
hidden = true,
usage = "Whether to apply input source maps to the output source map, "
+ "i.e. have the result map back to original inputs")
private boolean applyInputSourceMaps = true;
// Used to define the flag, values are stored by the handler.
@SuppressWarnings("unused")
@Option(
name = "--jscomp_error",
handler = WarningGuardErrorOptionHandler.class,
usage =
"Make the named class of warnings an error. Must be one "
+ "of the error group items. '*' adds all supported."
)
private List<String> jscompError = new ArrayList<>();
// Used to define the flag, values are stored by the handler.
@SuppressWarnings("unused")
@Option(
name = "--jscomp_warning",
handler = WarningGuardWarningOptionHandler.class,
usage =
"Make the named class of warnings a normal warning. Must be one "
+ "of the error group items. '*' adds all supported."
)
private List<String> jscompWarning = new ArrayList<>();
// Used to define the flag, values are stored by the handler.
@SuppressWarnings("unused")
@Option(
name = "--jscomp_off",
handler = WarningGuardOffOptionHandler.class,
usage =
"Turn off the named class of warnings. Must be one "
+ "of the error group items. '*' adds all supported."
)
private List<String> jscompOff = new ArrayList<>();
@Option(name = "--define",
aliases = {"--D", "-D"},
usage = "Override the value of a variable annotated @define. "
+ "The format is <name>[=<val>], where <name> is the name of a @define "
+ "variable and <val> is a boolean, number, or a single-quoted string "
+ "that contains no single quotes. If [=<val>] is omitted, "
+ "the variable is marked true")
private List<String> define = new ArrayList<>();
@Option(name = "--charset",
usage = "Input and output charset for all files. By default, we "
+ "accept UTF-8 as input and output US_ASCII")
private String charset = "";
@Option(name = "--compilation_level",
aliases = {"-O"},
usage = "Specifies the compilation level to use. Options: "
+ "WHITESPACE_ONLY, "
+ "SIMPLE, "
+ "ADVANCED")
private String compilationLevel = "SIMPLE";
private CompilationLevel compilationLevelParsed = null;
@Option(name = "--checks_only",
aliases = {"--checks-only"},
handler = BooleanOptionHandler.class,
usage = "Don't generate output. Run checks, but no optimization passes.")
private boolean checksOnly = false;
@Option(name = "--use_types_for_optimization",
handler = BooleanOptionHandler.class,
usage = "Enable or disable the optimizations "
+ "based on available type information. Inaccurate type annotations "
+ "may result in incorrect results.")
private boolean useTypesForOptimization = true;
@Option(name = "--assume_function_wrapper",
handler = BooleanOptionHandler.class,
usage = "Enable additional optimizations based on the assumption that the output will be "
+ "wrapped with a function wrapper. This flag is used to indicate that \"global\" "
+ "declarations will not actually be global but instead isolated to the compilation unit. "
+ "This enables additional optimizations.")
private boolean assumeFunctionWrapper = false;
@Option(name = "--warning_level",
aliases = {"-W"},
usage = "Specifies the warning level to use. Options: "
+ "QUIET, DEFAULT, VERBOSE")
private WarningLevel warningLevel = WarningLevel.DEFAULT;
@Option(name = "--debug",
hidden = true,
handler = BooleanOptionHandler.class,
usage = "Enable debugging options")
private boolean debug = false;
@Option(name = "--generate_exports",
handler = BooleanOptionHandler.class,
usage = "Generates export code for those marked with @export")
private boolean generateExports = false;
@Option(name = "--export_local_property_definitions",
handler = BooleanOptionHandler.class,
usage = "Generates export code for local properties marked with @export")
private boolean exportLocalPropertyDefinitions = false;
@Option(name = "--formatting",
usage = "Specifies which formatting options, if any, should be "
+ "applied to the output JS. Options: "
+ "PRETTY_PRINT, PRINT_INPUT_DELIMITER, SINGLE_QUOTES")
private List<FormattingOption> formatting = new ArrayList<>();
@Option(name = "--process_common_js_modules",
handler = BooleanOptionHandler.class,
usage = "Process CommonJS modules to a concatenable form.")
private boolean processCommonJsModules = false;
@Option(
name = "--common_js_module_path_prefix",
hidden = true,
usage = "Deprecated: use --js_module_root."
)
private List<String> commonJsPathPrefix = new ArrayList<>();
@Option(
name = "--js_module_root",
usage = "Path prefixes to be removed from ES6 & CommonJS modules."
)
private List<String> moduleRoot = new ArrayList<>();
@Option(
name = "--common_js_entry_module",
hidden = true,
usage = "Deprecated: use --entry_point."
)
private String commonJsEntryModule;
@Option(name = "--transform_amd_modules",
handler = BooleanOptionHandler.class,
usage = "Transform AMD to CommonJS modules.")
private boolean transformAmdModules = false;
@Option(name = "--process_closure_primitives",
handler = BooleanOptionHandler.class,
usage = "Processes built-ins from the Closure library, such as "
+ "goog.require(), goog.provide(), and goog.exportSymbol(). "
+ "True by default.")
private boolean processClosurePrimitives = true;
@Option(
name = "--manage_closure_dependencies",
hidden = true,
handler = BooleanOptionHandler.class,
usage = "Deprecated: use --dependency_mode=LOOSE."
)
private boolean manageClosureDependencies = false;
@Option(
name = "--only_closure_dependencies",
hidden = true,
handler = BooleanOptionHandler.class,
usage = "Deprecated: use --dependency_mode=STRICT."
)
private boolean onlyClosureDependencies = false;
@Option(
name = "--closure_entry_point",
hidden = true,
usage = "Deprecated: use --entry_point.")
private List<String> closureEntryPoint = new ArrayList<>();
@Option(name = "--process_jquery_primitives",
hidden = true,
handler = BooleanOptionHandler.class,
usage = "Processes built-ins from the Jquery library, such as "
+ "jQuery.fn and jQuery.extend()")
private boolean processJqueryPrimitives = false;
@Option(name = "--angular_pass",
handler = BooleanOptionHandler.class,
usage = "Generate $inject properties for AngularJS for functions "
+ "annotated with @ngInject")
private boolean angularPass = false;
@Option(name = "--polymer_pass",
handler = BooleanOptionHandler.class,
usage = "Rewrite Polymer classes to be compiler-friendly.")
private boolean polymerPass = false;
@Option(name = "--dart_pass",
handler = BooleanOptionHandler.class,
usage = "Rewrite Dart Dev Compiler output to be compiler-friendly.")
private boolean dartPass = false;
@Option(
name = "--j2cl_pass",
hidden = true,
usage =
"Rewrite J2CL output to be compiler-friendly if enabled (ON or AUTO). "
+ "Options:OFF, ON, AUTO(default)"
)
private String j2clPassMode = "AUTO";
@Option(
name = "--output_manifest",
usage =
"Prints out a list of all the files in the compilation. "
+ "If --dependency_mode=STRICT or LOOSE is specified, this will not include "
+ "files that got dropped because they were not required. "
+ "The %outname% placeholder expands to the JS output file. "
+ "If you're using modularization, using %outname% will create "
+ "a manifest for each module."
)
private String outputManifest = "";
@Option(name = "--output_module_dependencies",
usage = "Prints out a JSON file of dependencies between modules.")
private String outputModuleDependencies = "";
@Option(
name = "--language_in",
usage =
"Sets what language spec that input sources conform. "
+ "Options: ECMASCRIPT3, ECMASCRIPT5, ECMASCRIPT5_STRICT, "
+ "ECMASCRIPT6 (default), ECMASCRIPT6_STRICT, ECMASCRIPT6_TYPED (experimental)"
)
private String languageIn = "ECMASCRIPT6";
@Option(name = "--language_out",
usage = "Sets what language spec the output should conform to. "
+ "Options: ECMASCRIPT3 (default), ECMASCRIPT5, ECMASCRIPT5_STRICT, "
+ "ECMASCRIPT6_TYPED (experimental)")
private String languageOut = "ECMASCRIPT3";
@Option(name = "--version",
handler = BooleanOptionHandler.class,
usage = "Prints the compiler version to stdout and exit.")
private boolean version = false;
@Option(name = "--translations_file",
hidden = true,
usage = "Source of translated messages. Currently only supports XTB.")
private String translationsFile = "";
@Option(name = "--translations_project",
hidden = true,
usage = "Scopes all translations to the specified project."
+ "When specified, we will use different message ids so that messages "
+ "in different projects can have different translations.")
private String translationsProject = null;
@Option(name = "--flagfile",
hidden = true,
usage = "A file containing additional command-line options.")
private String flagFile = "";
@Option(name = "--warnings_whitelist_file",
usage = "A file containing warnings to suppress. Each line should be "
+ "of the form\n"
+ "<file-name>:<line-number>? <warning-description>")
private String warningsWhitelistFile = "";
@Option(name = "--hide_warnings_for",
usage = "If specified, files whose path contains this string will "
+ "have their warnings hidden. You may specify multiple.")
private List<String> hideWarningsFor = new ArrayList<>();
@Option(name = "--extra_annotation_name",
usage = "A whitelist of tag names in JSDoc. You may specify multiple")
private List<String> extraAnnotationName = new ArrayList<>();
@Option(name = "--tracer_mode",
hidden = true,
usage = "Shows the duration of each compiler pass and the impact to "
+ "the compiled output size. "
+ "Options: ALL, AST_SIZE, RAW_SIZE, TIMING_ONLY, OFF")
private CompilerOptions.TracerMode tracerMode =
CompilerOptions.TracerMode.OFF;
@Option(name = "--new_type_inf",
handler = BooleanOptionHandler.class,
usage = "Checks for type errors using the new type inference algorithm.")
private boolean useNewTypeInference = false;
@Option(name = "--rename_prefix_namespace",
usage = "Specifies the name of an object that will be used to store all "
+ "non-extern globals")
private String renamePrefixNamespace = null;
@Option(name = "--conformance_configs",
usage = "A list of JS Conformance configurations in text protocol buffer format.")
private List<String> conformanceConfigs = new ArrayList<>();
@Option(name = "--env",
usage = "Determines the set of builtin externs to load. "
+ "Options: BROWSER, CUSTOM. Defaults to BROWSER.")
private CompilerOptions.Environment environment =
CompilerOptions.Environment.BROWSER;
@Option(name = "--instrumentation_template",
hidden = true,
usage = "A file containing an instrumentation template.")
private String instrumentationFile = "";
@Option(
name = "--json_streams",
hidden = true,
usage =
"Specifies whether standard input and output streams will be "
+ "a JSON array of sources. Each source will be an object of the "
+ "form {path: filename, src: file_contents, srcmap: srcmap_contents }. "
+ "Intended for use by stream-based build systems such as gulpjs. "
+ "Options: NONE, IN, OUT, BOTH. Defaults to NONE."
)
private CompilerOptions.JsonStreamMode jsonStreamMode = CompilerOptions.JsonStreamMode.NONE;
@Option(name = "--preserve_type_annotations",
hidden = true,
handler = BooleanOptionHandler.class,
usage = "Preserves type annotations.")
private boolean preserveTypeAnnotations = false;
@Option(name = "--inject_libraries",
usage = "Allow injecting runtime libraries.")
private boolean injectLibraries = true;
@Option(
name = "--dependency_mode",
usage = "Specifies how the compiler should determine the set and order "
+ "of files for a compilation. Options: NONE the compiler will include "
+ "all src files in the order listed, STRICT files will be included and "
+ "sorted by starting from namespaces or files listed by the "
+ "--entry_point flag - files will only be included if they are "
+ "referenced by a goog.require or CommonJS require or ES6 import, LOOSE "
+ "same as with STRICT but files which do not goog.provide a namespace "
+ "and are not modules will be automatically added as "
+ "--entry_point entries. Defaults to NONE."
)
private CompilerOptions.DependencyMode dependencyMode = CompilerOptions.DependencyMode.NONE;
@Option(
name = "--entry_point",
usage = "A file or namespace to use as the starting point for determining "
+ "which src files to include in the compilation. ES6 and CommonJS "
+ "modules are specified as file paths (without the extension). "
+ "Closure-library namespaces are specified with a \"goog:\" prefix. "
+ "Example: --entry_point=goog:goog.Promise"
)
private List<String> entryPoints = new ArrayList<>();
@Option(name = "--rewrite_polyfills",
handler = BooleanOptionHandler.class,
usage = "Rewrite ES6 library calls to use polyfills provided by the compiler's runtime.")
private boolean rewritePolyfills = true;
@Option(name = "--print_source_after_each_pass",
hidden = true,
usage = "Whether to iteratively print resulting JS source per pass.")
private boolean printSourceAfterEachPass = false;
@Argument
private List<String> arguments = new ArrayList<>();
private final CmdLineParser parser;
private static final Map<String, CompilationLevel> COMPILATION_LEVEL_MAP =
ImmutableMap.of(
"WHITESPACE_ONLY",
CompilationLevel.WHITESPACE_ONLY,
"SIMPLE",
CompilationLevel.SIMPLE_OPTIMIZATIONS,
"SIMPLE_OPTIMIZATIONS",
CompilationLevel.SIMPLE_OPTIMIZATIONS,
"ADVANCED",
CompilationLevel.ADVANCED_OPTIMIZATIONS,
"ADVANCED_OPTIMIZATIONS",
CompilationLevel.ADVANCED_OPTIMIZATIONS);
Flags() {
parser = new CmdLineParser(this);
}
/**
* Parse the given args list.
*/
private void parse(List<String> args) throws CmdLineException {
parser.parseArgument(args.toArray(new String[] {}));
compilationLevelParsed = COMPILATION_LEVEL_MAP.get(Ascii.toUpperCase(compilationLevel));
if (compilationLevelParsed == null) {
throw new CmdLineException(
parser, "Bad value for --compilation_level: " + compilationLevel);
}
}
private static final Multimap<String, String> categories =
new ImmutableMultimap.Builder<String, String>()
.putAll(
"Basic Usage",
ImmutableList.of(
"compilation_level",
"env",
"externs",
"js",
"js_output_file",
"language_in",
"language_out",
"warning_level"))
.putAll(
"Warning and Error Management",
ImmutableList.of(
"conformance_configs",
"extra_annotation_name",
"hide_warnings_for",
"jscomp_error",
"jscomp_off",
"jscomp_warning",
"new_type_inf",
"warnings_whitelist_file"))
.putAll(
"Output",
ImmutableList.of(
"assume_function_wrapper",
"debug",
"export_local_property_definitions",
"formatting",
"generate_exports",
"output_wrapper",
"output_wrapper_file"))
.putAll("Dependency Management", ImmutableList.of("dependency_mode", "entry_point"))
.putAll(
"JS Modules",
ImmutableList.of(
"js_module_root", "process_common_js_modules", "transform_amd_modules"))
.putAll(
"Library and Framework Specific",
ImmutableList.of(
"angular_pass",
"dart_pass",
"noinject_library",
"polymer_pass",
"process_closure_primitives",
"rewrite_polyfills"))
.putAll(
"Code Splitting",
ImmutableList.of("module", "module_output_path_prefix", "module_wrapper"))
.putAll(
"Reports",
ImmutableList.of(
"create_source_map",
"output_manifest",
"output_module_dependencies",
"property_renaming_report",
"source_map_input",
"source_map_location_mapping",
"variable_renaming_report"))
.putAll(
"Miscellaneous",
ImmutableList.of(
"charset",
"checks_only",
"define",
"flagfile",
"help",
"third_party",
"use_types_for_optimization",
"version"))
.build();
private void printUsage(PrintStream ps) {
OutputStreamWriter outputStream = new OutputStreamWriter(ps, UTF_8);
boolean isFirst = true;
for (Map.Entry<String, Collection<String>> entry : categories.asMap().entrySet()) {
String prefix = "\n\n";
String suffix = "";
if (isFirst) {
isFirst = false;
prefix = "";
}
if (entry.getKey().equals("Warning and Error Management")) {
suffix =
"\n"
+ boldPrefix
+ "Available Error Groups: "
+ normalPrefix
+ DiagnosticGroups.DIAGNOSTIC_GROUP_NAMES;
}
printCategoryUsage(entry.getKey(), entry.getValue(), outputStream, prefix, suffix);
}
ps.flush();
}
private final String boldPrefix = "\033[1m";
private final String normalPrefix = "\033[0m";
private void printCategoryUsage(
String categoryName,
final Collection<String> options,
OutputStreamWriter outputStream,
String prefix,
String suffix) {
try {
if (prefix != null) {
printStringLineWrapped(prefix, outputStream);
}
outputStream.write(boldPrefix + categoryName + ":\n" + normalPrefix);
parser.printUsage(
outputStream,
null,
new OptionHandlerFilter() {
@Override
public boolean select(OptionHandler optionHandler) {
if (optionHandler.option instanceof NamedOptionDef) {
return !optionHandler.option.hidden()
&& options.contains(
((NamedOptionDef) optionHandler.option).name().replaceFirst("^--", ""));
}
return false;
}
});
if (suffix != null) {
printStringLineWrapped(suffix, outputStream);
}
} catch (IOException e) {
// Ignore.
}
}
private final int maxLineLength = 80;
private final Pattern whitespacePattern = Pattern.compile("\\s");
private void printStringLineWrapped(String input, OutputStreamWriter outputStream)
throws IOException {
if (input.length() < maxLineLength) {
outputStream.write(input);
return;
}
int endIndex = maxLineLength;
String subString = input.substring(0, maxLineLength);
Matcher whitespaceMatcher = whitespacePattern.matcher(subString);
boolean foundMatch = false;
while (whitespaceMatcher.find()) {
endIndex = whitespaceMatcher.start();
foundMatch = true;
}
outputStream.write(input.substring(0, endIndex) + "\n");
printStringLineWrapped(
" " + input.substring(foundMatch ? endIndex + 1 : endIndex), outputStream);
}
private void printShortUsageAfterErrors(PrintStream ps) {
ps.print("Sample usage: ");
ps.println("--compilation_level (-O) VAL --externs VAL --js VAL"
+ " --js_output_file VAL"
+ " --warning_level (-W) [QUIET | DEFAULT | VERBOSE]");
ps.println("Run with --help for all options and details");
ps.flush();
}
/**
* Users may specify JS inputs via the {@code --js} flag, 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}:
* <pre>
* find MY_JS_SRC_DIR -name '*.js' \
* | xargs java -jar compiler.jar --dependency_mode=LOOSE
* </pre>
* 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.
* <p>
* Note that it is important to use the
* {@code --dependency_mode=LOOSE or STRICT} 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()}.
*/
protected List<String> getJsFiles() throws CmdLineException, IOException {
List<String> patterns = new ArrayList<>();
patterns.addAll(js);
patterns.addAll(arguments);
List<String> allJsInputs = findJsFiles(patterns);
if (!patterns.isEmpty() && allJsInputs.isEmpty()) {
throw new CmdLineException(parser, "No inputs matched");
}
return allJsInputs;
}
protected List<FlagEntry<JsSourceType>> getMixedJsSources()
throws CmdLineException, IOException {
List<FlagEntry<JsSourceType>> mixedSources = new ArrayList<>();
Set<String> excludes = new HashSet<>();
for (FlagEntry<JsSourceType> source : Flags.mixedJsSources) {
if (source.getValue().endsWith(".zip")) {
mixedSources.add(source);
} else if (source.getValue().startsWith("!")) {
for (String filename : findJsFiles(
Collections.singletonList(source.getValue().substring(1)))) {
excludes.add(filename);
mixedSources.remove(new FlagEntry<>(JsSourceType.JS, filename));
}
} else {
for (String filename : findJsFiles(Collections.singletonList(source.getValue()), true)) {
if (!excludes.contains(filename)) {
mixedSources.add(new FlagEntry<>(JsSourceType.JS, filename));
}
}
}
}
List<String> fromArguments = findJsFiles(arguments);
for (String filename : fromArguments) {
mixedSources.add(new FlagEntry<>(JsSourceType.JS, filename));
}
if (!Flags.mixedJsSources.isEmpty() && !arguments.isEmpty() && mixedSources.isEmpty()) {
throw new CmdLineException(parser, "No inputs matched");
}
return mixedSources;
}
List<SourceMap.LocationMapping> getSourceMapLocationMappings() throws CmdLineException {
ImmutableList.Builder<LocationMapping> locationMappings = ImmutableList.builder();
ImmutableMap<String, String> split = splitPipeParts(
sourceMapLocationMapping, "--source_map_location_mapping");
for (Map.Entry<String, String> mapping : split.entrySet()) {
locationMappings.add(new SourceMap.LocationMapping(mapping.getKey(),
mapping.getValue()));
}
return locationMappings.build();
}
ImmutableMap<String, String> getSourceMapInputs() throws CmdLineException {
return splitPipeParts(sourceMapInputs, "--source_map_input");
}
private ImmutableMap<String, String> splitPipeParts(Iterable<String> input,
String flagName) throws CmdLineException {
ImmutableMap.Builder<String, String> result = new ImmutableMap.Builder<>();
Splitter splitter = Splitter.on('|').limit(2);
for (String inputSourceMap : input) {
List<String> parts = splitter.splitToList(inputSourceMap);
if (parts.size() != 2) {
throw new CmdLineException(parser, "Bad value for " + flagName +
" (duplicate key): " + input);
}
result.put(parts.get(0), parts.get(1));
}
return result.build();
}
// Our own option parser to be backwards-compatible.
// It needs to be public because of the crazy reflection that args4j does.