-
Notifications
You must be signed in to change notification settings - Fork 184
Expand file tree
/
Copy pathAbstractCompilerMojo.java
More file actions
1905 lines (1799 loc) · 84.1 KB
/
AbstractCompilerMojo.java
File metadata and controls
1905 lines (1799 loc) · 84.1 KB
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.DiagnosticListener;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.OptionChecker;
import javax.tools.ToolProvider;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
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.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.List;
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 java.util.stream.Stream;
import org.apache.maven.api.JavaPathType;
import org.apache.maven.api.Language;
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.SourceRoot;
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.MavenException;
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.
*
* <h2>Thread-safety</h2>
* This class is not thread-safe. If this class is used in a multi-thread context,
* users are responsible for synchronizing all accesses to this <abbr>MOJO</abbr> instance.
* However, the executor returned by {@link #createExecutor(DiagnosticListener)} can safely
* launch the compilation in a background thread.
*
* @author <a href="mailto:trygvis@inamo.no">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;
/**
* Name of a {@link SourceVersion} enumeration value for a version above 17 (the current Maven target).
* The {@code SourceVersion} value cannot be referenced directly because it does not exist in Java 17.
* Used for detecting if {@code module-info.class} needs to be patched for reproducible builds.
*/
private static final String RELEASE_22 = "RELEASE_22";
/**
* Name of a {@link SourceVersion} enumeration value for a version above 17 (the current Maven target).
* The {@code SourceVersion} value cannot be referenced directly because it does not exist in Java 17.
* Used for determining the default value of the {@code -proc} compiler option.
*/
private static final String RELEASE_23 = "RELEASE_23";
/**
* The executable to use by default if nine is specified.
*/
private static final String DEFAULT_EXECUTABLE = "javac";
/**
* The quote character for filenames in shell scripts.
* Shall not be used with {@link javax.tools.JavaFileManager}.
*/
static final char QUOTE = '"';
// ----------------------------------------------------------------------
// 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.
*/
final 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 when the sources do not declare this version.
* The suggested way to declare the target Java release is to specify it with the sources like below:
*
* <pre>{@code
* <build>
* <sources>
* <source>
* <directory>src/main/java</directory>
* <targetVersion>17</targetVersion>
* </source>
* </sources>
* </build>}</pre>
*
* If such {@code <targetVersion>} element is found, it has precedence over this {@code release} property.
* If a source does not declare a target Java version, then the value of this {@code release} property is
* used as a fallback.
* If omitted, 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 {@link #target} or {@link #release} has a non-blank value.
* Used for logging a warning if no target Java version was specified.
*/
private boolean targetOrReleaseSet;
/**
* The highest version supported by the compiler, or {@code null} if not yet determined.
*
* @see #isVersionEqualOrNewer(String)
*/
private SourceVersion supportedVersion;
/**
* 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;
/**
* The root directories containing the source files to be compiled. If {@code null} or empty,
* the directories will be obtained from the {@code <Source>} elements declared in the project.
* If non-empty, the project {@code <Source>} elements are ignored. This configuration option
* should be used only when there is a need to override the project configuration.
*
* @deprecated Replaced by the project-wide {@code <sources>} element.
*/
@Parameter
@Deprecated(since = "4.0.0")
protected List<String> compileSourceRoots;
/**
* 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;
/**
* Configures if annotation processing and/or compilation are performed by the compiler.
* If set, the value will be appended to the {@code -proc:} compiler option.
*
* Possible values are:
* <ul>
* <li>{@code none} – no annotation processing is performed, only compilation is done.</li>
* <li>{@code only} – only annotation processing is done, no compilation.</li>
* <li>{@code full} – annotation processing followed by compilation is done.</li>
* </ul>
*
* The default value depends on the JDK used for the build.
* Prior to Java 23, the default was {@code full},
* so annotation processing and compilation were executed without explicit configuration.
*
* For security reasons, starting with Java 23 no annotation processing is done if neither
* any {@code -processor}, {@code -processor path} or {@code -processor module} are set,
* or either {@code only} or {@code full} is set.
* So literally the default is {@code none}.
* It is recommended to always list the annotation processors you want to execute
* instead of using the {@code proc} configuration,
* to ensure that only desired processors are executed and not any "hidden" (and maybe malicious).
*
* @see #annotationProcessors
* @see <a href="https://inside.java/2024/06/18/quality-heads-up/">Inside Java 2024-06-18 Quality Heads up</a>
* @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 (and {@code proc} is set to {@code only} or {@code full}), the default classpath is used to detect annotation
* processors. The detection itself depends on the configuration of {@link #annotationProcessors}.
* Since JDK 23 by default no annotation processing is performed as long as no processors is listed for security reasons.
* Therefore, you should always list the desired processors using this configuration element or {@code annotationProcessorPaths}.
*
* <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 processor}, {@code classpath-processor} or {@code modular-processor}.
*/
@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
*
* @deprecated This flag is ignored.
* Replaced by ordinary dependencies with {@code <type>} element set to
* {@code processor}, {@code classpath-processor} or {@code modular-processor}.
*/
@Deprecated(since = "4.0.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>
*
* @deprecated Setting this flag to {@code false} is replaced by {@code <debuglevel>none</debuglevel>}.
*/
@Deprecated(since = "4.0.0")
@Parameter(property = "maven.compiler.debug", defaultValue = "true")
protected boolean debug = true;
/**
* Kinds of debugging information to include in the compiled class files.
* Legal values are {@code lines}, {@code vars}, {@code source}, {@code all} and {@code none}.
* Values other than {@code all} and {@code none} can be combined in a comma-separated list.
*
* <p>If debug level is not specified, then the {@code -g} option will <em>not</em> be added,
* which means that the default debugging information will be generated
* (typically {@code lines} and {@code source} but not {@code vars}).</p>
*
* <p>If debug level is {@code all}, then only the {@code -g} option is added,
* which means that all debugging information will be generated.
* If debug level is anything else, then the comma-separated list of keywords
* is appended to the {@code -g} command-line switch.</p>
*
* @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.
* In addition, files such as {@code target/javac.args} will be generated even on successful compilation.
*
* @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 set to something else than {@code "none"}.
*
* @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 rebuild-on-change},
* {@code rebuild-on-add}, {@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 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 rebuild-on-add}:</b>
* modifier for recompiling all source files when the addition of a new file is detected.
* This flag is effective only when 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} for detecting renaming).</p>
*
* <p><b>{@code rebuild-on-change}:</b>
* modifier for recompiling all source files when a change is detected in at least one source file.
* This flag is effective only when used together with {@code sources} or {@code classes}.
* It does not rebuild when a new source file is added without change in other files,
* unless {@code rebuild-on-add} is also specified.</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.
*
* <h4>Default value</h4>
* The default value depends on the context.
* If there is no annotation processor, then the default is {@code "options,dependencies,sources"}.
* It means that a full rebuild will be done if the compiler options or the dependencies changed,
* or if a source file has been deleted. Otherwise, only the modified source files will be recompiled.
*
* <p>If an annotation processor is present (e.g., {@link #proc} set to a value other than {@code "none"}),
* then the default value is same as above with the addition of {@code "rebuild-on-add,rebuild-on-change"}.
* It means that a full rebuild will be done if any kind of change is detected.</p>
*
* @see #staleMillis
* @see #fileExtensions
* @see #showCompilationChanges
* @see #createMissingPackageInfoClass
* @since 4.0.0
*/
@Parameter(property = "maven.compiler.incrementalCompilation")
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,rebuild-on-add"}
* 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;
/**
* Returns the configuration of the incremental compilation.
* If the argument is null or blank, then this method applies
* the default values documented in {@link #incrementalCompilation} javadoc.
*
* @throws MojoException if a value is not recognized, or if mutually exclusive values are specified
*/
final EnumSet<IncrementalBuild.Aspect> incrementalCompilationConfiguration() {
if (isAbsent(incrementalCompilation)) {
if (useIncrementalCompilation != null) {
return useIncrementalCompilation
? EnumSet.of(
IncrementalBuild.Aspect.DEPENDENCIES,
IncrementalBuild.Aspect.SOURCES,
IncrementalBuild.Aspect.REBUILD_ON_ADD)
: EnumSet.of(IncrementalBuild.Aspect.CLASSES);
}
return EnumSet.of(
IncrementalBuild.Aspect.OPTIONS,
IncrementalBuild.Aspect.DEPENDENCIES,
IncrementalBuild.Aspect.SOURCES);
}
return IncrementalBuild.Aspect.parse(incrementalCompilation);
}
/**
* Amends the configuration of incremental compilation for the presence of annotation processors.
*
* @param aspects the configuration to amend if an annotation processor is found
* @param dependencyTypes the type of dependencies, for checking if any of them is a processor path
*/
final void amendincrementalCompilation(EnumSet<IncrementalBuild.Aspect> aspects, Set<PathType> dependencyTypes) {
if (isAbsent(incrementalCompilation) && hasAnnotationProcessor(dependencyTypes)) {
aspects.add(IncrementalBuild.Aspect.REBUILD_ON_ADD);
aspects.add(IncrementalBuild.Aspect.REBUILD_ON_CHANGE);
}
}
/**
* 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(defaultValue = "class,jar")
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.
*
* <h4>Thread safety</h4>
* This logger should be thread-safe if the {@link ToolExecutor} is executed in a background thread.
*/
@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 MAIN_COMPILE} if this MOJO is for compiling the main code,
* or {@code TEST_COMPILE} if compiling the tests.
*/
final PathScope compileScope;
/**
* Creates a new MOJO.
*
* @param compileScope {@code MAIN_COMPILE} or {@code TEST_COMPILE}
*/
protected AbstractCompilerMojo(PathScope compileScope) {
this.compileScope = compileScope;
}
/**
* {@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 a derivative of "glob" compatible with the
* behavior of Maven 3.
*/
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 a derivative of "glob" compatible with the
* behavior of Maven 3.
*/
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();
/**