-
Notifications
You must be signed in to change notification settings - Fork 172
/
Copy pathAbstractCompilerMojo.java
1823 lines (1731 loc) · 81.4 KB
/
AbstractCompilerMojo.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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.maven.plugin.compiler;
import javax.lang.model.SourceVersion;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.OptionChecker;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.Tool;
import javax.tools.ToolProvider;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.StreamTokenizer;
import java.io.StringWriter;
import java.io.UncheckedIOException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.StringJoiner;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import org.apache.maven.api.JavaPathType;
import org.apache.maven.api.PathScope;
import org.apache.maven.api.PathType;
import org.apache.maven.api.Project;
import org.apache.maven.api.ProjectScope;
import org.apache.maven.api.Session;
import org.apache.maven.api.Toolchain;
import org.apache.maven.api.Type;
import org.apache.maven.api.annotations.Nonnull;
import org.apache.maven.api.annotations.Nullable;
import org.apache.maven.api.di.Inject;
import org.apache.maven.api.plugin.Log;
import org.apache.maven.api.plugin.Mojo;
import org.apache.maven.api.plugin.MojoException;
import org.apache.maven.api.plugin.annotations.Parameter;
import org.apache.maven.api.services.ArtifactManager;
import org.apache.maven.api.services.DependencyResolver;
import org.apache.maven.api.services.DependencyResolverRequest;
import org.apache.maven.api.services.DependencyResolverResult;
import org.apache.maven.api.services.MessageBuilder;
import org.apache.maven.api.services.MessageBuilderFactory;
import org.apache.maven.api.services.ProjectManager;
import org.apache.maven.api.services.ToolchainManager;
import static org.apache.maven.plugin.compiler.SourceDirectory.CLASS_FILE_SUFFIX;
import static org.apache.maven.plugin.compiler.SourceDirectory.MODULE_INFO;
/**
* Base class of Mojos compiling Java source code.
* This plugin uses the {@link JavaCompiler} interface from JDK 6+.
* Each instance shall be used only once, then discarded.
*
* @author <a href="mailto:[email protected]">Trygve Laugstøl</a>
* @author Martin Desruisseaux
* @since 2.0
*/
public abstract class AbstractCompilerMojo implements Mojo {
/**
* Whether to support legacy (and often deprecated) behavior.
* This is currently hard-coded to {@code true} for compatibility reason.
* TODO: consider making configurable.
*/
static final boolean SUPPORT_LEGACY = true;
/**
* The executable to use by default if nine is specified.
*/
private static final String DEFAULT_EXECUTABLE = "javac";
/**
* The locale for diagnostics, or {@code null} for the platform default.
*
* @see #encoding
*/
private static final Locale LOCALE = null;
// ----------------------------------------------------------------------
// Configurables
// ----------------------------------------------------------------------
/**
* The {@code --module-version} argument for the Java compiler.
* This is ignored if not applicable, e.g., in non-modular projects.
*
* @see <a href="https://docs.oracle.com/en/java/javase/17/docs/specs/man/javac.html#option-module-version">javac --module-version</a>
* @since 4.0.0
*/
@Parameter(property = "maven.compiler.moduleVersion", defaultValue = "${project.version}")
protected String moduleVersion;
/**
* The {@code -encoding} argument for the Java compiler.
*
* @see <a href="https://docs.oracle.com/en/java/javase/17/docs/specs/man/javac.html#option-encoding">javac -encoding</a>
* @since 2.1
*/
@Parameter(property = "encoding", defaultValue = "${project.build.sourceEncoding}")
protected String encoding;
/**
* {@return the character set used for decoding bytes, or null for the platform default}.
* No warning is emitted in the latter case because as of Java 18, the default is UTF-8,
* i.e. the encoding is no longer platform-dependent.
*/
private Charset charset() {
if (encoding != null) {
try {
return Charset.forName(encoding);
} catch (UnsupportedCharsetException e) {
throw new CompilationFailureException("Invalid 'encoding' option: " + encoding, e);
}
}
return null;
}
/**
* The {@code --source} argument for the Java compiler.
* <p><b>Notes:</b></p>
* <ul>
* <li>Since 3.8.0 the default value has changed from 1.5 to 1.6.</li>
* <li>Since 3.9.0 the default value has changed from 1.6 to 1.7.</li>
* <li>Since 3.11.0 the default value has changed from 1.7 to 1.8.</li>
* <li>Since 4.0.0-beta-2 the default value has been removed.
* As of Java 9, the {@link #release} parameter is preferred.</li>
* </ul>
*
* @see <a href="https://docs.oracle.com/en/java/javase/17/docs/specs/man/javac.html#option-source">javac --source</a>
*/
@Parameter(property = "maven.compiler.source")
protected String source;
/**
* The {@code --target} argument for the Java compiler.
* <p><b>Notes:</b></p>
* <ul>
* <li>Since 3.8.0 the default value has changed from 1.5 to 1.6.</li>
* <li>Since 3.9.0 the default value has changed from 1.6 to 1.7.</li>
* <li>Since 3.11.0 the default value has changed from 1.7 to 1.8.</li>
* <li>Since 4.0.0-beta-2 the default value has been removed.
* As of Java 9, the {@link #release} parameter is preferred.</li>
* </ul>
*
* @see <a href="https://docs.oracle.com/en/java/javase/17/docs/specs/man/javac.html#option-target">javac --target</a>
*/
@Parameter(property = "maven.compiler.target")
protected String target;
/**
* The {@code --release} argument for the Java compiler.
* If omitted, then the compiler will generate bytecodes for the Java version running the compiler.
*
* @see <a href="https://docs.oracle.com/en/java/javase/17/docs/specs/man/javac.html#option-release">javac --release</a>
* @since 3.6
*/
@Parameter(property = "maven.compiler.release")
protected String release;
/**
* Whether to enable preview language features of the java compiler.
* If {@code true}, then the {@code --enable-preview} option will be added to compiler arguments.
*
* @see <a href="https://docs.oracle.com/en/java/javase/17/docs/specs/man/javac.html#option-enable-preview">javac --enable-preview</a>
* @since 3.10.1
*/
@Parameter(property = "maven.compiler.enablePreview", defaultValue = "false")
protected boolean enablePreview;
/**
* Additional arguments to be passed verbatim to the Java compiler. This parameter can be used when
* the Maven compiler plugin does not provide a parameter for a Java compiler option. It may happen,
* for example, for new or preview Java features which are not yet handled by this compiler plugin.
*
* <p>If an option has a value, the option and the value shall be specified in two separated {@code <arg>}
* elements. For example, the {@code -Xmaxerrs 1000} option (for setting the maximal number of errors to
* 1000) can be specified as below (together with other options):</p>
*
* <pre>{@code
* <compilerArgs>
* <arg>-Xlint</arg>
* <arg>-Xmaxerrs</arg>
* <arg>1000</arg>
* <arg>J-Duser.language=en_us</arg>
* </compilerArgs>}</pre>
*
* Note that {@code -J} options should be specified only if {@link #fork} is set to {@code true}.
* Other options can be specified regardless the {@link #fork} value.
* The compiler plugin does not verify whether the arguments given through this parameter are valid.
* For this reason, the other parameters provided by the compiler plugin should be preferred when
* they exist, because the plugin checks whether the corresponding options are supported.
*
* @see <a href="https://docs.oracle.com/en/java/javase/17/docs/specs/man/javac.html#option-J">javac -J</a>
* @since 3.1
*/
@Parameter
protected List<String> compilerArgs;
/**
* The single argument string to be passed to the compiler. To pass multiple arguments such as
* {@code -Xmaxerrs 1000} (which are actually two arguments), {@link #compilerArgs} is preferred.
*
* <p>Note that {@code -J} options should be specified only if {@link #fork} is set to {@code true}.</p>
*
* @see <a href="https://docs.oracle.com/en/java/javase/17/docs/specs/man/javac.html#option-J">javac -J</a>
*
* @deprecated Use {@link #compilerArgs} instead.
*/
@Parameter
@Deprecated(since = "4.0.0")
protected String compilerArgument;
/**
* Whether annotation processing is performed or not.
* If not set, both compilation and annotation processing are performed at the same time.
* If set, the value will be appended to the {@code -proc:} compiler option.
* Standard values are:
* <ul>
* <li>{@code none} – no annotation processing is performed.</li>
* <li>{@code only} – only annotation processing is done, no compilation.</li>
* <li>{@code full} – annotation processing and compilation are done.</li>
* </ul>
*
* Prior Java 21, {@code full} was the default.
* Starting with JDK 21, this option must be set explicitly.
*
* @see #annotationProcessors
* @see <a href="https://docs.oracle.com/en/java/javase/17/docs/specs/man/javac.html#option-proc">javac -proc</a>
* @see <a href="https://docs.oracle.com/en/java/javase/17/docs/specs/man/javac.html#annotation-processing">javac Annotation Processing</a>
* @since 2.2
*/
@Parameter(property = "maven.compiler.proc")
protected String proc;
// Reminder: if above list of legal values is modified, update also addComaSeparated("-proc", …)
/**
* Class names of annotation processors to run.
* If not set, the default annotation processors discovery process applies.
* If set, the value will be appended to the {@code -processor} compiler option.
*
* @see #proc
* @since 2.2
*/
@Parameter
protected String[] annotationProcessors;
/**
* Classpath elements to supply as annotation processor path. If specified, the compiler will detect annotation
* processors only in those classpath elements. If omitted, the default classpath is used to detect annotation
* processors. The detection itself depends on the configuration of {@link #annotationProcessors}.
* <p>
* Each classpath element is specified using their Maven coordinates (groupId, artifactId, version, classifier,
* type). Transitive dependencies are added automatically. Exclusions are supported as well. Example:
* </p>
*
* <pre>
* <configuration>
* <annotationProcessorPaths>
* <path>
* <groupId>org.sample</groupId>
* <artifactId>sample-annotation-processor</artifactId>
* <version>1.2.3</version> <!-- Optional - taken from dependency management if not specified -->
* <!-- Optionally exclude transitive dependencies -->
* <exclusions>
* <exclusion>
* <groupId>org.sample</groupId>
* <artifactId>sample-dependency</artifactId>
* </exclusion>
* </exclusions>
* </path>
* <!-- ... more ... -->
* </annotationProcessorPaths>
* </configuration>
* </pre>
*
* <b>Note:</b> Exclusions are supported from version 3.11.0.
*
* @see <a href="https://docs.oracle.com/en/java/javase/17/docs/specs/man/javac.html#option-processor-path">javac -processorpath</a>
* @see <a href="https://docs.oracle.com/en/java/javase/17/docs/specs/man/javac.html#annotation-processing">javac Annotation Processing</a>
* @since 3.5
*
* @deprecated Replaced by ordinary dependencies with {@code <type>} element
* set to {@code proc}, {@code classpath-proc} or {@code modular-proc}.
*/
@Parameter
@Deprecated(since = "4.0.0")
protected List<DependencyCoordinate> annotationProcessorPaths;
/**
* Whether to use the Maven dependency management section when resolving transitive dependencies of annotation
* processor paths.
* <p>
* This flag does not enable / disable the ability to resolve the version of annotation processor paths
* from dependency management section. It only influences the resolution of transitive dependencies of those
* top-level paths.
* </p>
*
* @since 3.12.0
*/
@Parameter(defaultValue = "false")
protected boolean annotationProcessorPathsUseDepMgmt;
/**
* Whether to generate {@code package-info.class} even when empty.
* By default, package info source files that only contain javadoc and no annotation
* on the package can lead to no class file being generated by the compiler.
* It may cause a file miss on build systems that check for file existence in order to decide what to recompile.
*
* <p>If {@code true}, the {@code -Xpkginfo:always} compiler option is added if the compiler supports that
* extra option. If the extra option is not supported, then a warning is logged and no option is added to
* the compiler arguments.</p>
*
* @see #incrementalCompilation
* @since 3.10
*/
@Parameter(property = "maven.compiler.createMissingPackageInfoClass", defaultValue = "false")
protected boolean createMissingPackageInfoClass;
/**
* Whether to generate class files for implicitly referenced files.
* If set, the value will be appended to the {@code -implicit:} compiler option.
* Standard values are:
* <ul>
* <li>{@code class} – automatically generates class files.</li>
* <li>{@code none} – suppresses class file generation.</li>
* </ul>
*
* @see <a href="https://docs.oracle.com/en/java/javase/17/docs/specs/man/javac.html#option-implicit">javac -implicit</a>
* @since 3.10.2
*/
@Parameter(property = "maven.compiler.implicit")
protected String implicit;
// Reminder: if above list of legal values is modified, update also addComaSeparated("-implicit", …)
/**
* Whether to generate metadata for reflection on method parameters.
* If {@code true}, the {@code -parameters} option will be added to compiler arguments.
*
* @see <a href="https://docs.oracle.com/en/java/javase/17/docs/specs/man/javac.html#option-parameters">javac -parameters</a>
* @since 3.6.2
*/
@Parameter(property = "maven.compiler.parameters", defaultValue = "false")
protected boolean parameters;
/**
* Whether to include debugging information in the compiled class files.
* The amount of debugging information to include is specified by the {@link #debuglevel} parameter.
* If this {@code debug} flag is {@code true}, then the {@code -g} option may be added to compiler arguments
* with a value determined by the {@link #debuglevel} argument. If this {@code debug} flag is {@code false},
* then the {@code -g:none} option will be added to the compiler arguments.
*
* @see #debuglevel
* @see <a href="https://docs.oracle.com/en/java/javase/17/docs/specs/man/javac.html#option-g">javac -g</a>
*/
@Parameter(property = "maven.compiler.debug", defaultValue = "true")
protected boolean debug = true;
/**
* Keyword list to be appended to the {@code -g} command-line switch.
* Legal values are a comma-separated list of the following keywords:
* {@code lines}, {@code vars}, {@code source} and {@code all}.
* If debug level is not specified, then the {@code -g} option will <em>not</em> by added,
* which means that the default debugging information will be generated
* (typically {@code lines} and {@code source} but not {@code vars}).
* If {@link #debug} is turned off, this attribute will be ignored.
*
* @see #debug
* @see <a href="https://docs.oracle.com/en/java/javase/17/docs/specs/man/javac.html#option-g-custom">javac -G:[lines,vars,source]</a>
* @since 2.1
*/
@Parameter(property = "maven.compiler.debuglevel")
protected String debuglevel;
// Reminder: if above list of legal values is modified, update also addComaSeparated("-g", …)
/**
* Whether to optimize the compiled code using the compiler's optimization methods.
* @deprecated This property is ignored.
*/
@Deprecated(forRemoval = true)
@Parameter(property = "maven.compiler.optimize")
protected Boolean optimize;
/**
* Whether to show messages about what the compiler is doing.
* If {@code true}, then the {@code -verbose} option will be added to compiler arguments.
*
* @see <a href="https://docs.oracle.com/en/java/javase/17/docs/specs/man/javac.html#option-verbose">javac -verbose</a>
*/
@Parameter(property = "maven.compiler.verbose", defaultValue = "false")
protected boolean verbose;
/**
* Whether to provide more details about why a module is rebuilt.
* This is used only if {@link #incrementalCompilation} is {@code "inputTreeChanges"}.
*
* @see #incrementalCompilation
*/
@Parameter(property = "maven.compiler.showCompilationChanges", defaultValue = "false")
protected boolean showCompilationChanges;
/**
* Whether to show source locations where deprecated APIs are used.
* If {@code true}, then the {@code -deprecation} option will be added to compiler arguments.
* That option is itself a shorthand for {@code -Xlint:deprecation}.
*
* @see #showWarnings
* @see #failOnWarning
*/
@Parameter(property = "maven.compiler.showDeprecation", defaultValue = "false")
protected boolean showDeprecation;
/**
* Whether to show compilation warnings.
* If {@code false}, then the {@code -nowarn} option will be added to compiler arguments.
* That option is itself a shorthand for {@code -Xlint:none}.
*
* @see #showDeprecation
* @see #failOnWarning
*/
@Parameter(property = "maven.compiler.showWarnings", defaultValue = "true")
protected boolean showWarnings = true;
/**
* Whether the build will stop if there are compilation warnings.
* If {@code true}, then the {@code -Werror} option will be added to compiler arguments.
*
* @see #showWarnings
* @see #showDeprecation
* @since 3.6
*/
@Parameter(property = "maven.compiler.failOnWarning", defaultValue = "false")
protected boolean failOnWarning;
/**
* Whether the build will stop if there are compilation errors.
*
* @see #failOnWarning
* @since 2.0.2
*/
@Parameter(property = "maven.compiler.failOnError", defaultValue = "true")
protected boolean failOnError = true;
/**
* Sets the name of the output file when compiling a set of sources to a single file.
*
* <p>expression="${project.build.finalName}"</p>
*
* @deprecated Bundling many class files into a single file should be done by other plugins.
*/
@Parameter
@Deprecated(since = "4.0.0", forRemoval = true)
protected String outputFileName;
/**
* Timestamp for reproducible output archive entries. It can be either formatted as ISO 8601
* {@code yyyy-MM-dd'T'HH:mm:ssXXX} or as an int representing seconds since the epoch (like
* <a href="https://reproducible-builds.org/docs/source-date-epoch/">SOURCE_DATE_EPOCH</a>).
*
* @since 3.12.0
*
* @deprecated Not used by the compiler plugin since it does not generate archive.
*/
@Deprecated(since = "4.0.0", forRemoval = true)
@Parameter(defaultValue = "${project.build.outputTimestamp}")
protected String outputTimestamp;
/**
* The algorithm to use for selecting which files to compile.
* Values can be {@code dependencies}, {@code sources}, {@code classes}, {@code additions},
* {@code modules} or {@code none}.
*
* <p><b>{@code options}:</b>
* recompile all source files if the compiler options changed.
* Changes are detected on a <i>best-effort</i> basis only.</p>
*
* <p><b>{@code dependencies}:</b>
* recompile all source files if at least one dependency (JAR file) changed since the last build.
* This check is based on the last modification times of JAR files.</p>
*
* <p><b>{@code sources}:</b>
* recompile source files modified since the last build.
* In addition, if a source file has been deleted, then all source files are recompiled.
* This check is based on the modification times of source files
* rather than the modification times of the {@code *.class} files.</p>
*
* <p><b>{@code classes}:</b>
* recompile source files ({@code *.java}) associated to no output file ({@code *.class})
* or associated to an output file older than the source. This algorithm does not check
* if a source file has been removed, potentially leaving non-recompiled classes with
* references to classes that no longer exist.</p>
*
* <p>The {@code sources} and {@code classes} values are partially redundant,
* doing the same work in different ways. It is usually not necessary to specify those two values.</p>
*
* <p><b>{@code additions}:</b>
* recompile all source files when the addition of a new file is detected.
* This aspect should be used together with {@code sources} or {@code classes}.
* When used with {@code classes}, it provides a way to detect class renaming
* (this is not needed with {@code sources}).</p>
*
* <p><b>{@code modules}:</b>
* recompile modules and let the compiler decides which individual files to recompile.
* The compiler plugin does not enumerate the source files to recompile (actually, it does not scan at all the
* source directories). Instead, it only specifies the module to recompile using the {@code --module} option.
* The Java compiler will scan the source directories itself and compile only those source files that are newer
* than the corresponding files in the output directory.</p>
*
* <p><b>{@code none}:</b>
* the compiler plugin unconditionally specifies all sources to the Java compiler.
* This option is mutually exclusive with all other incremental compilation options.</p>
*
* <h4>Limitations</h4>
* In all cases, the current compiler-plugin does not detect structural changes other than file addition or removal.
* For example, the plugin does not detect whether a method has been removed in a class.
*
* @see #staleMillis
* @see #fileExtensions
* @see #showCompilationChanges
* @see #createMissingPackageInfoClass
* @since 4.0.0
*/
@Parameter(defaultValue = "options,dependencies,sources")
protected String incrementalCompilation;
/**
* Whether to enable/disable incremental compilation feature.
*
* @since 3.1
*
* @deprecated Replaced by {@link #incrementalCompilation}.
* A value of {@code true} in this old property is equivalent to {@code "dependencies,sources,additions"}
* in the new property, and a value of {@code false} is equivalent to {@code "classes"}.
*/
@Deprecated(since = "4.0.0")
@Parameter(property = "maven.compiler.useIncrementalCompilation")
protected Boolean useIncrementalCompilation;
/**
* File extensions to check timestamp for incremental build.
* Default contains only {@code class} and {@code jar}.
*
* TODO: Rename with a name making clearer that this parameter is about incremental build.
*
* @see #incrementalCompilation
* @since 3.1
*/
@Parameter
protected List<String> fileExtensions;
/**
* The granularity in milliseconds of the last modification
* date for testing whether a source needs recompilation.
*
* @see #incrementalCompilation
*/
@Parameter(property = "lastModGranularityMs", defaultValue = "0")
protected int staleMillis;
/**
* Allows running the compiler in a separate process.
* If {@code false}, the plugin uses the built-in compiler, while if {@code true} it will use an executable.
*
* @see #executable
* @see #compilerId
* @see #meminitial
* @see #maxmem
*/
@Parameter(property = "maven.compiler.fork", defaultValue = "false")
protected boolean fork;
/**
* Requirements for this JDK toolchain for using a different {@code javac} than the one of the JDK used by Maven.
* This overrules the toolchain selected by the
* <a href="https://maven.apache.org/plugins/maven-toolchains-plugin/">maven-toolchain-plugin</a>.
* See <a href="https://maven.apache.org/guides/mini/guide-using-toolchains.html"> Guide to Toolchains</a>
* for more info.
*
* <pre>
* <configuration>
* <jdkToolchain>
* <version>11</version>
* </jdkToolchain>
* ...
* </configuration>
*
* <configuration>
* <jdkToolchain>
* <version>1.8</version>
* <vendor>zulu</vendor>
* </jdkToolchain>
* ...
* </configuration>
* </pre>
*
* @see #fork
* @see #executable
* @since 3.6
*/
@Parameter
protected Map<String, String> jdkToolchain;
/**
* Identifier of the compiler to use. This identifier shall match the identifier of a compiler known
* to the {@linkplain #jdkToolchain JDK tool chain}, or the {@linkplain JavaCompiler#name() name} of
* a {@link JavaCompiler} instance registered as a service findable by {@link ServiceLoader}.
* See this <a href="non-javac-compilers.html">guide</a> for more information.
* If unspecified, then the {@linkplain ToolProvider#getSystemJavaCompiler() system Java compiler} is used.
* The identifier of the system Java compiler is usually {@code javac}.
*
* @see #fork
* @see #executable
* @see JavaCompiler#name()
*/
@Parameter(property = "maven.compiler.compilerId")
protected String compilerId;
/**
* Version of the compiler to use if {@link #fork} is set to {@code true}.
* Examples! "1.3", "1.5".
*
* @deprecated This parameter is no longer used by the underlying compilers.
*
* @see #fork
*/
@Deprecated(since = "4.0.0", forRemoval = true)
@Parameter(property = "maven.compiler.compilerVersion")
protected String compilerVersion;
/**
* Whether to use the legacy {@code com.sun.tools.javac} API instead of {@code javax.tools} API.
*
* @see <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.compiler/javax/tools/package-summary.html">New API</a>
* @see <a href="https://docs.oracle.com/en/java/javase/17/docs/api/jdk.compiler/com/sun/tools/javac/package-summary.html">Legacy API</a>
* @since 3.13
*
* @deprecated Ignored because the compiler plugin now always use the {@code javax.tools} API.
*/
@Deprecated(since = "4.0.0", forRemoval = true)
@Parameter(property = "maven.compiler.forceLegacyJavacApi")
protected Boolean forceLegacyJavacApi;
/**
* Whether to use legacy compiler API.
*
* @since 3.0
*
* @deprecated Ignored because {@code java.lang.Compiler} has been deprecated and removed from the JDK.
*/
@Deprecated(since = "4.0.0", forRemoval = true)
@Parameter(property = "maven.compiler.forceJavacCompilerUse")
protected Boolean forceJavacCompilerUse;
/**
* Strategy to re use {@code javacc} class created. Legal values are:
* <ul>
* <li>{@code reuseCreated} (default) – will reuse already created but in case of multi-threaded builds,
* each thread will have its own instance.</li>
* <li>{@code reuseSame} – the same Javacc class will be used for each compilation even
* for multi-threaded build.</li>
* <li>{@code alwaysNew} – a new Javacc class will be created for each compilation.</li>
* </ul>
* Note this parameter value depends on the OS/JDK you are using, but the default value should work on most of env.
*
* @since 2.5
*
* @deprecated Not supported anymore. The reuse of {@link JavaFileManager} instance is plugin implementation details.
*/
@Deprecated(since = "4.0.0", forRemoval = true)
@Parameter(property = "maven.compiler.compilerReuseStrategy")
protected String compilerReuseStrategy;
/**
* @since 2.5
*
* @deprecated Deprecated as a consequence of {@link #compilerReuseStrategy} deprecation.
*/
@Deprecated(since = "4.0.0", forRemoval = true)
@Parameter(property = "maven.compiler.skipMultiThreadWarning")
protected Boolean skipMultiThreadWarning;
/**
* Executable of the compiler to use when {@link #fork} is {@code true}.
* If this parameter is specified, then the {@link #jdkToolchain} is ignored.
*
* @see #jdkToolchain
* @see #fork
* @see #compilerId
*/
@Parameter(property = "maven.compiler.executable")
protected String executable;
/**
* Initial size, in megabytes, of the memory allocation pool if {@link #fork} is set to {@code true}.
* Examples: "64", "64M". Suffixes "k" (for kilobytes) and "G" (for gigabytes) are also accepted.
* If no suffix is provided, "M" is assumed.
*
* @see #fork
* @since 2.0.1
*/
@Parameter(property = "maven.compiler.meminitial")
protected String meminitial;
/**
* Maximum size, in megabytes, of the memory allocation pool if {@link #fork} is set to {@code true}.
* Examples: "128", "128M". Suffixes "k" (for kilobytes) and "G" (for gigabytes) are also accepted.
* If no suffix is provided, "M" is assumed.
*
* @see #fork
* @since 2.0.1
*/
@Parameter(property = "maven.compiler.maxmem")
protected String maxmem;
// ----------------------------------------------------------------------
// Read-only parameters
// ----------------------------------------------------------------------
/**
* The directory to run the compiler from if fork is true.
*/
@Parameter(defaultValue = "${project.basedir}", required = true, readonly = true)
protected Path basedir;
/**
* Path to a file where to cache information about the last incremental build.
* This is used when "incremental" builds are enabled for detecting additions
* or removals of source files, or changes in plugin configuration.
* This file should be in the output directory and can be deleted at any time
*/
@Parameter(
defaultValue =
"${project.build.directory}/maven-status/${mojo.plugin.descriptor.artifactId}/${mojo.executionId}.cache",
required = true,
readonly = true)
protected Path mojoStatusPath;
/**
* The current build session instance.
*/
@Inject
protected Session session;
/**
* The current project instance.
*/
@Inject
protected Project project;
@Inject
protected ProjectManager projectManager;
@Inject
protected ArtifactManager artifactManager;
@Inject
protected ToolchainManager toolchainManager;
@Inject
protected MessageBuilderFactory messageBuilderFactory;
/**
* The logger for reporting information or warnings to the user.
* Currently, this is also used for console output.
*/
@Inject
protected Log logger;
/**
* Cached value for writing replacement proposal when a deprecated option is used.
* This is set to a non-null value when first needed. An empty string means that
* this information couldn't be fetched.
*
* @see #writePlugin(MessageBuilder, String, String)
*/
private String mavenCompilerPluginVersion;
/**
* A tip about how to launch the Java compiler from the command-line.
* The command-line may have {@code -J} options before the argument file.
* This is non-null if the compilation failed or if Maven is executed in debug mode.
*/
private String tipForCommandLineCompilation;
/**
* {@code true} if this MOJO is for compiling tests, or {@code false} if compiling the main code.
*/
final boolean isTestCompile;
/**
* Creates a new MOJO.
*
* @param isTestCompile {@code true} for compiling tests, or {@code false} for compiling the main code
*/
protected AbstractCompilerMojo(boolean isTestCompile) {
this.isTestCompile = isTestCompile;
}
/**
* {@return the root directories of Java source files to compile}. If the sources are organized according the
* <i>Module Source Hierarchy</i>, then the list shall enumerate the root source directory for each module.
*/
@Nonnull
protected abstract List<Path> getCompileSourceRoots();
/**
* {@return the inclusion filters for the compiler, or an empty list for all Java source files}.
* The filter patterns are described in {@link java.nio.file.FileSystem#getPathMatcher(String)}.
* If no syntax is specified, the default syntax is "glob".
*/
protected abstract Set<String> getIncludes();
/**
* {@return the exclusion filters for the compiler, or an empty list if none}.
* The filter patterns are described in {@link java.nio.file.FileSystem#getPathMatcher(String)}.
* If no syntax is specified, the default syntax is "glob".
*/
protected abstract Set<String> getExcludes();
/**
* {@return the exclusion filters for the incremental calculation}.
* Updated source files, if excluded by this filter, will not cause the project to be rebuilt.
*
* @see SourceFile#ignoreModification
*/
protected abstract Set<String> getIncrementalExcludes();
/**
* {@return the destination directory (or class output directory) for class files}.
* This directory will be given to the {@code -d} Java compiler option.
*/
@Nonnull
protected abstract Path getOutputDirectory();
/**
* {@return the {@code --source} argument for the Java compiler}.
* The default implementation returns the {@link #source} value.
*/
@Nullable
protected String getSource() {
return source;
}
/**
* {@return the {@code --target} argument for the Java compiler}.
* The default implementation returns the {@link #target} value.
*/
@Nullable
protected String getTarget() {
return target;
}
/**
* {@return the {@code --release} argument for the Java compiler}.
* The default implementation returns the {@link #release} value.
*/
@Nullable
protected String getRelease() {
return release;
}
/**
* {@return the path where to place generated source files created by annotation processing}.
*/
@Nullable
protected abstract Path getGeneratedSourcesDirectory();
/**
* {@return whether the sources contain at least one {@code module-info.java} file}.
* Note that the sources may contain more than one {@code module-info.java} file
* if compiling a project with Module Source Hierarchy.
*
* <p>The test compiler overrides this method for checking the existence of the
* the {@code module-info.class} file in the main output directory instead.</p>
*
* @param roots root directories of the sources to compile
* @throws IOException if this method needed to read a module descriptor and failed
*/
boolean hasModuleDeclaration(final List<SourceDirectory> roots) throws IOException {
for (SourceDirectory root : roots) {
if (root.getModuleInfo().isPresent()) {
return true;
}
}
return false;
}
/**
* Adds dependencies others than the ones declared in POM file.
* The typical case is the compilation of tests, which depends on the main compilation outputs.
* The default implementation does nothing.
*
* @param addTo where to add dependencies
* @param hasModuleDeclaration whether the main sources have or should have a {@code module-info} file
* @throws IOException if this method needs to walk through directories and that operation failed
*/
protected void addImplicitDependencies(Map<PathType, List<Path>> addTo, boolean hasModuleDeclaration)
throws IOException {
// Nothing to add in a standard build of main classes.
}
/**
* Adds options for declaring the source directories. The way to declare those directories depends on whether
* we are compiling the main classes (in which case the {@code --source-path} or {@code --module-source-path}
* options may be used) or the test classes (in which case the {@code --patch-module} option may be used).
*
* @param addTo the collection of source paths to augment
* @param compileSourceRoots the source paths to eventually adds to the {@code toAdd} map
* @throws IOException if this method needs to read a module descriptor and this operation failed
*/
void addSourceDirectories(Map<PathType, List<Path>> addTo, List<SourceDirectory> compileSourceRoots)
throws IOException {
// No need to specify --source-path at this time, as it is for additional sources.
}
/**
* Generates options for handling the given dependencies.
* This method should do nothing when compiling the main classes, because the {@code module-info.java} file
* should contain all the required configuration. However, this method may need to add some {@code -add-reads}
* options when compiling the test classes.
*
* @param dependencies the project dependencies
* @param addTo where to add the options
* @throws IOException if the module information of a dependency cannot be read
*/
protected void addModuleOptions(DependencyResolverResult dependencies, Options addTo) throws IOException {}
/**
* {@return the file where to dump the command-line when debug logging is enabled or when the compilation failed}.
* For example, if the value is {@code "javac"}, then the Java compiler can be launched
* from the command-line by typing {@code javac @target/javac.args}.
* The debug file will contain the compiler options together with the list of source files to compile.
*
* <p>Note: debug logging should not be confused with the {@link #debug} flag.</p>
*/
@Nullable
protected abstract String getDebugFileName();
/**
* {@return the debug file name with its path, or null if none}.
*/
final Path getDebugFilePath() {
String filename = getDebugFileName();
if (filename == null || filename.isBlank()) {
return null;
}
// Do not use `this.getOutputDirectory()` because it may be deeper in `classes/META-INF/versions/`.
return Path.of(project.getBuild().getOutputDirectory()).resolveSibling(filename);
}
/**
* Runs the Java compiler.
*
* @throws MojoException if the compiler cannot be run
*/
@Override
public void execute() throws MojoException {
JavaCompiler compiler = compiler();
Options compilerConfiguration = acceptParameters(compiler);
try {
compile(compiler, compilerConfiguration);
} catch (RuntimeException e) {
String message = e.getLocalizedMessage();
if (message == null) {
message = e.getClass().getSimpleName();
} else if (e instanceof MojoException) {