-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
CreateProjectMojo.java
477 lines (412 loc) · 20 KB
/
CreateProjectMojo.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
package io.quarkus.maven;
import static io.quarkus.devtools.project.CodestartResourceLoadersBuilder.codestartLoadersBuilder;
import static org.fusesource.jansi.Ansi.ansi;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Model;
import org.apache.maven.model.Parent;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.BuildPluginManager;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectBuilder;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.impl.RemoteRepositoryManager;
import org.eclipse.aether.repository.RemoteRepository;
import org.fusesource.jansi.Ansi;
import io.quarkus.bootstrap.resolver.maven.MavenArtifactResolver;
import io.quarkus.devtools.commands.CreateProject;
import io.quarkus.devtools.commands.CreateProjectHelper;
import io.quarkus.devtools.messagewriter.MessageWriter;
import io.quarkus.devtools.project.BuildTool;
import io.quarkus.devtools.project.QuarkusProject;
import io.quarkus.devtools.project.QuarkusProjectHelper;
import io.quarkus.maven.components.MavenVersionEnforcer;
import io.quarkus.maven.components.Prompter;
import io.quarkus.maven.utilities.MojoUtils;
import io.quarkus.platform.descriptor.loader.json.ResourceLoader;
import io.quarkus.platform.tools.ToolsUtils;
import io.quarkus.platform.tools.maven.MojoMessageWriter;
import io.quarkus.registry.ExtensionCatalogResolver;
import io.quarkus.registry.RegistryResolutionException;
import io.quarkus.registry.catalog.ExtensionCatalog;
/**
* This goal helps in setting up Quarkus Maven project with quarkus-maven-plugin, with sensible defaults
*/
@Mojo(name = "create", requiresProject = false)
public class CreateProjectMojo extends AbstractMojo {
private static final String DEFAULT_GROUP_ID = "org.acme";
private static final String DEFAULT_ARTIFACT_ID = "code-with-quarkus";
private static final String DEFAULT_VERSION = "1.0.0-SNAPSHOT";
private static final String DEFAULT_EXTENSIONS = "resteasy";
@Parameter(defaultValue = "${project}")
protected MavenProject project;
@Parameter(property = "projectGroupId")
private String projectGroupId;
@Parameter(property = "projectArtifactId")
private String projectArtifactId;
@Parameter(property = "projectVersion")
private String projectVersion;
/**
* When true, do not include any code in the generated Quarkus project.
*/
@Parameter(property = "noCode", defaultValue = "false")
private boolean noCode;
@Parameter(property = "example")
private String example;
/**
* Group ID of the target platform BOM
*/
@Parameter(property = "platformGroupId", required = false)
private String bomGroupId;
/**
* Artifact ID of the target platform BOM
*/
@Parameter(property = "platformArtifactId", required = false)
private String bomArtifactId;
/**
* Version of the target platform BOM
*/
@Parameter(property = "platformVersion", required = false)
private String bomVersion;
@Parameter(property = "javaVersion")
private String javaVersion;
/**
* The {@link #path} will define the REST path of the generated code when picking only one of those extensions resteasy,
* resteasy-reactive and spring-web.
* <br />
* If more than one of those extensions are picked, this parameter will be ignored.
* <br />
* More info: https://github.com/quarkusio/quarkus/issues/14437
* <br />
* {@code className}
*/
@Parameter(property = "path")
private String path;
/**
* The {@link #className} will define the generated class names when picking only one of those extensions resteasy,
* resteasy-reactive and spring-web.
* <br />
* If more than one of those extensions are picked, then only the package name part will be used as {@link #packageName}
* <br />
* More info: https://github.com/quarkusio/quarkus/issues/14437
* <br />
* By default, the {@link #projectGroupId} is used as package for generated classes (you can also use {@link #packageName}
* to have them different).
* <br />
* {@code className}
*/
@Parameter(property = "className")
private String className;
/**
* Set the package name of the generated classes.
* <br />
* If not set, {@link #projectGroupId} will be used as {@link #packageName}
* <p>
* {@code packageName}
*/
@Parameter(property = "packageName")
private String packageName;
@Parameter(property = "buildTool", defaultValue = "MAVEN")
private String buildTool;
@Parameter(property = "extensions")
private Set<String> extensions;
@Parameter(property = "outputDirectory", defaultValue = "${basedir}")
private File outputDirectory;
@Parameter(defaultValue = "${session}")
private MavenSession session;
@Parameter(defaultValue = "${project.remoteProjectRepositories}", readonly = true, required = true)
private List<RemoteRepository> repos;
@Parameter(defaultValue = "${repositorySystemSession}", readonly = true)
private RepositorySystemSession repoSession;
@Component
private MavenVersionEnforcer mavenVersionEnforcer;
@Component
private BuildPluginManager pluginManager;
@Component
private ProjectBuilder projectBuilder;
@Component
private RepositorySystem repoSystem;
@Component
RemoteRepositoryManager remoteRepoManager;
@Parameter(property = "appConfig")
private String appConfig;
@Override
public void execute() throws MojoExecutionException {
// We detect the Maven version during the project generation to indicate the user immediately that the installed
// version may not be supported.
mavenVersionEnforcer.ensureMavenVersion(getLog(), session);
try {
Files.createDirectories(outputDirectory.toPath());
} catch (IOException e) {
throw new MojoExecutionException("Could not create directory " + outputDirectory, e);
}
final MavenArtifactResolver mvn;
try {
mvn = MavenArtifactResolver.builder()
.setRepositorySystem(repoSystem)
.setRepositorySystemSession(
getLog().isDebugEnabled() ? repoSession : MojoUtils.muteTransferListener(repoSession))
.setRemoteRepositories(repos)
.setRemoteRepositoryManager(remoteRepoManager)
.build();
} catch (Exception e) {
throw new MojoExecutionException("Failed to initialize Maven artifact resolver", e);
}
final MojoMessageWriter log = new MojoMessageWriter(getLog());
ExtensionCatalogResolver catalogResolver;
try {
catalogResolver = QuarkusProjectHelper.isRegistryClientEnabled()
? QuarkusProjectHelper.getCatalogResolver(mvn, log)
: ExtensionCatalogResolver.empty();
} catch (RegistryResolutionException e) {
// fall back to the default platform
catalogResolver = ExtensionCatalogResolver.empty();
}
ExtensionCatalog catalog = resolveExtensionsCatalog(this, bomGroupId, bomArtifactId, bomVersion, catalogResolver,
mvn, log);
File projectRoot = outputDirectory;
File pom = project != null ? project.getFile() : null;
Model parentPomModel = null;
boolean containsAtLeastOneGradleFile = false;
for (String gradleFile : Arrays.asList("build.gradle", "settings.gradle", "build.gradle.kts", "settings.gradle.kts")) {
containsAtLeastOneGradleFile |= new File(projectRoot, gradleFile).isFile();
}
BuildTool buildToolEnum = BuildTool.findTool(buildTool);
if (buildToolEnum == null) {
String validBuildTools = String.join(",",
Arrays.asList(BuildTool.values()).stream().map(BuildTool::toString).collect(Collectors.toList()));
throw new IllegalArgumentException("Choose a valid build tool. Accepted values are: " + validBuildTools);
}
if (BuildTool.MAVEN.equals(buildToolEnum)) {
if (pom != null && pom.isFile()) {
try {
parentPomModel = MojoUtils.readPom(pom);
if (!"pom".equals(parentPomModel.getPackaging())) {
throw new MojoExecutionException(
"The parent project must have a packaging type of POM. Current packaging: "
+ parentPomModel.getPackaging());
}
} catch (IOException e) {
throw new MojoExecutionException("Could not access parent pom.", e);
}
} else if (containsAtLeastOneGradleFile) {
throw new MojoExecutionException(
"You are trying to create a Maven project in a directory that contains only Gradle build files.");
}
} else if (BuildTool.GRADLE.equals(buildToolEnum) || BuildTool.GRADLE_KOTLIN_DSL.equals(buildToolEnum)) {
if (containsAtLeastOneGradleFile) {
throw new MojoExecutionException("Adding subprojects to gradle projects is not implemented.");
} else if (pom != null && pom.isFile()) {
throw new MojoExecutionException(
"You are trying to create gradle project in a directory that contains only maven build files.");
}
}
askTheUserForMissingValues();
projectRoot = new File(outputDirectory, projectArtifactId);
if (projectRoot.exists()) {
throw new MojoExecutionException("Unable to create the project, " +
"the directory " + projectRoot.getAbsolutePath() + " already exists");
}
boolean success;
final Path projectDirPath = projectRoot.toPath();
try {
extensions = CreateProjectHelper.sanitizeExtensions(extensions);
catalog = CreateProjectHelper.completeCatalog(catalog, extensions, mvn);
sanitizeOptions();
final List<ResourceLoader> codestartsResourceLoader = codestartLoadersBuilder()
.catalog(catalog)
.artifactResolver(mvn)
.build();
QuarkusProject newProject = QuarkusProject.of(projectDirPath, catalog,
codestartsResourceLoader, log, buildToolEnum);
final CreateProject createProject = new CreateProject(newProject)
.groupId(projectGroupId)
.artifactId(projectArtifactId)
.version(projectVersion)
.javaVersion(javaVersion)
.resourceClassName(className)
.packageName(packageName)
.extensions(extensions)
.resourcePath(path)
.example(example)
.noCode(noCode)
.appConfig(appConfig);
success = createProject.execute().isSuccess();
if (success && parentPomModel != null && BuildTool.MAVEN.equals(buildToolEnum)) {
// Write to parent pom and submodule pom if project creation is successful
if (!parentPomModel.getModules().contains(this.projectArtifactId)) {
parentPomModel.addModule(this.projectArtifactId);
}
File subModulePomFile = new File(projectRoot, buildToolEnum.getDependenciesFile());
Model subModulePomModel = MojoUtils.readPom(subModulePomFile);
Parent parent = new Parent();
parent.setGroupId(parentPomModel.getGroupId());
parent.setArtifactId(parentPomModel.getArtifactId());
parent.setVersion(parentPomModel.getVersion());
subModulePomModel.setParent(parent);
MojoUtils.write(parentPomModel, pom);
MojoUtils.write(subModulePomModel, subModulePomFile);
}
} catch (Exception e) {
throw new MojoExecutionException("Failed to generate Quarkus project", e);
}
if (success) {
printUserInstructions(projectRoot);
} else {
throw new MojoExecutionException(
"The project was created but (some of) the requested extensions couldn't be added.");
}
}
static ExtensionCatalog resolveExtensionsCatalog(AbstractMojo mojo, String groupId, String artifactId, String version,
ExtensionCatalogResolver catalogResolver, MavenArtifactResolver artifactResolver, MessageWriter log)
throws MojoExecutionException {
if (catalogResolver.hasRegistries()) {
try {
return isBlank(groupId) && isBlank(artifactId) && isBlank(version)
? catalogResolver.resolveExtensionCatalog()
: catalogResolver.resolveExtensionCatalog(Collections.singletonList(
new ArtifactCoords(getPlatformGroupId(mojo, groupId), getPlatformArtifactId(artifactId), "pom",
getPlatformVersion(mojo, version))));
} catch (RegistryResolutionException e) {
log.warn(e.getLocalizedMessage());
mojo.getLog().debug(e);
}
}
return resolveExtensionCatalogDirectly(mojo, groupId, artifactId, version, catalogResolver, artifactResolver, log);
}
private static ExtensionCatalog resolveExtensionCatalogDirectly(AbstractMojo mojo, String groupId, String artifactId,
String version,
ExtensionCatalogResolver catalogResolver, MavenArtifactResolver artifactResolver, MessageWriter log) {
groupId = getPlatformGroupId(mojo, groupId);
artifactId = getPlatformArtifactId(artifactId);
version = getPlatformVersion(mojo, version);
final ExtensionCatalog catalog = ToolsUtils.resolvePlatformDescriptorDirectly(groupId, artifactId, version,
artifactResolver, log);
final StringBuilder buf = new StringBuilder();
buf.append("The extension catalog will be narrowed to the ").append(groupId).append(":").append(artifactId)
.append(":").append(version).append(" platform release.");
if (!QuarkusProjectHelper.isRegistryClientEnabled()) {
buf.append(
" To enable the complete Quarkiverse extension catalog along with the latest recommended platform releases, please, make sure the extension registry client is enabled.");
}
log.warn(buf.toString());
return catalog;
}
private void askTheUserForMissingValues() throws MojoExecutionException {
// If the user has disabled the interactive mode or if the user has specified the artifactId, disable the
// user interactions.
if (!session.getRequest().isInteractiveMode() || shouldUseDefaults()) {
if (isBlank(projectArtifactId)) {
// we need to set it for the project directory
projectArtifactId = DEFAULT_ARTIFACT_ID;
}
if (isBlank(projectGroupId)) {
projectGroupId = DEFAULT_GROUP_ID;
}
if (isBlank(projectVersion)) {
projectVersion = DEFAULT_VERSION;
}
return;
}
try {
final Prompter prompter = new Prompter();
if (isBlank(projectGroupId)) {
prompter.addPrompt("Set the project groupId: ", DEFAULT_GROUP_ID, input -> projectGroupId = input);
}
if (isBlank(projectArtifactId)) {
prompter.addPrompt("Set the project artifactId: ", DEFAULT_ARTIFACT_ID, input -> projectArtifactId = input);
}
if (isBlank(projectVersion)) {
prompter.addPrompt("Set the project version: ", DEFAULT_VERSION, input -> projectVersion = input);
}
if (!noCode && isBlank(example)) {
if (extensions.isEmpty()) {
prompter.addPrompt("What extensions do you wish to add (comma separated list): ", DEFAULT_EXTENSIONS,
input -> extensions = Arrays
.stream(input.split(","))
.map(String::trim).filter(Predicate.not(String::isEmpty)).collect(Collectors.toSet()));
}
prompter.addPrompt("Would you like some code to start (yes), or just an empty Quarkus project (no): ", "yes",
input -> noCode = input.startsWith("n"));
prompter.collectInput();
}
} catch (IOException e) {
throw new MojoExecutionException("Unable to get user input", e);
}
}
private boolean shouldUseDefaults() {
// Must be called before user input
return projectArtifactId != null;
}
private void sanitizeOptions() {
if (className != null) {
className = className.replaceAll("\\.(java|kotlin|scala)$", "");
int idx = className.lastIndexOf('.');
if (idx >= 0 && isBlank(packageName)) {
// if it's a full qualified class name, we use the package name part (only if the packageName wasn't already defined)
packageName = className.substring(0, idx);
// And we strip it from the className
className = className.substring(idx + 1);
}
if (isBlank(path)) {
path = "/hello";
} else if (!path.startsWith("/")) {
path = "/" + path;
}
}
// if package name is empty, the groupId will be used as part of the CreateProject logic
}
private void printUserInstructions(File root) {
getLog().info("");
getLog().info("========================================================================================");
getLog().info(
ansi().a("Your new application has been created in ").bold().a(root.getAbsolutePath()).boldOff().toString());
getLog().info(ansi().a("Navigate into this directory and launch your application with ")
.bold()
.fg(Ansi.Color.CYAN)
.a("mvn quarkus:dev")
.reset()
.toString());
getLog().info(
ansi().a("Your application will be accessible on ").bold().fg(Ansi.Color.CYAN).a("http://localhost:8080")
.reset().toString());
getLog().info("========================================================================================");
getLog().info("");
}
public static String getPlatformVersion(AbstractMojo mojo, String version) {
return isBlank(version) ? getPluginVersion(mojo) : version;
}
public static String getPlatformArtifactId(String artifactId) {
return isBlank(artifactId) ? "quarkus-bom" : artifactId;
}
public static String getPlatformGroupId(AbstractMojo mojo, String groupId) {
return isBlank(groupId) ? getPluginGroupId(mojo) : groupId;
}
private static String getPluginGroupId(AbstractMojo mojo) {
return getPluginDescriptor(mojo).getGroupId();
}
private static String getPluginVersion(AbstractMojo mojo) {
return getPluginDescriptor(mojo).getVersion();
}
private static PluginDescriptor getPluginDescriptor(AbstractMojo mojo) {
return (PluginDescriptor) mojo.getPluginContext().get("pluginDescriptor");
}
private static boolean isBlank(String s) {
return s == null || s.isBlank();
}
}