Skip to content

Commit

Permalink
Fix issues #670, #671, #672, #673 and #675
Browse files Browse the repository at this point in the history
* #670 - improve the decision about the project location
* #671 - when the user does not specify a package, a package name is generated either from the passed groupId or using the default value
* #672 - use the Prompter to get user values, this is disabled in batch mode
* #673 - if the user modifies an existing project, the user is not allowed to pass GAV. Now this case it detected and the build is failed
* #675 - if the user modifies an existing project the GAV are retrieved from the existing project.
  • Loading branch information
cescoffier committed Feb 2, 2019
1 parent afd7e1e commit 40e9de4
Show file tree
Hide file tree
Showing 2 changed files with 161 additions and 36 deletions.
155 changes: 125 additions & 30 deletions cli/maven/src/main/java/org/jboss/shamrock/maven/CreateProjectMojo.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@

package org.jboss.shamrock.maven;

import org.apache.commons.lang3.StringUtils;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Component;
Expand Down Expand Up @@ -45,55 +47,86 @@ public class CreateProjectMojo extends AbstractMojo {

public static final String PLUGIN_KEY = MojoUtils.getPluginGroupId() + ":" + MojoUtils.getPluginArtifactId();

/**
* FQCN of the generated resources when applied on a project with an existing `pom.xml` file and the user
* does not pass the `className` parameter.
*/
private static final String DEFAULT_CLASS_NAME = "io.jboss.shamrock.sample.HelloResource";

@Parameter(defaultValue = "${project}")
protected MavenProject project;

@Parameter(property = "projectGroupId", defaultValue = "io.jboss.shamrock.sample")
@Parameter(property = "projectGroupId")
private String projectGroupId;

@Parameter(property = "projectArtifactId", defaultValue = "my-shamrock-project")
@Parameter(property = "projectArtifactId")
private String projectArtifactId;

@Parameter(property = "projectVersion", defaultValue = "1.0-SNAPSHOT")
@Parameter(property = "projectVersion")
private String projectVersion;

@Parameter(property = "path", defaultValue = "/hello")
protected String path;
@Parameter(property = "path")
private String path;

@Parameter(property = "className")
private String className;

@Parameter(property = "root", defaultValue = "/app")
private String root;

@Parameter(property = "extensions")
private List<String> extensions;

@Parameter(defaultValue = "${session}")
private MavenSession session;

@Component
private Prompter prompter;

@Override
public void execute() throws MojoExecutionException {
File projectRoot = new File(".");
File pom = new File(projectRoot, "pom.xml");

if (pom.isFile()) {
// Enforce that the GAV are not set
if (! StringUtils.isBlank(projectGroupId) || ! StringUtils.isBlank(projectArtifactId)
|| ! StringUtils.isBlank(projectVersion)) {
throw new MojoExecutionException("Unable to generate the project, the `projectGroupId`, " +
"`projectArtifactId` and `projectVersion` parameters are not supported when applied to an " +
"existing `pom.xml` file");
}

// Load the GAV from the existing project
projectGroupId = project.getGroupId();
projectArtifactId = project.getArtifactId();
projectVersion = project.getVersion();

} else {
askTheUserForMissingValues();
if (! isDirectoryEmpty(projectRoot)) {
projectRoot = new File(projectArtifactId);
if (projectRoot.exists()) {
throw new MojoExecutionException("Unable to create the project - the current directory is not empty and" +
" the directory " + projectArtifactId + " exists");
}
}
}

boolean success;
try {
sanitizeOptions();

final Map<String, Object> context = new HashMap<>();
context.put("className", className);
context.put("docRoot", root);
context.put("path", path);

success = new CreateProject(projectRoot)
.groupId(projectGroupId)
.artifactId(projectArtifactId)
.version(projectVersion)
.doCreateProject(context);
.groupId(projectGroupId)
.artifactId(projectArtifactId)
.version(projectVersion)
.doCreateProject(context);

if (success) {
new AddExtensions(new File(projectRoot, "pom.xml"))
.addExtensions(extensions);
.addExtensions(extensions);
}
} catch (IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
Expand All @@ -103,41 +136,103 @@ public void execute() throws MojoExecutionException {
}
}

private void sanitizeOptions() {
className = getOrDefault(className, projectGroupId.replace("-", ".")
.replace("_", ".")
+ ".HelloResource");

private void askTheUserForMissingValues() throws MojoExecutionException {

if (! session.getRequest().isInteractiveMode()) {
// Inject default values in all non-set parameters
if (StringUtils.isBlank(projectGroupId)) {
projectGroupId = "io.jboss.shamrock.sample";
}
if (StringUtils.isBlank(projectArtifactId)) {
projectArtifactId = "my-shamrock-project";
}
if (StringUtils.isBlank(projectVersion)) {
projectVersion = "1.0-SNAPSHOT";
}
return;
}

try {
if (StringUtils.isBlank(projectGroupId)) {
projectGroupId = prompter.promptWithDefaultValue("Set the project groupId",
"io.jboss.shamrock.sample");
}

if (StringUtils.isBlank(projectArtifactId)) {
projectArtifactId = prompter.promptWithDefaultValue("Set the project artifactId",
"my-shamrock-project");
}

if (StringUtils.isBlank(projectVersion)) {
projectVersion = prompter.promptWithDefaultValue("Set the Shamrock version",
"1.0-SNAPSHOT");
}

if (StringUtils.isBlank(className)) {
String defaultResourceName = projectGroupId.replace("-", ".")
.replace("_", ".") + ".HelloResource";

className = prompter.promptWithDefaultValue("Set the resource classname", defaultResourceName);
}

if (StringUtils.isBlank(path)) {
path = prompter.promptWithDefaultValue("Set the resource path ", "/hello");
}
} catch (IOException e) {
throw new MojoExecutionException("Unable to get user input", e);
}
}

private void sanitizeOptions() {
if (className == null) {
className = DEFAULT_CLASS_NAME;
}
if (className.endsWith(MojoUtils.JAVA_EXTENSION)) {
className = className.substring(0, className.length() - MojoUtils.JAVA_EXTENSION.length());
}

if (!root.startsWith("/")) {
root = "/" + root;
if (!className.contains(".")) {
// No package name, inject one
className = projectGroupId.replace("-", ".").replace("_", ".") + "." + className;
}

if (StringUtils.isBlank(path)) {
path = "/hello";
}

if (!path.startsWith("/")) {
path = "/" + path;
}
}

private String getOrDefault(final String parameter, final String defaultValue) {
return parameter != null ? parameter : defaultValue;
}

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 compile shamrock:dev")
.reset()
.toString());
.bold()
.fg(Ansi.Color.CYAN)
.a("mvn compile shamrock:dev")
.reset()
.toString());
getLog().info(
ansi().a("Your application will be accessible on ").bold().fg(Ansi.Color.CYAN).a("http://localhost:8080").reset().toString());
ansi().a("Your application will be accessible on ").bold().fg(Ansi.Color.CYAN).a("http://localhost:8080").reset().toString());
getLog().info("========================================================================================");
getLog().info("");
}

