dependencies = getHelpPluginPom().getDependencies();
- for (Dependency dependency : dependencies) {
- if ("org.apache.maven".equals(dependency.getGroupId())) {
- if (artifactId.equals(dependency.getArtifactId())) {
- Artifact mavenArtifact = new DefaultArtifact(
- dependency.getGroupId(), dependency.getArtifactId(), "jar", dependency.getVersion());
-
- return resolveArtifact(mavenArtifact).getArtifact().getFile();
- }
- }
- }
-
- throw new MojoExecutionException("Unable to find the 'org.apache.maven:" + artifactId + "' artifact");
- }
-
- /**
- * @return the Maven POM for the current help plugin
- * @throws MojoExecutionException if any
- */
- private MavenProject getHelpPluginPom() throws MojoExecutionException {
- String resource = "META-INF/maven/org.apache.maven.plugins/maven-help-plugin/pom.properties";
-
- InputStream resourceAsStream = EvaluateMojo.class.getClassLoader().getResourceAsStream(resource);
- if (resourceAsStream == null) {
- throw new MojoExecutionException("The help plugin artifact was not found.");
- }
- Properties properties = new Properties();
- try (InputStream is = resourceAsStream) {
- properties.load(is);
- } catch (IOException e) {
- if (getLog().isDebugEnabled()) {
- getLog().debug("IOException: " + e.getMessage(), e);
+ } catch (Exception e) {
+ throw new MavenException(e);
}
}
-
- String artifactString = properties.getProperty("groupId", "unknown") + ":"
- + properties.getProperty("artifactId", "unknown") + ":"
- + properties.getProperty("version", "unknown");
-
- return getMavenProject(artifactString);
}
/**
diff --git a/src/main/java/org/apache/maven/plugins/help/SystemMojo.java b/src/main/java/org/apache/maven/plugins/help/SystemMojo.java
index d3552d4c..f51dbf6f 100644
--- a/src/main/java/org/apache/maven/plugins/help/SystemMojo.java
+++ b/src/main/java/org/apache/maven/plugins/help/SystemMojo.java
@@ -19,12 +19,12 @@
package org.apache.maven.plugins.help;
import java.io.IOException;
-import java.util.Properties;
+import java.util.Locale;
+import java.util.Map;
-import org.apache.maven.plugin.MojoExecutionException;
-import org.apache.maven.plugins.annotations.Mojo;
-import org.codehaus.plexus.util.StringUtils;
-import org.codehaus.plexus.util.cli.CommandLineUtils;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.api.plugin.annotations.Mojo;
+import org.apache.maven.api.plugin.annotations.Parameter;
/**
* Displays a list of the platform details like system properties and environment variables.
@@ -32,47 +32,85 @@
* @author Vincent Siveton
* @since 2.1
*/
-@Mojo(name = "system", requiresProject = false)
+@Mojo(name = "system", projectRequired = false)
public class SystemMojo extends AbstractHelpMojo {
+
/** Magic number to beautify the output */
private static final int REPEAT = 25;
+ /**
+ * This options gives the option to output information in cases where the output has been suppressed by using
+ * -q
(quiet option) in Maven.
+ *
+ * @since 4.0.0
+ */
+ @Parameter(property = "forceStdout", defaultValue = "false")
+ protected boolean forceStdout;
+
+ /**
+ * Property to control whether property values are escaped or not.
+ *
+ * @since 4.0.0
+ */
+ @Parameter(property = "escape", defaultValue = "true")
+ boolean escape;
+
// ----------------------------------------------------------------------
// Public methods
// ----------------------------------------------------------------------
/** {@inheritDoc} */
- public void execute() throws MojoExecutionException {
+ public void execute() throws MojoException {
StringBuilder message = new StringBuilder();
+ String eqStr = "=".repeat(LINE_LENGTH);
+ String reStr = "=".repeat(REPEAT);
+
message.append(LS);
- message.append(StringUtils.repeat("=", LINE_LENGTH)).append(LS);
- message.append(StringUtils.repeat("=", REPEAT));
- message.append(" Platform Properties Details ");
- message.append(StringUtils.repeat("=", REPEAT)).append(LS);
- message.append(StringUtils.repeat("=", LINE_LENGTH)).append(LS);
+ message.append(eqStr).append(LS);
+ message.append(reStr)
+ .append(" Platform Properties Details ")
+ .append(reStr)
+ .append(LS);
+ message.append(eqStr).append(LS);
message.append(LS);
- message.append(StringUtils.repeat("=", LINE_LENGTH)).append(LS);
- message.append("System Properties").append(LS);
- message.append(StringUtils.repeat("=", LINE_LENGTH)).append(LS);
-
- Properties systemProperties = System.getProperties();
- for (String key : systemProperties.stringPropertyNames()) {
- message.append(LS);
- message.append(key).append("=").append(systemProperties.getProperty(key));
- }
+ message.append(eqStr).append(LS);
+ message.append("User Properties").append(LS);
+ message.append(eqStr).append(LS);
+ message.append(LS);
+ session.getUserProperties().entrySet().stream()
+ .sorted(Map.Entry.comparingByKey())
+ .forEach(e -> message.append(e.getKey())
+ .append("=")
+ .append(escape ? escapeJava(e.getValue()) : e.getValue())
+ .append(LS));
+ message.append(LS);
- message.append(LS).append(LS);
- message.append(StringUtils.repeat("=", LINE_LENGTH)).append(LS);
- message.append("Environment Variables").append(LS);
- message.append(StringUtils.repeat("=", LINE_LENGTH)).append(LS);
- Properties envVars = CommandLineUtils.getSystemEnvVars();
- for (String key : envVars.stringPropertyNames()) {
- message.append(LS);
- message.append(key).append("=").append(envVars.getProperty(key));
- }
+ message.append(eqStr).append(LS);
+ message.append("System Properties").append(LS);
+ message.append(eqStr).append(LS);
+ message.append(LS);
+ session.getSystemProperties().entrySet().stream()
+ .filter(e -> !e.getKey().startsWith("env."))
+ .sorted(Map.Entry.comparingByKey())
+ .forEach(e -> message.append(e.getKey())
+ .append("=")
+ .append(escape ? escapeJava(e.getValue()) : e.getValue())
+ .append(LS));
+ message.append(LS);
+ message.append(eqStr).append(LS);
+ message.append("Environment Properties").append(LS);
+ message.append(eqStr).append(LS);
+ message.append(LS);
+ session.getSystemProperties().entrySet().stream()
+ .filter(e -> e.getKey().startsWith("env."))
+ .sorted(Map.Entry.comparingByKey())
+ .forEach(e -> message.append(e.getKey().substring("env.".length()))
+ .append("=")
+ .append(escape ? escapeJava(e.getValue()) : e.getValue())
+ .append(LS));
message.append(LS);
if (output != null) {
@@ -81,17 +119,118 @@ public void execute() throws MojoExecutionException {
sb.append("See: https://maven.apache.org/plugins/maven-help-plugin/")
.append(LS)
.append(LS);
- sb.append(message.toString());
+ sb.append(message);
try {
writeFile(output, sb);
} catch (IOException e) {
- throw new MojoExecutionException("Cannot write system report to output: " + output, e);
+ throw new MojoException("Cannot write system report to output: " + output, e);
}
getLog().info("System report written to: " + output);
} else {
- getLog().info(message);
+ if (getLog().isInfoEnabled()) {
+ getLog().info(message);
+ } else if (forceStdout) {
+ System.out.println(message);
+ }
}
}
+
+ /**
+ * Escapes the characters in a String
using Java String rules.
+ *
+ * Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)
+ *
+ * So a tab becomes the characters '\\'
and
+ * 't'
.
+ *
+ * The only difference between Java strings and JavaScript strings
+ * is that in JavaScript, a single quote must be escaped.
+ *
+ * Example:
+ *
+ * input string: He didn't say, "Stop!"
+ * output string: He didn't say, \"Stop!\"
+ *
+ *
+ *
+ * @param str String to escape values in, may be null
+ * @return String with escaped values, null
if null string input
+ */
+ @SuppressWarnings("checkstyle:MagicNumber")
+ protected static String escapeJava(String str) {
+ if (str == null) {
+ return null;
+ }
+ int sz = str.length();
+ StringBuilder out = new StringBuilder(sz * 2);
+ for (int i = 0; i < sz; i++) {
+ char ch = str.charAt(i);
+ // handle unicode
+ if (ch > 0xfff) {
+ out.append("\\u").append(hex(ch));
+ } else if (ch > 0xff) {
+ out.append("\\u0").append(hex(ch));
+ } else if (ch > 0x7f) {
+ out.append("\\u00").append(hex(ch));
+ } else if (ch < 32) {
+ switch (ch) {
+ case '\b':
+ out.append('\\');
+ out.append('b');
+ break;
+ case '\n':
+ out.append('\\');
+ out.append('n');
+ break;
+ case '\t':
+ out.append('\\');
+ out.append('t');
+ break;
+ case '\f':
+ out.append('\\');
+ out.append('f');
+ break;
+ case '\r':
+ out.append('\\');
+ out.append('r');
+ break;
+ default:
+ if (ch > 0xf) {
+ out.append("\\u00").append(hex(ch));
+ } else {
+ out.append("\\u000").append(hex(ch));
+ }
+ break;
+ }
+ } else {
+ switch (ch) {
+ case '"':
+ out.append('\\');
+ out.append('"');
+ break;
+ case '\\':
+ out.append('\\');
+ out.append('\\');
+ break;
+ default:
+ out.append(ch);
+ break;
+ }
+ }
+ }
+ return out.toString();
+ }
+
+ /**
+ * Returns an upper case hexadecimal String
for the given
+ * character.
+ *
+ * @param ch The character to convert.
+ * @return An upper case hexadecimal String
+ */
+ protected static String hex(char ch) {
+ return Integer.toHexString(ch).toUpperCase(Locale.ENGLISH);
+ }
}
diff --git a/src/main/java/org/apache/maven/plugins/help/ActiveProfilesMojo.java b/src/main/to-migrate/ActiveProfilesMojo.java
similarity index 83%
rename from src/main/java/org/apache/maven/plugins/help/ActiveProfilesMojo.java
rename to src/main/to-migrate/ActiveProfilesMojo.java
index fdbecabf..50212067 100644
--- a/src/main/java/org/apache/maven/plugins/help/ActiveProfilesMojo.java
+++ b/src/main/to-migrate/ActiveProfilesMojo.java
@@ -18,14 +18,15 @@
*/
package org.apache.maven.plugins.help;
+import org.apache.maven.api.Project;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.api.plugin.annotations.Mojo;
+import org.apache.maven.api.plugin.annotations.Parameter;
+
import java.io.IOException;
import java.util.List;
import java.util.Map;
-import org.apache.maven.plugin.MojoExecutionException;
-import org.apache.maven.plugins.annotations.Mojo;
-import org.apache.maven.plugins.annotations.Parameter;
-import org.apache.maven.project.MavenProject;
/**
* Displays a list of the profiles which are currently active for this build.
@@ -41,18 +42,18 @@ public class ActiveProfilesMojo extends AbstractHelpMojo {
/**
* This is the list of projects currently slated to be built by Maven.
*/
- @Parameter(defaultValue = "${reactorProjects}", required = true, readonly = true)
- private List projects;
+ @Parameter(defaultValue = "${session.projects}", required = true, readonly = true)
+ private List projects;
// ----------------------------------------------------------------------
// Public methods
// ----------------------------------------------------------------------
/** {@inheritDoc} */
- public void execute() throws MojoExecutionException {
+ public void execute() throws MojoException {
StringBuilder message = new StringBuilder();
- for (MavenProject project : projects) {
+ for (Project project : projects) {
getActiveProfileStatement(project, message);
message.append(LS).append(LS);
@@ -64,12 +65,12 @@ public void execute() throws MojoExecutionException {
sb.append("See: https://maven.apache.org/plugins/maven-help-plugin/")
.append(LS)
.append(LS);
- sb.append(message.toString());
+ sb.append(message);
try {
writeFile(output, sb);
} catch (IOException e) {
- throw new MojoExecutionException("Cannot write active profiles to output: " + output, e);
+ throw new MojoException("Cannot write active profiles to output: " + output, e);
}
getLog().info("Active profile report written to: " + output);
@@ -88,7 +89,7 @@ public void execute() throws MojoExecutionException {
* @param project the current project
* @param message the object where the information will be appended to
*/
- private void getActiveProfileStatement(MavenProject project, StringBuilder message) {
+ private void getActiveProfileStatement(Project project, StringBuilder message) {
Map> activeProfileIds = project.getInjectedProfileIds();
message.append(LS);
diff --git a/src/main/java/org/apache/maven/plugins/help/AllProfilesMojo.java b/src/main/to-migrate/AllProfilesMojo.java
similarity index 84%
rename from src/main/java/org/apache/maven/plugins/help/AllProfilesMojo.java
rename to src/main/to-migrate/AllProfilesMojo.java
index 3d389160..a64b31d6 100644
--- a/src/main/java/org/apache/maven/plugins/help/AllProfilesMojo.java
+++ b/src/main/to-migrate/AllProfilesMojo.java
@@ -23,13 +23,11 @@
import java.util.List;
import java.util.Map;
-import org.apache.maven.model.Profile;
-import org.apache.maven.plugin.MojoExecutionException;
-import org.apache.maven.plugin.MojoFailureException;
-import org.apache.maven.plugins.annotations.Mojo;
-import org.apache.maven.plugins.annotations.Parameter;
-import org.apache.maven.project.MavenProject;
-import org.apache.maven.settings.SettingsUtils;
+import org.apache.maven.api.Project;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.api.model.Profile;
+import org.apache.maven.api.plugin.annotations.Mojo;
+import org.apache.maven.api.plugin.annotations.Parameter;
/**
* Displays a list of available profiles under the current project.
@@ -41,7 +39,7 @@
* @author Rahul Thakur
* @since 2.1
*/
-@Mojo(name = "all-profiles", requiresProject = false)
+@Mojo(name = "all-profiles", projectRequired = false)
public class AllProfilesMojo extends AbstractHelpMojo {
// ----------------------------------------------------------------------
// Mojo parameters
@@ -50,24 +48,24 @@ public class AllProfilesMojo extends AbstractHelpMojo {
/**
* This is the list of projects currently slated to be built by Maven.
*/
- @Parameter(defaultValue = "${reactorProjects}", required = true, readonly = true)
- private List projects;
+ @Parameter(defaultValue = "${session.projects}", required = true, readonly = true)
+ private List projects;
/**
* The list of profiles defined in the current Maven settings.
*/
@Parameter(defaultValue = "${settings.profiles}", readonly = true, required = true)
- private List settingsProfiles;
+ private List settingsProfiles;
// ----------------------------------------------------------------------
// Public methods
// ----------------------------------------------------------------------
/** {@inheritDoc} */
- public void execute() throws MojoExecutionException, MojoFailureException {
+ public void execute() throws MojoException {
StringBuilder descriptionBuffer = new StringBuilder();
- for (MavenProject project : projects) {
+ for (Project project : projects) {
descriptionBuffer
.append("Listing Profiles for Project: ")
.append(project.getId())
@@ -94,7 +92,7 @@ public void execute() throws MojoExecutionException, MojoFailureException {
try {
writeFile(output, descriptionBuffer);
} catch (IOException e) {
- throw new MojoExecutionException("Cannot write profiles description to output: " + output, e);
+ throw new MojoException("Cannot write profiles description to output: " + output, e);
}
getLog().info("Wrote descriptions to: " + output);
@@ -127,7 +125,7 @@ private void writeProfilesDescription(StringBuilder sb, Map pro
* @param activeProfiles Map to add the active profiles to.
*/
private void addProjectPomProfiles(
- MavenProject project, Map allProfiles, Map activeProfiles) {
+ Project project, Map allProfiles, Map activeProfiles) {
if (project == null) {
// shouldn't happen as this mojo requires a project
getLog().debug("No pom.xml found to read Profiles from.");
@@ -156,7 +154,7 @@ private void addProjectPomProfiles(
*/
private void addSettingsProfiles(Map allProfiles) {
getLog().debug("Attempting to read profiles from settings.xml...");
- for (org.apache.maven.settings.Profile settingsProfile : settingsProfiles) {
+ for (org.apache.maven.api.settings.Profile settingsProfile : settingsProfiles) {
Profile profile = SettingsUtils.convertFromSettingsProfile(settingsProfile);
allProfiles.put(profile.getId(), profile);
}
diff --git a/src/main/java/org/apache/maven/plugins/help/DescribeMojo.java b/src/main/to-migrate/DescribeMojo.java
similarity index 82%
rename from src/main/java/org/apache/maven/plugins/help/DescribeMojo.java
rename to src/main/to-migrate/DescribeMojo.java
index 7cf0ec8d..666b9110 100644
--- a/src/main/java/org/apache/maven/plugins/help/DescribeMojo.java
+++ b/src/main/to-migrate/DescribeMojo.java
@@ -18,6 +18,14 @@
*/
package org.apache.maven.plugins.help;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.di.Inject;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.api.plugin.annotations.Mojo;
+import org.apache.maven.api.plugin.descriptor.MojoDescriptor;
+import org.apache.maven.api.plugin.descriptor.Parameter;
+import org.apache.maven.api.plugin.descriptor.PluginDescriptor;
+
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
@@ -32,35 +40,6 @@
import java.util.regex.Pattern;
import java.util.stream.Collectors;
-import org.apache.maven.RepositoryUtils;
-import org.apache.maven.lifecycle.DefaultLifecycles;
-import org.apache.maven.lifecycle.Lifecycle;
-import org.apache.maven.lifecycle.internal.MojoDescriptorCreator;
-import org.apache.maven.lifecycle.mapping.LifecycleMapping;
-import org.apache.maven.model.Plugin;
-import org.apache.maven.model.building.ModelBuildingRequest;
-import org.apache.maven.plugin.MavenPluginManager;
-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.Parameter;
-import org.apache.maven.plugin.descriptor.PluginDescriptor;
-import org.apache.maven.plugin.prefix.NoPluginFoundForPrefixException;
-import org.apache.maven.plugin.version.DefaultPluginVersionRequest;
-import org.apache.maven.plugin.version.PluginVersionResolutionException;
-import org.apache.maven.plugin.version.PluginVersionResolver;
-import org.apache.maven.plugin.version.PluginVersionResult;
-import org.apache.maven.plugins.annotations.Component;
-import org.apache.maven.plugins.annotations.Mojo;
-import org.apache.maven.project.DefaultProjectBuildingRequest;
-import org.apache.maven.project.MavenProject;
-import org.apache.maven.project.ProjectBuildingRequest;
-import org.apache.maven.reporting.MavenReport;
-import org.apache.maven.shared.utils.logging.MessageUtils;
-import org.apache.maven.tools.plugin.generator.HtmlToPlainTextConverter;
-import org.codehaus.plexus.util.StringUtils;
-import org.eclipse.aether.artifact.Artifact;
-import org.eclipse.aether.artifact.DefaultArtifact;
/**
* Displays a list of the attributes for a Maven Plugin and/or goals (aka Mojo - Maven plain Old Java Object).
@@ -68,7 +47,7 @@
* @see What is a Mojo?
* @since 2.0
*/
-@Mojo(name = "describe", requiresProject = false, aggregator = true)
+@Mojo(name = "describe", projectRequired = false, aggregator = true)
public class DescribeMojo extends AbstractHelpMojo {
/**
* The default indent size when writing description's Mojo.
@@ -95,37 +74,10 @@ public class DescribeMojo extends AbstractHelpMojo {
// ----------------------------------------------------------------------
// Mojo components
// ----------------------------------------------------------------------
-
- /**
- * Component used to get a plugin descriptor from a given plugin.
- */
- @Component
- protected MavenPluginManager pluginManager;
-
- /**
- * Component used to get a plugin by its prefix and get mojo descriptors.
- */
- @Component
- private MojoDescriptorCreator mojoDescriptorCreator;
-
- /**
- * Component used to resolve the version for a plugin.
- */
- @Component
- private PluginVersionResolver pluginVersionResolver;
-
- /**
- * The Maven default built-in lifecycles.
- */
- @Component
- private DefaultLifecycles defaultLifecycles;
-
- /**
- * A map from each packaging to its lifecycle mapping.
- */
- @Component
- private Map lifecycleMappings;
-
+
+ @Inject
+ Session session;
+
// ----------------------------------------------------------------------
// Mojo parameters
// ----------------------------------------------------------------------
@@ -139,7 +91,7 @@ public class DescribeMojo extends AbstractHelpMojo {
* groupId:artifactId:version, i.e. 'org.apache.maven.plugins:maven-help-plugin:2.0'
*
*/
- @org.apache.maven.plugins.annotations.Parameter(property = "plugin", alias = "prefix")
+ @org.apache.maven.api.plugin.annotations.Parameter(property = "plugin", alias = "prefix")
private String plugin;
/**
@@ -147,7 +99,7 @@ public class DescribeMojo extends AbstractHelpMojo {
*
* Note: Should be used with artifactId
parameter.
*/
- @org.apache.maven.plugins.annotations.Parameter(property = "groupId")
+ @org.apache.maven.api.plugin.annotations.Parameter(property = "groupId")
private String groupId;
/**
@@ -155,7 +107,7 @@ public class DescribeMojo extends AbstractHelpMojo {
*
* Note: Should be used with groupId
parameter.
*/
- @org.apache.maven.plugins.annotations.Parameter(property = "artifactId")
+ @org.apache.maven.api.plugin.annotations.Parameter(property = "artifactId")
private String artifactId;
/**
@@ -163,7 +115,7 @@ public class DescribeMojo extends AbstractHelpMojo {
*
* Note: Should be used with groupId/artifactId
parameters.
*/
- @org.apache.maven.plugins.annotations.Parameter(property = "version")
+ @org.apache.maven.api.plugin.annotations.Parameter(property = "version")
private String version;
/**
@@ -173,7 +125,7 @@ public class DescribeMojo extends AbstractHelpMojo {
*
* @since 2.1
*/
- @org.apache.maven.plugins.annotations.Parameter(property = "goal")
+ @org.apache.maven.api.plugin.annotations.Parameter(property = "goal")
private String goal;
/**
@@ -181,7 +133,7 @@ public class DescribeMojo extends AbstractHelpMojo {
*
* @since 2.1
*/
- @org.apache.maven.plugins.annotations.Parameter(property = "detail", defaultValue = "false")
+ @org.apache.maven.api.plugin.annotations.Parameter(property = "detail", defaultValue = "false")
private boolean detail;
/**
@@ -189,7 +141,7 @@ public class DescribeMojo extends AbstractHelpMojo {
*
* @since 2.1
*/
- @org.apache.maven.plugins.annotations.Parameter(property = "minimal", defaultValue = "false")
+ @org.apache.maven.api.plugin.annotations.Parameter(property = "minimal", defaultValue = "false")
private boolean minimal;
/**
@@ -199,7 +151,7 @@ public class DescribeMojo extends AbstractHelpMojo {
*
* @since 2.1
*/
- @org.apache.maven.plugins.annotations.Parameter(property = "cmd")
+ @org.apache.maven.api.plugin.annotations.Parameter(property = "cmd")
private String cmd;
// ----------------------------------------------------------------------
@@ -209,7 +161,7 @@ public class DescribeMojo extends AbstractHelpMojo {
/**
* {@inheritDoc}
*/
- public void execute() throws MojoExecutionException, MojoFailureException {
+ public void execute() throws MojoException {
StringBuilder descriptionBuffer = new StringBuilder();
boolean describePlugin = true;
@@ -221,9 +173,10 @@ public void execute() throws MojoExecutionException, MojoFailureException {
PluginInfo pi = parsePluginLookupInfo();
PluginDescriptor descriptor = lookupPluginDescriptor(pi);
if (goal != null && !goal.isEmpty()) {
- MojoDescriptor mojo = descriptor.getMojo(goal);
+ MojoDescriptor mojo = descriptor.getMojos()
+ .stream().filter(m -> goal.equals(m.getGoal())).findAny().orElse(null);
if (mojo == null) {
- throw new MojoFailureException(
+ throw new MojoException(
"The goal '" + goal + "' does not exist in the plugin '" + pi.getPrefix() + "'");
}
describeMojo(mojo, descriptionBuffer);
@@ -243,14 +196,14 @@ public void execute() throws MojoExecutionException, MojoFailureException {
* Method to write the Mojo description into the output file
*
* @param descriptionBuffer contains the description to be written to the file
- * @throws MojoExecutionException if any
+ * @throws MojoException if any
*/
- private void writeDescription(StringBuilder descriptionBuffer) throws MojoExecutionException {
+ private void writeDescription(StringBuilder descriptionBuffer) throws MojoException {
if (output != null) {
try {
writeFile(output, descriptionBuffer);
} catch (IOException e) {
- throw new MojoExecutionException("Cannot write plugin/goal description to output: " + output, e);
+ throw new MojoException("Cannot write plugin/goal description to output: " + output, e);
}
getLog().info("Wrote descriptions to: " + output);
@@ -264,16 +217,16 @@ private void writeDescription(StringBuilder descriptionBuffer) throws MojoExecut
*
* @param pi holds information of the plugin whose description is to be retrieved
* @return a PluginDescriptor where the plugin description is to be retrieved
- * @throws MojoExecutionException if the plugin could not be verify
- * @throws MojoFailureException if groupId or artifactId is empty
+ * @throws MojoException if the plugin could not be verify
+ * @throws MojoException if groupId or artifactId is empty
*/
- private PluginDescriptor lookupPluginDescriptor(PluginInfo pi) throws MojoExecutionException, MojoFailureException {
+ private PluginDescriptor lookupPluginDescriptor(PluginInfo pi) throws MojoException, MojoException {
Plugin forLookup = null;
- if (StringUtils.isNotEmpty(pi.getPrefix())) {
+ if (pi.getPrefix() != null && !pi.getPrefix().isEmpty()) {
try {
forLookup = mojoDescriptorCreator.findPluginForPrefix(pi.getPrefix(), session);
} catch (NoPluginFoundForPrefixException e) {
- throw new MojoExecutionException("Unable to find the plugin with prefix: " + pi.getPrefix(), e);
+ throw new MojoException("Unable to find the plugin with prefix: " + pi.getPrefix(), e);
}
} else if (StringUtils.isNotEmpty(pi.getGroupId()) && StringUtils.isNotEmpty(pi.getArtifactId())) {
forLookup = new Plugin();
@@ -292,7 +245,7 @@ private PluginDescriptor lookupPluginDescriptor(PluginInfo pi) throws MojoExecut
+ " # mvn help:describe -DgroupId=org.apache.maven.plugins -DartifactId=maven-help-plugin" + LS
+ LS
+ "Try 'mvn help:help -Ddetail=true' for more information.";
- throw new MojoFailureException(msg);
+ throw new MojoException(msg);
}
if (StringUtils.isNotEmpty(pi.getVersion())) {
@@ -304,7 +257,7 @@ private PluginDescriptor lookupPluginDescriptor(PluginInfo pi) throws MojoExecut
PluginVersionResult versionResult = pluginVersionResolver.resolve(versionRequest);
forLookup.setVersion(versionResult.getVersion());
} catch (PluginVersionResolutionException e) {
- throw new MojoExecutionException(
+ throw new MojoException(
"Unable to resolve the version of the plugin with prefix: " + pi.getPrefix(), e);
}
}
@@ -313,7 +266,7 @@ private PluginDescriptor lookupPluginDescriptor(PluginInfo pi) throws MojoExecut
return pluginManager.getPluginDescriptor(
forLookup, project.getRemotePluginRepositories(), session.getRepositorySession());
} catch (Exception e) {
- throw new MojoExecutionException(
+ throw new MojoException(
"Error retrieving plugin descriptor for:" + LS + LS + "groupId: '"
+ groupId + "'" + LS + "artifactId: '" + artifactId + "'" + LS + "version: '" + version
+ "'" + LS
@@ -326,10 +279,10 @@ private PluginDescriptor lookupPluginDescriptor(PluginInfo pi) throws MojoExecut
* Method for parsing the plugin parameter
*
* @return Plugin info containing information about the plugin whose description is to be retrieved
- * @throws MojoFailureException if plugin<*code> parameter is not conform to
+ * @throws MojoException if plugin<*code> parameter is not conform to
* groupId:artifactId[:version]
*/
- private PluginInfo parsePluginLookupInfo() throws MojoFailureException {
+ private PluginInfo parsePluginLookupInfo() throws MojoException {
PluginInfo pi = new PluginInfo();
if (plugin != null && !plugin.isEmpty()) {
if (plugin.indexOf(':') > -1) {
@@ -349,7 +302,7 @@ private PluginInfo parsePluginLookupInfo() throws MojoFailureException {
pi.setVersion(pluginParts[2]);
break;
default:
- throw new MojoFailureException("plugin parameter must be a plugin prefix,"
+ throw new MojoException("plugin parameter must be a plugin prefix,"
+ " or conform to: 'groupId:artifactId[:version]'.");
}
} else {
@@ -368,11 +321,11 @@ private PluginInfo parsePluginLookupInfo() throws MojoFailureException {
*
* @param pd contains the plugin description
* @param buffer contains the information to be displayed or printed
- * @throws MojoFailureException if any reflection exceptions occur.
- * @throws MojoExecutionException if any
+ * @throws MojoException if any reflection exceptions occur.
+ * @throws MojoException if any
*/
private void describePlugin(PluginDescriptor pd, StringBuilder buffer)
- throws MojoFailureException, MojoExecutionException {
+ throws MojoException, MojoException {
append(buffer, pd.getId(), 0);
buffer.append(LS);
@@ -441,11 +394,11 @@ private void describePlugin(PluginDescriptor pd, StringBuilder buffer)
*
* @param md contains the description of the Plugin Mojo
* @param buffer the displayed output
- * @throws MojoFailureException if any reflection exceptions occur.
- * @throws MojoExecutionException if any
+ * @throws MojoException if any reflection exceptions occur.
+ * @throws MojoException if any
*/
private void describeMojo(MojoDescriptor md, StringBuilder buffer)
- throws MojoFailureException, MojoExecutionException {
+ throws MojoException, MojoException {
buffer.append("Mojo: '").append(md.getFullGoalName()).append("'");
buffer.append(LS);
@@ -464,11 +417,11 @@ private void describeMojo(MojoDescriptor md, StringBuilder buffer)
* @param md contains the description of the Plugin Mojo
* @param buffer contains information to be printed or displayed
* @param fullDescription specifies whether all the details about the Plugin Mojo is to be displayed
- * @throws MojoFailureException if any reflection exceptions occur.
- * @throws MojoExecutionException if any
+ * @throws MojoException if any reflection exceptions occur.
+ * @throws MojoException if any
*/
private void describeMojoGuts(MojoDescriptor md, StringBuilder buffer, boolean fullDescription)
- throws MojoFailureException, MojoExecutionException {
+ throws MojoException, MojoException {
append(buffer, MessageUtils.buffer().strong(md.getFullGoalName()).toString(), 0);
// indent 1
@@ -534,11 +487,11 @@ private void describeMojoGuts(MojoDescriptor md, StringBuilder buffer, boolean f
*
* @param md contains the description of the Plugin Mojo
* @param buffer contains information to be printed or displayed
- * @throws MojoFailureException if any reflection exceptions occur.
- * @throws MojoExecutionException if any
+ * @throws MojoException if any reflection exceptions occur.
+ * @throws MojoException if any
*/
private void describeMojoParameters(MojoDescriptor md, StringBuilder buffer)
- throws MojoFailureException, MojoExecutionException {
+ throws MojoException, MojoException {
List params = md.getParameters();
if (params == null || params.isEmpty()) {
@@ -548,7 +501,7 @@ private void describeMojoParameters(MojoDescriptor md, StringBuilder buffer)
params = params.stream()
.sorted((p1, p2) -> p1.getName().compareToIgnoreCase(p2.getName()))
- .collect(Collectors.toList());
+ .toList();
append(buffer, "Available parameters:", 1);
@@ -623,14 +576,14 @@ private void describeMojoParameters(MojoDescriptor md, StringBuilder buffer)
*
* @param descriptionBuffer not null
* @return true
if it implies to describe a plugin, false
otherwise.
- * @throws MojoExecutionException if any
+ * @throws MojoException if any
*/
- private boolean describeCommand(StringBuilder descriptionBuffer) throws MojoExecutionException {
+ private boolean describeCommand(StringBuilder descriptionBuffer) throws MojoException {
if (cmd.indexOf(':') == -1) {
// phase
Lifecycle lifecycle = defaultLifecycles.getPhaseToLifecycleMap().get(cmd);
if (lifecycle == null) {
- throw new MojoExecutionException("The given phase '" + cmd + "' is an unknown phase.");
+ throw new MojoException("The given phase '" + cmd + "' is an unknown phase.");
}
Map defaultLifecyclePhases = lifecycleMappings
@@ -702,7 +655,7 @@ private boolean describeCommand(StringBuilder descriptionBuffer) throws MojoExec
try {
mojoDescriptor = mojoDescriptorCreator.getMojoDescriptor(cmd, session, project);
} catch (Exception e) {
- throw new MojoExecutionException("Unable to get descriptor for " + cmd, e);
+ throw new MojoException("Unable to get descriptor for " + cmd, e);
}
descriptionBuffer
.append("'")
@@ -725,11 +678,11 @@ private boolean describeCommand(StringBuilder descriptionBuffer) throws MojoExec
* @param indentSize The size of each indentation, must not be negative.
* @param lineLength The length of the line, must not be negative.
* @return The sequence of display lines, never null
.
- * @throws MojoFailureException if any can not invoke the method
- * @throws MojoExecutionException if no line was found for text
+ * @throws MojoException if any can not invoke the method
+ * @throws MojoException if no line was found for text
*/
private static List toLines(String text, int indent, int indentSize, int lineLength)
- throws MojoFailureException, MojoExecutionException {
+ throws MojoException, MojoException {
try {
Method m =
HelpMojo.class.getDeclaredMethod("toLines", String.class, Integer.TYPE, Integer.TYPE, Integer.TYPE);
@@ -738,26 +691,26 @@ private static List toLines(String text, int indent, int indentSize, int
List output = (List) m.invoke(HelpMojo.class, text, indent, indentSize, lineLength);
if (output == null) {
- throw new MojoExecutionException("No output was specified.");
+ throw new MojoException("No output was specified.");
}
return output;
} catch (SecurityException e) {
- throw new MojoFailureException("SecurityException: " + e.getMessage());
+ throw new MojoException("SecurityException: " + e.getMessage());
} catch (IllegalArgumentException e) {
- throw new MojoFailureException("IllegalArgumentException: " + e.getMessage());
+ throw new MojoException("IllegalArgumentException: " + e.getMessage());
} catch (NoSuchMethodException e) {
- throw new MojoFailureException("NoSuchMethodException: " + e.getMessage());
+ throw new MojoException("NoSuchMethodException: " + e.getMessage());
} catch (IllegalAccessException e) {
- throw new MojoFailureException("IllegalAccessException: " + e.getMessage());
+ throw new MojoException("IllegalAccessException: " + e.getMessage());
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof NegativeArraySizeException) {
- throw new MojoFailureException("NegativeArraySizeException: " + cause.getMessage());
+ throw new MojoException("NegativeArraySizeException: " + cause.getMessage());
}
- throw new MojoFailureException("InvocationTargetException: " + e.getMessage());
+ throw new MojoException("InvocationTargetException: " + e.getMessage());
}
}
@@ -768,12 +721,12 @@ private static List toLines(String text, int indent, int indentSize, int
* @param sb The buffer to append the description, not null
.
* @param description The description, not null
.
* @param indent The base indentation level of each line, must not be negative.
- * @throws MojoFailureException if any reflection exceptions occur.
- * @throws MojoExecutionException if any
+ * @throws MojoException if any reflection exceptions occur.
+ * @throws MojoException if any
* @see #toLines(String, int, int, int)
*/
private static void append(StringBuilder sb, String description, int indent)
- throws MojoFailureException, MojoExecutionException {
+ throws MojoException, MojoException {
if (description == null || description.isEmpty()) {
sb.append(UNKNOWN).append(LS);
return;
@@ -792,12 +745,12 @@ private static void append(StringBuilder sb, String description, int indent)
* @param key The key, not null
.
* @param value The value associated to the key, could be null
.
* @param indent The base indentation level of each line, must not be negative.
- * @throws MojoFailureException if any reflection exceptions occur.
- * @throws MojoExecutionException if any
+ * @throws MojoException if any reflection exceptions occur.
+ * @throws MojoException if any
* @see #toLines(String, int, int, int)
*/
private static void append(StringBuilder sb, String key, String value, int indent)
- throws MojoFailureException, MojoExecutionException {
+ throws MojoException, MojoException {
if (key == null || key.isEmpty()) {
throw new IllegalArgumentException("Key is required!");
}
@@ -821,12 +774,12 @@ private static void append(StringBuilder sb, String key, String value, int inden
* @param key The key, not null
.
* @param value The value, could be null
.
* @param indent The base indentation level of each line, must not be negative.
- * @throws MojoFailureException if any reflection exceptions occur.
- * @throws MojoExecutionException if any
+ * @throws MojoException if any reflection exceptions occur.
+ * @throws MojoException if any
* @see #toLines(String, int, int, int)
*/
private static void appendAsParagraph(StringBuilder sb, String key, String value, int indent)
- throws MojoFailureException, MojoExecutionException {
+ throws MojoException, MojoException {
if (value == null || value.isEmpty()) {
value = UNKNOWN;
}
@@ -851,7 +804,7 @@ private static void appendAsParagraph(StringBuilder sb, String key, String value
* transitive dependencies to determine if the Java class of this goal implements MavenReport
.
*
* @param md Mojo descriptor
- * @return Whether or not this goal should be used as a report.
+ * @return Whether this goal should be used as a report.
*/
private boolean isReportGoal(MojoDescriptor md) {
PluginDescriptor pd = md.getPluginDescriptor();
diff --git a/src/test/java/org/apache/maven/plugins/help/EffectivePomMojoTest.java b/src/test/java/org/apache/maven/plugins/help/EffectivePomMojoTest.java
new file mode 100644
index 00000000..cdde79d9
--- /dev/null
+++ b/src/test/java/org/apache/maven/plugins/help/EffectivePomMojoTest.java
@@ -0,0 +1,118 @@
+/*
+ * 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.plugins.help;
+
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.io.PrintStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+import org.apache.maven.api.Project;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.di.Provides;
+import org.apache.maven.api.di.Singleton;
+import org.apache.maven.api.model.InputSource;
+import org.apache.maven.api.model.Model;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.testing.Basedir;
+import org.apache.maven.api.plugin.testing.InjectMojo;
+import org.apache.maven.api.plugin.testing.MojoParameter;
+import org.apache.maven.api.plugin.testing.MojoTest;
+import org.apache.maven.api.plugin.testing.stubs.ArtifactStub;
+import org.apache.maven.api.plugin.testing.stubs.ProjectStub;
+import org.apache.maven.api.services.ArtifactManager;
+import org.apache.maven.model.v4.MavenStaxReader;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+@MojoTest
+class EffectivePomMojoTest {
+
+ static final String CONFIG_XML = "classpath:/unit/evaluate/plugin-config.xml";
+
+ final ByteArrayOutputStream stdout = new ByteArrayOutputStream();
+
+ final Log log = mock(Log.class);
+
+ @BeforeEach
+ void setUp() {
+ System.setOut(new PrintStream(stdout));
+ }
+
+ @Test
+ @InjectMojo(goal = "effective-pom", pom = CONFIG_XML)
+ @MojoParameter(name = "verbose", value = "false")
+ @MojoParameter(name = "forceStdout", value = "true")
+ @Basedir
+ void testEffectivePomForceStdout(EffectivePomMojo mojo) {
+ when(log.isInfoEnabled()).thenReturn(false);
+ mojo.execute();
+
+ String output = stdout.toString();
+ }
+
+ // @Provides
+ // @Singleton
+ // Session createSession() {
+ // InternalSession session = SessionMock.getMockSession("target/local-repo");
+ //
+ // when(session.getSettings()).thenReturn(Settings.newInstance());
+ //
+ // MessageBuilderFactory mbf = new DefaultMessageBuilderFactory
+ // when(session.getService(MessageBuilderFactory.class)).thenReturn(mbf);
+ //
+ // return session;
+ // }
+
+ @Provides
+ @Singleton
+ Log createlog() {
+ return log;
+ }
+
+ @Provides
+ @Singleton
+ Project createProject(Session s) throws Exception {
+ Path path = Paths.get(getClass()
+ .getResource(CONFIG_XML.substring("classpath:".length()))
+ .getFile());
+ Model model;
+ try (InputStream is = Files.newInputStream(path)) {
+ InputSource source = new InputSource(null, path.toUri().toString());
+ model = new MavenStaxReader().read(is, true, source);
+ }
+
+ ProjectStub stub = new ProjectStub();
+ if (!"pom".equals(model.getPackaging())) {
+ ArtifactStub artifact = new ArtifactStub(
+ model.getGroupId(), model.getArtifactId(), "", model.getVersion(), model.getPackaging());
+ stub.setMainArtifact(artifact);
+ }
+ stub.setModel(model);
+ stub.setBasedir(path.getParent());
+ stub.setPomPath(path);
+ s.getService(ArtifactManager.class).setPath(stub.getPomArtifact(), path);
+ return stub;
+ }
+}
diff --git a/src/test/java/org/apache/maven/plugins/help/EvaluateMojoTest.java b/src/test/java/org/apache/maven/plugins/help/EvaluateMojoTest.java
index f65fee03..5b4a9c2a 100644
--- a/src/test/java/org/apache/maven/plugins/help/EvaluateMojoTest.java
+++ b/src/test/java/org/apache/maven/plugins/help/EvaluateMojoTest.java
@@ -19,94 +19,101 @@
package org.apache.maven.plugins.help;
import java.io.ByteArrayOutputStream;
-import java.io.File;
import java.io.PrintStream;
-import java.util.ArrayList;
import java.util.List;
-import org.apache.maven.monitor.logging.DefaultLog;
-import org.apache.maven.plugin.Mojo;
-import org.apache.maven.plugin.PluginParameterExpressionEvaluator;
-import org.apache.maven.plugin.testing.AbstractMojoTestCase;
-import org.apache.maven.plugin.testing.stubs.MavenProjectStub;
-import org.apache.maven.settings.Settings;
-import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator;
-import org.codehaus.plexus.components.interactivity.InputHandler;
-import org.codehaus.plexus.logging.Logger;
-import org.codehaus.plexus.logging.LoggerManager;
-
+import org.apache.maven.api.di.Provides;
+import org.apache.maven.api.di.Singleton;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.testing.Basedir;
+import org.apache.maven.api.plugin.testing.InjectMojo;
+import org.apache.maven.api.plugin.testing.MojoParameter;
+import org.apache.maven.api.plugin.testing.MojoTest;
+import org.apache.maven.api.plugin.testing.stubs.SessionMock;
+import org.apache.maven.api.services.Prompter;
+import org.apache.maven.api.settings.Server;
+import org.apache.maven.api.settings.Settings;
+import org.apache.maven.internal.impl.InternalSession;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
/**
* Test class for the evaluate mojo of the Help Plugin.
*/
-public class EvaluateMojoTest extends AbstractMojoTestCase {
+@MojoTest
+class EvaluateMojoTest {
+
+ static final String CONFIG_XML = "classpath:/unit/evaluate/plugin-config.xml";
+
+ final Prompter prompter = mock(Prompter.class);
+
+ final Log log = mock(Log.class);
- private InterceptingLog interceptingLogger;
+ final ByteArrayOutputStream stdout = new ByteArrayOutputStream();
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- interceptingLogger =
- new InterceptingLog(getContainer().lookup(LoggerManager.class).getLoggerForComponent(Mojo.ROLE));
+ @BeforeEach
+ void setUp() {
+ System.setOut(new PrintStream(stdout));
}
/**
* Tests evaluation of an expression in interactive mode with a mock input handler.
* @throws Exception in case of errors.
*/
- public void testEvaluateWithoutExpression() throws Exception {
- File testPom = new File(getBasedir(), "target/test-classes/unit/evaluate/plugin-config.xml");
-
- EvaluateMojo mojo = (EvaluateMojo) lookupMojo("evaluate", testPom);
-
- InputHandler inputHandler = mock(InputHandler.class);
- when(inputHandler.readLine()).thenReturn("${project.groupId}", "0");
-
- ExpressionEvaluator expressionEvaluator = mock(PluginParameterExpressionEvaluator.class);
- when(expressionEvaluator.evaluate(anyString())).thenReturn("My result");
-
- setUpMojo(mojo, inputHandler, expressionEvaluator);
+ @Test
+ @InjectMojo(goal = "evaluate", pom = CONFIG_XML)
+ @Basedir
+ public void testEvaluateWithoutExpression(EvaluateMojo mojo) throws Exception {
+ when(prompter.prompt(anyString())).thenReturn("${project.groupId}", "0");
+ when(log.isInfoEnabled()).thenReturn(true);
mojo.execute();
- String ls = System.getProperty("line.separator");
-
- assertTrue(interceptingLogger.infoLogs.contains(ls + "My result"));
- assertTrue(interceptingLogger.warnLogs.isEmpty());
- verify(expressionEvaluator).evaluate("${project.groupId}");
- verify(inputHandler, times(2)).readLine();
+ verify(log, atLeastOnce()).isInfoEnabled();
+ verify(log)
+ .info(
+ "No artifact parameter specified, using 'org.apache.maven.its.help:evaluate:jar:1.0-SNAPSHOT' as project.");
+ verify(log, times(2)).info("Enter the Maven expression i.e. ${project.groupId} or 0 to exit?:");
+ verify(log).info(System.lineSeparator() + "org.apache.maven.its.help");
+ verify(log, never()).warn(any(CharSequence.class));
+ verify(prompter, times(2)).prompt("Enter the Maven expression i.e. ${project.groupId} or 0 to exit?");
+ verifyNoMoreInteractions(log, prompter);
}
/**
* Tests evaluation of an expression in interactive mode with a mock input handler, when "output" is set.
* @throws Exception in case of errors.
*/
- public void testEvaluateWithoutExpressionWithOutput() throws Exception {
- File testPom = new File(getBasedir(), "target/test-classes/unit/evaluate/plugin-config-output.xml");
-
- EvaluateMojo mojo = (EvaluateMojo) lookupMojo("evaluate", testPom);
-
- InputHandler inputHandler = mock(InputHandler.class);
- when(inputHandler.readLine()).thenReturn("${project.artifactId}", "0");
-
- ExpressionEvaluator expressionEvaluator = mock(PluginParameterExpressionEvaluator.class);
- when(expressionEvaluator.evaluate(anyString())).thenReturn("My result");
-
- setUpMojo(mojo, inputHandler, expressionEvaluator);
+ @Test
+ @InjectMojo(goal = "evaluate", pom = CONFIG_XML)
+ @MojoParameter(name = "output", value = "result.txt")
+ @Basedir
+ public void testEvaluateWithoutExpressionWithOutput(EvaluateMojo mojo) throws Exception {
+ when(prompter.prompt(any())).thenReturn("${project.groupId}", "0");
+ when(log.isInfoEnabled()).thenReturn(true);
mojo.execute();
- String ls = System.getProperty("line.separator");
-
- assertTrue(interceptingLogger.infoLogs.contains(ls + "My result"));
- assertFalse(interceptingLogger.warnLogs.isEmpty());
- verify(expressionEvaluator).evaluate("${project.artifactId}");
- verify(inputHandler, times(2)).readLine();
+ verify(log, atLeastOnce()).isInfoEnabled();
+ verify(log)
+ .info(
+ "No artifact parameter specified, using 'org.apache.maven.its.help:evaluate:jar:1.0-SNAPSHOT' as project.");
+ verify(log).warn("When prompting for input, the result will be written to the console, ignoring 'output'.");
+ verify(log, times(2)).info("Enter the Maven expression i.e. ${project.groupId} or 0 to exit?:");
+ verify(log).info(System.lineSeparator() + "org.apache.maven.its.help");
+ verify(prompter, times(2)).prompt("Enter the Maven expression i.e. ${project.groupId} or 0 to exit?");
+ verifyNoMoreInteractions(log, prompter);
}
/**
@@ -116,76 +123,78 @@ public void testEvaluateWithoutExpressionWithOutput() throws Exception {
* @throws Exception in case of errors.
* @see MPH-144
*/
- public void testEvaluateQuiteModeWithOutputOnStdout() throws Exception {
- File testPom = new File(getBasedir(), "target/test-classes/unit/evaluate/plugin-config-quiet-stdout.xml");
+ @Test
+ @InjectMojo(goal = "evaluate", pom = CONFIG_XML)
+ @MojoParameter(name = "forceStdout", value = "true")
+ @MojoParameter(name = "expression", value = "project.groupId")
+ @Basedir
+ public void testEvaluateQuietModeWithOutputOnStdout(EvaluateMojo mojo) throws Exception {
+ // Quiet mode given on command line.(simulation)
+ when(log.isInfoEnabled()).thenReturn(false);
- EvaluateMojo mojo = (EvaluateMojo) lookupMojo("evaluate", testPom);
+ mojo.execute();
- ExpressionEvaluator expressionEvaluator = mock(PluginParameterExpressionEvaluator.class);
- when(expressionEvaluator.evaluate(anyString())).thenReturn("org.apache.maven.its.help");
+ verify(log, atLeastOnce()).isInfoEnabled();
+ verify(log)
+ .info(
+ "No artifact parameter specified, using 'org.apache.maven.its.help:evaluate:jar:1.0-SNAPSHOT' as project.");
+ assertEquals("org.apache.maven.its.help", stdout.toString());
+ verifyNoMoreInteractions(log, prompter);
+ }
+ /**
+ * This test will check that only the project.groupId
is printed to
+ * stdout nothing else.
+ *
+ * @throws Exception in case of errors.
+ * @see MPH-144
+ */
+ @Test
+ @InjectMojo(goal = "evaluate", pom = CONFIG_XML)
+ @MojoParameter(name = "forceStdout", value = "true")
+ @MojoParameter(name = "expression", value = "settings.servers[0]")
+ @Basedir
+ public void testEvaluateSettings(EvaluateMojo mojo) throws Exception {
// Quiet mode given on command line.(simulation)
- interceptingLogger.setInfoEnabled(false);
+ when(log.isInfoEnabled()).thenReturn(false);
- setUpMojo(mojo, null, expressionEvaluator);
-
- PrintStream saveOut = System.out;
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- System.setOut(new PrintStream(baos));
-
- try {
- mojo.execute();
- } finally {
- System.setOut(saveOut);
- baos.close();
- }
+ mojo.execute();
- String stdResult = baos.toString();
- assertEquals("org.apache.maven.its.help", stdResult);
- assertTrue(interceptingLogger.warnLogs.isEmpty());
+ verify(log, atLeastOnce()).isInfoEnabled();
+ verify(log)
+ .info(
+ "No artifact parameter specified, using 'org.apache.maven.its.help:evaluate:jar:1.0-SNAPSHOT' as project.");
+ assertEquals(
+ "\n" + " central\n" + " foo\n" + "",
+ stdout.toString());
+ verifyNoMoreInteractions(log, prompter);
}
- private void setUpMojo(EvaluateMojo mojo, InputHandler inputHandler, ExpressionEvaluator expressionEvaluator)
- throws IllegalAccessException {
- setVariableValueToObject(mojo, "inputHandler", inputHandler);
- setVariableValueToObject(mojo, "log", interceptingLogger);
- setVariableValueToObject(mojo, "settings", new Settings());
- setVariableValueToObject(mojo, "project", new MavenProjectStub());
- setVariableValueToObject(mojo, "evaluator", expressionEvaluator);
+ @Provides
+ @Singleton
+ Prompter prompter() {
+ return prompter;
}
- private static final class InterceptingLog extends DefaultLog {
- private boolean isInfoEnabled;
-
- final List infoLogs = new ArrayList<>();
-
- final List warnLogs = new ArrayList<>();
-
- public InterceptingLog(Logger logger) {
- super(logger);
- this.isInfoEnabled = true;
- }
-
- public void setInfoEnabled(boolean isInfoEnabled) {
- this.isInfoEnabled = isInfoEnabled;
- }
+ @Provides
+ @Singleton
+ Log createlog() {
+ return log;
+ }
- public boolean isInfoEnabled() {
- return isInfoEnabled;
- }
+ @Provides
+ InternalSession createSession(Prompter prompter) {
+ InternalSession session = SessionMock.getMockSession("target/local-repo");
- @Override
- public void info(CharSequence content) {
- if (this.isInfoEnabled) {
- super.info(content);
- infoLogs.add(content.toString());
- }
- }
+ when(session.getSettings())
+ .thenReturn(Settings.newBuilder()
+ .servers(List.of(Server.newBuilder()
+ .id("central")
+ .username("foo")
+ .build()))
+ .build());
+ when(session.getService(Prompter.class)).thenReturn(prompter);
- @Override
- public void warn(CharSequence content) {
- super.warn(content);
- warnLogs.add(content.toString());
- }
+ return session;
}
}
diff --git a/src/test/java/org/apache/maven/plugins/help/stubs/DefaultMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/help/stubs/DefaultMavenProjectStub.java
deleted file mode 100644
index fdcd0203..00000000
--- a/src/test/java/org/apache/maven/plugins/help/stubs/DefaultMavenProjectStub.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * 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.plugins.help.stubs;
-
-import java.io.FileReader;
-
-import org.apache.maven.model.Model;
-import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
-import org.apache.maven.plugin.testing.stubs.MavenProjectStub;
-
-/**
- * @author Vincent Siveton
- */
-public class DefaultMavenProjectStub extends MavenProjectStub {
- /**
- * Default constructor.
- */
- public DefaultMavenProjectStub() {
- MavenXpp3Reader pomReader = new MavenXpp3Reader();
- Model model;
-
- try {
- try (FileReader reader = new FileReader(getBasedir()
- + "/src/test/resources/unit/default-configuration/default-configuration-plugin-config.xml")) {
- model = pomReader.read(reader);
- }
- setModel(model);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
-
- setGroupId(model.getGroupId());
- setArtifactId(model.getArtifactId());
- setVersion(model.getVersion());
- setName(model.getName());
- setUrl(model.getUrl());
- setPackaging(model.getPackaging());
- }
-}
diff --git a/src/test/resources/unit/evaluate/plugin-config-output.xml b/src/test/resources/unit/effective-pom/plugin-config.xml
similarity index 94%
rename from src/test/resources/unit/evaluate/plugin-config-output.xml
rename to src/test/resources/unit/effective-pom/plugin-config.xml
index 1d28872c..6ce8f0d8 100644
--- a/src/test/resources/unit/evaluate/plugin-config-output.xml
+++ b/src/test/resources/unit/effective-pom/plugin-config.xml
@@ -20,7 +20,7 @@ under the License.
4.0.0
org.apache.maven.its.help
- evaluate
+ effective-pom
jar
1.0-SNAPSHOT
http://maven.apache.org
@@ -30,7 +30,6 @@ under the License.
org.apache.maven.plugins
maven-help-plugin
-