forked from quarkusio/quarkus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DevMojo.java
1273 lines (1119 loc) · 52.1 KB
/
DevMojo.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
package io.quarkus.maven;
import static java.util.function.Predicate.not;
import static org.twdata.maven.mojoexecutor.MojoExecutor.artifactId;
import static org.twdata.maven.mojoexecutor.MojoExecutor.configuration;
import static org.twdata.maven.mojoexecutor.MojoExecutor.executeMojo;
import static org.twdata.maven.mojoexecutor.MojoExecutor.executionEnvironment;
import static org.twdata.maven.mojoexecutor.MojoExecutor.goal;
import static org.twdata.maven.mojoexecutor.MojoExecutor.groupId;
import static org.twdata.maven.mojoexecutor.MojoExecutor.plugin;
import static org.twdata.maven.mojoexecutor.MojoExecutor.version;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.aesh.readline.terminal.impl.ExecPty;
import org.aesh.readline.terminal.impl.Pty;
import org.aesh.terminal.Attributes;
import org.aesh.terminal.utils.ANSI;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.BuildBase;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.PluginExecution;
import org.apache.maven.model.Profile;
import org.apache.maven.model.Resource;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.BuildPluginManager;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.descriptor.MojoDescriptor;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
import org.apache.maven.shared.utils.cli.CommandLineUtils;
import org.apache.maven.toolchain.Toolchain;
import org.apache.maven.toolchain.ToolchainManager;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.artifact.DefaultArtifact;
import org.eclipse.aether.collection.CollectRequest;
import org.eclipse.aether.impl.RemoteRepositoryManager;
import org.eclipse.aether.repository.RemoteRepository;
import org.eclipse.aether.repository.WorkspaceReader;
import org.eclipse.aether.resolution.ArtifactRequest;
import org.eclipse.aether.resolution.ArtifactResolutionException;
import org.eclipse.aether.resolution.ArtifactResult;
import org.eclipse.aether.resolution.DependencyRequest;
import org.eclipse.aether.resolution.DependencyResolutionException;
import org.eclipse.aether.resolution.DependencyResult;
import org.eclipse.aether.util.artifact.JavaScopes;
import org.fusesource.jansi.internal.Kernel32;
import org.fusesource.jansi.internal.WindowsSupport;
import io.quarkus.bootstrap.BootstrapConstants;
import io.quarkus.bootstrap.app.QuarkusBootstrap;
import io.quarkus.bootstrap.devmode.DependenciesFilter;
import io.quarkus.bootstrap.model.ApplicationModel;
import io.quarkus.bootstrap.model.PathsCollection;
import io.quarkus.bootstrap.resolver.BootstrapAppModelResolver;
import io.quarkus.bootstrap.resolver.maven.MavenArtifactResolver;
import io.quarkus.bootstrap.resolver.maven.options.BootstrapMavenOptions;
import io.quarkus.bootstrap.util.BootstrapUtils;
import io.quarkus.bootstrap.workspace.ArtifactSources;
import io.quarkus.bootstrap.workspace.SourceDir;
import io.quarkus.deployment.dev.DevModeContext;
import io.quarkus.deployment.dev.DevModeMain;
import io.quarkus.deployment.dev.QuarkusDevModeLauncher;
import io.quarkus.maven.MavenDevModeLauncher.Builder;
import io.quarkus.maven.components.CompilerOptions;
import io.quarkus.maven.components.MavenVersionEnforcer;
import io.quarkus.maven.dependency.ArtifactKey;
import io.quarkus.maven.dependency.GACT;
import io.quarkus.maven.dependency.GACTV;
import io.quarkus.maven.dependency.ResolvedDependency;
import io.quarkus.paths.PathList;
import io.quarkus.runtime.LaunchMode;
/**
* The dev mojo, that runs a quarkus app in a forked process. A background compilation process is launched and any changes are
* automatically reflected in your running application.
* <p>
* You can use this dev mode in a remote container environment with {@code remote-dev}.
*/
@Mojo(name = "dev", defaultPhase = LifecyclePhase.PREPARE_PACKAGE, requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true)
public class DevMojo extends AbstractMojo {
private static final String EXT_PROPERTIES_PATH = "META-INF/quarkus-extension.properties";
private static final String KOTLIN_MAVEN_PLUGIN_GA = "org.jetbrains.kotlin:kotlin-maven-plugin";
/**
* running any one of these phases means the compile phase will have been run, if these have
* not been run we manually run compile.
*/
private static final List<String> POST_COMPILE_PHASES = List.of(
"compile",
"process-classes",
"generate-test-sources",
"process-test-sources",
"generate-test-resources",
"process-test-resources",
"test-compile",
"process-test-classes",
"test",
"prepare-package",
"package",
"pre-integration-test",
"integration-test",
"post-integration-test",
"verify",
"install",
"deploy");
/**
* running any one of these phases means the test-compile phase will have been run, if these have
* not been run we manually run test-compile
*/
private static final List<String> POST_TEST_COMPILE_PHASES = List.of(
"test-compile",
"process-test-classes",
"test",
"prepare-package",
"package",
"pre-integration-test",
"integration-test",
"post-integration-test",
"verify",
"install",
"deploy");
private static final String QUARKUS_GENERATE_CODE_GOAL = "generate-code";
private static final String QUARKUS_GENERATE_CODE_TESTS_GOAL = "generate-code-tests";
private static final String ORG_APACHE_MAVEN_PLUGINS = "org.apache.maven.plugins";
private static final String MAVEN_COMPILER_PLUGIN = "maven-compiler-plugin";
private static final String MAVEN_RESOURCES_PLUGIN = "maven-resources-plugin";
private static final String MAVEN_TOOLCHAINS_PLUGIN = "maven-toolchains-plugin";
private static final String ORG_JETBRAINS_KOTLIN = "org.jetbrains.kotlin";
private static final String KOTLIN_MAVEN_PLUGIN = "kotlin-maven-plugin";
private static final String ORG_JBOSS_JANDEX = "org.jboss.jandex";
private static final String JANDEX_MAVEN_PLUGIN = "jandex-maven-plugin";
/**
* The directory for compiled classes.
*/
@Parameter(readonly = true, required = true, defaultValue = "${project.build.outputDirectory}")
private File outputDirectory;
@Parameter(defaultValue = "${project}", readonly = true, required = true)
protected MavenProject project;
/**
* If this server should be started in debug mode. The default is to start in debug mode and listen on
* port 5005. Whether or not the JVM is suspended waiting for a debugger to be attached,
* depends on the value of {@link #suspend}.
* <p>
* {@code debug} supports the following options:
* <table>
* <tr>
* <td><b>Value</b></td>
* <td>Effect</td>
* </tr>
* <tr>
* <td><b>false</b></td>
* <td>The JVM is not started in debug mode</td>
* </tr>
* <tr>
* <td><b>true</b></td>
* <td>The JVM is started in debug mode and will be listening on {@code debugHost}:{@code debugPort}</td>
* </tr>
* <tr>
* <td><b>client</b></td>
* <td>The JVM is started in client mode, and will attempt to connect to {@code debugHost}:{@code debugPort}</td>
* </tr>
* <tr>
* <td><b>{port}</b></td>
* <td>The JVM is started in debug mode and will be listening on {@code debugHost}:{port}.</td>
* </tr>
* </table>
* By default, {@code debugHost} has the value "localhost", and {@code debugPort} is 5005.
*/
@Parameter(defaultValue = "${debug}")
private String debug;
@Parameter(defaultValue = "${open-lang-package}")
private boolean openJavaLang;
/**
* Whether or not the JVM launch, in debug mode, should be suspended. This parameter is only
* relevant when the JVM is launched in {@link #debug debug mode}. This parameter supports the
* following values (all the allowed values are case insensitive):
* <table>
* <th>
* <td>Value</td>
* <td>Effect</td>
* </th>
* <tr>
* <td>y or true</td>
* <td>The debug mode JVM launch is suspended</td>
* </tr>
* <tr>
* <td>n or false</td>
* <td>The debug mode JVM is started without suspending</td>
* </tr>
* </table>
*/
@Parameter(defaultValue = "${suspend}")
private String suspend;
@Parameter(defaultValue = "${debugHost}")
private String debugHost;
@Parameter(defaultValue = "${debugPort}")
private String debugPort;
@Parameter(defaultValue = "${project.build.directory}")
private File buildDir;
@Parameter(defaultValue = "${project.build.sourceDirectory}")
private File sourceDir;
@Parameter
private File workingDir;
@Parameter(defaultValue = "${jvm.args}")
private String jvmArgs;
@Parameter(defaultValue = "${quarkus.args}")
private String argsString;
@Parameter
private Map<String, String> environmentVariables = Collections.emptyMap();
@Parameter
private Map<String, String> systemProperties = Collections.emptyMap();
@Parameter(defaultValue = "${session}")
private MavenSession session;
@Parameter(defaultValue = "TRUE")
private boolean deleteDevJar;
@Component
private MavenVersionEnforcer mavenVersionEnforcer;
@Component
private RepositorySystem repoSystem;
@Component
RemoteRepositoryManager remoteRepositoryManager;
@Parameter(defaultValue = "${repositorySystemSession}", readonly = true)
private RepositorySystemSession repoSession;
@Parameter(defaultValue = "${project.remoteProjectRepositories}", readonly = true, required = true)
private List<RemoteRepository> repos;
@Parameter(defaultValue = "${project.remotePluginRepositories}", readonly = true, required = true)
private List<RemoteRepository> pluginRepos;
/**
* This value is intended to be set to true when some generated bytecode
* is erroneous causing the JVM to crash when the verify:none option is set (which is on by default)
*/
@Parameter(defaultValue = "${preventnoverify}")
private boolean preventnoverify = false;
/**
* Whether changes in the projects that appear to be dependencies of the project containing the application to be launched
* should trigger hot-reload. By default they do.
*/
@Parameter(defaultValue = "${noDeps}")
private boolean noDeps = false;
/**
* Additional parameters to pass to javac when recompiling changed
* source files.
*/
@Parameter
private List<String> compilerArgs;
/**
* Additional compiler arguments
*/
@Parameter
private List<CompilerOptions> compilerOptions;
/**
* The --release argument to javac.
*/
@Parameter(defaultValue = "${maven.compiler.release}")
private String release;
/**
* The -source argument to javac.
*/
@Parameter(defaultValue = "${maven.compiler.source}")
private String source;
/**
* The -target argument to javac.
*/
@Parameter(defaultValue = "${maven.compiler.target}")
private String target;
/**
* Whether or not to enforce the quarkus-maven-plugin build goal to be configured.
* By default, a missing build goal is considered an inconsistency (although the build goal is not <i>required</i>
* technically).
* In this case a warning will be logged and the application will not be started.
*/
@Parameter(defaultValue = "${quarkus.enforceBuildGoal}")
private boolean enforceBuildGoal = true;
@Component
private WorkspaceReader wsReader;
@Component
private BuildPluginManager pluginManager;
@Component
private ToolchainManager toolchainManager;
private Map<GACT, Plugin> pluginMap;
@Component
protected QuarkusBootstrapProvider bootstrapProvider;
@Parameter(defaultValue = "${mojoExecution}", readonly = true, required = true)
MojoExecution mojoExecution;
/**
* console attributes, used to restore the console state
*/
private Attributes attributes;
private int windowsAttributes;
private boolean windowsAttributesSet;
private Pty pty;
private boolean windowsColorSupport;
@Override
public void setLog(Log log) {
super.setLog(log);
MojoLogger.delegate = log;
}
@Override
public void execute() throws MojoFailureException, MojoExecutionException {
mavenVersionEnforcer.ensureMavenVersion(getLog(), session);
initToolchain();
// we always want to compile if needed, so if it is run from the parent it will compile dependent projects
handleAutoCompile();
if (enforceBuildGoal) {
final PluginDescriptor pluginDescr = getPluginDescriptor();
final Plugin pluginDef = getConfiguredPluginOrNull(pluginDescr.getGroupId(), pluginDescr.getArtifactId());
if (pluginDef == null || !isGoalConfigured(pluginDef, "build")) {
getLog().warn("The quarkus-maven-plugin build goal was not configured for this project," +
" skipping quarkus:dev as this is assumed to be a support library. If you want to run quarkus:dev" +
" on this project make sure the quarkus-maven-plugin is configured with the build goal" +
" or disable the enforceBuildGoal flag (via plugin configuration or via" +
" -Dquarkus.enforceBuildGoal=false).");
return;
}
}
saveTerminalState();
try {
DevModeRunner runner = new DevModeRunner();
Map<Path, Long> pomFiles = readPomFileTimestamps(runner);
runner.run();
long nextCheck = System.currentTimeMillis() + 100;
for (;;) {
//we never suspend after the first run
suspend = "n";
long sleep = Math.max(0, nextCheck - System.currentTimeMillis()) + 1;
Thread.sleep(sleep);
if (System.currentTimeMillis() > nextCheck) {
nextCheck = System.currentTimeMillis() + 100;
if (!runner.alive()) {
restoreTerminalState();
if (!runner.isExpectedExitValue()) {
throw new MojoExecutionException("Dev mode process did not complete successfully");
}
return;
}
final Set<Path> changed = new HashSet<>();
for (Map.Entry<Path, Long> e : pomFiles.entrySet()) {
long t = Files.getLastModifiedTime(e.getKey()).toMillis();
if (t > e.getValue()) {
changed.add(e.getKey());
pomFiles.put(e.getKey(), t);
}
}
if (!changed.isEmpty()) {
getLog().info("Changes detected to " + changed + ", restarting dev mode");
final DevModeRunner newRunner;
try {
triggerCompile(false, false);
triggerCompile(true, false);
newRunner = new DevModeRunner();
} catch (Exception e) {
getLog().info("Could not load changed pom.xml file, changes not applied", e);
continue;
}
runner.stop();
newRunner.run();
runner = newRunner;
}
}
}
} catch (Exception e) {
throw new MojoFailureException("Failed to run", e);
}
}
/**
* if the process is forcibly killed then the terminal may be left in raw mode, which
* messes everything up. This attempts to fix that by saving the state so it can be restored
*/
private void saveTerminalState() {
try {
windowsAttributes = WindowsSupport.getConsoleMode();
windowsAttributesSet = true;
if (windowsAttributes > 0) {
long hConsole = Kernel32.GetStdHandle(Kernel32.STD_INPUT_HANDLE);
if (hConsole != (long) Kernel32.INVALID_HANDLE_VALUE) {
final int VIRTUAL_TERMINAL_PROCESSING = 0x0004; //enable color on the windows console
if (Kernel32.SetConsoleMode(hConsole, windowsAttributes | VIRTUAL_TERMINAL_PROCESSING) != 0) {
windowsColorSupport = true;
}
}
}
} catch (Throwable t) {
//this only works with a proper PTY based terminal
//Aesh creates an input pump thread, that will steal
//input from the dev mode process
try {
Pty pty = ExecPty.current();
attributes = pty.getAttr();
DevMojo.this.pty = pty;
} catch (Exception e) {
getLog().debug("Failed to get a local tty", e);
}
}
}
private void restoreTerminalState() {
if (windowsAttributesSet) {
WindowsSupport.setConsoleMode(windowsAttributes);
} else {
if (attributes == null || pty == null) {
return;
}
Pty finalPty = pty;
try (finalPty) {
finalPty.setAttr(attributes);
int height = finalPty.getSize().getHeight();
String sb = ANSI.MAIN_BUFFER +
ANSI.CURSOR_SHOW +
"\u001B[0m" +
"\033[" + height + ";0H";
finalPty.getSlaveOutput().write(sb.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
getLog().error("Error restoring console state", e);
}
}
}
private void handleAutoCompile() throws MojoExecutionException {
//we check to see if there was a compile (or later) goal before this plugin
boolean compileNeeded = true;
boolean testCompileNeeded = true;
boolean prepareNeeded = true;
boolean prepareTestsNeeded = true;
String jandexGoalPhase = getGoalPhaseOrNull(ORG_JBOSS_JANDEX, JANDEX_MAVEN_PLUGIN, "jandex", "process-classes");
boolean indexClassNeeded = jandexGoalPhase != null;
for (String goal : session.getGoals()) {
if (goal.endsWith("quarkus:generate-code")) {
prepareNeeded = false;
}
if (goal.endsWith("quarkus:generate-code-tests")) {
prepareTestsNeeded = false;
}
if (POST_COMPILE_PHASES.contains(goal)) {
compileNeeded = false;
}
if (jandexGoalPhase != null
&& POST_COMPILE_PHASES.indexOf(goal) >= POST_COMPILE_PHASES.indexOf(jandexGoalPhase)) {
indexClassNeeded = false;
}
if (POST_TEST_COMPILE_PHASES.contains(goal)) {
testCompileNeeded = false;
}
if (goal.endsWith("quarkus:dev")) {
break;
}
}
//if the user did not compile we run it for them
if (compileNeeded) {
triggerCompile(false, prepareNeeded);
}
if (indexClassNeeded) {
initClassIndexes();
}
if (testCompileNeeded) {
try {
triggerCompile(true, prepareTestsNeeded);
} catch (Throwable t) {
getLog().error("Test compile failed, you will need to fix your tests before you can use continuous testing", t);
}
}
}
private void initToolchain() throws MojoExecutionException {
executeIfConfigured(ORG_APACHE_MAVEN_PLUGINS, MAVEN_TOOLCHAINS_PLUGIN, "toolchain", Collections.emptyMap());
}
private void triggerPrepare(boolean test) throws MojoExecutionException {
final PluginDescriptor pluginDescr = getPluginDescriptor();
executeIfConfigured(pluginDescr.getGroupId(), pluginDescr.getArtifactId(),
test ? QUARKUS_GENERATE_CODE_TESTS_GOAL : QUARKUS_GENERATE_CODE_GOAL,
Map.of("mode", LaunchMode.DEVELOPMENT.name(), QuarkusBootstrapMojo.CLOSE_BOOTSTRAPPED_APP, "false"));
}
private void initClassIndexes() throws MojoExecutionException {
executeIfConfigured(ORG_JBOSS_JANDEX, JANDEX_MAVEN_PLUGIN, "jandex", Collections.emptyMap());
}
private PluginDescriptor getPluginDescriptor() {
return mojoExecution.getMojoDescriptor().getPluginDescriptor();
}
private void triggerCompile(boolean test, boolean prepareNeeded) throws MojoExecutionException {
handleResources(test);
if (prepareNeeded) {
triggerPrepare(test);
}
// compile the Kotlin sources if needed
executeIfConfigured(ORG_JETBRAINS_KOTLIN, KOTLIN_MAVEN_PLUGIN, test ? "test-compile" : "compile",
Collections.emptyMap());
// Compile the Java sources if needed
executeIfConfigured(ORG_APACHE_MAVEN_PLUGINS, MAVEN_COMPILER_PLUGIN, test ? "testCompile" : "compile",
Collections.emptyMap());
}
/**
* Execute the resources:resources goal if resources have been configured on the project
*/
private void handleResources(boolean test) throws MojoExecutionException {
List<Resource> resources = project.getResources();
if (resources.isEmpty()) {
return;
}
executeIfConfigured(ORG_APACHE_MAVEN_PLUGINS, MAVEN_RESOURCES_PLUGIN, test ? "testResources" : "resources",
Collections.emptyMap());
}
private void executeIfConfigured(String pluginGroupId, String pluginArtifactId, String goal, Map<String, String> params)
throws MojoExecutionException {
final Plugin plugin = getConfiguredPluginOrNull(pluginGroupId, pluginArtifactId);
if (!isGoalConfigured(plugin, goal)) {
return;
}
getLog().info("Invoking " + plugin.getGroupId() + ":" + plugin.getArtifactId() + ":" + plugin.getVersion() + ":" + goal
+ ") @ " + project.getArtifactId());
executeMojo(
plugin(
groupId(pluginGroupId),
artifactId(pluginArtifactId),
version(plugin.getVersion()),
plugin.getDependencies()),
goal(goal),
getPluginConfig(plugin, goal, params),
executionEnvironment(
project,
session,
pluginManager));
}
private String getGoalPhaseOrNull(String groupId, String artifactId, String goal, String defaultPhase) {
Plugin plugin = getConfiguredPluginOrNull(groupId, artifactId);
if (plugin == null) {
return null;
}
for (PluginExecution pluginExecution : plugin.getExecutions()) {
if (pluginExecution.getGoals().contains(goal)) {
var configuredPhase = pluginExecution.getPhase();
return configuredPhase != null ? configuredPhase : defaultPhase;
}
}
return null;
}
public boolean isGoalConfigured(Plugin plugin, String goal) {
if (plugin == null) {
return false;
}
for (PluginExecution pluginExecution : plugin.getExecutions()) {
if (pluginExecution.getGoals().contains(goal)) {
return true;
}
}
return false;
}
private Xpp3Dom getPluginConfig(Plugin plugin, String goal, Map<String, String> params) throws MojoExecutionException {
Xpp3Dom mergedConfig = null;
if (!plugin.getExecutions().isEmpty()) {
for (PluginExecution exec : plugin.getExecutions()) {
if (exec.getConfiguration() != null && exec.getGoals().contains(goal)) {
mergedConfig = mergedConfig == null ? (Xpp3Dom) exec.getConfiguration()
: Xpp3Dom.mergeXpp3Dom(mergedConfig, (Xpp3Dom) exec.getConfiguration(), true);
}
}
}
if ((Xpp3Dom) plugin.getConfiguration() != null) {
mergedConfig = mergedConfig == null ? (Xpp3Dom) plugin.getConfiguration()
: Xpp3Dom.mergeXpp3Dom(mergedConfig, (Xpp3Dom) plugin.getConfiguration(), true);
}
final Xpp3Dom configuration = configuration();
if (mergedConfig != null) {
Set<String> supportedParams = null;
// Filter out `test*` configurations
for (Xpp3Dom child : mergedConfig.getChildren()) {
if (child.getName().startsWith("test")) {
continue;
}
if (supportedParams == null) {
supportedParams = getMojoDescriptor(plugin, goal).getParameterMap().keySet();
}
if (supportedParams.contains(child.getName())) {
configuration.addChild(child);
}
}
}
for (Map.Entry<String, String> param : params.entrySet()) {
final Xpp3Dom p = new Xpp3Dom(param.getKey());
p.setValue(param.getValue());
configuration.addChild(p);
}
return configuration;
}
private MojoDescriptor getMojoDescriptor(Plugin plugin, String goal) throws MojoExecutionException {
try {
return pluginManager.getMojoDescriptor(plugin, goal, pluginRepos, repoSession);
} catch (Exception e) {
throw new MojoExecutionException(
"Failed to obtain descriptor for Maven plugin " + plugin.getId() + " goal " + goal, e);
}
}
private Plugin getConfiguredPluginOrNull(String groupId, String artifactId) {
if (pluginMap == null) {
pluginMap = new HashMap<>();
// the original plugin keys may include property expressions, so we can't rely on the exact groupId:artifactId keys
for (Plugin p : project.getBuildPlugins()) {
pluginMap.put(new GACT(p.getGroupId(), p.getArtifactId()), p);
}
}
return pluginMap.get(new GACT(groupId, artifactId));
}
private Map<Path, Long> readPomFileTimestamps(DevModeRunner runner) throws IOException {
Map<Path, Long> ret = new HashMap<>();
for (Path i : runner.pomFiles()) {
ret.put(i, Files.getLastModifiedTime(i).toMillis());
}
return ret;
}
private String getSourceEncoding() {
Object sourceEncodingProperty = project.getProperties().get("project.build.sourceEncoding");
if (sourceEncodingProperty != null) {
return (String) sourceEncodingProperty;
}
return null;
}
private void addProject(MavenDevModeLauncher.Builder builder, ResolvedDependency module, boolean root) throws Exception {
if (!ArtifactCoords.TYPE_JAR.equals(module.getType())) {
return;
}
String projectDirectory;
Set<Path> sourcePaths;
String classesPath = null;
Set<Path> resourcePaths;
Set<Path> testSourcePaths;
String testClassesPath = null;
Set<Path> testResourcePaths;
List<Profile> activeProfiles = Collections.emptyList();
final MavenProject mavenProject = module.getClassifier().isEmpty()
? session.getProjectMap()
.get(String.format("%s:%s:%s", module.getGroupId(), module.getArtifactId(), module.getVersion()))
: null;
final ArtifactSources sources = module.getSources();
if (mavenProject == null) {
if (sources == null) {
getLog().debug("Local dependency " + module.toCompactCoords() + " does not appear to have any sources");
return;
}
projectDirectory = module.getWorkspaceModule().getModuleDir().getAbsolutePath();
sourcePaths = new LinkedHashSet<>();
for (SourceDir src : sources.getSourceDirs()) {
for (Path p : src.getSourceTree().getRoots()) {
sourcePaths.add(p.toAbsolutePath());
}
}
testSourcePaths = new LinkedHashSet<>();
ArtifactSources testSources = module.getWorkspaceModule().getTestSources();
if (testSources != null) {
for (SourceDir src : testSources.getSourceDirs()) {
for (Path p : src.getSourceTree().getRoots()) {
testSourcePaths.add(p.toAbsolutePath());
}
}
}
} else {
projectDirectory = mavenProject.getBasedir().getPath();
sourcePaths = mavenProject.getCompileSourceRoots().stream()
.map(Paths::get)
.map(Path::toAbsolutePath)
.collect(Collectors.toCollection(LinkedHashSet::new));
testSourcePaths = mavenProject.getTestCompileSourceRoots().stream()
.map(Paths::get)
.map(Path::toAbsolutePath)
.collect(Collectors.toCollection(LinkedHashSet::new));
activeProfiles = mavenProject.getActiveProfiles();
}
final Path sourceParent;
if (sourcePaths.isEmpty()) {
if (sources == null || sources.getResourceDirs() == null) {
throw new MojoExecutionException(
"Local dependency " + module.toCompactCoords() + " does not appear to have any sources");
}
sourceParent = sources.getResourceDirs().iterator().next().getDir().toAbsolutePath().getParent();
} else {
sourceParent = sourcePaths.iterator().next().toAbsolutePath().getParent();
}
Path classesDir = null;
resourcePaths = new LinkedHashSet<>();
if (sources != null) {
classesDir = sources.getSourceDirs().iterator().next().getOutputDir().toAbsolutePath();
if (Files.isDirectory(classesDir)) {
classesPath = classesDir.toString();
}
for (SourceDir src : sources.getResourceDirs()) {
for (Path p : src.getSourceTree().getRoots()) {
resourcePaths.add(p.toAbsolutePath());
}
}
}
if (module.getWorkspaceModule().hasTestSources()) {
Path testClassesDir = module.getWorkspaceModule().getTestSources().getSourceDirs().iterator().next().getOutputDir()
.toAbsolutePath();
testClassesPath = testClassesDir.toString();
}
testResourcePaths = new LinkedHashSet<>();
ArtifactSources testSources = module.getWorkspaceModule().getTestSources();
if (testSources != null) {
for (SourceDir src : testSources.getResourceDirs()) {
for (Path p : src.getSourceTree().getRoots()) {
testResourcePaths.add(p.toAbsolutePath());
}
}
}
// Add the resources and test resources from the profiles
for (Profile profile : activeProfiles) {
final BuildBase build = profile.getBuild();
if (build != null) {
resourcePaths.addAll(
build.getResources().stream()
.map(Resource::getDirectory)
.map(Path::of)
.map(Path::toAbsolutePath)
.collect(Collectors.toList()));
testResourcePaths.addAll(
build.getTestResources().stream()
.map(Resource::getDirectory)
.map(Path::of)
.map(Path::toAbsolutePath)
.collect(Collectors.toList()));
}
}
if (classesPath == null && (!sourcePaths.isEmpty() || !resourcePaths.isEmpty())) {
throw new MojoExecutionException("Hot reloadable dependency " + module.getWorkspaceModule().getId()
+ " has not been compiled yet (the classes directory " + (classesDir == null ? "" : classesDir)
+ " does not exist)");
}
Path targetDir = Path.of(project.getBuild().getDirectory());
DevModeContext.ModuleInfo moduleInfo = new DevModeContext.ModuleInfo.Builder()
.setArtifactKey(module.getKey())
.setProjectDirectory(projectDirectory)
.setSourcePaths(PathList.from(sourcePaths))
.setClassesPath(classesPath)
.setResourcesOutputPath(classesPath)
.setResourcePaths(PathList.from(resourcePaths))
.setSourceParents(PathList.of(sourceParent.toAbsolutePath()))
.setPreBuildOutputDir(targetDir.resolve("generated-sources").toAbsolutePath().toString())
.setTargetDir(targetDir.toAbsolutePath().toString())
.setTestSourcePaths(PathList.from(testSourcePaths))
.setTestClassesPath(testClassesPath)
.setTestResourcesOutputPath(testClassesPath)
.setTestResourcePaths(PathList.from(testResourcePaths))
.build();
if (root) {
builder.mainModule(moduleInfo);
} else {
builder.dependency(moduleInfo);
}
}
private class DevModeRunner {
final QuarkusDevModeLauncher launcher;
private Process process;
private DevModeRunner() throws Exception {
launcher = newLauncher();
}
Collection<Path> pomFiles() {
return launcher.watchedBuildFiles();
}
boolean alive() {
return process != null && process.isAlive();
}
int exitValue() {
return process == null ? -1 : process.exitValue();
}
boolean isExpectedExitValue() {
// '130' is what the process exits with in remote-dev mode under bash
return exitValue() == 0 || exitValue() == 130;
}
void run() throws Exception {
// Display the launch command line in dev mode
if (getLog().isDebugEnabled()) {
getLog().debug("Launching JVM with command line: " + String.join(" ", launcher.args()));
}
final ProcessBuilder processBuilder = new ProcessBuilder(launcher.args())
.redirectErrorStream(true)
.inheritIO()
.directory(workingDir == null ? project.getBasedir() : workingDir);
if (!environmentVariables.isEmpty()) {
processBuilder.environment().putAll(environmentVariables);
}
process = processBuilder.start();
//https://github.com/quarkusio/quarkus/issues/232
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
process.destroy();
try {
process.waitFor();
} catch (InterruptedException e) {
getLog().warn("Unable to properly wait for dev-mode end", e);
}
}
}, "Development Mode Shutdown Hook"));
}
void stop() throws InterruptedException {
process.destroy();
process.waitFor();
}
}
private QuarkusDevModeLauncher newLauncher() throws Exception {
String java = null;
// See if a toolchain is configured
if (toolchainManager != null) {
Toolchain toolchain = toolchainManager.getToolchainFromBuildContext("jdk", session);
if (toolchain != null) {
java = toolchain.findTool("java");
getLog().info("JVM from toolchain: " + java);
}
}
final MavenDevModeLauncher.Builder builder = MavenDevModeLauncher.builder(java, getLog())
.preventnoverify(preventnoverify)
.buildDir(buildDir)
.outputDir(outputDirectory)
.suspend(suspend)
.debug(debug)
.debugHost(debugHost)
.debugPort(debugPort)
.deleteDevJar(deleteDevJar);
setJvmArgs(builder);
if (windowsColorSupport) {
builder.jvmArgs("-Dio.quarkus.force-color-support=true");
}
if (openJavaLang) {
builder.jvmArgs("--add-opens");
builder.jvmArgs("java.base/java.lang=ALL-UNNAMED");
}
builder.projectDir(project.getFile().getParentFile());
builder.buildSystemProperties((Map) project.getProperties());
builder.applicationName(project.getArtifactId());
builder.applicationVersion(project.getVersion());
builder.sourceEncoding(getSourceEncoding());
if (compilerOptions != null) {
for (CompilerOptions compilerOption : compilerOptions) {
builder.compilerOptions(compilerOption.getName(), compilerOption.getArgs());
}
}
// Set compilation flags. Try the explicitly given configuration first. Otherwise,
// refer to the configuration of the Maven Compiler Plugin.
final Optional<Xpp3Dom> compilerPluginConfiguration = findCompilerPluginConfiguration();
if (compilerArgs != null) {
builder.compilerOptions("java", compilerArgs);
} else if (compilerPluginConfiguration.isPresent()) {
final Xpp3Dom compilerPluginArgsConfiguration = compilerPluginConfiguration.get().getChild("compilerArgs");
if (compilerPluginArgsConfiguration != null) {
List<String> compilerPluginArgs = new ArrayList<>();
for (Xpp3Dom argConfiguration : compilerPluginArgsConfiguration.getChildren()) {
compilerPluginArgs.add(argConfiguration.getValue());
}
// compilerArgs can also take a value without using arg
if (compilerPluginArgsConfiguration.getValue() != null
&& !compilerPluginArgsConfiguration.getValue().isEmpty()) {
compilerPluginArgs.add(compilerPluginArgsConfiguration.getValue().trim());
}
builder.compilerOptions("java", compilerPluginArgs);
}
}