private boolean isDirectoryEmpty(File dir) {
if (! dir.isDirectory()) {
throw new IllegalArgumentException("The specified file must be a directory: " + dir.getAbsolutePath());
}

String[] children = dir.list();
if (children == null) {
// IO Issue
throw new IllegalArgumentException("The specified directory cannot be accessed: " + dir.getAbsolutePath());
}

return children.length == 0;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ public void testProjectGenerationFromScratch() throws MavenInvocationException,
Properties properties = new Properties();
properties.put("projectGroupId", "org.acme");
properties.put("projectArtifactId", "acme");
properties.put("projectVersion", "1.0-SNAPSHOT");
setup(properties);
assertThat(new File(testDir, "pom.xml")).isFile();
assertThat(new File(testDir, "src/main/java")).isDirectory();
Expand Down Expand Up @@ -135,8 +136,6 @@ public void testProjectGenerationFromMinimalPomWithResource() throws Exception {
assertThat(testDir).isDirectory();
init(testDir);
Properties properties = new Properties();
properties.put("projectGroupId", "org.acme");
properties.put("projectArtifactId", "acme");
properties.put("className", "org.acme.MyResource.java");
setup(properties);

Expand Down Expand Up @@ -222,8 +221,6 @@ public void testProjectGenerationFromMinimalPomWithDependencies() throws Excepti
assertThat(testDir).isDirectory();
init(testDir);
Properties properties = new Properties();
properties.put("projectGroupId", "org.acme");
properties.put("projectArtifactId", "acme");
properties.put("className", "org.acme.MyResource");
properties.put("extensions", "commons-io:commons-io:2.5");
setup(properties);
Expand All @@ -232,6 +229,38 @@ public void testProjectGenerationFromMinimalPomWithDependencies() throws Excepti
check(new File(testDir, "pom.xml"), "commons-io");
}

/**
* Reproducer for https://github.com/jbossas/protean-shamrock/issues/671
*/
@Test
public void testThatDefaultPackageAreReplaced() throws Exception {
testDir = initEmptyProject("projects/default-package-test");
assertThat(testDir).isDirectory();
init(testDir);
Properties properties = new Properties();
properties.put("className", "MyGreatResource");
setup(properties);
check(new File(testDir, "src/main/java/io/jboss/shamrock/sample/MyGreatResource.java"), "package io.jboss.shamrock.sample;");
}


/**
* Reproducer for https://github.com/jbossas/protean-shamrock/issues/673
*/
@Test
public void testThatGenerationFailedWhenTheUserPassGAVonExistingPom() throws Exception {
testDir = initProject("projects/simple-pom-it","projects/fail-on-gav-and-existing-pom");
assertThat(testDir).isDirectory();
init(testDir);
Properties properties = new Properties();
properties.put("projectGroupId", "org.acme");
properties.put("className", "MyResource");
InvocationResult result = setup(properties);
assertThat(result.getExitCode()).isNotZero();
assertThat(new File(testDir, "src/main/java/org/acme/MyResource.java")).doesNotExist();
}


private void check(final File resource, final String contentsToFind) throws IOException {
assertThat(resource).isFile();
assertThat(FileUtils.readFileToString(resource, "UTF-8")).contains(contentsToFind);
Expand Down Expand Up @@ -270,7 +299,7 @@ public void generateNewProjectAndRun() throws MavenInvocationException, FileNotF
assertThat(greeting).containsIgnoringCase("hello");
}

private void setup(Properties params) throws MavenInvocationException, FileNotFoundException {
private InvocationResult setup(Properties params) throws MavenInvocationException, FileNotFoundException {
InvocationRequest request = new DefaultInvocationRequest();
request.setBatchMode(true);
request.setGoals(Collections.singletonList(
Expand All @@ -282,7 +311,8 @@ private void setup(Properties params) throws MavenInvocationException, FileNotFo
PrintStreamLogger logger = new PrintStreamLogger(new PrintStream(new FileOutputStream(log)),
InvokerLogger.DEBUG);
invoker.setLogger(logger);
invoker.execute(request);
InvocationResult result = invoker.execute(request);
return result;
}

}

0 comments on commit 40e9de4

Please sign in to comment.